hardhat/builtin-tasks/task-names#TASK_COMPILE TypeScript Examples

The following examples show how to use hardhat/builtin-tasks/task-names#TASK_COMPILE. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: 0044-layer2-prepare_upgrade_ClearingHouse.ts    From perpetual-protocol with GNU General Public License v3.0 6 votes vote down vote up
migration: MigrationDefinition = {
    configPath: "hardhat.flatten.clearinghouse.config.ts",

    // deploy the flattened clearingHouse and init it just in case
    getTasks: (context: MigrationContext) => [
        async (): Promise<void> => {
            const filename = `${ContractName.ClearingHouse}.sol`

            // after flatten sol file we must re-compile again
            await flatten(SRC_DIR, hre.config.paths.sources, filename)
            await hre.run(TASK_COMPILE)

            // deploy clearing house implementation
            const clearingHouseContract = await context.factory.create<ClearingHouse>(
                ContractFullyQualifiedName.FlattenClearingHouse,
            )
            await clearingHouseContract.prepareUpgradeContractLegacy()
        },
    ],
}
Example #2
Source File: 0029-layer2-prepare_upgrade_amm.ts    From perpetual-protocol with GNU General Public License v3.0 6 votes vote down vote up
migration: MigrationDefinition = {
    configPath: "hardhat.flatten.amm.config.ts",

    // deploy the flattened amm and init it just in case
    getTasks: (context: MigrationContext) => [
        // amm
        async (): Promise<void> => {
            console.log("deploy implementation of BTC/USD...")
            const filename = `${ContractName.Amm}.sol`

            // after flatten sol file we must re-compile again
            await flatten(SRC_DIR, hre.config.paths.sources, filename)
            await hre.run(TASK_COMPILE)

            // deploy amm implementation
            const BTCUSDC = context.factory.createAmm(AmmInstanceName.BTCUSDC, ContractFullyQualifiedName.FlattenAmm)
            await BTCUSDC.prepareUpgradeContract(...dummyAmmArgs)
        },
    ],
}
Example #3
Source File: 0026-layer2-upgrade_ClearingHouse.ts    From perpetual-protocol with GNU General Public License v3.0 6 votes vote down vote up
migration: MigrationDefinition = {
    configPath: "hardhat.flatten.clearinghouse.config.ts",

    // deploy the flattened clearingHouse and init it just in case
    getTasks: (context: MigrationContext) => [
        async (): Promise<void> => {
            const emptyAddr = "0x0000000000000000000000000000000000000001"
            const filename = `${ContractName.ClearingHouse}.sol`

            // after flatten sol file we must re-compile again
            await flatten(SRC_DIR, hre.config.paths.sources, filename)
            await hre.run(TASK_COMPILE)

            // deploy clearing house implementation
            const clearingHouseContract = await context.factory.create<ClearingHouse>(
                ContractFullyQualifiedName.FlattenClearingHouse,
            )
            await clearingHouseContract.prepareUpgradeContract(
                context.deployConfig.initMarginRequirement,
                context.deployConfig.maintenanceMarginRequirement,
                context.deployConfig.liquidationFeeRatio,
                emptyAddr,
                emptyAddr,
            )
        },
    ],
}
Example #4
Source File: 0024-layer2-hardhat_prepare_upgrade_amm.ts    From perpetual-protocol with GNU General Public License v3.0 6 votes vote down vote up
migration: MigrationDefinition = {
    configPath: "hardhat.flatten.amm.config.ts",

    // deploy the flattened amm and init it just in case
    getTasks: (context: MigrationContext) => [
        // amm
        async (): Promise<void> => {
            console.log("deploy implementation of BTC/USD...")
            const filename = `${ContractName.Amm}.sol`

            // after flatten sol file we must re-compile again
            await flatten(SRC_DIR, hre.config.paths.sources, filename)
            await hre.run(TASK_COMPILE)

            // deploy amm implementation
            const BTCUSDC = context.factory.createAmm(AmmInstanceName.BTCUSDC, ContractFullyQualifiedName.FlattenAmm)
            await BTCUSDC.prepareUpgradeContract()
        },
    ],
}
Example #5
Source File: 0014-layer2-upgradeAmm.ts    From perpetual-protocol with GNU General Public License v3.0 6 votes vote down vote up
migration: MigrationDefinition = {
    configPath: "hardhat.flatten.amm.config.ts",

    getTasks: (context: MigrationContext) => [
        async (): Promise<void> => {
            const filename = `${ContractName.Amm}.sol`

            // after flatten sol file we must re-compile again
            await flatten(SRC_DIR, hre.config.paths.sources, filename)
            await hre.run(TASK_COMPILE)

            // deploy clearing house implementation
            // proxy does not use here, we just use createAmm to create an implementation
            const contract = context.factory.createAmm(AmmInstanceName.BTCUSDC, ContractFullyQualifiedName.FlattenAmm)
            const impAddress = await contract.prepareUpgradeContractLegacy()
            const amm = (await ethers.getContractAt(ContractName.Amm, impAddress)) as Amm
            const wei = BigNumber.from(1)
            const emptyAddr = "0x0000000000000000000000000000000000000001"
            await amm.initialize(
                wei,
                wei,
                wei,
                wei,
                emptyAddr,
                ethers.utils.formatBytes32String(""),
                emptyAddr,
                wei,
                wei,
                wei,
            )
        },
    ],
}
Example #6
Source File: hardhat.config.ts    From perpetual-protocol with GNU General Public License v3.0 6 votes vote down vote up
task(TASK_MIGRATE, "Migrate contract deployment")
    .addPositionalParam("stage", "Target stage of the deployment")
    .addPositionalParam("migrationPath", "Target migration")
    .setAction(async ({ stage, migrationPath }, hre) => {
        // only load dependencies when deploy is in action
        // because it depends on built artifacts and creates circular dependencies
        const { migrate } = await import("./publish/Migration")

        await hre.run(TASK_COMPILE)
        await migrate(stage, migrationPath, hre)
    })
Example #7
Source File: 0008-layer2-prepare_upgrade_amm_DOT.ts    From perpetual-protocol with GNU General Public License v3.0 6 votes vote down vote up
migration: MigrationDefinition = {
    configPath: "hardhat.flatten.amm.config.ts",

    // batch 6
    // deploy the flattened amm for DOT (production), or LINK (staging)
    // cant prepare upgrade for other amm due to openzeppelin upgrade sdk issue
    // https://github.com/OpenZeppelin/openzeppelin-upgrades/issues/175
    getTasks: (context: MigrationContext) => [
        async (): Promise<void> => {
            const filename = `${ContractName.AmmV1}.sol`
            const toFilename = `${ContractName.Amm}.sol`

            // after flatten sol file we must re-compile again
            await flatten(LEGACY_SRC_DIR, hre.config.paths.sources, filename, toFilename)
            await hre.run(TASK_COMPILE)

            // deploy amm implementation
            const DOTUSDC = context.factory.createAmm(AmmInstanceName.DOTUSDC, ContractFullyQualifiedName.FlattenAmm)
            const dotUsdcImplAddr = await DOTUSDC.prepareUpgradeContractLegacy()

            // in normal case we don't need to do anything to the implementation contract
            const ammImplInstance = (await ethers.getContractAt(ContractName.Amm, dotUsdcImplAddr)) as Amm
            const wei = BigNumber.from(1)
            const emptyAddr = "0x0000000000000000000000000000000000000001"
            await ammImplInstance.initialize(
                wei,
                wei,
                wei,
                wei,
                emptyAddr,
                ethers.utils.formatBytes32String(""),
                emptyAddr,
                wei,
                wei,
                wei,
            )
        },
    ],
}
Example #8
Source File: 0006-layer2-prepare_upgrade_amm_YFI.ts    From perpetual-protocol with GNU General Public License v3.0 6 votes vote down vote up
migration: MigrationDefinition = {
    configPath: "hardhat.flatten.amm.config.ts",

    // batch 4
    // prepareUpgradeLegacy the flatten YFI AMM
    getTasks: (context: MigrationContext) => [
        async (): Promise<void> => {
            const filename = `${ContractName.AmmV1}.sol`
            const toFilename = `${ContractName.Amm}.sol`

            // after flatten sol file we must re-compile again
            await flatten(LEGACY_SRC_DIR, hre.config.paths.sources, filename, toFilename)
            await hre.run(TASK_COMPILE)

            // deploy amm implementation
            const YFIUSDC = context.factory.createAmm(AmmInstanceName.YFIUSDC, ContractFullyQualifiedName.FlattenAmm)
            await YFIUSDC.prepareUpgradeContractLegacy()
        },
    ],
}
Example #9
Source File: 0003-layer2-deploy_ClearingHouse.ts    From perpetual-protocol with GNU General Public License v3.0 6 votes vote down vote up
migration: MigrationDefinition = {
    configPath: "hardhat.flatten.clearinghouse.config.ts",

    // deploy a new implementation of ClearingHouse, in order to make xdai blockscout verification works,
    // we'll deploy a flatten one in an isolated build env. then PROXY_ADMIN should upgrade proxy to the new implementation
    getTasks: (context: MigrationContext) => [
        async (): Promise<void> => {
            const filename = `${ContractName.ClearingHouse}.sol`

            // after flatten sol file we must re-compile again
            await flatten(SRC_DIR, hre.config.paths.sources, filename)
            await hre.run(TASK_COMPILE)

            // deploy clearing house implementation
            const contract = context.factory.create<ClearingHouse>(ContractFullyQualifiedName.FlattenClearingHouse)
            await contract.prepareUpgradeContractLegacy()
        },
    ],
}
Example #10
Source File: 0004-layer2-deploy_amm_BTC_ETH.ts    From perpetual-protocol with GNU General Public License v3.0 6 votes vote down vote up
migration: MigrationDefinition = {
    configPath: "hardhat.flatten.amm.config.ts",

    // deploy a new implementation of Amm, in order to make xdai blockscout verification works,
    // we'll deploy a flatten one in an isolated build env. then PROXY_ADMIN should upgrade proxy to the new implementation
    getTasks: (context: MigrationContext) => [
        async (): Promise<void> => {
            const filename = `${ContractName.AmmV1}.sol`
            const toFilename = `${ContractName.Amm}.sol`

            // after flatten sol file we must re-compile again
            await flatten(LEGACY_SRC_DIR, hre.config.paths.sources, filename, toFilename)
            await hre.run(TASK_COMPILE)

            // deploy amm implementation
            const ETHUSDC = context.factory.createAmm(AmmInstanceName.ETHUSDC, ContractFullyQualifiedName.FlattenAmm)
            await ETHUSDC.prepareUpgradeContractLegacy()

            const BTCUSDC = context.factory.createAmm(AmmInstanceName.BTCUSDC, ContractFullyQualifiedName.FlattenAmm)
            await BTCUSDC.prepareUpgradeContractLegacy()
        },
    ],
}
Example #11
Source File: hardhat.config.ts    From hardhat-deploy with MIT License 5 votes vote down vote up
task(TASK_COMPILE).setAction(async (args, hre, runSuper) => {
  await runSuper(args);
  const extendedArtifactFolderpath = 'extendedArtifacts';
  fs.emptyDirSync(extendedArtifactFolderpath);
  const artifactPaths = await hre.artifacts.getArtifactPaths();
  for (const artifactPath of artifactPaths) {
    const artifact: Artifact = await fs.readJSON(artifactPath);
    const artifactName = path.basename(artifactPath, '.json');
    const artifactDBGPath = path.join(
      path.dirname(artifactPath),
      artifactName + '.dbg.json'
    );
    const artifactDBG = await fs.readJSON(artifactDBGPath);
    const buildinfoPath = path.join(
      path.dirname(artifactDBGPath),
      artifactDBG.buildInfo
    );
    const buildInfo: BuildInfo = await fs.readJSON(buildinfoPath);
    const output =
      buildInfo.output.contracts[artifact.sourceName][artifactName];

    // TODO decide on ExtendedArtifact vs Artifact vs Deployment type
    // save space by not duplicating bytecodes
    if (output.evm?.bytecode?.object) {
      // eslint-disable-next-line @typescript-eslint/no-explicit-any
      (output.evm.bytecode.object as any) = undefined;
    }
    if (output.evm?.deployedBytecode?.object) {
      // eslint-disable-next-line @typescript-eslint/no-explicit-any
      (output.evm.deployedBytecode.object as any) = undefined;
    }
    // -----------------------------------------

    const solcInput = JSON.stringify(buildInfo.input, null, '  ');
    const solcInputHash = Buffer.from(murmur128(solcInput)).toString('hex');
    const extendedArtifact = {
      ...artifact,
      ...output,
      solcInput,
      solcInputHash,
    };
    // eslint-disable-next-line @typescript-eslint/no-explicit-any
    (extendedArtifact._format as any) = undefined;
    fs.writeFileSync(
      path.join(extendedArtifactFolderpath, artifactName + '.json'),
      JSON.stringify(extendedArtifact, null, '  ')
    );
  }
});
Example #12
Source File: compile.ts    From nova with GNU Affero General Public License v3.0 5 votes vote down vote up
task(TASK_COMPILE).setAction(async (args, hre: any, runSuper) => {
  // Don't run typechain for OVM because they will get included with the L1 types.
  if (hre.network.config.ovm) {
    return runSuper({ ...args, noTypechain: true });
  } else {
    return runSuper(args);
  }
});
Example #13
Source File: 0009-layer2-upgrade_ClearingHouse.ts    From perpetual-protocol with GNU General Public License v3.0 5 votes vote down vote up
migration: MigrationDefinition = {
    configPath: "hardhat.flatten.clearinghouse.config.ts",

    // batch 7
    // deploy the flattened clearingHouse and init it just in case
    getTasks: (context: MigrationContext) => [
        async (): Promise<void> => {
            const filename = `${ContractName.ClearingHouse}.sol`

            // after flatten sol file we must re-compile again
            await flatten(SRC_DIR, hre.config.paths.sources, filename)
            await hre.run(TASK_COMPILE)

            // deploy clearing house implementation
            const clearingHouseContract = await context.factory.create<ClearingHouse>(
                ContractFullyQualifiedName.FlattenClearingHouse,
            )
            const implContractAddr = await clearingHouseContract.prepareUpgradeContractLegacy()

            // in normal case we don't need to do anything to the implementation contract
            const insuranceFundContract = context.factory.create<InsuranceFund>(
                ContractFullyQualifiedName.FlattenInsuranceFund,
            )
            const metaTxGatewayContract = context.factory.create<MetaTxGateway>(
                ContractFullyQualifiedName.FlattenMetaTxGateway,
            )
            const clearingHouseImplInstance = (await ethers.getContractAt(
                ContractName.ClearingHouse,
                implContractAddr,
            )) as ClearingHouse
            await clearingHouseImplInstance.initialize(
                context.deployConfig.initMarginRequirement,
                context.deployConfig.maintenanceMarginRequirement,
                context.deployConfig.liquidationFeeRatio,
                insuranceFundContract.address!,
                metaTxGatewayContract.address!,
            )
        },
    ],
}
Example #14
Source File: DeployUtil.ts    From perpetual-protocol with GNU General Public License v3.0 5 votes vote down vote up
export function makeAmmDeployMigrationTasks(
    context: MigrationContext,
    ammConfig: AmmConfig,
    priceFeedAddress: string,
    needFlatten = false,
): MigrationTask[] {
    return [
        async (): Promise<void> => {
            console.log(`deploy ${ammConfig.name} amm...`)
            const filename = `${ContractName.Amm}.sol`

            if (needFlatten) {
                // after flatten sol file we must re-compile again
                await flatten(SRC_DIR, hre.config.paths.sources, filename)
                await hre.run(TASK_COMPILE)
            }

            const ammContract = context.factory.createAmm(ammConfig.name, ContractFullyQualifiedName.FlattenAmm)
            const quoteTokenAddr = context.externalContract.usdc!
            await ammContract.deployUpgradableContract(ammConfig.deployArgs, priceFeedAddress, quoteTokenAddr)
        },
        async (): Promise<void> => {
            console.log(`set ${ammConfig.name} amm Cap...`)
            const amm = await context.factory
                .createAmm(ammConfig.name, ContractFullyQualifiedName.FlattenAmm)
                .instance()
            const { maxHoldingBaseAsset, openInterestNotionalCap } = ammConfig.properties
            if (maxHoldingBaseAsset.gt(0)) {
                await (
                    await amm.setCap({ d: maxHoldingBaseAsset.toString() }, { d: openInterestNotionalCap.toString() })
                ).wait(context.deployConfig.confirmations)
            }
        },
        async (): Promise<void> => {
            console.log(`${ammConfig.name} amm.setCounterParty...`)
            const clearingHouseContract = context.factory.create<ClearingHouse>(
                ContractFullyQualifiedName.ClearingHouse,
            )
            const amm = await context.factory
                .createAmm(ammConfig.name, ContractFullyQualifiedName.FlattenAmm)
                .instance()
            await (await amm.setCounterParty(clearingHouseContract.address!)).wait(context.deployConfig.confirmations)
        },
        async (): Promise<void> => {
            console.log(`opening Amm ${ammConfig.name}...`)
            const amm = await context.factory
                .createAmm(ammConfig.name, ContractFullyQualifiedName.FlattenAmm)
                .instance()
            await (await amm.setOpen(true)).wait(context.deployConfig.confirmations)
        },
        async (): Promise<void> => {
            const gov = context.externalContract.foundationGovernance!
            console.log(
                `transferring ${ammConfig.name} owner to governance=${gov}...please remember to claim the ownership`,
            )
            const amm = await context.factory
                .createAmm(ammConfig.name, ContractFullyQualifiedName.FlattenAmm)
                .instance()
            await (await amm.setOwner(gov)).wait(context.deployConfig.confirmations)
        },
    ]
}
Example #15
Source File: DeployUtil.ts    From perpetual-protocol with GNU General Public License v3.0 5 votes vote down vote up
export function makeAmmV1DeployMigrationTasks(
    context: MigrationContext,
    ammConfig: AmmConfig,
    needFlatten = false,
): MigrationTask[] {
    return [
        async (): Promise<void> => {
            console.log(`deploy ${ammConfig.name} amm...`)
            const filename = `${ContractName.AmmV1}.sol`
            const toFilename = `${ContractName.Amm}.sol`
            const l2PriceFeedContract = context.factory.create<L2PriceFeed>(ContractFullyQualifiedName.L2PriceFeed)

            if (needFlatten) {
                // after flatten sol file we must re-compile again
                await flatten(LEGACY_SRC_DIR, hre.config.paths.sources, filename, toFilename)
                await hre.run(TASK_COMPILE)
            }

            const ammContract = context.factory.createAmm(ammConfig.name, ContractFullyQualifiedName.FlattenAmm)
            const quoteTokenAddr = context.externalContract.usdc!
            await ammContract.deployUpgradableContract(
                ammConfig.deployArgs,
                l2PriceFeedContract.address!,
                quoteTokenAddr,
            )
        },
        async (): Promise<void> => {
            console.log(`set ${ammConfig.name} amm Cap...`)
            const amm = await context.factory
                .createAmm(ammConfig.name, ContractFullyQualifiedName.FlattenAmm)
                .instance()
            const { maxHoldingBaseAsset, openInterestNotionalCap } = ammConfig.properties
            if (maxHoldingBaseAsset.gt(0)) {
                await (
                    await amm.setCap({ d: maxHoldingBaseAsset.toString() }, { d: openInterestNotionalCap.toString() })
                ).wait(context.deployConfig.confirmations)
            }
        },
        async (): Promise<void> => {
            console.log(`${ammConfig.name} amm.setCounterParty...`)
            const clearingHouseContract = context.factory.create<ClearingHouse>(
                ContractFullyQualifiedName.ClearingHouse,
            )
            const amm = await context.factory
                .createAmm(ammConfig.name, ContractFullyQualifiedName.FlattenAmm)
                .instance()
            await (await amm.setCounterParty(clearingHouseContract.address!)).wait(context.deployConfig.confirmations)
        },
        async (): Promise<void> => {
            console.log(`opening Amm ${ammConfig.name}...`)
            const amm = await context.factory
                .createAmm(ammConfig.name, ContractFullyQualifiedName.FlattenAmm)
                .instance()
            await (await amm.setOpen(true)).wait(context.deployConfig.confirmations)
        },
        async (): Promise<void> => {
            const gov = context.externalContract.foundationGovernance!
            console.log(
                `transferring ${ammConfig.name} owner to governance=${gov}...please remember to claim the ownership`,
            )
            const amm = await context.factory
                .createAmm(ammConfig.name, ContractFullyQualifiedName.FlattenAmm)
                .instance()
            await (await amm.setOwner(gov)).wait(context.deployConfig.confirmations)
        },
    ]
}
Example #16
Source File: hardhat.config.ts    From perpetual-protocol with GNU General Public License v3.0 5 votes vote down vote up
task(TASK_CHECK_CHAINLINK, "Check Chainlink")
    .addParam("address", "a Chainlink aggregator address")
    .setAction(async ({ address }, hre) => {
        await hre.run(TASK_COMPILE)
        // eslint-disable-next-line @typescript-eslint/no-var-requires
        const { checkChainlink } = require("./publish/check-chainlink")
        await checkChainlink(address, hre)
    })
Example #17
Source File: run-local.ts    From nouns-monorepo with GNU General Public License v3.0 5 votes vote down vote up
task(
  'run-local',
  'Start a hardhat node, deploy contracts, and execute setup transactions',
).setAction(async (_, { ethers, run }) => {
  await run(TASK_COMPILE);

  await Promise.race([run(TASK_NODE), new Promise(resolve => setTimeout(resolve, 2_000))]);

  const contracts = await run('deploy-local');

  await run('populate-descriptor', {
    nftDescriptor: contracts.NFTDescriptor.instance.address,
    nounsDescriptor: contracts.NounsDescriptor.instance.address,
  });

  await contracts.NounsAuctionHouse.instance
    .attach(contracts.NounsAuctionHouseProxy.instance.address)
    .unpause({
      gasLimit: 1_000_000,
    });

  await run('create-proposal', {
    nounsDaoProxy: contracts.NounsDAOProxy.instance.address,
  });

  const { chainId } = await ethers.provider.getNetwork();

  const accounts = {
    'Account #0': {
      Address: '0xf39fd6e51aad88f6f4ce6ab8827279cfffb92266',
      'Private Key': '0xac0974bec39a17e36ba4a6b4d238ff944bacb478cbed5efcae784d7bf4f2ff80',
    },
    'Account #1': {
      Address: '0x70997970c51812dc3a010c7d01b50e0d17dc79c8',
      'Private Key': '0x59c6995e998f97a5a0044966f0945389dc9e86dae88c7a8412f4603b6b78690d',
    },
  };

  console.table(accounts);
  console.log(
    `Noun contracts deployed to local node at http://localhost:8545 (Chain ID: ${chainId})`,
  );
  console.log(`Auction House Proxy address: ${contracts.NounsAuctionHouseProxy.instance.address}`);
  console.log(`Nouns ERC721 address: ${contracts.NounsToken.instance.address}`);
  console.log(`Nouns DAO Executor address: ${contracts.NounsDAOExecutor.instance.address}`);
  console.log(`Nouns DAO Proxy address: ${contracts.NounsDAOProxy.instance.address}`);

  await ethers.provider.send('evm_setIntervalMining', [12_000]);

  await new Promise(() => {
    /* keep node alive until this process is killed */
  });
});
Example #18
Source File: compile.ts    From eth with GNU General Public License v3.0 5 votes vote down vote up
task(TASK_COMPILE, 'hook the compile step to copy our abis after').setAction(copyAbi);
Example #19
Source File: hardhat.config.ts    From balancer-v2-monorepo with GNU General Public License v3.0 5 votes vote down vote up
task(TASK_COMPILE).setAction(overrideQueryFunctions);
Example #20
Source File: hardhat.config.ts    From balancer-v2-monorepo with GNU General Public License v3.0 5 votes vote down vote up
task(TASK_COMPILE).setAction(overrideQueryFunctions);
Example #21
Source File: hardhat.config.ts    From balancer-v2-monorepo with GNU General Public License v3.0 5 votes vote down vote up
task(TASK_COMPILE).setAction(overrideQueryFunctions);
Example #22
Source File: hardhat.config.ts    From balancer-v2-monorepo with GNU General Public License v3.0 5 votes vote down vote up
task(TASK_COMPILE).setAction(overrideQueryFunctions);
Example #23
Source File: 0001-layer2-clearingHouse.ts    From perpetual-protocol with GNU General Public License v3.0 4 votes vote down vote up
migration: MigrationDefinition = {
    configPath: "hardhat.flatten.clearinghouse.config.ts",

    // deploy the flattened clearingHouse and init it just in case
    getTasks: (context: MigrationContext) => {
        let arbitrageur: string
        let initMarginRatio: string
        let oldImpAddr: string
        let insuranceFund: string
        let BTC: string
        let arbitrageurBTCPositionSize: string
        let openInterestNotional: string
        let newImplContractAddr: string
        return [
            async (): Promise<void> => {
                console.log("verifying state variables...")

                // have to first flatten contracts for creating instances
                const filename = `${ContractName.ClearingHouse}.sol`
                await flatten(SRC_DIR, hre.config.paths.sources, filename)
                // after flatten sol file we must re-compile again
                await hre.run(TASK_COMPILE)

                const clearingHouseContract = await context.factory
                    .create<ClearingHouse>(ContractFullyQualifiedName.FlattenClearingHouse)
                    .instance()

                oldImpAddr = await getImplementation(clearingHouseContract.address)
                initMarginRatio = (await clearingHouseContract.initMarginRatio()).toString()
                insuranceFund = await clearingHouseContract.insuranceFund()
                BTC = context.systemMetadataDao.getContractMetadata(context.layer, AmmInstanceName.BTCUSDC).address
                openInterestNotional = (await clearingHouseContract.openInterestNotionalMap(BTC)).toString()

                arbitrageur = context.externalContract.arbitrageur!
                arbitrageurBTCPositionSize = (
                    await clearingHouseContract.getUnadjustedPosition(BTC, arbitrageur)
                ).size.toString()
            },
            async (): Promise<void> => {
                console.log("prepare upgrading...")
                // deploy clearing house implementation
                const clearingHouseContract = await context.factory.create<ClearingHouse>(
                    ContractFullyQualifiedName.FlattenClearingHouse,
                )
                newImplContractAddr = await clearingHouseContract.prepareUpgradeContractLegacy()
            },
            async (): Promise<void> => {
                console.info("do upgrade")
                // create an impersonated signer
                const govAddr = context.externalContract.foundationGovernance
                await hre.network.provider.request({
                    method: "hardhat_impersonateAccount",
                    params: [govAddr],
                })
                const govSigner = ethers.provider.getSigner(govAddr)

                // prepare information for upgrading
                const contractName = ContractFullyQualifiedName.FlattenClearingHouse
                const proxyAddr = context.factory.create<ClearingHouse>(contractName).address!

                const proxyAdmin = await upgrades.admin.getInstance()
                await proxyAdmin.connect(govSigner).upgrade(proxyAddr, newImplContractAddr)

                console.log(
                    `upgrade: contractFullyQualifiedName=${contractName}, proxy=${proxyAddr}, implementation=${newImplContractAddr}`,
                )
            },
            async (): Promise<void> => {
                const clearingHouseContract = await context.factory
                    .create<ClearingHouse>(ContractFullyQualifiedName.FlattenClearingHouse)
                    .instance()

                // for comparing with the new implementation address
                console.log("old implementation address: ", oldImpAddr)
                console.log("new implementation address: ", await getImplementation(clearingHouseContract.address))

                const newInsuranceFund = await clearingHouseContract.insuranceFund()
                console.log("insuranceFund address (shouldn't be zero address): ", newInsuranceFund)
                expect(newInsuranceFund).to.eq(insuranceFund)
                console.log("insuranceFund verified!")

                expect((await clearingHouseContract.initMarginRatio()).toString()).to.eq(initMarginRatio)
                console.log("initMarginRatio verified!")
                expect((await clearingHouseContract.openInterestNotionalMap(BTC)).toString()).to.eq(
                    openInterestNotional,
                )
                console.log("openInterestNotional verified!")
                expect((await clearingHouseContract.getUnadjustedPosition(BTC, arbitrageur)).size.toString()).to.eq(
                    arbitrageurBTCPositionSize,
                )
                console.log("arbitrageurBTCPositionSize verified!")
            },
        ]
    },
}
Example #24
Source File: 0004-layer2-clearingHouse-amm-openPos.ts    From perpetual-protocol with GNU General Public License v3.0 4 votes vote down vote up
migration: MigrationDefinition = {
    configPath: "hardhat.flatten.clearinghouse.config.ts",

    // deploy the flattened clearingHouse and init it just in case
    getTasks: (context: MigrationContext) => {
        let arbitrageur: string
        let oldClearingHouseImpAddr: string
        let oldAmmImpAddr: string
        let newClearingHouseImplAddr: string
        let newAmmImplAddr: string
        let ammETHAddr: string
        let arbitrageurPosition: any
        let oldQuoteAssetReserve: BigNumber
        let quoteAssetAddr: string
        return [
            async (): Promise<void> => {
                console.log("get state variables for verification later...")

                // flat clearingHouse
                const fileClearingHouse = `${ContractName.ClearingHouse}.sol`
                await flatten(SRC_DIR, hre.config.paths.sources, fileClearingHouse)
                await hre.run(TASK_COMPILE)

                // flat Amm
                const fileAmm = `${ContractName.Amm}.sol`
                await flatten(SRC_DIR, hre.config.paths.sources, fileAmm)
                await hre.run(TASK_COMPILE)

                const clearingHouseContract = await context.factory
                    .create<ClearingHouse>(ContractFullyQualifiedName.FlattenClearingHouse)
                    .instance()
                const ammContract = await context.factory
                    .createAmm(AmmInstanceName.ETHUSDC, ContractFullyQualifiedName.FlattenAmmUnderClearingHouse)
                    .instance()

                oldClearingHouseImpAddr = await getImplementation(clearingHouseContract.address)
                oldAmmImpAddr = await getImplementation(ammContract.address)
                ammETHAddr = ammContract.address

                arbitrageur = context.externalContract.arbitrageur!
                arbitrageurPosition = await clearingHouseContract.getPosition(ammETHAddr, arbitrageur)
                oldQuoteAssetReserve = await ammContract.quoteAssetReserve()
                quoteAssetAddr = await ammContract.quoteAsset()
            },
            async (): Promise<void> => {
                console.log("prepare upgrading...")

                // deploy clearingHouse implementation
                const clearingHouseContract = await context.factory.create<ClearingHouse>(
                    ContractFullyQualifiedName.FlattenClearingHouse,
                )
                newClearingHouseImplAddr = await clearingHouseContract.prepareUpgradeContractLegacy()

                // deploy Amm implementation
                const ammContract = await context.factory.createAmm(
                    AmmInstanceName.ETHUSDC,
                    ContractFullyQualifiedName.FlattenAmmUnderClearingHouse,
                )
                newAmmImplAddr = await ammContract.prepareUpgradeContractLegacy()
            },
            async (): Promise<void> => {
                console.info("upgrading...")

                // create an impersonated signer
                const govSigner = await impersonateAccount(context.externalContract.foundationGovernance!)

                // prepare information for upgrading
                const contractNameClearingHouse = ContractFullyQualifiedName.FlattenClearingHouse
                const proxyClearingHouseAddr = context.factory.create<ClearingHouse>(contractNameClearingHouse).address!

                const proxyAdmin = await upgrades.admin.getInstance()
                await proxyAdmin.connect(govSigner).upgrade(proxyClearingHouseAddr, newClearingHouseImplAddr)
                console.log(
                    `upgrade: contractFullyQualifiedName=${contractNameClearingHouse}, proxy=${proxyClearingHouseAddr}, implementation=${newClearingHouseImplAddr}`,
                )

                await proxyAdmin.connect(govSigner).upgrade(ammETHAddr, newAmmImplAddr)
                console.log(
                    `upgrade: contractFullyQualifiedName=${contractNameClearingHouse}, proxy=${ammETHAddr}, implementation=${newAmmImplAddr}`,
                )
            },
            // verify can openPosition
            async (): Promise<void> => {
                const clearingHouseContract = await context.factory
                    .create<ClearingHouse>(ContractFullyQualifiedName.FlattenClearingHouse)
                    .instance()

                const gov = context.externalContract.foundationGovernance!
                const govSigner = await impersonateAccount(gov)
                const arbitrageurSigner = await impersonateAccount(arbitrageur)

                const usdcAddr = context.externalContract.usdc!
                const USDCArtifact = await artifacts.readArtifact(ContractFullyQualifiedName.FlattenIERC20)
                const usdcInstance = (await ethers.getContractAt(USDCArtifact.abi, usdcAddr)) as ERC20

                // send eth and usdc to gov account
                const txETH = await arbitrageurSigner.sendTransaction({
                    to: gov,
                    value: ethers.utils.parseEther("0.1"),
                })
                await txETH.wait()
                const txUSDC = await usdcInstance.connect(arbitrageurSigner).transfer(gov, parseUnits("1000", 6))
                await txUSDC.wait()
                const txApprove = await usdcInstance
                    .connect(govSigner)
                    .approve(clearingHouseContract.address, parseUnits("1000", 6))
                await txApprove.wait()

                // open position
                const receipt = await clearingHouseContract
                    .connect(govSigner)
                    .openPosition(
                        ammETHAddr,
                        Side.BUY,
                        { d: parseEther("600") },
                        { d: parseEther("1") },
                        { d: parseEther("0") },
                    )

                const ownerPosition = await clearingHouseContract.getPosition(ammETHAddr, gov)
                expect(ownerPosition.margin.d).to.eq(parseEther("600"))
                expect(ownerPosition.blockNumber).to.eq(receipt.blockNumber)
            },
            // verify arbitrageur's position on ETH market and Amm's reserve
            async (): Promise<void> => {
                const clearingHouseContract = await context.factory
                    .create<ClearingHouse>(ContractFullyQualifiedName.FlattenClearingHouse)
                    .instance()
                const ammContract = await context.factory
                    .createAmm(AmmInstanceName.ETHUSDC, ContractFullyQualifiedName.FlattenAmmUnderClearingHouse)
                    .instance()

                // for comparing with the new implementation address
                console.log("old implementation address of ClearingHouse: ", oldClearingHouseImpAddr)
                console.log(
                    "new implementation address of ClearingHouse: ",
                    await getImplementation(clearingHouseContract.address),
                )
                console.log("old implementation address of Amm: ", oldAmmImpAddr)
                console.log("new implementation address of Amm: ", await getImplementation(ammContract.address))

                console.log("arbitrageur position: ")
                const arbitrageurPositionNow = await clearingHouseContract.getPosition(ammETHAddr, arbitrageur)
                console.log("size: ", arbitrageurPositionNow.size.d.toString())
                console.log("margin: ", arbitrageurPositionNow.margin.d.toString())
                console.log("last updated blockNumber: ", arbitrageurPositionNow.blockNumber.toString())
                expect(arbitrageurPosition.size.d).to.eq(arbitrageurPositionNow.size.d)
                expect(arbitrageurPosition.margin.d).to.eq(arbitrageurPositionNow.margin.d)
                expect(arbitrageurPosition.blockNumber).to.eq(arbitrageurPositionNow.blockNumber)

                console.log("amm states: ")
                const newQuoteAssetReserve = await ammContract.quoteAssetReserve()
                console.log("quote asset reserve: ", oldQuoteAssetReserve.toString())
                console.log("USDC addr: ", quoteAssetAddr.toString())
                expect(newQuoteAssetReserve).to.eq(oldQuoteAssetReserve.add(parseEther("600")))
                expect(await ammContract.quoteAsset()).to.eq(quoteAssetAddr)
            },
        ]
    },
}