@ethersproject/address#getAddress TypeScript Examples

The following examples show how to use @ethersproject/address#getAddress. 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 QuickSwap-sdk with MIT License 7 votes vote down vote up
// warns if addresses are not checksummed
export function validateAndParseAddress(address: string): string {
  try {
    const checksummedAddress = getAddress(address)
    warning(address === checksummedAddress, `${address} is not checksummed.`)
    return checksummedAddress
  } catch (error) {
    invariant(false, `${address} is not a valid address.`)
  }
}
Example #2
Source File: utils.ts    From pancake-swap-sdk with MIT License 7 votes vote down vote up
// warns if addresses are not checksummed
export function validateAndParseAddress(address: string): string {
  try {
    const checksummedAddress = getAddress(address)
    warning(address === checksummedAddress, `${address} is not checksummed.`)
    return checksummedAddress
  } catch (error) {
    invariant(false, `${address} is not a valid address.`)
  }
}
Example #3
Source File: creation.ts    From safe-tasks with GNU Lesser General Public License v3.0 6 votes vote down vote up
task("create", "Create a Safe")
    .addFlag("l2", "Should use version of the Safe contract that is more event heave")
    .addFlag("buildOnly", "Indicate whether this transaction should only be logged and not submitted on-chain")
    .addParam("signers", "Comma separated list of signer addresses (dafault is the address of linked account)", "", types.string, true)
    .addParam("threshold", "Threshold that should be used", 1, types.int, true)
    .addParam("fallback", "Fallback handler address", AddressZero, types.string, true)
    .addParam("nonce", "Nonce used with factory", new Date().getTime(), types.int, true)
    .addParam("singleton", "Set to overwrite which singleton address to use", "", types.string, true)
    .addParam("factory", "Set to overwrite which factory address to use", "", types.string, true)
    .setAction(async (taskArgs, hre) => {
        const singleton = taskArgs.l2 ? await safeL2Singleton(hre, taskArgs.singleton) : await safeSingleton(hre, taskArgs.singleton)
        const factory = await proxyFactory(hre, taskArgs.factory)
        const signers: string[] = taskArgs.signers ? parseSigners(taskArgs.signers) : [(await hre.getNamedAccounts()).deployer]
        const fallbackHandler = getAddress(taskArgs.fallback)
        const setupData = singleton.interface.encodeFunctionData(
            "setup",
            [signers, taskArgs.threshold, AddressZero, "0x", fallbackHandler, AddressZero, 0, AddressZero]
        )
        const predictedAddress = await calculateProxyAddress(factory, singleton.address, setupData, taskArgs.nonce)
        console.log(`Deploy Safe to ${predictedAddress}`)
        console.log(`Singleton: ${singleton.address}`)
        console.log(`Setup data: ${setupData}`)
        console.log(`Nonce: ${taskArgs.nonce}`)
        console.log(`To (factory): ${factory.address}`)
        console.log(`Data: ${factory.interface.encodeFunctionData("createProxyWithNonce", [singleton.address, setupData, taskArgs.nonce])}`)
        if (!taskArgs.buildOnly)
            await factory.createProxyWithNonce(singleton.address, setupData, taskArgs.nonce).then((tx: any) => tx.wait())
        // TODO verify deployment
    });
Example #4
Source File: Signer.ts    From bodhi.js with Apache License 2.0 6 votes vote down vote up
/**
   * Get the signer's EVM address, and claim an EVM address if it has not claimed one.
   * @returns A promise resolving to the EVM address of the signer's substrate
   * address
   */
  async getAddress(): Promise<string> {
    const address = await this.queryEvmAddress();
    if (address) {
      return address;
    } else {
      // default address
      return this.computeDefaultEvmAddress();
    }
  }
Example #5
Source File: data.ts    From hypertext with GNU General Public License v3.0 6 votes vote down vote up
// eslint-disable-next-line @typescript-eslint/no-explicit-any
export function useReserves(tokenA?: Token, tokenB?: Token): responseInterface<Pair | null, any> {
  const invalid = !!tokenA && !!tokenB && tokenA.equals(tokenB)
  const [token0, token1] =
    !!tokenA && !!tokenB && !invalid ? (tokenA.sortsBefore(tokenB) ? [tokenA, tokenB] : [tokenB, tokenA]) : []
  const pairAddress = !!token0 && !!token1 ? Pair.getAddress(token0, token1) : undefined
  const contract = useContract(pairAddress, IUniswapV2Pair.abi)
  const result = useSWR(
    token0 && pairAddress && contract && token1 ? [token0.chainId, pairAddress, DataType.Reserves] : null,
    getReserves(contract as Contract, token0 as Token, token1 as Token)
  )
  useKeepSWRDataLiveAsBlocksArrive(result.mutate)
  return result
}
Example #6
Source File: index.ts    From interface-v2 with GNU General Public License v3.0 6 votes vote down vote up
export function returnTokenFromKey(key: string): Token {
  if (key === 'MATIC') return GlobalValue.tokens.MATIC;
  const tokenIndex = Object.keys(tokenData).findIndex(
    (tokenKey) => tokenKey === key,
  );
  const token = Object.values(tokenData)[tokenIndex];
  return new Token(
    ChainId.MATIC,
    getAddress(token.address),
    token.decimals,
    token.symbol,
    token.name,
  );
}
Example #7
Source File: cleanupTokens.ts    From default-token-list with MIT License 6 votes vote down vote up
cleanupTokens = async (network: ICeloNetwork) => {
  const file = `${__dirname}/../src/${network}.tokens.json`;

  const tokens = getNetworkTokens(network)
    .slice()
    .sort((a, b) =>
      a.address.toLowerCase().localeCompare(b.address.toLowerCase())
    );

  await fs.writeFile(
    file,
    JSON.stringify(
      tokens.map((tok) => ({ ...tok, address: getAddress(tok.address) }))
    )
  );
}
Example #8
Source File: tradingPairsGraph.ts    From uniswap-trading-example with MIT License 6 votes vote down vote up
public async createTradingGraph(): Promise<void> {
    const allPairsLength = +(await this.uniswapFactory.methods
      .allPairsLength()
      .call());
    console.log(
      `There are ${allPairsLength} tradable pairs, but we will only get the first 1000 for the sake of time. Can you cache the results to speed things up next time?`,
    );
    const allPairs = await runConcurrently(
      [...range(0, 1000)],
      this.fetchTokenPairNoThrow.bind(this),
      { maxConcurrency: 16 },
    );
    allPairs.forEach((pair) => {
      if (pair) {
        this.uniswapTradingGraph.setEdge(
          getAddress(pair.token0),
          getAddress(pair.token1),
          getAddress(pair.tokenPairAddress),
        );
      }
    });
    console.log("You can choose from the following assets:");
    console.log(this.uniswapTradingGraph.nodes());
  }
Example #9
Source File: index.ts    From limit-orders-lib with GNU General Public License v3.0 6 votes vote down vote up
// returns the checksummed address if the address is valid, otherwise returns false
// eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types
export function isAddress(value: any): string | false {
  try {
    return getAddress(value);
  } catch {
    return false;
  }
}
Example #10
Source File: checksum.ts    From pancake-toolkit with GNU General Public License v3.0 6 votes vote down vote up
checksumAddresses = (listName: string): void => {
  let badChecksumCount = 0;
  const listToChecksum = lists[listName];
  const updatedList = listToChecksum.reduce((tokenList, token) => {
    const checksummedAddress = getAddress(token.address);
    if (checksummedAddress !== token.address) {
      badChecksumCount += 1;
      const updatedToken = { ...token, address: checksummedAddress };
      return [...tokenList, updatedToken];
    }
    return [...tokenList, token];
  }, []);

  if (badChecksumCount > 0) {
    console.info(`Found and fixed ${badChecksumCount} non-checksummed addreses`);
    const tokenListPath = `${path.resolve()}/src/tokens/${listName}.json`;
    console.info("Saving updated list to ", tokenListPath);
    const stringifiedList = JSON.stringify(updatedList, null, 2);
    fs.writeFileSync(tokenListPath, stringifiedList);
    console.info("Checksumming done!");
  } else {
    console.info("All addresses are already checksummed");
  }
}
Example #11
Source File: Signer.ts    From evm-provider.js with Apache License 2.0 6 votes vote down vote up
/**
   * Get the signer's EVM address, and claim an EVM address if it has not claimed one.
   * @returns A promise resolving to the EVM address of the signer's substrate
   * address
   */
  async getAddress(): Promise<string> {
    const address = await this.queryEvmAddress();
    if (address) {
      return address;
    } else {
      // default address
      return this.computeDefaultEvmAddress();
    }
  }
Example #12
Source File: alias.ts    From snapshot-hub with MIT License 6 votes vote down vote up
export async function action(message, ipfs, receipt, id): Promise<void> {
  const params = {
    id,
    ipfs,
    address: getAddress(message.from),
    alias: getAddress(message.alias),
    created: message.timestamp
  };
  await db.queryAsync('INSERT IGNORE INTO aliases SET ?', params);
  console.log(`[writer] Stored: ${message.from} alias ${message.alias}`);
}
Example #13
Source File: index.ts    From snapshot-plugins with MIT License 6 votes vote down vote up
async getTokenInfo(web3: any, tokenAddress: string) {
    try {
      const tokenInfo = await getTokenInfo(web3, tokenAddress);
      return {
        address: tokenAddress,
        checksumAddress: getAddress(tokenAddress),
        name: tokenInfo[0][0],
        symbol: tokenInfo[1][0]
      };
    } catch (e) {
      throw new Error(e);
    }
  }
Example #14
Source File: index.ts    From snapshot-strategies with MIT License 6 votes vote down vote up
export async function strategy(
  space,
  network,
  provider,
  addresses,
  options,
  snapshot
) {
  const params = {
    voters: {
      __args: {
        where: {
          id_in: addresses,
          votingPower_gt: 0
        },
        first: 1000,
        orderBy: 'votingPower',
        orderDirection: 'desc'
      },
      id: true,
      votingPower: true
    }
  };
  if (snapshot !== 'latest') {
    // @ts-ignore
    params.voters.__args.block = { number: snapshot };
  }

  const score = {};
  const result = await subgraphRequest(BADGETH_SUBGRAPH_URL, params);
  if (result && result.voters) {
    result.voters.forEach((voter) => {
      score[getAddress(voter.id)] = parseInt(voter.votingPower);
    });
  }

  return score || {};
}
Example #15
Source File: checksum.ts    From vvs-ui with GNU General Public License v3.0 6 votes vote down vote up
checksumAddresses = (listName: string): void => {
  let badChecksumCount = 0;
  const listToChecksum = lists[listName];
  const updatedList = listToChecksum.reduce((tokenList, token) => {
    const checksummedAddress = getAddress(token.address);
    if (checksummedAddress !== token.address) {
      badChecksumCount += 1;
      const updatedToken = { ...token, address: checksummedAddress };
      return [...tokenList, updatedToken];
    }
    return [...tokenList, token];
  }, []);

  if (badChecksumCount > 0) {
    console.info(`Found and fixed ${badChecksumCount} non-checksummed addreses`);
    const tokenListPath = `${path.resolve()}/src/tokens/${listName}.json`;
    console.info("Saving updated list to ", tokenListPath);
    const stringifiedList = JSON.stringify(updatedList, null, 2);
    fs.writeFileSync(tokenListPath, stringifiedList);
    console.info("Checksumming done!");
  } else {
    console.info("All addresses are already checksummed");
  }
}
Example #16
Source File: creation.ts    From safe-tasks with GNU Lesser General Public License v3.0 5 votes vote down vote up
parseSigners = (rawSigners: string): string[] => {
    return rawSigners.split(",").map(address => getAddress(address))
}
Example #17
Source File: address.ts    From bodhi.js with Apache License 2.0 5 votes vote down vote up
isEvmAddress = (address: string) => {
  try {
    getAddress(address);
    return true;
  } catch {
    return false;
  }
}
Example #18
Source File: index.ts    From cuiswap with GNU General Public License v3.0 5 votes vote down vote up
// returns the checksummed address if the address is valid, otherwise returns false
export function isAddress(value: any): string | false {
  try {
    return getAddress(value)
  } catch {
    return false
  }
}
Example #19
Source File: index.ts    From interface-v2 with GNU General Public License v3.0 5 votes vote down vote up
export function isAddress(value: string | null | undefined): string | false {
  try {
    return getAddress(value || '');
  } catch {
    return false;
  }
}
Example #20
Source File: Address.tsx    From useDApp with MIT License 5 votes vote down vote up
function formatAddress(address: string) {
  const lower = address.toLowerCase()
  try {
    return getAddress(lower)
  } catch {
    return lower
  }
}
Example #21
Source File: index.ts    From sybil-interface with GNU General Public License v3.0 5 votes vote down vote up
// returns the checksummed address if the address is valid, otherwise returns false
export function isAddress(value: any): string | false {
  try {
    return getAddress(value)
  } catch {
    return false
  }
}
Example #22
Source File: index.ts    From uniswap-trading-example with MIT License 5 votes vote down vote up
async function main(): Promise<void> {
  const argv = yargs(process.argv.slice(2)).options({
    api_url: { type: "string", alias: "Alchemy API URL", required: true },
  }).argv;

  const web3 = new Web3(argv.api_url);

  console.log("Creating graph of trading pairs");

  const uniswapTradingPairsGraph = new UniswapTradingPairsGraph(web3);

  await uniswapTradingPairsGraph.createTradingGraph();

  console.log(
    "This script will find the cheapest path for exchanging value between two given token addresses on Uniswap.",
  );

  while (true) {
    const onCancel = () => {
      console.log("Goodbye - happy trading!");
      process.exit();
    };
    const response = await prompts(
      [
        {
          type: "text",
          name: "tokenAddress0",
          message: "Trade from asset with address:",
          validate: (address) =>
            !/^0x[a-fA-F0-9]{40}$/.test(address) ? `Invalid eth address` : true,
        },
        {
          type: "number",
          name: "tokenAmount0",
          message: "Ammount of from asset to trade:",
        },
        {
          type: "text",
          name: "tokenAddress1",
          message: "Trade to asset with address:",
          validate: (address) =>
            !/^0x[a-fA-F0-9]{40}$/.test(address) ? `Invalid eth address` : true,
        },
      ],
      { onCancel },
    );
    await uniswapTradingPairsGraph.getCheapestTradingPath(
      getAddress(response.tokenAddress0),
      response.tokenAmount0,
      getAddress(response.tokenAddress1.toLowerCase()),
    );
  }
}
Example #23
Source File: assetHelpers.ts    From balancer-v2-monorepo with GNU General Public License v3.0 5 votes vote down vote up
constructor(wethAddress: string) {
    this.WETH = getAddress(wethAddress);
  }
Example #24
Source File: index.ts    From cheeseswap-interface with GNU General Public License v3.0 5 votes vote down vote up
// returns the checksummed address if the address is valid, otherwise returns false
export function isAddress(value: any): string | false {
  try {
    return getAddress(value)
  } catch {
    return false
  }
}
Example #25
Source File: index.ts    From dyp with Do What The F*ck You Want To Public License 5 votes vote down vote up
// returns the checksummed address if the address is valid, otherwise returns false
export function isAddress(value: any): string | false {
  try {
    return getAddress(value)
  } catch {
    return false
  }
}
Example #26
Source File: index.ts    From glide-frontend with GNU General Public License v3.0 5 votes vote down vote up
// returns the checksummed address if the address is valid, otherwise returns false
export function isAddress(value: any): string | false {
  try {
    return getAddress(value)
  } catch {
    return false
  }
}
Example #27
Source File: index.ts    From goose-frontend-amm with GNU General Public License v3.0 5 votes vote down vote up
// returns the checksummed address if the address is valid, otherwise returns false
export function isAddress(value: any): string | false {
  try {
    return getAddress(value)
  } catch {
    return false
  }
}
Example #28
Source File: index.ts    From mozartfinance-swap-interface with GNU General Public License v3.0 5 votes vote down vote up
// returns the checksummed address if the address is valid, otherwise returns false
export function isAddress(value: any): string | false {
  try {
    return getAddress(value)
  } catch {
    return false
  }
}
Example #29
Source File: index.ts    From pancake-swap-exchange-testnet with GNU General Public License v3.0 5 votes vote down vote up
// returns the checksummed address if the address is valid, otherwise returns false
export function isAddress(value: any): string | false {
  try {
    return getAddress(value)
  } catch {
    return false
  }
}