forked from ethereum-optimism/optimism
-
Notifications
You must be signed in to change notification settings - Fork 0
/
custom_gas_token_test.go
449 lines (377 loc) · 17.4 KB
/
custom_gas_token_test.go
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
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
package op_e2e
import (
"context"
"fmt"
"math/big"
"testing"
"github.com/ethereum-optimism/optimism/op-bindings/bindings"
"github.com/ethereum-optimism/optimism/op-e2e/e2eutils"
"github.com/ethereum-optimism/optimism/op-e2e/e2eutils/receipts"
"github.com/ethereum-optimism/optimism/op-e2e/e2eutils/wait"
"github.com/ethereum-optimism/optimism/op-node/rollup/derive"
"github.com/ethereum-optimism/optimism/op-service/predeploys"
"github.com/ethereum/go-ethereum/accounts/abi/bind"
"github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/core/types"
"github.com/ethereum/go-ethereum/ethclient"
"github.com/stretchr/testify/require"
)
func TestCustomGasToken(t *testing.T) {
InitParallel(t, SkipOnFPAC) // Custom Gas Token feature is not yet compatible with FPAC
cfg := DefaultSystemConfig(t)
sys, err := cfg.Start(t)
require.NoError(t, err, "Error starting up system")
defer sys.Close()
l1Client := sys.Clients["l1"]
l2Client := sys.Clients["sequencer"]
aliceOpts, err := bind.NewKeyedTransactorWithChainID(cfg.Secrets.Alice, cfg.L1ChainIDBig())
require.NoError(t, err)
// Deploy WETH9, we'll use this as our custom gas token for the purpose of the test
weth9Address, tx, weth9, err := bindings.DeployWETH9(aliceOpts, l1Client)
require.NoError(t, err)
_, err = wait.ForReceiptOK(context.Background(), l1Client, tx.Hash())
require.NoError(t, err)
// setup expectations using custom gas token
type Expectations struct {
tokenAddress common.Address
tokenName string
tokenSymbol string
tokenDecimals uint8
}
disabledExpectations := Expectations{
common.HexToAddress("0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE"),
"Ether",
"ETH",
uint8(18),
}
enabledExpectations := Expectations{}
enabledExpectations.tokenAddress = weth9Address
enabledExpectations.tokenName, err = weth9.Name(&bind.CallOpts{})
require.NoError(t, err)
enabledExpectations.tokenSymbol, err = weth9.Symbol(&bind.CallOpts{})
require.NoError(t, err)
enabledExpectations.tokenDecimals, err = weth9.Decimals(&bind.CallOpts{})
require.NoError(t, err)
// Get some WETH
aliceOpts.Value = big.NewInt(10_000_000)
tx, err = weth9.Deposit(aliceOpts)
waitForTx(t, tx, err, l1Client)
aliceOpts.Value = nil
newBalance, err := weth9.BalanceOf(&bind.CallOpts{}, aliceOpts.From)
require.NoError(t, err)
require.Equal(t, newBalance, big.NewInt(10_000_000))
// Function to prepare and make call to depositERC20Transaction and make
// appropriate assertions dependent on whether custom gas tokens have been enabled or not.
checkDeposit := func(t *testing.T, enabled bool) {
// Set amount of WETH9 to bridge to the recipient on L2
amountToBridge := big.NewInt(10)
recipient := common.HexToAddress("0xbeefdead")
// Approve OptimismPortal
tx, err = weth9.Approve(aliceOpts, cfg.L1Deployments.OptimismPortalProxy, amountToBridge)
waitForTx(t, tx, err, l1Client)
// Get recipient L2 balance before bridging
previousL2Balance, err := l2Client.BalanceAt(context.Background(), recipient, nil)
require.NoError(t, err)
// Bridge the tokens
optimismPortal, err := bindings.NewOptimismPortal(cfg.L1Deployments.OptimismPortalProxy, l1Client)
require.NoError(t, err)
tx, err = optimismPortal.DepositERC20Transaction(aliceOpts,
recipient,
amountToBridge,
amountToBridge,
50_0000, // _gasLimit
false,
[]byte{},
)
if enabled {
require.NoError(t, err)
receipt, err := wait.ForReceiptOK(context.Background(), l1Client, tx.Hash())
require.NoError(t, err)
// compute the deposit transaction hash + poll for it
depositEvent, err := receipts.FindLog(receipt.Logs, optimismPortal.ParseTransactionDeposited)
require.NoError(t, err, "Should emit deposit event")
depositTx, err := derive.UnmarshalDepositLogEvent(&depositEvent.Raw)
require.NoError(t, err)
_, err = wait.ForReceiptOK(context.Background(), l2Client, types.NewTx(depositTx).Hash())
require.NoError(t, err)
// check for balance increase on L2
newL2Balance, err := l2Client.BalanceAt(context.Background(), recipient, nil)
require.NoError(t, err)
l2BalanceIncrease := big.NewInt(0).Sub(newL2Balance, previousL2Balance)
require.Equal(t, amountToBridge, l2BalanceIncrease)
} else {
require.Error(t, err)
}
}
// Function to prepare and execute withdrawal flow for CGTs
// and assert token balance is increased on L1.
checkWithdrawal := func(t *testing.T) {
l2Seq := l2Client
l2Verif := sys.Clients["verifier"]
fromAddr := aliceOpts.From
ethPrivKey := cfg.Secrets.Alice
// Start L2 balance for withdrawal
startBalanceBeforeWithdrawal, err := l2Seq.BalanceAt(context.Background(), fromAddr, nil)
require.NoError(t, err)
withdrawAmount := big.NewInt(5)
tx, receipt := SendWithdrawal(t, cfg, l2Seq, cfg.Secrets.Alice, func(opts *WithdrawalTxOpts) {
opts.Value = withdrawAmount
opts.VerifyOnClients(l2Verif)
})
// Verify L2 balance after withdrawal
header, err := l2Verif.HeaderByNumber(context.Background(), receipt.BlockNumber)
require.NoError(t, err)
endBalanceAfterWithdrawal, err := wait.ForBalanceChange(context.Background(), l2Seq, fromAddr, startBalanceBeforeWithdrawal)
require.NoError(t, err)
// Take fee into account
diff := new(big.Int).Sub(startBalanceBeforeWithdrawal, endBalanceAfterWithdrawal)
fees := calcGasFees(receipt.GasUsed, tx.GasTipCap(), tx.GasFeeCap(), header.BaseFee)
fees = fees.Add(fees, receipt.L1Fee)
diff = diff.Sub(diff, fees)
require.Equal(t, withdrawAmount, diff)
// Take start token balance on L1
startTokenBalanceBeforeFinalize, err := weth9.BalanceOf(&bind.CallOpts{}, fromAddr)
require.NoError(t, err)
startETHBalanceBeforeFinalize, err := l1Client.BalanceAt(context.Background(), fromAddr, nil)
require.NoError(t, err)
proveReceipt, finalizeReceipt, resolveClaimReceipt, resolveReceipt := ProveAndFinalizeWithdrawal(t, cfg, sys, "verifier", ethPrivKey, receipt)
// Verify L1 ETH balance change
proveFee := new(big.Int).Mul(new(big.Int).SetUint64(proveReceipt.GasUsed), proveReceipt.EffectiveGasPrice)
finalizeFee := new(big.Int).Mul(new(big.Int).SetUint64(finalizeReceipt.GasUsed), finalizeReceipt.EffectiveGasPrice)
fees = new(big.Int).Add(proveFee, finalizeFee)
if e2eutils.UseFPAC() {
resolveClaimFee := new(big.Int).Mul(new(big.Int).SetUint64(resolveClaimReceipt.GasUsed), resolveClaimReceipt.EffectiveGasPrice)
resolveFee := new(big.Int).Mul(new(big.Int).SetUint64(resolveReceipt.GasUsed), resolveReceipt.EffectiveGasPrice)
fees = new(big.Int).Add(fees, resolveClaimFee)
fees = new(big.Int).Add(fees, resolveFee)
}
// Verify L1ETHBalance after withdrawal
// On CGT chains, the only change in ETH balance from a withdrawal
// is a decrease to pay for gas
endETHBalanceAfterFinalize, err := l1Client.BalanceAt(context.Background(), fromAddr, nil)
require.NoError(t, err)
diff = new(big.Int).Sub(endETHBalanceAfterFinalize, startETHBalanceBeforeFinalize)
require.Equal(t, new(big.Int).Sub(big.NewInt(0), fees), diff)
// Verify token balance after withdrawal
// L1 Fees are paid in ETH, and
// withdrawal is of a Custom Gas Token, so we do not subtract l1 fees from expected balance change
// as we would if ETH was the gas paying token
endTokenBalanceAfterFinalize, err := weth9.BalanceOf(&bind.CallOpts{}, fromAddr)
require.NoError(t, err)
diff = new(big.Int).Sub(endTokenBalanceAfterFinalize, startTokenBalanceBeforeFinalize)
require.Equal(t, withdrawAmount, diff)
}
checkL1TokenNameAndSymbol := func(t *testing.T, enabled bool) {
systemConfig, err := bindings.NewSystemConfig(cfg.L1Deployments.SystemConfigProxy, l1Client)
require.NoError(t, err)
token, err := systemConfig.GasPayingToken(&bind.CallOpts{})
require.NoError(t, err)
name, err := systemConfig.GasPayingTokenName(&bind.CallOpts{})
require.NoError(t, err)
symbol, err := systemConfig.GasPayingTokenSymbol(&bind.CallOpts{})
require.NoError(t, err)
if enabled {
require.Equal(t, enabledExpectations.tokenAddress, token.Addr)
require.Equal(t, enabledExpectations.tokenDecimals, token.Decimals)
require.Equal(t, enabledExpectations.tokenName, name)
require.Equal(t, enabledExpectations.tokenSymbol, symbol)
} else {
require.Equal(t, disabledExpectations.tokenAddress, token.Addr)
require.Equal(t, disabledExpectations.tokenDecimals, token.Decimals)
require.Equal(t, disabledExpectations.tokenName, name)
require.Equal(t, disabledExpectations.tokenSymbol, symbol)
}
}
checkL2TokenNameAndSymbol := func(t *testing.T, enabled bool) {
l1Block, err := bindings.NewL1Block(predeploys.L1BlockAddr, l2Client)
require.NoError(t, err)
token, err := l1Block.GasPayingToken(&bind.CallOpts{})
require.NoError(t, err)
name, err := l1Block.GasPayingTokenName(&bind.CallOpts{})
require.NoError(t, err)
symbol, err := l1Block.GasPayingTokenSymbol(&bind.CallOpts{})
require.NoError(t, err)
if enabled {
require.Equal(t, enabledExpectations.tokenAddress, token.Addr)
require.Equal(t, enabledExpectations.tokenDecimals, token.Decimals)
require.Equal(t, enabledExpectations.tokenName, name)
require.Equal(t, enabledExpectations.tokenSymbol, symbol)
} else {
require.Equal(t, disabledExpectations.tokenAddress, token.Addr)
require.Equal(t, disabledExpectations.tokenDecimals, token.Decimals)
require.Equal(t, disabledExpectations.tokenName, name)
require.Equal(t, disabledExpectations.tokenSymbol, symbol)
}
}
checkWETHTokenNameAndSymbol := func(t *testing.T, enabled bool) {
// Check name and symbol in WETH predeploy
weth, err := bindings.NewWETH(predeploys.WETHAddr, l2Client)
require.NoError(t, err)
name, err := weth.Name(&bind.CallOpts{})
require.NoError(t, err)
symbol, err := weth.Symbol(&bind.CallOpts{})
require.NoError(t, err)
if enabled {
require.Equal(t, "Wrapped "+enabledExpectations.tokenName, name)
require.Equal(t, "W"+enabledExpectations.tokenSymbol, symbol)
} else {
require.Equal(t, "Wrapped "+disabledExpectations.tokenName, name)
require.Equal(t, "W"+disabledExpectations.tokenSymbol, symbol)
}
}
// Begin by testing behaviour when CGT feature is not enabled
enabled := false
checkDeposit(t, enabled)
checkL1TokenNameAndSymbol(t, enabled)
checkL2TokenNameAndSymbol(t, enabled)
checkWETHTokenNameAndSymbol(t, enabled)
// Activate custom gas token feature (devnet does not have this activated at genesis)
setCustomGasToken(t, cfg, sys, weth9Address)
// Now test behaviour given CGT feature is enabled
enabled = true
checkDeposit(t, enabled)
checkWithdrawal(t)
checkL1TokenNameAndSymbol(t, enabled)
checkL2TokenNameAndSymbol(t, enabled)
checkWETHTokenNameAndSymbol(t, enabled)
}
// callViaSafe will use the Safe smart account at safeAddress to send a transaction to target using the provided data. The transaction signature is constructed from
// the supplied opts.
func callViaSafe(opts *bind.TransactOpts, client *ethclient.Client, safeAddress common.Address, target common.Address, data []byte) (*types.Transaction, error) {
signature := [65]byte{}
copy(signature[12:], opts.From[:])
signature[64] = uint8(1)
safe, err := bindings.NewSafe(safeAddress, client)
if err != nil {
return nil, err
}
owners, err := safe.GetOwners(&bind.CallOpts{})
if err != nil {
return nil, err
}
isOwner, err := safe.IsOwner(&bind.CallOpts{}, opts.From)
if err != nil {
return nil, err
}
if !isOwner {
return nil, fmt.Errorf("address %s is not in owners list %s", opts.From, owners)
}
return safe.ExecTransaction(opts, target, big.NewInt(0), data, 0, big.NewInt(0), big.NewInt(0), big.NewInt(0), common.Address{}, common.Address{}, signature[:])
}
// setCustomGasToeken enables the Custom Gas Token feature on a chain where it wasn't enabled at genesis.
// It reads existing parameters from the SystemConfig contract, inserts the supplied cgtAddress and reinitializes that contract.
// To do this it uses the ProxyAdmin and StorageSetter from the supplied cfg.
func setCustomGasToken(t *testing.T, cfg SystemConfig, sys *System, cgtAddress common.Address) {
l1Client := sys.Clients["l1"]
deployerOpts, err := bind.NewKeyedTransactorWithChainID(cfg.Secrets.Deployer, cfg.L1ChainIDBig())
require.NoError(t, err)
// Bind a SystemConfig at the SystemConfigProxy address
systemConfig, err := bindings.NewSystemConfig(cfg.L1Deployments.SystemConfigProxy, l1Client)
require.NoError(t, err)
// Get existing parameters from SystemConfigProxy contract
owner, err := systemConfig.Owner(&bind.CallOpts{})
require.NoError(t, err)
overhead, err := systemConfig.Overhead(&bind.CallOpts{})
require.NoError(t, err)
scalar, err := systemConfig.Scalar(&bind.CallOpts{})
require.NoError(t, err)
batcherHash, err := systemConfig.BatcherHash(&bind.CallOpts{})
require.NoError(t, err)
gasLimit, err := systemConfig.GasLimit(&bind.CallOpts{})
require.NoError(t, err)
unsafeBlockSigner, err := systemConfig.UnsafeBlockSigner(&bind.CallOpts{})
require.NoError(t, err)
resourceConfig, err := systemConfig.ResourceConfig(&bind.CallOpts{})
require.NoError(t, err)
batchInbox, err := systemConfig.BatchInbox(&bind.CallOpts{})
require.NoError(t, err)
addresses := bindings.SystemConfigAddresses{}
addresses.L1CrossDomainMessenger, err = systemConfig.L1CrossDomainMessenger(&bind.CallOpts{})
require.NoError(t, err)
addresses.L1ERC721Bridge, err = systemConfig.L1ERC721Bridge(&bind.CallOpts{})
require.NoError(t, err)
addresses.L1StandardBridge, err = systemConfig.L1StandardBridge(&bind.CallOpts{})
require.NoError(t, err)
addresses.DisputeGameFactory, err = systemConfig.DisputeGameFactory(&bind.CallOpts{})
require.NoError(t, err)
addresses.OptimismPortal, err = systemConfig.OptimismPortal(&bind.CallOpts{})
require.NoError(t, err)
addresses.OptimismMintableERC20Factory, err = systemConfig.OptimismMintableERC20Factory(&bind.CallOpts{})
require.NoError(t, err)
// Queue up custom gas token address ready for reinitialization
addresses.GasPayingToken = cgtAddress
// Bind a ProxyAdmin to the ProxyAdmin address
proxyAdmin, err := bindings.NewProxyAdmin(cfg.L1Deployments.ProxyAdmin, l1Client)
require.NoError(t, err)
// Compute Proxy Admin Owner (this is a SAFE with 1 owner)
proxyAdminOwner, err := proxyAdmin.Owner(&bind.CallOpts{})
require.NoError(t, err)
// Deploy a new StorageSetter contract
storageSetterAddr, tx, _, err := bindings.DeployStorageSetter(deployerOpts, l1Client)
waitForTx(t, tx, err, l1Client)
// Set up a signer which controls the Proxy Admin Owner SAFE
safeOwnerOpts, err := bind.NewKeyedTransactorWithChainID(cfg.Secrets.Deployer, cfg.L1ChainIDBig())
require.NoError(t, err)
// Encode calldata for upgrading SystemConfigProxy to the StorageSetter implementation
proxyAdminABI, err := bindings.ProxyAdminMetaData.GetAbi()
require.NoError(t, err)
encodedUpgradeCall, err := proxyAdminABI.Pack("upgrade",
cfg.L1Deployments.SystemConfigProxy, storageSetterAddr)
require.NoError(t, err)
// Execute the upgrade SystemConfigProxy -> StorageSetter
tx, err = callViaSafe(safeOwnerOpts, l1Client, proxyAdminOwner, cfg.L1Deployments.ProxyAdmin, encodedUpgradeCall)
waitForTx(t, tx, err, l1Client)
// Bind a StorageSetter to the SystemConfigProxy address
storageSetter, err := bindings.NewStorageSetter(cfg.L1Deployments.SystemConfigProxy, l1Client)
require.NoError(t, err)
// Use StorageSetter to clear out "initialize" slot
tx, err = storageSetter.SetBytes320(deployerOpts, [32]byte{0}, [32]byte{0})
waitForTx(t, tx, err, l1Client)
// Sanity check previous step worked
currentSlotValue, err := storageSetter.GetBytes32(&bind.CallOpts{}, [32]byte{0})
require.NoError(t, err)
require.Equal(t, currentSlotValue, [32]byte{0})
// Prepare calldata for SystemConfigProxy -> SystemConfig upgrade
encodedUpgradeCall, err = proxyAdminABI.Pack("upgrade",
cfg.L1Deployments.SystemConfigProxy, cfg.L1Deployments.SystemConfig)
require.NoError(t, err)
// Execute SystemConfigProxy -> SystemConfig upgrade
tx, err = callViaSafe(safeOwnerOpts, l1Client, proxyAdminOwner, cfg.L1Deployments.ProxyAdmin, encodedUpgradeCall)
waitForTx(t, tx, err, l1Client)
// Reinitialise with existing initializer values but with custom gas token set
tx, err = systemConfig.Initialize(deployerOpts, owner,
overhead,
scalar,
batcherHash,
gasLimit,
unsafeBlockSigner,
resourceConfig,
batchInbox,
addresses)
require.NoError(t, err)
receipt, err := wait.ForReceiptOK(context.Background(), l1Client, tx.Hash())
require.NoError(t, err)
// Read Custom Gas Token and check it has been set properly
gpt, err := systemConfig.GasPayingToken(&bind.CallOpts{})
require.NoError(t, err)
require.Equal(t, cgtAddress, gpt.Addr)
optimismPortal, err := bindings.NewOptimismPortal(cfg.L1Deployments.OptimismPortalProxy, l1Client)
require.NoError(t, err)
depositEvent, err := receipts.FindLog(receipt.Logs, optimismPortal.ParseTransactionDeposited)
require.NoError(t, err, "Should emit deposit event")
depositTx, err := derive.UnmarshalDepositLogEvent(&depositEvent.Raw)
require.NoError(t, err)
l2Client := sys.Clients["sequencer"]
receipt, err = wait.ForReceiptOK(context.Background(), l2Client, types.NewTx(depositTx).Hash())
require.NoError(t, err)
l1Block, err := bindings.NewL1Block(predeploys.L1BlockAddr, l2Client)
require.NoError(t, err)
_, err = receipts.FindLog(receipt.Logs, l1Block.ParseGasPayingTokenSet)
require.NoError(t, err)
}
// waitForTx is a thing wrapper around wait.ForReceiptOK which asserts on there being no errors.
func waitForTx(t *testing.T, tx *types.Transaction, err error, client *ethclient.Client) {
require.NoError(t, err)
_, err = wait.ForReceiptOK(context.Background(), client, tx.Hash())
require.NoError(t, err)
}