This guide demonstrates how to convert between Addresses
and Fuel's native types (Bytes32
, b256
) using helper functions. Native types are wrappers for bytes, and you can perform conversions between them by leveraging these functions.
The following example demonstrates how to convert between Bytes32
and to b256
:
const random256BitsArr: Bytes = randomBytes(32);
const hexed256BitsStr: string = hexlify(random256BitsArr);
const address = Address.fromB256(hexed256BitsStr);
const arrayB256: Uint8Array = arrayify(random256BitsArr);
expect(address.toBytes()).toEqual(arrayB256);
expect(address.toB256()).toEqual(hexed256BitsStr);
expect(arrayify(address.toB256())).toEqual(arrayB256);
The Contract id
property has the AbstractAddress type. This means that a contract ID can be converted amoung all the supported convertions from the AbstractClass
.
import { FUEL_NETWORK_URL } from 'fuels';
const address = Address.fromRandom();
const contractLike = new Contract(address, abi, provider);
expect(address.equals(<Address>contractLike.id)).toBeTruthy();
The Wallet address
property has the AbstractAddress type. So just like a contract ID, it can be converted amoung all the supported convertions from the AbstractClass
.
const address = Address.fromRandom();
const wallet: WalletLocked = Wallet.fromAddress(address, provider);
// we use the cast here to cast from `AbstractAddress` to `Address`
expect(address.equals(<Address>wallet.address)).toBeTruthy();
expect(wallet.address.toBytes()).toEqual(arrayify(wallet.address.toB256()));
Asset IDs have the type of b256 . The following example shows how to create an Address
from an b256
type:
import { ZeroBytes32 } from 'fuels';
const assetId: string = ZeroBytes32;
const address1 = Address.fromString(assetId);
const address2 = Address.fromB256(assetId);
const address3 = Address.fromDynamicInput(assetId);
expect(address1.toB256()).toEqual(assetId);
expect(address2.toB256()).toEqual(assetId);
expect(address3.toB256()).toEqual(assetId);
// consistent bytes conversion
expect(arrayify(assetId)).toEqual(arrayify(address1));
By following this guide, you should now be able to convert between Fuels native types using helper functions.
Was this page helpful?