ethers#ethers JavaScript Examples

The following examples show how to use ethers#ethers. 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.js    From dshop with MIT License 7 votes vote down vote up
getContracts = memoize(async function (provider) {
  const factory = new ethers.Contract(Addresses.factory, abi(factC), provider)
  const dai = new ethers.Contract(Addresses.dai, abi(ercBurnable), provider)
  const ogn = new ethers.Contract(Addresses.ogn, abi(ercBurnable), provider)
  const chico = new ethers.Contract(Addresses.chico, abi(ercFixed), provider)
  const weth = new ethers.Contract(Addresses.weth, abi(ercFixed), provider)
  const pairAddress = await factory.getPair(weth.address, chico.address)
  const pair = new ethers.Contract(pairAddress, abi(pairC), provider)
  const pairErc20 = new ethers.Contract(pairAddress, abi(pairEC), provider)
  const router = new ethers.Contract(Addresses.router, abi(routerC), provider)
  const erc20 = Contract(ercFixed)
  window.contracts = {
    factory,
    pair,
    pairErc20,
    router,
    dai,
    chico,
    erc20,
    weth,
    ogn
  }
  return { factory, pair, pairErc20, router, dai, chico, weth, ogn }
})
Example #2
Source File: useCreateDeposit.js    From tulip-frontend with GNU Affero General Public License v3.0 6 votes vote down vote up
export function useCreateDeposit(
  tokenAddress,
  amount,
  unlockTime = 0,
  referrer = '0x0000000000000000000000000000000000000000',
  chainId
) {
  // amount = amount !== '' ? ethers.utils.parseEther('0.00000426') : amount
  amount = ethers.utils.parseEther(amount)
  const network = getNetworkConfig(chainId)
  const contract = useContract(network.honeyfarm, honeyFarm)
  return () => {
    return new Promise((resolve, reject) => {
      contract
        .createDeposit(tokenAddress, amount, unlockTime, referrer)
        .then(x => {
          resolve(x)
        })
        .catch(err => reject(serializeError(err)))
    })
  }
}
Example #3
Source File: unstoppable.js    From dshop with MIT License 6 votes vote down vote up
export async function getResolver(providerOrSigner, token) {
  const registry = getRegistry(providerOrSigner)
  const resolverAddress = await registry.resolverOf(token)
  return new ethers.Contract(
    resolverAddress,
    CRYPTO_RESOLVER_ABI,
    providerOrSigner
  )
}
Example #4
Source File: index.jsx    From uniswap-v1-frontend with GNU General Public License v3.0 6 votes vote down vote up
function calculateSlippageBounds(value, token = false, tokenAllowedSlippage, allowedSlippage) {
  if (value) {
    const offset = value.mul(token ? tokenAllowedSlippage : allowedSlippage).div(ethers.utils.bigNumberify(10000))
    const minimum = value.sub(offset)
    const maximum = value.add(offset)
    return {
      minimum: minimum.lt(ethers.constants.Zero) ? ethers.constants.Zero : minimum,
      maximum: maximum.gt(ethers.constants.MaxUint256) ? ethers.constants.MaxUint256 : maximum
    }
  } else {
    return {}
  }
}
Example #5
Source File: utils.js    From dshop with MIT License 6 votes vote down vote up
Contract = (name) =>
  new ethers.ContractFactory(
    abis.contracts[name].abi,
    abis.contracts[name].bytecode
  )
Example #6
Source File: index.jsx    From uniswap-v1-frontend with GNU General Public License v3.0 6 votes vote down vote up
function getExchangeRate(inputValue, inputDecimals, outputValue, outputDecimals, invert = false) {
  try {
    if (
      inputValue &&
      (inputDecimals || inputDecimals === 0) &&
      outputValue &&
      (outputDecimals || outputDecimals === 0)
    ) {
      const factor = ethers.utils.bigNumberify(10).pow(ethers.utils.bigNumberify(18))

      if (invert) {
        return inputValue
          .mul(factor)
          .mul(ethers.utils.bigNumberify(10).pow(ethers.utils.bigNumberify(outputDecimals)))
          .div(ethers.utils.bigNumberify(10).pow(ethers.utils.bigNumberify(inputDecimals)))
          .div(outputValue)
      } else {
        return outputValue
          .mul(factor)
          .mul(ethers.utils.bigNumberify(10).pow(ethers.utils.bigNumberify(inputDecimals)))
          .div(ethers.utils.bigNumberify(10).pow(ethers.utils.bigNumberify(outputDecimals)))
          .div(inputValue)
      }
    }
  } catch {}
}
Example #7
Source File: utils.js    From dshop with MIT License 6 votes vote down vote up
// const provider = new ethers.providers.JsonRpcProvider()
// const provider = new ethers.providers.Web3Provider(
//   window.ethereum,
//   defaultChainId
// )

// async function setup() {
//   const accounts = await provider.listAccounts()
//   const signer = provider.getSigner(accounts[0])

//   window.pair = pair.connect(signer)
//   window.pairErc20 = pairErc20.connect(signer)
//   window.router = router.connect(signer)
//   window.dai = dai.connect(signer)
//   window.chico = chico.connect(signer)

//   // const quote = await router.getAmountsIn(ethers.utils.parseEther('1'), [
//   //   dai.address,
//   //   chico.address
//   // ])

//   // console.log(ethers.utils.formatEther(quote[0]))

//   // const reserves = await pair.getReserves()
//   // console.log(ethers.utils.formatEther(reserves[0]))
//   // console.log(ethers.utils.formatEther(reserves[1]))
// }

// setup()

/* eslint-disable */

async function goMeta() {
  ethers = _ethers
  provider = new ethers.providers.Web3Provider(window.ethereum)
  log = console.log
  accounts = await provider.listAccounts()
  signer = provider.getSigner(accounts[0])

  erc20 = _ethers.ContractFactory.fromSolidity(
    abis.contracts['ERC20FixedSupplyBurnable'],
    signer
  )

  factory = new _ethers.Contract(
    '0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f',
    abis.contracts['contracts/UniswapV2Factory.sol:UniswapV2Factory'].abi,
    signer
  )
  router = new _ethers.Contract(
    '0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D',
    abis.contracts['v2router'].abi,
    signer
  )

  await router.addLiquidityETH(
    dai.address,
    _ethers.utils.parseEther('400'),
    _ethers.utils.parseEther('400'),
    _ethers.utils.parseEther('0'),
    accounts[0],
    Math.round(new Date() / 1000) + 60 * 60 * 24,
    { value: _ethers.utils.parseEther('0.5'), gasLimit: '4000000' }
  )

  await router.addLiquidityETH(
    chico.address,
    _ethers.utils.parseEther('50'),
    _ethers.utils.parseEther('50'),
    _ethers.utils.parseEther('0'),
    accounts[0],
    Math.round(new Date() / 1000) + 60 * 60 * 24,
    { value: _ethers.utils.parseEther('0.1'), gasLimit: '4000000' }
  )
}
Example #8
Source File: AddLiquidity.js    From uniswap-v1-frontend with GNU General Public License v3.0 6 votes vote down vote up
function calculateSlippageBounds(value) {
  if (value) {
    const offset = value.mul(ALLOWED_SLIPPAGE).div(ethers.utils.bigNumberify(10000))
    const minimum = value.sub(offset)
    const maximum = value.add(offset)
    return {
      minimum: minimum.lt(ethers.constants.Zero) ? ethers.constants.Zero : minimum,
      maximum: maximum.gt(ethers.constants.MaxUint256) ? ethers.constants.MaxUint256 : maximum
    }
  } else {
    return {}
  }
}
Example #9
Source File: Web3Modal.js    From dshop with MIT License 6 votes vote down vote up
validate = (state) => {
  const newState = {}

  if (!state.web3Pk) {
    newState.web3PkError = fbt(
      'Private key is required',
      'admin.settings.payments.web3.pkError'
    )
  } else {
    try {
      new ethers.Wallet('0x' + state.web3Pk)
    } catch (err) {
      console.error(err)
      newState.web3PkError = fbt(
        'Invalid private key',
        'admin.settings.payments.web3.pkInvalidError'
      )
    }
  }

  const valid = Object.keys(newState).every((f) => !f.endsWith('Error'))

  return {
    valid,
    newState: {
      web3Pk: '0x' + state.web3Pk,
      ...newState
    }
  }
}
Example #10
Source File: AddLiquidity.js    From uniswap-v1-frontend with GNU General Public License v3.0 6 votes vote down vote up
function getExchangeRate(inputValue, inputDecimals, outputValue, outputDecimals, invert = false) {
  try {
    if (
      inputValue &&
      (inputDecimals || inputDecimals === 0) &&
      outputValue &&
      (outputDecimals || outputDecimals === 0)
    ) {
      const factor = ethers.utils.bigNumberify(10).pow(ethers.utils.bigNumberify(18))

      if (invert) {
        return inputValue
          .mul(factor)
          .mul(ethers.utils.bigNumberify(10).pow(ethers.utils.bigNumberify(outputDecimals)))
          .div(ethers.utils.bigNumberify(10).pow(ethers.utils.bigNumberify(inputDecimals)))
          .div(outputValue)
      } else {
        return outputValue
          .mul(factor)
          .mul(ethers.utils.bigNumberify(10).pow(ethers.utils.bigNumberify(inputDecimals)))
          .div(ethers.utils.bigNumberify(10).pow(ethers.utils.bigNumberify(outputDecimals)))
          .div(inputValue)
      }
    }
  } catch {}
}
Example #11
Source File: List.js    From dshop with MIT License 6 votes vote down vote up
validate = (state) => {
  const newState = {}

  if (!state.disableCryptoPayments) {
    if (!state.walletAddress) {
      newState.walletAddressError = fbt(
        'Wallet address is required',
        'admin.settings.payments.List.walletAddressRequired'
      )
    } else if (!ethers.utils.isAddress(state.walletAddress)) {
      newState.walletAddressError = fbt(
        'Invalid wallet address',
        'admin.settings.payments.List.invalidWalletAddressError'
      )
    }
  }

  const valid = Object.keys(newState).every((f) => !f.endsWith('Error'))

  return {
    valid,
    newState: {
      ...pickBy(state, (v, k) => !k.endsWith('Error')),
      ...newState
    }
  }
}
Example #12
Source File: Dapp.js    From hardhat-boilerplate with MIT License 6 votes vote down vote up
async _initializeEthers() {
    // We first initialize ethers by creating a provider using window.ethereum
    this._provider = new ethers.providers.Web3Provider(window.ethereum);

    // Then, we initialize the contract using that provider and the token's
    // artifact. You can do this same thing with your contracts.
    this._token = new ethers.Contract(
      contractAddress.Token,
      TokenArtifact.abi,
      this._provider.getSigner(0)
    );
  }
Example #13
Source File: RemoveLiquidity.js    From uniswap-v1-frontend with GNU General Public License v3.0 6 votes vote down vote up
function getExchangeRate(inputValue, inputDecimals, outputValue, outputDecimals, invert = false) {
  try {
    if (
      inputValue &&
      (inputDecimals || inputDecimals === 0) &&
      outputValue &&
      (outputDecimals || outputDecimals === 0)
    ) {
      const factor = ethers.utils.bigNumberify(10).pow(ethers.utils.bigNumberify(18))

      if (invert) {
        return inputValue
          .mul(factor)
          .mul(ethers.utils.bigNumberify(10).pow(ethers.utils.bigNumberify(outputDecimals)))
          .div(ethers.utils.bigNumberify(10).pow(ethers.utils.bigNumberify(inputDecimals)))
          .div(outputValue)
      } else {
        return outputValue
          .mul(factor)
          .mul(ethers.utils.bigNumberify(10).pow(ethers.utils.bigNumberify(inputDecimals)))
          .div(ethers.utils.bigNumberify(10).pow(ethers.utils.bigNumberify(outputDecimals)))
          .div(inputValue)
      }
    }
  } catch {}
}
Example #14
Source File: sc.interaction.js    From Artion-Client with GNU General Public License v3.0 6 votes vote down vote up
useContract = () => {
  const { chainId } = useWeb3React();

  const loadContract = useCallback(
    async (address, abi) => {
      const provider = new ethers.providers.Web3Provider(window.ethereum);
      const signer = provider.getSigner();
      return new ethers.Contract(address, abi, signer);
    },
    [chainId]
  );

  const getAccountBalance = useCallback(
    async address => {
      const provider = new ethers.providers.Web3Provider(window.ethereum);
      let balance = await provider.getBalance(address);
      balance = ethers.utils.formatEther(balance);
      return balance;
    },
    [chainId]
  );

  return { loadContract, getAccountBalance };
}
Example #15
Source File: index.js    From uniswap-v1-frontend with GNU General Public License v3.0 6 votes vote down vote up
// get token name
export async function getTokenName(tokenAddress, library) {
  if (!isAddress(tokenAddress)) {
    throw Error(`Invalid 'tokenAddress' parameter '${tokenAddress}'.`)
  }

  return getContract(tokenAddress, ERC20_ABI, library)
    .name()
    .catch(() =>
      getContract(tokenAddress, ERC20_BYTES32_ABI, library)
        .name()
        .then(bytes32 => ethers.utils.parseBytes32String(bytes32))
    )
    .catch(error => {
      error.code = ERROR_CODES.TOKEN_SYMBOL
      throw error
    })
}
Example #16
Source File: index.js    From acy-dex-interface with MIT License 6 votes vote down vote up
export function usePositionsForOrders(chainId, library, orders) {
  const key = orders ? orders.map(order => getOrderKey(order) + '____') : null
  const { data: positions = {} } = useSWR(key, async () => {
    const provider = getProvider(library, chainId)
    const vaultAddress = getContract(chainId, "Vault")
    const contract = new ethers.Contract(vaultAddress, Vault.abi, provider)
    const data = await Promise.all(orders.map(async order => {
      try {
        const position = await contract.getPosition(order.account, order.collateralToken, order.indexToken, order.isLong)
        if (position[0].eq(0)) {
          return [null, order]
        }
        return [position, order]
      } catch (ex) {
        console.error(ex)
      }
    }))
    return data.reduce((memo, [position, order]) => {
      memo[getOrderKey(order)] = position
      return memo
    }, {})
  })

  return positions
}
Example #17
Source File: Transaction.js    From web3-wallets with MIT License 6 votes vote down vote up
static bigNumberify(value, blockchain) {
    if (typeof value === 'number') {
      return ethers.utils.parseUnits(value.toString(), CONSTANTS[blockchain].DECIMALS)
    } else if (value && value.toString) {
      return ethers.BigNumber.from(value.toString())
    } else {
      return value
    }
  }
Example #18
Source File: _Perpetual.js    From acy-dex-interface with MIT License 6 votes vote down vote up
export async function approvePlugin(chainId, pluginAddress, { library, pendingTxns, setPendingTxns }) {
  const contract = new ethers.Contract(routerAddress, Router.abi, library.getSigner())
  return callContract(chainId, contract, 'approvePlugin', [pluginAddress], {
    sentMsg: 'Enable orders sent',
    failMsg: 'Enable orders failed',
    pendingTxns,
    setPendingTxns
  })
}
Example #19
Source File: testRouting.js    From web3-exchanges with MIT License 6 votes vote down vote up
function expectRoute({
  blockchain,
  route,
  tokenIn,
  tokenOut,
  path,
  amountOutBN,
  amountInBN,
  amountOutMinBN,
  amountInMaxBN,
  fromAddress,
  toAddress,
  exchange,
  transaction
}) {
  expect(route.tokenIn).toEqual(ethers.utils.getAddress(tokenIn))
  expect(route.tokenOut).toEqual(ethers.utils.getAddress(tokenOut))
  expect(route.path).toEqual(path.map((address)=>ethers.utils.getAddress(address)))
  if(typeof amountOutBN !== 'undefined') { expect(route.amountOut).toEqual(amountOutBN.toString()) }
  if(typeof amountInBN !== 'undefined') { expect(route.amountIn).toEqual(amountInBN.toString()) }
  if(typeof amountOutMinBN !== 'undefined') { expect(route.amountOutMin).toEqual(amountOutMinBN.toString()) }
  if(typeof amountInMaxBN !== 'undefined') { expect(route.amountInMax).toEqual(amountInMaxBN.toString()) }
  expect(route.fromAddress).toEqual(fromAddress)
  expect(route.toAddress).toEqual(toAddress)
  expect(route.exchange).toEqual(exchange)
  expect(route.transaction.blockchain).toEqual(blockchain)
  expect(route.transaction.to).toEqual(transaction.to)
  expect(route.transaction.api).toEqual(transaction.api)
  expect(route.transaction.method).toEqual(transaction.method)
  expect(route.transaction.params.deadline).toBeDefined()
  expect(route.transaction.value).toEqual(transaction.value?.toString())
  expect(
    Object.keys(transaction.params).every((key)=>{
      return JSON.stringify(normalize(route.transaction.params[key])) == JSON.stringify(normalize(transaction.params[key]))
    })
  ).toEqual(true)
}
Example #20
Source File: _Helpers.js    From acy-dex-interface with MIT License 6 votes vote down vote up
export function useENS(address) {
  const [ensName, setENSName] = useState();

  useEffect(() => {
    async function resolveENS() {
      if (address) {
        const provider = await ethers.providers.getDefaultProvider();
        const name = await provider.lookupAddress(address.toLowerCase());
        if (name) setENSName(name);
      }
    }
    resolveENS();
  }, [address]);

  return { ensName };
}
Example #21
Source File: path.js    From web3-exchanges with MIT License 6 votes vote down vote up
minReserveRequirements = ({ reserves, min, token, token0, token1, decimals }) => {
  if(token0.toLowerCase() == token.toLowerCase()) {
    return reserves[0].gte(ethers.utils.parseUnits(min.toString(), decimals))
  } else if (token1.toLowerCase() == token.toLowerCase()) {
    return reserves[1].gte(ethers.utils.parseUnits(min.toString(), decimals))
  } else {
    return false
  }
}
Example #22
Source File: perpetual_finance.route.js    From gateway-api with Apache License 2.0 6 votes vote down vote up
router.post('/receipt', async (req, res) => {
  /*
      POST: /receipt
      x-www-form-urlencoded: {
        txHash:{{txHash}}
      }
  */
  const initTime = Date.now();
  const paramData = getParamData(req.body);
  const txHash = paramData.txHash;
  const txReceipt = await perpFi.provider.getTransactionReceipt(txHash);
  const receipt = {};
  const confirmed = txReceipt && txReceipt.blockNumber ? true : false;
  if (txReceipt !== null) {
    receipt.gasUsed = ethers.utils.formatEther(txReceipt.gasUsed);
    receipt.blockNumber = txReceipt.blockNumber;
    receipt.confirmations = txReceipt.confirmations;
    receipt.status = txReceipt.status;
  }
  logger.info(`eth.route - Get TX Receipt: ${txHash}`, {
    message: JSON.stringify(receipt),
  });
  res.status(200).json({
    network: perpFi.network,
    timestamp: initTime,
    latency: latency(initTime, Date.now()),
    txHash: txHash,
    confirmed: confirmed,
    receipt: receipt,
  });
  return txReceipt;
});
Example #23
Source File: _Helpers.js    From acy-dex-interface with MIT License 6 votes vote down vote up
fetcher = (library, contractInfo, additionalArgs) => (...args) => {
  // eslint-disable-next-line
  const [id, chainId, arg0, arg1, ...params] = args;
  const provider = getProvider(library, chainId);

  const method = ethers.utils.isAddress(arg0) ? arg1 : arg0;

  function onError(e) {
    console.error(contractInfo.contractName, method, e);
  }

  if (ethers.utils.isAddress(arg0)) {
    const address = arg0;
    const contract = new ethers.Contract(address, contractInfo.abi, provider);

    try {
      if (additionalArgs) {
        return contract[method](...params.concat(additionalArgs)).catch(
          onError
        );
      }
      return contract[method](...params).catch(onError);
    } catch (e) {
      onError(e);
    }
  }

  if (!library) {
    return;
  }

  return library[method](arg1, ...params).catch(onError);
}
Example #24
Source File: hooks.js    From semaphore_auth with MIT License 6 votes vote down vote up
useProofOfBurn = () => {
  const { library, active } = useWeb3React()

  if (active) {
    return new ethers.Contract(
      proofOfBurnAddress,
      ProofOfBurnABI,
      library.getSigner()
    )
  } else {
    return null
  }
}
Example #25
Source File: ethereumFunctions.js    From Alternative-Uniswap-Interface with GNU General Public License v3.0 6 votes vote down vote up
//This function returns the conversion rate between two token addresses
//    `address1` - An Ethereum address of the token to swaped from (either a token or AUT)
//    `address2` - An Ethereum address of the token to swaped to (either a token or AUT)
//    `amountIn` - Amount of the token at address 1 to be swaped from
//    `routerContract` - The router contract to carry out this swap
export async function getAmountOut(
  address1,
  address2,
  amountIn,
  routerContract,
  signer
) {
  try {
    const token1 = new Contract(address1, ERC20.abi, signer);
    const token1Decimals = await getDecimals(token1);

    const token2 = new Contract(address2, ERC20.abi, signer);
    const token2Decimals = await getDecimals(token2);

    const values_out = await routerContract.getAmountsOut(
      ethers.utils.parseUnits(String(amountIn), token1Decimals),
      [address1, address2]
    );
    const amount_out = values_out[1]*10**(-token2Decimals);
    console.log('amount out: ', amount_out)
    return Number(amount_out);
  } catch {
    return false;
  }
}
Example #26
Source File: index.js    From acy-dex-interface with MIT License 6 votes vote down vote up
formatAmount = (amount, tokenDecimals, displayDecimals, useCommas, defaultValue) => {
  if (!defaultValue) {
    defaultValue = '...';
  }
  if (amount === undefined || amount.toString().length === 0) {
    return defaultValue;
  }
  if (displayDecimals === undefined) {
    displayDecimals = 4;
  }
  let amountStr = ethers.utils.formatUnits(amount, tokenDecimals);
  amountStr = limitDecimals(amountStr, displayDecimals);
  if (displayDecimals !== 0) {
    amountStr = padDecimals(amountStr, displayDecimals);
  }
  if (useCommas) {
    return numberWithCommas(amountStr);
  }
  return amountStr;
}
Example #27
Source File: unstoppable.js    From dshop with MIT License 5 votes vote down vote up
export function namehash(name) {
  return ethers.utils.namehash(name)
}
Example #28
Source File: wallet.js    From Artion-Client with GNU General Public License v3.0 5 votes vote down vote up
checkBalance = async address => {
  const provider = new ethers.providers.Web3Provider(window.ethereum);
  let balance = await provider.getBalance(address);
  balance = ethers.utils.formatEther(balance);
  return balance;
}
Example #29
Source File: Create.jsx    From Organizations-Interface with BSD 2-Clause "Simplified" License 5 votes vote down vote up
abi = new ethers.utils.AbiCoder()