Token Quantities
1 min
Tokens (also called Assets) can have an arbitrary divisibility from zero up to eight decimals. While Amount is meant to be used for Signa and Planck and fixed to eight decimals, another - more generic - value object class for arbitrary decimals is needed: ChainValue
Token amounts are called quantities and the Node HTTP API always returns the token quantities the suffix QNT. See an example here
So, a Token FOO can have four decimals, which would result in
1 FOO = 10,000 FOOQNT 1 FOOQNT = 0.0001 FOO
Similar to Amount SignumJS provides a value object class calls ChainValue and allows to convert and calculate with quantities.
const {ChainValue} = require("@signumjs/util");
// Note, we define the decimals for our Token
const FooValue = ChainValue.create(4)
console.log('One FOO is', FooValue.setCompound(1.0).getAtomic(), 'FOOQNT')
console.log('One FOOQNT is', FooValue.setAtomic(1).getCompound(), 'FOO')
// Attention, we need to clone FooValue to avoid an override for the calculations
console.log('10 FOO + 245,000 FOOQNT =', FooValue.setCompound(10).add(FooValue.clone().setAtomic(245000)).getCompound(), 'FOO')
console.log('10 FOO + 245,000 FOOQNT =', FooValue.setCompound(10).add(FooValue.clone().setAtomic(245000)).getAtomic(), 'FOOQNT')
console.log('50,000 FOOQNT * 16 =', FooValue.setAtomic(50_000).multiply(16).getCompound(), 'FOO')
console.log('2 FOO < 40,000 FOOQNT is ', FooValue.setCompound(2).less(FooValue.clone().setAtomic(40_000)))
// Mind that multiply, add, subtract and divide mutates the value object.
const mutatedValue = FooValue.setCompound(1)
mutatedValue.add(FooValue.clone().setCompound(2.65))
console.log('Value is', mutatedValue.getCompound())