L2ERC721Bridge.spec.ts 13.5 KB
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
/* Imports */
import { ethers } from 'hardhat'
import { Signer, ContractFactory, Contract, constants } from 'ethers'
import { smock, FakeContract } from '@defi-wonderland/smock'
import ICrossDomainMessenger from '@eth-optimism/contracts/artifacts/contracts/libraries/bridge/ICrossDomainMessenger.sol/ICrossDomainMessenger.json'
import { toRpcHexString } from '@eth-optimism/core-utils'

import { NON_NULL_BYTES32, NON_ZERO_ADDRESS } from '../../helpers'
import { expect } from '../../setup'

const ERR_ALREADY_INITIALIZED = 'Initializable: contract is already initialized'
const ERR_INVALID_MESSENGER = 'OVM_XCHAIN: messenger contract unauthenticated'
const ERR_INVALID_X_DOMAIN_MSG_SENDER =
  'OVM_XCHAIN: wrong sender of cross-domain message'
const DUMMY_L1BRIDGE_ADDRESS: string =
  '0x1234123412341234123412341234123412341234'
const DUMMY_L1ERC721_ADDRESS: string =
  '0x2234223412342234223422342234223422342234'
const ERR_INVALID_WITHDRAWAL: string =
  'Withdrawal is not being initiated by NFT owner'
const TOKEN_ID: number = 10

describe('L2ERC721Bridge', () => {
  let alice: Signer
  let aliceAddress: string
  let bob: Signer
  let bobsAddress: string
  let l2MessengerImpersonator: Signer
  let Factory__L1ERC721Bridge: ContractFactory

  before(async () => {
    // Create a special signer which will enable us to send messages from the L2Messenger contract
    ;[l2MessengerImpersonator, alice, bob] = await ethers.getSigners()
    aliceAddress = await alice.getAddress()
    bobsAddress = await bob.getAddress()
    Factory__L1ERC721Bridge = await ethers.getContractFactory('L1ERC721Bridge')
  })

  let L2ERC721Bridge: Contract
  let L2ERC721: Contract
  let Fake__L2CrossDomainMessenger: FakeContract
  beforeEach(async () => {
    // Get a new fake L2 messenger
    Fake__L2CrossDomainMessenger = await smock.fake<Contract>(
      new ethers.utils.Interface(ICrossDomainMessenger.abi),
      // This allows us to use an ethers override {from: Fake__L2CrossDomainMessenger.address} to mock calls
      { address: await l2MessengerImpersonator.getAddress() }
    )

    // Deploy the contract under test
    L2ERC721Bridge = await (
      await ethers.getContractFactory('L2ERC721Bridge')
    ).deploy(Fake__L2CrossDomainMessenger.address, DUMMY_L1BRIDGE_ADDRESS)

    // Deploy an L2 ERC721
    L2ERC721 = await (
      await ethers.getContractFactory('OptimismMintableERC721')
    ).deploy(
      L2ERC721Bridge.address,
      100,
      DUMMY_L1ERC721_ADDRESS,
      'L2Token',
      'L2T',
      { gasLimit: 4_000_000 } // Necessary to avoid an out-of-gas error
    )
  })

  describe('initialize', () => {
    it('Should only be callable once', async () => {
      await expect(
        L2ERC721Bridge.initialize(
          Fake__L2CrossDomainMessenger.address,
          DUMMY_L1BRIDGE_ADDRESS
        )
      ).to.be.revertedWith(ERR_ALREADY_INITIALIZED)
    })
  })

  // test the transfer flow of moving a token from L1 to L2
  describe('finalizeBridgeERC721', () => {
    it('onlyFromCrossDomainAccount: should revert on calls from a non-crossDomainMessenger L2 account', async () => {
      await expect(
        L2ERC721Bridge.connect(alice).finalizeBridgeERC721(
          DUMMY_L1ERC721_ADDRESS,
          NON_ZERO_ADDRESS,
          NON_ZERO_ADDRESS,
          NON_ZERO_ADDRESS,
          TOKEN_ID,
          NON_NULL_BYTES32
        )
      ).to.be.revertedWith(ERR_INVALID_MESSENGER)
    })

    it('onlyFromCrossDomainAccount: should revert on calls from the right crossDomainMessenger, but wrong xDomainMessageSender (ie. not the L1ERC721Bridge)', async () => {
      Fake__L2CrossDomainMessenger.xDomainMessageSender.returns(
        NON_ZERO_ADDRESS
      )

      await expect(
        L2ERC721Bridge.connect(l2MessengerImpersonator).finalizeBridgeERC721(
          DUMMY_L1ERC721_ADDRESS,
          NON_ZERO_ADDRESS,
          NON_ZERO_ADDRESS,
          NON_ZERO_ADDRESS,
          TOKEN_ID,
          NON_NULL_BYTES32,
          {
            from: Fake__L2CrossDomainMessenger.address,
          }
        )
      ).to.be.revertedWith(ERR_INVALID_X_DOMAIN_MSG_SENDER)
    })

    it('should initialize a withdrawal if the L2 token is not compliant', async () => {
      // Deploy a non compliant ERC721
      const NonCompliantERC721 = await (
        await ethers.getContractFactory(
          '@openzeppelin/contracts/token/ERC721/ERC721.sol:ERC721'
        )
      ).deploy('L2Token', 'L2T')

      Fake__L2CrossDomainMessenger.xDomainMessageSender.returns(
        DUMMY_L1BRIDGE_ADDRESS
      )

      // A failed attempt to finalize the deposit causes an ERC721BridgeFailed event to be emitted.
      await expect(
        L2ERC721Bridge.connect(l2MessengerImpersonator).finalizeBridgeERC721(
          NonCompliantERC721.address,
          DUMMY_L1ERC721_ADDRESS,
          aliceAddress,
          bobsAddress,
          TOKEN_ID,
          NON_NULL_BYTES32,
          {
            from: Fake__L2CrossDomainMessenger.address,
          }
        )
      )
        .to.emit(L2ERC721Bridge, 'ERC721BridgeFailed')
        .withArgs(
          NonCompliantERC721.address,
          DUMMY_L1ERC721_ADDRESS,
          aliceAddress,
          bobsAddress,
          TOKEN_ID,
          NON_NULL_BYTES32
        )

      const withdrawalCallToMessenger =
        Fake__L2CrossDomainMessenger.sendMessage.getCall(0)

      expect(withdrawalCallToMessenger.args[0]).to.equal(DUMMY_L1BRIDGE_ADDRESS)
      expect(withdrawalCallToMessenger.args[1]).to.equal(
        Factory__L1ERC721Bridge.interface.encodeFunctionData(
          'finalizeBridgeERC721',
          [
            DUMMY_L1ERC721_ADDRESS,
            NonCompliantERC721.address,
            bobsAddress,
            aliceAddress,
            TOKEN_ID,
            NON_NULL_BYTES32,
          ]
        )
      )
      expect(withdrawalCallToMessenger.args[2]).to.equal(0)
    })

    it('should credit funds to the depositor', async () => {
      Fake__L2CrossDomainMessenger.xDomainMessageSender.returns(
        DUMMY_L1BRIDGE_ADDRESS
      )

      // Assert that nobody owns the L2 token initially
      await expect(L2ERC721.ownerOf(TOKEN_ID)).to.be.revertedWith(
        'ERC721: owner query for nonexistent token'
      )

      // Successfully finalizes the deposit.
      const expectedResult = expect(
        L2ERC721Bridge.connect(l2MessengerImpersonator).finalizeBridgeERC721(
          L2ERC721.address,
          DUMMY_L1ERC721_ADDRESS,
          aliceAddress,
          bobsAddress,
          TOKEN_ID,
          NON_NULL_BYTES32,
          {
            from: Fake__L2CrossDomainMessenger.address,
          }
        )
      )

      // Depositing causes an ERC721BridgeFinalized event to be emitted.
      await expectedResult.to
        .emit(L2ERC721Bridge, 'ERC721BridgeFinalized')
        .withArgs(
          L2ERC721.address,
          DUMMY_L1ERC721_ADDRESS,
          aliceAddress,
          bobsAddress,
          TOKEN_ID,
          NON_NULL_BYTES32
        )

      // Causes a Transfer event to be emitted from the L2 ERC721.
      await expectedResult.to
        .emit(L2ERC721, 'Transfer')
        .withArgs(constants.AddressZero, bobsAddress, TOKEN_ID)

      // Bob is now the owner of the L2 ERC721
      const tokenIdOwner = await L2ERC721.ownerOf(TOKEN_ID)
      tokenIdOwner.should.equal(bobsAddress)
    })
  })

  describe('withdrawals', () => {
    let L2Token: Contract
    beforeEach(async () => {
      L2Token = await (
        await ethers.getContractFactory('OptimismMintableERC721')
      ).deploy(
        L2ERC721Bridge.address,
        100,
        DUMMY_L1ERC721_ADDRESS,
        'L2Token',
        'L2T'
      )

      await ethers.provider.send('hardhat_impersonateAccount', [
        L2ERC721Bridge.address,
      ])

      await ethers.provider.send('hardhat_setBalance', [
        L2ERC721Bridge.address,
        toRpcHexString(ethers.utils.parseEther('1')),
      ])

      const signer = await ethers.getSigner(L2ERC721Bridge.address)
      await L2Token.connect(signer).mint(aliceAddress, TOKEN_ID)
    })

    it('bridgeERC721() reverts when called by non-owner of nft', async () => {
      await expect(
        L2ERC721Bridge.connect(bob).bridgeERC721(
          L2Token.address,
          DUMMY_L1ERC721_ADDRESS,
          TOKEN_ID,
          0,
          NON_NULL_BYTES32
        )
      ).to.be.revertedWith(ERR_INVALID_WITHDRAWAL)
    })

    it('bridgeERC721() reverts if called by a contract', async () => {
      await expect(
        L2ERC721Bridge.connect(l2MessengerImpersonator).bridgeERC721(
          L2Token.address,
          DUMMY_L1ERC721_ADDRESS,
          TOKEN_ID,
          0,
          NON_NULL_BYTES32
        )
      ).to.be.revertedWith('L2ERC721Bridge: account is not externally owned')
    })

    it('bridgeERC721() burns and sends the correct withdrawal message', async () => {
      // Make sure that alice begins as the NFT owner
      expect(await L2Token.ownerOf(TOKEN_ID)).to.equal(aliceAddress)

      // Initiates a successful withdrawal.
      const expectedResult = expect(
        L2ERC721Bridge.connect(alice).bridgeERC721(
          L2Token.address,
          DUMMY_L1ERC721_ADDRESS,
          TOKEN_ID,
          0,
          NON_NULL_BYTES32
        )
      )

      // A successful withdrawal causes an ERC721BridgeInitiated event to be emitted from the L2 ERC721 Bridge.
      await expectedResult.to
        .emit(L2ERC721Bridge, 'ERC721BridgeInitiated')
        .withArgs(
          L2Token.address,
          DUMMY_L1ERC721_ADDRESS,
          aliceAddress,
          aliceAddress,
          TOKEN_ID,
          NON_NULL_BYTES32
        )

      // A withdrawal also causes a Transfer event to be emitted the L2 ERC721, signifying that the L2 token
      // has been burnt.
      await expectedResult.to
        .emit(L2Token, 'Transfer')
        .withArgs(aliceAddress, constants.AddressZero, TOKEN_ID)

      // Assert Alice's balance went down
      const aliceBalance = await L2Token.balanceOf(aliceAddress)
      expect(aliceBalance).to.equal(0)

      // Assert that the token isn't owned by anyone
      await expect(L2Token.ownerOf(TOKEN_ID)).to.be.revertedWith(
        'ERC721: owner query for nonexistent token'
      )

      const withdrawalCallToMessenger =
        Fake__L2CrossDomainMessenger.sendMessage.getCall(0)

      // Assert the correct cross-chain call was sent:
      // Message should be sent to the L1ERC721Bridge on L1
      expect(withdrawalCallToMessenger.args[0]).to.equal(DUMMY_L1BRIDGE_ADDRESS)
      // Message data should be a call telling the L1ERC721Bridge to finalize the withdrawal
      expect(withdrawalCallToMessenger.args[1]).to.equal(
        Factory__L1ERC721Bridge.interface.encodeFunctionData(
          'finalizeBridgeERC721',
          [
            DUMMY_L1ERC721_ADDRESS,
            L2Token.address,
            aliceAddress,
            aliceAddress,
            TOKEN_ID,
            NON_NULL_BYTES32,
          ]
        )
      )
      // gaslimit should be correct
      expect(withdrawalCallToMessenger.args[2]).to.equal(0)
    })

    it('bridgeERC721To() reverts when called by non-owner of nft', async () => {
      await expect(
        L2ERC721Bridge.connect(bob).bridgeERC721To(
          L2Token.address,
          DUMMY_L1ERC721_ADDRESS,
          bobsAddress,
          TOKEN_ID,
          0,
          NON_NULL_BYTES32
        )
      ).to.be.revertedWith(ERR_INVALID_WITHDRAWAL)
    })

    it('bridgeERC721To() burns and sends the correct withdrawal message', async () => {
      // Make sure that alice begins as the NFT owner
      expect(await L2Token.ownerOf(TOKEN_ID)).to.equal(aliceAddress)

      // Initiates a successful withdrawal.
      const expectedResult = expect(
        L2ERC721Bridge.connect(alice).bridgeERC721To(
          L2Token.address,
          DUMMY_L1ERC721_ADDRESS,
          bobsAddress,
          TOKEN_ID,
          0,
          NON_NULL_BYTES32
        )
      )

      // A successful withdrawal causes an ERC721BridgeInitiated event to be emitted from the L2 ERC721 Bridge.
      await expectedResult.to
        .emit(L2ERC721Bridge, 'ERC721BridgeInitiated')
        .withArgs(
          L2Token.address,
          DUMMY_L1ERC721_ADDRESS,
          aliceAddress,
          bobsAddress,
          TOKEN_ID,
          NON_NULL_BYTES32
        )

      // A withdrawal also causes a Transfer event to be emitted the L2 ERC721, signifying that the L2 token
      // has been burnt.
      await expectedResult.to
        .emit(L2Token, 'Transfer')
        .withArgs(aliceAddress, constants.AddressZero, TOKEN_ID)

      // Assert Alice's balance went down
      const aliceBalance = await L2Token.balanceOf(aliceAddress)
      expect(aliceBalance).to.equal(0)

      // Assert that the token isn't owned by anyone
      await expect(L2Token.ownerOf(TOKEN_ID)).to.be.revertedWith(
        'ERC721: owner query for nonexistent token'
      )

      const withdrawalCallToMessenger =
        Fake__L2CrossDomainMessenger.sendMessage.getCall(0)

      // Assert the correct cross-chain call was sent.
      // Message should be sent to the L1ERC721Bridge on L1
      expect(withdrawalCallToMessenger.args[0]).to.equal(DUMMY_L1BRIDGE_ADDRESS)
      // The message data should be a call telling the L1ERC721Bridge to finalize the withdrawal
      expect(withdrawalCallToMessenger.args[1]).to.equal(
        Factory__L1ERC721Bridge.interface.encodeFunctionData(
          'finalizeBridgeERC721',
          [
            DUMMY_L1ERC721_ADDRESS,
            L2Token.address,
            aliceAddress,
            bobsAddress,
            TOKEN_ID,
            NON_NULL_BYTES32,
          ]
        )
      )
      // gas value is ignored and set to 0.
      expect(withdrawalCallToMessenger.args[2]).to.equal(0)
    })
  })
})