deploy-utils.ts 8.36 KB
Newer Older
1
import { ethers, Contract } from 'ethers'
2 3
import { Provider } from '@ethersproject/abstract-provider'
import { Signer } from '@ethersproject/abstract-signer'
4
import { sleep, awaitCondition } from '@eth-optimism/core-utils'
5
import { HttpNetworkConfig } from 'hardhat/types'
6

7 8
import { getDeployConfig } from './deploy-config'

9 10 11 12 13 14 15 16 17
/**
 * @param  {Any} hre Hardhat runtime environment
 * @param  {String} name Contract name from the names object
 * @param  {Any[]} args Constructor arguments
 * @param  {String} contract Name of the solidity contract
 * @param  {String} iface Alternative interface for calling the contract
 * @param  {Function} postDeployAction Called after deployment
 */

18
export const deployAndVerifyAndThen = async ({
19 20 21 22
  hre,
  name,
  args,
  contract,
23 24
  iface,
  postDeployAction,
25
}: {
26
  hre: any
27 28 29
  name: string
  args: any[]
  contract?: string
30 31
  iface?: string
  postDeployAction?: (contract: Contract) => Promise<void>
32 33 34
}) => {
  const { deploy } = hre.deployments
  const { deployer } = await hre.getNamedAccounts()
35
  const deployConfig = getDeployConfig(hre.network.name)
36 37 38 39 40 41

  const result = await deploy(name, {
    contract,
    from: deployer,
    args,
    log: true,
42
    waitConfirmations: deployConfig.numDeployConfirmations,
43 44 45 46 47
  })

  await hre.ethers.provider.waitForTransaction(result.transactionHash)

  if (result.newlyDeployed) {
Maurelian's avatar
Maurelian committed
48
    if (!(await isHardhatNode(hre))) {
49 50 51 52 53 54 55 56 57
      // Verification sometimes fails, even when the contract is correctly deployed and eventually
      // verified. Possibly due to a race condition. We don't want to halt the whole deployment
      // process just because that happens.
      try {
        console.log('Verifying on Etherscan...')
        await hre.run('verify:verify', {
          address: result.address,
          constructorArguments: args,
        })
58
        console.log('Successfully verified on Etherscan')
59
      } catch (error) {
60 61 62 63 64 65 66 67 68 69
        console.log('Error when verifying bytecode on Etherscan:')
        console.log(error)
      }

      try {
        console.log('Verifying on Sourcify...')
        await hre.run('sourcify')
        console.log('Successfully verified on Sourcify')
      } catch (error) {
        console.log('Error when verifying bytecode on Sourcify:')
70 71 72
        console.log(error)
      }
    }
73 74 75 76 77 78 79
    if (postDeployAction) {
      const signer = hre.ethers.provider.getSigner(deployer)
      let abi = result.abi
      if (iface !== undefined) {
        const factory = await hre.ethers.getContractFactory(iface)
        abi = factory.interface
      }
80 81 82 83 84 85
      await postDeployAction(
        getAdvancedContract({
          hre,
          contract: new Contract(result.address, abi, signer),
        })
      )
86
    }
87 88 89
  }
}

90 91 92 93 94 95 96
// Returns a version of the contract object which modifies all of the input contract's methods to:
// 1. Waits for a confirmed receipt with more than deployConfig.numDeployConfirmations confirmations.
// 2. Include simple resubmission logic, ONLY for Kovan, which appears to drop transactions.
export const getAdvancedContract = (opts: {
  hre: any
  contract: Contract
}): Contract => {
97 98
  const deployConfig = getDeployConfig(opts.hre.network.name)

99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118
  // 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(
    opts.contract.address,
    opts.contract.interface,
    opts.contract.signer || opts.contract.provider
  )

  // 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) => {
119 120 121
      // We want to use the gas price that has been configured at the beginning of the deployment.
      // However, if the function being triggered is a "constant" (static) function, then we don't
      // want to provide a gas price because we're prone to getting insufficient balance errors.
122
      let gasPrice = deployConfig.gasPrice || undefined
123 124 125 126
      if (contract.interface.getFunction(fnName).constant) {
        gasPrice = 0
      }

127
      const tx = await fn(...args, {
128
        gasPrice,
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
      })

      if (typeof tx !== 'object' || typeof tx.wait !== 'function') {
        return tx
      }

      // Special logic for:
      // (1) handling confirmations
      // (2) handling an issue on Kovan specifically where transactions get dropped for no
      //     apparent reason.
      const maxTimeout = 120
      let timeout = 0
      while (true) {
        await sleep(1000)
        const receipt = await contract.provider.getTransactionReceipt(tx.hash)
        if (receipt === null) {
          timeout++
          if (timeout > maxTimeout && opts.hre.network.name === 'kovan') {
            // Special resubmission logic ONLY required on Kovan.
            console.log(
              `WARNING: Exceeded max timeout on transaction. Attempting to submit transaction again...`
            )
            return contract[fnName](...args)
          }
        } else if (
154
          receipt.confirmations >= deployConfig.numDeployConfirmations
155 156 157 158 159 160 161 162 163 164
        ) {
          return tx
        }
      }
    }
  }

  return contract
}

165 166 167 168 169
export const fundAccount = async (
  hre: any,
  address: string,
  amount: ethers.BigNumber
) => {
170 171 172
  const deployConfig = getDeployConfig(hre.network.name)

  if (!deployConfig.isForkedNetwork) {
173 174 175 176 177 178 179 180 181 182
    throw new Error('this method can only be used against a forked network')
  }

  console.log(`Funding account ${address}...`)
  await hre.ethers.provider.send('hardhat_setBalance', [
    address,
    amount.toHexString(),
  ])

  console.log(`Waiting for balance to reflect...`)
183 184 185 186 187 188 189 190
  await awaitCondition(
    async () => {
      const balance = await hre.ethers.provider.getBalance(address)
      return balance.gte(amount)
    },
    5000,
    100
  )
191 192 193 194 195 196 197 198 199 200 201 202

  console.log(`Account successfully funded.`)
}

export const sendImpersonatedTx = async (opts: {
  hre: any
  contract: ethers.Contract
  fn: string
  from: string
  gas: string
  args: any[]
}) => {
203 204 205
  const deployConfig = getDeployConfig(opts.hre.network.name)

  if (!deployConfig.isForkedNetwork) {
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
    throw new Error('this method can only be used against a forked network')
  }

  console.log(`Impersonating account ${opts.from}...`)
  await opts.hre.ethers.provider.send('hardhat_impersonateAccount', [opts.from])

  console.log(`Funding account ${opts.from}...`)
  await fundAccount(opts.hre, opts.from, BIG_BALANCE)

  console.log(`Sending impersonated transaction...`)
  const tx = await opts.contract.populateTransaction[opts.fn](...opts.args)
  const provider = new opts.hre.ethers.providers.JsonRpcProvider(
    (opts.hre.network.config as HttpNetworkConfig).url
  )
  await provider.send('eth_sendTransaction', [
    {
      ...tx,
      from: opts.from,
      gas: opts.gas,
    },
  ])

  console.log(`Stopping impersonation of account ${opts.from}...`)
  await opts.hre.ethers.provider.send('hardhat_stopImpersonatingAccount', [
    opts.from,
  ])
}

export const getContractFromArtifact = async (
  hre: any,
236 237 238 239 240
  name: string,
  options: {
    iface?: string
    signerOrProvider?: Signer | Provider | string
  } = {}
241 242
): Promise<ethers.Contract> => {
  const artifact = await hre.deployments.get(name)
243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261
  await hre.ethers.provider.waitForTransaction(artifact.receipt.transactionHash)

  // Get the deployed contract's interface.
  let iface = new hre.ethers.utils.Interface(artifact.abi)
  // Override with optional iface name if requested.
  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
    }
  }

262 263 264 265
  return getAdvancedContract({
    hre,
    contract: new hre.ethers.Contract(
      artifact.address,
266 267
      iface,
      signerOrProvider
268 269 270 271
    ),
  })
}

272 273 274 275 276
export const isHardhatNode = async (hre) => {
  const { chainId } = await hre.ethers.provider.getNetwork()
  return chainId === 31337
}

277 278
// Large balance to fund accounts with.
export const BIG_BALANCE = ethers.BigNumber.from(`0xFFFFFFFFFFFFFFFFFFFF`)