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

3 4 5 6
import { task, types } from 'hardhat/config'
import { HardhatRuntimeEnvironment } from 'hardhat/types'
import '@nomiclabs/hardhat-ethers'
import 'hardhat-deploy'
Kelvin Fichter's avatar
Kelvin Fichter committed
7
import { Event, Contract, Wallet, providers, utils } from 'ethers'
8 9 10 11
import {
  predeploys,
  getContractDefinition,
} from '@eth-optimism/contracts-bedrock'
Kelvin Fichter's avatar
Kelvin Fichter committed
12
import { sleep } from '@eth-optimism/core-utils'
13

14 15 16 17 18 19 20
import {
  CrossChainMessenger,
  MessageStatus,
  CONTRACT_ADDRESSES,
  OEContractsLike,
  DEFAULT_L2_CONTRACT_ADDRESSES,
} from '../src'
21 22 23 24 25 26 27 28

const deployWETH9 = async (
  hre: HardhatRuntimeEnvironment,
  wrap: boolean
): Promise<Contract> => {
  const signers = await hre.ethers.getSigners()
  const signer = signers[0]

29
  const Artifact__WETH9 = await getContractDefinition('WETH9')
30 31 32 33 34 35
  const Factory__WETH9 = new hre.ethers.ContractFactory(
    Artifact__WETH9.abi,
    Artifact__WETH9.bytecode,
    signer
  )

36
  console.log('Sending deployment transaction')
37
  const WETH9 = await Factory__WETH9.deploy()
38 39
  const receipt = await WETH9.deployTransaction.wait()
  console.log(`WETH9 deployed: ${receipt.transactionHash}`)
40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56

  if (wrap) {
    const deposit = await signer.sendTransaction({
      value: utils.parseEther('1'),
      to: WETH9.address,
    })
    await deposit.wait()
  }

  return WETH9
}

const createOptimismMintableERC20 = async (
  hre: HardhatRuntimeEnvironment,
  L1ERC20: Contract,
  l2Signer: Wallet
): Promise<Contract> => {
57 58 59
  const Artifact__OptimismMintableERC20Token = await getContractDefinition(
    'OptimismMintableERC20'
  )
60

61 62
  const Artifact__OptimismMintableERC20TokenFactory =
    await getContractDefinition('OptimismMintableERC20Factory')
63

64
  const OptimismMintableERC20TokenFactory = new Contract(
65
    predeploys.OptimismMintableERC20Factory,
66
    Artifact__OptimismMintableERC20TokenFactory.abi,
67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88
    l2Signer
  )

  const name = await L1ERC20.name()
  const symbol = await L1ERC20.symbol()

  const tx =
    await OptimismMintableERC20TokenFactory.createOptimismMintableERC20(
      L1ERC20.address,
      `L2 ${name}`,
      `L2-${symbol}`
    )

  const receipt = await tx.wait()
  const event = receipt.events.find(
    (e: Event) => e.event === 'OptimismMintableERC20Created'
  )

  if (!event) {
    throw new Error('Unable to find OptimismMintableERC20Created event')
  }

89
  const l2WethAddress = event.args.localToken
90 91
  console.log(`Deployed to ${l2WethAddress}`)

92
  return new Contract(
93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115
    l2WethAddress,
    Artifact__OptimismMintableERC20Token.abi,
    l2Signer
  )
}

// TODO(tynes): this task could be modularized in the future
// so that it can deposit an arbitrary token. Right now it
// deploys a WETH9 contract, mints some WETH9 and then
// deposits that into L2 through the StandardBridge.
task('deposit-erc20', 'Deposits WETH9 onto L2.')
  .addParam(
    'l2ProviderUrl',
    'L2 provider URL.',
    'http://localhost:9545',
    types.string
  )
  .addParam(
    'opNodeProviderUrl',
    'op-node provider URL',
    'http://localhost:7545',
    types.string
  )
116 117 118 119 120 121
  .addOptionalParam(
    'l1ContractsJsonPath',
    'Path to a JSON with L1 contract addresses in it',
    '',
    types.string
  )
122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145
  .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')
    }

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

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

146
    const l2ChainId = await l2Signer.getChainId()
147 148 149 150 151 152 153 154
    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
    }
155

156
    const Artifact__L2ToL1MessagePasser = await getContractDefinition(
157 158 159
      'L2ToL1MessagePasser'
    )

160
    const Artifact__L2CrossDomainMessenger = await getContractDefinition(
161 162 163
      'L2CrossDomainMessenger'
    )

164
    const Artifact__L2StandardBridge = await getContractDefinition(
165 166 167
      'L2StandardBridge'
    )

168
    const Artifact__OptimismPortal = await getContractDefinition(
169 170 171
      'OptimismPortal'
    )

172
    const Artifact__L1CrossDomainMessenger = await getContractDefinition(
173 174 175
      'L1CrossDomainMessenger'
    )

176
    const Artifact__L1StandardBridge = await getContractDefinition(
177 178 179 180
      'L1StandardBridge'
    )

    const OptimismPortal = new hre.ethers.Contract(
181 182
      contractAddrs.l1.OptimismPortal,
      Artifact__OptimismPortal.abi,
183 184 185 186
      signer
    )

    const L1CrossDomainMessenger = new hre.ethers.Contract(
187 188
      contractAddrs.l1.L1CrossDomainMessenger,
      Artifact__L1CrossDomainMessenger.abi,
189 190 191 192
      signer
    )

    const L1StandardBridge = new hre.ethers.Contract(
193 194
      contractAddrs.l1.L1StandardBridge,
      Artifact__L1StandardBridge.abi,
195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216
      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(),
217
      l2ChainId,
218
      bedrock: true,
219
      contracts: contractAddrs,
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
    })

    console.log('Deploying WETH9 to L1')
    const WETH9 = await deployWETH9(hre, true)
    console.log(`Deployed to ${WETH9.address}`)

    console.log('Creating L2 WETH9')
    const OptimismMintableERC20 = await createOptimismMintableERC20(
      hre,
      WETH9,
      l2Signer
    )

    console.log(`Approving WETH9 for deposit`)
    const approvalTx = await messenger.approveERC20(
      WETH9.address,
      OptimismMintableERC20.address,
      hre.ethers.constants.MaxUint256
    )
    await approvalTx.wait()
    console.log('WETH9 approved')

    console.log('Depositing WETH9 to L2')
    const depositTx = await messenger.depositERC20(
      WETH9.address,
      OptimismMintableERC20.address,
      utils.parseEther('1')
    )
    await depositTx.wait()
    console.log(`ERC20 deposited - ${depositTx.hash}`)

251
    // Deposit might get reorged, wait 30s and also log for reorgs.
252
    let prevBlockHash: string = ''
253
    for (let i = 0; i < 30; i++) {
Kelvin Fichter's avatar
Kelvin Fichter committed
254 255
      const messageReceipt = await messenger.waitForMessageReceipt(depositTx)
      if (messageReceipt.receiptStatus !== 1) {
256
        console.log(`Deposit failed, retrying...`)
Kelvin Fichter's avatar
Kelvin Fichter committed
257 258
      }

259 260 261 262
      if (
        prevBlockHash !== '' &&
        messageReceipt.transactionReceipt.blockHash !== prevBlockHash
      ) {
Kelvin Fichter's avatar
Kelvin Fichter committed
263
        console.log(
264
          `Block hash changed from ${prevBlockHash} to ${messageReceipt.transactionReceipt.blockHash}`
Kelvin Fichter's avatar
Kelvin Fichter committed
265
        )
266 267 268

        // Wait for stability, we want at least 30 seconds after any reorg
        i = 0
Kelvin Fichter's avatar
Kelvin Fichter committed
269 270
      }

271
      prevBlockHash = messageReceipt.transactionReceipt.blockHash
Kelvin Fichter's avatar
Kelvin Fichter committed
272
      await sleep(1000)
273
    }
Kelvin Fichter's avatar
Kelvin Fichter committed
274

275 276 277
    const l2Balance = await OptimismMintableERC20.balanceOf(address)
    if (l2Balance.lt(utils.parseEther('1'))) {
      throw new Error('bad deposit')
278
    }
279
    console.log(`Deposit success`)
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

    console.log('Starting withdrawal')
    const preBalance = await WETH9.balanceOf(signer.address)
    const withdraw = await messenger.withdrawERC20(
      WETH9.address,
      OptimismMintableERC20.address,
      utils.parseEther('1')
    )
    const withdrawalReceipt = await withdraw.wait()
    for (const log of withdrawalReceipt.logs) {
      switch (log.address) {
        case L2ToL1MessagePasser.address: {
          const parsed = L2ToL1MessagePasser.interface.parseLog(log)
          console.log(`Log ${parsed.name} from ${log.address}`)
          console.log(parsed.args)
          console.log()
          break
        }
        case L2StandardBridge.address: {
          const parsed = L2StandardBridge.interface.parseLog(log)
          console.log(`Log ${parsed.name} from ${log.address}`)
          console.log(parsed.args)
          console.log()
          break
        }
        case L2CrossDomainMessenger.address: {
          const parsed = L2CrossDomainMessenger.interface.parseLog(log)
          console.log(`Log ${parsed.name} from ${log.address}`)
          console.log(parsed.args)
          console.log()
          break
        }
        default: {
          console.log(`Unknown log from ${log.address} - ${log.topics[0]}`)
        }
      }
    }

    setInterval(async () => {
      const currentStatus = await messenger.getMessageStatus(withdraw)
      console.log(`Message status: ${MessageStatus[currentStatus]}`)
    }, 3000)

    const now = Math.floor(Date.now() / 1000)

325 326 327 328 329 330 331 332 333 334 335
    console.log('Waiting for message to be able to be proved')
    await messenger.waitForMessageStatus(withdraw, MessageStatus.READY_TO_PROVE)

    console.log('Proving withdrawal...')
    const prove = await messenger.proveMessage(withdraw)
    const proveReceipt = await prove.wait()
    console.log(proveReceipt)
    if (proveReceipt.status !== 1) {
      throw new Error('Prove withdrawal transaction reverted')
    }

336 337 338 339 340 341
    console.log('Waiting for message to be able to be relayed')
    await messenger.waitForMessageStatus(
      withdraw,
      MessageStatus.READY_FOR_RELAY
    )

342
    console.log('Finalizing withdrawal...')
343
    const finalize = await messenger.finalizeMessage(withdraw)
344
    const finalizeReceipt = await finalize.wait()
345 346
    console.log(`Took ${Math.floor(Date.now() / 1000) - now} seconds`)

347
    for (const log of finalizeReceipt.logs) {
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
      switch (log.address) {
        case OptimismPortal.address: {
          const parsed = OptimismPortal.interface.parseLog(log)
          console.log(`Log ${parsed.name} from ${log.address}`)
          console.log(parsed.args)
          console.log()
          break
        }
        case L1CrossDomainMessenger.address: {
          const parsed = L1CrossDomainMessenger.interface.parseLog(log)
          console.log(`Log ${parsed.name} from ${log.address}`)
          console.log(parsed.args)
          console.log()
          break
        }
        case L1StandardBridge.address: {
          const parsed = L1StandardBridge.interface.parseLog(log)
          console.log(`Log ${parsed.name} from ${log.address}`)
          console.log(parsed.args)
          console.log()
          break
        }
        default:
          console.log(
            `Unknown log emitted from ${log.address} - ${log.topics[0]}`
          )
      }
    }

    const postBalance = await WETH9.balanceOf(signer.address)

    const expectedBalance = preBalance.add(utils.parseEther('1'))
    if (!expectedBalance.eq(postBalance)) {
      throw new Error('Balance mismatch')
    }
    console.log('Withdrawal success')
  })