Icon Link地址

在 Sway 中,Address 类型作为对原始 b256 类型的类型安全包装器。SDK 采用了不同的方法,并为 Address 类型提供了自己的抽象。

Icon LinkAbstractAddress

SDK 定义了 AbstractAddress 类,它提供了一组实用函数,用于轻松操作和在不同地址格式之间进行转换。

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;
}

Icon LinkAddress 类

除了符合 AbstractAddress 的接口之外,Address 类还定义了一个属性;bech32Address,它是 Bech32 类型。

readonly bech32Address: Bech32Address;

Icon Link创建地址

由于 AbstractAddress 类提供的实用函数,有几种方法可以创建 Address 实例:

Icon LinkBech32 地址创建

要从 Bech32 地址创建 Address ,请使用以下代码片段:

const ADDRESS_BECH32 = 'fuel1elnmzsav56dqnp95sx4e2pckq36cvae9ser44m5zlvgtwxw49fmqd7e42e';
 
const address = new Address(ADDRESS_BECH32);
 
expect(address.toString()).toEqual(ADDRESS_BECH32);
expect(address.bech32Address).toEqual(ADDRESS_BECH32);

Icon Link从公钥创建

要从公钥创建 Address ,请使用以下代码片段:

const wallet = Wallet.generate({
  provider,
});
 
const address = Address.fromPublicKey(wallet.publicKey);
 
expect(address).toEqual(wallet.address);

Icon Link从 256 位地址创建

要从 256 位地址创建 Address ,请使用以下代码片段:

const b256 = '0xbebd3baab326f895289ecbd4210cf886ce41952316441ae4cac35f00f0e882a6';
 
const address = Address.fromB256(b256);
 
expect(address.toB256()).toEqual(b256);

Icon Link实用函数

Address 类还提供了一些实用函数:

  1. fromString: 从可能是 Bech32B256 地址的模糊源创建一个新的 Address
const address = Address.fromRandom();
 
const addressCloneFromBech = Address.fromString(address.toString());
const addressCloneFromB256 = Address.fromString(address.toB256());
 
expect(addressCloneFromBech.equals(addressCloneFromB256));
  1. fromDynamicInput: 当地址源未知时创建一个新的 Address
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();
  1. equals: 正如您可能已经注意到的,equals 函数可以比较地址实例:
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();