In Sway, there are multiple primitive number types:
u8
(8-bit unsigned integer) u16
(16-bit unsigned integer) u32
(32-bit unsigned integer) u64
(64-bit unsigned integer) u256
(256-bit unsigned integer) This guide explains how to create and interact with Sway numbers while using the SDK.
u64
and u256
When you pass in a u64
or a u256
to a Sway program from JavaScript, you must first convert it to a BigNum
object. This is because these types can have extremely large maximum values (2^64
and 2^256
respectively), and JavaScript's Number
type can only hold up to 53 bits of precision (2^53
).
import { bn } from 'fuels';
const originalNumber = 20;
const bigNumber = bn(originalNumber);
expect(bigNumber.toNumber()).toEqual(originalNumber);
You can also create a BigNum
from a string. This is useful when you want to pass in a number that is too large to be represented as a JavaScript number. Here's how you can do that:
import { bn } from 'fuels';
const originalNumber = '9007199254740992';
const bigNumber = bn(originalNumber);
expect(bigNumber.toString()).toEqual(originalNumber);
u8
, u16
, and u32
You don't need to do anything special to create these numbers. You can pass in a JavaScript number directly. See the examples below for more details.
u64
and u256
const originalNumber = 20;
const { waitForResult } = await contract.functions.echo_u64(bn(originalNumber)).call();
const { value } = await waitForResult();
expect(value.toNumber()).toEqual(originalNumber);
Note: If a contract call returns a number that is too large to be represented as a JavaScript number, you can convert it to a string using the
.toString()
method instead of.toNumber()
.
u8
, u16
, and u32
const originalNumber = 20;
const { waitForResult } = await contract.functions.echo_u8(originalNumber).call();
const { value } = await waitForResult();
expect(value).toEqual(originalNumber);
BigNum
from ethers
with fuels
import { toBigInt } from 'ethers';
import { bn } from 'fuels';
const originalNumber = 20;
const ethersBigNum = toBigInt(originalNumber);
const fuelsBigNum = bn(ethersBigNum.toString());
expect(fuelsBigNum.toNumber()).toEqual(originalNumber);