ERC20 decimals, specifying a big number

Hi @sirphemmiey,

We need to use the big number libraries multiply and power functions to do the calculation as the number is too big for JavaScript.

    const tokenbits = (new BN(10)).pow(decimals); 
    const amount = (new BN(100)).mul(tokenbits); 

See the following test for the SimpleToken contract above:

SimpleToken.test.js

const { accounts, contract } = require('@openzeppelin/test-environment');

const {
  BN,           // Big Number support
  constants,    // Common constants, like the zero address and largest integers
  expectEvent,  // Assertions for emitted events
  expectRevert, // Assertions for transactions that should fail
} = require('@openzeppelin/test-helpers');

const [ creator, other ] = accounts;

const { expect } = require('chai');

const SimpleToken = contract.fromArtifact('SimpleToken'); // Loads a compiled contract

describe('SimpleToken', function () {
  it('transfer', async function () {
    const token = await SimpleToken.new({ from: creator });
    const decimals = await token.decimals.call();
    const tokenbits = (new BN(10)).pow(decimals);
    const amount = (new BN(100)).mul(tokenbits);

    console.log(`Amount: ${amount}`);

    await token.transfer(other, amount, {from: creator});
    expect(await token.balanceOf(other)).to.be.bignumber.equal(amount);
  });
});
1 Like