-
Notifications
You must be signed in to change notification settings - Fork 2.1k
/
process_message.go
770 lines (644 loc) · 23 KB
/
process_message.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
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
package processor
import (
"context"
"encoding/hex"
"encoding/json"
"fmt"
"log/slog"
"math/big"
"strings"
"time"
"github.com/cenkalti/backoff"
"github.com/ethereum/go-ethereum/accounts/abi"
"github.com/ethereum/go-ethereum/accounts/abi/bind"
"github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/consensus/misc/eip1559"
"github.com/ethereum/go-ethereum/core/types"
"github.com/ethereum/go-ethereum/params"
"github.com/pkg/errors"
"github.com/taikoxyz/taiko-mono/packages/relayer"
"github.com/taikoxyz/taiko-mono/packages/relayer/bindings/bridge"
"github.com/taikoxyz/taiko-mono/packages/relayer/pkg/proof"
"github.com/taikoxyz/taiko-mono/packages/relayer/pkg/queue"
"github.com/taikoxyz/taiko-mono/packages/relayer/pkg/utils"
)
var (
errUnprocessable = errors.New("message is unprocessable")
)
// eventStatusFromMsgHash will check the event's msgHash/signal, and
// get it's on-chain current status.
func (p *Processor) eventStatusFromMsgHash(
ctx context.Context,
gasLimit *big.Int,
signal [32]byte,
) (relayer.EventStatus, error) {
var eventStatus relayer.EventStatus
ctx, cancel := context.WithTimeout(ctx, p.ethClientTimeout)
defer cancel()
messageStatus, err := p.destBridge.MessageStatus(&bind.CallOpts{
Context: ctx,
}, signal)
if err != nil {
return 0, errors.Wrap(err, "svc.destBridge.MessageStatus")
}
eventStatus = relayer.EventStatus(messageStatus)
return eventStatus, nil
}
// processMessage prepares and calls `processMessage` on the bridge, given a
// message from the queue (from the indexer). It will
// generate a proof, or multiple proofs if hops are needed.
// it returns a boolean of whether we should requeue the message or not.
func (p *Processor) processMessage(
ctx context.Context,
msg queue.Message,
) (bool, error) {
msgBody := &queue.QueueMessageSentBody{}
if err := json.Unmarshal(msg.Body, msgBody); err != nil {
return false, errors.Wrap(err, "json.Unmarshal")
}
eventStatus, err := p.eventStatusFromMsgHash(ctx, msgBody.Event.Message.GasLimit, msgBody.Event.MsgHash)
if err != nil {
return false, errors.Wrap(err, "p.eventStatusFromMsgHash")
}
if !canProcessMessage(
ctx,
eventStatus,
msgBody.Event.Message.SrcOwner,
p.relayerAddr,
msgBody.Event.Message.GasLimit,
) {
return false, nil
}
if err := p.waitForConfirmations(ctx, msgBody.Event.Raw.TxHash, msgBody.Event.Raw.BlockNumber); err != nil {
return false, errors.Wrap(err, "p.waitForConfirmations")
}
// we need to check the invocation delays and proof receipt to see if
// this is currently processable, or we need to wait.
invocationDelays, err := p.destBridge.GetInvocationDelays(nil)
if err != nil {
return false, errors.Wrap(err, "p.destBridge.invocationDelays")
}
proofReceipt, err := p.destBridge.ProofReceipt(nil, msgBody.Event.MsgHash)
if err != nil {
return false, errors.Wrap(err, "p.destBridge.ProofReceipt")
}
slog.Info("proofReceipt",
"receivedAt", proofReceipt.ReceivedAt,
"preferredExecutor", proofReceipt.PreferredExecutor.Hex(),
"msgHash", common.BytesToHash(msgBody.Event.MsgHash[:]).Hex(),
)
var encodedSignalProof []byte
// proof has not been submitted, we need to generate it
if proofReceipt.ReceivedAt == 0 {
encodedSignalProof, err = p.generateEncodedSignalProof(ctx, msgBody.Event)
if err != nil {
return false, errors.Wrap(err, "p.generateEncodedSignalProof")
}
} else {
// proof has been submitted
// we need to check the invocation delay and
// preferred exeuctor, if it wasnt us
// who proved it, there is an extra delay.
if err := p.waitForInvocationDelay(ctx, invocationDelays, proofReceipt); err != nil {
return false, errors.Wrap(err, "p.waitForInvocationDelay")
}
}
receipt, err := p.sendProcessMessageAndWaitForReceipt(ctx, encodedSignalProof, msgBody)
if err != nil {
return false, errors.Wrap(err, "p.sendProcessMessageAndWaitForReceipt")
}
bridgeAbi, err := abi.JSON(strings.NewReader(bridge.BridgeABI))
if err != nil {
return false, err
}
// we need to check the receipt logs to see if we received MessageReceived
// or MessageExecuted, because we have a two-step bridge.
for _, log := range receipt.Logs {
topic := log.Topics[0]
// if we have a MessageReceived event, this was not processed, only
// the first step was. now we have to wait for the invocation delay.
if topic == bridgeAbi.Events["MessageReceived"].ID {
slog.Info("message processing resulted in MessageReceived event",
"msgHash", common.BytesToHash(msgBody.Event.MsgHash[:]).Hex(),
)
slog.Info("waiting for invocation delay",
"msgHash", common.BytesToHash(msgBody.Event.MsgHash[:]).Hex())
proofReceipt, err := p.destBridge.ProofReceipt(nil, msgBody.Event.MsgHash)
if err != nil {
return false, errors.Wrap(err, "p.destBridge.ProofReceipt")
}
if err := p.waitForInvocationDelay(ctx, invocationDelays, proofReceipt); err != nil {
return false, errors.Wrap(err, "p.waitForInvocationDelay")
}
if _, err := p.sendProcessMessageAndWaitForReceipt(ctx, nil, msgBody); err != nil {
return false, errors.Wrap(err, "p.sendProcessMessageAndWaitForReceipt")
}
} else if topic == bridgeAbi.Events["MessageExecuted"].ID {
// if we got MessageExecuted, the message is finished processing. this occurs
// either in one-step bridge processing (no invocation delay), or if this is the second process
// message call after the first step was completed.
slog.Info("message processing resulted in MessageExecuted event. processing finished")
}
}
messageStatus, err := p.destBridge.MessageStatus(&bind.CallOpts{}, msgBody.Event.MsgHash)
if err != nil {
return false, errors.Wrap(err, "p.destBridge.GetMessageStatus")
}
slog.Info(
"updating message status",
"status", relayer.EventStatus(messageStatus).String(),
"occuredtxHash", msgBody.Event.Raw.TxHash.Hex(),
)
if messageStatus == uint8(relayer.EventStatusRetriable) {
relayer.RetriableEvents.Inc()
} else if messageStatus == uint8(relayer.EventStatusDone) {
relayer.DoneEvents.Inc()
}
// internal will only be set if it's an actual queue message, not a targeted
// transaction hash set via config flag.
if msg.Internal != nil {
// update message status
if err := p.eventRepo.UpdateStatus(ctx, msgBody.ID, relayer.EventStatus(messageStatus)); err != nil {
return false, errors.Wrap(err, fmt.Sprintf("p.eventRepo.UpdateStatus, id: %v", msgBody.ID))
}
}
return false, nil
}
// sendProcessMessageAndWaitForReceipt uses a backoff retry message mechanism
// to send the onchain processMessage call on the bridge, then wait
// for the transaction receipt, and save the updated status to the database.
func (p *Processor) sendProcessMessageAndWaitForReceipt(
ctx context.Context,
encodedSignalProof []byte,
msgBody *queue.QueueMessageSentBody,
) (*types.Receipt, error) {
var tx *types.Transaction
var err error
sendTx := func() error {
if ctx.Err() != nil {
return nil
}
tx, err = p.sendProcessMessageCall(ctx, msgBody.Event, encodedSignalProof)
if err != nil {
return err
}
return nil
}
if err := backoff.Retry(sendTx, backoff.WithContext(
backoff.WithMaxRetries(
backoff.NewConstantBackOff(p.backOffRetryInterval),
p.backOffMaxRetries), ctx),
); err != nil {
return nil, err
}
relayer.MessageSentEventsProcessed.Inc()
ctx, cancel := context.WithTimeout(ctx, 4*time.Minute)
defer cancel()
receipt, err := relayer.WaitReceipt(ctx, p.destEthClient, tx.Hash())
if err != nil {
return nil, errors.Wrap(err, "relayer.WaitReceipt")
}
slog.Info("Mined tx", "txHash", hex.EncodeToString(tx.Hash().Bytes()))
if err := p.saveMessageStatusChangedEvent(ctx, receipt, msgBody.Event); err != nil {
return nil, errors.Wrap(err, "p.saveMEssageStatusChangedEvent")
}
return receipt, nil
}
// waitForInvocationDelay will return when the invocation delay has been met,
// if one exists, or return immediately if not.
func (p *Processor) waitForInvocationDelay(
ctx context.Context,
invocationDelays struct {
InvocationDelay *big.Int
InvocationExtraDelay *big.Int
},
proofReceipt struct {
ReceivedAt uint64
PreferredExecutor common.Address
},
) error {
invocationDelay := invocationDelays.InvocationDelay
preferredExecutor := proofReceipt.PreferredExecutor
if invocationDelay.Cmp(common.Big0) == 1 && preferredExecutor.Cmp(p.relayerAddr) != 0 {
invocationDelay = new(big.Int).Add(invocationDelay, invocationDelays.InvocationExtraDelay)
}
processableAt := new(big.Int).Add(new(big.Int).SetUint64(proofReceipt.ReceivedAt), invocationDelay)
// check invocation delays and make sure we can submit it
if time.Now().UTC().Unix() >= processableAt.Int64() {
// if its passed already, we can submit
return nil
}
// its unprocessable, we shouldnt send the transaction.
// wait until it's processable.
t := time.NewTicker(60 * time.Second)
defer t.Stop()
w := time.After(time.Duration(invocationDelay.Int64()) * time.Second)
for {
select {
case <-ctx.Done():
return nil
case <-t.C:
slog.Info("waiting for invocation delay",
"processableAt", processableAt.String(),
"now", time.Now().UTC().Unix(),
)
case <-w:
slog.Info("done waiting for invocation delay")
return nil
}
}
}
// generateEncodedSignalproof takes a MessageSent event and calls a
// proof generation service to generate a proof for the source call
// as well as any additional hops required.
func (p *Processor) generateEncodedSignalProof(ctx context.Context,
event *bridge.BridgeMessageSent) ([]byte, error) {
var encodedSignalProof []byte
var err error
var blockNum uint64 = event.Raw.BlockNumber
// wait for srcChain => destChain header to sync if no hops,
// or srcChain => hopChain => hopChain => hopChain => destChain if hops exist.
if len(p.hops) > 0 {
var hopEthClient ethClient = p.srcEthClient
var hopChainID *big.Int
for _, hop := range p.hops {
hop.blockNum = blockNum
event, err := p.waitHeaderSynced(ctx, hopEthClient, hop.chainID.Uint64(), blockNum)
if err != nil {
return nil, errors.Wrap(err, "p.waitHeaderSynced")
}
if err != nil {
return nil, errors.Wrap(err, "hop.headerSyncer.GetSyncedSnippet")
}
blockNum = event.SyncedInBlockID
hopEthClient = hop.ethClient
hopChainID = hop.chainID
}
event, err := p.waitHeaderSynced(ctx, hopEthClient, hopChainID.Uint64(), blockNum)
if err != nil {
return nil, errors.Wrap(err, "p.waitHeaderSynced")
}
blockNum = event.SyncedInBlockID
} else {
if _, err := p.waitHeaderSynced(ctx, p.srcEthClient, p.destChainId.Uint64(), event.Raw.BlockNumber); err != nil {
return nil, errors.Wrap(err, "p.waitHeaderSynced")
}
}
hops := []proof.HopParams{}
key, err := p.srcSignalService.GetSignalSlot(&bind.CallOpts{},
event.Message.SrcChainId,
event.Raw.Address,
event.MsgHash,
)
if err != nil {
return nil, errors.Wrap(err, "p.srcSignalService.GetSignalSlot")
}
// if we have no hops, this is strictly a srcChain => destChain message.
// we can grab the latestBlockID, create a singular "hop" of srcChain => destChain,
// and generate a proof.
if len(p.hops) == 0 {
latestBlockID, err := p.eventRepo.LatestChainDataSyncedEvent(
ctx,
p.destChainId.Uint64(),
p.srcChainId.Uint64(),
)
if err != nil {
return nil, errors.Wrap(err, "p.eventRepo.ChainDataSyncedEventByBlockNumberOrGreater")
}
hops = append(hops, proof.HopParams{
ChainID: p.destChainId,
SignalServiceAddress: p.srcSignalServiceAddress,
Blocker: p.srcEthClient,
Caller: p.srcCaller,
SignalService: p.srcSignalService,
Key: key,
BlockNumber: latestBlockID,
})
} else {
// otherwise, we should just create the first hop in the array, we will append
// the rest of the hops after.
hops = append(hops, proof.HopParams{
ChainID: p.destChainId,
SignalServiceAddress: p.srcSignalServiceAddress,
Blocker: p.srcEthClient,
Caller: p.srcCaller,
SignalService: p.srcSignalService,
Key: key,
BlockNumber: blockNum,
})
}
// if a hop is set, the proof service needs to generate an additional proof
// for the signal service intermediary chain in between the source chain
// and the destination chain.
for _, hop := range p.hops {
slog.Info(
"adding hop",
"hopChainId", hop.chainID.Uint64(),
"hopSignalServiceAddress", hop.signalServiceAddress.Hex(),
)
block, err := hop.ethClient.BlockByNumber(
ctx,
new(big.Int).SetUint64(blockNum),
)
if err != nil {
return nil, errors.Wrap(err, "p.blockHeader")
}
hopStorageSlotKey, err := hop.signalService.GetSignalSlot(&bind.CallOpts{},
hop.chainID.Uint64(),
hop.taikoAddress,
block.Root(),
)
if err != nil {
return nil, errors.Wrap(err, "hopSignalService.GetSignalSlot")
}
hops = append(hops, proof.HopParams{
ChainID: hop.chainID,
SignalServiceAddress: hop.signalServiceAddress,
Blocker: hop.ethClient,
Caller: hop.caller,
SignalService: hop.signalService,
Key: hopStorageSlotKey,
BlockNumber: blockNum,
})
}
encodedSignalProof, err = p.prover.EncodedSignalProofWithHops(
ctx,
hops,
)
if err != nil {
slog.Error("error encoding hop proof",
"srcChainID", event.Message.SrcChainId,
"destChainID", event.Message.DestChainId,
"txHash", event.Raw.TxHash.Hex(),
"msgHash", common.Hash(event.MsgHash).Hex(),
"from", event.Message.From.Hex(),
"srcOwner", event.Message.SrcOwner.Hex(),
"destOwner", event.Message.DestOwner.Hex(),
"error", err,
"hopsLength", len(hops),
)
return nil, errors.Wrap(err, "p.prover.GetEncodedSignalProof")
}
// check if message is received first. if not, it will definitely fail,
// so we can exit early on this one. there is most likely
// an issue with the signal generation.
received, err := p.destBridge.ProveMessageReceived(&bind.CallOpts{
Context: ctx,
}, event.Message, encodedSignalProof)
if err != nil {
return nil, errors.Wrap(err, "p.destBridge.ProveMessageReceived")
}
// message will fail when we try to process it
if !received {
slog.Warn("Message not received on dest chain",
"msgHash", common.Hash(event.MsgHash).Hex(),
"srcChainId", event.Message.SrcChainId,
)
relayer.MessagesNotReceivedOnDestChain.Inc()
return nil, errors.New("message not received")
}
return encodedSignalProof, nil
}
// sendProcessMessageCall calls `bridge.processMessage` with latest nonce
// after estimating gas, and checking profitability.
func (p *Processor) sendProcessMessageCall(
ctx context.Context,
event *bridge.BridgeMessageSent,
proof []byte,
) (*types.Transaction, error) {
auth, err := bind.NewKeyedTransactorWithChainID(p.ecdsaKey, new(big.Int).SetUint64(event.Message.DestChainId))
if err != nil {
return nil, errors.Wrap(err, "bind.NewKeyedTransactorWithChainID")
}
auth.Context = ctx
p.mu.Lock()
defer p.mu.Unlock()
err = p.getLatestNonce(ctx, auth)
if err != nil {
return nil, errors.New("p.getLatestNonce")
}
eventType, canonicalToken, _, err := relayer.DecodeMessageData(event.Message.Data, event.Message.Value)
if err != nil {
return nil, errors.Wrap(err, "relayer.DecodeMessageData")
}
var gas uint64
var cost *big.Int
needsContractDeployment, err := p.needsContractDeployment(ctx, event, eventType, canonicalToken)
if err != nil {
return nil, errors.Wrap(err, "p.needsContractDeployment")
}
if needsContractDeployment {
auth.GasLimit = 3000000
} else {
// otherwise we can estimate gas
gas, err = p.estimateGas(ctx, event.Message, proof)
// and if gas estimation failed, we just try to hardcore a value no matter what type of event,
// or whether the contract is deployed.
if err != nil || gas == 0 {
slog.Info("gas estimation failed, hardcoding gas limit", "p.estimateGas:", err)
err = p.hardcodeGasLimit(ctx, auth, event, eventType, canonicalToken)
if err != nil {
return nil, errors.Wrap(err, "p.hardcodeGasLimit")
}
} else {
auth.GasLimit = gas
}
}
if err = utils.SetGasTipOrPrice(ctx, auth, p.destEthClient); err != nil {
return nil, errors.Wrap(err, "p.setGasTipOrPrice")
}
cost, err = p.getCost(ctx, auth)
if err != nil {
return nil, errors.Wrap(err, "p.getCost")
}
if bool(p.profitableOnly) {
profitable, err := p.isProfitable(ctx, event.Message, cost)
if err != nil || !profitable {
return nil, relayer.ErrUnprofitable
}
}
// process the message on the destination bridge.
tx, err := p.destBridge.ProcessMessage(auth, event.Message, proof)
if err != nil {
return nil, errors.Wrap(err, "p.destBridge.ProcessMessage")
}
p.setLatestNonce(tx.Nonce())
return tx, nil
}
// needsContractDeployment is needed because
// node is unable to estimate gas correctly for contract deployments,
// so we need to check if the token
// is deployed, and always hardcode in this case. we need to check this before calling
// estimategas, as the node will soemtimes return a gas estimate for a contract deployment, however,
// it is incorrect and the tx will revert.
func (p *Processor) needsContractDeployment(
ctx context.Context,
event *bridge.BridgeMessageSent,
eventType relayer.EventType,
canonicalToken relayer.CanonicalToken,
) (bool, error) {
if eventType == relayer.EventTypeSendETH {
return false, nil
}
var bridgedAddress common.Address
var err error
chainID := new(big.Int).SetUint64(canonicalToken.ChainID())
addr := canonicalToken.Address()
ctx, cancel := context.WithTimeout(ctx, p.ethClientTimeout)
defer cancel()
opts := &bind.CallOpts{
Context: ctx,
}
destChainID := new(big.Int).SetUint64(event.Message.DestChainId)
if eventType == relayer.EventTypeSendERC20 && destChainID.Cmp(chainID) != 0 {
// determine whether the canonical token is bridged or not on this chain
bridgedAddress, err = p.destERC20Vault.CanonicalToBridged(opts, chainID, addr)
}
if eventType == relayer.EventTypeSendERC721 && destChainID.Cmp(chainID) != 0 {
// determine whether the canonical token is bridged or not on this chain
bridgedAddress, err = p.destERC721Vault.CanonicalToBridged(opts, chainID, addr)
}
if eventType == relayer.EventTypeSendERC1155 && destChainID.Cmp(chainID) != 0 {
// determine whether the canonical token is bridged or not on this chain
bridgedAddress, err = p.destERC1155Vault.CanonicalToBridged(opts, chainID, addr)
}
if err != nil {
return false, err
}
return bridgedAddress == relayer.ZeroAddress, nil
}
// hardcodeGasLimit determines a viable gas limit when we can get
// unable to estimate gas for contract deployments within the contract code.
// if we get an error or the gas is 0, lets manual set high gas limit and ignore error,
// and try to actually send.
// if contract has not been deployed, we need much higher gas limit, otherwise, we can
// send lower.
func (p *Processor) hardcodeGasLimit(
ctx context.Context,
auth *bind.TransactOpts,
event *bridge.BridgeMessageSent,
eventType relayer.EventType,
canonicalToken relayer.CanonicalToken,
) error {
var bridgedAddress common.Address
var err error
switch eventType {
case relayer.EventTypeSendETH:
// eth bridges take much less gas, from 250k to 450k.
auth.GasLimit = 500000
case relayer.EventTypeSendERC20:
// determine whether the canonical token is bridged or not on this chain
bridgedAddress, err = p.destERC20Vault.CanonicalToBridged(
nil,
new(big.Int).SetUint64(canonicalToken.ChainID()),
canonicalToken.Address(),
)
if err != nil {
return errors.Wrap(err, "p.destERC20Vault.CanonicalToBridged")
}
case relayer.EventTypeSendERC721:
// determine whether the canonical token is bridged or not on this chain
bridgedAddress, err = p.destERC721Vault.CanonicalToBridged(
nil,
new(big.Int).SetUint64(canonicalToken.ChainID()),
canonicalToken.Address(),
)
if err != nil {
return errors.Wrap(err, "p.destERC721Vault.CanonicalToBridged")
}
case relayer.EventTypeSendERC1155:
// determine whether the canonical token is bridged or not on this chain
bridgedAddress, err = p.destERC1155Vault.CanonicalToBridged(
nil,
new(big.Int).SetUint64(canonicalToken.ChainID()),
canonicalToken.Address(),
)
if err != nil {
return errors.Wrap(err, "p.destERC1155Vault.CanonicalToBridged")
}
default:
return errors.New("unexpected event type")
}
if bridgedAddress == relayer.ZeroAddress {
// needs large gas limit because it has to deploy an ERC20 contract on destination
// chain. deploying ERC20 can be 2 mil by itself.
auth.GasLimit = 3000000
} else {
// needs larger than ETH gas limit but not as much as deploying ERC20.
// takes 450-550k gas after signalRoot refactors.
auth.GasLimit = 600000
}
return nil
}
// setLatestNonce sets the latest nonce used for the relayer key
func (p *Processor) setLatestNonce(nonce uint64) {
p.destNonce = nonce
}
// saveMessageStatusChangedEvent writes the MessageStatusChanged event to the
// database after a message is processed
func (p *Processor) saveMessageStatusChangedEvent(
ctx context.Context,
receipt *types.Receipt,
event *bridge.BridgeMessageSent,
) error {
bridgeAbi, err := abi.JSON(strings.NewReader(bridge.BridgeABI))
if err != nil {
return errors.Wrap(err, "abi.JSON")
}
m := make(map[string]interface{})
for _, log := range receipt.Logs {
topic := log.Topics[0]
if topic == bridgeAbi.Events["MessageStatusChanged"].ID {
err = bridgeAbi.UnpackIntoMap(m, "MessageStatusChanged", log.Data)
if err != nil {
return errors.Wrap(err, "abi.UnpackIntoInterface")
}
break
}
}
if m["status"] != nil {
// keep same format as other raw events
data := fmt.Sprintf(`{"Raw":{"transactionHash": "%v"}}`, receipt.TxHash.Hex())
_, err = p.eventRepo.Save(ctx, relayer.SaveEventOpts{
Name: relayer.EventNameMessageStatusChanged,
Data: data,
EmittedBlockID: event.Raw.BlockNumber,
ChainID: new(big.Int).SetUint64(event.Message.SrcChainId),
DestChainID: new(big.Int).SetUint64(event.Message.DestChainId),
Status: relayer.EventStatus(m["status"].(uint8)),
MsgHash: common.Hash(event.MsgHash).Hex(),
MessageOwner: event.Message.SrcOwner.Hex(),
Event: relayer.EventNameMessageStatusChanged,
})
if err != nil {
return errors.Wrap(err, "svc.eventRepo.Save")
}
}
return nil
}
// getCost determines the fee of a processMessage call
func (p *Processor) getCost(ctx context.Context, auth *bind.TransactOpts) (*big.Int, error) {
if auth.GasTipCap != nil {
blk, err := p.destEthClient.BlockByNumber(ctx, nil)
if err != nil {
return nil, err
}
var baseFee *big.Int
if p.taikoL2 != nil {
gasUsed := uint32(blk.GasUsed())
timeSince := uint64(time.Since(time.Unix(int64(blk.Time()), 0)))
baseFee, err = p.taikoL2.GetBasefee(&bind.CallOpts{Context: ctx}, timeSince, gasUsed)
if err != nil {
return nil, errors.Wrap(err, "p.taikoL2.GetBasefee")
}
} else {
cfg := params.NetworkIDToChainConfigOrDefault(p.destChainId)
baseFee = eip1559.CalcBaseFee(cfg, blk.Header())
}
return new(big.Int).Mul(
new(big.Int).SetUint64(auth.GasLimit),
new(big.Int).Add(auth.GasTipCap, baseFee)), nil
} else {
return new(big.Int).Mul(auth.GasPrice, new(big.Int).SetUint64(auth.GasLimit)), nil
}
}