How to use the ethers.utils function in ethers

To help you get started, we’ve selected a few ethers examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github ChainSafe / ChainBridge / on-chain / evm-contracts / scripts / cli / transfer.js View on Github external
async function assetTestTransfer(cfg) {
    try {
        const deployerWallet = new ethers.Wallet(constants.relayerPrivKeys[0], cfg.provider);
        let emitterInstance = new ethers.Contract(constants.TEST_EMITTER_ADDRESS, TestEmitterContract.abi, deployerWallet);
        // Trigger fallback
        const tx = await cfg.mainWallet.sendTransaction({
            to: emitterInstance.address,
            value: ethers.utils.parseEther("0.0")
        });
        console.log("[Deploy Asset] Tx hash: ", tx.hash);
    } catch (e) {
        console.log({ e })
    }
}
github ConnextProject / indra / ops / generateBots.js View on Github external
if (!tokenAddress) {
    throw new Error("No token address provided");
  }

  // make the funder account and wallet
  const ethGift = "1";
  const tokenGift = "10000";
  const cfPath = "m/44'/60'/0'/25446";
  const provider = new ethers.providers.JsonRpcProvider(ethRpc);
  const funder = new ethers.Wallet.fromMnemonic(funderMnemonic).connect(provider);
  const token = new ethers.Contract(tokenAddress, tokenArtifacts.abi, funder);

  let obj = {};
  for (let i = 0; i < number; i++) {
    const botMnemonic = ethers.Wallet.createRandom().mnemonic;
    const hdNode = ethers.utils.HDNode.fromMnemonic(botMnemonic).derivePath(cfPath);
    const xpub = hdNode.neuter().extendedKey;
    const addr = ethers.Wallet.fromMnemonic(botMnemonic, cfPath).address;

    // send eth
    console.log(`\nSending ${ethGift} eth to ${addr}`);
    const ethTx = await funder.sendTransaction({
      to: addr,
      value: ethers.utils.parseEther(ethGift),
    });
    await funder.provider.waitForTransaction(ethTx.hash);
    console.log(`Transaction mined! Hash: ${ethTx.hash}q`);

    // send tokens
    console.log(`Minting ${tokenGift} tokens for ${addr}`);
    const tokenTx = await token.mint(addr, ethers.utils.parseEther(tokenGift));
    await funder.provider.waitForTransaction(tokenTx.hash);
github ChainSafe / eth-local / cli / utils / sign.js View on Github external
SignTX = async (tx, walletAddress, password) => {
  debug('Wallet addr:', walletAddress)
  // Update wallet list
  let wallets = getWallets()
  debug('Loading key from: ', wallets[walletAddress])
  let keyStore = JSON.parse(fs.readFileSync(wallets[walletAddress]))
  debug('KeyStore: ', keyStore)
  let privateKey = await ethers.Wallet.fromEncryptedWallet(keyStore, password)
  debug('Private Key:', privateKey)
  let signingKey = new ethers.SigningKey(privateKey.privateKey)
  // Encode tx
  let txBytes = ethers.utils.toUtf8Bytes(tx);
  let txDigest = ethers.utils.keccak256(txBytes);
  debug('txDigest:', txDigest)
  // Sign tx and return it
  return signingKey.signDigest(txDigest)
}
github alice-si / monorepo / packages / jobs / gateways / ethProxy.js View on Github external
function mongoIdToBytes(id) {
  // return '0x' + web3.utils.padLeft(id.toString(), 64);
  return ethers.utils.hexZeroPad('0x' + id.toString(), 32);
}
github Amxx / KitsuneWallet-ERC1836 / test / fixtures / testRefund.js View on Github external
it('Refund in ether - Fine Tunning', async () => {
			const gasToken = ethers.constants.AddressZero;
			const gasPrice = 2000000000;
			const dest     = ethers.utils.getAddress(ethers.utils.hexlify(ethers.utils.randomBytes(20)));

			expect(await proxy.getKey(sdk.utils.addrToKey(user1.address))).to.be.eq('0x0000000000000000000000000000000000000000000000000000000000000007');

			expect(await sdk.provider.getBalance(proxy.address)).to.eq(eth(1.0));
			expect(await sdk.provider.getBalance(dest         )).to.eq(eth(0.0));

			const balanceBefore = await sdk.provider.getBalance(relayer.address);
			const tx = await sdk.multisig.execute(
				proxy,
				[user1],
				{
					to:       dest,
					value:    eth(0.1),
					gasToken,
					gasPrice,
				},
github horizon-games / eth-state-channels-research / client / src / dgame / index.ts View on Github external
private async runCallbacks(nextState: BasicState, previousState?: BasicState, aMove?: Move, anotherMove?: Move): Promise {
    this.isRunning = true

    switch (nextState.metaState.tag) {
    case MetaTag.CommittingRandom:
      this.random = ethers.utils.randomBytes(nextState.metaState.data[0])
      this.queueMove(await this.createMove(ethers.utils.arrayify(ethers.utils.keccak256(this.random))))
      break

    case MetaTag.RevealingRandom:
      this.queueMove(await this.createMove(this.random!))
      delete this.random
      break

    default:
      const run = (callback: NextStateCallback) => callback(nextState, previousState, aMove, anotherMove).catch((reason: any) => {})
      await Promise.all(this.callbacks.map(run))
      break
    }

    this.processQueue()
  }
github 0xProject / 0x-monorepo / packages / abi-gen-wrappers / src / generated-wrappers / i_validator.ts View on Github external
bytecode: string,
        abi: ContractAbi,
        supportedProvider: SupportedProvider,
        txDefaults: Partial,
        logDecodeDependencies: { [contractName: string]: ContractAbi },
    ): Promise {
        assert.isHexString('bytecode', bytecode);
        assert.doesConformToSchema('txDefaults', txDefaults, schemas.txDataSchema, [
            schemas.addressSchema,
            schemas.numberSchema,
            schemas.jsNumber,
        ]);
        const provider = providerUtils.standardizeOrThrow(supportedProvider);
        const constructorAbi = BaseContract._lookupConstructorAbi(abi);
        [] = BaseContract._formatABIDataItemList(constructorAbi.inputs, [], BaseContract._bigNumberToString);
        const iface = new ethers.utils.Interface(abi);
        const deployInfo = iface.deployFunction;
        const txData = deployInfo.encode(bytecode, []);
        const web3Wrapper = new Web3Wrapper(provider);
        const txDataWithDefaults = await BaseContract._applyDefaultsToContractTxDataAsync(
            {
                data: txData,
                ...txDefaults,
            },
            web3Wrapper.estimateGasAsync.bind(web3Wrapper),
        );
        const txHash = await web3Wrapper.sendTransactionAsync(txDataWithDefaults);
        logUtils.log(`transactionHash: ${txHash}`);
        const txReceipt = await web3Wrapper.awaitTransactionSuccessAsync(txHash);
        logUtils.log(`IValidator successfully deployed at ${txReceipt.contractAddress}`);
        const contractInstance = new IValidatorContract(
            txReceipt.contractAddress as string,
github matryx / MatryxPlatform / truffle-config.js View on Github external
fromWei = wei => +ethers.utils.formatEther(wei.toString())
toWei = eth => ethers.utils.parseEther(eth.toString())