Address
In Sway, the Address type serves as a type-safe wrapper around the primitive b256 type. The SDK takes a different approach and has its own abstraction for the Address type.
AbstractAddress Class
The SDK defines the AbstractAddress class, which provides a set of utility functions for easy manipulation and conversion between address formats.
export abstract class AbstractAddress {
abstract toJSON(): string;
abstract toString(): string;
abstract toAddress(): Bech32Address;
abstract toB256(): B256Address;
abstract toHexString(): string;
abstract toBytes(): Uint8Array;
abstract equals(other: AbstractAddress): boolean;
}Address Class
Besides conforming to the interface of the AbstractAddress, the Address class also defines one property; bech32Address, which is of the Bech32 type.
readonly bech32Address: Bech32Address;Creating an Address
Thanks to the utility functions provided by the AbstractAddress class, there are several ways to create an Address instance:
From a Bech32 Address
To create an Address from a Bech32 address, use the following code snippet:
const ADDRESS_BECH32 = 'fuel1elnmzsav56dqnp95sx4e2pckq36cvae9ser44m5zlvgtwxw49fmqd7e42e';
const address = new Address(ADDRESS_BECH32);
expect(address.toString()).toEqual(ADDRESS_BECH32);
expect(address.bech32Address).toEqual(ADDRESS_BECH32);From a Public Key
To create an Address from a public key, use the following code snippet:
const wallet = Wallet.generate({
provider,
});
const address = Address.fromPublicKey(wallet.publicKey);
expect(address).toEqual(wallet.address);From a 256-bit Address
To create an Address from a 256-bit address, use the following code snippet:
const b256 = '0xbebd3baab326f895289ecbd4210cf886ce41952316441ae4cac35f00f0e882a6';
const address = Address.fromB256(b256);
expect(address.toB256()).toEqual(b256);Utility Functions
The Address class also provides some practical utility functions:
fromString: Create a newAddressfrom an ambiguous source that may be aBech32orB256address:
const address = Address.fromRandom();
const addressCloneFromBech = Address.fromString(address.toString());
const addressCloneFromB256 = Address.fromString(address.toB256());
expect(addressCloneFromBech.equals(addressCloneFromB256));fromDynamicInput: Create a newAddresswhen the address source is unknown:
const dataFromInput: string =
'0xf1e92c42b90934aa6372e30bc568a326f6e66a1a0288595e6e3fbd392a4f3e6e';
// if the input string can't be resolved this will throw an error
const someAddress = Address.fromDynamicInput(dataFromInput);
expect(someAddress).toBeTruthy();equals:As you may already notice, theequalsfunction can compare addresses instances:
const address = Address.fromRandom();
const addressCloneFromBech = Address.fromString(address.toString());
const addressCloneFromB256 = Address.fromString(address.toB256());
expect(address.equals(addressCloneFromBech)).toBeTruthy();
expect(address.equals(addressCloneFromB256)).toBeTruthy();