cross-chain-messenger.spec.ts 53.5 KB
Newer Older
1
import { Provider } from '@ethersproject/abstract-provider'
2
import { expectApprox, hashCrossDomainMessage } from '@eth-optimism/core-utils'
3
import { predeploys } from '@eth-optimism/contracts'
4 5 6
import { Contract } from 'ethers'
import { ethers } from 'hardhat'

7 8 9 10 11 12 13 14 15 16
import { expect } from './setup'
import {
  MessageDirection,
  CONTRACT_ADDRESSES,
  omit,
  MessageStatus,
  CrossChainMessage,
  CrossChainMessenger,
  StandardBridgeAdapter,
  ETHBridgeAdapter,
17 18
  L1ChainID,
  L2ChainID,
19
} from '../src'
20
import { DUMMY_MESSAGE, DUMMY_EXTENDED_MESSAGE } from './helpers'
21 22 23 24 25 26 27 28 29 30 31 32 33 34

describe('CrossChainMessenger', () => {
  let l1Signer: any
  let l2Signer: any
  before(async () => {
    ;[l1Signer, l2Signer] = await ethers.getSigners()
  })

  describe('construction', () => {
    describe('when given an ethers provider for the L1 provider', () => {
      it('should use the provider as the L1 provider', () => {
        const messenger = new CrossChainMessenger({
          l1SignerOrProvider: ethers.provider,
          l2SignerOrProvider: ethers.provider,
35 36
          l1ChainId: L1ChainID.MAINNET,
          l2ChainId: L2ChainID.OPTIMISM,
37 38 39 40 41 42 43 44 45 46 47
        })

        expect(messenger.l1Provider).to.equal(ethers.provider)
      })
    })

    describe('when given an ethers provider for the L2 provider', () => {
      it('should use the provider as the L2 provider', () => {
        const messenger = new CrossChainMessenger({
          l1SignerOrProvider: ethers.provider,
          l2SignerOrProvider: ethers.provider,
48 49
          l1ChainId: L1ChainID.MAINNET,
          l2ChainId: L2ChainID.OPTIMISM,
50 51 52 53 54 55 56 57 58 59 60
        })

        expect(messenger.l2Provider).to.equal(ethers.provider)
      })
    })

    describe('when given a string as the L1 provider', () => {
      it('should create a JSON-RPC provider for the L1 provider', () => {
        const messenger = new CrossChainMessenger({
          l1SignerOrProvider: 'https://localhost:8545',
          l2SignerOrProvider: ethers.provider,
61 62
          l1ChainId: L1ChainID.MAINNET,
          l2ChainId: L2ChainID.OPTIMISM,
63 64 65 66 67 68 69 70 71 72 73
        })

        expect(Provider.isProvider(messenger.l1Provider)).to.be.true
      })
    })

    describe('when given a string as the L2 provider', () => {
      it('should create a JSON-RPC provider for the L2 provider', () => {
        const messenger = new CrossChainMessenger({
          l1SignerOrProvider: ethers.provider,
          l2SignerOrProvider: 'https://localhost:8545',
74 75
          l1ChainId: L1ChainID.MAINNET,
          l2ChainId: L2ChainID.OPTIMISM,
76 77 78 79 80 81
        })

        expect(Provider.isProvider(messenger.l2Provider)).to.be.true
      })
    })

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
    describe('when given a bad L1 chain ID', () => {
      it('should throw an error', () => {
        expect(() => {
          new CrossChainMessenger({
            l1SignerOrProvider: ethers.provider,
            l2SignerOrProvider: ethers.provider,
            l1ChainId: undefined as any,
            l2ChainId: L2ChainID.OPTIMISM,
          })
        }).to.throw('L1 chain ID is missing or invalid')
      })
    })

    describe('when given a bad L2 chain ID', () => {
      it('should throw an error', () => {
        expect(() => {
          new CrossChainMessenger({
            l1SignerOrProvider: ethers.provider,
            l2SignerOrProvider: ethers.provider,
            l1ChainId: L1ChainID.MAINNET,
            l2ChainId: undefined as any,
          })
        }).to.throw('L2 chain ID is missing or invalid')
      })
    })

108 109 110 111 112 113
    describe('when no custom contract addresses are provided', () => {
      describe('when given a known chain ID', () => {
        it('should use the contract addresses for the known chain ID', () => {
          const messenger = new CrossChainMessenger({
            l1SignerOrProvider: ethers.provider,
            l2SignerOrProvider: 'https://localhost:8545',
114 115
            l1ChainId: L1ChainID.MAINNET,
            l2ChainId: L2ChainID.OPTIMISM,
116 117
          })

118
          const addresses = CONTRACT_ADDRESSES[messenger.l2ChainId]
119 120 121 122 123 124 125 126 127 128 129 130 131 132 133
          for (const [contractName, contractAddress] of Object.entries(
            addresses.l1
          )) {
            const contract = messenger.contracts.l1[contractName]
            expect(contract.address).to.equal(contractAddress)
          }
          for (const [contractName, contractAddress] of Object.entries(
            addresses.l2
          )) {
            const contract = messenger.contracts.l2[contractName]
            expect(contract.address).to.equal(contractAddress)
          }
        })
      })

134
      describe('when given an unknown L2 chain ID', () => {
135 136 137 138 139
        it('should throw an error', () => {
          expect(() => {
            new CrossChainMessenger({
              l1SignerOrProvider: ethers.provider,
              l2SignerOrProvider: 'https://localhost:8545',
140 141
              l1ChainId: L1ChainID.MAINNET,
              l2ChainId: 1234,
142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161
            })
          }).to.throw()
        })
      })
    })

    describe('when custom contract addresses are provided', () => {
      describe('when given a known chain ID', () => {
        it('should use known addresses except where custom addresses are given', () => {
          const overrides = {
            l1: {
              L1CrossDomainMessenger: '0x' + '11'.repeat(20),
            },
            l2: {
              L2CrossDomainMessenger: '0x' + '22'.repeat(20),
            },
          }
          const messenger = new CrossChainMessenger({
            l1SignerOrProvider: ethers.provider,
            l2SignerOrProvider: 'https://localhost:8545',
162 163
            l1ChainId: L1ChainID.MAINNET,
            l2ChainId: L2ChainID.OPTIMISM,
164 165 166
            contracts: overrides,
          })

167
          const addresses = CONTRACT_ADDRESSES[messenger.l2ChainId]
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
          for (const [contractName, contractAddress] of Object.entries(
            addresses.l1
          )) {
            if (overrides.l1[contractName]) {
              const contract = messenger.contracts.l1[contractName]
              expect(contract.address).to.equal(overrides.l1[contractName])
            } else {
              const contract = messenger.contracts.l1[contractName]
              expect(contract.address).to.equal(contractAddress)
            }
          }
          for (const [contractName, contractAddress] of Object.entries(
            addresses.l2
          )) {
            if (overrides.l2[contractName]) {
              const contract = messenger.contracts.l2[contractName]
              expect(contract.address).to.equal(overrides.l2[contractName])
            } else {
              const contract = messenger.contracts.l2[contractName]
              expect(contract.address).to.equal(contractAddress)
            }
          }
        })
      })

193
      describe('when given an unknown L2 chain ID', () => {
194 195 196 197 198 199 200 201 202 203
        describe('when all L1 addresses are provided', () => {
          it('should use custom addresses where provided', () => {
            const overrides = {
              l1: {
                AddressManager: '0x' + '11'.repeat(20),
                L1CrossDomainMessenger: '0x' + '12'.repeat(20),
                L1StandardBridge: '0x' + '13'.repeat(20),
                StateCommitmentChain: '0x' + '14'.repeat(20),
                CanonicalTransactionChain: '0x' + '15'.repeat(20),
                BondManager: '0x' + '16'.repeat(20),
204 205
                OptimismPortal: '0x' + '17'.repeat(20),
                L2OutputOracle: '0x' + '18'.repeat(20),
206 207 208 209 210
              },
              l2: {
                L2CrossDomainMessenger: '0x' + '22'.repeat(20),
              },
            }
211

212 213 214
            const messenger = new CrossChainMessenger({
              l1SignerOrProvider: ethers.provider,
              l2SignerOrProvider: 'https://localhost:8545',
215 216
              l1ChainId: L1ChainID.MAINNET,
              l2ChainId: 1234,
217 218 219
              contracts: overrides,
            })

220
            const addresses = CONTRACT_ADDRESSES[L2ChainID.OPTIMISM]
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
            for (const [contractName, contractAddress] of Object.entries(
              addresses.l1
            )) {
              if (overrides.l1[contractName]) {
                const contract = messenger.contracts.l1[contractName]
                expect(contract.address).to.equal(overrides.l1[contractName])
              } else {
                const contract = messenger.contracts.l1[contractName]
                expect(contract.address).to.equal(contractAddress)
              }
            }
            for (const [contractName, contractAddress] of Object.entries(
              addresses.l2
            )) {
              if (overrides.l2[contractName]) {
                const contract = messenger.contracts.l2[contractName]
                expect(contract.address).to.equal(overrides.l2[contractName])
              } else {
                const contract = messenger.contracts.l2[contractName]
                expect(contract.address).to.equal(contractAddress)
              }
            }
          })
        })

        describe('when not all L1 addresses are provided', () => {
          it('should throw an error', () => {
            expect(() => {
              new CrossChainMessenger({
                l1SignerOrProvider: ethers.provider,
                l2SignerOrProvider: 'https://localhost:8545',
252 253
                l1ChainId: L1ChainID.MAINNET,
                l2ChainId: 1234,
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
                contracts: {
                  l1: {
                    // Missing some required L1 addresses
                    AddressManager: '0x' + '11'.repeat(20),
                    L1CrossDomainMessenger: '0x' + '12'.repeat(20),
                    L1StandardBridge: '0x' + '13'.repeat(20),
                  },
                  l2: {
                    L2CrossDomainMessenger: '0x' + '22'.repeat(20),
                  },
                },
              })
            }).to.throw()
          })
        })
      })
    })
  })

  describe('getMessagesByTransaction', () => {
    let l1Messenger: Contract
    let l2Messenger: Contract
    let messenger: CrossChainMessenger
    beforeEach(async () => {
      l1Messenger = (await (
        await ethers.getContractFactory('MockMessenger')
      ).deploy()) as any
      l2Messenger = (await (
        await ethers.getContractFactory('MockMessenger')
      ).deploy()) as any

      messenger = new CrossChainMessenger({
        l1SignerOrProvider: ethers.provider,
        l2SignerOrProvider: ethers.provider,
288 289
        l1ChainId: L1ChainID.HARDHAT_LOCAL,
        l2ChainId: L2ChainID.OPTIMISM_HARDHAT_LOCAL,
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
        contracts: {
          l1: {
            L1CrossDomainMessenger: l1Messenger.address,
          },
          l2: {
            L2CrossDomainMessenger: l2Messenger.address,
          },
        },
      })
    })

    describe('when a direction is specified', () => {
      describe('when the transaction exists', () => {
        describe('when the transaction has messages', () => {
          for (const n of [1, 2, 4, 8]) {
            it(`should find ${n} messages when the transaction emits ${n} messages`, async () => {
              const messages = [...Array(n)].map(() => {
                return DUMMY_MESSAGE
              })

              const tx = await l1Messenger.triggerSentMessageEvents(messages)
              const found = await messenger.getMessagesByTransaction(tx, {
                direction: MessageDirection.L1_TO_L2,
              })
              expect(found).to.deep.equal(
                messages.map((message, i) => {
                  return {
                    direction: MessageDirection.L1_TO_L2,
                    sender: message.sender,
                    target: message.target,
                    message: message.message,
                    messageNonce: ethers.BigNumber.from(message.messageNonce),
322 323
                    minGasLimit: ethers.BigNumber.from(message.minGasLimit),
                    value: ethers.BigNumber.from(message.value),
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
                    logIndex: i,
                    blockNumber: tx.blockNumber,
                    transactionHash: tx.hash,
                  }
                })
              )
            })
          }
        })

        describe('when the transaction has no messages', () => {
          it('should find nothing', async () => {
            const tx = await l1Messenger.doNothing()
            const found = await messenger.getMessagesByTransaction(tx, {
              direction: MessageDirection.L1_TO_L2,
            })
            expect(found).to.deep.equal([])
          })
        })
      })

      describe('when the transaction does not exist in the specified direction', () => {
        it('should throw an error', async () => {
          await expect(
            messenger.getMessagesByTransaction('0x' + '11'.repeat(32), {
              direction: MessageDirection.L1_TO_L2,
            })
          ).to.be.rejectedWith('unable to find transaction receipt')
        })
      })
    })

    describe('when a direction is not specified', () => {
      describe('when the transaction exists only on L1', () => {
        describe('when the transaction has messages', () => {
          for (const n of [1, 2, 4, 8]) {
            it(`should find ${n} messages when the transaction emits ${n} messages`, async () => {
              const messages = [...Array(n)].map(() => {
                return DUMMY_MESSAGE
              })

              const tx = await l1Messenger.triggerSentMessageEvents(messages)
              const found = await messenger.getMessagesByTransaction(tx)
              expect(found).to.deep.equal(
                messages.map((message, i) => {
                  return {
                    direction: MessageDirection.L1_TO_L2,
                    sender: message.sender,
                    target: message.target,
                    message: message.message,
                    messageNonce: ethers.BigNumber.from(message.messageNonce),
375 376
                    minGasLimit: ethers.BigNumber.from(message.minGasLimit),
                    value: ethers.BigNumber.from(message.value),
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
                    logIndex: i,
                    blockNumber: tx.blockNumber,
                    transactionHash: tx.hash,
                  }
                })
              )
            })
          }
        })

        describe('when the transaction has no messages', () => {
          it('should find nothing', async () => {
            const tx = await l1Messenger.doNothing()
            const found = await messenger.getMessagesByTransaction(tx)
            expect(found).to.deep.equal([])
          })
        })
      })

      describe('when the transaction exists only on L2', () => {
        describe('when the transaction has messages', () => {
          for (const n of [1, 2, 4, 8]) {
            it(`should find ${n} messages when the transaction emits ${n} messages`, () => {
              // TODO: Need support for simulating more than one network.
            })
          }
        })

        describe('when the transaction has no messages', () => {
          it('should find nothing', () => {
            // TODO: Need support for simulating more than one network.
          })
        })
      })

      describe('when the transaction does not exist', () => {
        it('should throw an error', async () => {
          await expect(
            messenger.getMessagesByTransaction('0x' + '11'.repeat(32))
          ).to.be.rejectedWith('unable to find transaction receipt')
        })
      })

      describe('when the transaction exists on both L1 and L2', () => {
        it('should throw an error', async () => {
          // TODO: Need support for simulating more than one network.
        })
      })
    })
  })

428 429
  // Skipped until getMessagesByAddress can be implemented
  describe.skip('getMessagesByAddress', () => {
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
    describe('when the address has sent messages', () => {
      describe('when no direction is specified', () => {
        it('should find all messages sent by the address')
      })

      describe('when a direction is specified', () => {
        it('should find all messages only in the given direction')
      })

      describe('when a block range is specified', () => {
        it('should find all messages within the block range')
      })

      describe('when both a direction and a block range are specified', () => {
        it(
          'should find all messages only in the given direction and within the block range'
        )
      })
    })

    describe('when the address has not sent messages', () => {
      it('should find nothing')
    })
  })

  describe('toCrossChainMessage', () => {
    let l1Bridge: Contract
    let l2Bridge: Contract
    let l1Messenger: Contract
    let l2Messenger: Contract
    let messenger: CrossChainMessenger
    beforeEach(async () => {
      l1Messenger = (await (
        await ethers.getContractFactory('MockMessenger')
      ).deploy()) as any
      l2Messenger = (await (
        await ethers.getContractFactory('MockMessenger')
      ).deploy()) as any
      l1Bridge = (await (
        await ethers.getContractFactory('MockBridge')
      ).deploy(l1Messenger.address)) as any
      l2Bridge = (await (
        await ethers.getContractFactory('MockBridge')
      ).deploy(l2Messenger.address)) as any

      messenger = new CrossChainMessenger({
        l1SignerOrProvider: ethers.provider,
        l2SignerOrProvider: ethers.provider,
478 479
        l1ChainId: L1ChainID.HARDHAT_LOCAL,
        l2ChainId: L2ChainID.OPTIMISM_HARDHAT_LOCAL,
480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502
        contracts: {
          l1: {
            L1CrossDomainMessenger: l1Messenger.address,
            L1StandardBridge: l1Bridge.address,
          },
          l2: {
            L2CrossDomainMessenger: l2Messenger.address,
            L2StandardBridge: l2Bridge.address,
          },
        },
        bridges: {
          Standard: {
            Adapter: StandardBridgeAdapter,
            l1Bridge: l1Bridge.address,
            l2Bridge: l2Bridge.address,
          },
        },
      })
    })

    describe('when the input is a CrossChainMessage', () => {
      it('should return the input', async () => {
        const message = {
503
          ...DUMMY_EXTENDED_MESSAGE,
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
          direction: MessageDirection.L1_TO_L2,
        }

        expect(await messenger.toCrossChainMessage(message)).to.deep.equal(
          message
        )
      })
    })

    describe('when the input is a TokenBridgeMessage', () => {
      // TODO: There are some edge cases here with custom bridges that conform to the interface but
      // not to the behavioral spec. Possibly worth testing those. For now this is probably
      // sufficient.
      it('should return the sent message event that came after the deposit or withdrawal', async () => {
        const from = '0x' + '99'.repeat(20)
        const deposit = {
          l1Token: '0x' + '11'.repeat(20),
          l2Token: '0x' + '22'.repeat(20),
          from,
          to: '0x' + '44'.repeat(20),
          amount: ethers.BigNumber.from(1234),
          data: '0x1234',
        }

        const tx = await l1Bridge.emitERC20DepositInitiated(deposit)

        const foundCrossChainMessages =
          await messenger.getMessagesByTransaction(tx)
532 533 534
        const foundTokenBridgeMessages = await messenger.getDepositsByAddress(
          from
        )
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
        const resolved = await messenger.toCrossChainMessage(
          foundTokenBridgeMessages[0]
        )

        expect(resolved).to.deep.equal(foundCrossChainMessages[0])
      })
    })

    describe('when the input is a TransactionLike', () => {
      describe('when the transaction sent exactly one message', () => {
        it('should return the CrossChainMessage sent in the transaction', async () => {
          const tx = await l1Messenger.triggerSentMessageEvents([DUMMY_MESSAGE])
          const foundCrossChainMessages =
            await messenger.getMessagesByTransaction(tx)
          const resolved = await messenger.toCrossChainMessage(tx)
          expect(resolved).to.deep.equal(foundCrossChainMessages[0])
        })
      })

      describe('when the transaction sent more than one message', () => {
        it('should throw an error', async () => {
          const messages = [...Array(2)].map(() => {
            return DUMMY_MESSAGE
          })

          const tx = await l1Messenger.triggerSentMessageEvents(messages)
          await expect(messenger.toCrossChainMessage(tx)).to.be.rejectedWith(
            'expected 1 message, got 2'
          )
        })
      })

      describe('when the transaction sent no messages', () => {
        it('should throw an error', async () => {
          const tx = await l1Messenger.triggerSentMessageEvents([])
          await expect(messenger.toCrossChainMessage(tx)).to.be.rejectedWith(
            'expected 1 message, got 0'
          )
        })
      })
    })
  })

  describe('getMessageStatus', () => {
    let scc: Contract
    let l1Messenger: Contract
    let l2Messenger: Contract
    let messenger: CrossChainMessenger
    beforeEach(async () => {
      // TODO: Get rid of the nested awaits here. Could be a good first issue for someone.
      scc = (await (await ethers.getContractFactory('MockSCC')).deploy()) as any
      l1Messenger = (await (
        await ethers.getContractFactory('MockMessenger')
      ).deploy()) as any
      l2Messenger = (await (
        await ethers.getContractFactory('MockMessenger')
      ).deploy()) as any

      messenger = new CrossChainMessenger({
        l1SignerOrProvider: ethers.provider,
        l2SignerOrProvider: ethers.provider,
596 597
        l1ChainId: L1ChainID.HARDHAT_LOCAL,
        l2ChainId: L2ChainID.OPTIMISM_HARDHAT_LOCAL,
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
        contracts: {
          l1: {
            L1CrossDomainMessenger: l1Messenger.address,
            StateCommitmentChain: scc.address,
          },
          l2: {
            L2CrossDomainMessenger: l2Messenger.address,
          },
        },
      })
    })

    const sendAndGetDummyMessage = async (direction: MessageDirection) => {
      const mockMessenger =
        direction === MessageDirection.L1_TO_L2 ? l1Messenger : l2Messenger
      const tx = await mockMessenger.triggerSentMessageEvents([DUMMY_MESSAGE])
      return (
        await messenger.getMessagesByTransaction(tx, {
          direction,
        })
      )[0]
    }

    const submitStateRootBatchForMessage = async (
      message: CrossChainMessage
    ) => {
      await scc.setSBAParams({
        batchIndex: 0,
        batchRoot: ethers.constants.HashZero,
        batchSize: 1,
        prevTotalElements: message.blockNumber,
        extraData: '0x',
      })
      await scc.appendStateBatch([ethers.constants.HashZero], 0)
    }

    describe('when the message is an L1 => L2 message', () => {
      describe('when the message has not been executed on L2 yet', () => {
        it('should return a status of UNCONFIRMED_L1_TO_L2_MESSAGE', async () => {
          const message = await sendAndGetDummyMessage(
            MessageDirection.L1_TO_L2
          )

          expect(await messenger.getMessageStatus(message)).to.equal(
            MessageStatus.UNCONFIRMED_L1_TO_L2_MESSAGE
          )
        })
      })

      describe('when the message has been executed on L2', () => {
        it('should return a status of RELAYED', async () => {
          const message = await sendAndGetDummyMessage(
            MessageDirection.L1_TO_L2
          )

          await l2Messenger.triggerRelayedMessageEvents([
654 655 656 657 658 659 660 661
            hashCrossDomainMessage(
              message.messageNonce,
              message.sender,
              message.target,
              message.value,
              message.minGasLimit,
              message.message
            ),
662 663 664 665 666 667 668 669 670 671 672 673 674 675 676
          ])

          expect(await messenger.getMessageStatus(message)).to.equal(
            MessageStatus.RELAYED
          )
        })
      })

      describe('when the message has been executed but failed', () => {
        it('should return a status of FAILED_L1_TO_L2_MESSAGE', async () => {
          const message = await sendAndGetDummyMessage(
            MessageDirection.L1_TO_L2
          )

          await l2Messenger.triggerFailedRelayedMessageEvents([
677 678 679 680 681 682 683 684
            hashCrossDomainMessage(
              message.messageNonce,
              message.sender,
              message.target,
              message.value,
              message.minGasLimit,
              message.message
            ),
685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705
          ])

          expect(await messenger.getMessageStatus(message)).to.equal(
            MessageStatus.FAILED_L1_TO_L2_MESSAGE
          )
        })
      })
    })

    describe('when the message is an L2 => L1 message', () => {
      describe('when the message state root has not been published', () => {
        it('should return a status of STATE_ROOT_NOT_PUBLISHED', async () => {
          const message = await sendAndGetDummyMessage(
            MessageDirection.L2_TO_L1
          )

          expect(await messenger.getMessageStatus(message)).to.equal(
            MessageStatus.STATE_ROOT_NOT_PUBLISHED
          )
        })
      })
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
      describe('when the message state root is still in the challenge period', () => {
        it('should return a status of IN_CHALLENGE_PERIOD', async () => {
          const message = await sendAndGetDummyMessage(
            MessageDirection.L2_TO_L1
          )

          await submitStateRootBatchForMessage(message)

          expect(await messenger.getMessageStatus(message)).to.equal(
            MessageStatus.IN_CHALLENGE_PERIOD
          )
        })
      })

      describe('when the message is no longer in the challenge period', () => {
        describe('when the message has been relayed successfully', () => {
          it('should return a status of RELAYED', async () => {
            const message = await sendAndGetDummyMessage(
              MessageDirection.L2_TO_L1
            )

            await submitStateRootBatchForMessage(message)

            const challengePeriod = await messenger.getChallengePeriodSeconds()
            ethers.provider.send('evm_increaseTime', [challengePeriod + 1])
            ethers.provider.send('evm_mine', [])

            await l1Messenger.triggerRelayedMessageEvents([
735 736 737 738 739 740 741 742
              hashCrossDomainMessage(
                message.messageNonce,
                message.sender,
                message.target,
                message.value,
                message.minGasLimit,
                message.message
              ),
743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763
            ])

            expect(await messenger.getMessageStatus(message)).to.equal(
              MessageStatus.RELAYED
            )
          })
        })

        describe('when the message has been relayed but the relay failed', () => {
          it('should return a status of READY_FOR_RELAY', async () => {
            const message = await sendAndGetDummyMessage(
              MessageDirection.L2_TO_L1
            )

            await submitStateRootBatchForMessage(message)

            const challengePeriod = await messenger.getChallengePeriodSeconds()
            ethers.provider.send('evm_increaseTime', [challengePeriod + 1])
            ethers.provider.send('evm_mine', [])

            await l1Messenger.triggerFailedRelayedMessageEvents([
764 765 766 767 768 769 770 771
              hashCrossDomainMessage(
                message.messageNonce,
                message.sender,
                message.target,
                message.value,
                message.minGasLimit,
                message.message
              ),
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
            ])

            expect(await messenger.getMessageStatus(message)).to.equal(
              MessageStatus.READY_FOR_RELAY
            )
          })
        })

        describe('when the message has not been relayed', () => {
          it('should return a status of READY_FOR_RELAY', async () => {
            const message = await sendAndGetDummyMessage(
              MessageDirection.L2_TO_L1
            )

            await submitStateRootBatchForMessage(message)

            const challengePeriod = await messenger.getChallengePeriodSeconds()
            ethers.provider.send('evm_increaseTime', [challengePeriod + 1])
            ethers.provider.send('evm_mine', [])

            expect(await messenger.getMessageStatus(message)).to.equal(
              MessageStatus.READY_FOR_RELAY
            )
          })
        })
      })
    })

    describe('when the message does not exist', () => {
      // TODO: Figure out if this is the correct behavior. Mark suggests perhaps returning null.
      it('should throw an error')
    })
804 805
  })

806 807 808
  describe('getMessageReceipt', () => {
    let l1Bridge: Contract
    let l2Bridge: Contract
809 810 811 812 813 814 815 816 817 818
    let l1Messenger: Contract
    let l2Messenger: Contract
    let messenger: CrossChainMessenger
    beforeEach(async () => {
      l1Messenger = (await (
        await ethers.getContractFactory('MockMessenger')
      ).deploy()) as any
      l2Messenger = (await (
        await ethers.getContractFactory('MockMessenger')
      ).deploy()) as any
819 820 821 822 823 824
      l1Bridge = (await (
        await ethers.getContractFactory('MockBridge')
      ).deploy(l1Messenger.address)) as any
      l2Bridge = (await (
        await ethers.getContractFactory('MockBridge')
      ).deploy(l2Messenger.address)) as any
825

826 827 828
      messenger = new CrossChainMessenger({
        l1SignerOrProvider: ethers.provider,
        l2SignerOrProvider: ethers.provider,
829 830
        l1ChainId: L1ChainID.HARDHAT_LOCAL,
        l2ChainId: L2ChainID.OPTIMISM_HARDHAT_LOCAL,
831 832 833
        contracts: {
          l1: {
            L1CrossDomainMessenger: l1Messenger.address,
834 835 836 837 838
            L1StandardBridge: l1Bridge.address,
          },
          l2: {
            L2CrossDomainMessenger: l2Messenger.address,
            L2StandardBridge: l2Bridge.address,
839
          },
840 841 842 843 844 845 846 847
        },
      })
    })

    describe('when the message has been relayed', () => {
      describe('when the relay was successful', () => {
        it('should return the receipt of the transaction that relayed the message', async () => {
          const message = {
848
            ...DUMMY_EXTENDED_MESSAGE,
849 850 851 852
            direction: MessageDirection.L1_TO_L2,
          }

          const tx = await l2Messenger.triggerRelayedMessageEvents([
853 854 855 856 857 858 859 860
            hashCrossDomainMessage(
              message.messageNonce,
              message.sender,
              message.target,
              message.value,
              message.minGasLimit,
              message.message
            ),
861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878
          ])

          const messageReceipt = await messenger.getMessageReceipt(message)
          expect(messageReceipt.receiptStatus).to.equal(1)
          expect(
            omit(messageReceipt.transactionReceipt, 'confirmations')
          ).to.deep.equal(
            omit(
              await ethers.provider.getTransactionReceipt(tx.hash),
              'confirmations'
            )
          )
        })
      })

      describe('when the relay failed', () => {
        it('should return the receipt of the transaction that attempted to relay the message', async () => {
          const message = {
879
            ...DUMMY_EXTENDED_MESSAGE,
880 881 882 883
            direction: MessageDirection.L1_TO_L2,
          }

          const tx = await l2Messenger.triggerFailedRelayedMessageEvents([
884 885 886 887 888 889 890 891
            hashCrossDomainMessage(
              message.messageNonce,
              message.sender,
              message.target,
              message.value,
              message.minGasLimit,
              message.message
            ),
892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909
          ])

          const messageReceipt = await messenger.getMessageReceipt(message)
          expect(messageReceipt.receiptStatus).to.equal(0)
          expect(
            omit(messageReceipt.transactionReceipt, 'confirmations')
          ).to.deep.equal(
            omit(
              await ethers.provider.getTransactionReceipt(tx.hash),
              'confirmations'
            )
          )
        })
      })

      describe('when the relay failed more than once', () => {
        it('should return the receipt of the last transaction that attempted to relay the message', async () => {
          const message = {
910
            ...DUMMY_EXTENDED_MESSAGE,
911 912 913 914
            direction: MessageDirection.L1_TO_L2,
          }

          await l2Messenger.triggerFailedRelayedMessageEvents([
915 916 917 918 919 920 921 922
            hashCrossDomainMessage(
              message.messageNonce,
              message.sender,
              message.target,
              message.value,
              message.minGasLimit,
              message.message
            ),
923 924 925
          ])

          const tx = await l2Messenger.triggerFailedRelayedMessageEvents([
926 927 928 929 930 931 932 933
            hashCrossDomainMessage(
              message.messageNonce,
              message.sender,
              message.target,
              message.value,
              message.minGasLimit,
              message.message
            ),
934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952
          ])

          const messageReceipt = await messenger.getMessageReceipt(message)
          expect(messageReceipt.receiptStatus).to.equal(0)
          expect(
            omit(messageReceipt.transactionReceipt, 'confirmations')
          ).to.deep.equal(
            omit(
              await ethers.provider.getTransactionReceipt(tx.hash),
              'confirmations'
            )
          )
        })
      })
    })

    describe('when the message has not been relayed', () => {
      it('should return null', async () => {
        const message = {
953
          ...DUMMY_EXTENDED_MESSAGE,
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
          direction: MessageDirection.L1_TO_L2,
        }

        await l2Messenger.doNothing()

        const messageReceipt = await messenger.getMessageReceipt(message)
        expect(messageReceipt).to.equal(null)
      })
    })

    // TODO: Go over all of these tests and remove the empty functions so we can accurately keep
    // track of
  })

  describe('waitForMessageReceipt', () => {
    let l2Messenger: Contract
    let messenger: CrossChainMessenger
    beforeEach(async () => {
      l2Messenger = (await (
        await ethers.getContractFactory('MockMessenger')
      ).deploy()) as any

      messenger = new CrossChainMessenger({
        l1SignerOrProvider: ethers.provider,
        l2SignerOrProvider: ethers.provider,
979 980
        l1ChainId: L1ChainID.HARDHAT_LOCAL,
        l2ChainId: L2ChainID.OPTIMISM_HARDHAT_LOCAL,
981
        contracts: {
982 983 984 985 986
          l2: {
            L2CrossDomainMessenger: l2Messenger.address,
          },
        },
      })
987 988 989 990 991
    })

    describe('when the message receipt already exists', () => {
      it('should immediately return the receipt', async () => {
        const message = {
992
          ...DUMMY_EXTENDED_MESSAGE,
993 994 995 996
          direction: MessageDirection.L1_TO_L2,
        }

        const tx = await l2Messenger.triggerRelayedMessageEvents([
997 998 999 1000 1001 1002 1003 1004
          hashCrossDomainMessage(
            message.messageNonce,
            message.sender,
            message.target,
            message.value,
            message.minGasLimit,
            message.message
          ),
1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023
        ])

        const messageReceipt = await messenger.waitForMessageReceipt(message)
        expect(messageReceipt.receiptStatus).to.equal(1)
        expect(
          omit(messageReceipt.transactionReceipt, 'confirmations')
        ).to.deep.equal(
          omit(
            await ethers.provider.getTransactionReceipt(tx.hash),
            'confirmations'
          )
        )
      })
    })

    describe('when the message receipt does not exist already', () => {
      describe('when no extra options are provided', () => {
        it('should wait for the receipt to be published', async () => {
          const message = {
1024
            ...DUMMY_EXTENDED_MESSAGE,
1025 1026 1027 1028 1029
            direction: MessageDirection.L1_TO_L2,
          }

          setTimeout(async () => {
            await l2Messenger.triggerRelayedMessageEvents([
1030 1031 1032 1033 1034 1035 1036 1037
              hashCrossDomainMessage(
                message.messageNonce,
                message.sender,
                message.target,
                message.value,
                message.minGasLimit,
                message.message
              ),
1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056
            ])
          }, 5000)

          const tick = Date.now()
          const messageReceipt = await messenger.waitForMessageReceipt(message)
          const tock = Date.now()
          expect(messageReceipt.receiptStatus).to.equal(1)
          expect(tock - tick).to.be.greaterThan(5000)
        })

        it('should wait forever for the receipt if the receipt is never published', () => {
          // Not sure how to easily test this without introducing some sort of cancellation token
          // I don't want the promise to loop forever and make the tests never finish.
        })
      })

      describe('when a timeout is provided', () => {
        it('should throw an error if the timeout is reached', async () => {
          const message = {
1057
            ...DUMMY_EXTENDED_MESSAGE,
1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076
            direction: MessageDirection.L1_TO_L2,
          }

          await expect(
            messenger.waitForMessageReceipt(message, {
              timeoutMs: 10000,
            })
          ).to.be.rejectedWith('timed out waiting for message receipt')
        })
      })
    })
  })

  describe('estimateL2MessageGasLimit', () => {
    let messenger: CrossChainMessenger
    beforeEach(async () => {
      messenger = new CrossChainMessenger({
        l1SignerOrProvider: ethers.provider,
        l2SignerOrProvider: ethers.provider,
1077 1078
        l1ChainId: L1ChainID.HARDHAT_LOCAL,
        l2ChainId: L2ChainID.OPTIMISM_HARDHAT_LOCAL,
1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162
      })
    })

    describe('when the message is an L1 to L2 message', () => {
      it('should return an accurate gas estimate plus a ~20% buffer', async () => {
        const message = {
          direction: MessageDirection.L1_TO_L2,
          target: '0x' + '11'.repeat(20),
          sender: '0x' + '22'.repeat(20),
          message: '0x' + '33'.repeat(64),
          messageNonce: 1234,
          logIndex: 0,
          blockNumber: 1234,
          transactionHash: '0x' + '44'.repeat(32),
        }

        const estimate = await ethers.provider.estimateGas({
          to: message.target,
          from: message.sender,
          data: message.message,
        })

        // Approximately 20% greater than the estimate, +/- 1%.
        expectApprox(
          await messenger.estimateL2MessageGasLimit(message),
          estimate.mul(120).div(100),
          {
            percentUpperDeviation: 1,
            percentLowerDeviation: 1,
          }
        )
      })

      it('should return an accurate gas estimate when a custom buffer is provided', async () => {
        const message = {
          direction: MessageDirection.L1_TO_L2,
          target: '0x' + '11'.repeat(20),
          sender: '0x' + '22'.repeat(20),
          message: '0x' + '33'.repeat(64),
          messageNonce: 1234,
          logIndex: 0,
          blockNumber: 1234,
          transactionHash: '0x' + '44'.repeat(32),
        }

        const estimate = await ethers.provider.estimateGas({
          to: message.target,
          from: message.sender,
          data: message.message,
        })

        // Approximately 30% greater than the estimate, +/- 1%.
        expectApprox(
          await messenger.estimateL2MessageGasLimit(message, {
            bufferPercent: 30,
          }),
          estimate.mul(130).div(100),
          {
            percentUpperDeviation: 1,
            percentLowerDeviation: 1,
          }
        )
      })
    })

    describe('when the message is an L2 to L1 message', () => {
      it('should throw an error', async () => {
        const message = {
          direction: MessageDirection.L2_TO_L1,
          target: '0x' + '11'.repeat(20),
          sender: '0x' + '22'.repeat(20),
          message: '0x' + '33'.repeat(64),
          messageNonce: 1234,
          logIndex: 0,
          blockNumber: 1234,
          transactionHash: '0x' + '44'.repeat(32),
        }

        await expect(messenger.estimateL2MessageGasLimit(message)).to.be
          .rejected
      })
    })
  })

1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180
  describe('estimateMessageWaitTimeSeconds', () => {
    let scc: Contract
    let l1Messenger: Contract
    let l2Messenger: Contract
    let messenger: CrossChainMessenger
    beforeEach(async () => {
      // TODO: Get rid of the nested awaits here. Could be a good first issue for someone.
      scc = (await (await ethers.getContractFactory('MockSCC')).deploy()) as any
      l1Messenger = (await (
        await ethers.getContractFactory('MockMessenger')
      ).deploy()) as any
      l2Messenger = (await (
        await ethers.getContractFactory('MockMessenger')
      ).deploy()) as any

      messenger = new CrossChainMessenger({
        l1SignerOrProvider: ethers.provider,
        l2SignerOrProvider: ethers.provider,
1181 1182
        l1ChainId: L1ChainID.HARDHAT_LOCAL,
        l2ChainId: L2ChainID.OPTIMISM_HARDHAT_LOCAL,
1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223
        contracts: {
          l1: {
            L1CrossDomainMessenger: l1Messenger.address,
            StateCommitmentChain: scc.address,
          },
          l2: {
            L2CrossDomainMessenger: l2Messenger.address,
          },
        },
      })
    })

    const sendAndGetDummyMessage = async (direction: MessageDirection) => {
      const mockMessenger =
        direction === MessageDirection.L1_TO_L2 ? l1Messenger : l2Messenger
      const tx = await mockMessenger.triggerSentMessageEvents([DUMMY_MESSAGE])
      return (
        await messenger.getMessagesByTransaction(tx, {
          direction,
        })
      )[0]
    }

    const submitStateRootBatchForMessage = async (
      message: CrossChainMessage
    ) => {
      await scc.setSBAParams({
        batchIndex: 0,
        batchRoot: ethers.constants.HashZero,
        batchSize: 1,
        prevTotalElements: message.blockNumber,
        extraData: '0x',
      })
      await scc.appendStateBatch([ethers.constants.HashZero], 0)
    }

    describe('when the message is an L1 => L2 message', () => {
      describe('when the message has not been executed on L2 yet', () => {
        it('should return the estimated seconds until the message will be confirmed on L2', async () => {
          const message = await sendAndGetDummyMessage(
            MessageDirection.L1_TO_L2
1224
          )
1225 1226 1227 1228 1229 1230

          await l1Messenger.triggerSentMessageEvents([message])

          expect(
            await messenger.estimateMessageWaitTimeSeconds(message)
          ).to.equal(1)
1231
        })
1232 1233 1234 1235 1236 1237 1238 1239 1240 1241
      })

      describe('when the message has been executed on L2', () => {
        it('should return 0', async () => {
          const message = await sendAndGetDummyMessage(
            MessageDirection.L1_TO_L2
          )

          await l1Messenger.triggerSentMessageEvents([message])
          await l2Messenger.triggerRelayedMessageEvents([
1242 1243 1244 1245 1246 1247 1248 1249
            hashCrossDomainMessage(
              message.messageNonce,
              message.sender,
              message.target,
              message.value,
              message.minGasLimit,
              message.message
            ),
1250
          ])
1251

1252 1253 1254
          expect(
            await messenger.estimateMessageWaitTimeSeconds(message)
          ).to.equal(0)
1255 1256
        })
      })
1257
    })
1258

1259 1260 1261 1262 1263
    describe('when the message is an L2 => L1 message', () => {
      describe('when the state root has not been published', () => {
        it('should return the estimated seconds until the state root will be published and pass the challenge period', async () => {
          const message = await sendAndGetDummyMessage(
            MessageDirection.L2_TO_L1
1264
          )
1265 1266 1267 1268

          expect(
            await messenger.estimateMessageWaitTimeSeconds(message)
          ).to.equal(await messenger.getChallengePeriodSeconds())
1269
        })
1270
      })
1271

1272 1273 1274 1275
      describe('when the state root is within the challenge period', () => {
        it('should return the estimated seconds until the state root passes the challenge period', async () => {
          const message = await sendAndGetDummyMessage(
            MessageDirection.L2_TO_L1
1276
          )
1277 1278 1279 1280 1281 1282 1283

          await submitStateRootBatchForMessage(message)

          const challengePeriod = await messenger.getChallengePeriodSeconds()
          ethers.provider.send('evm_increaseTime', [challengePeriod / 2])
          ethers.provider.send('evm_mine', [])

1284 1285 1286 1287 1288 1289 1290 1291
          expectApprox(
            await messenger.estimateMessageWaitTimeSeconds(message),
            challengePeriod / 2,
            {
              percentUpperDeviation: 5,
              percentLowerDeviation: 5,
            }
          )
1292
        })
1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305
      })

      describe('when the state root passes the challenge period', () => {
        it('should return 0', async () => {
          const message = await sendAndGetDummyMessage(
            MessageDirection.L2_TO_L1
          )

          await submitStateRootBatchForMessage(message)

          const challengePeriod = await messenger.getChallengePeriodSeconds()
          ethers.provider.send('evm_increaseTime', [challengePeriod + 1])
          ethers.provider.send('evm_mine', [])
1306

1307 1308 1309
          expect(
            await messenger.estimateMessageWaitTimeSeconds(message)
          ).to.equal(0)
1310 1311 1312
        })
      })

1313 1314 1315 1316 1317
      describe('when the message has been executed', () => {
        it('should return 0', async () => {
          const message = await sendAndGetDummyMessage(
            MessageDirection.L2_TO_L1
          )
1318

1319 1320
          await l2Messenger.triggerSentMessageEvents([message])
          await l1Messenger.triggerRelayedMessageEvents([
1321 1322 1323 1324 1325 1326 1327 1328
            hashCrossDomainMessage(
              message.messageNonce,
              message.sender,
              message.target,
              message.value,
              message.minGasLimit,
              message.message
            ),
1329 1330 1331 1332 1333 1334 1335 1336
          ])

          expect(
            await messenger.estimateMessageWaitTimeSeconds(message)
          ).to.equal(0)
        })
      })
    })
1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349
  })

  describe('sendMessage', () => {
    let l1Messenger: Contract
    let l2Messenger: Contract
    let messenger: CrossChainMessenger
    beforeEach(async () => {
      l1Messenger = (await (
        await ethers.getContractFactory('MockMessenger')
      ).deploy()) as any
      l2Messenger = (await (
        await ethers.getContractFactory('MockMessenger')
      ).deploy()) as any
1350 1351

      messenger = new CrossChainMessenger({
1352 1353
        l1SignerOrProvider: l1Signer,
        l2SignerOrProvider: l2Signer,
1354 1355
        l1ChainId: L1ChainID.HARDHAT_LOCAL,
        l2ChainId: L2ChainID.OPTIMISM_HARDHAT_LOCAL,
1356 1357 1358 1359 1360 1361 1362 1363
        contracts: {
          l1: {
            L1CrossDomainMessenger: l1Messenger.address,
          },
          l2: {
            L2CrossDomainMessenger: l2Messenger.address,
          },
        },
1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375
      })
    })

    describe('when the message is an L1 to L2 message', () => {
      describe('when no l2GasLimit is provided', () => {
        it('should send a message with an estimated l2GasLimit', async () => {
          const message = {
            direction: MessageDirection.L1_TO_L2,
            target: '0x' + '11'.repeat(20),
            message: '0x' + '22'.repeat(32),
          }

1376
          const estimate = await messenger.estimateL2MessageGasLimit(message)
1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411
          await expect(messenger.sendMessage(message))
            .to.emit(l1Messenger, 'SentMessage')
            .withArgs(
              message.target,
              await l1Signer.getAddress(),
              message.message,
              0,
              estimate
            )
        })
      })

      describe('when an l2GasLimit is provided', () => {
        it('should send a message with the provided l2GasLimit', async () => {
          const message = {
            direction: MessageDirection.L1_TO_L2,
            target: '0x' + '11'.repeat(20),
            message: '0x' + '22'.repeat(32),
          }

          await expect(
            messenger.sendMessage(message, {
              l2GasLimit: 1234,
            })
          )
            .to.emit(l1Messenger, 'SentMessage')
            .withArgs(
              message.target,
              await l1Signer.getAddress(),
              message.message,
              0,
              1234
            )
        })
      })
1412 1413
    })

1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431
    describe('when the message is an L2 to L1 message', () => {
      it('should send a message', async () => {
        const message = {
          direction: MessageDirection.L2_TO_L1,
          target: '0x' + '11'.repeat(20),
          message: '0x' + '22'.repeat(32),
        }

        await expect(messenger.sendMessage(message))
          .to.emit(l2Messenger, 'SentMessage')
          .withArgs(
            message.target,
            await l2Signer.getAddress(),
            message.message,
            0,
            0
          )
      })
1432 1433 1434 1435
    })
  })

  describe('resendMessage', () => {
1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446
    let l1Messenger: Contract
    let l2Messenger: Contract
    let messenger: CrossChainMessenger
    beforeEach(async () => {
      l1Messenger = (await (
        await ethers.getContractFactory('MockMessenger')
      ).deploy()) as any
      l2Messenger = (await (
        await ethers.getContractFactory('MockMessenger')
      ).deploy()) as any

1447 1448 1449
      messenger = new CrossChainMessenger({
        l1SignerOrProvider: l1Signer,
        l2SignerOrProvider: l2Signer,
1450 1451
        l1ChainId: L1ChainID.HARDHAT_LOCAL,
        l2ChainId: L2ChainID.OPTIMISM_HARDHAT_LOCAL,
1452 1453 1454 1455 1456 1457 1458 1459 1460
        contracts: {
          l1: {
            L1CrossDomainMessenger: l1Messenger.address,
          },
          l2: {
            L2CrossDomainMessenger: l2Messenger.address,
          },
        },
      })
1461 1462
    })

1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500
    describe('when resending an L1 to L2 message', () => {
      it('should resend the message with the new gas limit', async () => {
        const message = {
          direction: MessageDirection.L1_TO_L2,
          target: '0x' + '11'.repeat(20),
          message: '0x' + '22'.repeat(32),
        }

        const sent = await messenger.sendMessage(message, {
          l2GasLimit: 1234,
        })

        await expect(messenger.resendMessage(sent, 10000))
          .to.emit(l1Messenger, 'SentMessage')
          .withArgs(
            message.target,
            await l1Signer.getAddress(),
            message.message,
            1, // nonce is now 1
            10000
          )
      })
    })

    describe('when resending an L2 to L1 message', () => {
      it('should throw an error', async () => {
        const message = {
          direction: MessageDirection.L2_TO_L1,
          target: '0x' + '11'.repeat(20),
          message: '0x' + '22'.repeat(32),
        }

        const sent = await messenger.sendMessage(message, {
          l2GasLimit: 1234,
        })

        await expect(messenger.resendMessage(sent, 10000)).to.be.rejected
      })
1501 1502 1503 1504 1505 1506
    })
  })

  describe('finalizeMessage', () => {
    describe('when the message being finalized exists', () => {
      describe('when the message is ready to be finalized', () => {
1507
        it('should finalize the message')
1508 1509 1510
      })

      describe('when the message is not ready to be finalized', () => {
1511
        it('should throw an error')
1512 1513 1514
      })

      describe('when the message has already been finalized', () => {
1515
        it('should throw an error')
1516 1517 1518 1519
      })
    })

    describe('when the message being finalized does not exist', () => {
1520
      it('should throw an error')
1521 1522
    })
  })
1523 1524 1525

  describe('depositETH', () => {
    let l1Messenger: Contract
1526
    let l2Messenger: Contract
1527
    let l1Bridge: Contract
1528
    let l2Bridge: Contract
1529 1530 1531 1532 1533 1534 1535 1536
    let messenger: CrossChainMessenger
    beforeEach(async () => {
      l1Messenger = (await (
        await ethers.getContractFactory('MockMessenger')
      ).deploy()) as any
      l1Bridge = (await (
        await ethers.getContractFactory('MockBridge')
      ).deploy(l1Messenger.address)) as any
1537 1538 1539 1540 1541 1542
      l2Messenger = (await (
        await ethers.getContractFactory('MockMessenger')
      ).deploy()) as any
      l2Bridge = (await (
        await ethers.getContractFactory('MockBridge')
      ).deploy(l2Messenger.address)) as any
1543

1544 1545 1546
      messenger = new CrossChainMessenger({
        l1SignerOrProvider: l1Signer,
        l2SignerOrProvider: l2Signer,
1547 1548
        l1ChainId: L1ChainID.HARDHAT_LOCAL,
        l2ChainId: L2ChainID.OPTIMISM_HARDHAT_LOCAL,
1549 1550 1551 1552 1553
        contracts: {
          l1: {
            L1CrossDomainMessenger: l1Messenger.address,
            L1StandardBridge: l1Bridge.address,
          },
1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564
          l2: {
            L2CrossDomainMessenger: l2Messenger.address,
            L2StandardBridge: l2Bridge.address,
          },
        },
        bridges: {
          ETH: {
            Adapter: ETHBridgeAdapter,
            l1Bridge: l1Bridge.address,
            l2Bridge: l2Bridge.address,
          },
1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579
        },
      })
    })

    it('should trigger the deposit ETH function with the given amount', async () => {
      await expect(messenger.depositETH(100000))
        .to.emit(l1Bridge, 'ETHDepositInitiated')
        .withArgs(
          await l1Signer.getAddress(),
          await l1Signer.getAddress(),
          100000,
          '0x'
        )
    })
  })
1580 1581

  describe('withdrawETH', () => {
1582
    let l1Messenger: Contract
1583
    let l2Messenger: Contract
1584
    let l1Bridge: Contract
1585 1586 1587
    let l2Bridge: Contract
    let messenger: CrossChainMessenger
    beforeEach(async () => {
1588 1589 1590 1591 1592 1593
      l1Messenger = (await (
        await ethers.getContractFactory('MockMessenger')
      ).deploy()) as any
      l1Bridge = (await (
        await ethers.getContractFactory('MockBridge')
      ).deploy(l1Messenger.address)) as any
1594 1595 1596 1597 1598 1599 1600
      l2Messenger = (await (
        await ethers.getContractFactory('MockMessenger')
      ).deploy()) as any
      l2Bridge = (await (
        await ethers.getContractFactory('MockBridge')
      ).deploy(l2Messenger.address)) as any

1601 1602 1603
      messenger = new CrossChainMessenger({
        l1SignerOrProvider: l1Signer,
        l2SignerOrProvider: l2Signer,
1604 1605
        l1ChainId: L1ChainID.HARDHAT_LOCAL,
        l2ChainId: L2ChainID.OPTIMISM_HARDHAT_LOCAL,
1606
        contracts: {
1607 1608 1609 1610
          l1: {
            L1CrossDomainMessenger: l1Messenger.address,
            L1StandardBridge: l1Bridge.address,
          },
1611 1612 1613 1614 1615
          l2: {
            L2CrossDomainMessenger: l2Messenger.address,
            L2StandardBridge: l2Bridge.address,
          },
        },
1616 1617 1618 1619 1620 1621 1622
        bridges: {
          ETH: {
            Adapter: ETHBridgeAdapter,
            l1Bridge: l1Bridge.address,
            l2Bridge: l2Bridge.address,
          },
        },
1623 1624 1625
      })
    })

1626
    it('should trigger the withdraw ETH function with the given amount', async () => {
1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638
      await expect(messenger.withdrawETH(100000))
        .to.emit(l2Bridge, 'WithdrawalInitiated')
        .withArgs(
          ethers.constants.AddressZero,
          predeploys.OVM_ETH,
          await l2Signer.getAddress(),
          await l2Signer.getAddress(),
          100000,
          '0x'
        )
    })
  })
1639
})