forked from omni-network/omni
-
Notifications
You must be signed in to change notification settings - Fork 1
/
sender.go
247 lines (208 loc) · 6.79 KB
/
sender.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
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
package relayer
import (
"context"
"crypto/ecdsa"
"math/big"
"slices"
"strings"
"github.com/omni-network/omni/contracts/bindings"
"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/tokens"
"github.com/omni-network/omni/lib/txmgr"
"github.com/omni-network/omni/lib/umath"
"github.com/omni-network/omni/lib/xchain"
"github.com/ethereum/go-ethereum"
"github.com/ethereum/go-ethereum/accounts/abi"
"github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/common/hexutil"
ethtypes "github.com/ethereum/go-ethereum/core/types"
"github.com/ethereum/go-ethereum/params"
)
// Sender uses txmgr to send transactions a specific destination chain.
type onSubmitFunc func(context.Context, *ethtypes.Transaction, *ethtypes.Receipt, xchain.Submission)
// Sender uses txmgr to send transactions to a specific destination chain.
type Sender struct {
network netconf.ID
txMgr txmgr.TxManager
gasEstimator gasEstimator
abi *abi.ABI
chain netconf.Chain
gasToken tokens.Token
chainNames map[xchain.ChainVersion]string
ethCl ethclient.Client
onSubmit onSubmitFunc
}
// NewSender returns a new sender.
func NewSender(
network netconf.ID,
chain netconf.Chain,
rpcClient ethclient.Client,
privateKey ecdsa.PrivateKey,
chainNames map[xchain.ChainVersion]string,
onSubmit onSubmitFunc,
) (Sender, error) {
const receiptPollFreq = 3 // Query receipts every 1/3 of the block time
cfg, err := txmgr.NewConfig(
txmgr.NewCLIConfig(
chain.ID,
chain.BlockPeriod/receiptPollFreq,
txmgr.DefaultSenderFlagValues,
),
&privateKey,
rpcClient,
)
if err != nil {
return Sender{}, err
}
txMgr, err := txmgr.NewSimple(chain.Name, cfg)
if err != nil {
return Sender{}, errors.Wrap(err, "create tx mgr")
}
// Create ABI
parsedAbi, err := abi.JSON(strings.NewReader(bindings.OmniPortalMetaData.ABI))
if err != nil {
return Sender{}, errors.Wrap(err, "parse abi error")
}
meta, ok := evmchain.MetadataByID(chain.ID)
if !ok {
return Sender{}, errors.New("chain metadata not found", "chain_id", chain.ID)
}
return Sender{
network: network,
txMgr: txMgr,
gasEstimator: newGasEstimator(network),
abi: &parsedAbi,
chain: chain,
gasToken: meta.NativeToken,
chainNames: chainNames,
ethCl: rpcClient,
onSubmit: onSubmit,
}, nil
}
// SendAsync sends the submission to the destination chain asynchronously.
// It returns a channel that will receive an error if the submission fails or nil when it succeeds.
// Nonces are however reserved synchronously, so ordering of submissions
// is preserved.
func (s Sender) SendAsync(ctx context.Context, sub xchain.Submission) <-chan error {
// Helper function to return error "synchronously".
returnErr := func(err error) chan error {
resp := make(chan error, 1)
resp <- err
return resp
}
if s.txMgr == nil {
return returnErr(errors.New("tx mgr not found [BUG]", "dest_chain_id", sub.DestChainID))
} else if sub.DestChainID != s.chain.ID {
return returnErr(errors.New("unexpected destination chain [BUG]",
"got", sub.DestChainID, "expect", s.chain.ID))
}
// Get some info for logging
var startOffset uint64
if len(sub.Msgs) > 0 {
startOffset = sub.Msgs[0].StreamOffset
}
dstChain := s.chain.Name
srcChain := s.chainNames[sub.AttHeader.ChainVersion]
// Request attributes added to context (for downstream logging) and manually added to errors (for upstream logging).
reqAttrs := []any{
"req_id", randomHex7(),
"src_chain", srcChain,
}
ctx = log.WithCtx(ctx, reqAttrs...)
log.Debug(ctx, "Received submission",
"attest_offset", sub.AttHeader.AttestOffset,
"start_msg_offset", startOffset,
"msgs", len(sub.Msgs),
)
txData, err := xchain.EncodeXSubmit(xchain.SubmissionToBinding(sub))
if err != nil {
return returnErr(err)
}
// Reserve a nonce here to ensure correctly ordered submissions.
nonce, err := s.txMgr.ReserveNextNonce(ctx)
if err != nil {
return returnErr(err)
}
estimatedGas := s.gasEstimator(s.chain.ID, sub.Msgs)
candidate := txmgr.TxCandidate{
TxData: txData,
To: &s.chain.PortalAddress,
GasLimit: estimatedGas,
Value: big.NewInt(0),
Nonce: &nonce,
}
asyncResp := make(chan error, 1) // Actual async response populated by goroutine below.
go func() {
tx, rec, err := s.txMgr.Send(ctx, candidate)
if err != nil {
asyncResp <- errors.Wrap(err, "failed to send tx", reqAttrs...)
return
}
submissionTotal.WithLabelValues(srcChain, dstChain).Inc()
msgTotal.WithLabelValues(srcChain, dstChain).Add(float64(len(sub.Msgs)))
gasEstimated.WithLabelValues(dstChain).Observe(float64(estimatedGas))
receiptAttrs := []any{
"valset_id", sub.ValidatorSetID,
"status", rec.Status,
"nonce", tx.Nonce(),
"height", rec.BlockNumber.Uint64(),
"gas_used", rec.GasUsed,
"tx_hash", rec.TxHash,
}
spendTotal.WithLabelValues(dstChain, string(s.gasToken)).Add(totalSpendGwei(tx, rec))
if s.onSubmit != nil {
go s.onSubmit(ctx, tx, rec, sub)
}
const statusReverted = 0
if rec.Status == statusReverted {
// Try and get debug information of the reverted transaction
resp, err := s.ethCl.CallContract(ctx, callFromTx(s.txMgr.From(), tx), rec.BlockNumber)
errAttrs := slices.Concat(receiptAttrs, reqAttrs, []any{
"call_resp", hexutil.Encode(resp),
"call_err", err,
"gas_limit", tx.Gas(),
})
revertedSubmissionTotal.WithLabelValues(srcChain, dstChain).Inc()
asyncResp <- errors.New("submission reverted", errAttrs...)
return
}
log.Info(ctx, "Sent submission", receiptAttrs...)
asyncResp <- nil
}()
return asyncResp
}
func callFromTx(from common.Address, tx *ethtypes.Transaction) ethereum.CallMsg {
resp := ethereum.CallMsg{
From: from,
To: tx.To(),
Gas: tx.Gas(),
Value: tx.Value(),
Data: tx.Data(),
AccessList: tx.AccessList(),
BlobGasFeeCap: tx.BlobGasFeeCap(),
BlobHashes: tx.BlobHashes(),
}
// Either populate gas price or gas caps (not both).
if tx.GasPrice() != nil && tx.GasPrice().Sign() != 0 {
resp.GasPrice = tx.GasPrice()
} else {
resp.GasFeeCap = tx.GasFeeCap()
resp.GasTipCap = tx.GasTipCap()
}
return resp
}
// totalSpendGwei returns the total amount spent on a transaction in gwei.
func totalSpendGwei(tx *ethtypes.Transaction, rec *ethtypes.Receipt) float64 {
fees := new(big.Int).Mul(rec.EffectiveGasPrice, umath.NewBigInt(rec.GasUsed))
total := new(big.Int).Add(tx.Value(), fees)
return toGwei(total)
}
// 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
}