Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ require (
github.com/aws/aws-sdk-go-v2/service/dynamodb v1.59.0
github.com/aws/aws-sdk-go-v2/service/s3 v1.102.2
github.com/code-payments/code-vm-indexer v1.2.0
github.com/code-payments/ocp-protobuf-api v1.16.1-0.20260914145736-82202912574e
github.com/code-payments/ocp-protobuf-api v1.16.1-0.20260918154336-e3d25a85b1e1
github.com/emirpasic/gods v1.12.0
github.com/envoyproxy/protoc-gen-validate v1.3.3
github.com/golang/protobuf v1.5.4
Expand Down
4 changes: 2 additions & 2 deletions go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -80,8 +80,8 @@ github.com/cockroachdb/apd v1.1.0 h1:3LFP3629v+1aKXU5Q37mxmRxX/pIu1nijXydLShEq5I
github.com/cockroachdb/apd v1.1.0/go.mod h1:8Sl8LxpKi29FqWXR16WEFZRNSz3SoPzUzeMeY4+DwBQ=
github.com/code-payments/code-vm-indexer v1.2.0 h1:rSHpBMiT9BKgmKcXg/VIoi/h0t7jNxGx07Qz59m+6Q0=
github.com/code-payments/code-vm-indexer v1.2.0/go.mod h1:vn91YN2qNqb+gGJeZe2+l+TNxVmEEiRHXXnIn2Y40h8=
github.com/code-payments/ocp-protobuf-api v1.16.1-0.20260914145736-82202912574e h1:gxClbVslDPKJvwgZbY6RMuUIZi3DfR18O07SoCU5W3w=
github.com/code-payments/ocp-protobuf-api v1.16.1-0.20260914145736-82202912574e/go.mod h1:tw6BooY5a8l6CtSZnKOruyKII0W04n89pcM4BizrgG8=
github.com/code-payments/ocp-protobuf-api v1.16.1-0.20260918154336-e3d25a85b1e1 h1:/cE319d70UiXoor2x9b2faiFTUFlzdgs10D4Fvq7dN4=
github.com/code-payments/ocp-protobuf-api v1.16.1-0.20260918154336-e3d25a85b1e1/go.mod h1:tw6BooY5a8l6CtSZnKOruyKII0W04n89pcM4BizrgG8=
github.com/containerd/continuity v0.0.0-20190827140505-75bee3e2ccb6 h1:NmTXa/uVnDyp0TY5MKi197+3HWcnYWfnHGyaFthlnGw=
github.com/containerd/continuity v0.0.0-20190827140505-75bee3e2ccb6/go.mod h1:GL3xCUCBDV3CZiTSEKksMWbLE66hEyuu9qyDOOqM47Y=
github.com/coreos/bbolt v1.3.2/go.mod h1:iRUV2dpdMOn7Bo10OQBFzIJO9kkE559Wcmn+qkEiiKk=
Expand Down
7 changes: 7 additions & 0 deletions ocp/currency/exchange_rate.go
Original file line number Diff line number Diff line change
Expand Up @@ -20,3 +20,10 @@ func CalculateExchangeRate(mintAccount *common.Account, quarks uint64, nativeAmo
exchangeRate, _ := exchangeRateBig.Float64()
return exchangeRate
}

// CalculateFiatValueFromCoreMintQuarks calculates the fiat value of a core mint
// amount in quarks given an exchange rate denominated in fiat per core mint unit.
func CalculateFiatValueFromCoreMintQuarks(quarks uint64, exchangeRate float64) float64 {
coreMintUnits := float64(quarks) / float64(common.CoreMintQuarksPerUnit)
return coreMintUnits * exchangeRate
}
67 changes: 62 additions & 5 deletions ocp/rpc/balance/server.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package balance

import (
"context"
"strings"

"github.com/pkg/errors"
"go.uber.org/zap"
Expand Down Expand Up @@ -79,9 +80,17 @@ func (s *server) GetBalances(ctx context.Context, req *balancepb.GetBalancesRequ
// mid-request.
reserveStateCache := newReserveStateCache()

// Exchange rates are pinned once per request so every balance denominated
// in a currency uses the same rate. Currencies without a rate are dropped.
exchangeRates, err := s.getExchangeRates(ctx, req.CurrencyCodes)
if err != nil {
log.With(zap.Error(err)).Warn("failure getting live exchange rates")
return nil, status.Error(codes.Internal, "")
}

balancesByOwner := make(map[string]*balancepb.OwnerBalance, len(owners))
for _, owner := range owners {
ownerBalance, err := s.valueOwnerBalance(ctx, owner, balanceByOwnerAndTokenAccount[owner.PublicKey().ToBase58()], reserveStateCache)
ownerBalance, err := s.valueOwnerBalance(ctx, owner, balanceByOwnerAndTokenAccount[owner.PublicKey().ToBase58()], reserveStateCache, exchangeRates)
if err != nil {
log.With(zap.Error(err), zap.String("owner_account", owner.PublicKey().ToBase58())).Warn("failure valuing owner balance")
return nil, status.Error(codes.Internal, "")
Expand All @@ -99,7 +108,7 @@ func (s *server) GetBalances(ctx context.Context, req *balancepb.GetBalancesRequ
// valueOwnerBalance values an owner's cached holdings. Owner metadata checks
// are intentionally skipped as an optimization, so an owner with no ledger
// records has an empty balance.
func (s *server) valueOwnerBalance(ctx context.Context, owner *common.Account, balanceByTokenAccount map[string]*balance.Balance, reserveStateCache reserveStateCache) (*balancepb.OwnerBalance, error) {
func (s *server) valueOwnerBalance(ctx context.Context, owner *common.Account, balanceByTokenAccount map[string]*balance.Balance, reserveStateCache reserveStateCache, exchangeRates exchangeRates) (*balancepb.OwnerBalance, error) {
balancesByMint, err := s.calculateCoreMintValueByMint(ctx, balanceByTokenAccount, reserveStateCache)
if err != nil {
return nil, err
Expand All @@ -108,12 +117,14 @@ func (s *server) valueOwnerBalance(ctx context.Context, owner *common.Account, b
var totalCoreMintValue uint64
for _, mintBalance := range balancesByMint {
totalCoreMintValue += mintBalance.CoreMintValue
mintBalance.FiatValuesByCurrency = exchangeRates.toFiatValues(mintBalance.CoreMintValue)
}

return &balancepb.OwnerBalance{
Owner: owner.ToProto(),
CoreMintValue: totalCoreMintValue,
BalancesByMint: balancesByMint,
Owner: owner.ToProto(),
CoreMintValue: totalCoreMintValue,
BalancesByMint: balancesByMint,
FiatValuesByCurrency: exchangeRates.toFiatValues(totalCoreMintValue),
}, nil
}

Expand Down Expand Up @@ -142,6 +153,52 @@ func newMintFilter(protoMints []*commonpb.SolanaAccountId) ([]*common.Account, e
return mints, nil
}

// exchangeRates pins the live exchange rate observed for each requested
// currency code so every valuation within a single RPC uses the same rate.
type exchangeRates map[string]float64

// getExchangeRates resolves the requested currency codes against the live
// exchange rates. Codes without a live rate are omitted, so the result only
// holds currencies that can be valued. Nothing is fetched when no codes are
// requested.
func (s *server) getExchangeRates(ctx context.Context, currencyCodes []string) (exchangeRates, error) {
if len(currencyCodes) == 0 {
return nil, nil
}

liveExchangeRates, err := s.mintDataProvider.GetLiveExchangeRates(ctx)
if err != nil {
return nil, err
}

rates := make(exchangeRates, len(currencyCodes))
for _, currencyCode := range currencyCodes {
currencyCode = strings.ToLower(currencyCode)

rate, ok := liveExchangeRates.Rates[currencyCode]
if !ok {
continue
}
rates[currencyCode] = rate
}
return rates, nil
}

// toFiatValues denominates a core mint value in every pinned currency. A nil
// map is returned when there are no pinned currencies, which leaves the proto
// field unset.
func (r exchangeRates) toFiatValues(coreMintValue uint64) map[string]float64 {
if len(r) == 0 {
return nil
}

fiatValues := make(map[string]float64, len(r))
for currencyCode, rate := range r {
fiatValues[currencyCode] = currency_util.CalculateFiatValueFromCoreMintQuarks(coreMintValue, rate)
}
return fiatValues
}

// reserveStateCache pins the live reserve state observed for each launchpad
// mint so every valuation within a single RPC uses the same supply.
type reserveStateCache map[string]*currency_util.LiveReserveStateData
Expand Down
Loading
Loading