Builders can now use Kadana.js PactNumber to eliminate common errors when using out of safe numbers in Jasvascript. PactNumber also has other useful functions that is going to make life easier.
Kadena are thrilled to announce that PactNumber is now released in Kadena.js.
What is PactNumber and how is it used?
PactNumber is a typescript class that provides useful number functions for frontend builders to generate Pact Code conveniently with accuracy. In this article, we’ll take a look at the use of numbers in KDA transfer functions and introduce the usage of PactNumber.
Integer vs Decimal vs String
Pact functions often require numbers to be typed as integers or decimals. The amount in KDA transfer functions are typed as decimal. Therefore, the sample code below will receive a type error, “expected decimal, found integer”.
PactNumber now provides the functions toInteger()
and toDecimal()
, so builders can forget about number type errors, just like the code below.
There are also cases when we want to read numbers as strings. One example is the Chain IDs that are used in KDA’s cross chain transfers. Builders need to be aware that even though Kadena chains consist of integers ranging from 0..19, the Kadena chains are specified as strings. The 4th argument in the below example specifies the target chain as chain 10.
PactNumber now provides the functions to stringify any type of numbers with toStringifiedInteger()
and toStringifiedDecimal()
Pact native functions
We have looked composing Pact codes with different number types from Javascript with PactNumber. There also exists Pact native functions to read numbers from data
field: read-msg
, read-decimal
, read-integer
.
Above code is one example of writing the KDA transfer function with read-decimal
, where amount
is passed into data field as a string. This way, amount is always read as decimals, and the type error shown in example 1 is prevented.
read-msg
is also a function to read from data field, regardless of the type. Below are examples that depict how the numbers are formatted differently to be read as different types in Pact.
PactNumber provides the functions to format numbers in decimal or integer objects that Pact expects in the data field: toPactDecimal()
and toPactInteger()
.
Big Number
Lastly, PactNumber solves a big issue that builders often struggle with —operating with numbers in Javascript that are out of safe number range.
Number operations in smart contracts often involve big decimal points that Javascript cannot safely handle. PactNumber uses bignumber.js library and allow users to store and handle big number values safely.
What’s coming next?
Coming next with PactNumber is number operations.
Via This Site