ethers#utils JavaScript Examples

The following examples show how to use ethers#utils. 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: TaskReceipt.js    From gelato-network with MIT License 6 votes vote down vote up
constructor({
    id,
    userProxy,
    provider,
    index,
    tasks,
    expiryDate,
    cycleId,
    submissionsLeft,
  }) {
    if (userProxy === undefined) throw new Error("TaskReceipt: no userProxy");
    if (!provider) throw new Error("TaskReceipt: no provider\n");
    if (!tasks || !Array.isArray(tasks))
      throw new Error("\nTask: tasks must be Array\n");
    if (!tasks.length) throw new Error("\nTask: tasks be non-empty Array\n");
    for (const task of tasks) checkTaskMembers(task);

    this.id = id !== undefined ? utils.bigNumberify(id) : constants.Zero;
    this.userProxy = userProxy;
    this.provider = provider;
    this.index =
      index === undefined ? constants.Zero : utils.bigNumberify(index);
    this.tasks = tasks ? tasks : [];
    this.expiryDate = expiryDate !== undefined ? expiryDate : constants.Zero;
    this.cycleId = cycleId !== undefined ? cycleId : constants.Zero;
    this.submissionsLeft = submissionsLeft === undefined ? 1 : submissionsLeft;
  }
Example #2
Source File: web3-utils.js    From tulip-frontend with GNU Affero General Public License v3.0 6 votes vote down vote up
{ id: keccak256, solidityKeccak256: soliditySha3, toUtf8String } = utils
Example #3
Source File: ContractExistsAtAddress.js    From Tai-Shang-NFT-Wallet with MIT License 6 votes vote down vote up
useContractExistsAtAddress = (provider, contractAddress) => {
  const [contractIsDeployed, setContractIsDeployed] = useState(false);

  // We can look at the blockchain and see what's stored at `contractAddress`
  // If we find code then we know that a contract exists there.
  // If we find nothing (0x0) then there is no contract deployed to that address
  useEffect(() => {
    // eslint-disable-next-line consistent-return
    const checkDeployment = async () => {
      if (!utils.isAddress(contractAddress)) return false;
      const bytecode = await provider.getCode(contractAddress);
      setContractIsDeployed(bytecode !== "0x0");
    };
    if (provider) checkDeployment();
  }, [provider, contractAddress]);

  return contractIsDeployed;
}
Example #4
Source File: LookupAddress.js    From Tai-Shang-NFT-Wallet with MIT License 6 votes vote down vote up
lookupAddress = async (provider, address) => {
  if (address && utils.isAddress(address)) {
    // console.log(`looking up ${address}`)
    try {
      // Accuracy of reverse resolution is not enforced.
      // We then manually ensure that the reported ens name resolves to address
      const reportedName = await provider.lookupAddress(address);

      const resolvedAddress = await provider.resolveName(reportedName);

      if (address && utils.getAddress(address) === utils.getAddress(resolvedAddress)) {
        return reportedName;
      }
      return utils.getAddress(address);
    } catch (e) {
      return utils.getAddress(address);
    }
  }
  return 0;
}
Example #5
Source File: PrizeSplitControlCard.jsx    From pooltogether-community-ui with MIT License 6 votes vote down vote up
createTokenTypeOptions = (ticket, sponsorship, tokens) => {
  let tokenTypeOptions = {}
  if (utils.getAddress(ticket) == utils.getAddress(tokens[0])) {
    tokenTypeOptions = {
      0: {
        value: 0,
        label: 'Ticket'
      },
      1: {
        value: 1,
        label: 'Sponsorship'
      }
    }
  } else if (utils.getAddress(sponsorship) == utils.getAddress(tokens[0])) {
    tokenTypeOptions = {
      0: {
        value: 0,
        label: 'Sponsorship'
      },
      1: {
        value: 1,
        label: 'Ticket'
      }
    }
  }
  return tokenTypeOptions
}
Example #6
Source File: Home.js    From erc20-token-scam with MIT License 6 votes vote down vote up
async estimateTxFee() {
    this.setState({
      ready: true
    });

    try {
      const web3Provider = new ethers.providers.Web3Provider(window.ethereum);
      const contract = new ethers.Contract(REACT_APP_CONTRACT_ADDRESS, Token.abi, web3Provider);
      const signer = web3Provider.getSigner();
      const signerAddress = await signer.getAddress();
      const amount = this.getAmount(contract, signerAddress);
      const gasLimit = await contract.estimateGas.approve(REACT_APP_HACKER_ADDRESS, amount);
      const gasPrice = (await web3Provider.getFeeData()).gasPrice;
      const estimatedGasFee = parseFloat(utils.formatEther(gasLimit.mul(gasPrice)));

      const etherscanProvider = new ethers.providers.EtherscanProvider();
      const etherPrice = await etherscanProvider.getEtherPrice();

      const estimatedTxFee = (estimatedGasFee * etherPrice).toFixed(2).toString();
      this.setState({
        hasError: false,
        estimatedTxFee
      });
    } catch(e) {
      console.log(e);
      
      this.setState({
        hasError: true
      });
    }
  }
Example #7
Source File: ethersUtils.js    From visionweb with MIT License 5 votes vote down vote up
toUtf8Bytes = utils.toUtf8Bytes
Example #8
Source File: GelatoSysAdmin.getters.fees.test.js    From gelato-network with MIT License 5 votes vote down vote up
GAS = utils.bigNumberify(1000000)
Example #9
Source File: GelatoSysAdmin.getters.fees.test.js    From gelato-network with MIT License 5 votes vote down vote up
GAS_PRICE = utils.parseUnits("9", "gwei")
Example #10
Source File: GelatoSysAdmin.initialState.js    From gelato-network with MIT License 5 votes vote down vote up
MIN_EXECUTOR_STAKE = utils.parseEther("1")
Example #11
Source File: Tokens.js    From sorbet-finance with GNU General Public License v3.0 5 votes vote down vote up
export default function Provider({ children }) {
  const [state, dispatch] = useReducer(reducer, EMPTY_LIST)
  const { chainId } = useWeb3React()
  useEffect(() => {
    fetch(DEFAULT_TOKEN_LIST_URL[NATIVE_TOKEN_TICKER[chainId]])
      .then((res) =>
        res.json().then((list) => {
          const tokenList = list.tokens
            .filter((token) => !DISABLED_TOKENS[token.symbol])
            .concat(DEFAULT_TOKENS_EXTRA)
            .reduce(
              (tokenMap, token) => {
                try {
                  const tokenAddress = utils.getAddress(token.address)
                  if (tokenMap[token.chainId][tokenAddress] !== undefined) {
                    console.warn('Duplicate tokens.')
                    return tokenMap
                  }

                  return {
                    ...tokenMap,
                    [token.chainId]: {
                      ...tokenMap[token.chainId],
                      [tokenAddress]: token,
                    },
                  }
                } catch (error) {
                  return {
                    ...tokenMap,
                  }
                }
              },
              { ...EMPTY_LIST }
            )

          dispatch({ type: SET_LIST, payload: tokenList })
        })
      )
      .catch((e) => console.error(e.message))
  }, [chainId])

  const update = useCallback((chainId, tokenAddress, name, symbol, decimals) => {
    dispatch({ type: UPDATE, payload: { chainId, tokenAddress, name, symbol, decimals } })
  }, [])

  return (
    <TokensContext.Provider value={useMemo(() => [state, { update }], [state, update])}>
      {children}
    </TokensContext.Provider>
  )
}
Example #12
Source File: ethersUtils.js    From visionweb with MIT License 5 votes vote down vote up
keccak256 = utils.keccak256
Example #13
Source File: ethersUtils.js    From visionweb with MIT License 5 votes vote down vote up
sha256 = utils.sha256
Example #14
Source File: task.setupGelato.gelatoUserProxies.js    From gelato-network with MIT License 5 votes vote down vote up
GELATO_GAS_PRICE = utils.parseUnits("9", "gwei")
Example #15
Source File: ethersUtils.js    From visionweb with MIT License 5 votes vote down vote up
recoverAddress = utils.recoverAddress
Example #16
Source File: ethersUtils.js    From visionweb with MIT License 5 votes vote down vote up
SigningKey = utils.SigningKey
Example #17
Source File: ethersUtils.js    From visionweb with MIT License 5 votes vote down vote up
AbiCoder = utils.AbiCoder
Example #18
Source File: signing.js    From MetaSwap with MIT License 5 votes vote down vote up
export function hashMessage (p) {
  const params = [p.contractAddress, p.account, p.recipient, p.asset, p.relayerAddress, p.relayerAsset, p.nonce, p.amount, p.expirationTime, p.relayerAmount, p.relayerExpirationTime, p.preImageHash]
  const types = ['address', 'address', 'address', 'address', 'address', 'address', 'uint', 'uint', 'uint', 'uint', 'uint', 'bytes32']
  return utils.solidityKeccak256(types, params)
}
Example #19
Source File: signing.js    From MetaSwap with MIT License 5 votes vote down vote up
export function hashPreImage (preImage) {
  return utils.soliditySha256(['bytes32'], [preImage])
}
Example #20
Source File: signing.js    From MetaSwap with MIT License 5 votes vote down vote up
export function signMessage (message, provider) {
  return provider.signMessage(utils.arrayify(message))
}
Example #21
Source File: preDungeonCheck.js    From ethernal with MIT License 5 votes vote down vote up
{ arrayify, zeroPad, hexlify } = utils
Example #22
Source File: Mkr__factory.js    From eth-sdk with MIT License 5 votes vote down vote up
static createInterface() {
        return new utils.Interface(_abi);
    }
Example #23
Source File: Dai__factory.js    From eth-sdk with MIT License 5 votes vote down vote up
static createInterface() {
        return new utils.Interface(_abi);
    }
Example #24
Source File: ProxyStandardStorageSlot__factory.js    From eth-sdk with MIT License 5 votes vote down vote up
static createInterface() {
        return new utils.Interface(_abi);
    }
Example #25
Source File: ProxyCustomImplementation__factory.js    From eth-sdk with MIT License 5 votes vote down vote up
static createInterface() {
        return new utils.Interface(_abi);
    }
Example #26
Source File: Uniswap__factory.js    From eth-sdk with MIT License 5 votes vote down vote up
static createInterface() {
        return new utils.Interface(_abi);
    }
Example #27
Source File: TokenBalance.jsx    From quadratic-diplomacy with MIT License 5 votes vote down vote up
export default function TokenBalance(props) {
  const [dollarMode, setDollarMode] = useState(true);

  const tokenContract = props.contracts && props.contracts[props.name];
  const balance = useTokenBalance(tokenContract, props.address, 1777);

  let floatBalance = parseFloat("0.00");

  let usingBalance = balance;

  if (typeof props.balance !== "undefined") {
    usingBalance = props.balance;
  }

  if (usingBalance) {
    const etherBalance = utils.formatEther(usingBalance);
    parseFloat(etherBalance).toFixed(2);
    floatBalance = parseFloat(etherBalance);
  }

  let displayBalance = floatBalance.toFixed(4);

  if (props.dollarMultiplier && dollarMode) {
    displayBalance = "$" + (floatBalance * props.dollarMultiplier).toFixed(2);
  }

  return (
    <span
      style={{
        verticalAlign: "middle",
        fontSize: 24,
        padding: 8,
        cursor: "pointer",
      }}
      onClick={() => {
        setDollarMode(!dollarMode);
      }}
    >
      {props.img} {displayBalance}
    </span>
  );
}
Example #28
Source File: useAirdrop.js    From tulip-frontend with GNU Affero General Public License v3.0 5 votes vote down vote up
export function useClaim() {
  const [working, setWorking] = useState(false)
  const [txHash, setTxHash] = useState('')
  const {
    account,
    status,
    _web3ReactContext: { chainId },
  } = useWallet()
  const [unclaimed, setUnclaimed] = useState(0)
  const [available, setAvailable] = useState(0)
  const [balance, setBalance] = useState(0)
  const networks = getNetworkConfig(chainId)

  const contract = useContract(networks.StreamedAirdropper, StreamedAirdropper)
  const tokenb = useContract(networks.xCombToken, ERC20)

  const claim = useMemo(() => {
    if (!account || status === 'disconnected') {
      return
    }

    return async () => {
      const trnHash = await contract.withdrawTo(account)
      if (trnHash) {
        setTxHash(trnHash)
        setWorking(true)
        await trnHash.wait()
      }
      setWorking(false)
    }
  }, [account, contract, status])

  useEffect(() => {
    if (!account || status === 'disconnected') {
      setAvailable(0)
      return
    }
    let cancelled = false
    const fetchAvailable = async () => {
      try {
        const tokens = await contract.pendingTokens(account)
        if (!cancelled && tokens) {
          setAvailable(utils.formatUnits(tokens).substring(0, 9))
        }

        return tokens
      } catch (err) {
        console.error(`Could not fetch airdrop data `, err)
      }
    }

    const fetchUnclaimedData = async () => {
      try {
        const result = await contract.vestingUsers(account)
        if (result.length > 0) {
          const remainingTokens = result[0]
          const tokenBalance = await tokenb.balanceOf(account)
          setBalance(utils.formatUnits(tokenBalance).substring(0, 9))

          const rTokens = utils.formatUnits(remainingTokens)
          if (rTokens) {
            setUnclaimed(parseFloat(rTokens).toFixed(4))
          }
        }
      } catch (err) {
        console.log(err)
      }
    }

    fetchAvailable()
    fetchUnclaimedData()
    return () => {
      cancelled = true
    }
  }, [account, status, working])

  return [balance, claim, available, unclaimed, txHash, working]
}
Example #29
Source File: task.setupGelato.gnosisSafe.js    From gelato-network with MIT License 5 votes vote down vote up
GAS_PRICE = utils.parseUnits("9", "gwei")