How to use the ethereumjs-util.BN function in ethereumjs-util

To help you get started, we’ve selected a few ethereumjs-util 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 MetaMask / gaba / src / transaction / TransactionController.ts View on Github external
private normalizeTxFromEtherscan(txMeta: EtherscanTransactionMeta, currentNetworkID: string): TransactionMeta {
		const time = parseInt(txMeta.timeStamp, 10) * 1000;
		/* istanbul ignore next */
		const status = txMeta.isError === '0' ? 'confirmed' : 'failed';
		return {
			blockNumber: txMeta.blockNumber,
			id: random({ msecs: time }),
			networkID: currentNetworkID,
			status,
			time,
			transaction: {
				data: txMeta.input,
				from: txMeta.from,
				gas: BNToHex(new BN(txMeta.gas)),
				gasPrice: BNToHex(new BN(txMeta.gasPrice)),
				nonce: BNToHex(new BN(txMeta.nonce)),
				to: txMeta.to,
				value: BNToHex(new BN(txMeta.value))
			},
			transactionHash: txMeta.hash
		};
	}
github ethereumjs / ethereumjs-client / lib / blockchain / blockpool.js View on Github external
if (!Array.isArray(blocks)) {
      blocks = [ blocks ]
    }

    let latest = this.chain.blocks.height
    let first = new BN(blocks[0].header.number)

    if (first.gt(latest.addn(1))) {
      // if block segment arrived out of order, save it to the pool
      this.pool.set(first.toString(), blocks)
      return
    }
    while (blocks) {
      // otherwise save headers and keep saving headers from header pool in order
      let last = new BN(blocks[blocks.length - 1].header.number)
      let hash = blocks[0].hash().toString('hex').slice(0, 8) + '...'
      await this.chain.putBlocks(blocks)
      this.logger.info(`Imported blocks count=${blocks.length} number=${first.toString(10)} hash=${hash}`)
      latest = last
      blocks = this.pool.get(last.addn(1).toString())
      if (blocks) {
        this.pool.delete(last.addn(1).toString())
        first = new BN(blocks[0].header.number)
      }
    }
  }
}
github ethereum / remix / remix-debug / src / solidity-decoder / types / DynamicByteArray.js View on Github external
async decodeFromStorage (location, storageResolver) {
    let value = '0x0'
    try {
      value = await util.extractHexValue(location, storageResolver, this.storageBytes)
    } catch (e) {
      console.log(e)
      return {
        value: '',
        type: this.typeName
      }
    }
    const bn = new BN(value, 16)
    if (bn.testn(0)) {
      const length = bn.div(new BN(2))
      let dataPos = new BN(sha3256(location.slot).replace('0x', ''), 16)
      let ret = ''
      let currentSlot = '0x'
      try {
        currentSlot = await util.readFromStorage(dataPos, storageResolver)
      } catch (e) {
        console.log(e)
        return {
          value: '',
          type: this.typeName
        }
      }
      while (length.gt(ret.length) && ret.length < 32000) {
        currentSlot = currentSlot.replace('0x', '')
        ret += currentSlot
        dataPos = dataPos.add(new BN(1))
        try {
github blockchain / My-Wallet-V3 / src / eth / eth-tx-builder.js View on Github external
update () {
    let feeBN = new util.BN(this._tx.gas).mul(new util.BN(this._tx.gasPrice));
    let amountBN = new util.BN(this._tx.value);
    let availableBN = Math.max(parseFloat(this._account.wei.sub(feeBN)), 0);
    this._fee = parseFloat(fromWei(feeBN, 'ether'));
    this._amount = parseFloat(fromWei(amountBN, 'ether'));
    this._available = parseFloat(fromWei(availableBN, 'ether'));
  }
github nomiclabs / buidler / packages / buidler-core / src / internal / buidler-evm / provider / node.ts View on Github external
const node = new BuidlerNode(
      vm,
      genesisAccounts.map(acc => toBuffer(acc.privateKey)),
      new BN(blockGasLimit),
      genesisBlock,
      throwOnTransactionFailures,
      throwOnCallFailures,
      stackTracesOptions
    );

    return [common, node];
  }

  private readonly _common: Common;
  private readonly _stateManager: PStateManager;
  private _blockTimeOffsetSeconds: BN = new BN(0);

  private readonly _accountPrivateKeys: Map = new Map();
  private readonly _transactionByHash: Map = new Map();
  private readonly _transactionHashToBlockHash: Map = new Map();
  private readonly _blockHashToTxBlockResults: Map<
    string,
    TxBlockResult[]
  > = new Map();
  private readonly _blockHashToTotalDifficulty: Map = new Map();
  private readonly _stackTracesEnabled: boolean = false;
  private readonly _vmTracer?: VMTracer;
  private readonly _solidityTracer?: SolidityTracer;

  private readonly _getLatestBlock: () => Promise;
  private readonly _getBlock: (hashOrNumber: Buffer | BN) => Promise;
  private _failedStackTraces = 0;
github nomiclabs / buidler / packages / buidler-core / src / internal / buidler-evm / provider / node.ts View on Github external
private async _timestampClashesWithPreviousBlockOne(
    block: Block
  ): Promise {
    const blockTimestamp = new BN(block.header.timestamp);

    const latestBlock = await this.getLatestBlock();
    const latestBlockTimestamp = new BN(latestBlock.header.timestamp);

    return latestBlockTimestamp.eq(blockTimestamp);
  }
github MetaMask / metamask-mobile / app / util / number.js View on Github external
if (!whole) {
		whole = '0';
	}
	if (!fraction) {
		fraction = '';
	}
	if (fraction.length > decimals) {
		throw new Error(
			'[number] while converting number ' + tokenValue + ' to token minimal util, too many decimal places'
		);
	}
	while (fraction.length < decimals) {
		fraction += '0';
	}
	whole = new BN(whole);
	fraction = new BN(fraction);
	let tokenMinimal = whole.mul(base).add(fraction);
	if (negative) {
		tokenMinimal = tokenMinimal.mul(negative);
	}
	return new BN(tokenMinimal.toString(10), 10);
}
github ethereumjs / ethereumjs-client / lib / sync / lightsync.js View on Github external
.on('fetched', headers => {
        const first = new BN(headers[0].number)
        const hash = short(headers[0].hash())
        this.logger.info(`Imported headers count=${headers.length} number=${first.toString(10)} hash=${hash} peers=${this.pool.size}`)
      })
    await this.headerFetcher.fetch()
github nomiclabs / buidler / packages / buidler-core / src / internal / buidler-evm / provider / node.ts View on Github external
}

    await this._addTransactionToBlock(block, tx);

    const result = await this._vm.runBlock({
      block,
      generate: true,
      skipBlockValidation: true
    });

    const error = !this._throwOnTransactionFailures
      ? undefined
      : await this._manageErrors(result.results[0].execResult);

    if (needsTimestampIncrease) {
      await this.increaseTime(new BN(1));
    }

    await this._saveBlockAsSuccessfullyRun(block, result);
    await this._saveTransactionAsSuccessfullyRun(tx, block);

    if (error !== undefined) {
      throw error;
    }

    return result;
  }
github ethereum / remix / remix-debug / src / solidity-decoder / types / util.js View on Github external
function toBN (value) {
  if (value instanceof BN) {
    return value
  } else if (value.match && value.match(/^(0x)?([a-f0-9]*)$/)) {
    value = ethutil.unpad(value.replace(/^(0x)/, ''))
    value = new BN(value === '' ? '0' : value, 16)
  } else if (!isNaN(value)) {
    value = new BN(value)
  }
  return value
}