forked from neutron-org/neutron-query-relayer
/
tx_sender.go
286 lines (245 loc) · 8.83 KB
/
tx_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
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
package submit
import (
"context"
"encoding/hex"
"fmt"
"strings"
"sync"
tmtypes "github.com/cometbft/cometbft/types"
"go.uber.org/zap"
"cosmossdk.io/api/tendermint/abci"
rpcclient "github.com/cometbft/cometbft/rpc/client"
"github.com/cosmos/cosmos-sdk/client"
"github.com/cosmos/cosmos-sdk/client/tx"
"github.com/cosmos/cosmos-sdk/codec"
"github.com/cosmos/cosmos-sdk/crypto/keyring"
"github.com/cosmos/cosmos-sdk/crypto/keys/secp256k1"
sdk "github.com/cosmos/cosmos-sdk/types"
txtypes "github.com/cosmos/cosmos-sdk/types/tx"
"github.com/cosmos/cosmos-sdk/types/tx/signing"
authtxtypes "github.com/cosmos/cosmos-sdk/x/auth/tx"
authtypes "github.com/cosmos/cosmos-sdk/x/auth/types"
"github.com/hadronlabs-org/neutron-query-relayer/internal/config"
)
const (
accountQueryPath = "/cosmos.auth.v1beta1.Query/Account"
simulateQueryPath = "/cosmos.tx.v1beta1.Service/Simulate"
IncorrectAccountSequenceCode = 32
)
type TxSender struct {
lock sync.Mutex
sequence uint64
accountNumber uint64
keybase keyring.Keyring
baseTxf tx.Factory
txConfig client.TxConfig
rpcClient rpcclient.Client
chainID string
signKeyName string
gasPrices string
gasLimit uint64
logger *zap.Logger
}
func TestKeybase(chainID string, keyringRootDir string, cdc codec.Codec) (keyring.Keyring, error) {
keybase, err := keyring.New(chainID, "test", keyringRootDir, nil, cdc)
if err != nil {
return keybase, fmt.Errorf("error creating keybase for chainId=%s and keyringRootDir=%s: %w", chainID, keyringRootDir, err)
}
return keybase, nil
}
func NewTxSender(
ctx context.Context,
rpcClient rpcclient.Client,
marshaller codec.ProtoCodecMarshaler,
keybase keyring.Keyring,
cfg config.NeutronChainConfig,
logger *zap.Logger,
neutronChainID string,
) (*TxSender, error) {
txConfig := authtxtypes.NewTxConfig(marshaller, authtxtypes.DefaultSignModes)
baseTxf := tx.Factory{}.
WithKeybase(keybase).
WithSignMode(signing.SignMode_SIGN_MODE_DIRECT).
WithTxConfig(txConfig).
WithChainID(neutronChainID).
WithGasAdjustment(cfg.GasAdjustment).
WithGasPrices(cfg.GasPrices)
txs := &TxSender{
lock: sync.Mutex{},
keybase: keybase,
txConfig: txConfig,
baseTxf: baseTxf,
rpcClient: rpcClient,
chainID: neutronChainID,
signKeyName: cfg.SignKeyName,
gasPrices: cfg.GasPrices,
gasLimit: cfg.GasLimit,
logger: logger,
}
err := txs.refreshAccountInfo(ctx)
if err != nil {
return nil, fmt.Errorf("failed to init tx sender: %w", err)
}
return txs, nil
}
func (txs *TxSender) refreshAccountInfo(ctx context.Context) error {
senderAddr, err := txs.SenderAddr()
if err != nil {
return fmt.Errorf("could not fetch sender addr: %w", err)
}
account, err := txs.queryAccount(ctx, senderAddr)
if err != nil {
return fmt.Errorf("error fetching account: %w", err)
}
txs.accountNumber = account.AccountNumber
txs.sequence = account.Sequence
return nil
}
// Send builds transaction with calculated input msgs, calculated gas and fees, signs it and submits to chain
func (txs *TxSender) Send(ctx context.Context, msgs []sdk.Msg) (string, error) {
txs.lock.Lock()
defer txs.lock.Unlock()
txf := txs.baseTxf.
WithAccountNumber(txs.accountNumber).
WithSequence(txs.sequence)
gasNeeded, err := txs.calculateGas(ctx, txf, msgs...)
if err != nil {
// at this point error code for "incorrect account sequence" is 18 = "invalid request"
// it's a very common error code to rely on, hence we have to rely on error message
if strings.Contains(err.Error(), "incorrect account sequence") {
errInit := txs.refreshAccountInfo(ctx)
if errInit != nil {
return "", fmt.Errorf("error calculating gas: failed to reinit sender: %w", errInit)
}
txs.logger.Info("sender reinitialized successfully (account sequence reset)")
}
return "", fmt.Errorf("error calculating gas: %w", err)
}
if txs.gasLimit > 0 && gasNeeded > txs.gasLimit {
return "", fmt.Errorf("exceeds gas limit: gas needed %d, gas limit %d", gasNeeded, txs.gasLimit)
}
txf = txf.
WithGas(gasNeeded).
WithGasPrices(txs.gasPrices)
bz, err := txs.signAndBuildTxBz(txf, msgs)
if err != nil {
return "", fmt.Errorf("could not sign and build tx bz: %w", err)
}
res, err := txs.rpcClient.BroadcastTxSync(ctx, bz)
if err != nil {
return "", fmt.Errorf("error broadcasting sync transaction: %w", err)
}
if res.Code == 0 {
txs.sequence += 1
return hex.EncodeToString(tmtypes.Tx(bz).Hash()), nil
}
if res.Code == IncorrectAccountSequenceCode {
errInit := txs.refreshAccountInfo(ctx)
if errInit != nil {
return "", fmt.Errorf("error broadcasting sync transaction: failed to reinit sender: %w", errInit)
}
txs.logger.Info("sender reinitialized successfully (account sequence reset)")
}
return "", fmt.Errorf("error broadcasting sync transaction: log=%s", res.Log)
}
func (txs *TxSender) SenderAddr() (string, error) {
info, err := txs.keybase.Key(txs.signKeyName)
if err != nil {
return "", fmt.Errorf("could not fetch sender info from keychain with signKeyName=%s: %w", txs.signKeyName, err)
}
addr, err := info.GetAddress()
if err != nil {
return "", fmt.Errorf("failed to get addr from pubkey: %w", err)
}
return addr.String(), nil
}
// queryAccount returns BaseAccount for given account address
func (txs *TxSender) queryAccount(ctx context.Context, address string) (*authtypes.BaseAccount, error) {
request := authtypes.QueryAccountRequest{Address: address}
req, err := request.Marshal()
if err != nil {
return nil, fmt.Errorf("error marshalling query account request for account=%s: %w", address, err)
}
simQuery := abci.RequestQuery{
Path: accountQueryPath,
Data: req,
}
res, err := txs.rpcClient.ABCIQueryWithOptions(ctx, simQuery.Path, simQuery.Data, rpcclient.DefaultABCIQueryOptions)
if err != nil {
return nil, fmt.Errorf("error making abci query for account=%s: %w", address, err)
}
if res.Response.Code != 0 {
return nil, fmt.Errorf("error fetching account with address=%s log=%s", address, res.Response.Log)
}
var response authtypes.QueryAccountResponse
if err := response.Unmarshal(res.Response.Value); err != nil {
return nil, fmt.Errorf("error unmarshalling QueryAccountResponse for account=%s: %w", address, err)
}
var account authtypes.BaseAccount
err = account.Unmarshal(response.Account.Value)
if err != nil {
return nil, fmt.Errorf("error unmarshalling BaseAccount for account=%s: %w", address, err)
}
return &account, nil
}
func (txs *TxSender) signAndBuildTxBz(txf tx.Factory, msgs []sdk.Msg) ([]byte, error) {
txBuilder, err := txf.BuildUnsignedTx(msgs...)
if err != nil {
return nil, fmt.Errorf("failed to build transaction builder: %w", err)
}
err = tx.Sign(txf, txs.signKeyName, txBuilder, false)
if err != nil {
return nil, fmt.Errorf("error signing transaction: %w", err)
}
bz, err := txs.txConfig.TxEncoder()(txBuilder.GetTx())
return bz, err
}
func (txs *TxSender) calculateGas(ctx context.Context, txf tx.Factory, msgs ...sdk.Msg) (uint64, error) {
simulation, err := txs.buildSimulationTx(txf, msgs...)
if err != nil {
return 0, fmt.Errorf("error building simulation tx: %w", err)
}
// We then call the Simulate method on this client.
simQuery := abci.RequestQuery{
Path: simulateQueryPath,
Data: simulation,
}
res, err := txs.rpcClient.ABCIQueryWithOptions(ctx, simQuery.Path, simQuery.Data, rpcclient.DefaultABCIQueryOptions)
if err != nil {
return 0, fmt.Errorf("error making abci query for gas calculation: %w", err)
}
var simRes txtypes.SimulateResponse
if err := simRes.Unmarshal(res.Response.Value); err != nil {
return 0, fmt.Errorf("error unmarshalling simulate response value: %w", err)
}
if simRes.GasInfo == nil {
return 0, fmt.Errorf("no result in simulation response with log=%s code=%d", res.Response.Log, res.Response.Code)
}
return uint64(txf.GasAdjustment() * float64(simRes.GasInfo.GasUsed)), nil
}
// buildSimulationTx creates an unsigned tx with an empty single signature and returns
// the encoded transaction or an error if the unsigned transaction cannot be built.
func (txs *TxSender) buildSimulationTx(txf tx.Factory, msgs ...sdk.Msg) ([]byte, error) {
txb, err := txs.baseTxf.BuildUnsignedTx(msgs...)
if err != nil {
return nil, fmt.Errorf("error building unsigned tx for simulation: %w", err)
}
// Create an empty signature literal as the ante handler will populate with a
// sentinel pubkey.
sig := signing.SignatureV2{
PubKey: &secp256k1.PubKey{},
Data: &signing.SingleSignatureData{
SignMode: txs.baseTxf.SignMode(),
},
Sequence: txf.Sequence(),
}
if err := txb.SetSignatures(sig); err != nil {
return nil, fmt.Errorf("error settings signatures for simulation: %w", err)
}
bz, err := txs.txConfig.TxEncoder()(txb.GetTx())
if err != nil {
return nil, fmt.Errorf("error encoding transaction: %w", err)
}
simReq := txtypes.SimulateRequest{TxBytes: bz}
return simReq.Marshal()
}