-
Notifications
You must be signed in to change notification settings - Fork 86
Expand file tree
/
Copy pathcreateTokenBridge.ts
More file actions
394 lines (353 loc) · 12 KB
/
createTokenBridge.ts
File metadata and controls
394 lines (353 loc) · 12 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
import { JsonRpcProvider } from '@ethersproject/providers'
import {
ArbitrumNetwork,
} from '@arbitrum/sdk'
import { IERC20Bridge__factory } from '@arbitrum/sdk/dist/lib/abi/factories/IERC20Bridge__factory'
import { RollupAdminLogic__factory } from '@arbitrum/sdk/dist/lib/abi/factories/RollupAdminLogic__factory'
import * as fs from 'fs'
import { constants } from 'ethers'
import { defineChain, createPublicClient, http, Address } from 'viem'
import { privateKeyToAccount } from 'viem/accounts'
import {
createRollupFetchTransactionHash,
createRollupPrepareTransactionReceipt,
createTokenBridgeEnoughCustomFeeTokenAllowance,
createTokenBridgePrepareCustomFeeTokenApprovalTransactionRequest,
createTokenBridgePrepareTransactionRequest,
createTokenBridgePrepareTransactionReceipt,
createTokenBridgePrepareSetWethGatewayTransactionRequest,
createTokenBridgePrepareSetWethGatewayTransactionReceipt,
} from '@arbitrum/orbit-sdk'
import { sanitizePrivateKey } from '@arbitrum/orbit-sdk/utils'
import { L3Config } from './l3ConfigType'
function createPublicClientFromChainInfo({
id,
name,
rpcUrl,
}: {
id: number
name: string
rpcUrl: string
}) {
const chain = defineChain({
id: id,
network: name,
name: name,
nativeCurrency: { name: 'Ether', symbol: 'ETH', decimals: 18 },
rpcUrls: {
default: {
http: [rpcUrl],
},
public: {
http: [rpcUrl],
},
},
testnet: true,
})
return createPublicClient({ chain, transport: http() })
}
export const TOKEN_BRIDGE_CREATOR_Arb_Sepolia =
'0x56C486D3786fA26cc61473C499A36Eb9CC1FbD8E'
async function getNativeToken({
rollup,
provider,
}: {
rollup: string
provider: JsonRpcProvider
}): Promise<`0x${string}`> {
const bridge = await RollupAdminLogic__factory.connect(
rollup,
provider
).bridge()
try {
return (await IERC20Bridge__factory.connect(
bridge,
provider
).nativeToken()) as `0x${string}`
} catch (error) {
return constants.AddressZero
}
}
/**
* Steps:
* - read network info from local container and register networks
* - deploy L1 bridge creator and set templates
* - do single TX deployment of token bridge
* - populate network objects with new addresses and return it
*
* @param l1Deployer
* @param l2Deployer
* @param l1Url
* @param l2Url
* @returns
*/
export const createNewTokenBridge = async (
baseChainRpc: string,
baseChainDeployerKey: string,
childChainRpc: string,
rollupAddress: string
) => {
const l1Provider = new JsonRpcProvider(baseChainRpc)
const l1NetworkInfo = await l1Provider.getNetwork()
const l2Provider = new JsonRpcProvider(childChainRpc)
const l2NetworkInfo = await l2Provider.getNetwork()
const deployer = privateKeyToAccount(sanitizePrivateKey(baseChainDeployerKey))
const rollup = RollupAdminLogic__factory.connect(rollupAddress, l1Provider)
const parentChainPublicClient = createPublicClientFromChainInfo({
id: l1NetworkInfo.chainId,
name: l1NetworkInfo.name,
rpcUrl: baseChainRpc,
})
const orbitChainPublicClient = createPublicClientFromChainInfo({
id: l2NetworkInfo.chainId,
name: l2NetworkInfo.name,
rpcUrl: childChainRpc,
})
const nativeToken = await getNativeToken({
rollup: rollupAddress,
provider: l1Provider,
})
// custom gas token
if (nativeToken !== constants.AddressZero) {
console.log(
`Detected custom gas token chain with native token ${nativeToken}`
)
const allowanceParams = {
nativeToken,
owner: deployer.address,
publicClient: parentChainPublicClient,
}
const enoughCustomFeeTokenAllowance =
await createTokenBridgeEnoughCustomFeeTokenAllowance(allowanceParams)
if (!enoughCustomFeeTokenAllowance) {
console.log('Not enough allowance for custom gas token')
const approvalTxRequest =
await createTokenBridgePrepareCustomFeeTokenApprovalTransactionRequest(
allowanceParams
)
console.log(`Sending tx to approve custom gas token`)
// sign and send the transaction
const approvalTxHash = await parentChainPublicClient.sendRawTransaction({
serializedTransaction: await deployer.signTransaction(
approvalTxRequest
),
})
// get the transaction receipt after waiting for the transaction to complete
const approvalTxReceipt =
await parentChainPublicClient.waitForTransactionReceipt({
hash: approvalTxHash,
})
console.log(
`Done! Custom gas token approved in tx ${approvalTxReceipt.transactionHash}`
)
}
}
const txRequest = await createTokenBridgePrepareTransactionRequest({
params: {
rollup: rollupAddress as Address,
rollupOwner: deployer.address,
},
parentChainPublicClient,
orbitChainPublicClient,
account: deployer.address,
})
// submit tx
const txHash = await parentChainPublicClient.sendRawTransaction({
serializedTransaction: await deployer.signTransaction(txRequest),
})
// get the transaction receipt after waiting for the transaction to complete
const txReceipt = createTokenBridgePrepareTransactionReceipt(
await parentChainPublicClient.waitForTransactionReceipt({ hash: txHash })
)
console.log(
`Token bridge deployed in transaction ${txReceipt.transactionHash}`
)
console.log(`Waiting for retryables...`)
// wait for retryables to execute
const retryables = await txReceipt.waitForRetryables({
orbitPublicClient: orbitChainPublicClient,
})
console.log(`Retryable #1: ${retryables[0].transactionHash}`)
console.log(`Retryable #2: ${retryables[1].transactionHash}`)
console.log(`Done!`)
const { parentChainContracts, orbitChainContracts } =
await txReceipt.getTokenBridgeContracts({
parentChainPublicClient,
})
// set weth gateway (only for eth-based chains)
if (nativeToken === constants.AddressZero) {
const setWethGatewayTxRequest =
await createTokenBridgePrepareSetWethGatewayTransactionRequest({
rollup: rollupAddress as Address,
parentChainPublicClient,
orbitChainPublicClient,
account: deployer.address,
retryableGasOverrides: {
gasLimit: {
percentIncrease: 200n,
},
},
})
// sign and send the transaction
const setWethGatewayTxHash =
await parentChainPublicClient.sendRawTransaction({
serializedTransaction: await deployer.signTransaction(
setWethGatewayTxRequest
),
})
// get the transaction receipt after waiting for the transaction to complete
const setWethGatewayTxReceipt =
createTokenBridgePrepareSetWethGatewayTransactionReceipt(
await parentChainPublicClient.waitForTransactionReceipt({
hash: setWethGatewayTxHash,
})
)
console.log(
`Weth gateway set in tx ${setWethGatewayTxReceipt.transactionHash}`
)
// Wait for retryables to execute
console.log(`Waiting for retryables...`)
const orbitChainSetWethGatewayRetryableReceipt =
await setWethGatewayTxReceipt.waitForRetryables({
orbitPublicClient: orbitChainPublicClient,
})
console.log(
`Retryable #1: ${orbitChainSetWethGatewayRetryableReceipt[0].transactionHash}`
)
if (orbitChainSetWethGatewayRetryableReceipt[0].status !== 'success') {
console.error(
`Retryable status is not success: ${orbitChainSetWethGatewayRetryableReceipt[0].status}. The process will continue, but you'll have to register the Weth gateway later again.`
)
}
console.log(`Done!`)
}
// fetch core contracts
const createRollupTxHash = await createRollupFetchTransactionHash({
rollup: rollupAddress as Address,
publicClient: parentChainPublicClient,
})
const coreContracts = createRollupPrepareTransactionReceipt(
await parentChainPublicClient.getTransactionReceipt({
hash: createRollupTxHash,
})
).getCoreContracts()
const l1Network = {
blockTime: 10,
chainId: l1NetworkInfo.chainId,
explorerUrl: '',
isCustom: true,
name: l1NetworkInfo.name,
partnerChainIDs: [l2NetworkInfo.chainId],
isArbitrum: false,
}
const l2Network: ArbitrumNetwork = {
chainId: l2NetworkInfo.chainId,
confirmPeriodBlocks: (await rollup.confirmPeriodBlocks()).toNumber(),
ethBridge: {
bridge: coreContracts.bridge,
inbox: coreContracts.inbox,
outbox: coreContracts.outbox,
rollup: rollup.address,
sequencerInbox: coreContracts.sequencerInbox,
},
isCustom: true,
name: 'OrbitChain',
parentChainId: l1NetworkInfo.chainId,
retryableLifetimeSeconds: 7 * 24 * 60 * 60,
tokenBridge: {
parentCustomGateway: parentChainContracts.customGateway,
parentErc20Gateway: parentChainContracts.standardGateway,
parentGatewayRouter: parentChainContracts.router,
parentMultiCall: parentChainContracts.multicall,
// todo: fix
parentProxyAdmin: constants.AddressZero,
parentWeth: parentChainContracts.weth,
parentWethGateway: parentChainContracts.wethGateway,
childCustomGateway: orbitChainContracts.customGateway,
childErc20Gateway: orbitChainContracts.standardGateway,
childGatewayRouter: orbitChainContracts.router,
childMultiCall: orbitChainContracts.multicall,
childProxyAdmin: orbitChainContracts.proxyAdmin,
childWeth: orbitChainContracts.weth,
childWethGateway: orbitChainContracts.wethGateway,
},
}
return {
l1Network,
l2Network,
}
}
export const createERC20Bridge = async (
baseChainRpc: string,
baseChainDeployerKey: string,
childChainRpc: string,
rollupAddress: string
) => {
console.log('Creating token bridge for rollup', rollupAddress)
const { l1Network, l2Network } = await createNewTokenBridge(
baseChainRpc,
baseChainDeployerKey,
childChainRpc,
rollupAddress
)
const NETWORK_FILE = 'network.json'
fs.writeFileSync(
NETWORK_FILE,
JSON.stringify({ l1Network, l2Network }, null, 2)
)
console.log(NETWORK_FILE + ' updated')
// Read the JSON configuration
const configRaw = fs.readFileSync(
'./config/orbitSetupScriptConfig.json',
'utf-8'
)
const config: L3Config = JSON.parse(configRaw)
const outputInfo = {
chainInfo: {
minL2BaseFee: config.minL2BaseFee,
networkFeeReceiver: config.networkFeeReceiver,
infrastructureFeeCollector: config.infrastructureFeeCollector,
batchPoster: config.batchPoster,
staker: config.staker,
chainOwner: config.chainOwner,
chainName: config.chainName,
chainId: config.chainId,
parentChainId: config.parentChainId,
rpcUrl: 'http://localhost:8449',
explorerUrl: 'http://localhost',
nativeToken: config.nativeToken,
},
coreContracts: {
rollup: config.rollup,
inbox: config.inbox,
outbox: config.outbox,
adminProxy: config.adminProxy,
sequencerInbox: config.sequencerInbox,
bridge: config.bridge,
utils: config.utils,
validatorWalletCreator: config.validatorWalletCreator,
},
tokenBridgeContracts: {
l2Contracts: {
customGateway: l2Network!.tokenBridge!.parentCustomGateway,
multicall: l2Network!.tokenBridge!.parentMultiCall,
proxyAdmin: l2Network!.tokenBridge!.parentProxyAdmin,
router: l2Network!.tokenBridge!.parentGatewayRouter,
standardGateway: l2Network!.tokenBridge!.parentErc20Gateway,
weth: l2Network!.tokenBridge!.parentWeth,
wethGateway: l2Network!.tokenBridge!.parentWethGateway,
},
l3Contracts: {
customGateway: l2Network!.tokenBridge!.childCustomGateway,
multicall: l2Network!.tokenBridge!.childMultiCall,
proxyAdmin: l2Network!.tokenBridge!.childProxyAdmin,
router: l2Network!.tokenBridge!.childGatewayRouter,
standardGateway: l2Network!.tokenBridge!.childErc20Gateway,
weth: l2Network!.tokenBridge!.childWeth,
wethGateway: l2Network!.tokenBridge!.childWethGateway,
},
},
}
fs.writeFileSync('outputInfo.json', JSON.stringify(outputInfo, null, 2))
console.log('Done!')
}