-
Notifications
You must be signed in to change notification settings - Fork 62
/
Copy pathpnl.go
224 lines (186 loc) · 6.03 KB
/
pnl.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
package relayer
import (
"context"
"math/big"
"time"
"github.com/omni-network/omni/lib/errors"
"github.com/omni-network/omni/lib/ethclient"
"github.com/omni-network/omni/lib/evmchain"
"github.com/omni-network/omni/lib/log"
"github.com/omni-network/omni/lib/netconf"
"github.com/omni-network/omni/lib/pnl"
"github.com/omni-network/omni/lib/tokens"
"github.com/omni-network/omni/lib/tokens/coingecko"
"github.com/omni-network/omni/lib/umath"
"github.com/omni-network/omni/lib/xchain"
ethtypes "github.com/ethereum/go-ethereum/core/types"
"github.com/ethereum/go-ethereum/params"
)
const (
priceCacheEvictInterval = time.Minute
)
// newTokenPricer creates a new cached pricer with priceCacheEvictInterval.
func newTokenPricer(ctx context.Context) *tokens.CachedPricer {
pricer := tokens.NewCachedPricer(coingecko.New())
// use cached pricer avoid spamming coingecko public api
// TODO: use api key
go pricer.ClearCacheForever(ctx, priceCacheEvictInterval)
return pricer
}
type pnlLogger struct {
network netconf.ID
pricer tokens.Pricer
}
// newPnlLogger creates a new pnl logger.
func newPnlLogger(network netconf.ID, pricer tokens.Pricer) pnlLogger {
return pnlLogger{network: network, pricer: pricer}
}
// log logs the pnl for an xsubmit transaction, warning on error.
func (l pnlLogger) log(ctx context.Context, tx *ethtypes.Transaction, receipt *ethclient.Receipt, sub xchain.Submission) {
if err := l.logE(ctx, tx, receipt, sub); err != nil {
log.Warn(ctx, "Failed to log pnl", err)
}
}
// logE logs the pnl for an xsubmit transaction, returning any errors.
func (l pnlLogger) logE(ctx context.Context, tx *ethtypes.Transaction, receipt *ethclient.Receipt, sub xchain.Submission) error {
srcChainID := sub.BlockHeader.ChainID
dstChainID := sub.DestChainID
dest, ok := evmchain.MetadataByID(dstChainID)
if !ok {
return errors.New("unknown chain ID")
}
spendGwei := totalSpendGwei(tx, receipt)
spendTotal.WithLabelValues(dest.Name, dest.NativeToken.Symbol).Add(spendGwei)
prices, err := l.pricer.Price(ctx, tokens.OMNI, tokens.ETH)
if err != nil {
return errors.Wrap(err, "get prices")
}
log.Debug(ctx, "Using token prices", "omni", prices[tokens.OMNI], "eth", prices[tokens.ETH])
spend, err := spendByDenom(dest, spendGwei, prices)
if err != nil {
return errors.Wrap(err, "get spend")
}
md := map[string]any{
"tx": tx.Hash().Hex(),
"gas_used": receipt.GasUsed,
"status": receipt.Status,
"num_msgs": len(sub.Msgs),
}
id := tx.Hash().Hex()
// log expenses
pnl.Log(ctx,
pnl.LogP{
Type: pnl.Expense, AmountGwei: spend.nUSD, Currency: pnl.USD,
Category: "gas", Subcategory: "xsubmit",
Chain: dest.Name, ID: id, Metadata: md,
},
pnl.LogP{
Type: pnl.Expense, AmountGwei: spend.nETH, Currency: pnl.ETH,
Category: "gas", Subcategory: "xsubmit",
Chain: dest.Name, ID: id, Metadata: md,
},
pnl.LogP{
Type: pnl.Expense, AmountGwei: spend.nOMNI, Currency: pnl.OMNI,
Category: "gas", Subcategory: "xsubmit",
Chain: dest.Name, ID: id, Metadata: md,
},
)
// do not log income if:
// - the submission failed (avoid double counting)
// - source chain is omni consensus chain (no fees collected)
if netconf.IsOmniConsensus(l.network, srcChainID) || receipt.Status != ethtypes.ReceiptStatusSuccessful {
return nil
}
src, ok := evmchain.MetadataByID(srcChainID)
if !ok {
return errors.New("unknown source chain ID")
}
fees, err := feeByDenom(src, sub, prices)
if err != nil {
return errors.Wrap(err, "get fees")
}
// log income
pnl.Log(ctx,
pnl.LogP{
Type: pnl.Income, AmountGwei: fees.nUSD, Currency: pnl.USD,
Category: "fees", Subcategory: "xcall",
Chain: src.Name, ID: id, Metadata: md,
},
pnl.LogP{
Type: pnl.Income, AmountGwei: fees.nETH, Currency: pnl.ETH,
Category: "fees", Subcategory: "xcall",
Chain: src.Name, ID: id, Metadata: md,
},
pnl.LogP{
Type: pnl.Income, AmountGwei: fees.nOMNI, Currency: pnl.OMNI,
Category: "fees", Subcategory: "xcall",
Chain: src.Name, ID: id, Metadata: md,
},
)
return nil
}
type amtByDenom struct {
nUSD float64 // "nano" USD (gwei)
nOMNI float64 // "nano" OMNI (gwei)
nETH float64 // "nano" ETH (gwei)
}
// feeByDenom returns the amount fees collected from a receipt in omni, eth, and usd.
func feeByDenom(
src evmchain.Metadata,
sub xchain.Submission,
prices map[tokens.Token]float64,
) (amtByDenom, error) {
var fees amtByDenom
for _, msg := range sub.Msgs {
if msg.SourceChainID != src.ChainID {
return amtByDenom{}, errors.New("source chain ID mismatch [BUG]", "expected", src.ChainID, "got", msg.SourceChainID)
}
feesGwei := toGwei(msg.Fees)
switch src.NativeToken {
case tokens.OMNI:
fees.nOMNI += feesGwei
fees.nUSD += feesGwei * prices[tokens.OMNI]
case tokens.ETH:
fees.nETH += feesGwei
fees.nUSD += feesGwei * prices[tokens.ETH]
default:
return amtByDenom{}, errors.New("unknown native token", "token", src.NativeToken)
}
}
return fees, nil
}
// spendByDenom returns the amount spent on a transaction in omni, eth, and usd.
func spendByDenom(
dest evmchain.Metadata,
spendGwei float64,
prices map[tokens.Token]float64,
) (amtByDenom, error) {
var spend amtByDenom
switch dest.NativeToken {
case tokens.OMNI:
spend.nOMNI = spendGwei
spend.nUSD = spendGwei * prices[tokens.OMNI]
case tokens.ETH:
spend.nETH = spendGwei
spend.nUSD = spendGwei * prices[tokens.ETH]
default:
return amtByDenom{}, errors.New("unknown native token", "token", dest.NativeToken)
}
return spend, nil
}
// totalSpendGwei returns the total amount spent on a transaction in gwei.
func totalSpendGwei(tx *ethtypes.Transaction, rec *ethclient.Receipt) float64 {
spend := new(big.Int).Mul(rec.EffectiveGasPrice, umath.NewBigInt(rec.GasUsed))
// add op l1 fee, if any
if rec.OPL1Fee != nil {
spend = new(big.Int).Add(spend, rec.OPL1Fee)
}
// add tx value
spend = new(big.Int).Add(spend, tx.Value())
return toGwei(spend)
}
// toGwei converts a big.Int to gwei float64.
func toGwei(b *big.Int) float64 {
gwei, _ := new(big.Int).Div(b, umath.NewBigInt(params.GWei)).Float64()
return gwei
}