Commit 1a982215 authored by smartcontracts's avatar smartcontracts Committed by GitHub

feat: Add support for hardhat-deploy (#249)

* Another stab at a good hardhat-deploy

* Testing etherscan verifications

* Fix linting

* remove artifacts

* keep old deploy script

* remove old hardhat-typechain dependency

* remove unused import

* remove kovan config

* Tweak deployment a bit

* Clean up defaults

* rename hardhat => hh

* Use mock bond manager

* Make deploy a bit more robust

* I committed my private key again. There goes my goerli eth

* and my infura api key too

* Fix lint errors

* Use strict ordering

* refactor: use helper for easy AddressManager deployments (#350)

* Clean up georgios pr

* use dotenv to manage deployer keys

* Update src/hardhat-deploy-ethers.ts
Co-authored-by: default avatarGeorgios Konstantopoulos <me@gakonst.com>

* Stricter checking on address set

* add argument for sequencer address

* minor tweaks to console.log comments

* move predeploy addresses into their own file

* add small comment for clarity

* update deploy script

* fix incorrect env var in deploy script

* adding deploy.js shim to get ci to work

* simplify deployment environment vars

* temporary tweaks to get a ci run to pass

* print out deploy artifacts

* fix artifact log output format

* fix contract names in artifact log output

* add eth gateway to deploy

* add OVM_Proposer to address manager

* add some comments for clarity

* remove bytecode hash from compiler settings

* minor tweaks in response to review

* transfer address manager ownership after deploy

* explicitly attach deployer to address manager
Co-authored-by: default avatarGeorgios Konstantopoulos <me@gakonst.com>
parent 888f2486
# name of the network to deploy to e.g., kovan or mainnet
CONTRACTS_TARGET_NETWORK=
# private key for the account that will execute the deploy
CONTRACTS_DEPLOYER_KEY=
# rpc url for the node that will receive deploy transactions
CONTRACTS_RPC_URL=
...@@ -10,3 +10,6 @@ build/ ...@@ -10,3 +10,6 @@ build/
# Coverage output # Coverage output
coverage/ coverage/
coverage.json coverage.json
# Environment variables
.env
#!/usr/bin/env node #!/usr/bin/env node
const contracts = require('../build/src/contract-deployment/deploy'); const path = require('path')
const { providers, Wallet, utils, ethers } = require('ethers'); const { spawn } = require('child_process')
const { LedgerSigner } = require('@ethersproject/hardware-wallets'); const dirtree = require('directory-tree')
const { JsonRpcProvider } = providers;
const main = async () => {
const env = process.env; const task = spawn(path.join(__dirname, 'deploy.ts'))
const key = env.DEPLOYER_PRIVATE_KEY;
const sequencerKey = env.SEQUENCER_PRIVATE_KEY; await new Promise((resolve) => {
let SEQUENCER_ADDRESS = env.SEQUENCER_ADDRESS; task.on('exit', () => {
const web3Url = env.L1_NODE_WEB3_URL || 'http://127.0.0.1:8545'; resolve()
const DEPLOY_TX_GAS_LIMIT = env.DEPLOY_TX_GAS_LIMIT || 5000000; })
const MIN_TRANSACTION_GAS_LIMIT = env.MIN_TRANSACTION_GAS_LIMIT || 50000; })
const MAX_TRANSACTION_GAS_LIMIT = env.MAX_TRANSACTION_GAS_LIMIT || 9000000;
const MAX_GAS_PER_QUEUE_PER_EPOCH = env.MAX_GAS_PER_QUEUE_PER_EPOCH || 250000000; // Stuff below this line is currently required for CI to work properly. We probably want to
const SECONDS_PER_EPOCH = env.SECONDS_PER_EPOCH || 0; // update our CI so this is no longer necessary. But I'm adding it for backwards compat so we can
const WAIT_FOR_RECEIPTS = env.WAIT_FOR_RECEIPTS === 'true'; // get the hardhat-deploy stuff merged. Woot.
let WHITELIST_OWNER = env.WHITELIST_OWNER; const nicknames = {
const WHITELIST_ALLOW_ARBITRARY_CONTRACT_DEPLOYMENT = env.WHITELIST_ALLOW_ARBITRARY_CONTRACT_DEPLOYMENT || true; 'Lib_AddressManager': 'AddressManager',
const FORCE_INCLUSION_PERIOD_SECONDS = env.FORCE_INCLUSION_PERIOD_SECONDS || 2592000; // 30 days 'mockOVM_BondManager': 'OVM_BondManager'
const FRAUD_PROOF_WINDOW_SECONDS = env.FRAUD_PROOF_WINDOW_SECONDS || (60 * 60 * 24 * 7); // 7 days
const SEQUENCER_PUBLISH_WINDOW_SECONDS = env.SEQUENCER_PUBLISH_WINDOW_SECONDS || (60 * 30); // 30 min
const CHAIN_ID = env.CHAIN_ID || 420; // layer 2 chainid
const USE_LEDGER = env.USE_LEDGER || false;
const ADDRESS_MANAGER_ADDRESS = env.ADDRESS_MANAGER_ADDRESS || undefined;
const HD_PATH = env.HD_PATH || utils.defaultPath;
const BLOCK_TIME_SECONDS = env.BLOCK_TIME_SECONDS || 15;
const L2_CROSS_DOMAIN_MESSENGER_ADDRESS =
env.L2_CROSS_DOMAIN_MESSENGER_ADDRESS || '0x4200000000000000000000000000000000000007';
let RELAYER_ADDRESS = env.RELAYER_ADDRESS || '0x0000000000000000000000000000000000000000';
const RELAYER_PRIVATE_KEY = env.RELAYER_PRIVATE_KEY;
(async () => {
const provider = new JsonRpcProvider(web3Url);
let signer;
// Use the ledger for the deployer
if (USE_LEDGER) {
signer = new LedgerSigner(provider, 'default', HD_PATH);
} else {
if (typeof key === 'undefined')
throw new Error('Must pass deployer key as DEPLOYER_PRIVATE_KEY');
signer = new Wallet(key, provider);
} }
if (SEQUENCER_ADDRESS) { const contracts = dirtree(
if (!utils.isAddress(SEQUENCER_ADDRESS)) path.resolve(__dirname, `../deployments/custom`)
throw new Error(`Invalid Sequencer Address: ${SEQUENCER_ADDRESS}`); ).children.filter((child) => {
} else { return child.extension === '.json'
if (!sequencerKey) }).reduce((contracts, child) => {
throw new Error('Must pass sequencer key as SEQUENCER_PRIVATE_KEY'); const contractName = child.name.replace('.json', '')
const sequencer = new Wallet(sequencerKey, provider); const artifact = require(path.resolve(__dirname, `../deployments/custom/${child.name}`))
SEQUENCER_ADDRESS = await sequencer.getAddress(); contracts[nicknames[contractName] || contractName] = artifact.address
} return contracts
}, {})
if (typeof WHITELIST_OWNER === 'undefined')
WHITELIST_OWNER = signer; // We *must* console.log here because CI will pipe the output of this script into an
// addresses.json file. Also something we should probably remove.
// Use the address derived from RELAYER_PRIVATE_KEY if a private key console.log(JSON.stringify(contracts, null, 2))
// is passed. Using the zero address as the relayer address will mean }
// there is no relayer authentication.
if (RELAYER_PRIVATE_KEY) { main()
if (!utils.isAddress(RELAYER_ADDRESS)) .then(() => process.exit(0))
throw new Error(`Invalid Relayer Address: ${RELAYER_ADDRESS}`); .catch((error) => {
const relayer = new Wallet(RELAYER_PRIVATE_KEY, provider); console.log(
RELAYER_ADDRESS = await relayer.getAddress(); JSON.stringify({ error: error.message, stack: error.stack }, null, 2)
} )
process.exit(1)
const result = await contracts.deploy({ })
deploymentSigner: signer,
transactionChainConfig: {
forceInclusionPeriodSeconds: FORCE_INCLUSION_PERIOD_SECONDS,
sequencer: SEQUENCER_ADDRESS,
forceInclusionPeriodBlocks: Math.ceil(FORCE_INCLUSION_PERIOD_SECONDS/BLOCK_TIME_SECONDS),
},
stateChainConfig: {
fraudProofWindowSeconds: FRAUD_PROOF_WINDOW_SECONDS,
sequencerPublishWindowSeconds: SEQUENCER_PUBLISH_WINDOW_SECONDS,
},
ovmGlobalContext: {
ovmCHAINID: CHAIN_ID,
L2CrossDomainMessengerAddress: L2_CROSS_DOMAIN_MESSENGER_ADDRESS
},
l1CrossDomainMessengerConfig: {
relayerAddress: RELAYER_ADDRESS,
},
ovmGasMeteringConfig: {
minTransactionGasLimit: MIN_TRANSACTION_GAS_LIMIT,
maxTransactionGasLimit: MAX_TRANSACTION_GAS_LIMIT,
maxGasPerQueuePerEpoch: MAX_GAS_PER_QUEUE_PER_EPOCH,
secondsPerEpoch: SECONDS_PER_EPOCH
},
whitelistConfig: {
owner: WHITELIST_OWNER,
allowArbitraryContractDeployment: WHITELIST_ALLOW_ARBITRARY_CONTRACT_DEPLOYMENT
},
deployOverrides: {
gasLimit: DEPLOY_TX_GAS_LIMIT
},
waitForReceipts: WAIT_FOR_RECEIPTS,
addressManager: ADDRESS_MANAGER_ADDRESS,
});
const { failedDeployments, AddressManager } = result;
if (failedDeployments.length !== 0)
throw new Error(`Contract deployment failed: ${failedDeployments.join(',')}`);
const out = {};
out.AddressManager = AddressManager.address;
out.OVM_Sequencer = SEQUENCER_ADDRESS;
out.Deployer = await signer.getAddress()
for (const [name, contract] of Object.entries(result.contracts)) {
out[name] = contract.address;
}
console.log(JSON.stringify(out, null, 2));
})().catch(err => {
console.log(JSON.stringify({error: err.message, stack: err.stack}, null, 2));
process.exit(1);
});
#!/usr/bin/env ts-node-script
import { Wallet } from 'ethers'
// Ensures that all relevant environment vars are properly set. These lines *must* come before the
// hardhat import because importing will load the config (which relies on these vars). Necessary
// because CI currently uses different var names than the ones we've chosen here.
// TODO: Update CI so that we don't have to do this anymore.
process.env.HARDHAT_NETWORK = 'custom' // "custom" here is an arbitrary name. only used for CI.
process.env.CONTRACTS_TARGET_NETWORK = 'custom'
process.env.CONTRACTS_DEPLOYER_KEY = process.env.DEPLOYER_PRIVATE_KEY
process.env.CONTRACTS_RPC_URL =
process.env.L1_NODE_WEB3_URL || 'http://127.0.0.1:8545'
import hre from 'hardhat'
const main = async () => {
const sequencer = new Wallet(process.env.SEQUENCER_PRIVATE_KEY)
const deployer = new Wallet(process.env.DEPLOYER_PRIVATE_KEY)
await hre.run('deploy', {
l1BlockTimeSeconds: process.env.BLOCK_TIME_SECONDS,
ctcForceInclusionPeriodSeconds: process.env.FORCE_INCLUSION_PERIOD_SECONDS,
ctcMaxTransactionGasLimit: process.env.MAX_TRANSACTION_GAS_LIMIT,
emMinTransactionGasLimit: process.env.MIN_TRANSACTION_GAS_LIMIT,
emMaxtransactionGasLimit: process.env.MAX_TRANSACTION_GAS_LIMIT,
emMaxGasPerQueuePerEpoch: process.env.MAX_GAS_PER_QUEUE_PER_EPOCH,
emSecondsPerEpoch: process.env.SECONDS_PER_EPOCH,
emOvmChainId: process.env.CHAIN_ID,
sccFraudProofWindow: parseInt(process.env.FRAUD_PROOF_WINDOW_SECONDS, 10),
sccSequencerPublishWindow: process.env.SEQUENCER_PUBLISH_WINDOW_SECONDS,
ovmSequencerAddress: sequencer.address,
ovmProposerAddress: sequencer.address,
ovmRelayerAddress: sequencer.address,
ovmAddressManagerOwner: deployer.address,
})
}
main()
.then(() => process.exit(0))
.catch((error) => {
console.log(
JSON.stringify({ error: error.message, stack: error.stack }, null, 2)
)
process.exit(1)
})
/* Imports: External */
import { DeployFunction } from 'hardhat-deploy/dist/types'
/* Imports: Internal */
import { registerAddress } from '../src/hardhat-deploy-ethers'
import { predeploys } from '../src/predeploys'
const deployFn: DeployFunction = async (hre) => {
const { deploy } = hre.deployments
const { deployer } = await hre.getNamedAccounts()
await deploy('Lib_AddressManager', {
from: deployer,
args: [],
log: true,
})
await registerAddress({
hre,
name: 'OVM_L2CrossDomainMessenger',
address: predeploys.OVM_L2CrossDomainMessenger,
})
await registerAddress({
hre,
name: 'OVM_DecompressionPrecompileAddress',
address: predeploys.OVM_SequencerEntrypoint,
})
await registerAddress({
hre,
name: 'OVM_Sequencer',
address: (hre as any).deployConfig.ovmSequencerAddress,
})
await registerAddress({
hre,
name: 'OVM_Proposer',
address: (hre as any).deployConfig.ovmProposerAddress,
})
await registerAddress({
hre,
name: 'OVM_L2BatchMessageRelayer',
address: (hre as any).deployConfig.ovmRelayerAddress,
})
}
deployFn.tags = ['Lib_AddressManager', 'required']
export default deployFn
/* Imports: External */
import { DeployFunction } from 'hardhat-deploy/dist/types'
/* Imports: Internal */
import {
deployAndRegister,
getDeployedContract,
} from '../src/hardhat-deploy-ethers'
const deployFn: DeployFunction = async (hre) => {
const Lib_AddressManager = await getDeployedContract(
hre,
'Lib_AddressManager'
)
await deployAndRegister({
hre,
name: 'OVM_ChainStorageContainer:CTC:batches',
contract: 'OVM_ChainStorageContainer',
args: [Lib_AddressManager.address, 'OVM_CanonicalTransactionChain'],
})
}
deployFn.dependencies = ['Lib_AddressManager']
deployFn.tags = ['OVM_ChainStorageContainer_ctc_batches']
export default deployFn
/* Imports: External */
import { DeployFunction } from 'hardhat-deploy/dist/types'
/* Imports: Internal */
import {
deployAndRegister,
getDeployedContract,
} from '../src/hardhat-deploy-ethers'
const deployFn: DeployFunction = async (hre) => {
const Lib_AddressManager = await getDeployedContract(
hre,
'Lib_AddressManager'
)
await deployAndRegister({
hre,
name: 'OVM_ChainStorageContainer:CTC:queue',
contract: 'OVM_ChainStorageContainer',
args: [Lib_AddressManager.address, 'OVM_CanonicalTransactionChain'],
})
}
deployFn.dependencies = ['Lib_AddressManager']
deployFn.tags = ['OVM_ChainStorageContainer_ctc_queue']
export default deployFn
/* Imports: External */
import { DeployFunction } from 'hardhat-deploy/dist/types'
/* Imports: Internal */
import {
deployAndRegister,
getDeployedContract,
} from '../src/hardhat-deploy-ethers'
const deployFn: DeployFunction = async (hre) => {
const Lib_AddressManager = await getDeployedContract(
hre,
'Lib_AddressManager'
)
await deployAndRegister({
hre,
name: 'OVM_ChainStorageContainer:SCC:batches',
contract: 'OVM_ChainStorageContainer',
args: [Lib_AddressManager.address, 'OVM_StateCommitmentChain'],
})
}
deployFn.dependencies = ['Lib_AddressManager']
deployFn.tags = ['OVM_ChainStorageContainer_scc_batches']
export default deployFn
/* Imports: External */
import { DeployFunction } from 'hardhat-deploy/dist/types'
/* Imports: Internal */
import {
deployAndRegister,
getDeployedContract,
} from '../src/hardhat-deploy-ethers'
const deployFn: DeployFunction = async (hre) => {
const Lib_AddressManager = await getDeployedContract(
hre,
'Lib_AddressManager'
)
await deployAndRegister({
hre,
name: 'OVM_CanonicalTransactionChain',
args: [
Lib_AddressManager.address,
(hre as any).deployConfig.ctcForceInclusionPeriodSeconds,
(hre as any).deployConfig.ctcForceInclusionPeriodBlocks,
(hre as any).deployConfig.ctcMaxTransactionGasLimit,
],
})
}
deployFn.dependencies = ['Lib_AddressManager']
deployFn.tags = ['OVM_CanonicalTransactionChain']
export default deployFn
/* Imports: External */
import { DeployFunction } from 'hardhat-deploy/dist/types'
/* Imports: Internal */
import {
deployAndRegister,
getDeployedContract,
} from '../src/hardhat-deploy-ethers'
const deployFn: DeployFunction = async (hre) => {
const Lib_AddressManager = await getDeployedContract(
hre,
'Lib_AddressManager'
)
await deployAndRegister({
hre,
name: 'OVM_StateCommitmentChain',
args: [
Lib_AddressManager.address,
(hre as any).deployConfig.sccFraudProofWindow,
(hre as any).deployConfig.sccSequencerPublishWindow,
],
})
}
deployFn.dependencies = ['Lib_AddressManager']
deployFn.tags = ['OVM_StateCommitmentChain']
export default deployFn
/* Imports: External */
import { DeployFunction } from 'hardhat-deploy/dist/types'
/* Imports: Internal */
import { getDeployedContract } from '../src/hardhat-deploy-ethers'
const deployFn: DeployFunction = async (hre) => {
const { deploy } = hre.deployments
const { deployer } = await hre.getNamedAccounts()
const Lib_AddressManager = await getDeployedContract(
hre,
'Lib_AddressManager',
{
signerOrProvider: deployer,
}
)
const result = await deploy('mockOVM_BondManager', {
from: deployer,
args: [Lib_AddressManager.address],
log: true,
})
if (!result.newlyDeployed) {
return
}
await Lib_AddressManager.setAddress('OVM_BondManager', result.address)
}
deployFn.dependencies = ['Lib_AddressManager']
deployFn.tags = ['mockOVM_BondManager']
export default deployFn
/* Imports: External */
import { DeployFunction } from 'hardhat-deploy/dist/types'
/* Imports: Internal */
import { getDeployedContract } from '../src/hardhat-deploy-ethers'
const deployFn: DeployFunction = async (hre) => {
const { deploy } = hre.deployments
const { deployer } = await hre.getNamedAccounts()
const Lib_AddressManager = await getDeployedContract(
hre,
'Lib_AddressManager',
{
signerOrProvider: deployer,
}
)
const result = await deploy('OVM_L1CrossDomainMessenger', {
from: deployer,
args: [],
log: true,
})
if (!result.newlyDeployed) {
return
}
const OVM_L1CrossDomainMessenger = await getDeployedContract(
hre,
'OVM_L1CrossDomainMessenger',
{
signerOrProvider: deployer,
}
)
// NOTE: this initialization is *not* technically required (we only need to initialize the proxy)
// but it feels safer to initialize this anyway. Otherwise someone else could come along and
// initialize this.
await OVM_L1CrossDomainMessenger.initialize(Lib_AddressManager.address)
const libAddressManager = await OVM_L1CrossDomainMessenger.libAddressManager()
if (libAddressManager !== Lib_AddressManager.address) {
throw new Error(
`\n**FATAL ERROR. THIS SHOULD NEVER HAPPEN. CHECK YOUR DEPLOYMENT.**:\n` +
`OVM_L1CrossDomainMessenger could not be succesfully initialized.\n` +
`Attempted to set Lib_AddressManager to: ${Lib_AddressManager.address}\n` +
`Actual address after initialization: ${libAddressManager}\n` +
`This could indicate a compromised deployment.`
)
}
await Lib_AddressManager.setAddress(
'OVM_L1CrossDomainMessenger',
result.address
)
}
deployFn.dependencies = ['Lib_AddressManager']
deployFn.tags = ['OVM_L1CrossDomainMessenger']
export default deployFn
/* Imports: External */
import { DeployFunction } from 'hardhat-deploy/dist/types'
/* Imports: Internal */
import { getDeployedContract } from '../src/hardhat-deploy-ethers'
const deployFn: DeployFunction = async (hre) => {
const { deploy } = hre.deployments
const { deployer } = await hre.getNamedAccounts()
const Lib_AddressManager = await getDeployedContract(
hre,
'Lib_AddressManager',
{
signerOrProvider: deployer,
}
)
const result = await deploy('Proxy__OVM_L1CrossDomainMessenger', {
contract: 'Lib_ResolvedDelegateProxy',
from: deployer,
args: [Lib_AddressManager.address, 'OVM_L1CrossDomainMessenger'],
log: true,
})
if (!result.newlyDeployed) {
return
}
const Proxy__OVM_L1CrossDomainMessenger = await getDeployedContract(
hre,
'Proxy__OVM_L1CrossDomainMessenger',
{
signerOrProvider: deployer,
iface: 'OVM_L1CrossDomainMessenger',
}
)
await Proxy__OVM_L1CrossDomainMessenger.initialize(Lib_AddressManager.address)
const libAddressManager = await Proxy__OVM_L1CrossDomainMessenger.libAddressManager()
if (libAddressManager !== Lib_AddressManager.address) {
throw new Error(
`\n**FATAL ERROR. THIS SHOULD NEVER HAPPEN. CHECK YOUR DEPLOYMENT.**:\n` +
`Proxy__OVM_L1CrossDomainMessenger could not be succesfully initialized.\n` +
`Attempted to set Lib_AddressManager to: ${Lib_AddressManager.address}\n` +
`Actual address after initialization: ${libAddressManager}\n` +
`This could indicate a compromised deployment.`
)
}
await Lib_AddressManager.setAddress(
'Proxy__OVM_L1CrossDomainMessenger',
result.address
)
}
deployFn.dependencies = ['Lib_AddressManager', 'OVM_L1CrossDomainMessenger']
deployFn.tags = ['Proxy__OVM_L1CrossDomainMessenger']
export default deployFn
/* Imports: External */
import { DeployFunction } from 'hardhat-deploy/dist/types'
/* Imports: Internal */
import {
deployAndRegister,
getDeployedContract,
} from '../src/hardhat-deploy-ethers'
const deployFn: DeployFunction = async (hre) => {
const Lib_AddressManager = await getDeployedContract(
hre,
'Lib_AddressManager'
)
await deployAndRegister({
hre,
name: 'OVM_ExecutionManager',
args: [
Lib_AddressManager.address,
{
minTransactionGasLimit: (hre as any).deployConfig
.emMinTransactionGasLimit,
maxTransactionGasLimit: (hre as any).deployConfig
.emMaxTransactionGasLimit,
maxGasPerQueuePerEpoch: (hre as any).deployConfig
.emMaxGasPerQueuePerEpoch,
secondsPerEpoch: (hre as any).deployConfig.emSecondsPerEpoch,
},
{
ovmCHAINID: (hre as any).deployConfig.emOvmChainId,
},
],
})
}
deployFn.dependencies = ['Lib_AddressManager']
deployFn.tags = ['OVM_ExecutionManager']
export default deployFn
/* Imports: External */
import { DeployFunction } from 'hardhat-deploy/dist/types'
/* Imports: Internal */
import {
deployAndRegister,
getDeployedContract,
} from '../src/hardhat-deploy-ethers'
const deployFn: DeployFunction = async (hre) => {
const Lib_AddressManager = await getDeployedContract(
hre,
'Lib_AddressManager'
)
await deployAndRegister({
hre,
name: 'OVM_FraudVerifier',
args: [Lib_AddressManager.address],
})
}
deployFn.dependencies = ['Lib_AddressManager']
deployFn.tags = ['OVM_FraudVerifier']
export default deployFn
/* Imports: External */
import { DeployFunction } from 'hardhat-deploy/dist/types'
/* Imports: Internal */
import { deployAndRegister } from '../src/hardhat-deploy-ethers'
const deployFn: DeployFunction = async (hre) => {
await deployAndRegister({
hre,
name: 'OVM_StateManagerFactory',
args: [],
})
}
deployFn.tags = ['OVM_FraudVerifier']
export default deployFn
/* Imports: External */
import { DeployFunction } from 'hardhat-deploy/dist/types'
/* Imports: Internal */
import {
deployAndRegister,
getDeployedContract,
} from '../src/hardhat-deploy-ethers'
const deployFn: DeployFunction = async (hre) => {
const Lib_AddressManager = await getDeployedContract(
hre,
'Lib_AddressManager'
)
await deployAndRegister({
hre,
name: 'OVM_StateTransitionerFactory',
args: [Lib_AddressManager.address],
})
}
deployFn.dependencies = ['Lib_AddressManager']
deployFn.tags = ['OVM_StateTransitionerFactory']
export default deployFn
/* Imports: External */
import { DeployFunction } from 'hardhat-deploy/dist/types'
/* Imports: Internal */
import { deployAndRegister } from '../src/hardhat-deploy-ethers'
const deployFn: DeployFunction = async (hre) => {
await deployAndRegister({
hre,
name: 'OVM_SafetyChecker',
args: [],
})
}
deployFn.tags = ['OVM_SafetyChecker']
export default deployFn
/* Imports: External */
import { DeployFunction } from 'hardhat-deploy/dist/types'
/* Imports: Internal */
import {
deployAndRegister,
getDeployedContract,
} from '../src/hardhat-deploy-ethers'
const deployFn: DeployFunction = async (hre) => {
const Lib_AddressManager = await getDeployedContract(
hre,
'Lib_AddressManager'
)
await deployAndRegister({
hre,
name: 'OVM_L1MultiMessageRelayer',
args: [Lib_AddressManager.address],
})
}
deployFn.dependencies = ['Lib_AddressManager']
deployFn.tags = ['OVM_L1MultiMessageRelayer']
export default deployFn
/* Imports: External */
import { DeployFunction } from 'hardhat-deploy/dist/types'
/* Imports: Internal */
import { getDeployedContract } from '../src/hardhat-deploy-ethers'
import { predeploys } from '../src/predeploys'
const deployFn: DeployFunction = async (hre) => {
const { deploy } = hre.deployments
const { deployer } = await hre.getNamedAccounts()
const Lib_AddressManager = await getDeployedContract(
hre,
'Lib_AddressManager',
{
signerOrProvider: deployer,
}
)
const result = await deploy('OVM_L1ETHGateway', {
from: deployer,
args: [],
log: true,
})
if (!result.newlyDeployed) {
return
}
const OVM_L1ETHGateway = await getDeployedContract(hre, 'OVM_L1ETHGateway', {
signerOrProvider: deployer,
})
// NOTE: this initialization is *not* technically required (we only need to initialize the proxy)
// but it feels safer to initialize this anyway. Otherwise someone else could come along and
// initialize this.
await OVM_L1ETHGateway.initialize(
Lib_AddressManager.address,
predeploys.OVM_ETH
)
const libAddressManager = await OVM_L1ETHGateway.libAddressManager()
if (libAddressManager !== Lib_AddressManager.address) {
throw new Error(
`\n**FATAL ERROR. THIS SHOULD NEVER HAPPEN. CHECK YOUR DEPLOYMENT.**:\n` +
`OVM_L1ETHGateway could not be succesfully initialized.\n` +
`Attempted to set Lib_AddressManager to: ${Lib_AddressManager.address}\n` +
`Actual address after initialization: ${libAddressManager}\n` +
`This could indicate a compromised deployment.`
)
}
await Lib_AddressManager.setAddress('OVM_L1ETHGateway', result.address)
}
deployFn.dependencies = ['Lib_AddressManager']
deployFn.tags = ['OVM_L1ETHGateway']
export default deployFn
/* Imports: External */
import { DeployFunction } from 'hardhat-deploy/dist/types'
/* Imports: Internal */
import { getDeployedContract } from '../src/hardhat-deploy-ethers'
import { predeploys } from '../src/predeploys'
const deployFn: DeployFunction = async (hre) => {
const { deploy } = hre.deployments
const { deployer } = await hre.getNamedAccounts()
const Lib_AddressManager = await getDeployedContract(
hre,
'Lib_AddressManager',
{
signerOrProvider: deployer,
}
)
const result = await deploy('Proxy__OVM_L1ETHGateway', {
contract: 'Lib_ResolvedDelegateProxy',
from: deployer,
args: [Lib_AddressManager.address, 'OVM_L1ETHGateway'],
log: true,
})
if (!result.newlyDeployed) {
return
}
const Proxy__OVM_L1ETHGateway = await getDeployedContract(
hre,
'Proxy__OVM_L1ETHGateway',
{
signerOrProvider: deployer,
iface: 'OVM_L1ETHGateway',
}
)
await Proxy__OVM_L1ETHGateway.initialize(
Lib_AddressManager.address,
predeploys.OVM_ETH
)
const libAddressManager = await Proxy__OVM_L1ETHGateway.libAddressManager()
if (libAddressManager !== Lib_AddressManager.address) {
throw new Error(
`\n**FATAL ERROR. THIS SHOULD NEVER HAPPEN. CHECK YOUR DEPLOYMENT.**:\n` +
`Proxy__OVM_L1ETHGateway could not be succesfully initialized.\n` +
`Attempted to set Lib_AddressManager to: ${Lib_AddressManager.address}\n` +
`Actual address after initialization: ${libAddressManager}\n` +
`This could indicate a compromised deployment.`
)
}
await Lib_AddressManager.setAddress('Proxy__OVM_L1ETHGateway', result.address)
}
deployFn.dependencies = ['Lib_AddressManager', 'OVM_L1ETHGateway']
deployFn.tags = ['Proxy__OVM_L1ETHGateway']
export default deployFn
/* Imports: External */
import { DeployFunction } from 'hardhat-deploy/dist/types'
/* Imports: Internal */
import { getDeployedContract } from '../src/hardhat-deploy-ethers'
const deployFn: DeployFunction = async (hre) => {
const { deployer } = await hre.getNamedAccounts()
const Lib_AddressManager = await getDeployedContract(
hre,
'Lib_AddressManager',
{
signerOrProvider: deployer,
}
)
const owner = (hre as any).deployConfig.ovmAddressManagerOwner
const remoteOwner = await Lib_AddressManager.owner()
if (remoteOwner === owner) {
console.log(
`✓ Not changing owner of Lib_AddressManager because it's already correctly set`
)
return
}
console.log(`Transferring ownership of Lib_AddressManager to ${owner}...`)
const tx = await Lib_AddressManager.transferOwnership(owner)
await tx.wait()
const newRemoteOwner = await Lib_AddressManager.owner()
if (newRemoteOwner !== owner) {
throw new Error(
`\n**FATAL ERROR. THIS SHOULD NEVER HAPPEN. CHECK YOUR DEPLOYMENT.**:\n` +
`Could not transfer ownership of Lib_AddressManager.\n` +
`Attempted to set owner of Lib_AddressManager to: ${owner}\n` +
`Actual owner after transaction: ${newRemoteOwner}\n` +
`This could indicate a compromised deployment.`
)
}
console.log(`✓ Set owner of Lib_AddressManager to: ${owner}`)
}
deployFn.dependencies = ['Lib_AddressManager']
deployFn.tags = ['finalize']
export default deployFn
import { HardhatUserConfig } from 'hardhat/types' import { HardhatUserConfig } from 'hardhat/types'
import 'solidity-coverage' import 'solidity-coverage'
import * as dotenv from 'dotenv'
import { import {
DEFAULT_ACCOUNTS_HARDHAT, DEFAULT_ACCOUNTS_HARDHAT,
...@@ -9,14 +10,22 @@ import { ...@@ -9,14 +10,22 @@ import {
// Hardhat plugins // Hardhat plugins
import '@nomiclabs/hardhat-ethers' import '@nomiclabs/hardhat-ethers'
import '@nomiclabs/hardhat-waffle' import '@nomiclabs/hardhat-waffle'
import 'hardhat-deploy'
import '@typechain/hardhat' import '@typechain/hardhat'
import '@eth-optimism/plugins/hardhat/compiler' import '@eth-optimism/plugins/hardhat/compiler'
import './hh'
// Load environment variables from .env
dotenv.config()
const config: HardhatUserConfig = { const config: HardhatUserConfig = {
networks: { networks: {
hardhat: { hardhat: {
accounts: DEFAULT_ACCOUNTS_HARDHAT, accounts: DEFAULT_ACCOUNTS_HARDHAT,
blockGasLimit: RUN_OVM_TEST_GAS * 2, blockGasLimit: RUN_OVM_TEST_GAS * 2,
live: false,
saveDeployments: false,
tags: ['local'],
}, },
}, },
mocha: { mocha: {
...@@ -26,6 +35,9 @@ const config: HardhatUserConfig = { ...@@ -26,6 +35,9 @@ const config: HardhatUserConfig = {
version: '0.7.6', version: '0.7.6',
settings: { settings: {
optimizer: { enabled: true, runs: 200 }, optimizer: { enabled: true, runs: 200 },
metadata: {
bytecodeHash: 'none',
},
outputSelection: { outputSelection: {
'*': { '*': {
'*': ['storageLayout'], '*': ['storageLayout'],
...@@ -37,6 +49,29 @@ const config: HardhatUserConfig = { ...@@ -37,6 +49,29 @@ const config: HardhatUserConfig = {
outDir: 'build/types', outDir: 'build/types',
target: 'ethers-v5', target: 'ethers-v5',
}, },
paths: {
deploy: './deploy',
deployments: './deployments',
},
namedAccounts: {
deployer: {
default: 0,
},
},
}
if (
process.env.CONTRACTS_TARGET_NETWORK &&
process.env.CONTRACTS_DEPLOYER_KEY &&
process.env.CONTRACTS_RPC_URL
) {
config.networks[process.env.CONTRACTS_TARGET_NETWORK] = {
accounts: [process.env.CONTRACTS_DEPLOYER_KEY],
url: process.env.CONTRACTS_RPC_URL,
live: true,
saveDeployments: true,
tags: [process.env.CONTRACTS_TARGET_NETWORK],
}
} }
export default config export default config
import './tasks/task-deploy'
/* Imports: External */
import { ethers } from 'ethers'
import { task } from 'hardhat/config'
import * as types from 'hardhat/internal/core/params/argumentTypes'
const DEFAULT_L1_BLOCK_TIME_SECONDS = 15
const DEFAULT_CTC_FORCE_INCLUSION_PERIOD_SECONDS = 60 * 60 * 24 * 30 // 30 days
const DEFAULT_CTC_MAX_TRANSACTION_GAS_LIMIT = 9_000_000
const DEFAULT_EM_MIN_TRANSACTION_GAS_LIMIT = 50_000
const DEFAULT_EM_MAX_TRANSACTION_GAS_LIMIT = 9_000_000
const DEFAULT_EM_MAX_GAS_PER_QUEUE_PER_EPOCH = 250_000_000
const DEFAULT_EM_SECONDS_PER_EPOCH = 0
const DEFAULT_EM_OVM_CHAIN_ID = 420
const DEFAULT_SCC_FRAUD_PROOF_WINDOW = 60 * 60 * 24 * 7 // 7 days
const DEFAULT_SCC_SEQUENCER_PUBLISH_WINDOW = 60 * 30 // 30 minutes
task('deploy')
.addOptionalParam(
'l1BlockTimeSeconds',
'Number of seconds on average between every L1 block.',
DEFAULT_L1_BLOCK_TIME_SECONDS,
types.int
)
.addOptionalParam(
'ctcForceInclusionPeriodSeconds',
'Number of seconds that the sequencer has to include transactions before the L1 queue.',
DEFAULT_CTC_FORCE_INCLUSION_PERIOD_SECONDS,
types.int
)
.addOptionalParam(
'ctcMaxTransactionGasLimit',
'Max gas limit for L1 queue transactions.',
DEFAULT_CTC_MAX_TRANSACTION_GAS_LIMIT,
types.int
)
.addOptionalParam(
'emMinTransactionGasLimit',
'Minimum allowed transaction gas limit.',
DEFAULT_EM_MIN_TRANSACTION_GAS_LIMIT,
types.int
)
.addOptionalParam(
'emMaxTransactionGasLimit',
'Maximum allowed transaction gas limit.',
DEFAULT_EM_MAX_TRANSACTION_GAS_LIMIT,
types.int
)
.addOptionalParam(
'emMaxGasPerQueuePerEpoch',
'Maximum gas allowed in a given queue for each epoch.',
DEFAULT_EM_MAX_GAS_PER_QUEUE_PER_EPOCH,
types.int
)
.addOptionalParam(
'emSecondsPerEpoch',
'Number of seconds in each epoch.',
DEFAULT_EM_SECONDS_PER_EPOCH,
types.int
)
.addOptionalParam(
'emOvmChainId',
'Chain ID for the L2 network.',
DEFAULT_EM_OVM_CHAIN_ID,
types.int
)
.addOptionalParam(
'sccFraudProofWindow',
'Number of seconds until a transaction is considered finalized.',
DEFAULT_SCC_FRAUD_PROOF_WINDOW,
types.int
)
.addOptionalParam(
'sccSequencerPublishWindow',
'Number of seconds that the sequencer is exclusively allowed to post state roots.',
DEFAULT_SCC_SEQUENCER_PUBLISH_WINDOW,
types.int
)
.addOptionalParam(
'ovmSequencerAddress',
'Address of the sequencer. Must be provided or this deployment will fail.',
undefined,
types.string
)
.addOptionalParam(
'ovmProposerAddress',
'Address of the account that will propose state roots. Must be provided or this deployment will fail.',
undefined,
types.string
)
.addOptionalParam(
'ovmRelayerAddress',
'Address of the message relayer. Must be provided or this deployment will fail.',
undefined,
types.string
)
.addOptionalParam(
'ovmAddressManagerOwner',
'Address that will own the Lib_AddressManager. Must be provided or this deployment will fail.',
undefined,
types.string
)
.setAction(async (args, hre: any, runSuper) => {
// Necessary because hardhat doesn't let us attach non-optional parameters to existing tasks.
const validateAddressArg = (argName: string) => {
if (args[argName] === undefined) {
throw new Error(
`argument for ${argName} is required but was not provided`
)
}
if (!ethers.utils.isAddress(args[argName])) {
throw new Error(
`argument for ${argName} is not a valid address: ${args[argName]}`
)
}
}
validateAddressArg('ovmSequencerAddress')
validateAddressArg('ovmProposerAddress')
validateAddressArg('ovmRelayerAddress')
validateAddressArg('ovmAddressManagerOwner')
args.ctcForceInclusionPeriodBlocks = Math.floor(
args.ctcForceInclusionPeriodSeconds / args.l1BlockTimeSeconds
)
hre.deployConfig = args
return runSuper(args)
})
...@@ -32,7 +32,7 @@ ...@@ -32,7 +32,7 @@
"test:coverage": "NODE_OPTIONS=--max_old_space_size=8192 hardhat coverage", "test:coverage": "NODE_OPTIONS=--max_old_space_size=8192 hardhat coverage",
"lint": "yarn lint:fix && yarn lint:check", "lint": "yarn lint:fix && yarn lint:check",
"lint:check": "tslint --format stylish --project .", "lint:check": "tslint --format stylish --project .",
"lint:fix": "prettier --config prettier-config.json --write \"hardhat.config.ts\" \"{src,test}/**/*.ts\"", "lint:fix": "prettier --config prettier-config.json --write \"hardhat.config.ts\" \"{src,test,hh,deploy,bin}/**/*.ts\"",
"clean": "rm -rf ./build ./artifacts ./artifacts-ovm ./cache ./cache-ovm", "clean": "rm -rf ./build ./artifacts ./artifacts-ovm ./cache ./cache-ovm",
"deploy": "./bin/deploy.js", "deploy": "./bin/deploy.js",
"serve": "./bin/serve_dump.sh" "serve": "./bin/serve_dump.sh"
...@@ -53,6 +53,7 @@ ...@@ -53,6 +53,7 @@
"@eth-optimism/dev": "^1.1.1", "@eth-optimism/dev": "^1.1.1",
"@eth-optimism/plugins": "^1.0.0-alpha.2", "@eth-optimism/plugins": "^1.0.0-alpha.2",
"@eth-optimism/smock": "1.0.0-alpha.3", "@eth-optimism/smock": "1.0.0-alpha.3",
"@ethersproject/abstract-signer": "^5.0.14",
"@nomiclabs/hardhat-ethers": "^2.0.1", "@nomiclabs/hardhat-ethers": "^2.0.1",
"@nomiclabs/hardhat-waffle": "^2.0.1", "@nomiclabs/hardhat-waffle": "^2.0.1",
"@typechain/ethers-v5": "1.0.0", "@typechain/ethers-v5": "1.0.0",
...@@ -62,9 +63,12 @@ ...@@ -62,9 +63,12 @@
"buffer-xor": "^2.0.2", "buffer-xor": "^2.0.2",
"chai": "^4.3.1", "chai": "^4.3.1",
"copyfiles": "^2.3.0", "copyfiles": "^2.3.0",
"directory-tree": "^2.2.7",
"dotenv": "^8.2.0",
"ethereum-waffle": "^3.3.0", "ethereum-waffle": "^3.3.0",
"ethers": "^5.0.31", "ethers": "^5.0.31",
"hardhat": "^2.0.8", "hardhat": "^2.0.8",
"hardhat-deploy": "^0.7.0-beta.50",
"lodash": "^4.17.20", "lodash": "^4.17.20",
"merkle-patricia-tree": "^4.0.0", "merkle-patricia-tree": "^4.0.0",
"merkletreejs": "^0.2.12", "merkletreejs": "^0.2.12",
......
...@@ -8,6 +8,7 @@ import { fromHexString, toHexString, remove0x } from '@eth-optimism/core-utils' ...@@ -8,6 +8,7 @@ import { fromHexString, toHexString, remove0x } from '@eth-optimism/core-utils'
/* Internal Imports */ /* Internal Imports */
import { deploy, RollupDeployConfig } from './contract-deployment' import { deploy, RollupDeployConfig } from './contract-deployment'
import { getContractDefinition } from './contract-defs' import { getContractDefinition } from './contract-defs'
import { predeploys } from './predeploys'
interface StorageDump { interface StorageDump {
[key: string]: string [key: string]: string
...@@ -160,19 +161,6 @@ export const makeStateDump = async (cfg: RollupDeployConfig): Promise<any> => { ...@@ -160,19 +161,6 @@ export const makeStateDump = async (cfg: RollupDeployConfig): Promise<any> => {
config = { ...config, ...cfg } config = { ...config, ...cfg }
const predeploys = {
OVM_L2ToL1MessagePasser: '0x4200000000000000000000000000000000000000',
OVM_L1MessageSender: '0x4200000000000000000000000000000000000001',
OVM_DeployerWhitelist: '0x4200000000000000000000000000000000000002',
OVM_ECDSAContractAccount: '0x4200000000000000000000000000000000000003',
OVM_ProxySequencerEntrypoint: '0x4200000000000000000000000000000000000004',
OVM_SequencerEntrypoint: '0x4200000000000000000000000000000000000005',
OVM_ETH: '0x4200000000000000000000000000000000000006',
OVM_L2CrossDomainMessenger: '0x4200000000000000000000000000000000000007',
Lib_AddressManager: '0x4200000000000000000000000000000000000008',
ERC1820Registry: '0x1820a4B7618BdE71Dce8cdc73aAB6C95905faD24',
}
const ovmCompiled = [ const ovmCompiled = [
'OVM_L2ToL1MessagePasser', 'OVM_L2ToL1MessagePasser',
'OVM_L2CrossDomainMessenger', 'OVM_L2CrossDomainMessenger',
......
/* Imports: External */
import { Contract } from 'ethers'
import { Provider } from '@ethersproject/abstract-provider'
import { Signer } from '@ethersproject/abstract-signer'
import { HardhatRuntimeEnvironment } from 'hardhat/types'
export const registerAddress = async ({
hre,
name,
address,
}): Promise<void> => {
// TODO: Cache these 2 across calls?
const { deployer } = await hre.getNamedAccounts()
const Lib_AddressManager = await getDeployedContract(
hre,
'Lib_AddressManager',
{
signerOrProvider: deployer,
}
)
const currentAddress = await Lib_AddressManager.getAddress(name)
if (address === currentAddress) {
console.log(
`✓ Not registering address for ${name} because it's already been correctly registered`
)
return
}
console.log(`Registering address for ${name} to ${address}...`)
const tx = await Lib_AddressManager.setAddress(name, address)
await tx.wait()
const remoteAddress = await Lib_AddressManager.getAddress(name)
if (remoteAddress !== address) {
throw new Error(
`\n**FATAL ERROR. THIS SHOULD NEVER HAPPEN. CHECK YOUR DEPLOYMENT.**:\n` +
`Call to Lib_AddressManager.setAddress(${name}) was unsuccessful.\n` +
`Attempted to set address to: ${address}\n` +
`Actual address was set to: ${remoteAddress}\n` +
`This could indicate a compromised deployment.`
)
}
console.log(`✓ Registered address for ${name}`)
}
export const deployAndRegister = async ({
hre,
name,
args,
contract,
}: {
hre: HardhatRuntimeEnvironment
name: string
args: any[]
contract?: string
}) => {
const { deploy } = hre.deployments
const { deployer } = await hre.getNamedAccounts()
const result = await deploy(name, {
contract,
from: deployer,
args,
log: true,
})
await hre.ethers.provider.waitForTransaction(result.transactionHash)
if (result.newlyDeployed) {
await registerAddress({
hre,
name,
address: result.address,
})
}
}
export const getDeployedContract = async (
hre: HardhatRuntimeEnvironment,
name: string,
options: {
iface?: string
signerOrProvider?: Signer | Provider | string
} = {}
): Promise<Contract> => {
const deployed = await hre.deployments.get(name)
await hre.ethers.provider.waitForTransaction(deployed.receipt.transactionHash)
// Get the correct interface.
let iface = new hre.ethers.utils.Interface(deployed.abi)
if (options.iface) {
const factory = await hre.ethers.getContractFactory(options.iface)
iface = factory.interface
}
let signerOrProvider: Signer | Provider = hre.ethers.provider
if (options.signerOrProvider) {
if (typeof options.signerOrProvider === 'string') {
signerOrProvider = hre.ethers.provider.getSigner(options.signerOrProvider)
} else {
signerOrProvider = options.signerOrProvider
}
}
// Temporarily override Object.defineProperty to bypass ether's object protection.
const def = Object.defineProperty
Object.defineProperty = (obj, propName, prop) => {
prop.writable = true
return def(obj, propName, prop)
}
const contract = new Contract(deployed.address, iface, signerOrProvider)
// Now reset Object.defineProperty
Object.defineProperty = def
// Override each function call to also `.wait()` so as to simplify the deploy scripts' syntax.
for (const fnName of Object.keys(contract.functions)) {
const fn = contract[fnName].bind(contract)
;(contract as any)[fnName] = async (...args: any) => {
const result = await fn(...args)
if (typeof result === 'object' && typeof result.wait === 'function') {
await result.wait()
}
return result
}
}
return contract
}
export const predeploys = {
OVM_L2ToL1MessagePasser: '0x4200000000000000000000000000000000000000',
OVM_L1MessageSender: '0x4200000000000000000000000000000000000001',
OVM_DeployerWhitelist: '0x4200000000000000000000000000000000000002',
OVM_ECDSAContractAccount: '0x4200000000000000000000000000000000000003',
OVM_ProxySequencerEntrypoint: '0x4200000000000000000000000000000000000004',
OVM_SequencerEntrypoint: '0x4200000000000000000000000000000000000005',
OVM_ETH: '0x4200000000000000000000000000000000000006',
OVM_L2CrossDomainMessenger: '0x4200000000000000000000000000000000000007',
Lib_AddressManager: '0x4200000000000000000000000000000000000008',
ERC1820Registry: '0x1820a4B7618BdE71Dce8cdc73aAB6C95905faD24',
}
...@@ -2,6 +2,7 @@ ...@@ -2,6 +2,7 @@
"extends": "@eth-optimism/dev/tslint.json", "extends": "@eth-optimism/dev/tslint.json",
"rules": { "rules": {
"array-type": false, "array-type": false,
"class-name": false "class-name": false,
"prefer-conditional-expression": false
} }
} }
This diff is collapsed.
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment