How to use ethers - 10 common examples

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 AdExNetwork / adex-protocol-eth / test / TestAdExCore.js View on Github external
before(async function() {
		const tokenWeb3 = await MockToken.new()
		const coreWeb3 = await AdExCore.deployed()
		libMock = await MockLibs.new()
		// WARNING: all invokations to core/token will be from account[0]
		const signer = web3Provider.getSigner(userAcc)
		core = new Contract(coreWeb3.address, AdExCore._json.abi, signer)
		token = new Contract(tokenWeb3.address, MockToken._json.abi, signer)
	})
	beforeEach(async function() {
github magmo / apps / packages / wallet / src / redux / protocols / new-ledger-funding / player-a / __tests__ / scenarios.ts View on Github external
} from '../../../../../domain/commitments/__tests__';
import { success } from '../../../indirect-defunding/states';
import { NEW_LEDGER_FUNDING_PROTOCOL_LOCATOR } from '../../reducer';

// -----------
// Commitments
// -----------
const processId = 'processId';
const protocolLocator = NEW_LEDGER_FUNDING_PROTOCOL_LOCATOR;

const twoThree = [
  { address: asAddress, wei: bigNumberify(2).toHexString() },
  { address: bsAddress, wei: bigNumberify(3).toHexString() },
];

const fiveToApp = [{ address: channelId, wei: bigNumberify(5).toHexString() }];

const app0 = appCommitment({ turnNum: 0, balances: twoThree });
const app1 = appCommitment({ turnNum: 1, balances: twoThree });
const app2 = appCommitment({ turnNum: 2, balances: twoThree });
const app3 = appCommitment({ turnNum: 3, balances: twoThree });

const ledger0 = ledgerCommitment({ turnNum: 0, balances: twoThree });
const ledger1 = ledgerCommitment({ turnNum: 1, balances: twoThree });
const ledger2 = ledgerCommitment({ turnNum: 2, balances: twoThree });
const ledger3 = ledgerCommitment({ turnNum: 3, balances: twoThree });
const ledger4 = ledgerCommitment({ turnNum: 4, balances: twoThree, proposedBalances: fiveToApp });
const ledger5 = ledgerCommitment({ turnNum: 5, balances: fiveToApp });

// Channels

const props = { channelId, ledgerId, processId };
github hubiinetwork / nahmii-contracts / test / scenarios / DriipSettlementChallenge.js View on Github external
);

                    // Index is 1-based
                    const intendedIndex = await ethersDriipSettlementChallenge.proposalIndexByWalletCurrency(
                        trade.buyer.wallet, trade.currencies.intended.ct, trade.currencies.intended.id
                    );
                    intendedIndex._bn.should.eq.BN(1);

                    // Index is 1-based
                    const conjugateIndex = await ethersDriipSettlementChallenge.proposalIndexByWalletCurrency(
                        trade.buyer.wallet, trade.currencies.conjugate.ct, trade.currencies.conjugate.id
                    );
                    conjugateIndex._bn.should.eq.BN(2);

                    const intendedProposal = await ethersDriipSettlementChallenge.proposals(intendedIndex.sub(1));
                    intendedProposal.wallet.should.equal(utils.getAddress(trade.buyer.wallet));
                    intendedProposal.nonce._bn.should.eq.BN(trade.nonce._bn);
                    intendedProposal.blockNumber._bn.should.eq.BN(trade.blockNumber._bn);
                    intendedProposal.status.should.equal(mocks.settlementStatuses.indexOf('Qualified'));
                    intendedProposal.stageAmount._bn.should.eq.BN(trade.buyer.balances.intended.current._bn);
                    intendedProposal.targetBalanceAmount._bn.should.eq.BN(0);
                    intendedProposal.driipType.should.equal(mocks.driipTypes.indexOf('Trade'));
                    intendedProposal.balanceReward.should.be.false;

                    const conjugateProposal = await ethersDriipSettlementChallenge.proposals(conjugateIndex.sub(1));
                    conjugateProposal.wallet.should.equal(utils.getAddress(trade.buyer.wallet));
                    conjugateProposal.nonce._bn.should.eq.BN(trade.nonce._bn);
                    conjugateProposal.blockNumber._bn.should.eq.BN(trade.blockNumber._bn);
                    conjugateProposal.status.should.equal(mocks.settlementStatuses.indexOf('Qualified'));
                    conjugateProposal.stageAmount._bn.should.eq.BN(trade.buyer.balances.conjugate.current._bn);
                    conjugateProposal.targetBalanceAmount._bn.should.eq.BN(0);
                    conjugateProposal.driipType.should.equal(mocks.driipTypes.indexOf('Trade'));
github trufflesuite / ganache-core / test / ethers.js View on Github external
before("Setting up ethers wallet provider", async function() {
    this.timeout(10000);
    const ganacheOptions = {
      accounts: [
        {
          secretKey: `0x${secretKey}`,
          balance: `0x${new BN("1000000000000000000000").toString("hex")}`
        }
      ]
    };

    const { provider } = await intializeTestProvider(ganacheOptions);

    ethersProvider = new ethers.providers.Web3Provider(provider);
    const privateKey = Buffer.from(secretKey, "hex");
    wallet = new ethers.Wallet(privateKey);
    gasPrice = 20 * 10 ** 9; // 20000000000
    value = `0x${new BN(10).pow(new BN(18)).toString("hex")}`;
  });
github JoinColony / colonyNetwork / helpers / test-data-generator.js View on Github external
evaluator,
  worker,
  managerPayout = MANAGER_PAYOUT,
  evaluatorPayout = EVALUATOR_PAYOUT,
  workerPayout = WORKER_PAYOUT
}) {
  const accounts = await web3GetAccounts();
  manager = manager || accounts[0]; // eslint-disable-line no-param-reassign
  evaluator = evaluator || manager; // eslint-disable-line no-param-reassign
  worker = worker || accounts[2]; // eslint-disable-line no-param-reassign

  let tokenAddress;
  if (token === undefined) {
    tokenAddress = await colony.getToken();
  } else {
    tokenAddress = token === ethers.constants.AddressZero ? ethers.constants.AddressZero : token.address;
  }

  const taskId = await makeTask({ colonyNetwork, colony, dueDate, domainId, skillId, manager });
  const task = await colony.getTask(taskId);
  const managerPayoutBN = new BN(managerPayout);
  const evaluatorPayoutBN = new BN(evaluatorPayout);
  const workerPayoutBN = new BN(workerPayout);
  const totalPayouts = managerPayoutBN.add(workerPayoutBN).add(evaluatorPayoutBN);

  const childSkillIndex = await getChildSkillIndex(colonyNetwork, colony, 1, task.domainId);
  await colony.setFundingRole(1, 0, manager, 1, true);
  await colony.moveFundsBetweenPots(1, 0, childSkillIndex, 1, task.fundingPotId, totalPayouts, tokenAddress, { from: manager });
  await colony.setAllTaskPayouts(taskId, tokenAddress, managerPayout, evaluatorPayout, workerPayout, { from: manager });
  await assignRoles({ colony, taskId, manager, evaluator, worker });

  return taskId;
github leapdao / solEVM-enforcer / test / helpers / utils.js View on Github external
Utils.deployContract = async function (truffleContract, ...args) {
  // wait for RPC
  while (true) {
    try {
      await Utils.provider.getBlockNumber();
      break;
    } catch (e) {
      // ignore
    }
    await new Promise((resolve) => setTimeout(resolve, 100));
  }

  let _factory = new ethers.ContractFactory(
    truffleContract.abi,
    truffleContract.bytecode,
    Utils.wallets[0]
  );
  const contract = await _factory.deploy(...args, Utils.txOverrides);

  await contract.deployed();
  return contract;
};
github JoinColony / colonyNetwork / packages / reputation-miner / ReputationMiner.js View on Github external
async addLogContentsToReputationTree(blockNumber = "latest") {
    if (this.useJsTree) {
      this.justificationTree = new PatriciaTreeNoHash();
    } else {
      const contractFactory = new ethers.ContractFactory(
        this.patriciaTreeNoHashContractDef.abi,
        this.patriciaTreeNoHashContractDef.bytecode,
        this.ganacheWallet
      );
      const contract = await contractFactory.deploy();
      this.justificationTree = new ethers.Contract(contract.address, this.patriciaTreeNoHashContractDef.abi, this.ganacheWallet);
    }

    this.justificationHashes = {};
    const addr = await this.colonyNetwork.getReputationMiningCycle(true, { blockTag: blockNumber });
    const repCycle = new ethers.Contract(addr, this.repCycleContractDef.abi, this.realWallet);

    // Do updates

    this.nReputationsBeforeLatestLog = ethers.utils.bigNumberify(this.nReputations.toString());
    // This is also the number of decays we have.

    // How many updates from the logs do we have?
    const nLogEntries = await repCycle.getReputationUpdateLogLength({ blockTag: blockNumber });
    if (nLogEntries.toString() === "0") {
      console.log("WARNING: No log entries found. If this is not one of the very first two cycles, something is wrong");
      return;
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 airswap / airswap-maker-kit / scripts / lib / network.js View on Github external
select: function(operation, callback) {
    try {
      console.log(`\n${chalk.white.bold('AirSwap')}${chalk.white.bold(operation)}`)

      // The private key used to sign orders
      if (!process.env.ETHEREUM_ACCOUNT) throw new Error('ETHEREUM_ACCOUNT must be set in your .env file')
      const currentAccount = new ethers.Wallet(Buffer.from(process.env.ETHEREUM_ACCOUNT, 'hex')).address
      const selectedNetwork = constants.chainNames[process.env.CHAIN_ID || '4']
      const networkName = process.env.CHAIN_ID === '1' ? chalk.green(selectedNetwork) : chalk.cyan(selectedNetwork)

      console.log(chalk.gray(`Account ${currentAccount} ${networkName}\n`))

      const signerPrivateKey = Buffer.from(process.env.ETHEREUM_ACCOUNT, 'hex')

      const provider = ethers.getDefaultProvider(selectedNetwork)
      const wallet = new ethers.Wallet(signerPrivateKey, provider)
      const publicAddress = wallet.address

      provider.getBalance(publicAddress).then(balance => {
        if (balance.eq(0)) {
          console.log(
            chalk.red('\n\nError ') +
              `The selected account (From .env: ${publicAddress}) must have some (${selectedNetwork}) ether to execute transactions.\n`,