wighawag / hardhat-deploy

hardhat deployment plugin
MIT License
1.19k stars 292 forks source link

Truffle to Hardhat save deployments task #314

Open dalechyn opened 2 years ago

dalechyn commented 2 years ago

Is your feature request related to a problem? Please describe. Migrating from truffle to hardhat-deploy was a bit of a struggle. I could not use fixtures in tests because hardhat could not find the deployments of old contracts, and didn't pull them from truffle artifacts as it does for deploy task.

Describe the solution you'd like I'd like to have truffle deployments available in tests for use in fixtures

Describe alternatives you've considered I added a simple task which saves truffle deployments as they were deployed by hardhat-deploy.

task(
  'save-truffle-deployments',
  'Saves Truffle deployments to Hardhat. Use --network to chose the deployments path to save to'
)
  .addParam('from', 'Network to export from')
  .addParam('artifacts', 'Artifacts path to export from')
  .setAction(async (taskArgs, { deployments: { log, save, getExtendedArtifact } }) => {
    const matchedNetwork = Object.entries(config.networks ?? []).find(
      ([networkName]) => networkName === taskArgs.from
    )
    if (!matchedNetwork || !matchedNetwork[1])
      throw new Error(`Network with name ${taskArgs.from} does not exist`)

    const chainId = matchedNetwork[1].chainId
    if (!chainId) throw new Error('Chain ID must be specified in the config')

    console.log('Saving truffle deployments for chain id', chainId)
    const ARTIFACTS_PATH = path.resolve(taskArgs.artifacts)
    const artifacts = await fs.readdir(ARTIFACTS_PATH)

    const truffleDeployedAddresses = await Promise.all(
      artifacts.map(async (path) => {
        const file = await import(ARTIFACTS_PATH + '/' + path)
        const address = file.networks[chainId]?.address
        if (address) return [file.contractName, address]
        else return []
      })
    ).then((result) => result.filter((p) => p.length !== 0))

    await Promise.all(
      truffleDeployedAddresses.map(async ([name, address]) => {
        await save(name, {
          address,
          ...(await getExtendedArtifact(name))
        })
      })
    )

    console.log(`Done! Exported ${truffleDeployedAddresses.length} deployed contracts`)
  })