|
| 1 | +import { loadEnv, CLIArgs, CLIEnvironment } from '../../env' |
| 2 | +import { logger } from '../../logging' |
| 3 | +import { getAddressBook } from '../../address-book' |
| 4 | +import { getProvider, sendTransaction, toGRT } from '../../network' |
| 5 | +import { chainIdIsL2 } from '../../utils' |
| 6 | +import { loadAddressBookContract } from '../../contracts' |
| 7 | +import { |
| 8 | + L2TransactionReceipt, |
| 9 | + getL2Network, |
| 10 | + L2ToL1MessageStatus, |
| 11 | + L2ToL1MessageWriter, |
| 12 | +} from '@arbitrum/sdk' |
| 13 | +import { L2GraphTokenGateway } from '../../../build/types/L2GraphTokenGateway' |
| 14 | +import { BigNumber } from 'ethers' |
| 15 | +import { JsonRpcProvider } from '@ethersproject/providers' |
| 16 | + |
| 17 | +const FOURTEEN_DAYS_IN_SECONDS = 24 * 3600 * 14 |
| 18 | + |
| 19 | +const BLOCK_SEARCH_THRESHOLD = 6 * 3600 |
| 20 | +const searchForArbBlockByTimestamp = async ( |
| 21 | + l2Provider: JsonRpcProvider, |
| 22 | + timestamp: number, |
| 23 | +): Promise<number> => { |
| 24 | + let step = 131072 |
| 25 | + let block = await l2Provider.getBlock('latest') |
| 26 | + while (block.timestamp > timestamp) { |
| 27 | + while (block.number - step < 0) { |
| 28 | + step = Math.round(step / 2) |
| 29 | + } |
| 30 | + block = await l2Provider.getBlock(block.number - step) |
| 31 | + } |
| 32 | + while (step > 1 && Math.abs(block.timestamp - timestamp) > BLOCK_SEARCH_THRESHOLD) { |
| 33 | + step = Math.round(step / 2) |
| 34 | + if (block.timestamp - timestamp > 0) { |
| 35 | + block = await l2Provider.getBlock(block.number - step) |
| 36 | + } else { |
| 37 | + block = await l2Provider.getBlock(block.number + step) |
| 38 | + } |
| 39 | + } |
| 40 | + return block.number |
| 41 | +} |
| 42 | + |
| 43 | +const wait = (ms: number): Promise<void> => { |
| 44 | + return new Promise((res) => setTimeout(res, ms)) |
| 45 | +} |
| 46 | + |
| 47 | +const waitUntilOutboxEntryCreatedWithCb = async ( |
| 48 | + msg: L2ToL1MessageWriter, |
| 49 | + retryDelay: number, |
| 50 | + callback: () => void, |
| 51 | +) => { |
| 52 | + let done = false |
| 53 | + while (!done) { |
| 54 | + const status = await msg.status(null) |
| 55 | + if (status == L2ToL1MessageStatus.CONFIRMED) { |
| 56 | + done = true |
| 57 | + } else { |
| 58 | + callback() |
| 59 | + await wait(retryDelay) |
| 60 | + } |
| 61 | + } |
| 62 | +} |
| 63 | + |
| 64 | +export const startSendToL1 = async (cli: CLIEnvironment, cliArgs: CLIArgs): Promise<void> => { |
| 65 | + logger.info(`>>> Sending tokens to L1 <<<\n`) |
| 66 | + const l2Provider = getProvider(cliArgs.l2ProviderUrl) |
| 67 | + const l2ChainId = (await l2Provider.getNetwork()).chainId |
| 68 | + if (chainIdIsL2(cli.chainId) || !chainIdIsL2(l2ChainId)) { |
| 69 | + throw new Error( |
| 70 | + 'Please use an L1 provider in --provider-url, and an L2 provider in --l2-provider-url', |
| 71 | + ) |
| 72 | + } |
| 73 | + |
| 74 | + const l1GRT = cli.contracts['GraphToken'] |
| 75 | + const l1GRTAddress = l1GRT.address |
| 76 | + const amount = toGRT(cliArgs.amount) |
| 77 | + const recipient = cliArgs.recipient ? cliArgs.recipient : cli.wallet.address |
| 78 | + const l2Wallet = cli.wallet.connect(l2Provider) |
| 79 | + const l2AddressBook = getAddressBook(cliArgs.addressBook, l2ChainId.toString()) |
| 80 | + |
| 81 | + const gateway = loadAddressBookContract('L2GraphTokenGateway', l2AddressBook, l2Wallet) |
| 82 | + const l2GRT = loadAddressBookContract('L2GraphToken', l2AddressBook, l2Wallet) |
| 83 | + |
| 84 | + const l1Gateway = cli.contracts['L1GraphTokenGateway'] |
| 85 | + logger.info(`Will send ${cliArgs.amount} GRT to ${recipient}`) |
| 86 | + logger.info(`Using L2 gateway ${gateway.address} and L1 gateway ${l1Gateway.address}`) |
| 87 | + |
| 88 | + const params = [l1GRTAddress, recipient, amount, '0x'] |
| 89 | + logger.info('Approving token transfer') |
| 90 | + await sendTransaction(l2Wallet, l2GRT, 'approve', [gateway.address, amount]) |
| 91 | + logger.info('Sending outbound transfer transaction') |
| 92 | + const receipt = await sendTransaction( |
| 93 | + l2Wallet, |
| 94 | + gateway, |
| 95 | + 'outboundTransfer(address,address,uint256,bytes)', |
| 96 | + params, |
| 97 | + ) |
| 98 | + const l2Receipt = new L2TransactionReceipt(receipt) |
| 99 | + const l2ToL1Message = ( |
| 100 | + await l2Receipt.getL2ToL1Messages(cli.wallet, await getL2Network(l2Provider)) |
| 101 | + )[0] |
| 102 | + |
| 103 | + logger.info( |
| 104 | + `The transaction generated an outbox message with batch number ${l2ToL1Message.batchNumber}`, |
| 105 | + ) |
| 106 | + logger.info(`and index in batch ${l2ToL1Message.indexInBatch}.`) |
| 107 | + logger.info( |
| 108 | + `After the dispute period is finalized (in ~1 week), you can finalize this by calling`, |
| 109 | + ) |
| 110 | + logger.info(`finish-send-to-l1 with the following txhash:`) |
| 111 | + logger.info(l2Receipt.transactionHash) |
| 112 | +} |
| 113 | + |
| 114 | +export const finishSendToL1 = async ( |
| 115 | + cli: CLIEnvironment, |
| 116 | + cliArgs: CLIArgs, |
| 117 | + wait: boolean, |
| 118 | +): Promise<void> => { |
| 119 | + logger.info(`>>> Finishing transaction sending tokens to L1 <<<\n`) |
| 120 | + const l2Provider = getProvider(cliArgs.l2ProviderUrl) |
| 121 | + const l2ChainId = (await l2Provider.getNetwork()).chainId |
| 122 | + if (chainIdIsL2(cli.chainId) || !chainIdIsL2(l2ChainId)) { |
| 123 | + throw new Error( |
| 124 | + 'Please use an L1 provider in --provider-url, and an L2 provider in --l2-provider-url', |
| 125 | + ) |
| 126 | + } |
| 127 | + |
| 128 | + const l2AddressBook = getAddressBook(cliArgs.addressBook, l2ChainId.toString()) |
| 129 | + |
| 130 | + const gateway = loadAddressBookContract( |
| 131 | + 'L2GraphTokenGateway', |
| 132 | + l2AddressBook, |
| 133 | + l2Provider, |
| 134 | + ) as L2GraphTokenGateway |
| 135 | + let txHash: string |
| 136 | + if (cliArgs.txHash) { |
| 137 | + txHash = cliArgs.txHash |
| 138 | + } else { |
| 139 | + logger.info( |
| 140 | + `Looking for withdrawals initiated by ${cli.wallet.address} in roughly the last 14 days`, |
| 141 | + ) |
| 142 | + const fromBlock = await searchForArbBlockByTimestamp( |
| 143 | + l2Provider, |
| 144 | + Math.round(Date.now() / 1000) - FOURTEEN_DAYS_IN_SECONDS, |
| 145 | + ) |
| 146 | + const filt = gateway.filters.WithdrawalInitiated(null, cli.wallet.address) |
| 147 | + const allEvents = await gateway.queryFilter(filt, BigNumber.from(fromBlock).toHexString()) |
| 148 | + if (allEvents.length == 0) { |
| 149 | + throw new Error('No withdrawals found') |
| 150 | + } |
| 151 | + txHash = allEvents[allEvents.length - 1].transactionHash |
| 152 | + } |
| 153 | + logger.info(`Getting receipt from transaction ${txHash}`) |
| 154 | + const receipt = await l2Provider.getTransactionReceipt(txHash) |
| 155 | + |
| 156 | + const l2Receipt = new L2TransactionReceipt(receipt) |
| 157 | + logger.info(`Getting L2 to L1 message...`) |
| 158 | + const l2ToL1Message = ( |
| 159 | + await l2Receipt.getL2ToL1Messages(cli.wallet, await getL2Network(l2Provider)) |
| 160 | + )[0] |
| 161 | + |
| 162 | + if (wait) { |
| 163 | + const retryDelayMs = cliArgs.retryDelaySeconds ? cliArgs.retryDelaySeconds * 1000 : 60000 |
| 164 | + logger.info('Waiting for outbox entry to be created, this can take a full week...') |
| 165 | + await waitUntilOutboxEntryCreatedWithCb(l2ToL1Message, retryDelayMs, () => { |
| 166 | + logger.info('Still waiting...') |
| 167 | + }) |
| 168 | + } else { |
| 169 | + logger.info('Checking if L2 to L1 message is confirmed...') |
| 170 | + const status = await l2ToL1Message.status(null) |
| 171 | + if (status != L2ToL1MessageStatus.CONFIRMED) { |
| 172 | + throw new Error( |
| 173 | + `Transaction is not confirmed, status is ${status} when it should be ${L2ToL1MessageStatus.CONFIRMED}. Has the dispute period passed?`, |
| 174 | + ) |
| 175 | + } |
| 176 | + } |
| 177 | + logger.info('Getting proof to execute message') |
| 178 | + const proofInfo = await l2ToL1Message.tryGetProof(l2Provider) |
| 179 | + |
| 180 | + if (await l2ToL1Message.hasExecuted(proofInfo)) { |
| 181 | + throw new Error('Message already executed!') |
| 182 | + } |
| 183 | + |
| 184 | + logger.info('Executing outbox transaction') |
| 185 | + const tx = await l2ToL1Message.execute(proofInfo) |
| 186 | + const outboxExecuteReceipt = await tx.wait() |
| 187 | + logger.info('Transaction succeeded! tx hash:') |
| 188 | + logger.info(outboxExecuteReceipt.transactionHash) |
| 189 | +} |
| 190 | + |
| 191 | +export const startSendToL1Command = { |
| 192 | + command: 'start-send-to-l1 <amount> [recipient]', |
| 193 | + describe: 'Start an L2-to-L1 Graph Token transaction', |
| 194 | + handler: async (argv: CLIArgs): Promise<void> => { |
| 195 | + return startSendToL1(await loadEnv(argv), argv) |
| 196 | + }, |
| 197 | +} |
| 198 | + |
| 199 | +export const finishSendToL1Command = { |
| 200 | + command: 'finish-send-to-l1 [txHash]', |
| 201 | + describe: |
| 202 | + 'Finish an L2-to-L1 Graph Token transaction. L2 dispute period must have completed. ' + |
| 203 | + 'If txHash is not specified, the last withdrawal from the main account in the past 14 days will be redeemed.', |
| 204 | + handler: async (argv: CLIArgs): Promise<void> => { |
| 205 | + return finishSendToL1(await loadEnv(argv), argv, false) |
| 206 | + }, |
| 207 | +} |
| 208 | + |
| 209 | +export const waitFinishSendToL1Command = { |
| 210 | + command: 'wait-finish-send-to-l1 [txHash] [retryDelaySeconds]', |
| 211 | + describe: |
| 212 | + "Wait for an L2-to-L1 Graph Token transaction's dispute period to complete (which takes about a week), and then finalize it. " + |
| 213 | + 'If txHash is not specified, the last withdrawal from the main account in the past 14 days will be redeemed.', |
| 214 | + handler: async (argv: CLIArgs): Promise<void> => { |
| 215 | + return finishSendToL1(await loadEnv(argv), argv, true) |
| 216 | + }, |
| 217 | +} |
0 commit comments