forked from ethereum-optimism/optimism
-
Notifications
You must be signed in to change notification settings - Fork 0
/
cross-chain-messenger.ts
2801 lines (2596 loc) · 94 KB
/
cross-chain-messenger.ts
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
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* eslint-disable @typescript-eslint/no-unused-vars */
import {
Provider,
BlockTag,
TransactionReceipt,
TransactionResponse,
TransactionRequest,
} from '@ethersproject/abstract-provider'
import { Signer } from '@ethersproject/abstract-signer'
import {
ethers,
BigNumber,
Overrides,
CallOverrides,
PayableOverrides,
} from 'ethers'
import {
sleep,
remove0x,
toHexString,
toRpcHexString,
encodeCrossDomainMessageV0,
encodeCrossDomainMessageV1,
BedrockOutputData,
BedrockCrossChainMessageProof,
decodeVersionedNonce,
encodeVersionedNonce,
getChainId,
hashCrossDomainMessagev0,
hashCrossDomainMessagev1,
} from '@eth-optimism/core-utils'
import { getContractInterface, predeploys } from '@eth-optimism/contracts'
import * as rlp from 'rlp'
import semver from 'semver'
import {
OEContracts,
OEContractsLike,
MessageLike,
MessageRequestLike,
TransactionLike,
AddressLike,
NumberLike,
SignerOrProviderLike,
CrossChainMessage,
CrossChainMessageRequest,
CrossChainMessageProof,
MessageDirection,
MessageStatus,
TokenBridgeMessage,
MessageReceipt,
MessageReceiptStatus,
BridgeAdapterData,
BridgeAdapters,
StateRoot,
StateRootBatch,
IBridgeAdapter,
ProvenWithdrawal,
LowLevelMessage,
FPACProvenWithdrawal,
} from './interfaces'
import {
toSignerOrProvider,
toNumber,
toTransactionHash,
DeepPartial,
getAllOEContracts,
getBridgeAdapters,
makeMerkleTreeProof,
makeStateTrieProof,
hashLowLevelMessage,
migratedWithdrawalGasLimit,
DEPOSIT_CONFIRMATION_BLOCKS,
CHAIN_BLOCK_TIMES,
hashMessageHash,
getContractInterfaceBedrock,
toJsonRpcProvider,
} from './utils'
export class CrossChainMessenger {
/**
* Provider connected to the L1 chain.
*/
public l1SignerOrProvider: Signer | Provider
/**
* Provider connected to the L2 chain.
*/
public l2SignerOrProvider: Signer | Provider
/**
* Chain ID for the L1 network.
*/
public l1ChainId: number
/**
* Chain ID for the L2 network.
*/
public l2ChainId: number
/**
* Contract objects attached to their respective providers and addresses.
*/
public contracts: OEContracts
/**
* List of custom bridges for the given network.
*/
public bridges: BridgeAdapters
/**
* Number of blocks before a deposit is considered confirmed.
*/
public depositConfirmationBlocks: number
/**
* Estimated average L1 block time in seconds.
*/
public l1BlockTimeSeconds: number
/**
* Whether or not Bedrock compatibility is enabled.
*/
public bedrock: boolean
/**
* Cache for output root validation. Output roots are expensive to verify, so we cache them.
*/
private _outputCache: Array<{ root: string; valid: boolean }> = []
/**
* Creates a new CrossChainProvider instance.
*
* @param opts Options for the provider.
* @param opts.l1SignerOrProvider Signer or Provider for the L1 chain, or a JSON-RPC url.
* @param opts.l2SignerOrProvider Signer or Provider for the L2 chain, or a JSON-RPC url.
* @param opts.l1ChainId Chain ID for the L1 chain.
* @param opts.l2ChainId Chain ID for the L2 chain.
* @param opts.depositConfirmationBlocks Optional number of blocks before a deposit is confirmed.
* @param opts.l1BlockTimeSeconds Optional estimated block time in seconds for the L1 chain.
* @param opts.contracts Optional contract address overrides.
* @param opts.bridges Optional bridge address list.
* @param opts.bedrock Whether or not to enable Bedrock compatibility.
*/
constructor(opts: {
l1SignerOrProvider: SignerOrProviderLike
l2SignerOrProvider: SignerOrProviderLike
l1ChainId: NumberLike
l2ChainId: NumberLike
depositConfirmationBlocks?: NumberLike
l1BlockTimeSeconds?: NumberLike
contracts?: DeepPartial<OEContractsLike>
bridges?: BridgeAdapterData
bedrock?: boolean
}) {
this.bedrock = opts.bedrock ?? true
this.l1SignerOrProvider = toSignerOrProvider(opts.l1SignerOrProvider)
this.l2SignerOrProvider = toSignerOrProvider(opts.l2SignerOrProvider)
try {
this.l1ChainId = toNumber(opts.l1ChainId)
} catch (err) {
throw new Error(`L1 chain ID is missing or invalid: ${opts.l1ChainId}`)
}
try {
this.l2ChainId = toNumber(opts.l2ChainId)
} catch (err) {
throw new Error(`L2 chain ID is missing or invalid: ${opts.l2ChainId}`)
}
this.depositConfirmationBlocks =
opts?.depositConfirmationBlocks !== undefined
? toNumber(opts.depositConfirmationBlocks)
: DEPOSIT_CONFIRMATION_BLOCKS[this.l2ChainId] || 0
this.l1BlockTimeSeconds =
opts?.l1BlockTimeSeconds !== undefined
? toNumber(opts.l1BlockTimeSeconds)
: CHAIN_BLOCK_TIMES[this.l1ChainId] || 1
this.contracts = getAllOEContracts(this.l2ChainId, {
l1SignerOrProvider: this.l1SignerOrProvider,
l2SignerOrProvider: this.l2SignerOrProvider,
overrides: opts.contracts,
})
this.bridges = getBridgeAdapters(this.l2ChainId, this, {
overrides: opts.bridges,
contracts: opts.contracts,
})
}
/**
* Provider connected to the L1 chain.
*/
get l1Provider(): Provider {
if (Provider.isProvider(this.l1SignerOrProvider)) {
return this.l1SignerOrProvider
} else {
return this.l1SignerOrProvider.provider
}
}
/**
* Provider connected to the L2 chain.
*/
get l2Provider(): Provider {
if (Provider.isProvider(this.l2SignerOrProvider)) {
return this.l2SignerOrProvider
} else {
return this.l2SignerOrProvider.provider
}
}
/**
* Signer connected to the L1 chain.
*/
get l1Signer(): Signer {
if (Provider.isProvider(this.l1SignerOrProvider)) {
throw new Error(`messenger has no L1 signer`)
} else {
return this.l1SignerOrProvider
}
}
/**
* Signer connected to the L2 chain.
*/
get l2Signer(): Signer {
if (Provider.isProvider(this.l2SignerOrProvider)) {
throw new Error(`messenger has no L2 signer`)
} else {
return this.l2SignerOrProvider
}
}
/**
* Uses portal version to determine if the messenger is using fpac contracts. Better not to cache
* this value as it will change during the fpac upgrade and we want clients to automatically
* begin using the new logic without throwing any errors.
*
* @returns Whether or not the messenger is using fpac contracts.
*/
public async fpac(): Promise<boolean> {
if (
this.contracts.l1.OptimismPortal.address === ethers.constants.AddressZero
) {
// Only really relevant for certain SDK tests where the portal is not deployed. We should
// probably just update the tests so the portal gets deployed but feels like it's out of
// scope for the FPAC changes.
return false
} else {
return semver.gte(
await this.contracts.l1.OptimismPortal.version(),
'3.0.0'
)
}
}
/**
* Retrieves all cross chain messages sent within a given transaction.
*
* @param transaction Transaction hash or receipt to find messages from.
* @param opts Options object.
* @param opts.direction Direction to search for messages in. If not provided, will attempt to
* automatically search both directions under the assumption that a transaction hash will only
* exist on one chain. If the hash exists on both chains, will throw an error.
* @returns All cross chain messages sent within the transaction.
*/
public async getMessagesByTransaction(
transaction: TransactionLike,
opts: {
direction?: MessageDirection
} = {}
): Promise<CrossChainMessage[]> {
// Wait for the transaction receipt if the input is waitable.
await (transaction as TransactionResponse).wait?.()
// Convert the input to a transaction hash.
const txHash = toTransactionHash(transaction)
let receipt: TransactionReceipt
if (opts.direction !== undefined) {
// Get the receipt for the requested direction.
if (opts.direction === MessageDirection.L1_TO_L2) {
receipt = await this.l1Provider.getTransactionReceipt(txHash)
} else {
receipt = await this.l2Provider.getTransactionReceipt(txHash)
}
} else {
// Try both directions, starting with L1 => L2.
receipt = await this.l1Provider.getTransactionReceipt(txHash)
if (receipt) {
opts.direction = MessageDirection.L1_TO_L2
} else {
receipt = await this.l2Provider.getTransactionReceipt(txHash)
opts.direction = MessageDirection.L2_TO_L1
}
}
if (!receipt) {
throw new Error(`unable to find transaction receipt for ${txHash}`)
}
// By this point opts.direction will always be defined.
const messenger =
opts.direction === MessageDirection.L1_TO_L2
? this.contracts.l1.L1CrossDomainMessenger
: this.contracts.l2.L2CrossDomainMessenger
return receipt.logs
.filter((log) => {
// Only look at logs emitted by the messenger address
return log.address === messenger.address
})
.filter((log) => {
// Only look at SentMessage logs specifically
const parsed = messenger.interface.parseLog(log)
return parsed.name === 'SentMessage'
})
.map((log) => {
// Try to pull out the value field, but only if the very next log is a SentMessageExtension1
// event which was introduced in the Bedrock upgrade.
let value = ethers.BigNumber.from(0)
const next = receipt.logs.find((l) => {
return (
l.logIndex === log.logIndex + 1 && l.address === messenger.address
)
})
if (next) {
const nextParsed = messenger.interface.parseLog(next)
if (nextParsed.name === 'SentMessageExtension1') {
value = nextParsed.args.value
}
}
// Convert each SentMessage log into a message object
const parsed = messenger.interface.parseLog(log)
return {
direction: opts.direction,
target: parsed.args.target,
sender: parsed.args.sender,
message: parsed.args.message,
messageNonce: parsed.args.messageNonce,
value,
minGasLimit: parsed.args.gasLimit,
logIndex: log.logIndex,
blockNumber: log.blockNumber,
transactionHash: log.transactionHash,
}
})
}
/**
* Transforms a legacy message into its corresponding Bedrock representation.
*
* @param message Legacy message to transform.
* @param messageIndex The index of the message, if multiple exist from multicall
* @returns Bedrock representation of the message.
*/
public async toBedrockCrossChainMessage(
message: MessageLike,
messageIndex = 0
): Promise<CrossChainMessage> {
const resolved = await this.toCrossChainMessage(message, messageIndex)
// Bedrock messages are already in the correct format.
const { version } = decodeVersionedNonce(resolved.messageNonce)
if (version.eq(1)) {
return resolved
}
let value = BigNumber.from(0)
if (
resolved.direction === MessageDirection.L2_TO_L1 &&
resolved.sender === this.contracts.l2.L2StandardBridge.address &&
resolved.target === this.contracts.l1.L1StandardBridge.address
) {
try {
;[, , value] =
this.contracts.l1.L1StandardBridge.interface.decodeFunctionData(
'finalizeETHWithdrawal',
resolved.message
)
} catch (err) {
// No problem, not a message with value.
}
}
return {
...resolved,
value,
minGasLimit: BigNumber.from(0),
messageNonce: encodeVersionedNonce(
BigNumber.from(0),
resolved.messageNonce
),
}
}
/**
* Transforms a CrossChainMessenger message into its low-level representation inside the
* L2ToL1MessagePasser contract on L2.
*
* @param message Message to transform.
* @param messageIndex The index of the message, if multiple exist from multicall
* @return Transformed message.
*/
public async toLowLevelMessage(
message: MessageLike,
messageIndex = 0
): Promise<LowLevelMessage> {
const resolved = await this.toCrossChainMessage(message, messageIndex)
if (resolved.direction === MessageDirection.L1_TO_L2) {
throw new Error(`can only convert L2 to L1 messages to low level`)
}
// We may have to update the message if it's a legacy message.
const { version } = decodeVersionedNonce(resolved.messageNonce)
let updated: CrossChainMessage
if (version.eq(0)) {
updated = await this.toBedrockCrossChainMessage(resolved, messageIndex)
} else {
updated = resolved
}
// Encode the updated message, we need this for legacy messages.
const encoded = encodeCrossDomainMessageV1(
updated.messageNonce,
updated.sender,
updated.target,
updated.value,
updated.minGasLimit,
updated.message
)
// EVERYTHING following here is basically repeating the logic from getMessagesByTransaction
// consider cleaning this up
// We need to figure out the final withdrawal data that was used to compute the withdrawal hash
// inside the L2ToL1Message passer contract. Exact mechanism here depends on whether or not
// this is a legacy message or a new Bedrock message.
let gasLimit: BigNumber
let messageNonce: BigNumber
if (version.eq(0)) {
const chainID = await getChainId(this.l2Provider)
gasLimit = migratedWithdrawalGasLimit(encoded, chainID)
messageNonce = resolved.messageNonce
} else {
const receipt = await this.l2Provider.getTransactionReceipt(
(
await this.toCrossChainMessage(message)
).transactionHash
)
const withdrawals: ethers.utils.Result[] = []
for (const log of receipt.logs) {
if (log.address === this.contracts.l2.BedrockMessagePasser.address) {
const decoded =
this.contracts.l2.L2ToL1MessagePasser.interface.parseLog(log)
if (decoded.name === 'MessagePassed') {
withdrawals.push(decoded.args)
}
}
}
// Should not happen.
if (withdrawals.length === 0) {
throw new Error(`no withdrawals found in receipt`)
}
const withdrawal = withdrawals[messageIndex]
if (!withdrawal) {
throw new Error(
`withdrawal index ${messageIndex} out of bounds there are ${withdrawals.length} withdrawals`
)
}
messageNonce = withdrawal.nonce
gasLimit = withdrawal.gasLimit
}
return {
messageNonce,
sender: this.contracts.l2.L2CrossDomainMessenger.address,
target: this.contracts.l1.L1CrossDomainMessenger.address,
value: updated.value,
minGasLimit: gasLimit,
message: encoded,
}
}
// public async getMessagesByAddress(
// address: AddressLike,
// opts?: {
// direction?: MessageDirection
// fromBlock?: NumberLike
// toBlock?: NumberLike
// }
// ): Promise<CrossChainMessage[]> {
// throw new Error(`
// The function getMessagesByAddress is currently not enabled because the sender parameter of
// the SentMessage event is not indexed within the CrossChainMessenger contracts.
// getMessagesByAddress will be enabled by plugging in an Optimism Indexer (coming soon).
// See the following issue on GitHub for additional context:
// https://github.com/ethereum-optimism/optimism/issues/2129
// `)
// }
/**
* Finds the appropriate bridge adapter for a given L1<>L2 token pair. Will throw if no bridges
* support the token pair or if more than one bridge supports the token pair.
*
* @param l1Token L1 token address.
* @param l2Token L2 token address.
* @returns The appropriate bridge adapter for the given token pair.
*/
public async getBridgeForTokenPair(
l1Token: AddressLike,
l2Token: AddressLike
): Promise<IBridgeAdapter> {
const bridges: IBridgeAdapter[] = []
for (const bridge of Object.values(this.bridges)) {
try {
if (await bridge.supportsTokenPair(l1Token, l2Token)) {
bridges.push(bridge)
}
} catch (err) {
if (
!err?.message?.toString().includes('CALL_EXCEPTION') &&
!err?.stack?.toString().includes('execution reverted')
) {
console.error('Unexpected error when checking bridge', err)
}
}
}
if (bridges.length === 0) {
throw new Error(`no supported bridge for token pair`)
}
if (bridges.length > 1) {
throw new Error(`found more than one bridge for token pair`)
}
return bridges[0]
}
/**
* Gets all deposits for a given address.
*
* @param address Address to search for messages from.
* @param opts Options object.
* @param opts.fromBlock Block to start searching for messages from. If not provided, will start
* from the first block (block #0).
* @param opts.toBlock Block to stop searching for messages at. If not provided, will stop at the
* latest known block ("latest").
* @returns All deposit token bridge messages sent by the given address.
*/
public async getDepositsByAddress(
address: AddressLike,
opts: {
fromBlock?: BlockTag
toBlock?: BlockTag
} = {}
): Promise<TokenBridgeMessage[]> {
return (
await Promise.all(
Object.values(this.bridges).map(async (bridge) => {
return bridge.getDepositsByAddress(address, opts)
})
)
)
.reduce((acc, val) => {
return acc.concat(val)
}, [])
.sort((a, b) => {
// Sort descending by block number
return b.blockNumber - a.blockNumber
})
}
/**
* Gets all withdrawals for a given address.
*
* @param address Address to search for messages from.
* @param opts Options object.
* @param opts.fromBlock Block to start searching for messages from. If not provided, will start
* from the first block (block #0).
* @param opts.toBlock Block to stop searching for messages at. If not provided, will stop at the
* latest known block ("latest").
* @returns All withdrawal token bridge messages sent by the given address.
*/
public async getWithdrawalsByAddress(
address: AddressLike,
opts: {
fromBlock?: BlockTag
toBlock?: BlockTag
} = {}
): Promise<TokenBridgeMessage[]> {
return (
await Promise.all(
Object.values(this.bridges).map(async (bridge) => {
return bridge.getWithdrawalsByAddress(address, opts)
})
)
)
.reduce((acc, val) => {
return acc.concat(val)
}, [])
.sort((a, b) => {
// Sort descending by block number
return b.blockNumber - a.blockNumber
})
}
/**
* Resolves a MessageLike into a CrossChainMessage object.
* Unlike other coercion functions, this function is stateful and requires making additional
* requests. For now I'm going to keep this function here, but we could consider putting a
* similar function inside of utils/coercion.ts if people want to use this without having to
* create an entire CrossChainProvider object.
*
* @param message MessageLike to resolve into a CrossChainMessage.
* @param messageIndex The index of the message, if multiple exist from multicall
* @returns Message coerced into a CrossChainMessage.
*/
public async toCrossChainMessage(
message: MessageLike,
messageIndex = 0
): Promise<CrossChainMessage> {
if (!message) {
throw new Error('message is undefined')
}
// TODO: Convert these checks into proper type checks.
if ((message as CrossChainMessage).message) {
return message as CrossChainMessage
} else if (
(message as TokenBridgeMessage).l1Token &&
(message as TokenBridgeMessage).l2Token &&
(message as TokenBridgeMessage).transactionHash
) {
const messages = await this.getMessagesByTransaction(
(message as TokenBridgeMessage).transactionHash
)
// The `messages` object corresponds to a list of SentMessage events that were triggered by
// the same transaction. We want to find the specific SentMessage event that corresponds to
// the TokenBridgeMessage (either a ETHDepositInitiated, ERC20DepositInitiated, or
// WithdrawalInitiated event). We expect the behavior of bridge contracts to be that these
// TokenBridgeMessage events are triggered and then a SentMessage event is triggered. Our
// goal here is therefore to find the first SentMessage event that comes after the input
// event.
const found = messages
.sort((a, b) => {
// Sort all messages in ascending order by log index.
return a.logIndex - b.logIndex
})
.find((m) => {
return m.logIndex > (message as TokenBridgeMessage).logIndex
})
if (!found) {
throw new Error(`could not find SentMessage event for message`)
}
return found
} else {
// TODO: Explicit TransactionLike check and throw if not TransactionLike
const messages = await this.getMessagesByTransaction(
message as TransactionLike
)
const out = messages[messageIndex]
if (!out) {
throw new Error(
`withdrawal index ${messageIndex} out of bounds. There are ${messages.length} withdrawals`
)
}
return out
}
}
/**
* Retrieves the status of a particular message as an enum.
*
* @param message Cross chain message to check the status of.
* @param messageIndex The index of the message, if multiple exist from multicall
* @param fromBlockOrBlockHash The start block to use for the query filter on the RECEIVING chain
* @param toBlockOrBlockHash The end block to use for the query filter on the RECEIVING chain
* @returns Status of the message.
*/
public async getMessageStatus(
message: MessageLike,
// consider making this an options object next breaking release
messageIndex = 0,
/**
* @deprecated no longer used since no log filters are used
*/
fromBlockOrBlockHash?: BlockTag,
/**
* @deprecated no longer used since no log filters are used
*/
toBlockOrBlockHash?: BlockTag
): Promise<MessageStatus> {
const resolved = await this.toCrossChainMessage(message, messageIndex)
// legacy withdrawals relayed prebedrock are v1
const messageHashV0 = hashCrossDomainMessagev0(
resolved.target,
resolved.sender,
resolved.message,
resolved.messageNonce
)
// bedrock withdrawals are v1
// legacy withdrawals relayed postbedrock are v1
// there is no good way to differentiate between the two types of legacy
// so what we will check for both
const messageHashV1 = hashCrossDomainMessagev1(
resolved.messageNonce,
resolved.sender,
resolved.target,
resolved.value,
resolved.minGasLimit,
resolved.message
)
// Here we want the messenger that will receive the message, not the one that sent it.
const messenger =
resolved.direction === MessageDirection.L1_TO_L2
? this.contracts.l2.L2CrossDomainMessenger
: this.contracts.l1.L1CrossDomainMessenger
const success =
(await messenger.successfulMessages(messageHashV0)) ||
(await messenger.successfulMessages(messageHashV1))
// Avoid the extra query if we already know the message was successful.
if (success) {
return MessageStatus.RELAYED
}
const failure =
(await messenger.failedMessages(messageHashV0)) ||
(await messenger.failedMessages(messageHashV1))
if (resolved.direction === MessageDirection.L1_TO_L2) {
if (failure) {
return MessageStatus.FAILED_L1_TO_L2_MESSAGE
} else {
return MessageStatus.UNCONFIRMED_L1_TO_L2_MESSAGE
}
} else {
if (failure) {
return MessageStatus.READY_FOR_RELAY
} else {
let timestamp: number
if (this.bedrock) {
const output = await this.getMessageBedrockOutput(
resolved,
messageIndex
)
if (output === null) {
return MessageStatus.STATE_ROOT_NOT_PUBLISHED
}
// Convert the message to the low level message that was proven.
const withdrawal = await this.toLowLevelMessage(
resolved,
messageIndex
)
// Attempt to fetch the proven withdrawal.
const provenWithdrawal = await this.getProvenWithdrawal(
hashLowLevelMessage(withdrawal)
)
// If the withdrawal hash has not been proven on L1, return READY_TO_PROVE.
// Note that this will also apply in the case that a withdrawal has been proven but the
// proposal used to create the proof was invalidated. This is fine because in that case
// the withdrawal needs to be proven again anyway.
if (provenWithdrawal === null) {
return MessageStatus.READY_TO_PROVE
}
// Set the timestamp to the provenWithdrawal's timestamp
timestamp = provenWithdrawal.timestamp.toNumber()
} else {
const stateRoot = await this.getMessageStateRoot(
resolved,
messageIndex
)
if (stateRoot === null) {
return MessageStatus.STATE_ROOT_NOT_PUBLISHED
}
const bn = stateRoot.batch.blockNumber
const block = await this.l1Provider.getBlock(bn)
timestamp = block.timestamp
}
if (await this.fpac()) {
// Convert the message to the low level message that was proven.
const withdrawal = await this.toLowLevelMessage(
resolved,
messageIndex
)
// Get the withdrawal hash.
const withdrawalHash = hashLowLevelMessage(withdrawal)
// Grab the proven withdrawal data.
const provenWithdrawal = await this.getProvenWithdrawal(
withdrawalHash
)
// Sanity check, should've already happened above but do it just in case.
if (provenWithdrawal === null) {
// Ready to prove is the correct status here, we would not expect to hit this code path
// unless there was an unexpected reorg on L1. Since this is unlikely we log a warning.
console.warn(
'Unexpected code path reached in getMessageStatus, returning READY_TO_PROVE'
)
return MessageStatus.READY_TO_PROVE
}
// Shouldn't happen, but worth checking just in case.
if (!('proofSubmitter' in provenWithdrawal)) {
throw new Error(
`expected to get FPAC withdrawal but got legacy withdrawal`
)
}
try {
// If this doesn't revert then we should be fine to relay.
await this.contracts.l1.OptimismPortal2.checkWithdrawal(
hashLowLevelMessage(withdrawal),
provenWithdrawal.proofSubmitter
)
return MessageStatus.READY_FOR_RELAY
} catch (err) {
return MessageStatus.IN_CHALLENGE_PERIOD
}
} else {
const challengePeriod = await this.getChallengePeriodSeconds()
const latestBlock = await this.l1Provider.getBlock('latest')
if (timestamp + challengePeriod > latestBlock.timestamp) {
return MessageStatus.IN_CHALLENGE_PERIOD
} else {
return MessageStatus.READY_FOR_RELAY
}
}
}
}
}
/**
* Finds the receipt of the transaction that executed a particular cross chain message.
*
* @param message Message to find the receipt of.
* @param messageIndex The index of the message, if multiple exist from multicall
* @param fromBlockOrBlockHash The start block to use for the query filter on the RECEIVING chain
* @param toBlockOrBlockHash The end block to use for the query filter on the RECEIVING chain
* @returns CrossChainMessage receipt including receipt of the transaction that relayed the
* given message.
*/
public async getMessageReceipt(
message: MessageLike,
messageIndex = 0,
fromBlockOrBlockHash?: BlockTag,
toBlockOrHash?: BlockTag
): Promise<MessageReceipt> {
const resolved = await this.toCrossChainMessage(message, messageIndex)
// legacy withdrawals relayed prebedrock are v1
const messageHashV0 = hashCrossDomainMessagev0(
resolved.target,
resolved.sender,
resolved.message,
resolved.messageNonce
)
// bedrock withdrawals are v1
// legacy withdrawals relayed postbedrock are v1
// there is no good way to differentiate between the two types of legacy
// so what we will check for both
const messageHashV1 = hashCrossDomainMessagev1(
resolved.messageNonce,
resolved.sender,
resolved.target,
resolved.value,
resolved.minGasLimit,
resolved.message
)
// Here we want the messenger that will receive the message, not the one that sent it.
const messenger =
resolved.direction === MessageDirection.L1_TO_L2
? this.contracts.l2.L2CrossDomainMessenger
: this.contracts.l1.L1CrossDomainMessenger
// this is safe because we can guarantee only one of these filters max will return something
const relayedMessageEvents = [
...(await messenger.queryFilter(
messenger.filters.RelayedMessage(messageHashV0),
fromBlockOrBlockHash,
toBlockOrHash
)),
...(await messenger.queryFilter(
messenger.filters.RelayedMessage(messageHashV1),
fromBlockOrBlockHash,
toBlockOrHash
)),
]
// Great, we found the message. Convert it into a transaction receipt.
if (relayedMessageEvents.length === 1) {
return {
receiptStatus: MessageReceiptStatus.RELAYED_SUCCEEDED,
transactionReceipt:
await relayedMessageEvents[0].getTransactionReceipt(),
}
} else if (relayedMessageEvents.length > 1) {
// Should never happen!
throw new Error(`multiple successful relays for message`)
}
// We didn't find a transaction that relayed the message. We now attempt to find
// FailedRelayedMessage events instead.
const failedRelayedMessageEvents = [
...(await messenger.queryFilter(
messenger.filters.FailedRelayedMessage(messageHashV0),
fromBlockOrBlockHash,
toBlockOrHash
)),
...(await messenger.queryFilter(
messenger.filters.FailedRelayedMessage(messageHashV1),
fromBlockOrBlockHash,
toBlockOrHash
)),
]
// A transaction can fail to be relayed multiple times. We'll always return the last
// transaction that attempted to relay the message.
// TODO: Is this the best way to handle this?
if (failedRelayedMessageEvents.length > 0) {
return {
receiptStatus: MessageReceiptStatus.RELAYED_FAILED,
transactionReceipt: await failedRelayedMessageEvents[
failedRelayedMessageEvents.length - 1
].getTransactionReceipt(),
}
}
// TODO: If the user doesn't provide enough gas then there's a chance that FailedRelayedMessage
// will never be triggered. We should probably fix this at the contract level by requiring a
// minimum amount of input gas and designing the contracts such that the gas will always be
// enough to trigger the event. However, for now we need a temporary way to find L1 => L2
// transactions that fail but don't alert us because they didn't provide enough gas.
// TODO: Talk with the systems and protocol team about coordinating a hard fork that fixes this
// on both L1 and L2.
// Just return null if we didn't find a receipt. Slightly nicer than throwing an error.
return null
}
/**
* Waits for a message to be executed and returns the receipt of the transaction that executed
* the given message.
*
* @param message Message to wait for.
* @param opts Options to pass to the waiting function.
* @param opts.confirmations Number of transaction confirmations to wait for before returning.
* @param opts.pollIntervalMs Number of milliseconds to wait between polling for the receipt.
* @param opts.timeoutMs Milliseconds to wait before timing out.
* @param opts.fromBlockOrBlockHash The start block to use for the query filter on the RECEIVING chain
* @param opts.toBlockOrBlockHash The end block to use for the query filter on the RECEIVING chain
* @param messageIndex The index of the message, if multiple exist from multicall
* @returns CrossChainMessage receipt including receipt of the transaction that relayed the
* given message.
*/
public async waitForMessageReceipt(
message: MessageLike,
opts: {
fromBlockOrBlockHash?: BlockTag
toBlockOrHash?: BlockTag
confirmations?: number
pollIntervalMs?: number
timeoutMs?: number
} = {},
/**
* The index of the withdrawal if multiple are made with multicall
*/
messageIndex = 0
): Promise<MessageReceipt> {
// Resolving once up-front is slightly more efficient.
const resolved = await this.toCrossChainMessage(message, messageIndex)
let totalTimeMs = 0
while (totalTimeMs < (opts.timeoutMs || Infinity)) {