Upgrade to Pro — share decks privately, control downloads, hide ads and more …

dapp 開発における big number の落とし穴 / Pitfalls of the ...

blue planet
November 10, 2018

dapp 開発における big number の落とし穴 / Pitfalls of the big number in dapp development

イーサリアムと web3.js で dapp 開発する際の落とし穴と対応策

blue planet

November 10, 2018
Tweet

More Decks by blue planet

Other Decks in Technology

Transcript

  1. 5

  2. 7 Solidity のデータ型には、⼩数型はないですよね const transaction = … const testCoin =

    new web3.eth.Contract(abi, tokenAddress) const decimals = await testCoin.methods.decimals().call() const tokenValue = transaction.value / 10 ** tokenInfo.decimals console.log(tokenValue)
  3. 8 ERC20 の decimals は普通に 18 ですよね @bob: 10 TTC

    送⾦金金してみたぜ! @alice: 10 TTC 来てます! @bob: 0.01 TTC 送⾦金金してみたぜ! @alice: 0.01 TTC 来てます!
  4. 9 ERC20 の decimals は普通に 18 ですよね @bob: 10 TTC

    送⾦金金してみたぜ! @alice: 10 TTC 来てます! @bob: 0.01 TTC 送⾦金金してみたぜ! @alice: 1.0000000000000001e-20 TTC 来てます!
  5. 11 web3.utils.fromWei 使いたい Ver 0.20.7 var fromWei = function(number, unit)

    { var returnValue = toBigNumber(number).dividedBy(getValueOfUnit(unit)); return isBigNumber(number) ? returnValue : returnValue.toString(10); }; https://github.com/ethereum/web3.js/blob/develop/lib/utils/utils.js#L329-L333
  6. 13 web3.utils.fromWei 使いたい Ver 1.0.0-beta.36 var fromWei = function(number, unit)

    { unit = getUnitValue(unit); if(!utils.isBN(number) && !_.isString(number)) { throw new Error('Please pass numbers as strings or BigNumber objects to avoid precision errors.'); } return utils.isBN(number) ? ethjsUnit.fromWei(number, unit) : ethjsUnit.fromWei(number, unit).toString(10); }; https://github.com/ethereum/web3.js/blob/1.0/packages/web3-utils/src/index.js#L231-L239
  7. 14 web3.utils.fromWei 使いたい Ver 1.0.0-beta.36 "dependencies": { "bn.js": "4.11.6", "eth-lib":

    "0.1.27", "ethjs-unit": "0.1.6", "number-to-bn": "1.7.0", "randomhex": "0.1.5", "underscore": "1.8.3", "utf8": "2.1.1" }
  8. 15 web3.utils.fromWei 使いたい Ver 1.0.0-beta.36 function fromWei(weiInput, unit, optionsInput) {

    var wei = numberToBN(weiInput); // eslint-disable-line var negative = wei.lt(zero); // eslint-disable-line const base = getValueOfUnit(unit); const baseLength = unitMap[unit].length - 1 || 1; const options = optionsInput || {}; if (negative) { wei = wei.mul(negative1); } var fraction = wei.mod(base).toString(10); // eslint-disable-line while (fraction.length < baseLength) { fraction = `0${fraction}`; } if (!options.pad) { fraction = fraction.match(/^([0-9]*[1-9]|0)(0*)/)[1]; // 省略 return value; } https://github.com/ethjs/ethjs-unit/blob/master/src/index.js#L83-L117
  9. 16 web3.utils.fromWei 使いたい Ver 1.0.0-beta.36 import Big from 'bignumber.js'; function

    BigNumber (number, base) { return new Big(number, base); } function toDecimals (number, decimals) { return BigNumber(number).times(BigNumber(10).pow(decimals)); } function fromDecimals (number, decimals) { return BigNumber(number).div(BigNumber(10).pow(decimals)); }