contracts.ts 1.82 KB
Newer Older
smartcontracts's avatar
smartcontracts committed
1 2
/* Imports: External */
import { constants, Contract, Signer } from 'ethers'
3
import { BaseProvider } from '@ethersproject/providers'
4
import { getContractInterface } from '@eth-optimism/contracts'
smartcontracts's avatar
smartcontracts committed
5 6 7 8

export const loadContract = (
  name: string,
  address: string,
9
  provider: BaseProvider
smartcontracts's avatar
smartcontracts committed
10 11 12 13 14 15 16 17
): Contract => {
  return new Contract(address, getContractInterface(name) as any, provider)
}

export const loadProxyFromManager = async (
  name: string,
  proxy: string,
  Lib_AddressManager: Contract,
18
  provider: BaseProvider
smartcontracts's avatar
smartcontracts committed
19 20 21 22 23 24 25 26 27 28 29 30 31 32
): Promise<Contract> => {
  const address = await Lib_AddressManager.getAddress(proxy)

  if (address === constants.AddressZero) {
    throw new Error(
      `Lib_AddressManager does not have a record for a contract named: ${proxy}`
    )
  }

  return loadContract(name, address, provider)
}

export interface OptimismContracts {
  Lib_AddressManager: Contract
33 34
  StateCommitmentChain: Contract
  CanonicalTransactionChain: Contract
smartcontracts's avatar
smartcontracts committed
35 36 37
}

export const loadOptimismContracts = async (
38
  l1RpcProvider: BaseProvider,
smartcontracts's avatar
smartcontracts committed
39 40 41 42 43 44 45 46 47 48 49
  addressManagerAddress: string,
  signer?: Signer
): Promise<OptimismContracts> => {
  const Lib_AddressManager = loadContract(
    'Lib_AddressManager',
    addressManagerAddress,
    l1RpcProvider
  )

  const inputs = [
    {
50 51
      name: 'StateCommitmentChain',
      interface: 'IStateCommitmentChain',
smartcontracts's avatar
smartcontracts committed
52 53
    },
    {
54 55
      name: 'CanonicalTransactionChain',
      interface: 'ICanonicalTransactionChain',
smartcontracts's avatar
smartcontracts committed
56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77
    },
  ]

  const contracts = {}
  for (const input of inputs) {
    contracts[input.name] = await loadProxyFromManager(
      input.interface,
      input.name,
      Lib_AddressManager,
      l1RpcProvider
    )

    if (signer) {
      contracts[input.name] = contracts[input.name].connect(signer)
    }
  }

  contracts['Lib_AddressManager'] = Lib_AddressManager

  // TODO: sorry
  return contracts as OptimismContracts
}