@ethersproject/contracts#ContractFactory TypeScript Examples

The following examples show how to use @ethersproject/contracts#ContractFactory. 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: Trident.ts    From trident with GNU General Public License v3.0 6 votes vote down vote up
private async deployTokens(ERC20: ContractFactory) {
    this.tokens = await Promise.all([
      ERC20.deploy("TokenA", "TOK", this.tokenSupply),
      ERC20.deploy("TokenB", "TOK", this.tokenSupply),
    ] as Promise<ERC20Mock>[]);
    this.extraToken = (await ERC20.deploy("TokenC", "TOK", this.tokenSupply)) as ERC20Mock;
    this.tokenMap[this.tokens[0].address] = this.tokens[0];
    this.tokenMap[this.tokens[1].address] = this.tokens[1];
    this.tokens = sortTokens(this.tokens);
  }
Example #2
Source File: Trident.ts    From trident with GNU General Public License v3.0 6 votes vote down vote up
private async deployTridentPeriphery(Deployer: ContractFactory, TridentRouter: ContractFactory) {
    this.masterDeployer = (await Deployer.deploy(
      randBetween(1, 9999),
      this.accounts[1].address,
      this.bento.address
    )) as MasterDeployer;
    this.router = (await TridentRouter.deploy(
      this.bento.address,
      this.masterDeployer.address,
      this.tokens[0].address
    )) as TridentRouter;
  }
Example #3
Source File: Trident.ts    From trident with GNU General Public License v3.0 6 votes vote down vote up
private async deployConcentratedPeriphery(
    ConcentratedPoolManager: ContractFactory,
    ConcentratedPoolStaker: ContractFactory,
    ConcentratedPoolFactory: ContractFactory,
    ConcentratedPoolHelper: ContractFactory,
    TickMath: ContractFactory
  ) {
    this.concentratedPoolManager = (await ConcentratedPoolManager.deploy(
      this.masterDeployer.address,
      this.tokens[0].address
    )) as ConcentratedLiquidityPoolManager;
    this.concentratedPoolStaker = (await ConcentratedPoolStaker.deploy(
      this.concentratedPoolManager.address
    )) as ConcentratedLiquidityPoolStaker;
    this.concentratedPoolFactory = (await ConcentratedPoolFactory.deploy(
      this.masterDeployer.address
    )) as ConcentratedLiquidityPoolFactory;
    // for testing
    this.concentratedPoolHelper = (await ConcentratedPoolHelper.deploy()) as ConcentratedLiquidityPoolHelper;
    this.tickMath = (await TickMath.deploy()) as TickMathMock;
  }
Example #4
Source File: ERC721__factory.ts    From nft-marketplace with European Union Public License 1.2 6 votes vote down vote up
export class ERC721__factory extends ContractFactory {
  constructor(signer?: Signer) {
    super(_abi, _bytecode, signer);
  }

  deploy(
    name_: string,
    symbol_: string,
    overrides?: Overrides
  ): Promise<ERC721> {
    return super.deploy(name_, symbol_, overrides || {}) as Promise<ERC721>;
  }
  getDeployTransaction(
    name_: string,
    symbol_: string,
    overrides?: Overrides
  ): TransactionRequest {
    return super.getDeployTransaction(name_, symbol_, overrides || {});
  }
  attach(address: string): ERC721 {
    return super.attach(address) as ERC721;
  }
  connect(signer: Signer): ERC721__factory {
    return super.connect(signer) as ERC721__factory;
  }
  static connect(address: string, signerOrProvider: Signer | Provider): ERC721 {
    return new Contract(address, _abi, signerOrProvider) as ERC721;
  }
}
Example #5
Source File: UnchainedCryptoMarket__factory.ts    From nft-marketplace with European Union Public License 1.2 6 votes vote down vote up
export class UnchainedCryptoMarket__factory extends ContractFactory {
  constructor(signer?: Signer) {
    super(_abi, _bytecode, signer);
  }

  deploy(
    pricePerToken_: BigNumberish,
    overrides?: Overrides
  ): Promise<UnchainedCryptoMarket> {
    return super.deploy(
      pricePerToken_,
      overrides || {}
    ) as Promise<UnchainedCryptoMarket>;
  }
  getDeployTransaction(
    pricePerToken_: BigNumberish,
    overrides?: Overrides
  ): TransactionRequest {
    return super.getDeployTransaction(pricePerToken_, overrides || {});
  }
  attach(address: string): UnchainedCryptoMarket {
    return super.attach(address) as UnchainedCryptoMarket;
  }
  connect(signer: Signer): UnchainedCryptoMarket__factory {
    return super.connect(signer) as UnchainedCryptoMarket__factory;
  }
  static connect(
    address: string,
    signerOrProvider: Signer | Provider
  ): UnchainedCryptoMarket {
    return new Contract(
      address,
      _abi,
      signerOrProvider
    ) as UnchainedCryptoMarket;
  }
}
Example #6
Source File: Trident.ts    From trident with GNU General Public License v3.0 5 votes vote down vote up
private async deployConcentratedCore(CLP: ContractFactory) {
    const [token0, token1] = sortTokens(this.tokens);
    const concentratedPools: ConcentratedLiquidityPool[] = [];
    const prices: BigNumber[] = [];

    // random price feed
    // prices."push(BigNumber.from(2).pow(96).mul(randBetween(1, 10000000)).div(randBetween(1, 10000000)));

    // stable price feed
    prices.push(TWO_POW_96);

    // low price feed
    prices.push(TWO_POW_96.div(16));

    // high price feed
    prices.push(TWO_POW_96.mul(16));

    const fees = [5, 30];

    const tickSpacings = [1, 5, 60];

    function data(token0, token1, fee, price, tickSpacing) {
      return ethers.utils.defaultAbiCoder.encode(
        ["address", "address", "uint24", "uint160", "uint24"],
        [token0, token1, fee, price, tickSpacing]
      );
    }

    for (let j = 0; j < fees.length; j++) {
      for (let k = 0; k < tickSpacings.length; k++) {
        await this.masterDeployer.deployPool(
          this.concentratedPoolFactory.address,
          data(token0.address, token1.address, fees[j], prices[(j + k) % prices.length], tickSpacings[k])
        );
      }
    }

    const poolAddresses = await this.concentratedPoolFactory.getPools(
      token0.address,
      token1.address,
      0,
      fees.length * tickSpacings.length
    );

    for (let poolAddress of poolAddresses) {
      concentratedPools.push((await CLP.attach(poolAddress)) as ConcentratedLiquidityPool);
    }

    this.concentratedPools = concentratedPools;
  }
Example #7
Source File: Trident.ts    From trident with GNU General Public License v3.0 5 votes vote down vote up
private async deployBento(Bento: ContractFactory) {
    this.bento = (await Bento.deploy(this.tokens[0].address)) as BentoBoxV1;
  }
Example #8
Source File: TestContext.ts    From trident with GNU General Public License v3.0 5 votes vote down vote up
public Erc20Factory!: ContractFactory;
Example #9
Source File: TopologyFactory.ts    From trident with GNU General Public License v3.0 5 votes vote down vote up
constructor(erc20Factory: ContractFactory, poolFactory: TridentPoolFactory, bento: BentoBoxV1, signer: SignerWithAddress) {
    this.Erc20Factory = erc20Factory;
    this.PoolFactory = poolFactory;
    this.Bento = bento;
    this.Signer = signer;
  }
Example #10
Source File: TopologyFactory.ts    From trident with GNU General Public License v3.0 5 votes vote down vote up
private Erc20Factory!: ContractFactory;
Example #11
Source File: TridentPoolFactory.ts    From trident with GNU General Public License v3.0 5 votes vote down vote up
private ConcentratedLiquidityPool!: ContractFactory;
Example #12
Source File: TridentPoolFactory.ts    From trident with GNU General Public License v3.0 5 votes vote down vote up
private HybridPool!: ContractFactory;
Example #13
Source File: TridentPoolFactory.ts    From trident with GNU General Public License v3.0 5 votes vote down vote up
private ConstantProductPool!: ContractFactory;
Example #14
Source File: deployUpgrade.ts    From aavegotchi-contracts with MIT License 4 votes vote down vote up
task(
  "deployUpgrade",
  "Deploys a Diamond Cut, given an address, facets and addSelectors, and removeSelectors"
)
  .addParam("diamondUpgrader", "Address of the multisig signer")
  .addParam("diamondAddress", "Address of the Diamond to upgrade")
  .addParam(
    "facetsAndAddSelectors",
    "Stringified array of facet names to upgrade, along with an array of add Selectors"
  )
  .addOptionalParam("initAddress", "The facet address to call init function on")
  .addOptionalParam("initCalldata", "The calldata for init function")
  .addFlag(
    "useMultisig",
    "Set to true if multisig should be used for deploying"
  )
  .addFlag("useLedger", "Set to true if Ledger should be used for signing")
  // .addFlag("verifyFacets","Set to true if facets should be verified after deployment")

  .setAction(
    async (taskArgs: DeployUpgradeTaskArgs, hre: HardhatRuntimeEnvironment) => {
      const facets: string = taskArgs.facetsAndAddSelectors;
      const facetsAndAddSelectors: FacetsAndAddSelectors[] = convertStringToFacetAndSelectors(
        facets
      );
      const diamondUpgrader: string = taskArgs.diamondUpgrader;
      const diamondAddress: string = taskArgs.diamondAddress;
      const useMultisig = taskArgs.useMultisig;
      const useLedger = taskArgs.useLedger;
      const initAddress = taskArgs.initAddress;
      const initCalldata = taskArgs.initCalldata;

      //Instantiate the Signer
      let signer: Signer;
      const owner = await ((await hre.ethers.getContractAt(
        "OwnershipFacet",
        diamondAddress
      )) as OwnershipFacet).owner();
      const testing = ["hardhat", "localhost"].includes(hre.network.name);

      if (testing) {
        await hre.network.provider.request({
          method: "hardhat_impersonateAccount",
          params: [owner],
        });
        signer = await hre.ethers.getSigner(owner);
      } else if (hre.network.name === "matic") {
        if (useLedger) {
          signer = new LedgerSigner(hre.ethers.provider);
        } else signer = (await hre.ethers.getSigners())[0];
      } else {
        throw Error("Incorrect network selected");
      }

      //Create the cut
      const deployedFacets = [];
      const cut: Cut[] = [];

      for (let index = 0; index < facetsAndAddSelectors.length; index++) {
        const facet = facetsAndAddSelectors[index];

        console.log("facet:", facet);
        if (facet.facetName.length > 0) {
          const factory = (await hre.ethers.getContractFactory(
            facet.facetName
          )) as ContractFactory;
          const deployedFacet: Contract = await factory.deploy({
            gasPrice: gasPrice,
          });
          await deployedFacet.deployed();
          console.log(
            `Deployed Facet Address for ${facet.facetName}:`,
            deployedFacet.address
          );
          deployedFacets.push(deployedFacet);

          const newSelectors = getSighashes(facet.addSelectors, hre.ethers);

          let existingFuncs = getSelectors(deployedFacet);
          for (const selector of newSelectors) {
            if (!existingFuncs.includes(selector)) {
              const index = newSelectors.findIndex((val) => val == selector);

              throw Error(
                `Selector ${selector} (${facet.addSelectors[index]}) not found`
              );
            }
          }

          let existingSelectors = getSelectors(deployedFacet);
          existingSelectors = existingSelectors.filter(
            (selector) => !newSelectors.includes(selector)
          );
          if (newSelectors.length > 0) {
            cut.push({
              facetAddress: deployedFacet.address,
              action: FacetCutAction.Add,
              functionSelectors: newSelectors,
            });
          }

          //Always replace the existing selectors to prevent duplications
          if (existingSelectors.length > 0) {
            cut.push({
              facetAddress: deployedFacet.address,
              action: FacetCutAction.Replace,
              functionSelectors: existingSelectors,
            });
          }
        }
        let removeSelectors: string[];
        if (taskArgs.rawSigs == true) {
          removeSelectors = facet.removeSelectors;
        } else {
          removeSelectors = getSighashes(facet.removeSelectors, hre.ethers);
        }
        if (removeSelectors.length > 0) {
          console.log("Removing selectors:", removeSelectors);
          cut.push({
            facetAddress: hre.ethers.constants.AddressZero,
            action: FacetCutAction.Remove,
            functionSelectors: removeSelectors,
          });
        }
      }

      //Execute the Cut
      const diamondCut = (await hre.ethers.getContractAt(
        "IDiamondCut",
        diamondAddress,
        signer
      )) as IDiamondCut;

      //Helpful for debugging
      const diamondLoupe = (await hre.ethers.getContractAt(
        "IDiamondLoupe",
        diamondAddress,
        signer
      )) as IDiamondLoupe;

      if (testing) {
        console.log("Diamond cut");
        const tx: ContractTransaction = await diamondCut.diamondCut(
          cut,
          initAddress ? initAddress : hre.ethers.constants.AddressZero,
          initCalldata ? initCalldata : "0x",
          { gasLimit: 8000000 }
        );
        console.log("Diamond cut tx:", tx.hash);
        const receipt: ContractReceipt = await tx.wait();
        if (!receipt.status) {
          throw Error(`Diamond upgrade failed: ${tx.hash}`);
        }
        console.log("Completed diamond cut: ", tx.hash);
      } else {
        //Choose to use a multisig or a simple deploy address
        if (useMultisig) {
          console.log("Diamond cut");
          const tx: PopulatedTransaction = await diamondCut.populateTransaction.diamondCut(
            cut,
            initAddress ? initAddress : hre.ethers.constants.AddressZero,
            initCalldata ? initCalldata : "0x",
            { gasLimit: 800000 }
          );
          await sendToMultisig(diamondUpgrader, signer, tx, hre.ethers);
        } else {
          const tx: ContractTransaction = await diamondCut.diamondCut(
            cut,
            initAddress ? initAddress : hre.ethers.constants.AddressZero,
            initCalldata ? initCalldata : "0x",
            { gasLimit: 800000 }
          );

          const receipt: ContractReceipt = await tx.wait();
          if (!receipt.status) {
            throw Error(`Diamond upgrade failed: ${tx.hash}`);
          }
          console.log("Completed diamond cut: ", tx.hash);
        }
      }
    }
  );
Example #15
Source File: deployUpgrade.ts    From ghst-staking with MIT License 4 votes vote down vote up
task(
  "deployUpgrade",
  "Deploys a Diamond Cut, given an address, facets and addSelectors, and removeSelectors"
)
  .addParam("diamondUpgrader", "Address of the multisig signer")
  .addParam("diamondAddress", "Address of the Diamond to upgrade")
  .addParam(
    "facetsAndAddSelectors",
    "Stringified array of facet names to upgrade, along with an array of add Selectors"
  )
  .addOptionalParam("initAddress", "The facet address to call init function on")
  .addOptionalParam("initCalldata", "The calldata for init function")
  .addFlag(
    "useMultisig",
    "Set to true if multisig should be used for deploying"
  )
  .addFlag("useLedger", "Set to true if Ledger should be used for signing")
  // .addFlag("verifyFacets","Set to true if facets should be verified after deployment")

  .setAction(
    async (taskArgs: DeployUpgradeTaskArgs, hre: HardhatRuntimeEnvironment) => {
      const facets: string = taskArgs.facetsAndAddSelectors;
      const facetsAndAddSelectors: FacetsAndAddSelectors[] =
        convertStringToFacetAndSelectors(facets);
      const diamondUpgrader: string = taskArgs.diamondUpgrader;
      const diamondAddress: string = taskArgs.diamondAddress;
      const useMultisig = taskArgs.useMultisig;
      const useLedger = taskArgs.useLedger;
      const initAddress = taskArgs.initAddress;
      const initCalldata = taskArgs.initCalldata;

      //Instantiate the Signer
      let signer: Signer;
      const owner = await (
        (await hre.ethers.getContractAt(
          "OwnershipFacet",
          diamondAddress
        )) as OwnershipFacet
      ).owner();
      const testing = ["hardhat", "localhost"].includes(hre.network.name);

      if (testing) {
        await hre.network.provider.request({
          method: "hardhat_impersonateAccount",
          params: [owner],
        });
        signer = await hre.ethers.getSigner(owner);
      } else if (hre.network.name === "matic") {
        if (useLedger) {
          signer = new LedgerSigner(hre.ethers.provider);
        } else signer = (await hre.ethers.getSigners())[0];
      } else {
        throw Error("Incorrect network selected");
      }

      //Create the cut
      const deployedFacets = [];
      const cut: Cut[] = [];

      for (let index = 0; index < facetsAndAddSelectors.length; index++) {
        const facet = facetsAndAddSelectors[index];

        const factory = (await hre.ethers.getContractFactory(
          facet.facetName
        )) as ContractFactory;
        const deployedFacet: Contract = await factory.deploy({
          gasPrice: gasPrice,
        });
        await deployedFacet.deployed();
        console.log(
          `Deployed Facet Address for ${facet.facetName}:`,
          deployedFacet.address
        );
        deployedFacets.push(deployedFacet);

        //Verify
        if (hre.network.name === "matic") {
          // await hre.run("verify:verify", {
          //   address: deployedFacet.address,
          //   constructorArguments: [],
          // });
        }

        const newSelectors = getSighashes(facet.addSelectors, hre.ethers);

        const removeSelectors = getSighashes(facet.removeSelectors, hre.ethers);

        let existingFuncs = getSelectors(deployedFacet);

        console.log("existing funcs:", existingFuncs);
        for (const selector of newSelectors) {
          if (!existingFuncs.includes(selector)) {
            const index = newSelectors.findIndex((val) => val == selector);

            throw Error(
              `Selector ${selector} (${facet.addSelectors[index]}) not found`
            );
          }
        }

        // console.log("funcs:", existingFuncs.length);

        let existingSelectors = getSelectors(deployedFacet);
        existingSelectors = existingSelectors.filter(
          (selector) => !newSelectors.includes(selector)
        );

        // console.log("existing selectors:", existingSelectors);

        // console.log("funcs:", existingSelectors.length);

        if (newSelectors.length > 0) {
          cut.push({
            facetAddress: deployedFacet.address,
            action: FacetCutAction.Add,
            functionSelectors: newSelectors,
          });
        }

        //Always replace the existing selectors to prevent duplications

        //remove extra selectors

        // existingSelectors = existingSelectors.filter(
        //   (selector) => !extra.includes(selector)
        // );

        if (existingSelectors.length > 0)
          cut.push({
            facetAddress: deployedFacet.address,
            action: FacetCutAction.Replace,
            functionSelectors: existingSelectors,
          });

        if (removeSelectors.length > 0) {
          cut.push({
            facetAddress: hre.ethers.constants.AddressZero,
            action: FacetCutAction.Remove,
            functionSelectors: removeSelectors,
          });
        }
      }

      console.log(cut);

      //Execute the Cut
      const diamondCut = (await hre.ethers.getContractAt(
        "IDiamondCut",
        diamondAddress,
        signer
      )) as IDiamondCut;

      if (testing) {
        console.log("Diamond cut");
        const tx: ContractTransaction = await diamondCut.diamondCut(
          cut,
          initAddress ? initAddress : hre.ethers.constants.AddressZero,
          initCalldata ? initCalldata : "0x",
          { gasLimit: 8000000 }
        );
        console.log("Diamond cut tx:", tx.hash);
        const receipt: ContractReceipt = await tx.wait();
        if (!receipt.status) {
          throw Error(`Diamond upgrade failed: ${tx.hash}`);
        }
        console.log("Completed diamond cut: ", tx.hash);
      } else {
        //Choose to use a multisig or a simple deploy address
        if (useMultisig) {
          console.log("Diamond cut");
          const tx: PopulatedTransaction =
            await diamondCut.populateTransaction.diamondCut(
              cut,
              initAddress ? initAddress : hre.ethers.constants.AddressZero,
              initCalldata ? initCalldata : "0x",
              { gasLimit: 800000 }
            );
          await sendToMultisig(diamondUpgrader, signer, tx, hre.ethers);
        } else {
          const tx: ContractTransaction = await diamondCut.diamondCut(
            cut,
            initAddress ? initAddress : hre.ethers.constants.AddressZero,
            initCalldata ? initCalldata : "0x",
            { gasLimit: 800000, gasPrice: gasPrice }
          );

          const receipt: ContractReceipt = await tx.wait();
          if (!receipt.status) {
            throw Error(`Diamond upgrade failed: ${tx.hash}`);
          }
          console.log("Completed diamond cut: ", tx.hash);
        }
      }
    }
  );