How to use the web3-utils.toBN function in web3-utils

To help you get started, we’ve selected a few web3-utils 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 JoinColony / colonyNetwork / test / reputation-system / types-of-disagreement.js View on Github external
await goodClient.resetDB();
      await goodClient.addLogContentsToReputationTree();
      await advanceMiningCycleNoContest({ colonyNetwork, test: this, client: goodClient });
      await goodClient.saveCurrentState();

      // The update log should contain the person being rewarded for the previous
      // update cycle, and reputation updates for one task completion (manager, worker (skill and domain), evaluator);
      // That's five in total.
      const repCycle = await getActiveRepCycle(colonyNetwork);
      const nLogEntries = await repCycle.getReputationUpdateLogLength();
      expect(nLogEntries).to.eq.BN(5);

      const badClient = new MaliciousReputationMinerExtraRep(
        { loader, realProviderPort, useJsTree, minerAddress: MINER2 },
        17,
        toBN("170141183460469231731687302715884105727").mul(toBN(-1))
      );
      await badClient.initialise(colonyNetwork.address);

      // Moving the state to the bad client
      const currentGoodClientState = await goodClient.getRootHash();
      await badClient.loadState(currentGoodClientState);

      await submitAndForwardTimeToDispute([goodClient, badClient], this);

      await accommodateChallengeAndInvalidateHash(colonyNetwork, this, goodClient, badClient, {
        client2: { respondToChallenge: "colony-reputation-mining-reputation-not-max-int128" }
      });
      await repCycle.confirmNewHash(1);
    });
  });
github JoinColony / colonyNetwork / test / colony-funding.js View on Github external
const tokenSupplyCeiling = toBN(2)
          .pow(toBN(256))
          .subn(1)
          .toString();
        await newColony.setTokenSupplyCeiling(tokenSupplyCeiling);

        const payoutTokenArgs = getTokenArgs();
        const payoutToken = await Token.new(...payoutTokenArgs);
        await fundColonyWithTokens(newColony, payoutToken, data.totalAmountOfPayoutTokens.toString());
        // Issuing colony's native tokens so they can be given to users in `bootstrapColony`
        await newColony.mintTokens(data.totalReputation.toString());

        // Every user has equal amount of reputation and tokens (totalReputationAndTokens / 3)
        const reputationPerUser = data.totalReputation.div(toBN(3));
        const tokensPerUser = toBN(reputationPerUser);
        // Giving colony's native tokens to 3 users.
        // Reputation log is appended to inactive reputation mining cycle
        await newColony.bootstrapColony(
          [userAddress1, userAddress2, userAddress3],
          [reputationPerUser.toString(), reputationPerUser.toString(), reputationPerUser.toString()]
        );

        // Submit current hash in active reputation mining cycle
        await miningClient.addLogContentsToReputationTree();
        await forwardTime(MINING_CYCLE_DURATION, this);
        await miningClient.submitRootHash();

        let addr = await colonyNetwork.getReputationMiningCycle.call(true);
        let repCycle = await IReputationMiningCycle.at(addr);
        await repCycle.confirmNewHash(0);
github JoinColony / colonyNetwork / test / colony-funding.js View on Github external
const promises = initialSquareRoots.map((param, i) => {
        const squareRoots = [...initialSquareRoots];
        // If we are passing total reputation, total tokens or denominator, we will divide by 2, else multiply
        const functionName = [2, 3, 5].includes(i) ? "div" : "mul";
        squareRoots[i] = toBN(squareRoots[i])
          [functionName](toBN(2))
          .toString();

        return checkErrorRevert(
          colony.claimRewardPayout(payoutId, squareRoots, ...userReputationProof1, {
            from: userAddress1
          }),
          errorMessages[i]
        );
      });
github JoinColony / colonyNetwork / test / colony-funding.js View on Github external
describe("when creating reward payouts", async () => {
    let miningClient;
    let colonyWideReputationProof;
    let userReputationProof1;
    const initialFunding = toBN(100 * 1e18);
    const userReputation = toBN(50 * 1e18);
    const userTokens = toBN(userReputation);
    const totalReputation = toBN(userReputation);
    const totalTokens = toBN(userReputation);

    const userAddress1 = accounts[0];
    const userAddress2 = accounts[1];
    const userAddress3 = accounts[2];
    let initialSquareRoots;

    beforeEach(async () => {
      await fundColonyWithTokens(colony, otherToken, initialFunding.toString());
      await colony.mintTokens(initialFunding.toString());
      await colony.bootstrapColony([userAddress1], [userReputation.toString()]);

      await token.approve(tokenLocking.address, userReputation.toString(), {
        from: userAddress1
      });
github bodhiproject / bodhi-ui / src / helpers / utility.js View on Github external
export function satoshiToDecimal(number) {
  if (!number) {
    return number;
  }

  let bn;
  if (isNaN(Number(number))) {
    bn = toBN(number, 16);
  } else {
    const toStringNumber = String(number);
    const splitArr = toStringNumber.split('.');
    const integerPart = splitArr[0];
    bn = toBN(integerPart);
  }

  const conversionBN = toBN(SATOSHI_CONVERSION);
  const integerPart = bn.div(conversionBN).toNumber();
  const decimalPartBN = bn.sub(conversionBN.mul(toBN(integerPart)));
  const decimalPart = NP.divide(decimalPartBN.toNumber(), SATOSHI_CONVERSION);
  return NP.plus(integerPart, decimalPart);
}
github OpenST / openst.js / lib / deployers / TokenHolderDeployer.js View on Github external
deployTokenHolderOnAuxiliary: async function() {
    const oThis = this;

    let web3 = oThis.ic().chainWeb3();
    let abiBinProvider = oThis.ic().abiBinProvider();

    let contractName = 'TokenHolder';
    let bnSuggestedGas = utils.toBN('4000000');
    let bnConfiguredGas = utils.toBN(oThis.gas || '0');
    let bnGasToUse = bnSuggestedGas.cmp(bnConfiguredGas) < 0 ? bnSuggestedGas : bnConfiguredGas;

    let tokenHolderDeployResponse = await new DeployContract({
      web3: web3,
      contractName: contractName,
      from: oThis.from,
      gasPrice: oThis.gasPrice,
      gas: bnGasToUse.toString(10),
      abi: abiBinProvider.getABI(contractName),
      bin: abiBinProvider.getBIN(contractName),
      args: oThis.args
    }).deploy();

    oThis.tokenHolderContractAddress = tokenHolderDeployResponse.receipt.contractAddress;
    console.log('TokenHolder Contract Address :', oThis.tokenHolderContractAddress);
    return tokenHolderDeployResponse;
github austintgriffith / burner-core / assets / src / Asset.js View on Github external
async getMaximumSendableBalance(address) {
    const [balance, sendFee] = await Promise.all([
      this.getBalance(address),
      this.getSendFee(address),
    ]);
    return toBN(balance).sub(toBN(sendFee)).toString();
  }
github 0xbitcoin / tokenpool / lib / peer-interface.js View on Github external
{
            validJSONSubmit = false;
          }


          var maxShareDifficulty = self.getPoolMaximumShareDifficulty()  ;
          if( maxShareDifficulty != null && difficulty >  maxShareDifficulty)
          {
            difficulty = maxShareDifficulty;
          }

          var poolEthAddress = self.getMintHelperAddress() ;
          var poolChallengeNumber = await self.tokenInterface.getPoolChallengeNumber();
          var computed_digest =  web3utils.soliditySha3( poolChallengeNumber , poolEthAddress, nonce )

          var digestBigNumber = web3utils.toBN(digest);
          var claimedTarget = self.getTargetFromDifficulty( difficulty )

          if(computed_digest !== digest || digestBigNumber.gte(claimedTarget))
          {
            validJSONSubmit = false;
          }

          var ethBlock = await self.redisInterface.getEthBlockNumber();

          var shareData = {block: ethBlock ,
            nonce: nonce,
            minerEthAddress: minerEthAddress,
            challengeNumber: challenge_number,
            digest: digest,
            difficulty: difficulty,
            customVardiff: custom_vardiff_used
github zapproject / zap-nodejs-api / src / api / contracts / Registry.js View on Github external
async getNextEndpointParams({provider, endpoint, index}){
    return this.contract.methods.getNextEndpointParam(
      provider,
      utf8ToHex(endpoint),
      toBN(index)
    ).call();
  }
github urbit / bridge / src / lib / error.js View on Github external
const txnCost = (web3, msg) => {
    const costWei = msg.match(/upfront cost is: ([0-9]+)/);
    const costEth = fromWei(toBN(costWei[1]), 'ether');
    return parseFloat(costEth).toFixed(4);
  };