Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

chore(solver/app): add usd pnl #3281

Merged
merged 1 commit into from
Mar 5, 2025
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 lib/contracts/feeoraclev1/feeparams.go
Original file line number Diff line number Diff line change
Expand Up @@ -104,7 +104,7 @@ func conversionRate(ctx context.Context, pricer tokens.Pricer, from, to tokens.T
return 1, nil
}

prices, err := pricer.Price(ctx, from, to)
prices, err := pricer.Prices(ctx, from, to)
if err != nil {
return 0, errors.Wrap(err, "get price", "from", from, "to", to)
}
Expand Down
2 changes: 1 addition & 1 deletion lib/contracts/feeoraclev2/feeparams.go
Original file line number Diff line number Diff line change
Expand Up @@ -204,7 +204,7 @@ func conversionRate(ctx context.Context, pricer tokens.Pricer, from, to tokens.T
return 1, nil
}

prices, err := pricer.Price(ctx, from, to)
prices, err := pricer.Prices(ctx, from, to)
if err != nil {
return 0, errors.Wrap(err, "get price", "from", from, "to", to)
}
Expand Down
19 changes: 17 additions & 2 deletions lib/tokens/coingecko/coingecko.go
Original file line number Diff line number Diff line change
Expand Up @@ -38,8 +38,23 @@ func New(opts ...func(*options)) Client {
}
}

// Price returns the price of each coin in USD.
func (c Client) Price(ctx context.Context, tkns ...tokens.Token) (map[tokens.Token]float64, error) {
// Price returns the price of the token in USD.
func (c Client) Price(ctx context.Context, tkn tokens.Token) (float64, error) {
prices, err := c.Prices(ctx, tkn)
if err != nil {
return 0, err
}

price, ok := prices[tkn]
if !ok {
return 0, errors.New("missing token [BUG]", "token", tkn)
}

return price, nil
}

// Prices returns the price of each coin in USD.
func (c Client) Prices(ctx context.Context, tkns ...tokens.Token) (map[tokens.Token]float64, error) {
return c.getPrice(ctx, "usd", tkns...)
}

Expand Down
4 changes: 2 additions & 2 deletions lib/tokens/coingecko/coingecko_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ func TestIntegration(t *testing.T) {
require.True(t, ok)

c := coingecko.New(coingecko.WithAPIKey(apikey))
prices, err := c.Price(context.Background(), tokens.OMNI, tokens.ETH)
prices, err := c.Prices(context.Background(), tokens.OMNI, tokens.ETH)
tutil.RequireNoError(t, err)
require.NotEmpty(t, prices)
}
Expand Down Expand Up @@ -80,7 +80,7 @@ func TestGetPrice(t *testing.T) {
defer server.Close()

c := coingecko.New(coingecko.WithHost(server.URL), coingecko.WithAPIKey(token))
prices, err := c.Price(context.Background(), tokens.OMNI, tokens.ETH)
prices, err := c.Prices(context.Background(), tokens.OMNI, tokens.ETH)

if shouldErr(t, test) {
require.Error(t, err)
Expand Down
9 changes: 8 additions & 1 deletion lib/tokens/mock.go
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,14 @@ func NewMockPricer(prices map[Token]float64) *MockPricer {
return &MockPricer{prices: cloned}
}

func (m *MockPricer) Price(_ context.Context, tkns ...Token) (map[Token]float64, error) {
func (m *MockPricer) Price(_ context.Context, tk Token) (float64, error) {
m.mu.RLock()
defer m.mu.RUnlock()

return m.prices[tk], nil
}

func (m *MockPricer) Prices(_ context.Context, tkns ...Token) (map[Token]float64, error) {
m.mu.RLock()
defer m.mu.RUnlock()

Expand Down
26 changes: 22 additions & 4 deletions lib/tokens/pricer.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,12 +4,16 @@ import (
"context"
"sync"
"time"

"github.com/omni-network/omni/lib/errors"
)

// Pricer is the token price provider interface.
type Pricer interface {
// Price returns the price of each provided token in USD.
Price(ctx context.Context, tokens ...Token) (map[Token]float64, error)
// Price returns the price of the token in USD.
Price(ctx context.Context, tokens Token) (float64, error)
// Prices returns the price of each provided token in USD.
Prices(ctx context.Context, tokens ...Token) (map[Token]float64, error)
Comment on lines +13 to +16
Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

slight change to pricer interface

}

type CachedPricer struct {
Expand All @@ -25,7 +29,21 @@ func NewCachedPricer(p Pricer) *CachedPricer {
}
}

func (c *CachedPricer) Price(ctx context.Context, tokens ...Token) (map[Token]float64, error) {
func (c *CachedPricer) Price(ctx context.Context, token Token) (float64, error) {
prices, err := c.Prices(ctx, token)
if err != nil {
return 0, err
}

price, ok := prices[token]
if !ok {
return 0, errors.New("missing token price [BUG]")
}

return price, nil
}

func (c *CachedPricer) Prices(ctx context.Context, tokens ...Token) (map[Token]float64, error) {
c.mu.Lock()
defer c.mu.Unlock()

Expand All @@ -45,7 +63,7 @@ func (c *CachedPricer) Price(ctx context.Context, tokens ...Token) (map[Token]fl
return prices, nil
}

newPrices, err := c.p.Price(ctx, uncached...)
newPrices, err := c.p.Prices(ctx, uncached...)
if err != nil {
return nil, err
}
Expand Down
6 changes: 3 additions & 3 deletions lib/tokens/pricer_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ func TestCachedPricer(t *testing.T) {

cached := tokens.NewCachedPricer(pricer)

prices, err := cached.Price(context.Background(), tokens.ETH, tokens.OMNI)
prices, err := cached.Prices(context.Background(), tokens.ETH, tokens.OMNI)
require.NoError(t, err)
require.InEpsilon(t, 100.0, prices[tokens.ETH], epsilon)
require.InEpsilon(t, 200.0, prices[tokens.OMNI], epsilon)
Expand All @@ -30,7 +30,7 @@ func TestCachedPricer(t *testing.T) {
pricer.SetPrice(tokens.OMNI, 250)

// prices should still be cached
prices, err = cached.Price(context.Background(), tokens.ETH, tokens.OMNI)
prices, err = cached.Prices(context.Background(), tokens.ETH, tokens.OMNI)
require.NoError(t, err)
require.InEpsilon(t, 100.0, prices[tokens.ETH], epsilon)
require.InEpsilon(t, 200.0, prices[tokens.OMNI], epsilon)
Expand All @@ -39,7 +39,7 @@ func TestCachedPricer(t *testing.T) {
cached.ClearCache()

// prices should be updated
prices, err = cached.Price(context.Background(), tokens.ETH, tokens.OMNI)
prices, err = cached.Prices(context.Background(), tokens.ETH, tokens.OMNI)
require.NoError(t, err)
require.InEpsilon(t, 150.0, prices[tokens.ETH], epsilon)
require.InEpsilon(t, 250.0, prices[tokens.OMNI], epsilon)
Expand Down
2 changes: 1 addition & 1 deletion monitor/xfeemngr/tokenprice/buffer.go
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,7 @@ func (b *buffer) Stream(ctx context.Context) {
// stream starts streaming prices for all tokens into the buffer.
func (b *buffer) stream(ctx context.Context) {
callback := func(ctx context.Context) {
prices, err := b.pricer.Price(ctx, b.tokens...)
prices, err := b.pricer.Prices(ctx, b.tokens...)
if err != nil {
log.Warn(ctx, "Failed to get prices (will retry)", err)
return
Expand Down
2 changes: 1 addition & 1 deletion monitor/xfeemngr/tokenprice/buffer_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,7 @@ func TestBufferStream(t *testing.T) {

tick.Tick()

live, err := pricer.Price(ctx, tokens.OMNI, tokens.ETH)
live, err := pricer.Prices(ctx, tokens.OMNI, tokens.ETH)
require.NoError(t, err)

// check if any live price is outside threshold
Expand Down
2 changes: 1 addition & 1 deletion relayer/app/pnl.go
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,7 @@ func (l pnlLogger) logE(ctx context.Context, tx *ethtypes.Transaction, receipt *
spendGwei := totalSpendGwei(tx, receipt)
spendTotal.WithLabelValues(dest.Name, dest.NativeToken.Symbol).Add(spendGwei)

prices, err := l.pricer.Price(ctx, tokens.OMNI, tokens.ETH)
prices, err := l.pricer.Prices(ctx, tokens.OMNI, tokens.ETH)
if err != nil {
return errors.Wrap(err, "get prices")
}
Expand Down
21 changes: 18 additions & 3 deletions solver/app/app.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,8 @@ import (
"github.com/omni-network/omni/lib/expbackoff"
"github.com/omni-network/omni/lib/log"
"github.com/omni-network/omni/lib/netconf"
tokenslib "github.com/omni-network/omni/lib/tokens"
"github.com/omni-network/omni/lib/tokens/coingecko"
"github.com/omni-network/omni/lib/tracer"
"github.com/omni-network/omni/lib/umath"
"github.com/omni-network/omni/lib/xchain"
Expand Down Expand Up @@ -120,7 +122,9 @@ func Run(ctx context.Context, cfg Config) error {
return errors.Wrap(err, "get contract addresses")
}

err = startEventStreams(ctx, network, xprov, backends, solverAddr, addrs, cursors)
pricer := newPricer(ctx, cfg.CoinGeckoAPIKey)

err = startEventStreams(ctx, network, xprov, backends, solverAddr, addrs, cursors, pricer)
if err != nil {
return errors.Wrap(err, "start event streams")
}
Expand All @@ -147,6 +151,16 @@ func Run(ctx context.Context, cfg Config) error {
}
}

func newPricer(ctx context.Context, apiKey string) tokenslib.Pricer {
pricer := tokenslib.NewCachedPricer(coingecko.New(coingecko.WithAPIKey(apiKey)))

// use cached pricer avoid spamming coingecko public api
const priceCacheEvictInterval = time.Minute * 10
go pricer.ClearCacheForever(ctx, priceCacheEvictInterval)

return pricer
}

// serveMonitoring starts a goroutine that serves the monitoring API. It
// returns a channel that will receive an error if the server fails to start.
func serveMonitoring(address string) <-chan error {
Expand Down Expand Up @@ -205,6 +219,7 @@ func startEventStreams(
solverAddr common.Address,
addrs contracts.Addresses,
cursors *cursors,
pricer tokenslib.Pricer,
) error {
inboxChains, err := detectContractChains(ctx, network, backends, addrs.SolverNetInbox)
if err != nil {
Expand Down Expand Up @@ -324,8 +339,8 @@ func startEventStreams(
ShouldReject: newShouldRejector(backends, solverAddr, addrs.SolverNetOutbox),
DidFill: newDidFiller(outboxContracts),
Reject: newRejector(inboxContracts, backends, solverAddr),
Fill: newFiller(outboxContracts, backends, solverAddr, addrs.SolverNetOutbox),
Claim: newClaimer(inboxContracts, backends, solverAddr),
Fill: newFiller(outboxContracts, backends, solverAddr, addrs.SolverNetOutbox, pricer),
Claim: newClaimer(inboxContracts, backends, solverAddr, pricer),
SetCursor: cursorSetter,
ChainName: network.ChainName,
TargetName: targetName,
Expand Down
33 changes: 27 additions & 6 deletions solver/app/pnl.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,51 +4,72 @@ import (
"context"

"github.com/omni-network/omni/lib/errors"
"github.com/omni-network/omni/lib/log"
"github.com/omni-network/omni/lib/pnl"
tokenslib "github.com/omni-network/omni/lib/tokens"

"github.com/ethereum/go-ethereum/common"
)

// pnlExpenses logs the solver expense PnL for the order.
func pnlExpenses(ctx context.Context, order Order, outboxAddr common.Address, dstChainName string) error {
func pnlExpenses(ctx context.Context, pricer tokenslib.Pricer, order Order, outboxAddr common.Address, dstChainName string) error {
maxSpent, err := parseMaxSpent(order, outboxAddr)
if err != nil {
return errors.Wrap(err, "parse max spent [BUG]") // This should never fail here.
}

for _, tknAmt := range maxSpent {
pnl.Log(ctx, pnl.LogP{
p := pnl.LogP{
Type: pnl.Expense,
AmountGwei: toGweiF64(tknAmt.Amount),
Currency: pnl.Currency(tknAmt.Token.Symbol),
Category: "solver",
Subcategory: "spend",
Chain: dstChainName,
ID: order.ID.String(),
})
}
pnl.Log(ctx, p)
usdPnL(ctx, pricer, tknAmt.Token.Token, p)
}

return nil
}

// pnlIncome logs the solver income PnL for the order.
func pnlIncome(ctx context.Context, order Order, srcChainName string) error {
func pnlIncome(ctx context.Context, pricer tokenslib.Pricer, order Order, srcChainName string) error {
minReceived, err := parseMinReceived(order)
if err != nil {
return errors.Wrap(err, "parse min received [BUG]") // This should never fail here.
}

for _, tknAmt := range minReceived {
pnl.Log(ctx, pnl.LogP{
p := pnl.LogP{
Type: pnl.Income,
AmountGwei: toGweiF64(tknAmt.Amount),
Currency: pnl.Currency(tknAmt.Token.Symbol),
Category: "solver",
Subcategory: "receive",
Chain: srcChainName,
ID: order.ID.String(),
})
}

pnl.Log(ctx, p)
usdPnL(ctx, pricer, tknAmt.Token.Token, p)
}

return nil
}

// usdPnL logs the USD equivalent PnL.
// This is best effort.
func usdPnL(ctx context.Context, pricer tokenslib.Pricer, token tokenslib.Token, p pnl.LogP) {
usdPrice, err := pricer.Price(ctx, token)
if err != nil {
log.Warn(ctx, "Failed to get token USD price (will retry)", err, "token", token.Name)
return
}

p.Currency = pnl.USD
p.AmountGwei *= usdPrice // USDAmount = TokenAmount * USDPricePerToken
pnl.Log(ctx, p)
}
7 changes: 5 additions & 2 deletions solver/app/procdeps.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import (
"github.com/omni-network/omni/lib/errors"
"github.com/omni-network/omni/lib/ethclient/ethbackend"
"github.com/omni-network/omni/lib/log"
libtokens "github.com/omni-network/omni/lib/tokens"

"github.com/ethereum/go-ethereum/accounts/abi/bind"
"github.com/ethereum/go-ethereum/common"
Expand Down Expand Up @@ -39,6 +40,7 @@ func newClaimer(
inboxContracts map[uint64]*bindings.SolverNetInbox,
backends ethbackend.Backends,
solverAddr common.Address,
pricer libtokens.Pricer,
) func(ctx context.Context, order Order) error {
return func(ctx context.Context, order Order) error {
inbox, ok := inboxContracts[order.SourceChainID]
Expand Down Expand Up @@ -67,14 +69,15 @@ func newClaimer(

srcChainName, _ := backend.Chain()

return pnlIncome(ctx, order, srcChainName)
return pnlIncome(ctx, pricer, order, srcChainName)
}
}

func newFiller(
outboxContracts map[uint64]*bindings.SolverNetOutbox,
backends ethbackend.Backends,
solverAddr, outboxAddr common.Address,
pricer libtokens.Pricer,
) func(ctx context.Context, order Order) error {
return func(ctx context.Context, order Order) error {
if order.DestinationSettler != outboxAddr {
Expand Down Expand Up @@ -164,7 +167,7 @@ func newFiller(

dstChainName, _ := backend.Chain()

return pnlExpenses(ctx, order, outboxAddr, dstChainName)
return pnlExpenses(ctx, pricer, order, outboxAddr, dstChainName)
}
}

Expand Down
Loading