ethers#Contract TypeScript Examples

The following examples show how to use ethers#Contract. 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: utils.ts    From hypervisor with The Unlicense 7 votes vote down vote up
signPermission = async (
  method: string,
  vault: Contract,
  owner: Wallet,
  delegateAddress: string,
  tokenAddress: string,
  amount: BigNumberish,
  vaultNonce: BigNumberish,
  chainId?: BigNumberish,
) => {
  // get chainId
  chainId = chainId || (await vault.provider.getNetwork()).chainId
  // craft permission
  const domain = {
    name: 'UniversalVault',
    version: '1.0.0',
    chainId: chainId,
    verifyingContract: vault.address,
  }
  const types = {} as Record<string, TypedDataField[]>
  types[method] = [
    { name: 'delegate', type: 'address' },
    { name: 'token', type: 'address' },
    { name: 'amount', type: 'uint256' },
    { name: 'nonce', type: 'uint256' },
  ]
  const value = {
    delegate: delegateAddress,
    token: tokenAddress,
    amount: amount,
    nonce: vaultNonce,
  }
  // sign permission
  // todo: add fallback if wallet does not support eip 712 rpc
  const signedPermission = await owner._signTypedData(domain, types, value)
  // return
  return signedPermission
}
Example #2
Source File: utilities.ts    From apeswap-swap-core with GNU General Public License v3.0 7 votes vote down vote up
export async function getApprovalDigest(
  token: Contract,
  approve: {
    owner: string
    spender: string
    value: BigNumber
  },
  nonce: BigNumber,
  deadline: BigNumber
): Promise<string> {
  const name = await token.name()
  const DOMAIN_SEPARATOR = getDomainSeparator(name, token.address)
  return keccak256(
    solidityPack(
      ['bytes1', 'bytes1', 'bytes32', 'bytes32'],
      [
        '0x19',
        '0x01',
        DOMAIN_SEPARATOR,
        keccak256(
          defaultAbiCoder.encode(
            ['bytes32', 'address', 'address', 'uint256', 'uint256', 'uint256'],
            [PERMIT_TYPEHASH, approve.owner, approve.spender, approve.value, nonce, deadline]
          )
        )
      ]
    )
  )
}
Example #3
Source File: submitting.ts    From safe-tasks with GNU Lesser General Public License v3.0 6 votes vote down vote up
prepareSignatures = async (safe: Contract, tx: SafeTransaction, signaturesCSV: string | undefined, submitter?: Signer, knownSafeTxHash?: string): Promise<SafeSignature[]> => {
    const owners = await safe.getOwners()
    const signatures = new Map<String, SafeSignature>()
    const submitterAddress = submitter && await submitter.getAddress()
    if (signaturesCSV) {
        const chainId = (await safe.provider.getNetwork()).chainId
        const safeTxHash = knownSafeTxHash ?? calculateSafeTransactionHash(safe, tx, chainId)
        for (const signatureString of signaturesCSV.split(",")) {
            const signature = isOwnerSignature(owners, parseSignature(safeTxHash, signatureString))
            if (submitterAddress === signature.signer || signatures.has(signature.signer)) continue
            signatures.set(signature.signer, signature)
        }
    }
    const threshold = (await safe.getThreshold()).toNumber()
    const submitterIsOwner = submitterAddress && owners.indexOf(submitterAddress) >= 0
    const requiredSigntures = submitterIsOwner ? threshold - 1 : threshold
    if (requiredSigntures > signatures.size) throw Error(`Not enough signatures (${signatures.size} of ${threshold})`)
    const signatureArray = []
    if (submitterIsOwner) {
        signatureArray.push(await safeApproveHash(submitter!!, safe, tx, true))
    }
    return signatureArray.concat(Array.from(signatures.values()).slice(0, requiredSigntures))
}
Example #4
Source File: task.ts    From balancer-v2-monorepo with GNU General Public License v3.0 6 votes vote down vote up
async deploy(name: string, args: Array<Param> = [], from?: SignerWithAddress, libs?: Libraries): Promise<Contract> {
    if (this.mode == TaskMode.CHECK) {
      return await this.check(name, args, libs);
    }

    if (this.mode !== TaskMode.LIVE && this.mode !== TaskMode.TEST) {
      throw Error(`Cannot deploy in tasks of mode ${TaskMode[this.mode]}`);
    }

    const instance = await deploy(this.artifact(name), args, from, libs);
    this.save({ [name]: instance });
    logger.success(`Deployed ${name} at ${instance.address}`);

    if (this.mode === TaskMode.LIVE) {
      await saveContractDeploymentTransactionHash(instance.address, instance.deployTransaction.hash, this.network);
    }
    return instance;
  }
Example #5
Source File: transactions.ts    From connect with GNU Lesser General Public License v3.0 6 votes vote down vote up
export async function buildForwardingFeePreTransactions(
  forwardingTransaction: Transaction,
  provider: ethersProviders.Provider
): Promise<Transaction[]> {
  const { to: forwarderAddress, from } = forwardingTransaction

  const forwarderFee = new Contract(forwarderAddress, forwarderFeeAbi, provider)

  const feeDetails = { amount: BigInt(0), tokenAddress: '' }
  try {
    const overrides = {
      from,
    }
    // Passing the EOA as `msg.sender` to the forwardFee call is useful for use cases where the fee differs relative to the account
    const [tokenAddress, amount] = await forwarderFee.forwardFee(overrides) // forwardFee() returns (address, uint256)
    feeDetails.tokenAddress = tokenAddress
    feeDetails.amount = BigInt(amount)
  } catch (err) {
    // Not all forwarders implement the `forwardFee()` interface
  }

  if (feeDetails.tokenAddress && feeDetails.amount > BigInt(0)) {
    // Needs a token approval pre-transaction
    const tokenData: TokenData = {
      address: feeDetails.tokenAddress,
      spender: forwarderAddress, // since it's a forwarding transaction, always show the real spender
      value: feeDetails.amount.toString(),
    }

    return buildApprovePreTransactions(
      forwardingTransaction,
      tokenData,
      provider
    )
  }
  return []
}
Example #6
Source File: eip1271.ts    From walletconnect-v2-monorepo with Apache License 2.0 6 votes vote down vote up
async function isValidSignature(
  address: string,
  sig: string,
  data: string,
  provider: providers.Provider,
  abi = eip1271.spec.abi,
  magicValue = eip1271.spec.magicValue,
): Promise<boolean> {
  let returnValue;
  try {
    returnValue = await new Contract(address, abi, provider).isValidSignature(
      utils.arrayify(data),
      sig,
    );
  } catch (e) {
    return false;
  }
  return returnValue.toLowerCase() === magicValue.toLowerCase();
}
Example #7
Source File: MockUniswapV3PoolDeployer__factory.ts    From hypervisor with The Unlicense 6 votes vote down vote up
static connect(
    address: string,
    signerOrProvider: Signer | Provider
  ): MockUniswapV3PoolDeployer {
    return new Contract(
      address,
      _abi,
      signerOrProvider
    ) as MockUniswapV3PoolDeployer;
  }
Example #8
Source File: UniswapV3Deployer.ts    From hardhat-v3-deploy with MIT License 6 votes vote down vote up
async deployNonfungiblePositionManager(
    factoryAddress: string,
    weth9Address: string,
    positionDescriptorAddress: string
  ) {
    return await this.deployContract<Contract>(
      artifacts.NonfungiblePositionManager.abi,
      artifacts.NonfungiblePositionManager.bytecode,
      [factoryAddress, weth9Address, positionDescriptorAddress],
      this.deployer
    );
  }
Example #9
Source File: connectContractToSigner.test.ts    From useDApp with MIT License 6 votes vote down vote up
describe('connectContractToSigner', () => {
  const mockProvider = new MockProvider()
  const [deployer] = mockProvider.getWallets()
  let token: Contract

  beforeEach(async () => {
    token = new Contract(deployer.address, ERC20Interface)
  })

  it('throws error without signer', () => {
    expect(() => connectContractToSigner(token)).to.throw('No signer available in contract, options or library')
  })

  it('noop if contract has signer', () => {
    const signer = mockProvider.getSigner()
    const connectedContract = token.connect(signer)

    expect(connectContractToSigner(connectedContract).signer).to.eq(signer)
  })

  it('takes signer from options', () => {
    const signer = mockProvider.getSigner()
    const connectedContract = connectContractToSigner(token, { signer })

    expect(connectedContract.signer).to.eq(signer)
  })

  it('takes signer from library', async () => {
    const { result, waitForCurrent } = await renderWeb3Hook(() => useEthers(), { mockProvider })
    await waitForCurrent((val) => val?.library !== undefined)
    const { library } = result.current

    const connectedContract = connectContractToSigner(token, undefined, library)

    expect(connectedContract.signer).to.be.deep.eq(library?.getSigner())
  })
})
Example #10
Source File: lp-bond.ts    From rugenerous-frontend with MIT License 6 votes vote down vote up
async getTreasuryBalance(networkID: Networks, provider: StaticJsonRpcProvider) {
    const addresses = getAddresses(networkID);

    const token = this.getContractForReserve(networkID, provider);
    const tokenAddress = this.getAddressForReserve(networkID);
    const bondCalculator = getBondCalculator(networkID, provider, this.name);
    const tokenAmount = await token.balanceOf(addresses.TREASURY_ADDRESS);
    const valuation = await bondCalculator.valuation(tokenAddress, tokenAmount);
    const markdown = await bondCalculator.markdown(tokenAddress);

    const token1: string = await token.token1();
    const token1Contract = new ethers.Contract(token1, ERC20Contract, provider);
    const token1Decimals = await token1Contract.decimals();

    const token0: string = await token.token0();
    const token0Contract = new ethers.Contract(token0, ERC20Contract, provider);
    const token0Decimals = await token0Contract.decimals();

    const isRug = token1.toLowerCase() === addresses.RUG_ADDRESS.toLowerCase();
    var tokenUSD;

    if (isRug) {
      tokenUSD = (valuation / Math.pow(10, 9)) * (markdown / Math.pow(10, token0Decimals));
    } else {
      tokenUSD = (valuation / Math.pow(10, 9)) * (markdown / Math.pow(10, token1Decimals));
    }

    return tokenUSD;
  }
Example #11
Source File: index.ts    From nova with GNU Affero General Public License v3.0 6 votes vote down vote up
/** Calls all stateful functions in a contract to check if they revert with unauthorized.  */
export async function checkAllFunctionsForAuth(
  contract: Contract,
  account: SignerWithAddress,
  ignoreNames?: string[]
) {
  const statefulFragments = getAllStatefulFragments(contract.interface);

  for (const fragment of statefulFragments) {
    if (ignoreNames?.includes(fragment.name)) {
      continue;
    }

    await contract
      .connect(account)
      [fragment.name](...fragment.inputs.map(getValueForParamType))
      .should.be.revertedWith("UNAUTHORIZED");
  }
}
Example #12
Source File: env.ts    From panvala with Apache License 2.0 6 votes vote down vote up
export async function loadContracts(provider) {
  const { chainId } = await provider.getNetwork();
  const signer = provider.getSigner();

  // Addresses
  const tokenAddress =
    chainId === 4
      ? '0x4912d6aBc68e4F02d1FdD6B79ed045C0A0BAf772'
      : chainId === 1 && '0xD56daC73A4d6766464b38ec6D91eB45Ce7457c44';
  const tcAddress =
    chainId === 4
      ? '0xA062C59F42a45f228BEBB6e7234Ed1ea14398dE7'
      : chainId === 1 && '0x9a7B675619d3633304134155c6c976E9b4c1cfB3';
  const exchangeAddress =
    chainId === 4
      ? '0x25EAd1E8e3a9C38321488BC5417c999E622e36ea'
      : chainId === 1 && '0xF53bBFBff01c50F2D42D542b09637DcA97935fF7';

  // Get codes
  const tokenCode = await provider.getCode(tokenAddress);
  const tcCode = await provider.getCode(tcAddress);
  const exchangeCode = await provider.getCode(exchangeAddress);

  // prettier-ignore
  if (!tokenAddress || !tcAddress || !exchangeAddress || !tokenCode || !tcCode || !exchangeCode) {
        throw new Error('Invalid address or no code at address.')
      }

  // Init token, token capacitor, uniswap exchange contracts
  const token = new Contract(tokenAddress, tokenAbi, signer);
  const tokenCapacitor = new Contract(tcAddress, tcAbi, signer);
  const exchange = new Contract(exchangeAddress, exchangeAbi as ContractInterface, signer);

  return {
    token,
    tokenCapacitor,
    exchange,
  };
}
Example #13
Source File: admin.ts    From openzeppelin-upgrades with MIT License 6 votes vote down vote up
export async function getManifestAdmin(hre: HardhatRuntimeEnvironment): Promise<Contract> {
  const manifest = await Manifest.forNetwork(hre.network.provider);
  const manifestAdmin = await manifest.getAdmin();
  const proxyAdminAddress = manifestAdmin?.address;

  if (proxyAdminAddress === undefined) {
    throw new Error('No ProxyAdmin was found in the network manifest');
  }

  const AdminFactory = await getProxyAdminFactory(hre);
  return AdminFactory.attach(proxyAdminAddress);
}
Example #14
Source File: index.ts    From index-ui with MIT License 6 votes vote down vote up
getSupplyCap = async (tokenAddress: string): Promise<string> => {
  const provider = getProvider()
  const tokenContract = await new Contract(
    tokenAddress,
    SupplyCapIssuanceABI,
    provider
  )
  try {
    const cap = await tokenContract.supplyCap()
    return cap.toString()
  } catch (e) {
    return '1'
  }
}
Example #15
Source File: rinkeby-diamond-arguments-etherscan.ts    From BarnBridge-Barn with Apache License 2.0 6 votes vote down vote up
async function getFacets (): Promise<Contract[]> {
    const facets: Contract[] = [];

    for (const key of facetAddresses.keys()) {
        facets.push(await helpers.contractAt(key, facetAddresses.get(key) || ''));
    }

    return facets;
}
Example #16
Source File: proposing.ts    From safe-tasks with GNU Lesser General Public License v3.0 6 votes vote down vote up
calcSafeTxHash = async (safe: Contract, tx: SafeTransaction, chainId: number, onChainOnly: boolean): Promise<string> => {
    const onChainHash = await safe.getTransactionHash(
        tx.to, tx.value, tx.data, tx.operation, tx.safeTxGas, tx.baseGas, tx.gasPrice, tx.gasToken, tx.refundReceiver, tx.nonce
    )
    if (onChainOnly) return onChainHash
    const offChainHash = calculateSafeTransactionHash(safe, tx, chainId)
    if (onChainHash != offChainHash) throw Error("Unexpected hash! (For pre-1.3.0 version use --on-chain-hash)")
    return offChainHash
}
Example #17
Source File: rinkeby-deploy-barn.ts    From BarnBridge-Barn with Apache License 2.0 6 votes vote down vote up
async function getFacets (): Promise<Contract[]> {
    const facets: Contract[] = [];

    for (const key of facetAddresses.keys()) {
        facets.push(await helpers.contractAt(key, facetAddresses.get(key) || ''));
    }

    return facets;
}
Example #18
Source File: fixtures.ts    From apeswap-swap-core with GNU General Public License v3.0 6 votes vote down vote up
export async function pairFixture([wallet]: Wallet[], provider: Web3Provider): Promise<PairFixture> {
  const { factory } = await factoryFixture([wallet], provider)

  const tokenA = await deployContract(wallet, ERC20, [expandTo18Decimals(10000)], overrides)
  const tokenB = await deployContract(wallet, ERC20, [expandTo18Decimals(10000)], overrides)

  await factory.createPair(tokenA.address, tokenB.address, overrides)
  const pairAddress = await factory.getPair(tokenA.address, tokenB.address)
  const pair = new Contract(pairAddress, JSON.stringify(ApePair.abi), provider).connect(wallet)

  const token0Address = (await pair.token0()).address
  const token0 = tokenA.address === token0Address ? tokenA : tokenB
  const token1 = tokenA.address === token0Address ? tokenB : tokenA

  return { factory, token0, token1, pair }
}
Example #19
Source File: sniper.ts    From pool-sniper with The Unlicense 6 votes vote down vote up
/**
   * Updates token and purchase details + sets up RPC
   * @param {string} tokenAddress of token to purchase
   * @param {string} factoryAddress of Uniswap V2 Factory
   * @param {string} rpcEndpoint for network
   * @param {string} privateKey of purchasing wallet
   * @param {string} purchaseAmount to swap with (input)
   * @param {string} gasPrice to pay
   * @param {number} slippage for trade execution
   * @param {boolean} testnet true if testnet
   */
  constructor(
    tokenAddress: string,
    factoryAddress: string,
    rpcEndpoint: string,
    privateKey: string,
    purchaseAmount: string,
    gasPrice: string,
    slippage: number,
    testnet: boolean
  ) {
    // Setup networking + wallet
    this.rpc = new providers.JsonRpcProvider(rpcEndpoint);
    this.wallet = new Wallet(privateKey, this.rpc);

    // Setup token details
    this.tokenAddress = utils.getAddress(tokenAddress); // Normalize address
    this.factory = new Contract(factoryAddress, ABI_UniswapV2Factory, this.rpc);
    this.purchaseAmount = purchaseAmount;
    this.gasPrice = utils.parseUnits(gasPrice, "gwei");
    this.slippage = slippage;
    this.testnet = testnet;
  }
Example #20
Source File: HelloWorld.test.ts    From bodhi.js with Apache License 2.0 6 votes vote down vote up
describe('HelloWorld', () => {
  let wallet: Signer;
  let instance: Contract;

  before(async () => {
    [wallet] = await provider.getWallets();
    instance = await deployContract(wallet, HelloWorld);
  });

  after(async () => {
    provider.api.disconnect();
  });

  it('returns the right value after the contract is deployed', async () => {
    console.log(instance.address);
    expect(await instance.helloWorld()).to.equal('Hello World!');
  });
});
Example #21
Source File: contracts.ts    From dxvote with GNU Affero General Public License v3.0 6 votes vote down vote up
export function getContract(
  address: string,
  ABI: any,
  library: providers.JsonRpcProvider,
  account?: string
): Contract {
  if (!isAddress(address) || address === constants.AddressZero) {
    return null;
  }

  return new Contract(
    address,
    ABI,
    getProviderOrSigner(library, account) as any
  );
}
Example #22
Source File: main.ts    From pawnft with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Impersonates three actors and provides connected contracts
 * @returns {Promise<Record<string, Contract>>} actor: connected contract
 */
async function impersonateBanks(): Promise<Record<string, Contract>> {
  // Snowfro.eth
  const SnowfroSigner = await impersonateSigner(ADDRESSES.SNOWFRO);
  const SnowfroBank: Contract = PawnBankContract.connect(SnowfroSigner);

  // Lender One
  const LenderOneSigner = await impersonateSigner(ADDRESSES.LENDER_ONE);
  const LenderOneBank: Contract = PawnBankContract.connect(LenderOneSigner);

  // Lender Two
  const LenderTwoSigner = await impersonateSigner(ADDRESSES.LENDER_TWO);
  const LenderTwoBank: Contract = PawnBankContract.connect(LenderTwoSigner);

  // Return available connected contracts
  return { SnowfroBank, LenderOneBank, LenderTwoBank };
}
Example #23
Source File: deploy.ts    From BarnBridge-Barn with Apache License 2.0 6 votes vote down vote up
export async function deployDiamond (diamondArtifactName: string, facets: Array<Contract>, owner: string): Promise<Contract> {
    const diamondCut = [];

    for (const facet of facets) {
        diamondCut.push([
            facet.address,
            diamond.FacetCutAction.Add,
            diamond.getSelectors(facet),
        ]);
    }

    const diamondFactory: ContractFactory = await ethers.getContractFactory(diamondArtifactName);
    const deployedDiamond: Contract = await diamondFactory.deploy(diamondCut, owner);
    await deployedDiamond.deployed();

    return deployedDiamond;
}
Example #24
Source File: useContract.ts    From dxvote with GNU Affero General Public License v3.0 6 votes vote down vote up
export default function useContract<T extends Contract>(
  contractId: string,
  abi: any,
  chainId?: number,
  withSignerIfPossible = true
): T | null {
  const provider = useJsonRpcProvider(chainId);
  const { chainId: walletChainId, account } = useWeb3React();

  return useMemo(() => {
    if (!provider || !contractId || !abi) return null;
    try {
      const signingAccount =
        !chainId || walletChainId === chainId ? account : null;
      const contract = getContract(
        contractId,
        abi,
        provider,
        withSignerIfPossible && signingAccount ? signingAccount : undefined
      );
      return contract;
    } catch (e) {
      console.error(e);
      return null;
    }
  }, [
    contractId,
    abi,
    provider,
    account,
    chainId,
    walletChainId,
    withSignerIfPossible,
  ]) as unknown as T;
}
Example #25
Source File: ERC1967UpgradeUpgradeable__factory.ts    From anchor-web-app with Apache License 2.0 6 votes vote down vote up
static connect(
    address: string,
    signerOrProvider: Signer | Provider,
  ): ERC1967UpgradeUpgradeable {
    return new Contract(
      address,
      _abi,
      signerOrProvider,
    ) as ERC1967UpgradeUpgradeable;
  }
Example #26
Source File: useToken.ts    From useDApp with MIT License 5 votes vote down vote up
/**
 * Returns name, symbol, decimals and token supply of a given token.
 * @param tokenAddress address of a token contract.
 * @returns a token info object (see {@link TokenInfo}) or `undefined` if all four methods don't exist on a token.
 * @public
 * @example
 * const DAI_ADDRESS = '0x6b175474e89094c44da98b954eedeac495271d0f'
 * const daiInfo = useToken(DAI_ADDRESS)
 *
 * return daiInfo ? (
 *   <>
 *     <p>Dai name: {daiInfo?.name}</p>
 *     <p>Dai symbol: {daiInfo?.symbol}</p>
 *     <p>Dai decimals: {daiInfo?.decimals}</p>
 *     <p>Dai totalSupply: {daiInfo?.totalSupply ? formatUnits(daiInfo?.totalSupply, daiInfo?.decimals) : ''}</p>
 *   </>
 * ) : null
 */
export function useToken(tokenAddress: string | Falsy): TokenInfo | undefined {
  const partialCall = tokenAddress && {
    contract: new Contract(tokenAddress, ERC20Interface),
    address: tokenAddress,
    args: [],
  }
  const args = ['name', 'symbol', 'decimals', 'totalSupply'].map(
    (method): Call | Falsy => partialCall && { ...partialCall, method }
  )
  const [name, symbol, decimals, totalSupply] = useCalls(args)

  if (!name && !symbol && !decimals && !totalSupply) {
    return undefined
  }

  return {
    name: name?.value[0] ?? '',
    symbol: symbol?.value[0] ?? '',
    decimals: decimals?.value[0],
    totalSupply: totalSupply?.value[0],
  }
}
Example #27
Source File: ApeFactory.spec.ts    From apeswap-swap-core with GNU General Public License v3.0 5 votes vote down vote up
describe('ApeFactory', () => {
  const provider = new MockProvider(
    { 
      ganacheOptions: {
        hardfork: 'istanbul',
        mnemonic: 'horn horn horn horn horn horn horn horn horn horn horn horn',
        gasLimit: 9999999
    }
  })
  const [wallet, other] = provider.getWallets()
  const loadFixture = createFixtureLoader([wallet], provider)

  let factory: Contract
  beforeEach(async () => {
    const fixture = await loadFixture(factoryFixture)
    factory = fixture.factory
  })

  it('feeTo, feeToSetter, allPairsLength', async () => {
    expect(await factory.feeTo()).to.eq(AddressZero)
    expect(await factory.feeToSetter()).to.eq(wallet.address)
    expect(await factory.allPairsLength()).to.eq(0)
  })

  async function createPair(tokens: [string, string]) {
    const bytecode = `0x${ApePair.bytecode}`
    const create2Address = getCreate2Address(factory.address, tokens, bytecode)
    await expect(factory.createPair(...tokens))
      .to.emit(factory, 'PairCreated')
      .withArgs(TEST_ADDRESSES[0], TEST_ADDRESSES[1], create2Address, BigNumber.from(1))

    await expect(factory.createPair(...tokens)).to.be.reverted // ApeSwap: PAIR_EXISTS
    await expect(factory.createPair(...tokens.slice().reverse())).to.be.reverted // ApeSwap: PAIR_EXISTS
    expect(await factory.getPair(...tokens)).to.eq(create2Address)
    expect(await factory.getPair(...tokens.slice().reverse())).to.eq(create2Address)
    expect(await factory.allPairs(0)).to.eq(create2Address)
    expect(await factory.allPairsLength()).to.eq(1)

    const pair = new Contract(create2Address, JSON.stringify(ApePair.abi), provider as any)
    expect(await pair.factory()).to.eq(factory.address)
    expect(await pair.token0()).to.eq(TEST_ADDRESSES[0])
    expect(await pair.token1()).to.eq(TEST_ADDRESSES[1])
  }

  it('createPair', async () => {
    await createPair(TEST_ADDRESSES)
  })

  it('createPair:reverse', async () => {
    await createPair(TEST_ADDRESSES.slice().reverse() as [string, string])
  })

  it('createPair:gas', async () => {
    const tx = await factory.createPair(...TEST_ADDRESSES)
    const receipt = await tx.wait()
    expect(receipt.gasUsed).to.eq(2505099)
  })

  it('setFeeTo', async () => {
    await expect(factory.connect(other).setFeeTo(other.address)).to.be.revertedWith('ApeSwap: FORBIDDEN')
    await factory.setFeeTo(wallet.address)
    expect(await factory.feeTo()).to.eq(wallet.address)
  })

  it('setFeeToSetter', async () => {
    await expect(factory.connect(other).setFeeToSetter(other.address)).to.be.revertedWith('ApeSwap: FORBIDDEN')
    await factory.setFeeToSetter(other.address)
    expect(await factory.feeToSetter()).to.eq(other.address)
    await expect(factory.setFeeToSetter(wallet.address)).to.be.revertedWith('ApeSwap: FORBIDDEN')
  })
})
Example #28
Source File: sniper.ts    From pool-sniper with The Unlicense 5 votes vote down vote up
// Factory contract
  factory: Contract;
Example #29
Source File: contractCallOutOfGasMock.ts    From useDApp with MIT License 5 votes vote down vote up
contractCallOutOfGasMock = ({
  transfer: transferOutOfGasMock,
  signer: true,
} as unknown) as Contract