@wormhole-foundation/sdk-evm
Version:
SDK for EVM chains, used in conjunction with @wormhole-foundation/sdk
82 lines • 3.23 kB
JavaScript
Object.defineProperty(exports, "__esModule", { value: true });
exports.EvmAddress = exports.EvmZeroAddress = void 0;
const sdk_connect_1 = require("@wormhole-foundation/sdk-connect");
const ethers_1 = require("ethers");
const types_js_1 = require("./types.js");
exports.EvmZeroAddress = '0x0000000000000000000000000000000000000000';
class EvmAddress {
static byteSize = 20;
static platform = types_js_1._platform;
type = 'Native';
// stored as checksum address
address;
constructor(address) {
if (EvmAddress.instanceof(address)) {
const a = address;
this.address = a.address;
return;
}
if (typeof address === 'string') {
if (!EvmAddress.isValidAddress(address))
throw new Error(`Invalid EVM address, expected ${EvmAddress.byteSize}-byte hex string but got ${address}`);
this.address = (0, ethers_1.getAddress)(address);
}
else if (address instanceof Uint8Array) {
address = this.trimUniversalAddress(address);
this.address = (0, ethers_1.getAddress)(sdk_connect_1.encoding.hex.encode(address));
}
else if (sdk_connect_1.UniversalAddress.instanceof(address)) {
const addressBytes = this.trimUniversalAddress(address.toUint8Array());
this.address = (0, ethers_1.getAddress)(sdk_connect_1.encoding.hex.encode(addressBytes));
}
else
throw new Error(`Invalid EVM address ${address}`);
}
unwrap() {
return this.address;
}
toString() {
return this.address;
}
toNative() {
return this;
}
toUint8Array() {
return sdk_connect_1.encoding.hex.decode(this.address);
}
toUniversalAddress() {
return new sdk_connect_1.UniversalAddress(this.address, 'hex');
}
trimUniversalAddress(address) {
if (address.length === EvmAddress.byteSize)
return address;
if (address.length < EvmAddress.byteSize)
throw new Error(`Invalid evm address, expected ${EvmAddress.byteSize} bytes`);
if (address.length !== sdk_connect_1.UniversalAddress.byteSize)
throw new Error(`Invalid universal address, expected ${sdk_connect_1.UniversalAddress.byteSize} bytes`);
// If the address is longer than 20 bytes, it is a universal address
// that has been padded with 12 bytes of zeros
if (sdk_connect_1.encoding.bignum.decode(address.slice(0, 12)) !== 0n) {
throw new Error(`Invalid EVM address ${address} expected first 12 bytes to be 0s`);
}
return address.slice(12);
}
static isValidAddress(address) {
return (0, ethers_1.isAddress)(address);
}
static instanceof(address) {
return address.constructor.platform === EvmAddress.platform;
}
equals(other) {
if (EvmAddress.instanceof(other)) {
return other.address === this.address;
}
else {
return other.equals(this.toUniversalAddress());
}
}
}
exports.EvmAddress = EvmAddress;
(0, sdk_connect_1.registerNative)(types_js_1._platform, EvmAddress);
//# sourceMappingURL=address.js.map
;