ethers#ethers TypeScript 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: configuration.service.ts    From 1hop with MIT License 6 votes vote down vote up
async setGasPrices() {

        try {

            let result;

            try {

                result = await this.http.get(this.CORS_PROXY_URL + this.GAS_PRICE_URL).toPromise();
            } catch (e) {

            }

            let fastGasPrice,
                standardGasPrice,
                instantGasPrice;

            if (!result || !result['health']) {

                result = await this.http.get(this.GAS_PRICE_URL2).toPromise();
            }

            fastGasPrice = result['fast'] * 110 * 1e9 / 100;
            standardGasPrice = result['standard'] * 110 * 1e9 / 100;
            instantGasPrice = result['instant'] * 110 * 1e9 / 100;

            this.fastGasPrice = ethers.utils.bigNumberify(Math.trunc(fastGasPrice));
            this.standardGasPrice = ethers.utils.bigNumberify(Math.trunc(standardGasPrice));
            this.instantGasPrice = ethers.utils.bigNumberify(Math.trunc(instantGasPrice));
        } catch (e) {

            // console.error(e);
        }
    }
Example #2
Source File: configuration.service.ts    From 1x.ag with MIT License 6 votes vote down vote up
async setGasPrices() {

        try {

            let result;

            try {

                result = await this.http.get(this.CORS_PROXY_URL + this.GAS_PRICE_URL).toPromise();
            } catch (e) {

            }

            let fastGasPrice,
                standardGasPrice,
                instantGasPrice;

            if (!result || !result['health']) {

                result = await this.http.get(this.GAS_PRICE_URL2).toPromise();
            }

            fastGasPrice = result['fast'] * 110 * 1e9 / 100;
            standardGasPrice = result['standard'] * 110 * 1e9 / 100;
            instantGasPrice = result['instant'] * 110 * 1e9 / 100;

            this.fastGasPrice = ethers.utils.bigNumberify(Math.trunc(fastGasPrice));
            this.standardGasPrice = ethers.utils.bigNumberify(Math.trunc(standardGasPrice));
            this.instantGasPrice = ethers.utils.bigNumberify(Math.trunc(instantGasPrice));
        } catch (e) {

            // console.error(e);
        }
    }
Example #3
Source File: gas-price.api.service.ts    From gnosis.1inch.exchange with MIT License 6 votes vote down vote up
constructor(private http: HttpClient) {
    timer(0, 30000).pipe(
      mergeMap(() => this.getGasPrice()),
      tap((gasPrice: GasPrice) => {

        const fast = formatGasPrice(gasPrice.fast);
        const instant = formatGasPrice(gasPrice.instant);
        const standard = formatGasPrice(gasPrice.standard);

        this.gasPrice.next({
          fast: ethers.utils.bigNumberify(Math.trunc(fast)),
          standard: ethers.utils.bigNumberify(Math.trunc(standard)),
          instant: ethers.utils.bigNumberify(Math.trunc(instant))
        });
      })
    ).subscribe();
  }
Example #4
Source File: loading.ts    From safe-tasks with GNU Lesser General Public License v3.0 6 votes vote down vote up
decodeTx = (account: string, tx: ethers.providers.TransactionResponse): DecodedMultisigTx | undefined => {
    try {
        const result = safeInterface.decodeFunctionData("execTransaction", tx.data)
        if (tx.to !== account) return undefined
        return {
            to: result.to,
            value: result.value.toString(),
            data: result.data,
            operation: result.operation,
            safeTxGas: result.safeTxGas.toString(),
            baseGas: result.baseGas.toString(),
            gasPrice: result.gasPrice.toString(),
            gasToken: result.gasToken,
            refundReceiver: result.refundReceiver,
            signatures: result.signatures,
        }
    } catch (e) {
        // TODO: try to decode other ways 
        console.log("Unknown function", tx.data.slice(0, 10))
        return undefined
    }
}
Example #5
Source File: new.ts    From MultiFaucet with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * Collects StaticJsonRpcProvider by network
 * @param {number} network id
 * @returns {ethers.providers.StaticJsonRpcProvider} provider
 */
function getProviderByNetwork(
  network: number
): ethers.providers.StaticJsonRpcProvider {
  // Collect all RPC URLs
  const rpcNetworks = { ...mainRpcNetworks, ...secondaryRpcNetworks };
  // Collect alchemy RPC URL
  const rpcUrl = rpcNetworks[network];
  // Return static provider
  return new ethers.providers.StaticJsonRpcProvider(rpcUrl);
}
Example #6
Source File: token.ts    From merkle-airdrop-starter with GNU Affero General Public License v3.0 6 votes vote down vote up
// State management

/**
 * Generate Merkle Tree leaf from address and value
 * @param {string} address of airdrop claimee
 * @param {string} value of airdrop tokens to claimee
 * @returns {Buffer} Merkle Tree node
 */
function generateLeaf(address: string, value: string): Buffer {
  return Buffer.from(
    // Hash in appropriate Merkle format
    ethers.utils
      .solidityKeccak256(["address", "uint256"], [address, value])
      .slice(2),
    "hex"
  );
}
Example #7
Source File: scraper.ts    From tweetdrop with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
   * Checks if an address is valid
   * @param {string} address to check
   * @returns {{valid: boolean, address: string}} returns validity and checksum address
   */
  isValidAddress(address: string): { valid: boolean; address: string } {
    // Setup address
    let addr: string = address;

    try {
      // Return valid and address if success
      addr = ethers.utils.getAddress(address);
      return { valid: true, address: addr };
    } catch {
      // Else, if error
      return { valid: false, address };
    }
  }
Example #8
Source File: injectedEthereumSigner.ts    From arbundles with Apache License 2.0 6 votes vote down vote up
async setPublicKey(): Promise<void> {
    const address = "sign this message to connect to Bundlr.Network";
    const signedMsg = await this.signer.signMessage(address);
    const hash = await ethers.utils.hashMessage(address);
    const recoveredKey = ethers.utils.recoverPublicKey(
      ethers.utils.arrayify(hash),
      signedMsg,
    );
    this.publicKey = Buffer.from(ethers.utils.arrayify(recoveredKey));
  }
Example #9
Source File: functions.ts    From cookietrack-api with MIT License 6 votes vote down vote up
query = async (chain: Chain, address: Address, abi: ABI[], method: string, args: any[]) => {
  let result;
  let errors = 0;
  while(!result && errors < 3) {
    try {
      let ethers_provider = new ethers.providers.JsonRpcProvider(rpcs[chain][0]);
      let contract = new ethers.Contract(address, abi, ethers_provider);
      result = await contract[method](...args);
    } catch {
      try {
        let ethers_provider = new ethers.providers.JsonRpcProvider(rpcs[chain][1]);
        let contract = new ethers.Contract(address, abi, ethers_provider);
        result = await contract[method](...args);
      } catch {
        if(++errors > 2) {
          if(!ignoreErrors.find(i => i.chain === chain && i.address === address.toLowerCase())) {
            console.error(`Calling ${method}(${args}) on ${address} (Chain: ${chain.toUpperCase()})`);
          }
        }
      }
    }
  }
  return result;
}
Example #10
Source File: ENSService.ts    From dxvote with GNU Affero General Public License v3.0 6 votes vote down vote up
async resolveENSName(address: string) {
    let name = null;
    try {
      const checksumed = ethers.utils.getAddress(address);
      name = await this.web3Provider.lookupAddress(checksumed);
    } catch (e) {
      console.warn(
        '[ENSService] Error while trying to reverse resolve ENS address.'
      );
    }
    return name;
  }
Example #11
Source File: convertResults.ts    From defillama-sdk with GNU Affero General Public License v3.0 6 votes vote down vote up
export default function (results: ethers.utils.Result) {
  if (typeof results === "string" || typeof results === "boolean") {
    return results;
  }
  let convertedResults = {} as any;
  if (results instanceof Array && !containsNamedResults(results)) {
    // Match every idiosynchrasy of the SDK
    convertedResults = [];
  }
  if (BigNumber.isBigNumber(results) || typeof results === "number") {
    convertedResults = results.toString();
  } else {
    stringifyBigNumbers(results, convertedResults);
  }
  if (results instanceof Array) {
    if (results.length === 1) {
      return convertedResults[0];
    } else {
      // Some calls return the extra __length__ parameter (I think when some results are named)
      if (containsNamedResults(convertedResults)) {
        convertedResults["__length__"] = results.length;
      }
    }
  }
  return convertedResults;
}
Example #12
Source File: protocolUtils.ts    From index-coop-smart-contracts with Apache License 2.0 6 votes vote down vote up
public async getCreatedSetTokenAddress (txnHash: string | undefined): Promise<string> {
    if (!txnHash) {
      throw new Error("Invalid transaction hash");
    }

    const abi = ["event SetTokenCreated(address indexed _setToken, address _manager, string _name, string _symbol)"];
    const iface = new ethers.utils.Interface(abi);

    const topic = ethers.utils.id("SetTokenCreated(address,address,string,string)");
    const logs = await this._provider.getLogs({
      fromBlock: "latest",
      toBlock: "latest",
      topics: [topic],
    });

    const parsed = iface.parseLog(logs[logs.length - 1]);
    return parsed.args._setToken;
  }
Example #13
Source File: index.ts    From index-ui with MIT License 6 votes vote down vote up
approve = async (
  userAddress: string,
  spenderAddress: string,
  tokenAddress: string,
  provider: provider,
  onTxHash?: (txHash: string) => void
): Promise<boolean> => {
  try {
    const tokenContract = getERC20Contract(provider, tokenAddress)
    return tokenContract.methods
      .approve(spenderAddress, ethers.constants.MaxUint256)
      .send(
        { from: userAddress, gas: 80000 },
        async (error: any, txHash: string) => {
          if (error) {
            console.log('ERC20 could not be approved', error)
            onTxHash && onTxHash('')
            return false
          }
          if (onTxHash) {
            onTxHash(txHash)
          }
          const status = await waitTransaction(provider, txHash)
          if (!status) {
            console.log('Approval transaction failed.')
            return false
          }
          return true
        }
      )
  } catch (e) {
    return false
  }
}
Example #14
Source File: account-slice.ts    From lobis-frontend with MIT License 6 votes vote down vote up
getBalances = createAsyncThunk("account/getBalances", async ({ address, networkID, provider }: IGetBalances): Promise<IAccountBalances> => {
    const sLobiContract = new ethers.Contract(addresses.lobi, abis.sLobi, provider);
    const sLobiBalance = await sLobiContract.balanceOf(address);
    const lobiContract = new ethers.Contract(addresses.sLobi, abis.lobi, provider);
    const lobiBalance = await lobiContract.balanceOf(address);

    return {
        balances: {
            sLobi: ethers.utils.formatUnits(sLobiBalance, "gwei"),
            lobi: ethers.utils.formatUnits(lobiBalance, "gwei"),
        },
    };
})
Example #15
Source File: tally-poll.ts    From panvala with Apache License 2.0 6 votes vote down vote up
async function getUniswapAccountBalance(
  pairContractAddress,
  tokenAddress,
  address,
  { provider = null, rpcEndpoint = null }
) {
  if (provider === null && rpcEndpoint === null) {
    throw new Error('Must pass a provider or an rpcEndpoint to create a provider');
  }
  if (provider === null) {
    provider = new ethers.providers.JsonRpcProvider(rpcEndpoint);
  }

  const panToken = new Contract(tokenAddress, contractABIs.BasicToken.abi, provider);
  const lpToken = new Contract(pairContractAddress, contractABIs.BasicToken.abi, provider);

  let balance = BigNumber.from(0);
  try {
    const accountLpBalance = await lpToken.balanceOf(address);
    if (!accountLpBalance.eq(0)) {
      const lpSupply = await lpToken.totalSupply();
      if (!lpSupply.eq(0)) {
        const poolPanBalance = await panToken.balanceOf(pairContractAddress);
        balance = accountLpBalance.mul(poolPanBalance).div(lpSupply);
      }
    }
  } catch (err) {
    console.log(`Error while fetching Uniswap balance via RPC: ${err}`);
    throw err;
  }

  console.log(`Got uniswap balance for ${address}`);
  return balance;
}
Example #16
Source File: test-ethers.ts    From moonbeam with GNU General Public License v3.0 6 votes vote down vote up
describeDevMoonbeam("Ethers.js contract", (context) => {
  it("should be deployable", async function () {
    let signer = new ethers.Wallet(GENESIS_ACCOUNT_PRIVATE_KEY, context.ethers);
    const contractData = await getCompiled("TestContract");
    const contractFactory = new ethers.ContractFactory(
      contractData.contract.abi as ethers.ContractInterface,
      contractData.byteCode,
      signer
    );

    // Must create the block and then wait, because etherjs will wait until
    // the contract is mined to return;
    let contract = await new Promise<ethers.Contract>(async (resolve) => {
      const contractPromise = contractFactory.deploy({
        gasLimit: 1_000_000,
        gasPrice: 1_000_000_000,
      });
      await context.createBlock();
      resolve(await contractPromise);
    });

    expect(contract.address);
    expect(await context.web3.eth.getCode(contract.address)).to.be.string;
  });
});
Example #17
Source File: compound.service.ts    From 1hop with MIT License 5 votes vote down vote up
async getBalances(walletAddress) {

        const allTokens = Object.values(this.tokens);

        const promises = allTokens
            .map(async token => {

                const contract = new (await this.web3Service.getWeb3Provider()).eth.Contract(
                    // @ts-ignore
                    CERC20ABI,
                    token.address
                );

                return contract.methods.balanceOfUnderlying(walletAddress).call();
            });

        return (await Promise.all(promises))
            .map((balance, i) => {

                const balanceBN = ethers.utils.bigNumberify(balance);

                const token = Object.assign({}, this.tokenService.tokens[allTokens[i].symbol.substr(1)]);

                if (balanceBN.gt(0)) {

                    token['balance'] = this.tokenService.toFixed(
                        this.tokenService.formatAsset(
                            token.symbol,
                            // @ts-ignore
                            balanceBN
                        ),
                        5
                    );
                } else {

                    token['balance'] = '0';
                }

                token['rawBalance'] = balance;

                return token;
            });
    }
Example #18
Source File: configuration.service.ts    From 1x.ag with MIT License 5 votes vote down vote up
public fastGasPrice = new ethers.utils.BigNumber(Math.trunc(6 * 100)).mul(1e7);
Example #19
Source File: app.component.ts    From gnosis.1inch.exchange with MIT License 5 votes vote down vote up
public swap(): void {

        this.loading = true;

        const walletAddress$ = this.gnosisService.walletAddress$;
        const tokenHelper$ = this.tokenService.tokenHelper$;

        const transactions: Tx[] = [];
        let token: ITokenDescriptor;
        let walletAddress: string;
        combineLatest([walletAddress$, tokenHelper$]).pipe(
            switchMap(([addr, tokenHelper]) => {
                walletAddress = addr;
                token = tokenHelper.getTokenBySymbol(this.fromTokenSymbol);
                const toToken = tokenHelper.getTokenBySymbol(this.toTokenSymbol);
                const isTokenApproved$ = this.ethereumService.isTokenApproved(
                    token.address,
                    walletAddress,
                    environment.TOKEN_SPENDER,
                    this.fromAmountBN
                );
                return forkJoin({
                    isApproved: isTokenApproved$,
                    fromToken: of(token),
                    toToken: of(toToken)
                });
            }),
            switchMap(({isApproved, fromToken, toToken}) => {

                if (!isApproved) {
                    const tx: Tx = {
                        to: token.address,
                        data: this.ethereumService.getApproveCallData(environment.TOKEN_SPENDER, ethers.constants.MaxUint256),
                        value: '0'
                    };
                    transactions.push(tx);
                }

                return this.oneInchApiService.getSwapData$(
                    fromToken.address,
                    toToken.address,
                    this.fromAmountBN.toString(),
                    walletAddress,
                    this.slippage,
                    true
                );
            }),
            tap((data: SwapData) => {

                const tx: Tx = {
                    to: data.tx.to,
                    value: data.tx.value,
                    data: data.tx.data,
                    gasPrice: data.tx.gasPrice
                };
                transactions.push(tx);

                this.gnosisService.sendTransactions(transactions);
                this.loading = false;
            }),
            catchError((e) => {
                this.loading = false;
                console.log(e);
                return of('');
            }),
            take(1),
        ).subscribe();
    }
Example #20
Source File: proposing.ts    From safe-tasks with GNU Lesser General Public License v3.0 5 votes vote down vote up
buildData = (method: string, params?: any[]): string => {
    const iface = new ethers.utils.Interface([`function ${method}`])
    return iface.encodeFunctionData(method, params)
}
Example #21
Source File: ACAToken.test.ts    From bodhi.js with Apache License 2.0 5 votes vote down vote up
describe('ACAToken', () => {
  let wallet: Signer;
  let walletTo: Signer;
  let token: Contract;

  before(async () => {
    [wallet, walletTo] = await provider.getWallets();
    token = new ethers.Contract(ADDRESS.ACA, ERC20_ABI, wallet as any);
  });

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

  it('get token name', async () => {
    const name = await token.name();
    expect(name).to.equal('Acala');
  });

  it('get token symbol', async () => {
    const symbol = await token.symbol();
    expect(symbol).to.equal('ACA');
  });

  it('get token decimals', async () => {
    const decimals = await token.decimals();
    expect(decimals).to.equal(12);
  });

  it('Transfer adds amount to destination account', async () => {
    const balance = await token.balanceOf(await walletTo.getAddress());
    await token.transfer(await walletTo.getAddress(), 7);
    expect((await token.balanceOf(await walletTo.getAddress())).sub(balance)).to.equal(7);
  });

  it('Transfer emits event', async () => {
    await expect(token.transfer(await walletTo.getAddress(), 7))
      .to.emit(token, 'Transfer')
      .withArgs(await wallet.getAddress(), await walletTo.getAddress(), 7);
  });

  it('Can not transfer above the amount', async () => {
    const balance = await token.balanceOf(await wallet.getAddress());
    await expect(token.transfer(await walletTo.getAddress(), balance.add(7))).to.be.reverted;
  });
});