EvmAddress
以太坊虚拟机 (EVM) 地址可以使用 EvmAddress
类型表示。其定义与 Sway 标准库类型相匹配,是一个围绕内部 Bits256
值的 Struct
包装器。
// #import { EvmAddress };
const evmAddress: EvmAddress = {
bits: Bits256,
};
EVM 地址仅有 20 字节,因此 Bits256
值的前 12 字节设置为 0。在 SDK 中,可以实例化一个 Address
,并使用 toEvmAddress()
函数将其转换为一个包装的、与 Sway 兼容的 EVM 地址:
// #import { EvmAddress, Address };
const b256Address = '0xbebd3baab326f895289ecbd4210cf886ce41952316441ae4cac35f00f0e882a6';
const address = Address.fromB256(b256Address);
const evmAddress: EvmAddress = address.toEvmAddress();
EvmAddress
类型可以与您的合约调用集成。考虑以下可以比较和返回 EVM 地址的合约:
contract;
use std::vm::evm::evm_address::EvmAddress;
configurable {
B256_ADDR: b256 = 0xbebd3baab326f895289ecbd4210cf886ce41952316441ae4cac35f00f0e882a6,
}
abi EvmTest {
fn echo_address() -> EvmAddress;
fn echo_address_comparison(evm_addr: EvmAddress) -> bool;
}
impl EvmTest for Contract {
fn echo_address() -> EvmAddress {
return EvmAddress::from(B256_ADDR);
}
fn echo_address_comparison(evm_addr: EvmAddress) -> bool {
let evm_addr2 = EvmAddress::from(B256_ADDR);
evm_addr == evm_addr2
}
}
可以使用 SDK 并将 EvmAddress
传递给合约函数,如下所示:
// #import { EvmAddress };
const evmAddress: EvmAddress = {
bits: Bits256,
};
const { value } = await contract.functions.echo_address_comparison(evmAddress).simulate();
expect(value).toBeTruthy();
并验证返回的值:
// #import { EvmAddress };
const evmAddress: EvmAddress = {
bits: Bits256,
};
const { value } = await contract.functions.echo_address().simulate();
expect(value).toEqual(evmAddress);