-
Notifications
You must be signed in to change notification settings - Fork 0
/
evm_signer.go
667 lines (615 loc) · 22.2 KB
/
evm_signer.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
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
package zetaclient
import (
"context"
"encoding/base64"
"encoding/hex"
"fmt"
"math/big"
"math/rand"
"strconv"
"strings"
"time"
"github.com/ethereum/go-ethereum/accounts/abi"
ethcommon "github.com/ethereum/go-ethereum/common"
ethtypes "github.com/ethereum/go-ethereum/core/types"
"github.com/ethereum/go-ethereum/crypto"
"github.com/ethereum/go-ethereum/ethclient"
"github.com/rs/zerolog"
"github.com/rs/zerolog/log"
"github.com/zeta-chain/protocol-contracts/pkg/contracts/evm/erc20custody.sol"
"github.com/zeta-chain/zetacore/common"
"github.com/zeta-chain/zetacore/x/crosschain/types"
observertypes "github.com/zeta-chain/zetacore/x/observer/types"
)
type EVMSigner struct {
client EVMRPCClient
chain *common.Chain
chainID *big.Int
tssSigner TSSSigner
ethSigner ethtypes.Signer
abi abi.ABI
erc20CustodyABI abi.ABI
metaContractAddress ethcommon.Address
erc20CustodyContractAddress ethcommon.Address
logger zerolog.Logger
ts *TelemetryServer
}
var _ ChainSigner = &EVMSigner{}
func NewEVMSigner(
chain common.Chain,
endpoint string,
tssSigner TSSSigner,
abiString string,
erc20CustodyABIString string,
metaContract ethcommon.Address,
erc20CustodyContract ethcommon.Address,
logger zerolog.Logger,
ts *TelemetryServer,
) (*EVMSigner, error) {
client, err := ethclient.Dial(endpoint)
if err != nil {
return nil, err
}
chainID, err := client.ChainID(context.TODO())
if err != nil {
return nil, err
}
ethSigner := ethtypes.LatestSignerForChainID(chainID)
connectorABI, err := abi.JSON(strings.NewReader(abiString))
if err != nil {
return nil, err
}
erc20CustodyABI, err := abi.JSON(strings.NewReader(erc20CustodyABIString))
if err != nil {
return nil, err
}
return &EVMSigner{
client: client,
chain: &chain,
tssSigner: tssSigner,
chainID: chainID,
ethSigner: ethSigner,
abi: connectorABI,
erc20CustodyABI: erc20CustodyABI,
metaContractAddress: metaContract,
erc20CustodyContractAddress: erc20CustodyContract,
logger: logger.With().
Str("chain", chain.ChainName.String()).
Str("module", "EVMSigner").Logger(),
ts: ts,
}, nil
}
// Sign given data, and metadata (gas, nonce, etc)
// returns a signed transaction, sig bytes, hash bytes, and error
func (signer *EVMSigner) Sign(
data []byte,
to ethcommon.Address,
gasLimit uint64,
gasPrice *big.Int,
nonce uint64,
height uint64,
) (*ethtypes.Transaction, []byte, []byte, error) {
log.Debug().Msgf("TSS SIGNER: %s", signer.tssSigner.Pubkey())
tx := ethtypes.NewTransaction(nonce, to, big.NewInt(0), gasLimit, gasPrice, data)
hashBytes := signer.ethSigner.Hash(tx).Bytes()
sig, err := signer.tssSigner.Sign(hashBytes, height, nonce, signer.chain, "")
if err != nil {
return nil, nil, nil, err
}
log.Debug().Msgf("Sign: Signature: %s", hex.EncodeToString(sig[:]))
pubk, err := crypto.SigToPub(hashBytes, sig[:])
if err != nil {
signer.logger.Error().Err(err).Msgf("SigToPub error")
}
addr := crypto.PubkeyToAddress(*pubk)
signer.logger.Info().Msgf("Sign: Ecrecovery of signature: %s", addr.Hex())
signedTX, err := tx.WithSignature(signer.ethSigner, sig[:])
if err != nil {
return nil, nil, nil, err
}
return signedTX, sig[:], hashBytes[:], nil
}
// Broadcast takes in signed tx, broadcast to external chain node
func (signer *EVMSigner) Broadcast(tx *ethtypes.Transaction) error {
ctxt, cancel := context.WithTimeout(context.Background(), 1*time.Second)
defer cancel()
return signer.client.SendTransaction(ctxt, tx)
}
// SignOutboundTx
// function onReceive(
//
// bytes calldata originSenderAddress,
// uint256 originChainId,
// address destinationAddress,
// uint zetaAmount,
// bytes calldata message,
// bytes32 internalSendHash
//
// ) external virtual {}
func (signer *EVMSigner) SignOutboundTx(sender ethcommon.Address,
srcChainID *big.Int,
to ethcommon.Address,
amount *big.Int,
gasLimit uint64,
message []byte,
sendHash [32]byte,
nonce uint64,
gasPrice *big.Int,
height uint64) (*ethtypes.Transaction, error) {
if len(sendHash) < 32 {
return nil, fmt.Errorf("sendHash len %d must be 32", len(sendHash))
}
var data []byte
var err error
data, err = signer.abi.Pack("onReceive", sender.Bytes(), srcChainID, to, amount, message, sendHash)
if err != nil {
return nil, fmt.Errorf("pack error: %w", err)
}
tx, _, _, err := signer.Sign(data, signer.metaContractAddress, gasLimit, gasPrice, nonce, height)
if err != nil {
return nil, fmt.Errorf("Sign error: %w", err)
}
return tx, nil
}
// SignRevertTx
// function onRevert(
// address originSenderAddress,
// uint256 originChainId,
// bytes calldata destinationAddress,
// uint256 destinationChainId,
// uint256 zetaAmount,
// bytes calldata message,
// bytes32 internalSendHash
// ) external override whenNotPaused onlyTssAddress
func (signer *EVMSigner) SignRevertTx(
sender ethcommon.Address,
srcChainID *big.Int,
to []byte,
toChainID *big.Int,
amount *big.Int,
gasLimit uint64,
message []byte,
sendHash [32]byte,
nonce uint64,
gasPrice *big.Int,
height uint64,
) (*ethtypes.Transaction, error) {
var data []byte
var err error
data, err = signer.abi.Pack("onRevert", sender, srcChainID, to, toChainID, amount, message, sendHash)
if err != nil {
return nil, fmt.Errorf("pack error: %w", err)
}
tx, _, _, err := signer.Sign(data, signer.metaContractAddress, gasLimit, gasPrice, nonce, height)
if err != nil {
return nil, fmt.Errorf("Sign error: %w", err)
}
return tx, nil
}
func (signer *EVMSigner) SignCancelTx(nonce uint64, gasPrice *big.Int, height uint64) (*ethtypes.Transaction, error) {
tx := ethtypes.NewTransaction(nonce, signer.tssSigner.EVMAddress(), big.NewInt(0), 21000, gasPrice, nil)
hashBytes := signer.ethSigner.Hash(tx).Bytes()
sig, err := signer.tssSigner.Sign(hashBytes, height, nonce, signer.chain, "")
if err != nil {
return nil, err
}
pubk, err := crypto.SigToPub(hashBytes, sig[:])
if err != nil {
signer.logger.Error().Err(err).Msgf("SigToPub error")
}
addr := crypto.PubkeyToAddress(*pubk)
signer.logger.Info().Msgf("Sign: Ecrecovery of signature: %s", addr.Hex())
signedTX, err := tx.WithSignature(signer.ethSigner, sig[:])
if err != nil {
return nil, err
}
return signedTX, nil
}
func (signer *EVMSigner) SignWithdrawTx(
to ethcommon.Address,
amount *big.Int,
nonce uint64,
gasPrice *big.Int,
height uint64,
) (*ethtypes.Transaction, error) {
tx := ethtypes.NewTransaction(nonce, to, amount, 21000, gasPrice, nil)
hashBytes := signer.ethSigner.Hash(tx).Bytes()
sig, err := signer.tssSigner.Sign(hashBytes, height, nonce, signer.chain, "")
if err != nil {
return nil, err
}
pubk, err := crypto.SigToPub(hashBytes, sig[:])
if err != nil {
signer.logger.Error().Err(err).Msgf("SigToPub error")
}
addr := crypto.PubkeyToAddress(*pubk)
signer.logger.Info().Msgf("Sign: Ecrecovery of signature: %s", addr.Hex())
signedTX, err := tx.WithSignature(signer.ethSigner, sig[:])
if err != nil {
return nil, err
}
return signedTX, nil
}
func (signer *EVMSigner) SignCommandTx(
cmd string,
params string,
to ethcommon.Address,
outboundParams *types.OutboundTxParams,
gasLimit uint64,
gasPrice *big.Int,
height uint64,
) (*ethtypes.Transaction, error) {
if cmd == common.CmdWhitelistERC20 {
erc20 := ethcommon.HexToAddress(params)
if erc20 == (ethcommon.Address{}) {
return nil, fmt.Errorf("SignCommandTx: invalid erc20 address %s", params)
}
custodyAbi, err := erc20custody.ERC20CustodyMetaData.GetAbi()
if err != nil {
return nil, err
}
data, err := custodyAbi.Pack("whitelist", erc20)
if err != nil {
return nil, err
}
tx, _, _, err := signer.Sign(data, to, gasLimit, gasPrice, outboundParams.OutboundTxTssNonce, height)
if err != nil {
return nil, fmt.Errorf("sign error: %w", err)
}
return tx, nil
}
if cmd == common.CmdMigrateTssFunds {
tx := ethtypes.NewTransaction(outboundParams.OutboundTxTssNonce, to, outboundParams.Amount.BigInt(), 21000, gasPrice, nil)
hashBytes := signer.ethSigner.Hash(tx).Bytes()
sig, err := signer.tssSigner.Sign(hashBytes, height, outboundParams.OutboundTxTssNonce, signer.chain, "")
if err != nil {
return nil, err
}
pubk, err := crypto.SigToPub(hashBytes, sig[:])
if err != nil {
signer.logger.Error().Err(err).Msgf("SigToPub error")
}
addr := crypto.PubkeyToAddress(*pubk)
signer.logger.Info().Msgf("Sign: Ecrecovery of signature: %s", addr.Hex())
signedTX, err := tx.WithSignature(signer.ethSigner, sig[:])
if err != nil {
return nil, err
}
return signedTX, nil
}
return nil, fmt.Errorf("SignCommandTx: unknown command %s", cmd)
}
func (signer *EVMSigner) TryProcessOutTx(
send *types.CrossChainTx,
outTxMan *OutTxProcessorManager,
outTxID string,
evmClient ChainClient,
zetaBridge ZetaCoreBridger,
height uint64,
) {
logger := signer.logger.With().
Str("outTxID", outTxID).
Str("SendHash", send.Index).
Logger()
logger.Info().Msgf("start processing outTxID %s", outTxID)
logger.Info().Msgf("EVM Chain TryProcessOutTx: %s, value %d to %s", send.Index, send.GetCurrentOutTxParam().Amount.BigInt(), send.GetCurrentOutTxParam().Receiver)
defer func() {
outTxMan.EndTryProcess(outTxID)
}()
myID := zetaBridge.GetKeys().GetOperatorAddress()
var to ethcommon.Address
var err error
var toChain *common.Chain
if send.CctxStatus.Status == types.CctxStatus_PendingRevert {
to = ethcommon.HexToAddress(send.InboundTxParams.Sender)
toChain = common.GetChainFromChainID(send.InboundTxParams.SenderChainId)
if toChain == nil {
logger.Error().Msgf("Unknown chain: %d", send.InboundTxParams.SenderChainId)
return
}
logger.Info().Msgf("Abort: reverting inbound")
} else if send.CctxStatus.Status == types.CctxStatus_PendingOutbound {
to = ethcommon.HexToAddress(send.GetCurrentOutTxParam().Receiver)
toChain = common.GetChainFromChainID(send.GetCurrentOutTxParam().ReceiverChainId)
if toChain == nil {
logger.Error().Msgf("Unknown chain: %d", send.GetCurrentOutTxParam().ReceiverChainId)
return
}
} else {
logger.Info().Msgf("Transaction doesn't need to be processed status: %d", send.CctxStatus.Status)
return
}
if err != nil {
logger.Error().Err(err).Msg("ParseChain fail; skip")
return
}
// Early return if the cctx is already processed
included, confirmed, err := evmClient.IsSendOutTxProcessed(send.Index, send.GetCurrentOutTxParam().OutboundTxTssNonce, send.GetCurrentOutTxParam().CoinType, logger)
if err != nil {
logger.Error().Err(err).Msg("IsSendOutTxProcessed failed")
}
if included || confirmed {
logger.Info().Msgf("CCTX already processed; exit signer")
return
}
var message []byte
if send.GetCurrentOutTxParam().CoinType != common.CoinType_Cmd {
message, err = base64.StdEncoding.DecodeString(send.RelayedMessage)
if err != nil {
logger.Err(err).Msgf("decode CCTX.Message %s error", send.RelayedMessage)
}
}
gasLimit := send.GetCurrentOutTxParam().OutboundTxGasLimit
if gasLimit < 100_000 {
gasLimit = 100_000
logger.Warn().Msgf("gasLimit %d is too low; set to %d", send.GetCurrentOutTxParam().OutboundTxGasLimit, gasLimit)
}
if gasLimit > 1_000_000 {
gasLimit = 1_000_000
logger.Warn().Msgf("gasLimit %d is too high; set to %d", send.GetCurrentOutTxParam().OutboundTxGasLimit, gasLimit)
}
logger.Info().Msgf("chain %s minting %d to %s, nonce %d, finalized zeta bn %d", toChain, send.InboundTxParams.Amount, to.Hex(), send.GetCurrentOutTxParam().OutboundTxTssNonce, send.InboundTxParams.InboundTxFinalizedZetaHeight)
sendHash, err := hex.DecodeString(send.Index[2:]) // remove the leading 0x
if err != nil || len(sendHash) != 32 {
logger.Error().Err(err).Msgf("decode CCTX %s error", send.Index)
return
}
var sendhash [32]byte
copy(sendhash[:32], sendHash[:32])
// use dynamic gas price for ethereum chains
var gasprice *big.Int
// The code below is a fix for https://github.com/zeta-chain/node/issues/1085
// doesn't close directly the issue because we should determine if we want to keep using SuggestGasPrice if no OutboundTxGasPrice
// we should possibly remove it completely and return an error if no OutboundTxGasPrice is provided because it means no fee is processed on ZetaChain
specified, ok := new(big.Int).SetString(send.GetCurrentOutTxParam().OutboundTxGasPrice, 10)
if !ok {
if common.IsEthereumChain(toChain.ChainId) {
suggested, err := signer.client.SuggestGasPrice(context.Background())
if err != nil {
logger.Error().Err(err).Msgf("cannot get gas price from chain %s ", toChain)
return
}
gasprice = roundUpToNearestGwei(suggested)
} else {
logger.Error().Err(err).Msgf("cannot convert gas price %s ", send.GetCurrentOutTxParam().OutboundTxGasPrice)
return
}
} else {
gasprice = specified
}
//if common.IsEthereumChain(toChain.ChainId) {
// suggested, err := signer.client.SuggestGasPrice(context.Background())
// if err != nil {
// logger.Error().Err(err).Msgf("cannot get gas price from chain %s ", toChain)
// return
// }
// gasprice = roundUpToNearestGwei(suggested)
//} else {
// specified, ok := new(big.Int).SetString(send.GetCurrentOutTxParam().OutboundTxGasPrice, 10)
// if !ok {
// logger.Error().Err(err).Msgf("cannot convert gas price %s ", send.GetCurrentOutTxParam().OutboundTxGasPrice)
// return
// }
// gasprice = specified
//}
flags, err := zetaBridge.GetCrosschainFlags()
if err != nil {
logger.Error().Err(err).Msgf("cannot get crosschain flags")
return
}
var tx *ethtypes.Transaction
if send.GetCurrentOutTxParam().CoinType == common.CoinType_Cmd { // admin command
to := ethcommon.HexToAddress(send.GetCurrentOutTxParam().Receiver)
if to == (ethcommon.Address{}) {
logger.Error().Msgf("invalid receiver %s", send.GetCurrentOutTxParam().Receiver)
return
}
msg := strings.Split(send.RelayedMessage, ":")
if len(msg) != 2 {
logger.Error().Msgf("invalid message %s", msg)
return
}
tx, err = signer.SignCommandTx(msg[0], msg[1], to, send.GetCurrentOutTxParam(), gasLimit, gasprice, height)
} else if send.InboundTxParams.SenderChainId == common.ZetaChain().ChainId && send.CctxStatus.Status == types.CctxStatus_PendingOutbound && flags.IsOutboundEnabled {
if send.GetCurrentOutTxParam().CoinType == common.CoinType_Gas {
logger.Info().Msgf("SignWithdrawTx: %d => %s, nonce %d, gasprice %d", send.InboundTxParams.SenderChainId, toChain, send.GetCurrentOutTxParam().OutboundTxTssNonce, gasprice)
tx, err = signer.SignWithdrawTx(
to,
send.GetCurrentOutTxParam().Amount.BigInt(),
send.GetCurrentOutTxParam().OutboundTxTssNonce,
gasprice,
height,
)
}
if send.GetCurrentOutTxParam().CoinType == common.CoinType_ERC20 {
asset := ethcommon.HexToAddress(send.InboundTxParams.Asset)
logger.Info().Msgf("SignERC20WithdrawTx: %d => %s, nonce %d, gasprice %d", send.InboundTxParams.SenderChainId, toChain, send.GetCurrentOutTxParam().OutboundTxTssNonce, gasprice)
tx, err = signer.SignERC20WithdrawTx(
to,
asset,
send.GetCurrentOutTxParam().Amount.BigInt(),
gasLimit,
send.GetCurrentOutTxParam().OutboundTxTssNonce,
gasprice,
height,
)
}
if send.GetCurrentOutTxParam().CoinType == common.CoinType_Zeta {
logger.Info().Msgf("SignOutboundTx: %d => %s, nonce %d, gasprice %d", send.InboundTxParams.SenderChainId, toChain, send.GetCurrentOutTxParam().OutboundTxTssNonce, gasprice)
tx, err = signer.SignOutboundTx(
ethcommon.HexToAddress(send.InboundTxParams.Sender),
big.NewInt(send.InboundTxParams.SenderChainId),
to,
send.GetCurrentOutTxParam().Amount.BigInt(),
gasLimit,
message,
sendhash,
send.GetCurrentOutTxParam().OutboundTxTssNonce,
gasprice,
height,
)
}
} else if send.CctxStatus.Status == types.CctxStatus_PendingRevert && send.OutboundTxParams[0].ReceiverChainId == common.ZetaChain().ChainId {
if send.GetCurrentOutTxParam().CoinType == common.CoinType_Gas {
logger.Info().Msgf("SignWithdrawTx: %d => %s, nonce %d, gasprice %d", send.InboundTxParams.SenderChainId, toChain, send.GetCurrentOutTxParam().OutboundTxTssNonce, gasprice)
tx, err = signer.SignWithdrawTx(
to,
send.GetCurrentOutTxParam().Amount.BigInt(),
send.GetCurrentOutTxParam().OutboundTxTssNonce,
gasprice,
height,
)
}
if send.GetCurrentOutTxParam().CoinType == common.CoinType_ERC20 {
asset := ethcommon.HexToAddress(send.InboundTxParams.Asset)
logger.Info().Msgf("SignERC20WithdrawTx: %d => %s, nonce %d, gasprice %d", send.InboundTxParams.SenderChainId, toChain, send.GetCurrentOutTxParam().OutboundTxTssNonce, gasprice)
tx, err = signer.SignERC20WithdrawTx(
to,
asset,
send.GetCurrentOutTxParam().Amount.BigInt(),
gasLimit,
send.GetCurrentOutTxParam().OutboundTxTssNonce,
gasprice,
height,
)
}
} else if send.CctxStatus.Status == types.CctxStatus_PendingRevert {
logger.Info().Msgf("SignRevertTx: %d => %s, nonce %d, gasprice %d", send.InboundTxParams.SenderChainId, toChain, send.GetCurrentOutTxParam().OutboundTxTssNonce, gasprice)
tx, err = signer.SignRevertTx(
ethcommon.HexToAddress(send.InboundTxParams.Sender),
big.NewInt(send.OutboundTxParams[0].ReceiverChainId),
to.Bytes(),
big.NewInt(send.GetCurrentOutTxParam().ReceiverChainId),
send.GetCurrentOutTxParam().Amount.BigInt(),
gasLimit,
message,
sendhash,
send.GetCurrentOutTxParam().OutboundTxTssNonce,
gasprice,
height,
)
} else if send.CctxStatus.Status == types.CctxStatus_PendingOutbound {
logger.Info().Msgf("SignOutboundTx: %d => %s, nonce %d, gasprice %d", send.InboundTxParams.SenderChainId, toChain, send.GetCurrentOutTxParam().OutboundTxTssNonce, gasprice)
tx, err = signer.SignOutboundTx(
ethcommon.HexToAddress(send.InboundTxParams.Sender),
big.NewInt(send.InboundTxParams.SenderChainId),
to,
send.GetCurrentOutTxParam().Amount.BigInt(),
gasLimit,
message,
sendhash,
send.GetCurrentOutTxParam().OutboundTxTssNonce,
gasprice,
height,
)
}
if err != nil {
logger.Warn().Err(err).Msgf("signer SignOutbound error: nonce %d chain %d", send.GetCurrentOutTxParam().OutboundTxTssNonce, send.GetCurrentOutTxParam().ReceiverChainId)
return
}
logger.Info().Msgf("Key-sign success: %d => %s, nonce %d", send.InboundTxParams.SenderChainId, toChain, send.GetCurrentOutTxParam().OutboundTxTssNonce)
_, err = zetaBridge.GetObserverList(*toChain)
if err != nil {
logger.Warn().Err(err).Msgf("unable to get observer list: chain %d observation %s", send.GetCurrentOutTxParam().OutboundTxTssNonce, observertypes.ObservationType_OutBoundTx.String())
}
if tx != nil {
outTxHash := tx.Hash().Hex()
logger.Info().Msgf("on chain %s nonce %d, outTxHash %s signer %s", signer.chain, send.GetCurrentOutTxParam().OutboundTxTssNonce, outTxHash, myID)
//if len(signers) == 0 || myid == signers[send.OutboundTxParams.Broadcaster] || myid == signers[int(send.OutboundTxParams.Broadcaster+1)%len(signers)] {
backOff := 1000 * time.Millisecond
// retry loop: 1s, 2s, 4s, 8s, 16s in case of RPC error
for i := 0; i < 5; i++ {
logger.Info().Msgf("broadcasting tx %s to chain %s: nonce %d, retry %d", outTxHash, toChain, send.GetCurrentOutTxParam().OutboundTxTssNonce, i)
// #nosec G404 randomness is not a security issue here
time.Sleep(time.Duration(rand.Intn(1500)) * time.Millisecond) // FIXME: use backoff
err := signer.Broadcast(tx)
if err != nil {
log.Warn().Err(err).Msgf("OutTx Broadcast error")
retry, report := HandleBroadcastError(err, strconv.FormatUint(send.GetCurrentOutTxParam().OutboundTxTssNonce, 10), toChain.String(), outTxHash)
if report {
zetaHash, err := zetaBridge.AddTxHashToOutTxTracker(toChain.ChainId, tx.Nonce(), outTxHash, nil, "", -1)
if err != nil {
logger.Err(err).Msgf("Unable to add to tracker on ZetaCore: nonce %d chain %s outTxHash %s", send.GetCurrentOutTxParam().OutboundTxTssNonce, toChain, outTxHash)
}
logger.Info().Msgf("Broadcast to core successful %s", zetaHash)
}
if !retry {
break
}
backOff *= 2
continue
}
logger.Info().Msgf("Broadcast success: nonce %d to chain %s outTxHash %s", send.GetCurrentOutTxParam().OutboundTxTssNonce, toChain, outTxHash)
zetaHash, err := zetaBridge.AddTxHashToOutTxTracker(toChain.ChainId, tx.Nonce(), outTxHash, nil, "", -1)
if err != nil {
logger.Err(err).Msgf("Unable to add to tracker on ZetaCore: nonce %d chain %s outTxHash %s", send.GetCurrentOutTxParam().OutboundTxTssNonce, toChain, outTxHash)
}
logger.Info().Msgf("Broadcast to core successful %s", zetaHash)
break // successful broadcast; no need to retry
}
}
}
// SignERC20WithdrawTx
// function withdraw(
// address recipient,
// address asset,
// uint256 amount,
// ) external onlyTssAddress
func (signer *EVMSigner) SignERC20WithdrawTx(
recipient ethcommon.Address,
asset ethcommon.Address,
amount *big.Int,
gasLimit uint64,
nonce uint64,
gasPrice *big.Int,
height uint64,
) (*ethtypes.Transaction, error) {
var data []byte
var err error
data, err = signer.erc20CustodyABI.Pack("withdraw", recipient, asset, amount)
if err != nil {
return nil, fmt.Errorf("pack error: %w", err)
}
tx, _, _, err := signer.Sign(data, signer.erc20CustodyContractAddress, gasLimit, gasPrice, nonce, height)
if err != nil {
return nil, fmt.Errorf("sign error: %w", err)
}
return tx, nil
}
// SignWhitelistTx
// function whitelist(
// address asset,
// ) external onlyTssAddress
// function unwhitelist(
// address asset,
// ) external onlyTssAddress
func (signer *EVMSigner) SignWhitelistTx(
action string,
_ ethcommon.Address,
asset ethcommon.Address,
gasLimit uint64,
nonce uint64,
gasPrice *big.Int,
height uint64,
) (*ethtypes.Transaction, error) {
var data []byte
var err error
data, err = signer.erc20CustodyABI.Pack(action, asset)
if err != nil {
return nil, fmt.Errorf("pack error: %w", err)
}
tx, _, _, err := signer.Sign(data, signer.erc20CustodyContractAddress, gasLimit, gasPrice, nonce, height)
if err != nil {
return nil, fmt.Errorf("Sign error: %w", err)
}
return tx, nil
}
func roundUpToNearestGwei(gasPrice *big.Int) *big.Int {
oneGwei := big.NewInt(1_000_000_000) // 1 Gwei
mod := new(big.Int)
mod.Mod(gasPrice, oneGwei)
if mod.Cmp(big.NewInt(0)) == 0 { // gasprice is already a multiple of 1 Gwei
return gasPrice
}
return new(big.Int).Add(gasPrice, new(big.Int).Sub(oneGwei, mod))
}