deposit-eth.ts 13.1 KB
Newer Older
1 2
import { promises as fs } from 'fs'

3 4 5
import { task, types } from 'hardhat/config'
import '@nomiclabs/hardhat-ethers'
import 'hardhat-deploy'
6
import { Deployment } from 'hardhat-deploy/types'
7 8 9 10
import {
  predeploys,
  getContractDefinition,
} from '@eth-optimism/contracts-bedrock'
11
import { providers, utils, ethers } from 'ethers'
12

13 14 15 16 17 18 19
import {
  CrossChainMessenger,
  MessageStatus,
  CONTRACT_ADDRESSES,
  OEContractsLike,
  DEFAULT_L2_CONTRACT_ADDRESSES,
} from '../src'
20

21 22
const { formatEther } = utils

23
task('deposit-eth', 'Deposits ether to L2.')
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
  .addParam(
    'l2ProviderUrl',
    'L2 provider URL.',
    'http://localhost:9545',
    types.string
  )
  .addParam(
    'opNodeProviderUrl',
    'op-node provider URL',
    'http://localhost:7545',
    types.string
  )
  .addOptionalParam('to', 'Recipient of the ether', '', types.string)
  .addOptionalParam(
    'amount',
    'Amount of ether to send (in ETH)',
    '',
    types.string
  )
  .addOptionalParam(
    'withdraw',
    'Follow up with a withdrawal',
    true,
    types.boolean
  )
49 50 51 52 53 54
  .addOptionalParam(
    'l1ContractsJsonPath',
    'Path to a JSON with L1 contract addresses in it',
    '',
    types.string
  )
55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71
  .addOptionalParam('withdrawAmount', 'Amount to withdraw', '', types.string)
  .setAction(async (args, hre) => {
    const signers = await hre.ethers.getSigners()
    if (signers.length === 0) {
      throw new Error('No configured signers')
    }
    // Use the first configured signer for simplicity
    const signer = signers[0]
    const address = await signer.getAddress()
    console.log(`Using signer ${address}`)

    // Ensure that the signer has a balance before trying to
    // do anything
    const balance = await signer.getBalance()
    if (balance.eq(0)) {
      throw new Error('Signer has no balance')
    }
72
    console.log(`Signer balance: ${formatEther(balance.toString())}`)
73 74 75 76 77 78 79 80 81 82

    const l2Provider = new providers.StaticJsonRpcProvider(args.l2ProviderUrl)

    // send to self if not specified
    const to = args.to ? args.to : address
    const amount = args.amount
      ? utils.parseEther(args.amount)
      : utils.parseEther('1')
    const withdrawAmount = args.withdrawAmount
      ? utils.parseEther(args.withdrawAmount)
83
      : amount.div(2)
84 85 86 87 88 89

    const l2Signer = new hre.ethers.Wallet(
      hre.network.config.accounts[0],
      l2Provider
    )

90
    const l2ChainId = await l2Signer.getChainId()
91 92 93 94 95 96 97
    let contractAddrs = CONTRACT_ADDRESSES[l2ChainId]
    if (args.l1ContractsJsonPath) {
      const data = await fs.readFile(args.l1ContractsJsonPath)
      contractAddrs = {
        l1: JSON.parse(data.toString()),
        l2: DEFAULT_L2_CONTRACT_ADDRESSES,
      } as OEContractsLike
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
    } else if (!contractAddrs) {
      // If the contract addresses have not been hardcoded,
      // attempt to read them from deployment artifacts
      let Deployment__AddressManager: Deployment
      try {
        Deployment__AddressManager = await hre.deployments.get('AddressManager')
      } catch (e) {
        Deployment__AddressManager = await hre.deployments.get(
          'Lib_AddressManager'
        )
      }
      let Deployment__L1CrossDomainMessenger: Deployment
      try {
        Deployment__L1CrossDomainMessenger = await hre.deployments.get(
          'L1CrossDomainMessengerProxy'
        )
      } catch (e) {
        Deployment__L1CrossDomainMessenger = await hre.deployments.get(
          'Proxy__OVM_L1CrossDomainMessenger'
        )
      }
      let Deployment__L1StandardBridge: Deployment
      try {
        Deployment__L1StandardBridge = await hre.deployments.get(
          'L1StandardBridgeProxy'
        )
      } catch (e) {
        Deployment__L1StandardBridge = await hre.deployments.get(
          'Proxy__OVM_L1StandardBridge'
        )
      }

      const Deployment__OptimismPortal = await hre.deployments.get(
        'OptimismPortalProxy'
      )
      const Deployment__L2OutputOracle = await hre.deployments.get(
        'L2OutputOracleProxy'
      )
      contractAddrs = {
        l1: {
          AddressManager: Deployment__AddressManager.address,
          L1CrossDomainMessenger: Deployment__L1CrossDomainMessenger,
          L1StandardBridge: Deployment__L1StandardBridge,
          StateCommitmentChain: ethers.constants.AddressZero,
          CanonicalTransactionChain: ethers.constants.AddressZero,
          BondManager: ethers.constants.AddressZero,
          OptimismPortal: Deployment__OptimismPortal.address,
          L2OutputOracle: Deployment__L2OutputOracle.address,
        },
        l2: DEFAULT_L2_CONTRACT_ADDRESSES,
      }
149
    }
150 151

    const Artifact__L2ToL1MessagePasser = await getContractDefinition(
152 153 154
      'L2ToL1MessagePasser'
    )

155
    const Artifact__L2CrossDomainMessenger = await getContractDefinition(
156 157 158
      'L2CrossDomainMessenger'
    )

159
    const Artifact__L2StandardBridge = await getContractDefinition(
160 161 162
      'L2StandardBridge'
    )

163
    const Artifact__OptimismPortal = await getContractDefinition(
164 165 166
      'OptimismPortal'
    )

167
    const Artifact__L1CrossDomainMessenger = await getContractDefinition(
168 169 170
      'L1CrossDomainMessenger'
    )

171
    const Artifact__L1StandardBridge = await getContractDefinition(
172 173 174 175
      'L1StandardBridge'
    )

    const OptimismPortal = new hre.ethers.Contract(
176 177
      contractAddrs.l1.OptimismPortal,
      Artifact__OptimismPortal.abi,
178 179 180 181
      signer
    )

    const L1CrossDomainMessenger = new hre.ethers.Contract(
182 183
      contractAddrs.l1.L1CrossDomainMessenger,
      Artifact__L1CrossDomainMessenger.abi,
184 185 186 187
      signer
    )

    const L1StandardBridge = new hre.ethers.Contract(
188 189
      contractAddrs.l1.L1StandardBridge,
      Artifact__L1StandardBridge.abi,
190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211
      signer
    )

    const L2ToL1MessagePasser = new hre.ethers.Contract(
      predeploys.L2ToL1MessagePasser,
      Artifact__L2ToL1MessagePasser.abi
    )

    const L2CrossDomainMessenger = new hre.ethers.Contract(
      predeploys.L2CrossDomainMessenger,
      Artifact__L2CrossDomainMessenger.abi
    )

    const L2StandardBridge = new hre.ethers.Contract(
      predeploys.L2StandardBridge,
      Artifact__L2StandardBridge.abi
    )

    const messenger = new CrossChainMessenger({
      l1SignerOrProvider: signer,
      l2SignerOrProvider: l2Signer,
      l1ChainId: await signer.getChainId(),
212
      l2ChainId,
213
      bedrock: true,
214
      contracts: contractAddrs,
215 216 217 218 219 220
    })

    const opBalanceBefore = await signer.provider.getBalance(
      OptimismPortal.address
    )

221 222 223 224
    const l1BridgeBalanceBefore = await signer.provider.getBalance(
      L1StandardBridge.address
    )

225 226
    // Deposit ETH
    console.log('Depositing ETH through StandardBridge')
227
    console.log(`Sending ${formatEther(amount)} ether`)
228
    const ethDeposit = await messenger.depositETH(amount, { recipient: to })
229
    console.log(`Transaction hash: ${ethDeposit.hash}`)
230 231 232 233 234 235 236
    const depositMessageReceipt = await messenger.waitForMessageReceipt(
      ethDeposit
    )
    if (depositMessageReceipt.receiptStatus !== 1) {
      throw new Error('deposit failed')
    }
    console.log(
237
      `Deposit complete - included in block ${depositMessageReceipt.transactionReceipt.blockNumber}`
238 239 240 241 242 243
    )

    const opBalanceAfter = await signer.provider.getBalance(
      OptimismPortal.address
    )

244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260
    const l1BridgeBalanceAfter = await signer.provider.getBalance(
      L1StandardBridge.address
    )

    console.log(
      `L1StandardBridge balance before: ${formatEther(l1BridgeBalanceBefore)}`
    )

    console.log(
      `L1StandardBridge balance after: ${formatEther(l1BridgeBalanceAfter)}`
    )

    console.log(
      `OptimismPortal balance before: ${formatEther(opBalanceBefore)}`
    )
    console.log(`OptimismPortal balance after: ${formatEther(opBalanceAfter)}`)

261 262 263 264
    if (!opBalanceBefore.add(amount).eq(opBalanceAfter)) {
      throw new Error(`OptimismPortal balance mismatch`)
    }

265 266 267 268 269 270 271
    const l2Balance = await l2Provider.getBalance(to)
    console.log(
      `L2 balance of deposit recipient: ${utils.formatEther(
        l2Balance.toString()
      )}`
    )

272 273 274 275 276 277
    if (!args.withdraw) {
      return
    }

    console.log('Withdrawing ETH')
    const ethWithdraw = await messenger.withdrawETH(withdrawAmount)
278
    console.log(`Transaction hash: ${ethWithdraw.hash}`)
279
    const ethWithdrawReceipt = await ethWithdraw.wait()
280 281 282
    console.log(
      `ETH withdrawn on L2 - included in block ${ethWithdrawReceipt.blockNumber}`
    )
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

    {
      // check the logs
      for (const log of ethWithdrawReceipt.logs) {
        switch (log.address) {
          case L2ToL1MessagePasser.address: {
            const parsed = L2ToL1MessagePasser.interface.parseLog(log)
            console.log(parsed.name)
            console.log(parsed.args)
            console.log()
            break
          }
          case L2StandardBridge.address: {
            const parsed = L2StandardBridge.interface.parseLog(log)
            console.log(parsed.name)
            console.log(parsed.args)
            console.log()
            break
          }
          case L2CrossDomainMessenger.address: {
            const parsed = L2CrossDomainMessenger.interface.parseLog(log)
            console.log(parsed.name)
            console.log(parsed.args)
            console.log()
            break
          }
          default: {
            console.log(`Unknown log from ${log.address} - ${log.topics[0]}`)
          }
        }
      }
    }

316
    console.log('Waiting to be able to prove withdrawal')
317

318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333
    const proveInterval = setInterval(async () => {
      const currentStatus = await messenger.getMessageStatus(ethWithdrawReceipt)
      console.log(`Message status: ${MessageStatus[currentStatus]}`)
    }, 3000)

    try {
      await messenger.waitForMessageStatus(
        ethWithdrawReceipt,
        MessageStatus.READY_TO_PROVE
      )
    } finally {
      clearInterval(proveInterval)
    }

    console.log('Proving eth withdrawal...')
    const ethProve = await messenger.proveMessage(ethWithdrawReceipt)
334
    console.log(`Transaction hash: ${ethProve.hash}`)
335 336 337 338
    const ethProveReceipt = await ethProve.wait()
    if (ethProveReceipt.status !== 1) {
      throw new Error('Prove withdrawal transaction reverted')
    }
339
    console.log('Successfully proved withdrawal')
340 341

    console.log('Waiting to be able to finalize withdrawal')
342

343
    const finalizeInterval = setInterval(async () => {
344 345 346 347
      const currentStatus = await messenger.getMessageStatus(ethWithdrawReceipt)
      console.log(`Message status: ${MessageStatus[currentStatus]}`)
    }, 3000)

348 349 350 351 352 353
    try {
      await messenger.waitForMessageStatus(
        ethWithdrawReceipt,
        MessageStatus.READY_FOR_RELAY
      )
    } finally {
354
      clearInterval(finalizeInterval)
355
    }
356

357
    console.log('Finalizing eth withdrawal...')
358
    const ethFinalize = await messenger.finalizeMessage(ethWithdrawReceipt)
359
    console.log(`Transaction hash: ${ethFinalize.hash}`)
360 361 362 363 364 365
    const ethFinalizeReceipt = await ethFinalize.wait()
    if (ethFinalizeReceipt.status !== 1) {
      throw new Error('Finalize withdrawal reverted')
    }

    console.log(
366
      `ETH withdrawal complete - included in block ${ethFinalizeReceipt.blockNumber}`
367 368 369 370 371 372 373 374 375 376
    )
    {
      // Check that the logs are correct
      for (const log of ethFinalizeReceipt.logs) {
        switch (log.address) {
          case L1StandardBridge.address: {
            const parsed = L1StandardBridge.interface.parseLog(log)
            console.log(parsed.name)
            console.log(parsed.args)
            console.log()
377 378 379 380
            if (
              parsed.name !== 'ETHBridgeFinalized' &&
              parsed.name !== 'ETHWithdrawalFinalized'
            ) {
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
              throw new Error('Wrong event name from L1StandardBridge')
            }
            if (!parsed.args.amount.eq(withdrawAmount)) {
              throw new Error('Wrong amount in event')
            }
            if (parsed.args.from !== address) {
              throw new Error('Wrong to in event')
            }
            if (parsed.args.to !== address) {
              throw new Error('Wrong from in event')
            }
            break
          }
          case L1CrossDomainMessenger.address: {
            const parsed = L1CrossDomainMessenger.interface.parseLog(log)
            console.log(parsed.name)
            console.log(parsed.args)
            console.log()
            if (parsed.name !== 'RelayedMessage') {
              throw new Error('Wrong event from L1CrossDomainMessenger')
            }
            break
          }
          case OptimismPortal.address: {
            const parsed = OptimismPortal.interface.parseLog(log)
            console.log(parsed.name)
            console.log(parsed.args)
            console.log()
            // TODO: remove this if check
            if (parsed.name === 'WithdrawalFinalized') {
              if (parsed.args.success !== true) {
                throw new Error('Unsuccessful withdrawal call')
              }
            }
            break
          }
          default: {
            console.log(`Unknown log from ${log.address} - ${log.topics[0]}`)
          }
        }
      }
    }

    const opBalanceFinally = await signer.provider.getBalance(
      OptimismPortal.address
    )
427 428 429

    if (!opBalanceFinally.add(withdrawAmount).eq(opBalanceAfter)) {
      throw new Error('OptimismPortal balance mismatch')
430 431 432
    }
    console.log('Withdraw success')
  })