@ethersproject/contracts#ContractReceipt TypeScript Examples

The following examples show how to use @ethersproject/contracts#ContractReceipt. 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: batchDeposit.ts    From aavegotchi-contracts with MIT License 5 votes vote down vote up
task(
  "batchDeposit",
  "Allows the batch deposit of ERC1155 to multiple ERC721 tokens"
)
  .addParam("gotchiIds", "String array of Gotchi IDs")
  .addParam(
    "quantity",
    "The amount of ERC1155 tokens to deposit into each ERC721 token"
  )
  .addParam("itemId", "The item to deposit")
  .setAction(async (taskArgs: TaskArgs, hre: HardhatRuntimeEnvironment) => {
    const gotchiIDs: string[] = taskArgs.gotchiIds.split(",");
    const quantity: number = Number(taskArgs.quantity);
    const itemId: number = Number(taskArgs.itemId);

    //assuming all item drops are in the data/airdrops/itemdrops folder
    // const { gotchis } = require(`../data/airdrops/itemdrops/${filename}.ts`);
    const diamondAddress = maticDiamondAddress;
    const itemManager = "0xa370f2ADd2A9Fba8759147995d6A0641F8d7C119";
    let signer: Signer;
    const testing = ["hardhat", "localhost"].includes(hre.network.name);
    if (testing) {
      await hre.network.provider.request({
        method: "hardhat_impersonateAccount",
        params: [itemManager],
      });
      signer = await hre.ethers.provider.getSigner(itemManager);
    } else if (hre.network.name === "matic") {
      signer = new LedgerSigner(hre.ethers.provider, "hid", "m/44'/60'/2'/0/0");
    } else {
      throw Error("Incorrect network selected");
    }

    const itemsTransfer = (
      await hre.ethers.getContractAt("ItemsTransferFacet", diamondAddress)
    ).connect(signer) as ItemsTransferFacet;
    const uniqueIds: string[] = removeDuplicates(gotchiIDs);
    console.log(
      "Batch Depositing",
      quantity,
      "items of itemId",
      itemId,
      "to",
      uniqueIds.length,
      "gotchis"
    );
    // let eachGotchi: number[] = Array(1).fill(itemId);
    // let eachValue: number[] = Array(1).fill(quantity);
    const tx: ContractTransaction =
      await itemsTransfer.batchBatchTransferToParent(
        itemManager,
        diamondAddress,
        uniqueIds,
        Array(uniqueIds.length).fill([itemId]),
        Array(uniqueIds.length).fill([quantity]),
        { gasPrice: gasPrice }
      );
    console.log("tx:", tx.hash);
    let receipt: ContractReceipt = await tx.wait();
    // console.log("Gas used:", strDisplay(receipt.gasUsed.toString()));
    if (!receipt.status) {
      throw Error(`Error:: ${tx.hash}`);
    }
  });
Example #2
Source File: grantXP_customValues.ts    From aavegotchi-contracts with MIT License 5 votes vote down vote up
task(
  "grantXP_customValues",
  "Grants XP to Gotchis by GotchiID, with a custom array"
)
  .addParam("filename", "File that contains the airdrop")
  .addParam(
    "batchSize",
    "How many Aavegotchis to send at a time. Default is 500"
  )

  .setAction(async (taskArgs: TaskArgs, hre: HardhatRuntimeEnvironment) => {
    const filename: string = taskArgs.filename;
    const batchSize: number = Number(taskArgs.batchSize);

    let { tokenIds, amounts } = require(`../data/airdrops/${filename}.ts`);

    const diamondAddress = maticDiamondAddress;
    const gameManager = "0x8D46fd7160940d89dA026D59B2e819208E714E82";
    console.log(gameManager);
    let signer: Signer;
    const testing = ["hardhat", "localhost"].includes(hre.network.name);
    if (testing) {
      await hre.network.provider.request({
        method: "hardhat_impersonateAccount",
        params: [gameManager],
      });
      signer = await hre.ethers.provider.getSigner(gameManager);
    } else if (hre.network.name === "matic") {
      const accounts = await hre.ethers.getSigners();
      signer = accounts[0];

      // signer = new LedgerSigner(hre.ethers.provider, "hid", "m/44'/60'/2'/0/0");
    } else throw Error("Incorrect network selected");

    const managedSigner = new NonceManager(signer);

    const batches = Math.ceil(tokenIds.length / batchSize);

    console.log(
      `Sending XP to ${tokenIds.length} Aavegotchis in ${tokenIds.length} addresses!`
    );

    const dao = (
      await hre.ethers.getContractAt("DAOFacet", diamondAddress)
    ).connect(managedSigner) as DAOFacet;

    for (let index = 0; index < batches; index++) {
      console.log("Current batch id:", index);

      const offset = batchSize * index;
      const sendTokenIds = tokenIds.slice(offset, offset + batchSize);
      const sendAmounts: string[] = amounts.slice(offset, offset + batchSize);

      console.log("send token ids:", sendTokenIds);

      console.log(
        `Sending ${sendAmounts.toString()} XP to ${
          sendTokenIds.length
        } Aavegotchis `
      );

      const tx: ContractTransaction = await dao.grantExperience(
        sendTokenIds,
        sendAmounts,
        { gasPrice: gasPrice }
      );
      console.log("tx:", tx.hash);
      let receipt: ContractReceipt = await tx.wait();

      if (!receipt.status) {
        throw Error(`Error:: ${tx.hash}`);
      }
      console.log(
        "Airdropped XP to Aaavegotchis. Last tokenID:",
        sendTokenIds[sendTokenIds.length - 1]
      );
    }
  });
Example #3
Source File: addItemTypes.ts    From aavegotchi-contracts with MIT License 4 votes vote down vote up
task("addItemTypes", "Adds itemTypes and SVGs ")
  .addParam("itemManager", "Address of the item manager", "0")
  .addParam("diamondAddress", "Address of the Diamond to upgrade")
  .addParam("itemFile", "File name of the items to add")
  .addParam("svgFile", "File name of the itemType SVGs")
  .addParam("sleeveStartId", "ID of the sleeve to start at")
  .addFlag("uploadItemTypes", "Upload itemTypes")
  .addFlag("uploadWearableSvgs", "Upload the SVGs")
  .addFlag("uploadSleeveSvgs", "Upload sleeve svgs")
  .addFlag("associateSleeves", "Associate the sleeves")
  .addFlag("sendToItemManager", "Mint and send the items to itemManager")
  .addFlag("replaceWearableSvgs", "Replace wearable SVGs instead of uploading")
  .addFlag("replaceSleeveSvgs", "Replace sleeve SVGs instead of uploading")

  .setAction(
    async (taskArgs: AddItemTypesTaskArgs, hre: HardhatRuntimeEnvironment) => {
      const itemFile: string = taskArgs.itemFile;
      const diamondAddress: string = taskArgs.diamondAddress;
      const svgFile: string = taskArgs.svgFile;
      const sleeveStartId: string = taskArgs.sleeveStartId;
      const itemManager = taskArgs.itemManager;
      const sendToItemManager = taskArgs.sendToItemManager;
      const uploadItemTypes = taskArgs.uploadItemTypes;
      const uploadWearableSvgs = taskArgs.uploadWearableSvgs;
      const associateSleeves = taskArgs.associateSleeves;
      const uploadSleeveSvgs = taskArgs.uploadSleeveSvgs;
      const replaceWearableSvgs = taskArgs.replaceWearableSvgs;
      const replaceSleeveSvgs = taskArgs.replaceSleeveSvgs;

      const {
        itemTypes: currentItemTypes,
      } = require(`../data/itemTypes/${itemFile}.ts`);

      const { getWearables } = require(`../svgs/${svgFile}.ts`);
      const { sleeves, wearables } = getWearables();

      const itemTypesArray: ItemTypeOutput[] = getItemTypes(
        currentItemTypes,
        hre.ethers
      );

      const svgsArray: string[] = wearables;
      const sleeveSvgsArray: SleeveObject[] = sleeves;

      let signer: Signer;

      let owner = itemManager;
      const testing = ["hardhat", "localhost"].includes(hre.network.name);
      if (testing) {
        await hre.network.provider.request({
          method: "hardhat_impersonateAccount",
          params: [owner],
        });
        signer = await hre.ethers.provider.getSigner(owner);
      } else if (hre.network.name === "matic") {
        signer = new LedgerSigner(
          hre.ethers.provider,
          "hid",
          "m/44'/60'/2'/0/0"
        );
      } else {
        throw Error("Incorrect network selected");
      }

      let tx: ContractTransaction;
      let receipt: ContractReceipt;

      let daoFacet = (await hre.ethers.getContractAt(
        "DAOFacet",
        diamondAddress,
        signer
      )) as DAOFacet;

      let svgFacet = (await hre.ethers.getContractAt(
        "SvgFacet",
        diamondAddress,
        signer
      )) as SvgFacet;

      if (uploadItemTypes) {
        console.log("Adding items", 0, "to", currentItemTypes.length);

        tx = await daoFacet.addItemTypes(itemTypesArray, {
          gasPrice: gasPrice,
        });

        receipt = await tx.wait();
        if (!receipt.status) {
          throw Error(`Error:: ${tx.hash}`);
        }
        console.log("Items were added:", tx.hash);
      }

      if (uploadWearableSvgs) {
        console.log("Upload SVGs");
        await uploadSvgs(svgFacet, svgsArray, "wearables", hre.ethers);
      }

      if (replaceWearableSvgs) {
        await updateSvgs(
          svgsArray,
          "wearables",
          itemTypesArray.map((value) => Number(value.svgId)),
          svgFacet,
          hre
        );
      }

      if (uploadSleeveSvgs) {
        console.log("Uploading Sleeves");

        await uploadSvgs(
          svgFacet,
          sleeveSvgsArray.map((value) => value.svg),
          "sleeves",
          hre.ethers
        );
      }

      if (replaceSleeveSvgs) {
        await updateSvgs(
          sleeveSvgsArray.map((value) => value.svg),
          "sleeves",
          sleeveSvgsArray.map((_, index) => Number(sleeveStartId) + index),
          svgFacet,
          hre
        );
      }

      if (associateSleeves) {
        interface SleeveInput {
          sleeveId: BigNumberish;
          wearableId: BigNumberish;
        }

        let sleevesSvgId: number = Number(sleeveStartId);
        let sleevesInput: SleeveInput[] = [];
        for (const sleeve of sleeveSvgsArray) {
          sleevesInput.push({
            sleeveId: sleevesSvgId,
            wearableId: sleeve.id,
          });
          sleevesSvgId++;
        }

        console.log("sleeves input:", sleevesInput);

        console.log("Associating sleeves svgs with body wearable svgs.");
        tx = await svgFacet.setSleeves(sleevesInput, { gasPrice: gasPrice });
        receipt = await tx.wait();
        if (!receipt.status) {
          throw Error(`Error:: ${tx.hash}`);
        }
        console.log("Sleeves associated:", tx.hash);
      }

      if (sendToItemManager) {
        const itemIds: BigNumberish[] = [];
        const quantities: BigNumberish[] = [];
        itemTypesArray.forEach((itemType: ItemTypeOutput) => {
          itemIds.push(itemType.svgId);
          quantities.push(itemType.maxQuantity);
        });

        console.log("final quantities:", itemIds, quantities);

        console.log(`Mint prize items to Item Manager ${itemManager}`);

        tx = await daoFacet.mintItems(itemManager, itemIds, quantities, {
          gasPrice: gasPrice,
        });
        receipt = await tx.wait();
        if (!receipt.status) {
          throw Error(`Error:: ${tx.hash}`);
        }

        console.log("Prize items minted:", tx.hash);
      }
    }
  );
Example #4
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 #5
Source File: grantXP.ts    From aavegotchi-contracts with MIT License 4 votes vote down vote up
task("grantXP", "Grants XP to Gotchis by addresses")
  .addParam("filename", "File that contains the airdrop")
  .addParam("xpAmount", "Amount of XP that each Aavegotchi should receive")
  .addParam(
    "batchSize",
    "How many Aavegotchis to send at a time. Default is 500"
  )
  .addParam("excludedAddresses", "Any addresses excluded")

  .setAction(async (taskArgs: TaskArgs, hre: HardhatRuntimeEnvironment) => {
    const filename: string = taskArgs.filename;
    const xpAmount: number = Number(taskArgs.xpAmount);
    const batchSize: number = Number(taskArgs.batchSize);
    const excludedAddresses: string[] = taskArgs.excludedAddresses
      .split(",")
      .map((val) => val.toLowerCase());

    let { addresses } = require(`../data/airdrops/${filename}.ts`);

    //Filter out addresses
    addresses = addresses.filter((address: string) => {
      return !excludedAddresses.includes(address.toLowerCase());
    });

    const { finalUsers, tokenIds } = await getPolygonAndMainnetGotchis(
      addresses,
      hre
    );

    const diamondAddress = maticDiamondAddress;
    const gameManager = "0x8D46fd7160940d89dA026D59B2e819208E714E82";
    console.log(gameManager);
    let signer: Signer;
    const testing = ["hardhat", "localhost"].includes(hre.network.name);
    if (testing) {
      await hre.network.provider.request({
        method: "hardhat_impersonateAccount",
        params: [gameManager],
      });
      signer = await hre.ethers.provider.getSigner(gameManager);
    } else if (hre.network.name === "matic") {
      const accounts = await hre.ethers.getSigners();
      signer = accounts[0];

      // signer = new LedgerSigner(hre.ethers.provider, "hid", "m/44'/60'/2'/0/0");
    } else throw Error("Incorrect network selected");

    const managedSigner = new NonceManager(signer);

    const batches = Math.ceil(tokenIds.length / batchSize);

    console.log(
      `Sending ${xpAmount} XP to ${tokenIds.length} Aavegotchis in ${finalUsers.length} addresses!`
    );

    const dao = (
      await hre.ethers.getContractAt("DAOFacet", diamondAddress)
    ).connect(managedSigner) as DAOFacet;

    for (let index = 0; index < batches; index++) {
      console.log("Current batch id:", index);

      const offset = batchSize * index;
      const sendTokenIds = tokenIds.slice(offset, offset + batchSize);

      console.log("send token ids:", sendTokenIds);

      // sendTokenIds.forEach((id: string) => {
      //   console.log(id);
      // });

      console.log(
        `Sending ${xpAmount} XP to ${sendTokenIds.length} Aavegotchis `
      );

      const tx: ContractTransaction = await dao.grantExperience(
        sendTokenIds,
        Array(sendTokenIds.length).fill(xpAmount),
        { gasPrice: gasPrice }
      );
      console.log("tx:", tx.hash);
      let receipt: ContractReceipt = await tx.wait();

      if (!receipt.status) {
        throw Error(`Error:: ${tx.hash}`);
      }
      console.log(
        "Airdropped XP to Aaavegotchis. Last tokenID:",
        sendTokenIds[sendTokenIds.length - 1]
      );
    }
  });
Example #6
Source File: grantXP_snapshot.ts    From aavegotchi-contracts with MIT License 4 votes vote down vote up
task("grantXP_snapshot", "Grants XP to Gotchis by addresses")
  .addParam("proposalId", "ID of the Snapshot proposal")
  .addParam("propType", "sigprop or coreprop")
  .addParam(
    "batchSize",
    "How many Aavegotchis to send at a time. Default is 500"
  )

  .setAction(
    async (
      taskArgs: GrantXPSnapshotTaskArgs,
      hre: HardhatRuntimeEnvironment
    ) => {
      const proposalId: string = taskArgs.proposalId;
      const xpAmount: number = taskArgs.propType === "sigprop" ? 10 : 20;
      const batchSize: number = Number(taskArgs.batchSize);

      const addresses = await getVotingAddresses(proposalId);
      const propDetails: ProposalDetails = await getProposalDetails(proposalId);

      if (propDetails.votes !== addresses.length) {
        throw new Error("Proposal voter count doesn't match");
      }

      const diamondAddress = maticDiamondAddress;
      const gameManager = "0x8D46fd7160940d89dA026D59B2e819208E714E82";
      console.log(gameManager);
      let signer: Signer;
      const testing = ["hardhat", "localhost"].includes(hre.network.name);
      if (testing) {
        await hre.network.provider.request({
          method: "hardhat_impersonateAccount",
          params: [gameManager],
        });
        signer = await hre.ethers.provider.getSigner(gameManager);
      } else if (hre.network.name === "matic") {
        const accounts = await hre.ethers.getSigners();
        signer = accounts[0]; /* new LedgerSigner(
          hre.ethers.provider,
          "hid",
          "m/44'/60'/2'/0/0"
        ); */
      } else {
        throw Error("Incorrect network selected");
      }

      const managedSigner = new NonceManager(signer);

      const { tokenIds, finalUsers } = await getPolygonAndMainnetGotchis(
        addresses,
        hre
      );

      const batches = Math.ceil(tokenIds.length / batchSize);

      console.log(`Deploying ${taskArgs.propType}: ${propDetails.title}!!!`);

      console.log(
        `Sending ${xpAmount} XP to ${tokenIds.length} Aavegotchis in ${finalUsers.length} addresses!`
      );

      const dao = (
        await hre.ethers.getContractAt("DAOFacet", diamondAddress)
      ).connect(managedSigner) as DAOFacet;

      for (let index = 0; index < batches; index++) {
        console.log("Current batch id:", index);

        // if (index < 13) continue;

        const offset = batchSize * index;
        const sendTokenIds = tokenIds.slice(offset, offset + batchSize);

        console.log(
          `Sending ${xpAmount} XP to ${sendTokenIds.length} Aavegotchis `
        );

        const tx: ContractTransaction = await dao.grantExperience(
          sendTokenIds,
          Array(sendTokenIds.length).fill(xpAmount),
          { gasPrice: gasPrice }
        );
        console.log("tx:", tx.hash);
        const receipt: ContractReceipt = await tx.wait();
        // console.log("Gas used:", strDisplay(receipt.gasUsed.toString()));
        if (!receipt.status) {
          throw Error(`Error:: ${tx.hash}`);
        }
        console.log(
          "Airdropped XP to Aaavegotchis. Last tokenID:",
          sendTokenIds[sendTokenIds.length - 1]
        );
      }
    }
  );
Example #7
Source File: mintBaadgeSvgs.ts    From aavegotchi-contracts with MIT License 4 votes vote down vote up
task("mintBaadgeSvgs", "Adds itemTypes and SVGs")
  .addParam("itemManager", "Address of the item manager", "0")
  .addParam("itemFile", "File name of the items to add")
  .addFlag("uploadItemTypes", "Upload itemTypes")
  .addFlag("sendToItemManager", "Mint and send the items to itemManager")

  .setAction(
    async (taskArgs: MintBaadgeTaskArgs, hre: HardhatRuntimeEnvironment) => {
      console.log("item manager:", taskArgs.itemManager);

      if (taskArgs.itemManager !== itemManagerAlt) {
        throw new Error("Wrong item manager");
      }

      const itemFile: string = taskArgs.itemFile;
      const itemManager = taskArgs.itemManager;
      const sendToItemManager = taskArgs.sendToItemManager;
      const uploadItemTypes = taskArgs.uploadItemTypes;

      const {
        itemTypes: currentItemTypes,
      } = require(`../scripts/addItemTypes/itemTypes/${itemFile}.ts`);

      const itemTypesArray: ItemTypeOutput[] =
        getBaadgeItemTypes(currentItemTypes);

      let signer: Signer;

      let owner = itemManager;
      const testing = ["hardhat", "localhost"].includes(hre.network.name);
      if (testing) {
        await hre.network.provider.request({
          method: "hardhat_impersonateAccount",
          params: [owner],
        });
        signer = await hre.ethers.provider.getSigner(owner);
      } else if (hre.network.name === "matic") {
        signer = await (await hre.ethers.getSigners())[0];
        // signer = new LedgerSigner(
        //   hre.ethers.provider,
        //   "hid",
        //   "m/44'/60'/2'/0/0"
        // );
      } else {
        throw Error("Incorrect network selected");
      }

      console.log("signer:", await signer.getAddress());

      let tx: ContractTransaction;
      let receipt: ContractReceipt;

      let daoFacet = (await hre.ethers.getContractAt(
        "DAOFacet",
        maticDiamondAddress,
        signer
      )) as DAOFacet;

      if (uploadItemTypes) {
        console.log("Adding items", 0, "to", currentItemTypes.length);

        tx = await daoFacet.addItemTypes(itemTypesArray, {
          gasPrice: gasPrice,
        });

        console.log("tx hash:", tx.hash);

        receipt = await tx.wait();
        if (!receipt.status) {
          throw Error(`Error:: ${tx.hash}`);
        }
        console.log("Items were added:", tx.hash);
      }

      if (sendToItemManager) {
        const itemIds: BigNumberish[] = [];
        const quantities: BigNumberish[] = [];
        currentItemTypes.forEach((itemType: ItemTypeOutput) => {
          itemIds.push(itemType.svgId);
          quantities.push(itemType.maxQuantity);
        });

        console.log("final quantities:", itemIds, quantities);

        console.log(`Mint prize items to Item Manager ${itemManager}`);

        tx = await daoFacet.mintItems(itemManager, itemIds, quantities, {
          gasPrice: gasPrice,
        });
        receipt = await tx.wait();
        if (!receipt.status) {
          throw Error(`Error:: ${tx.hash}`);
        }

        console.log("Prize items minted:", tx.hash);
      }
    }
  );
Example #8
Source File: rarityPayouts.ts    From aavegotchi-contracts with MIT License 4 votes vote down vote up
task("rarityPayout")
  .addParam("season")
  .addParam(
    "rarityDataFile",
    "File that contains all the data related to the particular rarity round"
  )
  .addParam("deployerAddress")
  .addParam("tieBreakerIndex", "The Tiebreaker index")
  .setAction(
    async (taskArgs: RarityPayoutTaskArgs, hre: HardhatRuntimeEnvironment) => {
      const filename: string = taskArgs.rarityDataFile;
      const diamondAddress = maticDiamondAddress;
      const deployerAddress = taskArgs.deployerAddress;

      console.log("deployer:", deployerAddress);
      const accounts = await hre.ethers.getSigners();
      tiebreakerIndex = taskArgs.tieBreakerIndex;

      const testing = ["hardhat", "localhost"].includes(hre.network.name);
      let signer: Signer;
      if (testing) {
        await hre.network.provider.request({
          method: "hardhat_impersonateAccount",
          params: [deployerAddress],
        });
        signer = await hre.ethers.provider.getSigner(deployerAddress);
      } else if (hre.network.name === "matic") {
        signer = accounts[0];
      } else {
        throw Error("Incorrect network selected");
      }

      const managedSigner = new NonceManager(signer);

      const rounds = Number(taskArgs.rounds);

      const signerAddress = await signer.getAddress();
      if (signerAddress !== deployerAddress) {
        throw new Error(
          `Deployer ${deployerAddress} does not match signer ${signerAddress}`
        );
      }

      //Get rewards for this season
      const {
        rewardArgs,
      } = require(`../data/airdrops/rarityfarming/szn${taskArgs.season}/rewards`);
      const rewards: RarityFarmingRewardArgs = rewardArgs;

      const maxProcess = 500;
      const finalRewards: rarityRewards = {};

      //Get data for this round from file
      const {
        dataArgs,
      } = require(`../data/airdrops/rarityfarming/szn${taskArgs.season}/${filename}.ts`);
      const data: RarityFarmingData = dataArgs;

      const leaderboards = [
        "withSetsRarityScore",
        "kinship",
        "experience",
        // "kinship",
        // "experience",
      ];
      const dataNames: LeaderboardDataName[] = [
        "rarityGotchis",
        "kinshipGotchis",
        "xpGotchis",
        // "rookieKinshipGotchis",
        // "rookieXpGotchis",
      ];

      //handle rookie now

      const leaderboardResults: RarityFarmingData = {
        rarityGotchis: [],
        xpGotchis: [],
        kinshipGotchis: [],
      };

      // let extraFilter: string = "";
      for (let index = 0; index < leaderboards.length; index++) {
        // if (
        //   index === leaderboards.length - 1 ||
        //   index === leaderboards.length - 2
        // ) {
        //   console.log("getting rookies");
        //   // extraFilter = rookieFilter;
        // }
        let element: LeaderboardType = leaderboards[index] as LeaderboardType;

        const result = stripGotchis(
          await fetchAndSortLeaderboard(
            element,
            taskArgs.blockNumber,
            Number(taskArgs.tieBreakerIndex)
          )
        );

        const dataName: LeaderboardDataName = dataNames[
          index
        ] as LeaderboardDataName;

        const correct = confirmCorrectness(result, data[dataName]);

        console.log("correct:", correct);

        if (correct !== 7500) {
          throw new Error("Results do not line up with subgraph");
        }

        leaderboardResults[dataName] = result;
      }

      //get rewards
      const rarityRoundRewards: string[] = rewards.rarity;
      const kinshipRoundRewards: string[] = rewards.kinship;
      const xpRoundRewards: string[] = rewards.xp;
      // const rookieKinshipRoundRewards: string[] = rewards.rookieKinship;
      // const rookieXpRoundRewards: string[] = rewards.rookieXp;

      //Iterate through all 5000 spots
      for (let index = 0; index < 7500; index++) {
        const gotchis: string[] = [
          leaderboardResults.rarityGotchis[index],
          leaderboardResults.kinshipGotchis[index],
          leaderboardResults.xpGotchis[index],
          // leaderboardResults.rookieKinshipGotchis[index],
          // leaderboardResults.rookieXpGotchis[index],
        ];

        const rewards: string[][] = [
          rarityRoundRewards,
          kinshipRoundRewards,
          xpRoundRewards,
          // rookieKinshipRoundRewards,
          // rookieXpRoundRewards,
        ];

        rewards.forEach((leaderboard, i) => {
          const gotchi = gotchis[i];
          const reward = leaderboard[index];

          if (finalRewards[gotchi])
            finalRewards[gotchi] += Number(reward) / rounds;
          else {
            finalRewards[gotchi] = Number(reward) / rounds;
          }
        });
      }

      //Check that sent amount matches total amount per round
      const roundAmount = Number(taskArgs.totalAmount) / rounds;
      let talliedAmount = 0;

      Object.keys(finalRewards).map((gotchiId) => {
        const amount = finalRewards[gotchiId];

        if (!isNaN(amount)) {
          talliedAmount = talliedAmount + amount;
        }
      });

      const sorted: string[] = [];
      const sortedKeys = Object.keys(finalRewards).sort((a, b) => {
        return finalRewards[b] - finalRewards[a];
      });

      sortedKeys.forEach((key) => {
        sorted.push(`${key}: ${finalRewards[key]}`);
      });

      console.log("Total GHST to send:", talliedAmount);
      console.log("Round amount:", roundAmount);

      let totalGhstSent = BigNumber.from(0);
      let txData = [];
      let txGroup: TxArgs[] = [];
      let tokenIdsNum = 0;

      for (const gotchiID of Object.keys(finalRewards)) {
        let amount = finalRewards[gotchiID];
        let parsedAmount = BigNumber.from(parseEther(amount.toString()));
        let finalParsed = parsedAmount.toString();

        if (maxProcess < tokenIdsNum + 1) {
          txData.push(txGroup);
          txGroup = [];
          tokenIdsNum = 0;
        }

        txGroup.push({
          tokenID: gotchiID,
          amount: amount,
          parsedAmount: finalParsed,
        });
        tokenIdsNum += 1;
      }

      if (tokenIdsNum > 0) {
        txData.push(txGroup);
        txGroup = [];
        tokenIdsNum = 0;
      }

      for (const [i, txGroup] of txData.entries()) {
        console.log("current index:", i);

        if (i < 10) continue;

        let tokenIds: string[] = [];
        let amounts: string[] = [];

        const removeList = ["17231", "21129", "21944", "16681"];

        txGroup.forEach((sendData) => {
          if (removeList.includes(sendData.tokenID)) {
            console.log(
              `Removing ${sendData.tokenID} because it's on the bad list`
            );
          } else {
            tokenIds.push(sendData.tokenID);
            amounts.push(sendData.parsedAmount);
          }
        });

        let totalAmount = amounts.reduce((prev, curr) => {
          return BigNumber.from(prev).add(BigNumber.from(curr)).toString();
        });

        totalGhstSent = totalGhstSent.add(totalAmount);

        console.log(
          `Sending ${formatEther(totalAmount)} GHST to ${
            tokenIds.length
          } Gotchis (from ${tokenIds[0]} to ${tokenIds[tokenIds.length - 1]})`
        );

        const escrowFacet = (
          await hre.ethers.getContractAt("EscrowFacet", diamondAddress)
        ).connect(managedSigner) as EscrowFacet;
        const tx = await escrowFacet.batchDepositGHST(tokenIds, amounts, {
          gasPrice: gasPrice,
        });

        let receipt: ContractReceipt = await tx.wait();
        console.log("receipt:", receipt.transactionHash);
        console.log("Gas used:", strDisplay(receipt.gasUsed.toString()));
        if (!receipt.status) {
          throw Error(`Error:: ${tx.hash}`);
        }
        console.log("Total GHST Sent:", formatEther(totalGhstSent));
      }
    }
  );
Example #9
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);
        }
      }
    }
  );