apply_test.go 44.5 KB
Newer Older
1 2 3
package integration_test

import (
4
	"bufio"
5
	"bytes"
6
	"compress/gzip"
7
	"context"
8
	"crypto/rand"
9
	"encoding/hex"
10
	"encoding/json"
11 12
	"fmt"
	"log/slog"
13
	"maps"
14
	"math/big"
15
	"os"
16
	"strings"
17
	"testing"
18 19
	"time"

20 21 22 23
	"github.com/ethereum/go-ethereum"
	"github.com/ethereum/go-ethereum/rpc"
	"github.com/lmittmann/w3"

24 25 26 27
	"github.com/ethereum-optimism/optimism/op-deployer/pkg/deployer/broadcaster"
	"github.com/ethereum-optimism/optimism/op-deployer/pkg/deployer/opcm"
	"github.com/ethereum-optimism/optimism/op-deployer/pkg/env"

28 29
	"github.com/ethereum-optimism/optimism/op-e2e/e2eutils/retryproxy"

30 31 32 33
	altda "github.com/ethereum-optimism/optimism/op-alt-da"
	"github.com/ethereum-optimism/optimism/op-deployer/pkg/deployer/inspect"
	"github.com/ethereum-optimism/optimism/op-node/rollup"

34 35
	"github.com/ethereum-optimism/optimism/op-deployer/pkg/deployer/artifacts"

36 37
	"github.com/ethereum-optimism/optimism/op-deployer/pkg/deployer"
	"github.com/ethereum-optimism/optimism/op-deployer/pkg/deployer/pipeline"
38
	"github.com/ethereum-optimism/optimism/op-deployer/pkg/deployer/standard"
39
	"github.com/ethereum-optimism/optimism/op-deployer/pkg/deployer/state"
40 41 42
	"github.com/ethereum-optimism/optimism/op-deployer/pkg/deployer/testutil"
	"github.com/ethereum-optimism/optimism/op-service/testutils/anvil"
	"github.com/ethereum/go-ethereum/crypto"
43

44 45
	op_e2e "github.com/ethereum-optimism/optimism/op-e2e"

46
	"github.com/holiman/uint256"
47 48

	"github.com/ethereum-optimism/optimism/op-chain-ops/devkeys"
49 50
	"github.com/ethereum-optimism/optimism/op-chain-ops/genesis"
	"github.com/ethereum-optimism/optimism/op-service/predeploys"
51 52 53
	"github.com/ethereum-optimism/optimism/op-service/testlog"
	"github.com/ethereum-optimism/optimism/op-service/testutils/kurtosisutil"
	"github.com/ethereum/go-ethereum/common"
54
	"github.com/ethereum/go-ethereum/core/types"
55 56 57 58 59 60 61
	"github.com/ethereum/go-ethereum/ethclient"
	"github.com/stretchr/testify/require"
)

const TestParams = `
participants:
  - el_type: geth
62 63
    el_extra_params:
      - "--gcmode=archive"
64
      - "--rpc.txfeecap=0"
65 66 67
    cl_type: lighthouse
network_params:
  prefunded_accounts: '{ "0xf39Fd6e51aad88F6F4ce6aB8827279cffFb92266": { "balance": "1000000ETH" } }'
68 69 70 71 72 73 74 75 76
  additional_preloaded_contracts: '{
    "0x4e59b44847b379578588920cA78FbF26c0B4956C": {
      balance: "0ETH",
      code: "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3",
      storage: {},
      nonce: 0,
      secretKey: "0x"
    }
  }'
77 78
  network_id: "77799777"
  seconds_per_slot: 3
79
  genesis_delay: 0
80 81
`

82 83
const defaultL1ChainID uint64 = 77799777

84 85
var versionFunc = w3.MustNewFunc("version()", "string")

86 87 88 89 90 91 92 93 94 95 96
type deployerKey struct{}

func (d *deployerKey) HDPath() string {
	return "m/44'/60'/0'/0/0"
}

func (d *deployerKey) String() string {
	return "deployer-key"
}

func TestEndToEndApply(t *testing.T) {
97
	op_e2e.InitParallel(t)
98 99
	kurtosisutil.Test(t)

100
	lgr := testlog.Logger(t, slog.LevelDebug)
101 102 103 104

	ctx, cancel := context.WithCancel(context.Background())
	defer cancel()

105
	enclaveCtx := kurtosisutil.StartEnclave(t, ctx, lgr, "github.com/ethpandaops/ethereum-package@4.4.0", TestParams)
106 107 108 109 110 111 112 113 114 115

	service, err := enclaveCtx.GetServiceContext("el-1-geth-lighthouse")
	require.NoError(t, err)

	ip := service.GetMaybePublicIPAddress()
	ports := service.GetPublicPorts()
	rpcURL := fmt.Sprintf("http://%s:%d", ip, ports["rpc"].GetNumber())
	l1Client, err := ethclient.Dial(rpcURL)
	require.NoError(t, err)

116 117 118
	pk, err := crypto.HexToECDSA("ac0974bec39a17e36ba4a6b4d238ff944bacb478cbed5efcae784d7bf4f2ff80")
	require.NoError(t, err)

119
	l1ChainID := new(big.Int).SetUint64(defaultL1ChainID)
120 121 122
	dk, err := devkeys.NewMnemonicDevKeys(devkeys.TestMnemonic)
	require.NoError(t, err)

123 124
	l2ChainID1 := uint256.NewInt(1)
	l2ChainID2 := uint256.NewInt(2)
125

126
	loc, _ := testutil.LocalArtifacts(t)
127

128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147
	t.Run("two chains one after another", func(t *testing.T) {
		intent, st := newIntent(t, l1ChainID, dk, l2ChainID1, loc, loc)
		cg := ethClientCodeGetter(ctx, l1Client)

		require.NoError(t, deployer.ApplyPipeline(
			ctx,
			deployer.ApplyPipelineOpts{
				L1RPCUrl:           rpcURL,
				DeployerPrivateKey: pk,
				Intent:             intent,
				State:              st,
				Logger:             lgr,
				StateWriter:        pipeline.NoopStateWriter(),
			},
		))

		// create a new environment with wiped state to ensure we can continue using the
		// state from the previous deployment
		intent.Chains = append(intent.Chains, newChainIntent(t, dk, l1ChainID, l2ChainID2))

148 149
		require.NoError(t, deployer.ApplyPipeline(
			ctx,
150 151 152 153 154 155 156 157
			deployer.ApplyPipelineOpts{
				L1RPCUrl:           rpcURL,
				DeployerPrivateKey: pk,
				Intent:             intent,
				State:              st,
				Logger:             lgr,
				StateWriter:        pipeline.NoopStateWriter(),
			},
158 159
		))

160
		validateSuperchainDeployment(t, st, cg)
161
		validateOPChainDeployment(t, cg, st, intent, false)
162 163
	})

164 165 166 167
	t.Run("chain with tagged artifacts", func(t *testing.T) {
		intent, st := newIntent(t, l1ChainID, dk, l2ChainID1, loc, loc)
		intent.L1ContractsLocator = artifacts.DefaultL1ContractsLocator
		intent.L2ContractsLocator = artifacts.DefaultL2ContractsLocator
168

169
		require.ErrorIs(t, deployer.ApplyPipeline(
170
			ctx,
171 172 173 174 175 176 177 178
			deployer.ApplyPipelineOpts{
				L1RPCUrl:           rpcURL,
				DeployerPrivateKey: pk,
				Intent:             intent,
				State:              st,
				Logger:             lgr,
				StateWriter:        pipeline.NoopStateWriter(),
			},
179
		), pipeline.ErrRefusingToDeployTaggedReleaseWithoutOPCM)
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
type existingOPCMTest struct {
	name         string
	network      string
	l1Release    string
	l2Release    string
	l2AllocsFile string
	l1Semvers    *expectedL1Semvers
	l2Semvers    *inspect.L2PredeploySemvers
}

type expectedL1Semvers struct {
	SystemConfig            string
	PermissionedDisputeGame string
	MIPS                    string
	OptimismPortal          string
	AnchorStateRegistry     string
	DelayedWETH             string
	DisputeGameFactory      string
	PreimageOracle          string
	L1CrossDomainMessenger  string
	L1ERC721Bridge          string
	L1StandardBridge        string
	OptimismMintableERC20   string
}

208
func TestApplyExistingOPCM(t *testing.T) {
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
	expectedL2SemversV160 := &inspect.L2PredeploySemvers{
		L2ToL1MessagePasser:           "1.1.1-beta.1",
		DeployerWhitelist:             "1.1.1-beta.1",
		WETH:                          "1.0.0-beta.1",
		L2CrossDomainMessenger:        "2.1.1-beta.1",
		L2StandardBridge:              "1.11.1-beta.1",
		SequencerFeeVault:             "1.5.0-beta.2",
		OptimismMintableERC20Factory:  "1.10.1-beta.2",
		L1BlockNumber:                 "1.1.1-beta.1",
		GasPriceOracle:                "1.3.1-beta.1",
		L1Block:                       "1.5.1-beta.1",
		LegacyMessagePasser:           "1.1.1-beta.1",
		L2ERC721Bridge:                "1.7.1-beta.2",
		OptimismMintableERC721Factory: "1.4.1-beta.1",
		BaseFeeVault:                  "1.5.0-beta.2",
		L1FeeVault:                    "1.5.0-beta.2",
		SchemaRegistry:                "1.3.1-beta.1",
		EAS:                           "1.4.1-beta.1",
		CrossL2Inbox:                  "",
		L2toL2CrossDomainMessenger:    "",
		SuperchainWETH:                "",
		ETHLiquidity:                  "",
		SuperchainTokenBridge:         "",
		OptimismMintableERC20:         "1.4.0-beta.1",
		OptimismMintableERC721:        "1.3.1-beta.1",
	}

	expectedL1SemversV160 := &expectedL1Semvers{
		SystemConfig:            "2.2.0",
		PermissionedDisputeGame: "1.3.1-beta.3", // Deployment bug
		MIPS:                    "1.1.0",
		OptimismPortal:          "3.10.0",
		AnchorStateRegistry:     "2.0.1-beta.3", // Deployment bug
		DelayedWETH:             "1.1.0",
		DisputeGameFactory:      "1.0.0",
		PreimageOracle:          "1.1.2",
		L1CrossDomainMessenger:  "2.3.0",
		L1ERC721Bridge:          "2.1.0",
		L1StandardBridge:        "2.1.0",
		OptimismMintableERC20:   "1.9.0",
	}

	expectedL1SemversV180 := &expectedL1Semvers{
		SystemConfig:            "2.3.0",
		PermissionedDisputeGame: "1.3.1",
		MIPS:                    "1.2.1",
		OptimismPortal:          "3.10.0",
		AnchorStateRegistry:     "2.0.1-beta.3", // Deployment bug persisting across releases
		DelayedWETH:             "1.1.0",
		DisputeGameFactory:      "1.0.0",
		PreimageOracle:          "1.1.2",
		L1CrossDomainMessenger:  "2.3.0",
		L1ERC721Bridge:          "2.1.0",
		L1StandardBridge:        "2.1.0",
		OptimismMintableERC20:   "1.9.0",
	}

	tests := []existingOPCMTest{
		{
			"mainnet v1.6.0",
			"mainnet",
			"op-contracts/v1.6.0",
			"op-contracts/v1.7.0-beta.1+l2-contracts",
			"allocs-l2-v160-1.json.gz",
			expectedL1SemversV160,
			expectedL2SemversV160,
		},
		{
			"sepolia v1.6.0",
			"sepolia",
			"op-contracts/v1.6.0",
			"op-contracts/v1.7.0-beta.1+l2-contracts",
			"allocs-l2-v160-11155111.json.gz",
			expectedL1SemversV160,
			expectedL2SemversV160,
		},
		{
			"sepolia v1.8.0-rc.4",
			"sepolia",
			"op-contracts/v1.8.0-rc.4",
			// The L2 predeploys need to still be the v1.7.0 beta contracts.
			"op-contracts/v1.7.0-beta.1+l2-contracts",
			// The L2 predeploys do not change in version 1.8.0.
			"allocs-l2-v160-11155111.json.gz",
			expectedL1SemversV180,
			expectedL2SemversV160,
		},
	}
	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			testApplyExistingOPCM(t, tt)
		})
	}
302 303
}

304
func testApplyExistingOPCM(t *testing.T, testInfo existingOPCMTest) {
305 306
	op_e2e.InitParallel(t)

307 308 309 310 311 312 313 314 315 316 317 318 319 320 321
	var forkRPCUrl string
	var l1Versions standard.L1Versions
	var l1ChainID uint64
	if testInfo.network == "mainnet" {
		forkRPCUrl = os.Getenv("MAINNET_RPC_URL")
		l1Versions = standard.L1VersionsMainnet
		l1ChainID = 1
	} else if testInfo.network == "sepolia" {
		forkRPCUrl = os.Getenv("SEPOLIA_RPC_URL")
		l1Versions = standard.L1VersionsSepolia
		l1ChainID = 11155111
	} else {
		t.Fatalf("invalid network: %s", testInfo.network)
	}

322
	require.NotEmpty(t, forkRPCUrl, "no fork RPC URL provided")
323

324
	lgr := testlog.Logger(t, slog.LevelDebug)
325

326 327 328
	ctx, cancel := context.WithTimeout(context.Background(), 5*time.Minute)
	defer cancel()

329 330 331 332 333 334
	retryProxy := retryproxy.New(lgr, forkRPCUrl)
	require.NoError(t, retryProxy.Start())
	t.Cleanup(func() {
		require.NoError(t, retryProxy.Stop())
	})

335
	runner, err := anvil.New(
336
		retryProxy.Endpoint(),
337 338 339 340
		lgr,
	)
	require.NoError(t, err)

341 342 343 344
	require.NoError(t, runner.Start(ctx))
	t.Cleanup(func() {
		require.NoError(t, runner.Stop())
	})
345

346 347 348
	l1RPC, err := rpc.Dial(runner.RPCUrl())
	require.NoError(t, err)
	l1Client := ethclient.NewClient(l1RPC)
349
	require.NoError(t, err)
350

351
	l1ChainIDBig := new(big.Int).SetUint64(l1ChainID)
352 353 354
	dk, err := devkeys.NewMnemonicDevKeys(devkeys.TestMnemonic)
	require.NoError(t, err)
	// index 0 from Anvil's test set
355
	pk, err := crypto.HexToECDSA("ac0974bec39a17e36ba4a6b4d238ff944bacb478cbed5efcae784d7bf4f2ff80")
356
	require.NoError(t, err)
357

358
	l2ChainID := uint256.NewInt(777)
359

360 361
	// Hardcode the below tags to ensure the test is validating the correct
	// version even if the underlying tag changes
362 363
	intent, st := newIntent(
		t,
364
		l1ChainIDBig,
365 366
		dk,
		l2ChainID,
367 368
		artifacts.MustNewLocatorFromTag(testInfo.l1Release),
		artifacts.MustNewLocatorFromTag(testInfo.l2Release),
369
	)
370 371 372 373 374 375
	// NOTE: the reference allocs for version 1.6 contain the gov token, so we need to enable it
	// via override here.
	intent.GlobalDeployOverrides = map[string]any{
		"enableGovernance": true,
	}

376 377 378
	// Define a new create2 salt to avoid contract address collisions
	_, err = rand.Read(st.Create2Salt[:])
	require.NoError(t, err)
379

380 381
	require.NoError(t, deployer.ApplyPipeline(
		ctx,
382 383 384 385 386 387 388 389
		deployer.ApplyPipelineOpts{
			L1RPCUrl:           runner.RPCUrl(),
			DeployerPrivateKey: pk,
			Intent:             intent,
			State:              st,
			Logger:             lgr,
			StateWriter:        pipeline.NoopStateWriter(),
		},
390
	))
391

392
	validateOPChainDeployment(t, ethClientCodeGetter(ctx, l1Client), st, intent, true)
393

394
	releases := l1Versions[testInfo.l1Release]
395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412

	implTests := []struct {
		name    string
		expAddr common.Address
		actAddr common.Address
	}{
		{"OptimismPortal", releases.OptimismPortal.ImplementationAddress, st.ImplementationsDeployment.OptimismPortalImplAddress},
		{"SystemConfig,", releases.SystemConfig.ImplementationAddress, st.ImplementationsDeployment.SystemConfigImplAddress},
		{"L1CrossDomainMessenger", releases.L1CrossDomainMessenger.ImplementationAddress, st.ImplementationsDeployment.L1CrossDomainMessengerImplAddress},
		{"L1ERC721Bridge", releases.L1ERC721Bridge.ImplementationAddress, st.ImplementationsDeployment.L1ERC721BridgeImplAddress},
		{"L1StandardBridge", releases.L1StandardBridge.ImplementationAddress, st.ImplementationsDeployment.L1StandardBridgeImplAddress},
		{"OptimismMintableERC20Factory", releases.OptimismMintableERC20Factory.ImplementationAddress, st.ImplementationsDeployment.OptimismMintableERC20FactoryImplAddress},
		{"DisputeGameFactory", releases.DisputeGameFactory.ImplementationAddress, st.ImplementationsDeployment.DisputeGameFactoryImplAddress},
		{"MIPS", releases.MIPS.Address, st.ImplementationsDeployment.MipsSingletonAddress},
		{"PreimageOracle", releases.PreimageOracle.Address, st.ImplementationsDeployment.PreimageOracleSingletonAddress},
		{"DelayedWETH", releases.DelayedWETH.ImplementationAddress, st.ImplementationsDeployment.DelayedWETHImplAddress},
	}
	for _, tt := range implTests {
413 414 415
		require.Equal(t, tt.expAddr, tt.actAddr, "unexpected address for %s", tt.name)
	}

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
	chainState := st.Chains[0]
	versionTests := []struct {
		name       string
		expVersion string
		addr       common.Address
	}{
		{"SystemConfig", testInfo.l1Semvers.SystemConfig, chainState.SystemConfigProxyAddress},
		{"PermissionedDisputeGame", testInfo.l1Semvers.PermissionedDisputeGame, chainState.PermissionedDisputeGameAddress},
		{"MIPS", testInfo.l1Semvers.MIPS, st.ImplementationsDeployment.MipsSingletonAddress},
		{"OptimismPortal", testInfo.l1Semvers.OptimismPortal, chainState.OptimismPortalProxyAddress},
		{"AnchorStateRegistry", testInfo.l1Semvers.AnchorStateRegistry, chainState.AnchorStateRegistryProxyAddress},
		{"DelayedWETH", testInfo.l1Semvers.DelayedWETH, chainState.DelayedWETHPermissionedGameProxyAddress},
		{"DisputeGameFactory", testInfo.l1Semvers.DisputeGameFactory, chainState.DisputeGameFactoryProxyAddress},
		{"PreimageOracle", testInfo.l1Semvers.PreimageOracle, st.ImplementationsDeployment.PreimageOracleSingletonAddress},
		{"L1CrossDomainMessenger", testInfo.l1Semvers.L1CrossDomainMessenger, chainState.L1CrossDomainMessengerProxyAddress},
		{"L1ERC721Bridge", testInfo.l1Semvers.L1ERC721Bridge, chainState.L1ERC721BridgeProxyAddress},
		{"L1StandardBridge", testInfo.l1Semvers.L1StandardBridge, chainState.L1StandardBridgeProxyAddress},
		{"OptimismMintableERC20", testInfo.l1Semvers.OptimismMintableERC20, chainState.OptimismMintableERC20FactoryProxyAddress},
	}
	versionArgs, err := versionFunc.EncodeArgs()
	require.NoError(t, err)
	for _, tt := range versionTests {
		ret, err := l1Client.CallContract(ctx, ethereum.CallMsg{
			To:   &tt.addr,
			Data: versionArgs,
		}, nil)
		require.NoError(t, err)

		var actVersion string
		require.NoError(t, versionFunc.DecodeReturns(ret, &actVersion))
		require.Equal(t, tt.expVersion, actVersion, "unexpected version for %s", tt.name)
	}

449 450 451
	superchain, err := standard.SuperchainFor(l1ChainIDBig.Uint64())
	require.NoError(t, err)

452
	managerOwner, err := standard.SuperchainProxyAdminAddrFor(l1ChainIDBig.Uint64())
453 454 455 456 457 458 459 460 461 462 463 464 465
	require.NoError(t, err)

	superchainTests := []struct {
		name    string
		expAddr common.Address
		actAddr common.Address
	}{
		{"ProxyAdmin", managerOwner, st.SuperchainDeployment.ProxyAdminAddress},
		{"SuperchainConfig", common.Address(*superchain.Config.SuperchainConfigAddr), st.SuperchainDeployment.SuperchainConfigProxyAddress},
		{"ProtocolVersions", common.Address(*superchain.Config.ProtocolVersionsAddr), st.SuperchainDeployment.ProtocolVersionsProxyAddress},
	}
	for _, tt := range superchainTests {
		require.Equal(t, tt.expAddr, tt.actAddr, "unexpected address for %s", tt.name)
466
	}
467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486

	artifactsFSL2, cleanupL2, err := artifacts.Download(
		ctx,
		intent.L2ContractsLocator,
		artifacts.LogProgressor(lgr),
	)
	require.NoError(t, err)
	t.Cleanup(func() {
		require.NoError(t, cleanupL2())
	})

	chainIntent := intent.Chains[0]

	semvers, err := inspect.L2Semvers(inspect.L2SemversConfig{
		Lgr:        lgr,
		Artifacts:  artifactsFSL2,
		ChainState: chainState,
	})
	require.NoError(t, err)

487
	require.EqualValues(t, testInfo.l2Semvers, semvers)
488

489
	f, err := os.Open(fmt.Sprintf("./testdata/%s", testInfo.l2AllocsFile))
490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561
	require.NoError(t, err)
	defer f.Close()
	gzr, err := gzip.NewReader(f)
	require.NoError(t, err)
	defer gzr.Close()
	dec := json.NewDecoder(bufio.NewReader(gzr))
	var expAllocs types.GenesisAlloc
	require.NoError(t, dec.Decode(&expAllocs))

	type storageCheckerFunc func(addr common.Address, actStorage map[common.Hash]common.Hash)

	storageDiff := func(addr common.Address, expStorage, actStorage map[common.Hash]common.Hash) {
		require.EqualValues(t, expStorage, actStorage, "storage for %s differs", addr)
	}

	defaultStorageChecker := func(addr common.Address, actStorage map[common.Hash]common.Hash) {
		storageDiff(addr, expAllocs[addr].Storage, actStorage)
	}

	overrideStorageChecker := func(addr common.Address, actStorage, overrides map[common.Hash]common.Hash) {
		expStorage := make(map[common.Hash]common.Hash)
		maps.Copy(expStorage, expAllocs[addr].Storage)
		maps.Copy(expStorage, overrides)
		storageDiff(addr, expStorage, actStorage)
	}

	storageCheckers := map[common.Address]storageCheckerFunc{
		predeploys.L2CrossDomainMessengerAddr: func(addr common.Address, actStorage map[common.Hash]common.Hash) {
			overrideStorageChecker(addr, actStorage, map[common.Hash]common.Hash{
				{31: 0xcf}: common.BytesToHash(chainState.L1CrossDomainMessengerProxyAddress.Bytes()),
			})
		},
		predeploys.L2StandardBridgeAddr: func(addr common.Address, actStorage map[common.Hash]common.Hash) {
			overrideStorageChecker(addr, actStorage, map[common.Hash]common.Hash{
				{31: 0x04}: common.BytesToHash(chainState.L1StandardBridgeProxyAddress.Bytes()),
			})
		},
		predeploys.L2ERC721BridgeAddr: func(addr common.Address, actStorage map[common.Hash]common.Hash) {
			overrideStorageChecker(addr, actStorage, map[common.Hash]common.Hash{
				{31: 0x02}: common.BytesToHash(chainState.L1ERC721BridgeProxyAddress.Bytes()),
			})
		},
		predeploys.ProxyAdminAddr: func(addr common.Address, actStorage map[common.Hash]common.Hash) {
			overrideStorageChecker(addr, actStorage, map[common.Hash]common.Hash{
				{}: common.BytesToHash(intent.Chains[0].Roles.L2ProxyAdminOwner.Bytes()),
			})
		},
		// The ProxyAdmin owner is also set on the ProxyAdmin contract's implementation address, see
		// L2Genesis.s.sol line 292.
		common.HexToAddress("0xc0d3c0d3c0d3c0d3c0d3c0d3c0d3c0d3c0d30018"): func(addr common.Address, actStorage map[common.Hash]common.Hash) {
			overrideStorageChecker(addr, actStorage, map[common.Hash]common.Hash{
				{}: common.BytesToHash(chainIntent.Roles.L2ProxyAdminOwner.Bytes()),
			})
		},
	}

	//Use a custom equality function to compare the genesis allocs
	//because the reflect-based one is really slow
	actAllocs := st.Chains[0].Allocs.Data.Accounts
	for addr, expAcc := range expAllocs {
		actAcc, ok := actAllocs[addr]
		require.True(t, ok)
		require.True(t, expAcc.Balance.Cmp(actAcc.Balance) == 0, "balance for %s differs", addr)
		require.Equal(t, expAcc.Nonce, actAcc.Nonce, "nonce for %s differs", addr)
		require.Equal(t, hex.EncodeToString(expAllocs[addr].Code), hex.EncodeToString(actAcc.Code), "code for %s differs", addr)

		storageChecker, ok := storageCheckers[addr]
		if !ok {
			storageChecker = defaultStorageChecker
		}
		storageChecker(addr, actAcc.Storage)
	}
562 563 564 565 566 567 568
	for addr := range actAllocs {
		if _, ok := expAllocs[addr]; ok {
			continue
		}

		t.Logf("unexpected account: %s", addr.Hex())
	}
569 570
}

571
func TestGlobalOverrides(t *testing.T) {
572 573 574 575 576
	op_e2e.InitParallel(t)

	ctx, cancel := context.WithCancel(context.Background())
	defer cancel()

577
	opts, intent, st := setupGenesisChain(t, defaultL1ChainID)
578 579 580 581 582 583 584 585 586 587
	expectedGasLimit := strings.ToLower("0x1C9C380")
	expectedBaseFeeVaultRecipient := common.HexToAddress("0x0000000000000000000000000000000000000001")
	expectedL1FeeVaultRecipient := common.HexToAddress("0x0000000000000000000000000000000000000002")
	expectedSequencerFeeVaultRecipient := common.HexToAddress("0x0000000000000000000000000000000000000003")
	expectedBaseFeeVaultMinimumWithdrawalAmount := strings.ToLower("0x1BC16D674EC80000")
	expectedBaseFeeVaultWithdrawalNetwork := genesis.FromUint8(0)
	expectedEnableGovernance := false
	expectedGasPriceOracleBaseFeeScalar := uint32(1300)
	expectedEIP1559Denominator := uint64(500)
	expectedUseFaultProofs := false
588
	intent.GlobalDeployOverrides = map[string]interface{}{
589 590 591 592 593 594 595 596 597 598 599
		"l2BlockTime":                         float64(3),
		"l2GenesisBlockGasLimit":              expectedGasLimit,
		"baseFeeVaultRecipient":               expectedBaseFeeVaultRecipient,
		"l1FeeVaultRecipient":                 expectedL1FeeVaultRecipient,
		"sequencerFeeVaultRecipient":          expectedSequencerFeeVaultRecipient,
		"baseFeeVaultMinimumWithdrawalAmount": expectedBaseFeeVaultMinimumWithdrawalAmount,
		"baseFeeVaultWithdrawalNetwork":       expectedBaseFeeVaultWithdrawalNetwork,
		"enableGovernance":                    expectedEnableGovernance,
		"gasPriceOracleBaseFeeScalar":         expectedGasPriceOracleBaseFeeScalar,
		"eip1559Denominator":                  expectedEIP1559Denominator,
		"useFaultProofs":                      expectedUseFaultProofs,
600
	}
601

602
	require.NoError(t, deployer.ApplyPipeline(ctx, opts))
603 604 605 606

	cfg, err := state.CombineDeployConfig(intent, intent.Chains[0], st, st.Chains[0])
	require.NoError(t, err)
	require.Equal(t, uint64(3), cfg.L2InitializationConfig.L2CoreDeployConfig.L2BlockTime, "L2 block time should be 3 seconds")
607 608 609 610 611 612 613 614 615 616
	require.Equal(t, expectedGasLimit, strings.ToLower(cfg.L2InitializationConfig.L2GenesisBlockDeployConfig.L2GenesisBlockGasLimit.String()), "L2 Genesis Block Gas Limit should be 30_000_000")
	require.Equal(t, expectedBaseFeeVaultRecipient, cfg.L2InitializationConfig.L2VaultsDeployConfig.BaseFeeVaultRecipient, "Base Fee Vault Recipient should be the expected address")
	require.Equal(t, expectedL1FeeVaultRecipient, cfg.L2InitializationConfig.L2VaultsDeployConfig.L1FeeVaultRecipient, "L1 Fee Vault Recipient should be the expected address")
	require.Equal(t, expectedSequencerFeeVaultRecipient, cfg.L2InitializationConfig.L2VaultsDeployConfig.SequencerFeeVaultRecipient, "Sequencer Fee Vault Recipient should be the expected address")
	require.Equal(t, expectedBaseFeeVaultMinimumWithdrawalAmount, strings.ToLower(cfg.L2InitializationConfig.L2VaultsDeployConfig.BaseFeeVaultMinimumWithdrawalAmount.String()), "Base Fee Vault Minimum Withdrawal Amount should be the expected value")
	require.Equal(t, expectedBaseFeeVaultWithdrawalNetwork, cfg.L2InitializationConfig.L2VaultsDeployConfig.BaseFeeVaultWithdrawalNetwork, "Base Fee Vault Withdrawal Network should be the expected value")
	require.Equal(t, expectedEnableGovernance, cfg.L2InitializationConfig.GovernanceDeployConfig.EnableGovernance, "Governance should be disabled")
	require.Equal(t, expectedGasPriceOracleBaseFeeScalar, cfg.L2InitializationConfig.GasPriceOracleDeployConfig.GasPriceOracleBaseFeeScalar, "Gas Price Oracle Base Fee Scalar should be the expected value")
	require.Equal(t, expectedEIP1559Denominator, cfg.L2InitializationConfig.EIP1559DeployConfig.EIP1559Denominator, "EIP-1559 Denominator should be the expected value")
	require.Equal(t, expectedUseFaultProofs, cfg.L2InitializationConfig.UseInterop, "Fault proofs should be enabled")
617 618
}

619 620 621 622 623 624
func TestApplyGenesisStrategy(t *testing.T) {
	op_e2e.InitParallel(t)

	ctx, cancel := context.WithCancel(context.Background())
	defer cancel()

625
	opts, intent, st := setupGenesisChain(t, defaultL1ChainID)
626

627
	require.NoError(t, deployer.ApplyPipeline(ctx, opts))
628 629 630 631 632 633

	cg := stateDumpCodeGetter(st)
	validateSuperchainDeployment(t, st, cg)

	for i := range intent.Chains {
		t.Run(fmt.Sprintf("chain-%d", i), func(t *testing.T) {
634
			validateOPChainDeployment(t, cg, st, intent, false)
635 636 637 638
		})
	}
}

639 640
func TestProofParamOverrides(t *testing.T) {
	op_e2e.InitParallel(t)
641

642 643
	ctx, cancel := context.WithCancel(context.Background())
	defer cancel()
644

645
	opts, intent, st := setupGenesisChain(t, defaultL1ChainID)
646
	intent.GlobalDeployOverrides = map[string]any{
647 648 649
		"faultGameWithdrawalDelay":                standard.WithdrawalDelaySeconds + 1,
		"preimageOracleMinProposalSize":           standard.MinProposalSizeBytes + 1,
		"preimageOracleChallengePeriod":           standard.ChallengePeriodSeconds + 1,
650 651 652 653 654 655 656 657 658 659
		"proofMaturityDelaySeconds":               standard.ProofMaturityDelaySeconds + 1,
		"disputeGameFinalityDelaySeconds":         standard.DisputeGameFinalityDelaySeconds + 1,
		"mipsVersion":                             standard.MIPSVersion + 1,
		"disputeGameType":                         standard.DisputeGameType, // This must be set to the permissioned game
		"disputeAbsolutePrestate":                 common.Hash{'A', 'B', 'S', 'O', 'L', 'U', 'T', 'E'},
		"disputeMaxGameDepth":                     standard.DisputeMaxGameDepth + 1,
		"disputeSplitDepth":                       standard.DisputeSplitDepth + 1,
		"disputeClockExtension":                   standard.DisputeClockExtension + 1,
		"disputeMaxClockDuration":                 standard.DisputeMaxClockDuration + 1,
		"dangerouslyAllowCustomDisputeParameters": true,
660
	}
661

662
	require.NoError(t, deployer.ApplyPipeline(ctx, opts))
663

664 665
	allocs := st.L1StateDump.Data.Accounts
	chainState := st.Chains[0]
666

667 668
	uint64Caster := func(t *testing.T, val any) common.Hash {
		return common.BigToHash(new(big.Int).SetUint64(val.(uint64)))
669
	}
670

671 672 673 674 675 676
	tests := []struct {
		name    string
		caster  func(t *testing.T, val any) common.Hash
		address common.Address
	}{
		{
677
			"faultGameWithdrawalDelay",
678 679 680 681
			uint64Caster,
			st.ImplementationsDeployment.DelayedWETHImplAddress,
		},
		{
682
			"preimageOracleMinProposalSize",
683 684 685 686
			uint64Caster,
			st.ImplementationsDeployment.PreimageOracleSingletonAddress,
		},
		{
687
			"preimageOracleChallengePeriod",
688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730
			uint64Caster,
			st.ImplementationsDeployment.PreimageOracleSingletonAddress,
		},
		{
			"proofMaturityDelaySeconds",
			uint64Caster,
			st.ImplementationsDeployment.OptimismPortalImplAddress,
		},
		{
			"disputeGameFinalityDelaySeconds",
			uint64Caster,
			st.ImplementationsDeployment.OptimismPortalImplAddress,
		},
		{
			"disputeAbsolutePrestate",
			func(t *testing.T, val any) common.Hash {
				return val.(common.Hash)
			},
			chainState.PermissionedDisputeGameAddress,
		},
		{
			"disputeMaxGameDepth",
			uint64Caster,
			chainState.PermissionedDisputeGameAddress,
		},
		{
			"disputeSplitDepth",
			uint64Caster,
			chainState.PermissionedDisputeGameAddress,
		},
		{
			"disputeClockExtension",
			uint64Caster,
			chainState.PermissionedDisputeGameAddress,
		},
		{
			"disputeMaxClockDuration",
			uint64Caster,
			chainState.PermissionedDisputeGameAddress,
		},
	}
	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
731
			checkImmutable(t, allocs, tt.address, tt.caster(t, intent.GlobalDeployOverrides[tt.name]))
732
		})
733
	}
734
}
735

736 737
func TestInteropDeployment(t *testing.T) {
	op_e2e.InitParallel(t)
738

739
	ctx, cancel := context.WithCancel(context.Background())
740 741
	defer cancel()

742
	opts, intent, st := setupGenesisChain(t, defaultL1ChainID)
743
	intent.UseInterop = true
744

745
	require.NoError(t, deployer.ApplyPipeline(ctx, opts))
746

747 748
	chainState := st.Chains[0]
	depManagerSlot := common.HexToHash("0x1708e077affb93e89be2665fb0fb72581be66f84dc00d25fed755ae911905b1c")
749 750 751
	checkImmutable(t, st.L1StateDump.Data.Accounts, st.ImplementationsDeployment.SystemConfigImplAddress, depManagerSlot)
	proxyAdminOwnerHash := common.BytesToHash(intent.Chains[0].Roles.SystemConfigOwner.Bytes())
	checkStorageSlot(t, st.L1StateDump.Data.Accounts, chainState.SystemConfigProxyAddress, depManagerSlot, proxyAdminOwnerHash)
752
}
753

754 755 756 757 758 759
func TestAltDADeployment(t *testing.T) {
	op_e2e.InitParallel(t)

	ctx, cancel := context.WithCancel(context.Background())
	defer cancel()

760
	opts, intent, st := setupGenesisChain(t, defaultL1ChainID)
761 762 763 764 765 766 767 768 769 770
	altDACfg := genesis.AltDADeployConfig{
		UseAltDA:                   true,
		DACommitmentType:           altda.KeccakCommitmentString,
		DAChallengeWindow:          10,
		DAResolveWindow:            10,
		DABondSize:                 100,
		DAResolverRefundPercentage: 50,
	}
	intent.Chains[0].DangerousAltDAConfig = altDACfg

771
	require.NoError(t, deployer.ApplyPipeline(ctx, opts))
772 773 774 775 776 777 778 779 780 781 782 783 784 785 786

	chainState := st.Chains[0]
	require.NotEmpty(t, chainState.DataAvailabilityChallengeProxyAddress)
	require.NotEmpty(t, chainState.DataAvailabilityChallengeImplAddress)

	_, rollupCfg, err := inspect.GenesisAndRollup(st, chainState.ID)
	require.NoError(t, err)
	require.EqualValues(t, &rollup.AltDAConfig{
		CommitmentType:     altda.KeccakCommitmentString,
		DAChallengeWindow:  altDACfg.DAChallengeWindow,
		DAChallengeAddress: chainState.DataAvailabilityChallengeProxyAddress,
		DAResolveWindow:    altDACfg.DAResolveWindow,
	}, rollupCfg.AltDAConfig)
}

787
func TestInvalidL2Genesis(t *testing.T) {
788
	op_e2e.InitParallel(t)
789 790 791 792

	ctx, cancel := context.WithCancel(context.Background())
	defer cancel()

793 794
	// these tests were generated by grepping all usages of the deploy
	// config in L2Genesis.s.sol.
795
	tests := []struct {
796 797
		name      string
		overrides map[string]any
798 799
	}{
		{
800 801 802 803
			name: "L2 proxy admin owner not set",
			overrides: map[string]any{
				"proxyAdminOwner": nil,
			},
804 805
		},
		{
806 807 808
			name: "base fee vault recipient not set",
			overrides: map[string]any{
				"baseFeeVaultRecipient": nil,
809 810 811
			},
		},
		{
812 813 814 815
			name: "l1 fee vault recipient not set",
			overrides: map[string]any{
				"l1FeeVaultRecipient": nil,
			},
816 817
		},
		{
818 819 820 821
			name: "sequencer fee vault recipient not set",
			overrides: map[string]any{
				"sequencerFeeVaultRecipient": nil,
			},
822 823
		},
		{
824 825 826 827
			name: "l1 chain ID not set",
			overrides: map[string]any{
				"l1ChainID": nil,
			},
828 829
		},
		{
830 831 832 833
			name: "l2 chain ID not set",
			overrides: map[string]any{
				"l2ChainID": nil,
			},
834 835 836 837
		},
	}
	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
838
			opts, intent, _ := setupGenesisChain(t, defaultL1ChainID)
839 840 841
			intent.DeploymentStrategy = state.DeploymentStrategyGenesis
			intent.GlobalDeployOverrides = tt.overrides

842
			err := deployer.ApplyPipeline(ctx, opts)
843 844
			require.Error(t, err)
			require.ErrorContains(t, err, "failed to combine L2 init config")
845 846 847 848
		})
	}
}

849 850 851 852 853 854 855
func TestAdditionalDisputeGames(t *testing.T) {
	op_e2e.InitParallel(t)

	ctx, cancel := context.WithCancel(context.Background())
	defer cancel()

	opts, intent, st := setupGenesisChain(t, defaultL1ChainID)
856 857 858
	deployerAddr := crypto.PubkeyToAddress(opts.DeployerPrivateKey.PublicKey)
	(&intent.Chains[0].Roles).L1ProxyAdminOwner = deployerAddr
	intent.SuperchainRoles.Guardian = deployerAddr
859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875
	intent.GlobalDeployOverrides = map[string]any{
		"challengePeriodSeconds": 1,
	}
	intent.Chains[0].AdditionalDisputeGames = []state.AdditionalDisputeGame{
		{
			ChainProofParams: state.ChainProofParams{
				DisputeGameType:                         255,
				DisputeAbsolutePrestate:                 standard.DisputeAbsolutePrestate,
				DisputeMaxGameDepth:                     50,
				DisputeSplitDepth:                       14,
				DisputeClockExtension:                   0,
				DisputeMaxClockDuration:                 1200,
				DangerouslyAllowCustomDisputeParameters: true,
			},
			UseCustomOracle:              true,
			OracleMinProposalSize:        10000,
			OracleChallengePeriodSeconds: 120,
876
			MakeRespected:                true,
877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892
			VMType:                       state.VMTypeAlphabet,
		},
	}

	require.NoError(t, deployer.ApplyPipeline(ctx, opts))

	chainState := st.Chains[0]
	require.Equal(t, 1, len(chainState.AdditionalDisputeGames))

	gameInfo := chainState.AdditionalDisputeGames[0]
	require.NotEmpty(t, gameInfo.VMAddress)
	require.NotEmpty(t, gameInfo.GameAddress)
	require.NotEmpty(t, gameInfo.OracleAddress)
	require.NotEqual(t, st.ImplementationsDeployment.PreimageOracleSingletonAddress, gameInfo.OracleAddress)
}

893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946
func TestIntentConfiguration(t *testing.T) {
	op_e2e.InitParallel(t)

	tests := []struct {
		name       string
		mutator    func(*state.Intent)
		assertions func(t *testing.T, st *state.State)
	}{
		{
			"governance token disabled by default",
			func(intent *state.Intent) {},
			func(t *testing.T, st *state.State) {
				l2Genesis := st.Chains[0].Allocs.Data
				_, ok := l2Genesis.Accounts[predeploys.GovernanceTokenAddr]
				require.False(t, ok)
			},
		},
		{
			"governance token enabled via override",
			func(intent *state.Intent) {
				intent.GlobalDeployOverrides = map[string]any{
					"enableGovernance":     true,
					"governanceTokenOwner": common.Address{'O'}.Hex(),
				}
			},
			func(t *testing.T, st *state.State) {
				l2Genesis := st.Chains[0].Allocs.Data
				_, ok := l2Genesis.Accounts[predeploys.GovernanceTokenAddr]
				require.True(t, ok)
				checkStorageSlot(
					t,
					l2Genesis.Accounts,
					predeploys.GovernanceTokenAddr,
					common.Hash{31: 0x0a},
					common.BytesToHash(common.Address{'O'}.Bytes()),
				)
			},
		},
	}
	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			t.Parallel()

			ctx, cancel := context.WithCancel(context.Background())
			defer cancel()

			opts, intent, st := setupGenesisChain(t, defaultL1ChainID)
			tt.mutator(intent)
			require.NoError(t, deployer.ApplyPipeline(ctx, opts))
			tt.assertions(t, st)
		})
	}
}

947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987
func TestManageDependencies(t *testing.T) {
	t.Parallel()

	ctx, cancel := context.WithCancel(context.Background())
	defer cancel()

	l1ChainID := uint64(999)
	l1ChainIDBig := new(big.Int).SetUint64(l1ChainID)

	opts, intent, st := setupGenesisChain(t, l1ChainID)
	intent.UseInterop = true
	require.NoError(t, deployer.ApplyPipeline(ctx, opts))

	dk, err := devkeys.NewMnemonicDevKeys(devkeys.TestMnemonic)
	require.NoError(t, err)
	sysConfigOwner, err := dk.Address(devkeys.SystemConfigOwner.Key(l1ChainIDBig))
	require.NoError(t, err)

	// Have to recreate the host again since deployer.ApplyPipeline
	// doesn't expose the host directly.

	loc, _ := testutil.LocalArtifacts(t)
	afacts, _, err := artifacts.Download(ctx, loc, artifacts.NoopDownloadProgressor)
	require.NoError(t, err)

	host, err := env.DefaultScriptHost(
		broadcaster.NoopBroadcaster(),
		opts.Logger,
		sysConfigOwner,
		afacts,
	)
	require.NoError(t, err)
	host.ImportState(st.L1StateDump.Data)

	require.NoError(t, opcm.ManageDependencies(host, opcm.ManageDependenciesInput{
		ChainId:      big.NewInt(1234),
		SystemConfig: st.Chains[0].SystemConfigProxyAddress,
		Remove:       false,
	}))
}

988
func setupGenesisChain(t *testing.T, l1ChainID uint64) (deployer.ApplyPipelineOpts, *state.Intent, *state.State) {
989 990 991
	lgr := testlog.Logger(t, slog.LevelDebug)

	depKey := new(deployerKey)
992
	l1ChainIDBig := new(big.Int).SetUint64(l1ChainID)
993 994 995 996 997
	dk, err := devkeys.NewMnemonicDevKeys(devkeys.TestMnemonic)
	require.NoError(t, err)

	l2ChainID1 := uint256.NewInt(1)

998
	priv, err := dk.Secret(depKey)
999 1000
	require.NoError(t, err)

1001
	loc, _ := testutil.LocalArtifacts(t)
1002

1003
	intent, st := newIntent(t, l1ChainIDBig, dk, l2ChainID1, loc, loc)
1004
	intent.DeploymentStrategy = state.DeploymentStrategyGenesis
1005

1006 1007 1008 1009 1010 1011
	opts := deployer.ApplyPipelineOpts{
		DeployerPrivateKey: priv,
		Intent:             intent,
		State:              st,
		Logger:             lgr,
		StateWriter:        pipeline.NoopStateWriter(),
1012 1013
	}

1014
	return opts, intent, st
1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027
}

func addrFor(t *testing.T, dk *devkeys.MnemonicDevKeys, key devkeys.Key) common.Address {
	addr, err := dk.Address(key)
	require.NoError(t, err)
	return addr
}

func newIntent(
	t *testing.T,
	l1ChainID *big.Int,
	dk *devkeys.MnemonicDevKeys,
	l2ChainID *uint256.Int,
1028 1029
	l1Loc *artifacts.Locator,
	l2Loc *artifacts.Locator,
1030 1031
) (*state.Intent, *state.State) {
	intent := &state.Intent{
1032
		ConfigType:         state.IntentConfigTypeCustom,
1033 1034 1035 1036 1037 1038
		DeploymentStrategy: state.DeploymentStrategyLive,
		L1ChainID:          l1ChainID.Uint64(),
		SuperchainRoles: &state.SuperchainRoles{
			ProxyAdminOwner:       addrFor(t, dk, devkeys.L1ProxyAdminOwnerRole.Key(l1ChainID)),
			ProtocolVersionsOwner: addrFor(t, dk, devkeys.SuperchainDeployerKey.Key(l1ChainID)),
			Guardian:              addrFor(t, dk, devkeys.SuperchainConfigGuardianKey.Key(l1ChainID)),
1039
		},
1040
		FundDevAccounts:    false,
1041 1042 1043 1044
		L1ContractsLocator: l1Loc,
		L2ContractsLocator: l2Loc,
		Chains: []*state.ChainIntent{
			newChainIntent(t, dk, l1ChainID, l2ChainID),
1045
		},
1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058
	}
	st := &state.State{
		Version: 1,
	}
	return intent, st
}

func newChainIntent(t *testing.T, dk *devkeys.MnemonicDevKeys, l1ChainID *big.Int, l2ChainID *uint256.Int) *state.ChainIntent {
	return &state.ChainIntent{
		ID:                         l2ChainID.Bytes32(),
		BaseFeeVaultRecipient:      addrFor(t, dk, devkeys.BaseFeeVaultRecipientRole.Key(l1ChainID)),
		L1FeeVaultRecipient:        addrFor(t, dk, devkeys.L1FeeVaultRecipientRole.Key(l1ChainID)),
		SequencerFeeVaultRecipient: addrFor(t, dk, devkeys.SequencerFeeVaultRecipientRole.Key(l1ChainID)),
1059 1060 1061
		Eip1559DenominatorCanyon:   standard.Eip1559DenominatorCanyon,
		Eip1559Denominator:         standard.Eip1559Denominator,
		Eip1559Elasticity:          standard.Eip1559Elasticity,
1062
		Roles: state.ChainRoles{
1063 1064 1065 1066 1067 1068 1069
			L1ProxyAdminOwner: addrFor(t, dk, devkeys.L2ProxyAdminOwnerRole.Key(l1ChainID)),
			L2ProxyAdminOwner: addrFor(t, dk, devkeys.L2ProxyAdminOwnerRole.Key(l1ChainID)),
			SystemConfigOwner: addrFor(t, dk, devkeys.SystemConfigOwner.Key(l1ChainID)),
			UnsafeBlockSigner: addrFor(t, dk, devkeys.SequencerP2PRole.Key(l1ChainID)),
			Batcher:           addrFor(t, dk, devkeys.BatcherRole.Key(l1ChainID)),
			Proposer:          addrFor(t, dk, devkeys.ProposerRole.Key(l1ChainID)),
			Challenger:        addrFor(t, dk, devkeys.ChallengerRole.Key(l1ChainID)),
1070 1071
		},
	}
1072
}
1073

1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101
type codeGetter func(t *testing.T, addr common.Address) []byte

func ethClientCodeGetter(ctx context.Context, client *ethclient.Client) codeGetter {
	return func(t *testing.T, addr common.Address) []byte {
		code, err := client.CodeAt(ctx, addr, nil)
		require.NoError(t, err)
		return code
	}
}

func stateDumpCodeGetter(st *state.State) codeGetter {
	return func(t *testing.T, addr common.Address) []byte {
		acc, ok := st.L1StateDump.Data.Accounts[addr]
		require.True(t, ok, "no account found for address %s", addr)
		return acc.Code
	}
}

func validateSuperchainDeployment(t *testing.T, st *state.State, cg codeGetter) {
	addrs := []struct {
		name string
		addr common.Address
	}{
		{"SuperchainProxyAdmin", st.SuperchainDeployment.ProxyAdminAddress},
		{"SuperchainConfigProxy", st.SuperchainDeployment.SuperchainConfigProxyAddress},
		{"SuperchainConfigImpl", st.SuperchainDeployment.SuperchainConfigImplAddress},
		{"ProtocolVersionsProxy", st.SuperchainDeployment.ProtocolVersionsProxyAddress},
		{"ProtocolVersionsImpl", st.SuperchainDeployment.ProtocolVersionsImplAddress},
1102
		{"Opcm", st.ImplementationsDeployment.OpcmAddress},
1103 1104 1105 1106 1107 1108 1109
		{"PreimageOracleSingleton", st.ImplementationsDeployment.PreimageOracleSingletonAddress},
		{"MipsSingleton", st.ImplementationsDeployment.MipsSingletonAddress},
	}
	for _, addr := range addrs {
		t.Run(addr.name, func(t *testing.T) {
			code := cg(t, addr.addr)
			require.NotEmpty(t, code, "contract %s at %s has no code", addr.name, addr.addr)
1110 1111 1112
		})
	}
}
1113

1114
func validateOPChainDeployment(t *testing.T, cg codeGetter, st *state.State, intent *state.Intent, govEnabled bool) {
1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169
	// Validate that the implementation addresses are always set, even in subsequent deployments
	// that pull from an existing OPCM deployment.
	implAddrs := []struct {
		name string
		addr common.Address
	}{
		{"DelayedWETHImplAddress", st.ImplementationsDeployment.DelayedWETHImplAddress},
		{"OptimismPortalImplAddress", st.ImplementationsDeployment.OptimismPortalImplAddress},
		{"SystemConfigImplAddress", st.ImplementationsDeployment.SystemConfigImplAddress},
		{"L1CrossDomainMessengerImplAddress", st.ImplementationsDeployment.L1CrossDomainMessengerImplAddress},
		{"L1ERC721BridgeImplAddress", st.ImplementationsDeployment.L1ERC721BridgeImplAddress},
		{"L1StandardBridgeImplAddress", st.ImplementationsDeployment.L1StandardBridgeImplAddress},
		{"OptimismMintableERC20FactoryImplAddress", st.ImplementationsDeployment.OptimismMintableERC20FactoryImplAddress},
		{"DisputeGameFactoryImplAddress", st.ImplementationsDeployment.DisputeGameFactoryImplAddress},
		{"MipsSingletonAddress", st.ImplementationsDeployment.MipsSingletonAddress},
		{"PreimageOracleSingletonAddress", st.ImplementationsDeployment.PreimageOracleSingletonAddress},
	}
	for _, addr := range implAddrs {
		require.NotEmpty(t, addr.addr, "%s should be set", addr.name)
		code := cg(t, addr.addr)
		require.NotEmpty(t, code, "contract %s at %s has no code", addr.name, addr.addr)
	}

	for i, chainState := range st.Chains {
		chainAddrs := []struct {
			name string
			addr common.Address
		}{
			{"ProxyAdminAddress", chainState.ProxyAdminAddress},
			{"AddressManagerAddress", chainState.AddressManagerAddress},
			{"L1ERC721BridgeProxyAddress", chainState.L1ERC721BridgeProxyAddress},
			{"SystemConfigProxyAddress", chainState.SystemConfigProxyAddress},
			{"OptimismMintableERC20FactoryProxyAddress", chainState.OptimismMintableERC20FactoryProxyAddress},
			{"L1StandardBridgeProxyAddress", chainState.L1StandardBridgeProxyAddress},
			{"L1CrossDomainMessengerProxyAddress", chainState.L1CrossDomainMessengerProxyAddress},
			{"OptimismPortalProxyAddress", chainState.OptimismPortalProxyAddress},
			{"DisputeGameFactoryProxyAddress", chainState.DisputeGameFactoryProxyAddress},
			{"AnchorStateRegistryProxyAddress", chainState.AnchorStateRegistryProxyAddress},
			{"FaultDisputeGameAddress", chainState.FaultDisputeGameAddress},
			{"PermissionedDisputeGameAddress", chainState.PermissionedDisputeGameAddress},
			{"DelayedWETHPermissionedGameProxyAddress", chainState.DelayedWETHPermissionedGameProxyAddress},
			// {"DelayedWETHPermissionlessGameProxyAddress", chainState.DelayedWETHPermissionlessGameProxyAddress},
		}
		for _, addr := range chainAddrs {
			// TODO Delete this `if`` block once FaultDisputeGameAddress is deployed.
			if addr.name == "FaultDisputeGameAddress" {
				continue
			}
			code := cg(t, addr.addr)
			require.NotEmpty(t, code, "contract %s at %s for chain %s has no code", addr.name, addr.addr, chainState.ID)
		}

		alloc := chainState.Allocs.Data.Accounts

		chainIntent := intent.Chains[i]
1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180
		checkImmutableBehindProxy(t, alloc, predeploys.BaseFeeVaultAddr, chainIntent.BaseFeeVaultRecipient)
		checkImmutableBehindProxy(t, alloc, predeploys.L1FeeVaultAddr, chainIntent.L1FeeVaultRecipient)
		checkImmutableBehindProxy(t, alloc, predeploys.SequencerFeeVaultAddr, chainIntent.SequencerFeeVaultRecipient)
		checkImmutableBehindProxy(t, alloc, predeploys.OptimismMintableERC721FactoryAddr, common.BigToHash(new(big.Int).SetUint64(intent.L1ChainID)))

		// ownership slots
		var addrAsSlot common.Hash
		addrAsSlot.SetBytes(chainIntent.Roles.L1ProxyAdminOwner.Bytes())
		// slot 0
		ownerSlot := common.Hash{}
		checkStorageSlot(t, alloc, predeploys.ProxyAdminAddr, ownerSlot, addrAsSlot)
1181 1182 1183 1184 1185 1186 1187 1188 1189

		if govEnabled {
			var defaultGovOwner common.Hash
			defaultGovOwner.SetBytes(common.HexToAddress("0xDeaDDEaDDeAdDeAdDEAdDEaddeAddEAdDEAdDEad").Bytes())
			checkStorageSlot(t, alloc, predeploys.GovernanceTokenAddr, common.Hash{31: 0x0a}, defaultGovOwner)
		} else {
			_, ok := alloc[predeploys.GovernanceTokenAddr]
			require.False(t, ok, "governance token should not be deployed by default")
		}
1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206

		require.Equal(t, int(chainIntent.Eip1559Denominator), 50, "EIP1559Denominator should be set")
		require.Equal(t, int(chainIntent.Eip1559Elasticity), 6, "EIP1559Elasticity should be set")
	}
}

func getEIP1967ImplementationAddress(t *testing.T, allocations types.GenesisAlloc, proxyAddress common.Address) common.Address {
	storage := allocations[proxyAddress].Storage
	storageValue := storage[genesis.ImplementationSlot]
	require.NotEmpty(t, storageValue, "Implementation address for %s should be set", proxyAddress)
	return common.HexToAddress(storageValue.Hex())
}

type bytesMarshaler interface {
	Bytes() []byte
}

1207
func checkImmutableBehindProxy(t *testing.T, allocations types.GenesisAlloc, proxyContract common.Address, thing bytesMarshaler) {
1208
	implementationAddress := getEIP1967ImplementationAddress(t, allocations, proxyContract)
1209
	checkImmutable(t, allocations, implementationAddress, thing)
1210 1211
}

1212
func checkImmutable(t *testing.T, allocations types.GenesisAlloc, implementationAddress common.Address, thing bytesMarshaler) {
1213
	account, ok := allocations[implementationAddress]
1214 1215 1216 1217 1218 1219 1220
	require.True(t, ok, "%s not found in allocations", implementationAddress)
	require.NotEmpty(t, account.Code, "%s should have code", implementationAddress)
	require.True(
		t,
		bytes.Contains(account.Code, thing.Bytes()),
		"%s code should contain %s immutable", implementationAddress, hex.EncodeToString(thing.Bytes()),
	)
1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233
}

func checkStorageSlot(t *testing.T, allocs types.GenesisAlloc, address common.Address, slot common.Hash, expected common.Hash) {
	account, ok := allocs[address]
	require.True(t, ok, "account not found for address %s", address)
	value, ok := account.Storage[slot]
	if expected == (common.Hash{}) {
		require.False(t, ok, "slot %s for account %s should not be set", slot, address)
		return
	}
	require.True(t, ok, "slot %s not found for account %s", slot, address)
	require.Equal(t, expected, value, "slot %s for account %s should be %s", slot, address, expected)
}