'use strict'; var aptos2 = require('aptos'); var invariant2 = require('tiny-invariant'); var lzDefinitions = require('@layerzerolabs/lz-definitions'); var crypto = require('crypto'); var sha3 = require('@noble/hashes/sha3'); var utils = require('@noble/hashes/utils'); var bip39 = require('bip39'); var BN = require('bn.js'); var extendedBuffer = require('extended-buffer'); function _interopDefault (e) { return e && e.__esModule ? e : { default: e }; } function _interopNamespace(e) { if (e && e.__esModule) return e; var n = Object.create(null); if (e) { Object.keys(e).forEach(function (k) { if (k !== 'default') { var d = Object.getOwnPropertyDescriptor(e, k); Object.defineProperty(n, k, d.get ? d : { enumerable: true, get: function () { return e[k]; } }); } }); } n.default = e; return Object.freeze(n); } var aptos2__namespace = /*#__PURE__*/_interopNamespace(aptos2); var invariant2__default = /*#__PURE__*/_interopDefault(invariant2); var crypto__default = /*#__PURE__*/_interopDefault(crypto); var bip39__namespace = /*#__PURE__*/_interopNamespace(bip39); var BN__default = /*#__PURE__*/_interopDefault(BN); var __defProp = Object.defineProperty; var __export = (target, all) => { for (var name in all) __defProp(target, name, { get: all[name], enumerable: true }); }; // src/constants.ts var constants_exports = {}; __export(constants_exports, { BRIDGE_ADDRESS: () => BRIDGE_ADDRESS, BRIDGE_PRECRIME_ADDRESS: () => BRIDGE_PRECRIME_ADDRESS, COUNTER_ADDRESS: () => COUNTER_ADDRESS, EXECUTOR_ADDRESS: () => EXECUTOR_ADDRESS, EXECUTOR_EXT_ADDRESS: () => EXECUTOR_EXT_ADDRESS, FAUCET_URL: () => FAUCET_URL, LAYERZERO_ADDRESS: () => LAYERZERO_ADDRESS, LAYERZERO_APPS_ADDRESS: () => LAYERZERO_APPS_ADDRESS, LAYERZERO_APPS_PUBKEY: () => LAYERZERO_APPS_PUBKEY, NODE_URL: () => NODE_URL, OFT_PRECRIME_ADDRESS: () => OFT_PRECRIME_ADDRESS, ORACLE_ADDRESS: () => ORACLE_ADDRESS, ORACLE_SIGNER_ADDRESS: () => ORACLE_SIGNER_ADDRESS, RELAYER_SIGNER_ADDRESS: () => RELAYER_SIGNER_ADDRESS }); var NODE_URL = { [lzDefinitions.Environment.MAINNET]: "https://mainnet.aptoslabs.com/v1", [lzDefinitions.Environment.TESTNET]: "https://fullnode.testnet.aptoslabs.com/v1", [lzDefinitions.Environment.DEVNET]: "https://fullnode.devnet.aptoslabs.com/v1", [lzDefinitions.Environment.LOCAL]: "http://127.0.0.1:8080/v1" // 'http://192.168.0.169:8080/v1 }; var FAUCET_URL = { [lzDefinitions.Environment.MAINNET]: "", [lzDefinitions.Environment.TESTNET]: "https://faucet.testnet.aptoslabs.com", [lzDefinitions.Environment.DEVNET]: "https://faucet.devnet.aptoslabs.com", [lzDefinitions.Environment.LOCAL]: "http://127.0.0.1:8081" // 'http://192.168.0.169:8081 }; var LAYERZERO_ADDRESS = { [lzDefinitions.Stage.MAINNET]: "0x54ad3d30af77b60d939ae356e6606de9a4da67583f02b962d2d3f2e481484e90", // MAINNET [lzDefinitions.Stage.TESTNET]: "0x1759cc0d3161f1eb79f65847d4feb9d1f74fb79014698a23b16b28b9cd4c37e3", [lzDefinitions.Stage.SANDBOX]: "0xf2e1e034475dc0439487dd09dfc3950c462f731599e53a6b015dd85502352e68" //TODO(Ethan) double check }; var LAYERZERO_APPS_ADDRESS = { [lzDefinitions.Stage.MAINNET]: "0x43d8cad89263e6936921a0adb8d5d49f0e236c229460f01b14dca073114df2b9", [lzDefinitions.Stage.TESTNET]: "0x2f972c173927006c83277b6e6ae38f83482eba560f343d022f145979020d3621", [lzDefinitions.Stage.SANDBOX]: "0x9b2bac312330430f5e7287a18065e24b55a5e3834459a92be0784177441959bf" //TODO(Ethan) double check }; var ORACLE_ADDRESS = { [lzDefinitions.Stage.MAINNET]: "0xc2846ea05319c339b3b52186ceae40b43d4e9cf6c7350336c3eb0b351d9394eb", // MAINNET [lzDefinitions.Stage.TESTNET]: "0x8ab85d94bf34808386b3ce0f9516db74d2b6d2f1166aa48f75ca641f3adb6c63", [lzDefinitions.Stage.SANDBOX]: "0x86052d5722c3222a88de346aad92a02ace56839487165c6b1bad844e85297d5e" //TODO(Ethan) double check }; var ORACLE_SIGNER_ADDRESS = { [lzDefinitions.Stage.MAINNET]: "0x12e12de0af996d9611b0b78928cd9f4cbf50d94d972043cdd829baa77a78929b", // MAINNET [lzDefinitions.Stage.TESTNET]: "0x47a30bcdb5b5bdbf6af883c7325827f3e40b3f52c3538e9e677e68cf0c0db060", [lzDefinitions.Stage.SANDBOX]: "0x81f5957aa36d8d1515ba5eb95df187fed85185610e7b14fbb0f281b12397f807" //TODO(Ethan) double check }; var RELAYER_SIGNER_ADDRESS = { [lzDefinitions.Stage.MAINNET]: "0x1d8727df513fa2a8785d0834e40b34223daff1affc079574082baadb74b66ee4", // MAINNET [lzDefinitions.Stage.TESTNET]: "0xc192864c4215741051321d44f89c3b7a54840a0b1b7ef5bec6149a07f9df4641", [lzDefinitions.Stage.SANDBOX]: "0x34fb23a3db82f39629506b507fdf886202c7935f74ddc8ecef9dac0bb849b07f" //TODO(Ethan) double check }; var EXECUTOR_ADDRESS = { [lzDefinitions.Stage.MAINNET]: "0x1d8727df513fa2a8785d0834e40b34223daff1affc079574082baadb74b66ee4", // MAINNET [lzDefinitions.Stage.TESTNET]: "0xc192864c4215741051321d44f89c3b7a54840a0b1b7ef5bec6149a07f9df4641", [lzDefinitions.Stage.SANDBOX]: "0xbfef909638ef90885158fdab9f56e216fd811fe25b32ead0bc2a272d66522bb0" //TODO(Ethan) double check }; var EXECUTOR_EXT_ADDRESS = { [lzDefinitions.Stage.MAINNET]: "0xd122ac52d43736e0f524a334fc37b6750884559da7ddf1aee0b11b6ae62643d7", // MAINNET [lzDefinitions.Stage.TESTNET]: "0x39942f4bd78e899f162644b5ec5998a19cb6de1ff8b7321070cb75cf96e5cf6c", [lzDefinitions.Stage.SANDBOX]: "0xd8f318cab62a1142e1cd60f3f090331becc9a462a1a85180de8a99e2a27eadc0" //TODO(Ethan) double check }; var LAYERZERO_APPS_PUBKEY = { [lzDefinitions.Stage.MAINNET]: "0xf57e5a95ae0e2b5f999ac14abd0ff73daf64e6e7e2a1fad024f2e44422e88d76", // MAINNET [lzDefinitions.Stage.TESTNET]: "0xa6d39a1f522da0298a387032952393b1dd2f88ea75423de05c26792930c60ac0", [lzDefinitions.Stage.SANDBOX]: "0x116a5d69ece688512eaf0c0849ca587c6386c36a474d21504a4b6f6ae3a3a487" }; var BRIDGE_ADDRESS = { [lzDefinitions.Stage.MAINNET]: "0xf22bede237a07e121b56d91a491eb7bcdfd1f5907926a9e58338f964a01b17fa", // MAINNET [lzDefinitions.Stage.TESTNET]: "0xec84c05cc40950c86d8a8bed19552f1e8ebb783196bb021c916161d22dc179f7", [lzDefinitions.Stage.SANDBOX]: "0xf52132c1ce7922eb0ac4f5342e8d7d0f817a5af9fb8da23793b058ad8ad38e19" //TODO(Ethan) double check }; var BRIDGE_PRECRIME_ADDRESS = { [lzDefinitions.Stage.MAINNET]: "0x16c7d29eea08ac77dfc4e4665bb56da0ded4e7b82c4c25d535b3d5a5fd6071ad", [lzDefinitions.Stage.TESTNET]: "0x3ed30825c327d8ee51e079c48b12981053fe2bfe07f74a6572726abf4d5c9afc", [lzDefinitions.Stage.SANDBOX]: "0x93b4711e61b1339868ab29f109b2204b452d6997bb5b58cf9d2160addfb71724" // TODO TESTNET_SANDBOX }; var OFT_PRECRIME_ADDRESS = { [lzDefinitions.Stage.MAINNET]: "0x273f3e39593a6723adcecd5aa112158c07239043f79609a0380473157c841e19", [lzDefinitions.Stage.TESTNET]: "0x9fea38276544542be16c4592d1b10cf08d4d9dee33b51eca8a88f17921d985d2", [lzDefinitions.Stage.SANDBOX]: "0xa721bd722a3eff335044536af6e048afcfaae03043da920639f773154f20afd6" // TODO TESTNET_SANDBOX }; var COUNTER_ADDRESS = { [lzDefinitions.Stage.MAINNET]: "", // MAINNET [lzDefinitions.Stage.TESTNET]: "0xf8de36e67ea6dbc7d23db64606e95fba866161343ad8e75d3b95db05ea8c87fe", // [Stage.SANDBOX]: '0x9584ff2b8ec928fc82889c979a0d443ebccde12a0c65840bd302f6254e14c004', [lzDefinitions.Stage.SANDBOX]: "0x2b249feeed4e30deb84f92c0960baf68652757ce2d7d672d566fdb9a34f8720e" }; // src/utils.ts var utils_exports = {}; __export(utils_exports, { GAS_LIMIT_SAFETY_BPS: () => GAS_LIMIT_SAFETY_BPS, ZERO_ADDRESS_BYTES: () => ZERO_ADDRESS_BYTES, ZERO_ADDRESS_HEX: () => ZERO_ADDRESS_HEX, applyGasLimitSafety: () => applyGasLimitSafety, buildStructTagFromTypeInfo: () => buildStructTagFromTypeInfo, bytesToUint8Array: () => bytesToUint8Array, computeGuid: () => computeGuid, convertBytesToUint64: () => convertBytesToUint64, convertToPaddedUint8Array: () => convertToPaddedUint8Array, convertUint64ToBytes: () => convertUint64ToBytes, decodePacket: () => decodePacket, decodePacketString: () => decodePacketString, decodePayload: () => decodePayload, encodePacket: () => encodePacket, fullAddress: () => fullAddress, generateMultisig: () => generateMultisig, getAccountFromMnemonic: () => getAccountFromMnemonic, getAccountFromPrivateKey: () => getAccountFromPrivateKey, getAddressFromPublicKey: () => getAddressFromPublicKey, getLzReceiveTypeArguments: () => getLzReceiveTypeArguments, getResourceAddress: () => getResourceAddress, getSignedTransactionHash: () => getSignedTransactionHash, hashBuffer: () => hashBuffer, hashPacket: () => hashPacket, hexToAscii: () => hexToAscii, isErrorOfApiError: () => isErrorOfApiError, isSameAddress: () => isSameAddress, isTypeInfo: () => isTypeInfo, isZeroAddress: () => isZeroAddress, makeSignFuncWithMultipleSigners: () => makeSignFuncWithMultipleSigners, multiSigSignedBCSTxn: () => multiSigSignedBCSTxn, normalizeTypeInfo: () => normalizeTypeInfo, paddingUint8Array: () => paddingUint8Array, rebuildPacketFromEvent: () => rebuildPacketFromEvent, stringToPaddedUint8Array: () => stringToPaddedUint8Array, stringToUint8Array: () => stringToUint8Array }); var TypeArgumentABI = class _TypeArgumentABI { /** * Constructs a TypeArgumentABI instance. * * @param {string} name - The name of the type argument. */ constructor(name) { this.name = name; } /** * Serializes the TypeArgumentABI instance. * * @param {aptos.BCS.Serializer} serializer - The serializer. */ serialize(serializer) { serializer.serializeStr(this.name); } /** * Deserializes a TypeArgumentABI instance. * * @param {aptos.BCS.Deserializer} deserializer - The deserializer. * @returns {TypeArgumentABI} The deserialized TypeArgumentABI instance. */ static deserialize(deserializer) { const name = deserializer.deserializeStr(); return new _TypeArgumentABI(name); } }; var ArgumentABI = class _ArgumentABI { /** * Constructs an ArgumentABI instance. * * @param {string} name - The name of the argument. * @param {aptos.TxnBuilderTypes.TypeTag} type_tag - The type tag of the argument. */ constructor(name, type_tag) { this.name = name; this.type_tag = type_tag; } /** * Serializes the ArgumentABI instance. * * @param {aptos.BCS.Serializer} serializer - The serializer. */ serialize(serializer) { serializer.serializeStr(this.name); this.type_tag.serialize(serializer); } /** * Deserializes an ArgumentABI instance. * * @param {aptos.BCS.Deserializer} deserializer - The deserializer. * @returns {ArgumentABI} The deserialized ArgumentABI instance. */ static deserialize(deserializer) { const name = deserializer.deserializeStr(); const typeTag = aptos2__namespace.TxnBuilderTypes.TypeTag.deserialize(deserializer); return new _ArgumentABI(name, typeTag); } }; var ScriptABI = class { /** * Deserializes a ScriptABI instance. * * @param {aptos.BCS.Deserializer} deserializer - The deserializer. * @returns {ScriptABI} The deserialized ScriptABI instance. */ static deserialize(deserializer) { const index = deserializer.deserializeUleb128AsU32(); switch (index) { case 0: return TransactionScriptABI.load(deserializer); case 1: return EntryFunctionABI.load(deserializer); default: throw new Error(`Unknown variant index for TransactionPayload: ${index}`); } } }; var TransactionScriptABI = class _TransactionScriptABI extends ScriptABI { /** * Constructs a TransactionScriptABI instance. * * @param {string} name - The entry function name. * @param {string} doc - The documentation. * @param {aptos.BCS.Bytes} code - The code. * @param {aptos.BCS.Seq} ty_args - The type arguments. * @param {aptos.BCS.Seq} args - The arguments. */ constructor(name, doc, code, ty_args, args) { super(); this.name = name; this.doc = doc; this.code = code; this.ty_args = ty_args; this.args = args; } /** * Serializes the TransactionScriptABI instance. * * @param {aptos.BCS.Serializer} serializer - The serializer. */ serialize(serializer) { serializer.serializeU32AsUleb128(0); serializer.serializeStr(this.name); serializer.serializeStr(this.doc); serializer.serializeBytes(this.code); aptos2__namespace.BCS.serializeVector(this.ty_args, serializer); aptos2__namespace.BCS.serializeVector(this.args, serializer); } /** * Loads a TransactionScriptABI instance from a deserializer. * * @param {aptos.BCS.Deserializer} deserializer - The deserializer. * @returns {TransactionScriptABI} The loaded TransactionScriptABI instance. */ static load(deserializer) { const name = deserializer.deserializeStr(); const doc = deserializer.deserializeStr(); const code = deserializer.deserializeBytes(); const tyArgs = aptos2__namespace.BCS.deserializeVector(deserializer, TypeArgumentABI); const args = aptos2__namespace.BCS.deserializeVector(deserializer, ArgumentABI); return new _TransactionScriptABI(name, doc, code, tyArgs, args); } }; var EntryFunctionABI = class _EntryFunctionABI extends ScriptABI { /** * Constructs an EntryFunctionABI instance. * * @param {string} name - The name of the entry function. * @param {aptos.TxnBuilderTypes.ModuleId} module_name - The fully qualified module ID. * @param {string} doc - The documentation. * @param {aptos.BCS.Seq} ty_args - The type arguments. * @param {aptos.BCS.Seq} args - The arguments. */ constructor(name, module_name, doc, ty_args, args) { super(); this.name = name; this.module_name = module_name; this.doc = doc; this.ty_args = ty_args; this.args = args; } /** * Serializes the EntryFunctionABI instance. * * @param {aptos.BCS.Serializer} serializer - The serializer. */ serialize(serializer) { serializer.serializeU32AsUleb128(1); serializer.serializeStr(this.name); this.module_name.serialize(serializer); serializer.serializeStr(this.doc); aptos2__namespace.BCS.serializeVector(this.ty_args, serializer); aptos2__namespace.BCS.serializeVector(this.args, serializer); } /** * Loads an EntryFunctionABI instance from a deserializer. * * @param {aptos.BCS.Deserializer} deserializer - The deserializer. * @returns {EntryFunctionABI} The loaded EntryFunctionABI instance. */ static load(deserializer) { const name = deserializer.deserializeStr(); const moduleName = aptos2__namespace.TxnBuilderTypes.ModuleId.deserialize(deserializer); const doc = deserializer.deserializeStr(); const tyArgs = aptos2__namespace.BCS.deserializeVector(deserializer, TypeArgumentABI); const args = aptos2__namespace.BCS.deserializeVector(deserializer, ArgumentABI); return new _EntryFunctionABI(name, moduleName, doc, tyArgs, args); } }; // src/utils.ts var ZERO_ADDRESS_HEX = fullAddress("0x0").toString(); var ZERO_ADDRESS_BYTES = fullAddress("0x0").toUint8Array(); var GAS_LIMIT_SAFETY_BPS = 2e3; function encodePacket(packet) { const encoded_packet = new extendedBuffer.ExtendedBuffer(); encoded_packet.writeBuffer(new BN__default.default(packet.nonce.toString()).toArrayLike(Buffer, "be", 8)); encoded_packet.writeUInt16BE(new BN__default.default(packet.src_chain_id).toNumber()); encoded_packet.writeBuffer(packet.src_address); encoded_packet.writeUInt16BE(new BN__default.default(packet.dst_chain_id).toNumber()); encoded_packet.writeBuffer(packet.dst_address); encoded_packet.writeBuffer(packet.payload); return encoded_packet.buffer; } function computeGuid(packet) { const encoded_packet = new extendedBuffer.ExtendedBuffer(); encoded_packet.writeBuffer(new BN__default.default(packet.nonce.toString()).toArrayLike(Buffer, "be", 8)); encoded_packet.writeUInt16BE(new BN__default.default(packet.src_chain_id).toNumber()); encoded_packet.writeBuffer(packet.src_address); encoded_packet.writeUInt16BE(new BN__default.default(packet.dst_chain_id).toNumber()); encoded_packet.writeBuffer(packet.dst_address); return hashBuffer(encoded_packet.buffer); } async function decodePacket(buf, getAddressSizeOfChain) { const extendedBuffer$1 = new extendedBuffer.ExtendedBuffer(); extendedBuffer$1.writeBuffer(buf); const nonce = BigInt(new BN__default.default(Uint8Array.from(extendedBuffer$1.readBuffer(8, true)), "be").toString()); const src_chain_id = extendedBuffer$1.readUInt16BE(); const src_address = extendedBuffer$1.readBuffer(32, true); const dst_chain_id = extendedBuffer$1.readUInt16BE(); let addressSize = 0; if (typeof getAddressSizeOfChain === "number") { addressSize = getAddressSizeOfChain; } else if (typeof getAddressSizeOfChain === "function") { addressSize = await getAddressSizeOfChain(dst_chain_id); } const dst_address = extendedBuffer$1.readBuffer(addressSize, true); const payload = extendedBuffer$1.readBuffer(extendedBuffer$1.getReadableSize(), true); return { nonce, src_chain_id, src_address, dst_chain_id, dst_address, payload }; } async function decodePacketString(encodedPacket, dstAddressSize) { return decodePacket(Buffer.from(aptos2__namespace.HexString.ensure(encodedPacket).toUint8Array()), dstAddressSize); } function hashBuffer(buf) { return crypto__default.default.createHash("sha3-256").update(buf).digest("hex"); } function hashPacket(packet) { return hashBuffer(encodePacket(packet)); } async function rebuildPacketFromEvent(event, getAddressSizeOfChain) { const hexValue = event.data.encoded_packet.replace(/^0x/, ""); const input = Buffer.from(hexValue, "hex"); return decodePacket(input, getAddressSizeOfChain); } async function generateMultisig(publicKeys, threshold) { const multiSigPublicKey = new aptos2__namespace.TxnBuilderTypes.MultiEd25519PublicKey( publicKeys.map((publicKey) => new aptos2__namespace.TxnBuilderTypes.Ed25519PublicKey(publicKey)), threshold ); const authKey = aptos2__namespace.TxnBuilderTypes.AuthenticationKey.fromMultiEd25519PublicKey(multiSigPublicKey); return [multiSigPublicKey, authKey.derivedAddress().toString()]; } function multiSigSignedBCSTxn(pubkey, rawTx, signatures, bitmap) { const txBuilder = new aptos2__namespace.TransactionBuilderMultiEd25519(() => { return new aptos2__namespace.TxnBuilderTypes.MultiEd25519Signature( signatures.map((signature) => new aptos2__namespace.TxnBuilderTypes.Ed25519Signature(signature.toUint8Array())), aptos2__namespace.TxnBuilderTypes.MultiEd25519Signature.createBitmap(bitmap) ); }, pubkey); return txBuilder.sign(rawTx); } function fullAddress(address) { const rawValue = aptos2__namespace.HexString.ensure(address).noPrefix(); return aptos2__namespace.HexString.ensure( Buffer.concat([Buffer.alloc(64 - rawValue.length, "0"), Buffer.from(rawValue)]).toString() ); } function isHexStrict(hex) { return /^(-)?0x[0-9a-f]*$/i.test(hex); } function hexToAscii(hex) { invariant2__default.default(isHexStrict(hex), `Invalid hex string ${hex}`); let str = ""; let i = 0; const l = hex.length; if (hex.startsWith("0x")) { i = 2; } for (; i < l; i += 2) { const code = parseInt(hex.slice(i, i + 2), 16); str += String.fromCharCode(code); } return str; } function isSameAddress(a, b) { return fullAddress(a).toString() == fullAddress(b).toString(); } function isZeroAddress(a) { return isSameAddress(a, ZERO_ADDRESS_HEX); } function convertUint64ToBytes(number) { return aptos2__namespace.BCS.bcsSerializeUint64(number).reverse(); } function convertBytesToUint64(bytes) { return BigInt(new BN__default.default(bytes, "be").toString()); } function isErrorOfApiError(e, status) { if (e instanceof aptos2__namespace.ApiError) { return e.status === status; } else if (e instanceof Error && e.constructor.name.match(/ApiError[0-9]*/)) { if (Object.prototype.hasOwnProperty.call(e, "vmErrorCode")) { const err = e; return err.status === status; } else if (Object.prototype.hasOwnProperty.call(e, "request")) { const err = e; return err.status === status; } } else if (e instanceof Error) { if (Object.prototype.hasOwnProperty.call(e, "status")) { return e.status === status; } } return false; } function bytesToUint8Array(data, length) { return paddingUint8Array(data, length); } function convertToPaddedUint8Array(str, length) { return stringToPaddedUint8Array(str, length); } function stringToPaddedUint8Array(str, length) { const value = stringToUint8Array(str); return paddingUint8Array(value, length); } function paddingUint8Array(bytes, length) { if (bytes.length >= length) { return bytes; } return Uint8Array.from([...new Array(length - bytes.length), ...Array.from(bytes)]); } function stringToUint8Array(str) { const value = str.replace(/^0x/i, ""); const len = value.length + 1 - (value.length + 1) % 2; return Uint8Array.from(Buffer.from(value.padStart(len, "0"), "hex")); } function makeSignFuncWithMultipleSigners(...signers) { return async function(data) { const retval = signers.map((s, index) => { return { signature: s.signBuffer(data), bitmap: index }; }); return Promise.resolve(retval); }; } function applyGasLimitSafety(gasUsed) { return BigInt(gasUsed) * BigInt(1e4 + GAS_LIMIT_SAFETY_BPS) / BigInt(1e4); } function decodePayload(payload) { const extendedBuffer$1 = new extendedBuffer.ExtendedBuffer(); extendedBuffer$1.writeBuffer(payload); const packetType = extendedBuffer$1.readUInt8(); const remoteCoinAddr = extendedBuffer$1.readBuffer(32, true); const receiverBytes = extendedBuffer$1.readBuffer(32, true); const amount = new BN__default.default(extendedBuffer$1.readBuffer(8, true)); return { packetType, remoteCoinAddr, receiverBytes, amount }; } function getSignedTransactionHash(signedTransaction) { const deserializer = new aptos2__namespace.BCS.Deserializer(signedTransaction); const userTxn = aptos2__namespace.TxnBuilderTypes.UserTransaction.load(deserializer); const txnHash = aptos2__namespace.HexString.fromUint8Array(userTxn.hash()).toString(); return txnHash; } function getAddressFromPublicKey(publicKey) { const hash = sha3.sha3_256.create(); hash.update(publicKey.toBytes()); hash.update("\0"); return aptos2__namespace.HexString.fromUint8Array(hash.digest()); } async function getLzReceiveTypeArguments(bytecode, sdk, publicKey, dstAddress, srcChainId, srcAddress, payload) { const uaAddress = aptos2__namespace.HexString.ensure(Buffer.from(dstAddress).toString("hex")); await sdk.LayerzeroModule.Endpoint.getUATypeInfo(uaAddress); const ABIS = [ new TransactionScriptABI( "main", "", bytecode, [], [ new ArgumentABI("src_chain_id", new aptos2__namespace.TypeTagParser("u64").parseTypeTag()), new ArgumentABI("src_address", new aptos2__namespace.TypeTagParser("vector").parseTypeTag()), new ArgumentABI("payload", new aptos2__namespace.TypeTagParser("vector").parseTypeTag()) ] ) ]; const abis = ABIS.map((abi) => { const serializer = new aptos2__namespace.BCS.Serializer(); abi.serialize(serializer); return serializer.getBytes(); }); const builder = new aptos2__namespace.TransactionBuilderABI(abis); const transaction = builder.buildTransactionPayload( "main", [], [srcChainId, Uint8Array.from(srcAddress), Uint8Array.from(payload)] ); const address = getAddressFromPublicKey(publicKey); const rawTransaction = await sdk.client.generateRawTransaction(address, transaction, {}); const txns = await sdk.client.simulateTransaction(publicKey, rawTransaction); if (!txns[0].success) { throw new Error(txns[0].vm_status); } const result = txns.flatMap((txn) => txn.changes).filter( (change) => change.type === "write_resource" && change.data.type.match(/::executor_ext::TypeArguments$/) ).map((change) => change.data.data).flatMap((r) => { return r.types; }).map((t) => { const account_address = fullAddress(t.account_address).toString(); const module_name = hexToAscii(t.module_name); const struct_name = hexToAscii(t.struct_name); return `${account_address}::${module_name}::${struct_name}`; }); return result; } var DERIVE_RESOURCE_ACCOUNT_SCHEME = 255; function getResourceAddress(source, seed) { const bytes = [...aptos2__namespace.HexString.ensure(source).toUint8Array(), ...seed, DERIVE_RESOURCE_ACCOUNT_SCHEME]; const hash = crypto__default.default.createHash("sha3-256").update(Buffer.from(bytes)).digest("hex"); return aptos2__namespace.HexString.ensure(hash); } function getAccountFromPrivateKey(key) { const privateKeyBytes = Uint8Array.from(Buffer.from(aptos2__namespace.HexString.ensure(key).noPrefix(), "hex")); return new aptos2__namespace.AptosAccount(privateKeyBytes); } function getAccountFromMnemonic(mnemonic, path = "m/44'/637'/0'/0'/0'") { if (!aptos2__namespace.AptosAccount.isValidPath(path)) { throw new Error(`Invalid derivation path: ${path}`); } const normalizeMnemonics = mnemonic.trim().split(/\s+/).map((part) => part.toLowerCase()).join(" "); { const { key } = aptos2__namespace.derivePath(path, utils.bytesToHex(bip39__namespace.mnemonicToSeedSync(normalizeMnemonics))); return new aptos2__namespace.AptosAccount(new Uint8Array(key)); } } function normalizeTypeInfo(typeInfo) { const account_address = aptos2__namespace.HexString.ensure(typeInfo.account_address).toString(); const module_name = hexToAscii(typeInfo.module_name); const struct_name = hexToAscii(typeInfo.struct_name); return { account_address, module_name, struct_name }; } function buildStructTagFromTypeInfo(typeInfo) { let info = typeInfo; if (typeInfo.module_name.match("/^0x.*/i") && typeInfo.struct_name.match(/^0x.*/i)) { info = normalizeTypeInfo(typeInfo); } return `${info.account_address}::${info.module_name}::${info.struct_name}`; } function isTypeInfo(value) { const hasProperty = Object.prototype.hasOwnProperty; return hasProperty.call(value, "account_address") && hasProperty.call(value, "module_name") && hasProperty.call(value, "struct_name"); } // src/modules/channel.ts var Channel = class { /** * Creates an instance of the Channel class. * * @param {SDK} sdk - The SDK instance. */ constructor(sdk) { this.sdk = sdk; this.module = `${sdk.accounts.layerzero}::channel`; } /** * The module name. */ module; /** * Gets outbound events. * * @param {bigint} start - The start index. * @param {number} limit - The limit of events to retrieve. * @returns {Promise} A promise that resolves to an array of events. */ async getOutboundEvents(start, limit) { return this.sdk.client.getEventsByEventHandle( this.sdk.accounts.layerzero, `${this.module}::EventStore`, "outbound_events", { start, limit } ); } /** * Gets inbound events. * * @param {bigint} start - The start index. * @param {number} limit - The limit of events to retrieve. * @returns {Promise} A promise that resolves to an array of events. */ async getInboundEvents(start, limit) { return this.sdk.client.getEventsByEventHandle( this.sdk.accounts.layerzero, `${this.module}::EventStore`, "inbound_events", { start, limit } ); } /** * Gets receive events. * * @param {bigint} start - The start index. * @param {number} limit - The limit of events to retrieve. * @returns {Promise} A promise that resolves to an array of events. */ async getReceiveEvents(start, limit) { return this.sdk.client.getEventsByEventHandle( this.sdk.accounts.layerzero, `${this.module}::EventStore`, "receive_events", { start, limit } ); } /** * Gets the channel state. * * @param {aptos.MaybeHexString} uaAddress - The user address. * @param {aptos.BCS.Uint16} remoteChainId - The remote chain ID. * @param {aptos.BCS.Bytes} remoteAddress - The remote address. * @param {Object} [query] - The query parameters. * @param {bigint | number} [query.ledgerVersion] - The ledger version. * @returns {Promise} A promise that resolves to the channel state. */ async getChannelState(uaAddress, remoteChainId, remoteAddress, query) { const resource = await this.sdk.client.getAccountResource(uaAddress, `${this.module}::Channels`, query); const { states } = resource.data; const pathsHandle = states.handle; return this.sdk.client.getTableItem( pathsHandle, { key_type: `${this.module}::Remote`, value_type: `${this.module}::Channel`, key: { chain_id: remoteChainId.toString(), addr: Buffer.from(remoteAddress).toString("hex") } }, query ); } /** * Gets the outbound nonce. * * @param {aptos.MaybeHexString} uaAddress - The user address. * @param {aptos.BCS.Uint16} remoteChainId - The remote chain ID. * @param {aptos.BCS.Bytes} remoteAddress - The remote address. * @param {Object} [query] - The query parameters. * @param {bigint | number} [query.ledgerVersion] - The ledger version. * @returns {Promise} A promise that resolves to the outbound nonce. */ async getOutboundNonce(uaAddress, remoteChainId, remoteAddress, query) { try { const pathInfo = await this.getChannelState(uaAddress, remoteChainId, remoteAddress, query); const outboundNonce = pathInfo.outbound_nonce; return BigInt(outboundNonce); } catch (e) { if (isErrorOfApiError(e, 404)) { return BigInt(0); } throw e; } } /** * Gets the inbound nonce. * * @param {aptos.MaybeHexString} uaAddress - The user address. * @param {aptos.BCS.Uint16} remoteChainId - The remote chain ID. * @param {aptos.BCS.Bytes} remoteAddress - The remote address. * @param {Object} [query] - The query parameters. * @param {bigint | number} [query.ledgerVersion] - The ledger version. * @returns {Promise} A promise that resolves to the inbound nonce. */ async getInboundNonce(uaAddress, remoteChainId, remoteAddress, query) { try { const pathInfo = await this.getChannelState(uaAddress, remoteChainId, remoteAddress, query); const inboundNonce = pathInfo.inbound_nonce; return BigInt(inboundNonce); } catch (e) { if (isErrorOfApiError(e, 404)) { return BigInt(0); } throw e; } } /** * Gets the payload hash. * * @param {aptos.MaybeHexString} uaAddress - The user address. * @param {aptos.BCS.Uint16} remoteChainId - The remote chain ID. * @param {aptos.BCS.Bytes} remoteAddress - The remote address. * @param {aptos.BCS.Uint64} nonce - The nonce. * @param {Object} [query] - The query parameters. * @param {bigint | number} [query.ledgerVersion] - The ledger version. * @returns {Promise} A promise that resolves to the payload hash. */ async getPayloadHash(uaAddress, remoteChainId, remoteAddress, nonce, query) { try { const pathInfo = await this.getChannelState(uaAddress, remoteChainId, remoteAddress, query); const resource = pathInfo.payload_hashs; return await this.sdk.client.getTableItem( resource.handle, { key_type: "u64", value_type: "vector", key: nonce.toString() }, query ); } catch (e) { if (isErrorOfApiError(e, 404)) { return ""; } throw e; } } /** * Checks if the proof is delivered. * * @param {aptos.MaybeHexString} uaAddress - The user address. * @param {aptos.BCS.Uint16} remoteChainId - The remote chain ID. * @param {aptos.BCS.Bytes} remoteAddress - The remote address. * @param {aptos.BCS.Uint64} nonce - The nonce. * @param {Object} [query] - The query parameters. * @param {bigint | number} [query.ledgerVersion] - The ledger version. * @returns {Promise} A promise that resolves to true if the proof is delivered, false otherwise. */ async isProofDelivered(uaAddress, remoteChainId, remoteAddress, nonce, query) { const inboundNonce = await this.getInboundNonce(uaAddress, remoteChainId, remoteAddress, query); console.log(`inboundNonce: ${inboundNonce}`); console.log(`nonce: ${nonce}`); if (nonce <= inboundNonce) { return true; } const payloadHash = await this.getPayloadHash(uaAddress, remoteChainId, remoteAddress, nonce, query); return payloadHash !== ""; } }; var Endpoint = class { /** * Creates an instance of the Endpoint class. * * @param {SDK} sdk - The SDK instance. */ constructor(sdk) { this.sdk = sdk; this.module = `${sdk.accounts.layerzero}::endpoint`; this.moduleName = "layerzero::endpoint"; } /** * The module name. */ module; /** * The module name with namespace. */ moduleName; /** * Initializes the endpoint. * * @param {aptos.AptosAccount} signer - The signer account. * @param {aptos.BCS.Uint16} localChainId - The local chain ID. * @returns {Promise} A promise that resolves to the transaction. */ async initialize(signer, localChainId) { const transaction = { function: `${this.module}::init`, type_arguments: [], arguments: [localChainId] }; return this.sdk.sendAndConfirmTransaction(signer, transaction); } /** * Gets the local chain ID. * * @returns {Promise} A promise that resolves to the local chain ID or undefined if not found. */ async getLocalChainId() { try { const resource = await this.sdk.client.getAccountResource( this.sdk.accounts.layerzero, `${this.module}::ChainConfig` ); const { local_chain_id } = resource.data; return local_chain_id; } catch (err) { if (err instanceof aptos2.ApiError && err.errorCode === "resource_not_found") { return void 0; } throw err; } } /** * Gets the UA type information. * * @param {aptos.MaybeHexString} uaAddress - The UA address. * @returns {Promise} A promise that resolves to the type information. */ async getUATypeInfo(uaAddress) { const resource = await this.sdk.client.getAccountResource( this.sdk.accounts.layerzero, `${this.module}::UaRegistry` ); const { ua_infos } = resource.data; const typesHandle = ua_infos.handle; const typeInfo = await this.sdk.client.getTableItem(typesHandle, { key_type: "address", value_type: `0x1::type_info::TypeInfo`, key: aptos2__namespace.HexString.ensure(uaAddress).toString() }); const account_address = fullAddress(typeInfo.account_address).toString(); const module_name = hexToAscii(typeInfo.module_name); const struct_name = hexToAscii(typeInfo.struct_name); return { account_address, module_name, struct_name, type: `${account_address}::${module_name}::${struct_name}` }; } /** * Gets the oracle fee. * * @param {aptos.MaybeHexString} oracleAddr - The oracle address. * @param {aptos.BCS.Uint16} dstChainId - The destination chain ID. * @returns {Promise} A promise that resolves to the oracle fee. */ async getOracleFee(oracleAddr, dstChainId) { if (this.sdk.accounts.layerzero === void 0) { throw new Error("endpoint sdk accounts layerzero is undefined when invoke getOracleFee"); } const resource = await this.sdk.client.getAccountResource( this.sdk.accounts.layerzero, `${this.module}::FeeStore` ); const { oracle_fees } = resource.data; const response = await this.sdk.client.getTableItem(oracle_fees.handle, { key_type: `${this.module}::QuoteKey`, value_type: "u64", key: { agent: aptos2__namespace.HexString.ensure(oracleAddr).toString(), chain_id: dstChainId.toString() } }); return BigInt(response); } /** * Gets the register events. * * @param {bigint} start - The start index. * @param {number} limit - The limit of events to fetch. * @returns {Promise} A promise that resolves to an array of events. */ async getRegisterEvents(start, limit) { if (this.sdk.accounts.layerzero === void 0) { throw new Error("endpoint sdk accounts layerzero is undefined when invoke getRegisterEvents"); } return this.sdk.client.getEventsByEventHandle( this.sdk.accounts.layerzero, `${this.module}::UaRegistry`, "register_events", { start, limit } ); } /** * Quotes the fee. * * @param {aptos.MaybeHexString} uaAddress - The UA address. * @param {aptos.BCS.Uint16} dstChainId - The destination chain ID. * @param {aptos.BCS.Bytes} adapterParams - The adapter parameters. * @param {number} payloadSize - The payload size. * @param {Object} [query] - The query parameters. * @param {bigint | number} [query.ledgerVersion] - The ledger version. * @returns {Promise} A promise that resolves to the quoted fee. */ async quoteFee(uaAddress, dstChainId, adapterParams, payloadSize, query) { let totalFee = BigInt( await this.sdk.LayerzeroModule.Uln.Config.quoteFee(uaAddress, dstChainId, payloadSize, query) ); const [executor] = await this.sdk.LayerzeroModule.ExecutorConfig.getExecutor(uaAddress, dstChainId, query); totalFee += await this.sdk.LayerzeroModule.Executor.quoteFee(executor, dstChainId, adapterParams, query); return totalFee; } /** * Creates a payload for registering an executor. * * @param {string} executorType - The executor type. * @returns {aptos.Types.EntryFunctionPayload} The payload. */ registerExecutorPayload(executorType) { return { function: `${this.module}::register_executor`, type_arguments: [executorType], arguments: [] }; } /** * Registers an executor. * * @param {aptos.AptosAccount} signer - The signer account. * @param {string} executorType - The executor type. * @returns {Promise} A promise that resolves to the transaction. */ async registerExecutor(signer, executorType) { const transaction = this.registerExecutorPayload(executorType); return this.sdk.sendAndConfirmTransaction(signer, transaction); } /** * Gets the executor capability. * * @param {string} [version='1'] - The version. * @returns {Promise} A promise that resolves to the executor capability or undefined if not found. */ async getExecutorCap(version = "1") { try { const resource = await this.sdk.client.getAccountResource( this.sdk.accounts.layerzero, `${this.module}::Capabilities` ); const { executor_caps } = resource.data; const { handle } = executor_caps; const executorCap = await this.sdk.client.getTableItem(handle, { key_type: "u64", value_type: `${this.sdk.accounts.executor_auth}::executor_cap::ExecutorCapability`, key: version }); return executorCap.version; } catch (err) { if (err instanceof aptos2.ApiError && (err.errorCode === "resource_not_found" || err.errorCode === "table_item_not_found")) { return void 0; } throw err; } } }; // src/format/bytecode.ts var Bytecode = class { /** * Deserializes the bytecode. * @param {BCS.Deserializer} deserializer - The deserializer. * @returns {Bytecode} The deserialized bytecode. * @throws {Error} If the method is not implemented. */ static deserialize(deserializer) { throw new Error("Not implemented"); } }; var UnaryBytecode = class _UnaryBytecode extends Bytecode { /** * Creates an instance of UnaryBytecode. * @param {Opcodes} opcode - The opcode. */ constructor(opcode) { super(); this.opcode = opcode; } /** * Serializes the unary bytecode. * @param {BCS.Serializer} serializer - The serializer. */ serialize(serializer) { serializer.serializeU8(this.opcode); } /** * Deserializes the unary bytecode. * @param {BCS.Deserializer} deserializer - The deserializer. * @returns {Bytecode} The deserialized unary bytecode. */ static deserialize(deserializer) { const opcode = deserializer.deserializeU8(); return new _UnaryBytecode(opcode); } }; var BinaryBytecode = class _BinaryBytecode extends Bytecode { /** * Creates an instance of BinaryBytecode. * @param {Opcodes} opcode - The opcode. * @param {Index} operand - The operand. */ constructor(opcode, operand) { super(); this.opcode = opcode; this.operand = operand; } /** * Serializes the binary bytecode. * @param {BCS.Serializer} serializer - The serializer. */ serialize(serializer) { serializer.serializeU8(this.opcode); this.operand.serialize(serializer); } /** * Deserializes the binary bytecode. * @param {BCS.Deserializer} deserializer - The deserializer. * @returns {Bytecode} The deserialized binary bytecode. */ static deserialize(deserializer) { const opcode = deserializer.deserializeU8(); const index = Index.deserialize(deserializer); return new _BinaryBytecode(opcode, index); } }; var ROP = class extends UnaryBytecode { }; var RET = class extends UnaryBytecode { }; var BR_TRUE = class extends BinaryBytecode { }; var BR_FALSE = class extends BinaryBytecode { }; var BRANCH = class extends BinaryBytecode { }; var LD_U8 = class _LD_U8 extends Bytecode { /** * Creates an instance of LD_U8. * @param {Opcodes} opcode - The opcode. * @param {BCS.Uint8} value - The value. */ constructor(opcode, value) { super(); this.opcode = opcode; this.value = value; } /** * Serializes the LD_U8 bytecode. * @param {BCS.Serializer} serializer - The serializer. */ serialize(serializer) { serializer.serializeU8(this.opcode); serializer.serializeU8(this.value); } /** * Deserializes the LD_U8 bytecode. * @param {BCS.Deserializer} deserializer - The deserializer. * @returns {Bytecode} The deserialized LD_U8 bytecode. */ static deserialize(deserializer) { const opcode = deserializer.deserializeU8(); const value = deserializer.deserializeU8(); return new _LD_U8(opcode, value); } }; var LD_U64 = class _LD_U64 extends Bytecode { /** * Creates an instance of LD_U64. * @param {Opcodes} opcode - The opcode. * @param {BCS.Uint64} value - The value. */ constructor(opcode, value) { super(); this.opcode = opcode; this.value = value; } /** * Serializes the LD_U64 bytecode. * @param {BCS.Serializer} serializer - The serializer. */ serialize(serializer) { serializer.serializeU8(this.opcode); serializer.serializeU64(this.value); } /** * Deserializes the LD_U64 bytecode. * @param {BCS.Deserializer} deserializer - The deserializer. * @returns {Bytecode} The deserialized LD_U64 bytecode. */ static deserialize(deserializer) { const opcode = deserializer.deserializeU8(); const value = deserializer.deserializeU64(); return new _LD_U64(opcode, value); } }; var LD_U128 = class _LD_U128 extends Bytecode { /** * Creates an instance of LD_U128. * @param {Opcodes} opcode - The opcode. * @param {BCS.Uint128} value - The value. */ constructor(opcode, value) { super(); this.opcode = opcode; this.value = value; } /** * Serializes the LD_U128 bytecode. * @param {BCS.Serializer} serializer - The serializer. */ serialize(serializer) { serializer.serializeU8(this.opcode); serializer.serializeU128(this.value); } /** * Deserializes the LD_U128 bytecode. * @param {BCS.Deserializer} deserializer - The deserializer. * @returns {Bytecode} The deserialized LD_U128 bytecode. */ static deserialize(deserializer) { const opcode = deserializer.deserializeU8(); const value = deserializer.deserializeU128(); return new _LD_U128(opcode, value); } }; var CAST_U8 = class extends UnaryBytecode { }; var CAST_U64 = class extends UnaryBytecode { }; var CAST_U128 = class extends UnaryBytecode { }; var LD_CONST = class extends BinaryBytecode { }; var LD_TRUE = class extends UnaryBytecode { }; var LD_FALSE = class extends UnaryBytecode { }; var COPY_LOC = class extends BinaryBytecode { }; var MOVE_LOC = class extends BinaryBytecode { }; var ST_LOC = class extends BinaryBytecode { }; var MUT_BORROW_LOC = class extends BinaryBytecode { }; var IMM_BORROW_LOC = class extends BinaryBytecode { }; var MUT_BORROW_FIELD = class extends BinaryBytecode { }; var MUT_BORROW_FIELD_GENERIC = class extends BinaryBytecode { }; var IMM_BORROW_FIELD = class extends BinaryBytecode { }; var IMM_BORROW_FIELD_GENERIC = class extends BinaryBytecode { }; var CALL = class extends BinaryBytecode { }; var CALL_GENERIC = class extends BinaryBytecode { }; var PACK = class extends BinaryBytecode { }; var PACK_GENERIC = class extends BinaryBytecode { }; var UNPACK = class extends BinaryBytecode { }; var UNPACK_GENERIC = class extends BinaryBytecode { }; var READ_REF = class extends UnaryBytecode { }; var WRITE_REF = class extends UnaryBytecode { }; var ADD = class extends UnaryBytecode { }; var SUB = class extends UnaryBytecode { }; var MUL = class extends UnaryBytecode { }; var MOD = class extends UnaryBytecode { }; var DIV = class extends UnaryBytecode { }; var BIT_OR = class extends UnaryBytecode { }; var BIT_AND = class extends UnaryBytecode { }; var XOR = class extends UnaryBytecode { }; var SHL = class extends UnaryBytecode { }; var SHR = class extends UnaryBytecode { }; var OR = class extends UnaryBytecode { }; var AND = class extends UnaryBytecode { }; var NOT = class extends UnaryBytecode { }; var EQ = class extends UnaryBytecode { }; var NEQ = class extends UnaryBytecode { }; var LT = class extends UnaryBytecode { }; var GT = class extends UnaryBytecode { }; var LE = class extends UnaryBytecode { }; var GE = class extends UnaryBytecode { }; var ABORT = class extends UnaryBytecode { }; var NOP = class extends UnaryBytecode { }; var EXISTS = class extends BinaryBytecode { }; var EXISTS_GENERIC = class extends BinaryBytecode { }; var MUT_BORROW_GLOBAL = class extends BinaryBytecode { }; var MUT_BORROW_GLOBAL_GENERIC = class extends BinaryBytecode { }; var IMM_BORROW_GLOBAL = class extends BinaryBytecode { }; var IMM_BORROW_GLOBAL_GENERIC = class extends BinaryBytecode { }; var MOVE_FROM = class extends BinaryBytecode { }; var MOVE_FROM_GENERIC = class extends BinaryBytecode { }; var MOVE_TO = class extends BinaryBytecode { }; var MOVE_TO_GENERIC = class extends BinaryBytecode { }; var FREEZE_REF = class extends UnaryBytecode { }; var VEC_PACK = class _VEC_PACK extends Bytecode { /** * Creates an instance of VEC_PACK. * @param {Opcodes} opcode - The opcode. * @param {Index} operand - The operand. * @param {BCS.Uint64} value - The value. */ constructor(opcode, operand, value) { super(); this.opcode = opcode; this.operand = operand; this.value = value; } /** * Serializes the VEC_PACK bytecode. * @param {BCS.Serializer} serializer - The serializer. */ serialize(serializer) { serializer.serializeU8(this.opcode); this.operand.serialize(serializer); serializer.serializeU64(this.value); } /** * Deserializes the VEC_PACK bytecode. * @param {BCS.Deserializer} deserializer - The deserializer. * @returns {Bytecode} The deserialized VEC_PACK bytecode. */ static deserialize(deserializer) { const opcode = deserializer.deserializeU8(); const operand = Index.deserialize(deserializer); const value = deserializer.deserializeU64(); return new _VEC_PACK(opcode, operand, value); } }; var VEC_LEN = class extends BinaryBytecode { }; var VEC_IMM_BORROW = class extends BinaryBytecode { }; var VEC_MUT_BORROW = class extends BinaryBytecode { }; var VEC_PUSH_BACK = class extends BinaryBytecode { }; var VEC_POP_BACK = class extends BinaryBytecode { }; var VEC_UNPACK = class _VEC_UNPACK extends Bytecode { /** * Creates an instance of VEC_UNPACK. * @param {Opcodes} opcode - The opcode. * @param {Index} operand - The operand. * @param {BCS.Uint64} value - The value. */ constructor(opcode, operand, value) { super(); this.opcode = opcode; this.operand = operand; this.value = value; } /** * Serializes the VEC_UNPACK bytecode. * @param {BCS.Serializer} serializer - The serializer. */ serialize(serializer) { serializer.serializeU8(this.opcode); this.operand.serialize(serializer); serializer.serializeU64(this.value); } /** * Deserializes the VEC_UNPACK bytecode. * @param {BCS.Deserializer} deserializer - The deserializer. * @returns {Bytecode} The deserialized VEC_UNPACK bytecode. */ static deserialize(deserializer) { const opcode = deserializer.deserializeU8(); const operand = Index.deserialize(deserializer); const value = deserializer.deserializeU64(); return new _VEC_UNPACK(opcode, operand, value); } }; var VEC_SWAP = class extends BinaryBytecode { }; var LD_U16 = class _LD_U16 extends Bytecode { /** * Creates an instance of LD_U16. * @param {Opcodes} opcode - The opcode. * @param {BCS.Uint16} value - The value. */ constructor(opcode, value) { super(); this.opcode = opcode; this.value = value; } /** * Serializes the LD_U16 bytecode. * @param {BCS.Serializer} serializer - The serializer. */ serialize(serializer) { serializer.serializeU8(this.opcode); serializer.serializeU16(this.value); } /** * Deserializes the LD_U16 bytecode. * @param {BCS.Deserializer} deserializer - The deserializer. * @returns {Bytecode} The deserialized LD_U16 bytecode. */ static deserialize(deserializer) { const opcode = deserializer.deserializeU8(); const value = deserializer.deserializeU16(); return new _LD_U16(opcode, value); } }; var LD_U32 = class _LD_U32 extends Bytecode { /** * Creates an instance of LD_U32. * @param {Opcodes} opcode - The opcode. * @param {BCS.Uint32} value - The value. */ constructor(opcode, value) { super(); this.opcode = opcode; this.value = value; } /** * Serializes the LD_U32 bytecode. * @param {BCS.Serializer} serializer - The serializer. */ serialize(serializer) { serializer.serializeU8(this.opcode); serializer.serializeU32(this.value); } /** * Deserializes the LD_U32 bytecode. * @param {BCS.Deserializer} deserializer - The deserializer. * @returns {Bytecode} The deserialized LD_U32 bytecode. */ static deserialize(deserializer) { const opcode = deserializer.deserializeU8(); const value = deserializer.deserializeU16(); return new _LD_U32(opcode, value); } }; var CAST_U16 = class extends UnaryBytecode { }; var CAST_U32 = class extends UnaryBytecode { }; var CAST_U256 = class extends UnaryBytecode { }; // src/format/basic.ts var Table = class _Table { /** * Creates an instance of Table. * * @param {BCS.Uint8} kind - The kind of the table. * @param {BCS.Uint32} offset - The offset of the table. * @param {BCS.Uint32} count - The count of the table. */ constructor(kind, offset, count) { this.kind = kind; this.offset = offset; this.count = count; } /** * Deserializes a Table from the given deserializer. * * @param {BCS.Deserializer} deserializer - The deserializer to use. * @returns {Table} The deserialized Table. */ static deserialize(deserializer) { const kind = deserializer.deserializeUleb128AsU32(); const offset = deserializer.deserializeUleb128AsU32(); const count = deserializer.deserializeUleb128AsU32(); return new _Table(kind, offset, count); } /** * Serializes the Table using the given serializer. * * @param {BCS.Serializer} serializer - The serializer to use. */ serialize(serializer) { serializer.serializeU32AsUleb128(this.kind); serializer.serializeU32AsUleb128(this.offset); serializer.serializeU32AsUleb128(this.count); } }; var Tables = class _Tables { /** * Creates an instance of Tables. * * @param {BCS.Seq} tables - The sequence of tables. * @param {BCS.Bytes} data - The associated data. */ constructor(tables, data) { this.tables = tables; this.data = data; } /** * Deserializes Tables from the given deserializer. * * @param {BCS.Deserializer} deserializer - The deserializer to use. * @returns {Tables} The deserialized Tables. */ static deserialize(deserializer) { const count = deserializer.deserializeUleb128AsU32(); let tables = []; for (let i = 0; i < count; i++) { const table = Table.deserialize(deserializer); tables.push(table); } tables = tables.sort((a, b) => a.kind - b.kind); let currentOffset = 0; const tableTypes = /* @__PURE__ */ new Set(); for (const table of tables) { if (table.offset != currentOffset) { throw new Error("Invalid table offset"); } if (table.count == 0) { throw new Error("Invalid table count"); } if (tableTypes.has(table.kind)) { throw new Error("Duplicate table kind"); } tableTypes.add(table.kind); currentOffset += table.count; } const data = deserializer.deserializeFixedBytes(currentOffset); return new _Tables(tables, data); } /** * Serializes the Tables using the given serializer. * * @param {BCS.Serializer} serializer - The serializer to use. */ serialize(serializer) { serializer.serializeU32AsUleb128(this.tables.length); const tables = this.tables.sort((a, b) => a.kind - b.kind); for (const table of tables) { table.serialize(serializer); } serializer.serializeFixedBytes(this.data); } }; var AbilitySet = class _AbilitySet { /** * Creates an instance of AbilitySet. * * @param {BCS.Uint8} ability - The ability value. */ constructor(ability) { this.ability = ability; } /** * Deserializes an AbilitySet from the given deserializer. * * @param {BCS.Deserializer} deserializer - The deserializer to use. * @returns {AbilitySet} The deserialized AbilitySet. */ static deserialize(deserializer) { const ability = deserializer.deserializeUleb128AsU32(); if (ability > 255) { throw new Error("Invalid ability"); } return new _AbilitySet(ability); } /** * Serializes the AbilitySet using the given serializer. * * @param {BCS.Serializer} serializer - The serializer to use. */ serialize(serializer) { serializer.serializeU32AsUleb128(this.ability); } }; var Index = class _Index { /** * Creates an instance of Index. * * @param {BCS.Uint32} index - The index value. */ constructor(index) { this.index = index; } /** * Deserializes an Index from the given deserializer. * * @param {BCS.Deserializer} deserializer - The deserializer to use. * @returns {Index} The deserialized Index. */ static deserialize(deserializer) { const index = deserializer.deserializeUleb128AsU32(); return new _Index(index); } /** * Serializes the Index using the given serializer. * * @param {BCS.Serializer} serializer - The serializer to use. */ serialize(serializer) { serializer.serializeU32AsUleb128(this.index); } }; var Code = class _Code { /** * Creates an instance of Code. * * @param {Index} locals - The local index. * @param {BCS.Uint32} count - The count of bytecode instructions. * @param {BCS.Seq} codes - The sequence of bytecode instructions. */ constructor(locals, count, codes) { this.locals = locals; this.count = count; this.codes = codes; } /** * Deserializes a Code from the given deserializer. * * @param {BCS.Deserializer} deserializer - The deserializer to use. * @returns {Code} The deserialized Code. */ static deserialize(deserializer) { const locals = Index.deserialize(deserializer); const count = deserializer.deserializeUleb128AsU32(); const codes = []; for (let i = 0; i < count; i++) { const opcode = deserializer.deserializeU8(); const bytecode = ((opcode2) => { switch (opcode2) { case 1 /* POP */: return new ROP(opcode2); case 2 /* RET */: return new RET(opcode2); case 3 /* BR_TRUE */: return new BR_TRUE(opcode2, Index.deserialize(deserializer)); case 4 /* BR_FALSE */: return new BR_FALSE(opcode2, Index.deserialize(deserializer)); case 5 /* BRANCH */: return new BRANCH(opcode2, Index.deserialize(deserializer)); case 49 /* LD_U8 */: return new LD_U8(opcode2, deserializer.deserializeU8()); case 6 /* LD_U64 */: return new LD_U64(opcode2, deserializer.deserializeU64()); case 50 /* LD_U128 */: return new LD_U128(opcode2, deserializer.deserializeU128()); case 51 /* CAST_U8 */: return new CAST_U8(opcode2); case 52 /* CAST_U64 */: return new CAST_U64(opcode2); case 53 /* CAST_U128 */: return new CAST_U128(opcode2); case 7 /* LD_CONST */: return new LD_CONST(opcode2, Index.deserialize(deserializer)); case 8 /* LD_TRUE */: return new LD_TRUE(opcode2); case 9 /* LD_FALSE */: return new LD_FALSE(opcode2); case 10 /* COPY_LOC */: return new COPY_LOC(opcode2, Index.deserialize(deserializer)); case 11 /* MOVE_LOC */: return new MOVE_LOC(opcode2, Index.deserialize(deserializer)); case 12 /* ST_LOC */: return new ST_LOC(opcode2, Index.deserialize(deserializer)); case 13 /* MUT_BORROW_LOC */: return new MUT_BORROW_LOC(opcode2, Index.deserialize(deserializer)); case 14 /* IMM_BORROW_LOC */: return new IMM_BORROW_LOC(opcode2, Index.deserialize(deserializer)); case 15 /* MUT_BORROW_FIELD */: return new MUT_BORROW_FIELD(opcode2, Index.deserialize(deserializer)); case 54 /* MUT_BORROW_FIELD_GENERIC */: return new MUT_BORROW_FIELD_GENERIC(opcode2, Index.deserialize(deserializer)); case 16 /* IMM_BORROW_FIELD */: return new IMM_BORROW_FIELD(opcode2, Index.deserialize(deserializer)); case 55 /* IMM_BORROW_FIELD_GENERIC */: return new IMM_BORROW_FIELD_GENERIC(opcode2, Index.deserialize(deserializer)); case 17 /* CALL */: return new CALL(opcode2, Index.deserialize(deserializer)); case 56 /* CALL_GENERIC */: return new CALL_GENERIC(opcode2, Index.deserialize(deserializer)); case 18 /* PACK */: return new PACK(opcode2, Index.deserialize(deserializer)); case 57 /* PACK_GENERIC */: return new PACK_GENERIC(opcode2, Index.deserialize(deserializer)); case 19 /* UNPACK */: return new UNPACK(opcode2, Index.deserialize(deserializer)); case 58 /* UNPACK_GENERIC */: return new UNPACK_GENERIC(opcode2, Index.deserialize(deserializer)); case 20 /* READ_REF */: return new READ_REF(opcode2); case 21 /* WRITE_REF */: return new WRITE_REF(opcode2); case 22 /* ADD */: return new ADD(opcode2); case 23 /* SUB */: return new SUB(opcode2); case 24 /* MUL */: return new MUL(opcode2); case 25 /* MOD */: return new MOD(opcode2); case 26 /* DIV */: return new DIV(opcode2); case 27 /* BIT_OR */: return new BIT_OR(opcode2); case 28 /* BIT_AND */: return new BIT_AND(opcode2); case 29 /* XOR */: return new XOR(opcode2); case 47 /* SHL */: return new SHL(opcode2); case 48 /* SHR */: return new SHR(opcode2); case 30 /* OR */: return new OR(opcode2); case 31 /* AND */: return new AND(opcode2); case 32 /* NOT */: return new NOT(opcode2); case 33 /* EQ */: return new EQ(opcode2); case 34 /* NEQ */: return new NEQ(opcode2); case 35 /* LT */: return new LT(opcode2); case 36 /* GT */: return new GT(opcode2); case 37 /* LE */: return new LE(opcode2); case 38 /* GE */: return new GE(opcode2); case 39 /* ABORT */: return new ABORT(opcode2); case 40 /* NOP */: return new NOP(opcode2); case 41 /* EXISTS */: return new EXISTS(opcode2, Index.deserialize(deserializer)); case 59 /* EXISTS_GENERIC */: return new EXISTS_GENERIC(opcode2, Index.deserialize(deserializer)); case 42 /* MUT_BORROW_GLOBAL */: return new MUT_BORROW_GLOBAL(opcode2, Index.deserialize(deserializer)); case 60 /* MUT_BORROW_GLOBAL_GENERIC */: return new MUT_BORROW_GLOBAL_GENERIC(opcode2, Index.deserialize(deserializer)); case 43 /* IMM_BORROW_GLOBAL */: return new IMM_BORROW_GLOBAL(opcode2, Index.deserialize(deserializer)); case 61 /* IMM_BORROW_GLOBAL_GENERIC */: return new IMM_BORROW_GLOBAL_GENERIC(opcode2, Index.deserialize(deserializer)); case 44 /* MOVE_FROM */: return new MOVE_FROM(opcode2, Index.deserialize(deserializer)); case 62 /* MOVE_FROM_GENERIC */: return new MOVE_FROM_GENERIC(opcode2, Index.deserialize(deserializer)); case 45 /* MOVE_TO */: return new MOVE_TO(opcode2, Index.deserialize(deserializer)); case 63 /* MOVE_TO_GENERIC */: return new MOVE_TO_GENERIC(opcode2, Index.deserialize(deserializer)); case 46 /* FREEZE_REF */: return new FREEZE_REF(opcode2); case 64 /* VEC_PACK */: return new VEC_PACK( opcode2, Index.deserialize(deserializer), deserializer.deserializeU64() ); case 65 /* VEC_LEN */: return new VEC_LEN(opcode2, Index.deserialize(deserializer)); case 66 /* VEC_IMM_BORROW */: return new VEC_IMM_BORROW(opcode2, Index.deserialize(deserializer)); case 67 /* VEC_MUT_BORROW */: return new VEC_MUT_BORROW(opcode2, Index.deserialize(deserializer)); case 68 /* VEC_PUSH_BACK */: return new VEC_PUSH_BACK(opcode2, Index.deserialize(deserializer)); case 69 /* VEC_POP_BACK */: return new VEC_POP_BACK(opcode2, Index.deserialize(deserializer)); case 70 /* VEC_UNPACK */: return new VEC_UNPACK( opcode2, Index.deserialize(deserializer), deserializer.deserializeU64() ); case 71 /* VEC_SWAP */: return new VEC_SWAP(opcode2, Index.deserialize(deserializer)); case 72 /* LD_U16 */: return new LD_U16(opcode2, deserializer.deserializeU16()); case 73 /* LD_U32 */: return new LD_U32(opcode2, deserializer.deserializeU32()); case 74 /* LD_U256 */: throw new Error("Not supported yet"); case 75 /* CAST_U16 */: return new CAST_U16(opcode2); case 76 /* CAST_U32 */: return new CAST_U32(opcode2); case 77 /* CAST_U256 */: return new CAST_U256(opcode2); default: throw new Error(`Unknown opcode: ${opcode2}`); } })(opcode); codes.push(bytecode); } return new _Code(locals, count, codes); } /** * Serializes the Code using the given serializer. * * @param {BCS.Serializer} serializer - The serializer to use. */ serialize(serializer) { this.locals.serialize(serializer); serializer.serializeU32AsUleb128(this.count); for (const code of this.codes) { code.serialize(serializer); } } }; var Header = class _Header { /** * Creates an instance of Header. * * @param {BCS.Bytes} magic - The magic bytes. * @param {BCS.Uint32} version - The version number. */ constructor(magic, version) { this.magic = magic; this.version = version; } /** * Deserializes a Header from the given deserializer. * * @param {BCS.Deserializer} deserializer - The deserializer to use. * @returns {Header} The deserialized Header. */ static deserialize(deserializer) { const magic = deserializer.deserializeFixedBytes(4); const version = deserializer.deserializeU32(); return new _Header(magic, version); } /** * Serializes the Header using the given serializer. * * @param {BCS.Serializer} serializer - The serializer to use. */ serialize(serializer) { serializer.serializeFixedBytes(this.magic); serializer.serializeU32(this.version); } }; var ModuleHandle = class _ModuleHandle { /** * Creates an instance of ModuleHandle. * * @param {Index} address - The address index. * @param {Index} name - The name index. */ constructor(address, name) { this.address = address; this.name = name; } /** * Deserializes a ModuleHandle from the given deserializer. * * @param {BCS.Deserializer} deserializer - The deserializer to use. * @returns {ModuleHandle} The deserialized ModuleHandle. */ static deserialize(deserializer) { const address = Index.deserialize(deserializer); const name = Index.deserialize(deserializer); return new _ModuleHandle(address, name); } /** * Serializes the ModuleHandle using the given serializer. * * @param {BCS.Serializer} serializer - The serializer to use. */ serialize(serializer) { this.address.serialize(serializer); this.name.serialize(serializer); } }; var StructTypeParameter = class _StructTypeParameter { /** * Creates an instance of StructTypeParameter. * * @param {AbilitySet} constraints - The ability set constraints. * @param {boolean} isPhantom - The phantom flag. */ constructor(constraints, isPhantom) { this.constraints = constraints; this.isPhantom = isPhantom; } /** * Deserializes a StructTypeParameter from the given deserializer. * * @param {BCS.Deserializer} deserializer - The deserializer to use. * @returns {StructTypeParameter} The deserialized StructTypeParameter. */ static deserialize(deserializer) { const constraints = AbilitySet.deserialize(deserializer); const isPhantom = deserializer.deserializeUleb128AsU32() !== 0; return new _StructTypeParameter(constraints, isPhantom); } /** * Serializes the StructTypeParameter using the given serializer. * * @param {BCS.Serializer} serializer - The serializer to use. */ serialize(serializer) { this.constraints.serialize(serializer); serializer.serializeU32AsUleb128(this.isPhantom ? 1 : 0); } }; var StructHandle = class _StructHandle { /** * Creates an instance of StructHandle. * * @param {Index} module - The module index. * @param {Index} name - The name index. * @param {AbilitySet} abilities - The ability set. * @param {BCS.Seq} typeParameters - The sequence of type parameter indices. */ constructor(module, name, abilities, typeParameters) { this.module = module; this.name = name; this.abilities = abilities; this.typeParameters = typeParameters; } /** * Deserializes a StructHandle from the given deserializer. * * @param {BCS.Deserializer} deserializer - The deserializer to use. * @returns {StructHandle} The deserialized StructHandle. */ static deserialize(deserializer) { const module = Index.deserialize(deserializer); const name = Index.deserialize(deserializer); const abilities = AbilitySet.deserialize(deserializer); const typeParameters = aptos2.BCS.deserializeVector(deserializer, StructTypeParameter); return new _StructHandle(module, name, abilities, typeParameters); } /** * Serializes the StructHandle using the given serializer. * * @param {BCS.Serializer} serializer - The serializer to use. */ serialize(serializer) { this.module.serialize(serializer); this.name.serialize(serializer); this.abilities.serialize(serializer); aptos2.BCS.serializeVector(this.typeParameters, serializer); } }; var FunctionHandle = class _FunctionHandle { /** * Creates an instance of FunctionHandle. * * @param {Index} module - The module index. * @param {Index} name - The name index. * @param {Index} parameters - The parameters index. * @param {Index} return_ - The return type index. * @param {BCS.Seq} typeParameters - The sequence of ability sets. */ constructor(module, name, parameters, return_, typeParameters) { this.module = module; this.name = name; this.parameters = parameters; this.return_ = return_; this.typeParameters = typeParameters; } /** * Deserializes a FunctionHandle from the given deserializer. * * @param {BCS.Deserializer} deserializer - The deserializer to use. * @returns {FunctionHandle} The deserialized FunctionHandle. */ static deserialize(deserializer) { const module = Index.deserialize(deserializer); const name = Index.deserialize(deserializer); const parameters = Index.deserialize(deserializer); const return_ = Index.deserialize(deserializer); const typeParameters = aptos2.BCS.deserializeVector(deserializer, AbilitySet); return new _FunctionHandle(module, name, parameters, return_, typeParameters); } /** * Serializes the FunctionHandle using the given serializer. * * @param {BCS.Serializer} serializer - The serializer to use. */ serialize(serializer) { this.module.serialize(serializer); this.name.serialize(serializer); this.parameters.serialize(serializer); this.return_.serialize(serializer); aptos2.BCS.serializeVector(this.typeParameters, serializer); } }; var FunctionInstantiation = class _FunctionInstantiation { /** * Creates an instance of FunctionInstantiation. * * @param {Index} handle - The handle index. * @param {BCS.Seq} typeParameters - The sequence of type parameter indices. */ constructor(handle, typeParameters) { this.handle = handle; this.typeParameters = typeParameters; } /** * Deserializes a FunctionInstantiation from the given deserializer. * * @param {BCS.Deserializer} deserializer - The deserializer to use. * @returns {FunctionInstantiation} The deserialized FunctionInstantiation. */ static deserialize(deserializer) { const handle = Index.deserialize(deserializer); const typeParameters = aptos2.BCS.deserializeVector(deserializer, Index); return new _FunctionInstantiation(handle, typeParameters); } /** * Serializes the FunctionInstantiation using the given serializer. * * @param {BCS.Serializer} serializer - The serializer to use. */ serialize(serializer) { this.handle.serialize(serializer); aptos2.BCS.serializeVector(this.typeParameters, serializer); } }; var Identifier = class _Identifier { /** * Creates an instance of Identifier. * * @param {string} value - The string value. */ constructor(value) { this.value = value; } /** * Deserializes an Identifier from the given deserializer. * * @param {BCS.Deserializer} deserializer - The deserializer to use. * @returns {Identifier} The deserialized Identifier. */ static deserialize(deserializer) { const value = deserializer.deserializeStr(); return new _Identifier(value); } /** * Serializes the Identifier using the given serializer. * * @param {BCS.Serializer} serializer - The serializer to use. */ serialize(serializer) { serializer.serializeStr(this.value); } }; var AddressIdentifier = class _AddressIdentifier { /** * Creates an instance of AddressIdentifier. * * @param {BCS.Bytes} address - The byte array address. */ constructor(address) { this.address = address; } /** * Deserializes an AddressIdentifier from the given deserializer. * * @param {BCS.Deserializer} deserializer - The deserializer to use. * @returns {AddressIdentifier} The deserialized AddressIdentifier. */ static deserialize(deserializer) { const address = deserializer.deserializeFixedBytes(32); return new _AddressIdentifier(address); } /** * Creates an AddressIdentifier from a JSON value. * * @param {any} value - The JSON value. * @returns {AddressIdentifier} The created AddressIdentifier. */ static fromJSON(value) { const bytes = aptos2__namespace.HexString.ensure(value.toString()).toUint8Array(); return new _AddressIdentifier(bytes); } /** * Serializes the AddressIdentifier using the given serializer. * * @param {BCS.Serializer} serializer - The serializer to use. */ serialize(serializer) { serializer.serializeFixedBytes(this.address); } /** * Converts the AddressIdentifier to a JSON string. * * @returns {string} The JSON string representation. */ toJSON() { return aptos2__namespace.HexString.fromUint8Array(this.address).toString(); } }; function load_module_handles(deserializer) { return load_handles(deserializer, ModuleHandle); } function load_struct_handles(deserializer) { return load_handles(deserializer, StructHandle); } function load_function_handles(deserializer) { return load_handles(deserializer, FunctionHandle); } function load_function_instantiations(deserializer) { return load_handles(deserializer, FunctionInstantiation); } function load_identifiers(deserializer) { return load_handles(deserializer, Identifier); } function load_address_identifiers(deserializer) { return load_handles(deserializer, AddressIdentifier); } function load_handles(deserializer, cls) { const handles = []; try { while (true) { const handle = cls.deserialize(deserializer); handles.push(handle); } } catch (e) { if (!(e instanceof Error && isOutOfBoundError(e))) { throw e; } } return handles; } // src/format/table-types.ts var TableType = /* @__PURE__ */ ((TableType2) => { TableType2[TableType2["MODULE_HANDLES"] = 1] = "MODULE_HANDLES"; TableType2[TableType2["STRUCT_HANDLES"] = 2] = "STRUCT_HANDLES"; TableType2[TableType2["FUNCTION_HANDLES"] = 3] = "FUNCTION_HANDLES"; TableType2[TableType2["FUNCTION_INST"] = 4] = "FUNCTION_INST"; TableType2[TableType2["SIGNATURES"] = 5] = "SIGNATURES"; TableType2[TableType2["CONSTANT_POOL"] = 6] = "CONSTANT_POOL"; TableType2[TableType2["IDENTIFIERS"] = 7] = "IDENTIFIERS"; TableType2[TableType2["ADDRESS_IDENTIFIERS"] = 8] = "ADDRESS_IDENTIFIERS"; TableType2[TableType2["STRUCT_DEFS"] = 10] = "STRUCT_DEFS"; TableType2[TableType2["STRUCT_DEF_INST"] = 11] = "STRUCT_DEF_INST"; TableType2[TableType2["FUNCTION_DEFS"] = 12] = "FUNCTION_DEFS"; TableType2[TableType2["FIELD_HANDLE"] = 13] = "FIELD_HANDLE"; TableType2[TableType2["FIELD_INST"] = 14] = "FIELD_INST"; TableType2[TableType2["FRIEND_DECLS"] = 15] = "FRIEND_DECLS"; TableType2[TableType2["METADATA"] = 16] = "METADATA"; return TableType2; })(TableType || {}); // src/format/compiled-script.ts var CompiledScriptRaw = class _CompiledScriptRaw { /** * Creates an instance of CompiledScriptRaw. * * @param {Header} header - The header. * @param {Tables} tables - The tables. * @param {BCS.Seq} typeParameters - The type parameters. * @param {Index} parameters - The parameters. * @param {Code} code - The code. */ constructor(header, tables, typeParameters, parameters, code) { this.header = header; this.tables = tables; this.typeParameters = typeParameters; this.parameters = parameters; this.code = code; } /** * Deserializes a CompiledScriptRaw from the given deserializer. * * @param {BCS.Deserializer} deserializer - The deserializer to use. * @returns {CompiledScriptRaw} The deserialized CompiledScriptRaw. */ static deserialize(deserializer) { const header = Header.deserialize(deserializer); const table = Tables.deserialize(deserializer); const typeParameters = aptos2.BCS.deserializeVector(deserializer, AbilitySet); const parameters = Index.deserialize(deserializer); const code = Code.deserialize(deserializer); return new _CompiledScriptRaw(header, table, typeParameters, parameters, code); } /** * Serializes the CompiledScriptRaw using the given serializer. * * @param {BCS.Serializer} serializer - The serializer to use. */ serialize(serializer) { this.header.serialize(serializer); this.tables.serialize(serializer); aptos2.BCS.serializeVector(this.typeParameters, serializer); this.parameters.serialize(serializer); this.code.serialize(serializer); } }; var CompiledScript = class _CompiledScript { // @ts-expect-error header; // @ts-expect-error table; moduleHandles = []; structHandles = []; functionHandles = []; functionInstatiations = []; // @ts-expect-error signatures; // @ts-expect-error constantPool; // @ts-expect-error metadata; identifiers = []; addressIdentifiers = []; // @ts-expect-error typeParameters; // @ts-expect-error parameters; // @ts-expect-error code; /** * Creates an instance of CompiledScript from a raw compiled script. * * @param {CompiledScriptRaw} raw - The raw compiled script. * @returns {CompiledScript} The created CompiledScript. */ static from(raw) { const script = new _CompiledScript(); script.header = raw.header; script.table = raw.tables; script.typeParameters = raw.typeParameters; script.parameters = raw.parameters; script.code = raw.code; for (const table of raw.tables.tables) { const data = raw.tables.data.subarray(table.offset, table.offset + table.count); const deserializer = new aptos2.BCS.Deserializer(data); switch (table.kind) { case 1 /* MODULE_HANDLES */: script.moduleHandles = load_module_handles(deserializer); break; case 2 /* STRUCT_HANDLES */: script.structHandles = load_struct_handles(deserializer); break; case 3 /* FUNCTION_HANDLES */: script.functionHandles = load_function_handles(deserializer); break; case 4 /* FUNCTION_INST */: script.functionInstatiations = load_function_instantiations(deserializer); break; case 5 /* SIGNATURES */: script.signatures = data; break; case 6 /* CONSTANT_POOL */: script.constantPool = data; break; case 16 /* METADATA */: script.metadata = data; break; case 7 /* IDENTIFIERS */: script.identifiers = load_identifiers(deserializer); break; case 8 /* ADDRESS_IDENTIFIERS */: script.addressIdentifiers = load_address_identifiers(deserializer); break; default: throw new Error(`Unsupported table type: ${table.kind}, ${TableType[table.kind]}`); } } return script; } /** * Serializes the CompiledScript using the given serializer. * * @param {BCS.Serializer} serializer - The serializer to use. */ serialize(serializer) { this.header.serialize(serializer); const tables = this.table.tables.sort((a, b) => a.kind - b.kind); serializer.serializeU32AsUleb128(tables.length); let offset = 0; for (const table of tables) { table.offset = offset; switch (table.kind) { case 7 /* IDENTIFIERS */: { const length = calculateContentLength(this.identifiers); table.count = length; break; } } table.serialize(serializer); offset += table.count; } for (const table of tables) { switch (table.kind) { case 1 /* MODULE_HANDLES */: serializeVectorWithoutLength(this.moduleHandles, serializer); break; case 2 /* STRUCT_HANDLES */: serializeVectorWithoutLength(this.structHandles, serializer); break; case 3 /* FUNCTION_HANDLES */: serializeVectorWithoutLength(this.functionHandles, serializer); break; case 4 /* FUNCTION_INST */: serializeVectorWithoutLength(this.functionInstatiations, serializer); break; case 5 /* SIGNATURES */: serializer.serializeFixedBytes(this.signatures); break; case 6 /* CONSTANT_POOL */: serializer.serializeFixedBytes(this.constantPool); break; case 16 /* METADATA */: serializer.serializeFixedBytes(this.metadata); break; case 7 /* IDENTIFIERS */: serializeVectorWithoutLength(this.identifiers, serializer); break; case 8 /* ADDRESS_IDENTIFIERS */: serializeVectorWithoutLength(this.addressIdentifiers, serializer); break; default: throw new Error(`Unsupported table type: ${table.kind}, ${TableType[table.kind]}`); } } aptos2.BCS.serializeVector(this.typeParameters, serializer); this.parameters.serialize(serializer); this.code.serialize(serializer); } }; // src/format/utils.ts function serializeVectorWithoutLength(value, serializer) { value.forEach((item) => { item.serialize(serializer); }); } function calculateContentLength(value) { const serializer = new aptos2.BCS.Serializer(); serializeVectorWithoutLength(value, serializer); return serializer.getBytes().length; } function isOutOfBoundError(e) { return e.message.match(/Reached to the end of buffer/) !== null; } function isEqual(a, b) { return a.length === b.length && a.every((v, i) => v === b[i]); } function replaceTableValue(compiled, tableType, oldValue, newValue) { switch (tableType) { case 7 /* IDENTIFIERS */: { compiled.identifiers = compiled.identifiers.map((identifier, index) => { if (identifier.value === oldValue) { return new Identifier(newValue); } return identifier; }); break; } case 8 /* ADDRESS_IDENTIFIERS */: { compiled.addressIdentifiers = compiled.addressIdentifiers.map((addressIdentifier, index) => { if (addressIdentifier.address.length != oldValue.length || addressIdentifier.address.length != newValue.length) { throw new Error(`Invalid address length, newValue: ${newValue.toString("hex")}`); } if (isEqual(addressIdentifier.address, oldValue)) { return new AddressIdentifier(newValue); } return addressIdentifier; }); break; } default: throw new Error(`Unsupported table type: ${tableType}, ${TableType[tableType]}`); } } function rebuildCompileScriptBytecode(bytecode, addresses, names) { const code = typeof bytecode === "string" ? utils.hexToBytes(bytecode) : bytecode; const deserializer = new aptos2.BCS.Deserializer(code); const raw = CompiledScriptRaw.deserialize(deserializer); const compiledScript = CompiledScript.from(raw); for (const item of addresses) { replaceTableValue(compiledScript, 8 /* ADDRESS_IDENTIFIERS */, item.oldValue, item.newValue); } for (const item of names) { replaceTableValue(compiledScript, 7 /* IDENTIFIERS */, item.oldValue, item.newValue); } const serializer = new aptos2.BCS.Serializer(); compiledScript.serialize(serializer); const result = Buffer.from(serializer.getBytes()).toString("hex"); return result; } // src/modules/executor.ts var Executor = class { /** * Creates an instance of the Executor class. * * @param {SDK} sdk - The SDK instance. */ constructor(sdk) { this.sdk = sdk; this.module = `${sdk.accounts.layerzero}::executor_v1`; this.moduleName = "layerzero::executor_v1"; this.type = `${this.module}::Executor`; } module; moduleName; type; /** * Creates the payload for setting the default adapter parameters. * * @param {aptos.BCS.Uint16} dstChainId - The destination chain ID. * @param {aptos.BCS.Bytes} adapterParams - The adapter parameters. * @returns {aptos.Types.EntryFunctionPayload} The payload for setting the default adapter parameters. */ setDefaultAdapterParamsPayload(dstChainId, adapterParams) { return { function: `${this.module}::set_default_adapter_params`, type_arguments: [], arguments: [dstChainId, Array.from(adapterParams)] }; } /** * Sets the default adapter parameters. * * @param {aptos.AptosAccount} signer - The signer account. * @param {aptos.BCS.Uint16} dstChainId - The destination chain ID. * @param {aptos.BCS.Bytes} adapterParams - The adapter parameters. * @returns {Promise} A promise that resolves to the transaction. */ async setDefaultAdapterParams(signer, dstChainId, adapterParams) { const transaction = this.setDefaultAdapterParamsPayload(dstChainId, adapterParams); return this.sdk.sendAndConfirmTransaction(signer, transaction); } /** * Gets the default adapter parameters for a given chain ID. * * @param {aptos.BCS.Uint16} chainId - The chain ID. * @returns {Promise} A promise that resolves to the default adapter parameters. * @throws {Error} If the LayerZero account is undefined. */ async getDefaultAdapterParams(chainId) { if (this.sdk.accounts.layerzero === void 0) { throw new Error("endpoint sdk accounts layerzero is undefined when invoke getDefaultAdapterParams"); } const resource = await this.sdk.client.getAccountResource( this.sdk.accounts.layerzero, `${this.module}::AdapterParamsConfig` ); const { params } = resource.data; try { const response = await this.sdk.client.getTableItem(params.handle, { key_type: "u64", value_type: "vector", key: chainId.toString() }); return Buffer.from(aptos2__namespace.HexString.ensure(response).noPrefix(), "hex"); } catch (e) { return this.buildDefaultAdapterParams(0); } } /** * Checks if an address is registered. * * @param {aptos.MaybeHexString} address - The address to check. * @returns {Promise} A promise that resolves to true if the address is registered, false otherwise. */ async isRegistered(address) { try { await this.sdk.client.getAccountResource(address, `${this.module}::ExecutorConfig`); return true; } catch (e) { if (isErrorOfApiError(e, 404)) { return false; } throw e; } } /** * Creates the payload for registering an executor. * * @returns {aptos.Types.EntryFunctionPayload} The payload for registering an executor. */ registerPayload() { return { function: `${this.module}::register`, type_arguments: [], arguments: [] }; } /** * Registers an executor. * * @param {aptos.AptosAccount} signer - The signer account. * @returns {Promise} A promise that resolves to the transaction. */ async register(signer) { const transaction = this.registerPayload(); return this.sdk.sendAndConfirmTransaction(signer, transaction); } /** * Creates the payload for setting the fee. * * @param {aptos.BCS.Uint16} dstChainId - The destination chain ID. * @param {Fee} config - The fee configuration. * @returns {aptos.Types.EntryFunctionPayload} The payload for setting the fee. */ setFeePayload(dstChainId, config) { return { function: `${this.module}::set_fee`, type_arguments: [], arguments: [dstChainId, config.airdropAmtCap, config.priceRatio, config.gasPrice] }; } /** * Sets the fee. * * @param {aptos.AptosAccount} signer - The signer account. * @param {aptos.BCS.Uint16} dstChainId - The destination chain ID. * @param {Fee} config - The fee configuration. * @returns {Promise} A promise that resolves to the transaction. */ async setFee(signer, dstChainId, config) { const transaction = this.setFeePayload(dstChainId, config); return this.sdk.sendAndConfirmTransaction(signer, transaction); } /** * Gets the fee configuration for a given executor and chain ID. * * @param {aptos.MaybeHexString} executor - The executor address. * @param {aptos.BCS.Uint16} chainId - The chain ID. * @param {object} [query] - The query parameters. * @param {bigint | number} [query.ledgerVersion] - The ledger version. * @returns {Promise} A promise that resolves to the fee configuration. * @throws {Error} If an error occurs while fetching the fee configuration. */ async getFee(executor, chainId, query) { try { const resource = await this.sdk.client.getAccountResource(executor, `${this.module}::ExecutorConfig`, query); const { fee } = resource.data; const response = await this.sdk.client.getTableItem( fee.handle, { key_type: "u64", value_type: `${this.module}::Fee`, key: chainId.toString() }, query ); return { airdropAmtCap: BigInt(response.airdrop_amt_cap), priceRatio: BigInt(response.price_ratio), gasPrice: BigInt(response.gas_price) }; } catch (e) { if (isErrorOfApiError(e, 404)) { return { airdropAmtCap: 0n, priceRatio: 0n, gasPrice: 0n }; } throw e; } } /** * Creates the payload for airdropping tokens. * * @param {aptos.BCS.Uint16} srcChainId - The source chain ID. * @param {aptos.BCS.Bytes} guid - The GUID. * @param {aptos.MaybeHexString} receiver - The receiver address. * @param {aptos.BCS.Uint64 | aptos.BCS.Uint32} amount - The amount to airdrop. * @returns {aptos.Types.EntryFunctionPayload} The payload for airdropping tokens. */ airdropPayload(srcChainId, guid, receiver, amount) { return { function: `${this.module}::airdrop`, type_arguments: [], arguments: [srcChainId, Array.from(guid), receiver, amount.toString()] }; } /** * Airdrops tokens. * * @param {aptos.AptosAccount} signer - The signer account. * @param {aptos.BCS.Uint16} srcChainId - The source chain ID. * @param {aptos.BCS.Bytes} guid - The GUID. * @param {aptos.MaybeHexString} receiver - The receiver address. * @param {aptos.BCS.Uint64 | aptos.BCS.Uint32} amount - The amount to airdrop. * @returns {Promise} A promise that resolves to the transaction. */ async airdrop(signer, srcChainId, guid, receiver, amount) { const transaction = this.airdropPayload(srcChainId, guid, receiver, amount); return this.sdk.sendAndConfirmTransaction(signer, transaction); } /** * Checks if a GUID has been airdropped to a receiver. * * @param {aptos.BCS.Bytes} guid - The GUID. * @param {aptos.MaybeHexString} receiver - The receiver address. * @returns {Promise} A promise that resolves to true if the GUID has been airdropped, false otherwise. * @throws {Error} If the LayerZero account is undefined. */ async isAirdropped(guid, receiver) { try { if (this.sdk.accounts.layerzero === void 0) { throw new Error("endpoint sdk accounts layerzero is undefined when invoke isAirdropped"); } const resource = await this.sdk.client.getAccountResource( this.sdk.accounts.layerzero, `${this.module}::JobStore` ); const { done } = resource.data; const response = await this.sdk.client.getTableItem(done.handle, { key_type: `${this.module}::JobKey`, value_type: "bool", key: { guid: Buffer.from(guid).toString("hex"), executor: receiver.toString() } }); return response; } catch (e) { if (isErrorOfApiError(e, 404)) { return false; } throw e; } } /** * Quotes the fee for a given executor, destination chain ID, and adapter parameters. * * @param {aptos.MaybeHexString} executor - The executor address. * @param {aptos.BCS.Uint16} dstChainId - The destination chain ID. * @param {aptos.BCS.Bytes} adapterParams - The adapter parameters. * @param {object} [query] - The query parameters. * @param {bigint | number} [query.ledgerVersion] - The ledger version. * @returns {Promise} A promise that resolves to the quoted fee. */ async quoteFee(executor, dstChainId, adapterParams, query) { if (adapterParams === void 0 || adapterParams.length === 0) { adapterParams = await this.getDefaultAdapterParams(dstChainId); } const fee = await this.getFee(executor, dstChainId, query); const [, uaGas, airdropAmount] = this.decodeAdapterParams(adapterParams); return (uaGas * fee.gasPrice + airdropAmount) * fee.priceRatio / 10000000000n; } /** * Builds the default adapter parameters. * * @param {aptos.BCS.Uint64 | aptos.BCS.Uint32} uaGas - The user application gas. * @returns {aptos.BCS.Bytes} The default adapter parameters. */ buildDefaultAdapterParams(uaGas) { const params = [0, 1].concat(Array.from(convertUint64ToBytes(uaGas))); return Uint8Array.from(Buffer.from(params)); } /** * Builds the airdrop adapter parameters. * * @param {aptos.BCS.Uint64 | aptos.BCS.Uint32} uaGas - The user application gas. * @param {aptos.BCS.Uint64 | aptos.BCS.Uint32} airdropAmount - The airdrop amount. * @param {string} airdropAddress - The airdrop address. * @returns {aptos.BCS.Bytes} The airdrop adapter parameters. */ buildAirdropAdapterParams(uaGas, airdropAmount, airdropAddress) { if (airdropAmount === 0n) { return this.buildDefaultAdapterParams(uaGas); } const params = [0, 2].concat(Array.from(convertUint64ToBytes(uaGas))).concat(Array.from(convertUint64ToBytes(airdropAmount))).concat(Array.from(aptos2__namespace.HexString.ensure(airdropAddress).toUint8Array())); return Buffer.from(params); } /** * Decodes the adapter parameters. * * txType 1 * bytes [2 8 ] * fields [txType extraGas] * txType 2 * bytes [2 8 8 unfixed ] * fields [txType extraGas airdropAmt airdropAddress] * * @param {aptos.BCS.Bytes} adapterParams - The adapter parameters. * @returns {[aptos.BCS.Uint16, aptos.BCS.Uint64, aptos.BCS.Uint64, string]} The decoded adapter parameters. * @throws {Error} If the adapter parameters are invalid. */ decodeAdapterParams(adapterParams) { const type = adapterParams[0] * 256 + adapterParams[1]; if (type === 1) { if (adapterParams.length !== 10) throw new Error("invalid adapter params"); const uaGas = adapterParams.slice(2, 10); return [type, convertBytesToUint64(uaGas), 0n, ""]; } else if (type === 2) { if (adapterParams.length <= 18) throw new Error("invalid adapter params"); const uaGas = adapterParams.slice(2, 10); const airdropAmount = adapterParams.slice(10, 18); const airdropAddressBytes = adapterParams.slice(18); return [ type, convertBytesToUint64(uaGas), convertBytesToUint64(airdropAmount), aptos2__namespace.HexString.fromUint8Array(airdropAddressBytes).toString() ]; } else { throw new Error("invalid adapter params"); } } /** * Rebuilds a compiled script to query type arguments for the lz_receive function. * * @param {Packet} packet - The packet. * @returns {Promise} A promise that resolves to the rebuilt script bytecode. * @throws {Error} If the executor_ext account is undefined. */ async rebuildTypeArgsScript(packet) { const SCRIPT_BYTECODE = "a11ceb0b0500000006010006020604030a0a051419072d50087d60000001010202000307000104030100020504020004060c030a020a02010a08000003030a020a0202060c0a080009747970655f696e666f07636f756e7465720c6578656375746f725f6578740854797065496e666f106c7a5f726563656976655f7479706573166275696c645f6c7a5f726563656976655f74797065730000000000000000000000000000000000000000000000000000000000000001000000000000000000000000000000000000000000000000000000000000cafe000000000000000000000000000000000000000000000000000000000000face000001090b010b020b0311000c040b000b04110102"; const uaTypeInfo = await this.sdk.LayerzeroModule.Endpoint.getUATypeInfo( aptos2__namespace.HexString.fromBuffer(packet.dst_address) ); if (this.sdk.accounts.executor_ext === void 0) { throw new Error("sdk accounts executor_ext is undefined when invoked rebuildTypeArgsScript"); } const bytecode = rebuildCompileScriptBytecode( SCRIPT_BYTECODE, [ { oldValue: aptos2__namespace.HexString.ensure( "0x000000000000000000000000000000000000000000000000000000000000face" ).toUint8Array(), newValue: aptos2__namespace.HexString.ensure(this.sdk.accounts.executor_ext).toUint8Array() }, { oldValue: aptos2__namespace.HexString.ensure( "0x000000000000000000000000000000000000000000000000000000000000cafe" ).toUint8Array(), newValue: aptos2__namespace.HexString.ensure(uaTypeInfo.account_address).toUint8Array() } ], [ { oldValue: "counter", newValue: uaTypeInfo.module_name } ] ); return bytecode; } /** * Executes compiled script on chain to get type arguments for lz_receive function. * * @param {Packet} packet - The packet. * @returns {Promise} A promise that resolves to the type arguments. * @throws {Error} If the sdk accounts layerzero_apps_pubkey is undefined. */ async getLzReceiveTypeArguments(packet) { const bytecode = await this.rebuildTypeArgsScript(packet); if (this.sdk.accounts.layerzero_apps_pubkey === void 0) { throw new Error("sdk accounts layerzero_apps_pubkey is undefined when invoked getLzReceiveTypeArguments"); } const typeInfos = await getLzReceiveTypeArguments( new aptos2__namespace.HexString(bytecode).toUint8Array(), this.sdk, new aptos2__namespace.TxnBuilderTypes.Ed25519PublicKey( stringToUint8Array(this.sdk.accounts.layerzero_apps_pubkey.toString()) ), packet.dst_address, parseInt(packet.src_chain_id.toString()), packet.src_address, Buffer.from(packet.payload) ); return typeInfos; } /** * Gets lz_receive_types arguments by view function (tagged with #[view]). * 1. Tries UA::${module}::lz_receive_types, if failed, then * 2. Tries UA::lz_receive::lz_receive_types by convention. * * @param {Packet} packet - The packet. * @param {string} [ledger_version] - The ledger version. * @returns {Promise<[string[], TypeInfoEx]>} A promise that resolves to the type arguments and TypeInfoEx. * @throws {Error} If the lz_receive_types arguments cannot be retrieved. */ async getLzReceiveTypeArgumentsView(packet, ledger_version) { const dstAddressHex = Buffer.from(packet.dst_address).toString("hex"); const uaAddress = aptos2__namespace.HexString.ensure(dstAddressHex); const uaTypeInfo = await this.sdk.LayerzeroModule.Endpoint.getUATypeInfo(uaAddress); const potentialModules = [uaTypeInfo.module_name, "lz_receive"]; for (const module of potentialModules) { const payload = { function: `${uaTypeInfo.account_address}::${module}::lz_receive_types`, type_arguments: [], arguments: [ `${packet.src_chain_id}`, Buffer.from(packet.src_address).toString("hex"), Buffer.from(packet.payload).toString("hex") ] }; try { const ret = await this.sdk.client.view(payload, ledger_version); const types = ret[0]; return [ types.map((t) => { const account_address = fullAddress(t.account_address).toString(); const module_name = hexToAscii(t.module_name); const struct_name = hexToAscii(t.struct_name); return `${account_address}::${module_name}::${struct_name}`; }), { account_address: uaTypeInfo.account_address, module_name: module, struct_name: uaTypeInfo.struct_name, type: uaTypeInfo.type } ]; } catch (e) { if (isErrorOfApiError(e, 400)) { continue; } throw e; } } throw new Error(`failed to get lz_receive_types arguments for ${uaAddress}`); } /** * Gets the payload for the lz_receive function. * * @param {string[]} type_arguments - The type arguments. * @param {Packet} packet - The packet. * @param {TypeInfo} [uaTypeInfo] - The TypeInfo. * @returns {Promise} A promise that resolves to the payload. */ async getLzReceivePayload(type_arguments, packet, uaTypeInfo) { if (!uaTypeInfo) { uaTypeInfo = await this.sdk.LayerzeroModule.Endpoint.getUATypeInfo( aptos2__namespace.HexString.fromBuffer(packet.dst_address) ); } const transaction = { function: `${uaTypeInfo.account_address}::${uaTypeInfo.module_name}::lz_receive`, type_arguments, arguments: [ packet.src_chain_id, Array.from(Uint8Array.from(packet.src_address)), Array.from(Uint8Array.from(packet.payload)) ] }; return transaction; } /** * Executes the lz_receive function. * * @param {aptos.AptosAccount} signer - The signer account. * @param {string[]} type_arguments - The type arguments. * @param {Packet} packet - The packet. * @returns {Promise} A promise that resolves to the transaction. */ async lzReceive(signer, type_arguments, packet) { const transaction = await this.getLzReceivePayload(type_arguments, packet); return this.sdk.sendAndConfirmTransaction(signer, transaction); } /** * Auto-detects lz_receive_types and calls lz_receive. * * @param {aptos.AptosAccount} signer - The signer account. * @param {Packet} packet - The packet. * @returns {Promise} A promise that resolves to the transaction. */ async lzReceiveNew(signer, packet) { let transaction; try { const [typeArgs, uaTypeInfo] = await this.getLzReceiveTypeArgumentsView(packet); transaction = await this.getLzReceivePayload(typeArgs, packet, uaTypeInfo); } catch (e) { } if (!transaction) { const typeArgs = await this.getLzReceiveTypeArguments(packet); transaction = await this.getLzReceivePayload(typeArgs, packet); } return this.sdk.sendAndConfirmTransaction(signer, transaction); } /** * Gets the short request event type. * * @returns {string} The short request event type. */ getShortRequestEventType() { return `${this.module}::RequestEvent`.replace(/^(0x)0*/i, "$1"); } }; // src/modules/executor_config.ts var ExecutorConfig = class { /** * Creates an instance of the ExecutorConfig class. * * @param {SDK} sdk - The SDK instance. */ constructor(sdk) { this.sdk = sdk; this.module = `${sdk.accounts.layerzero}::executor_config`; } /** * The module name. */ module; /** * Gets the default executor for a given remote chain ID. * * @param {aptos.BCS.Uint16} remoteChainId - The remote chain ID. * @returns {Promise<[string, aptos.BCS.Uint64]>} A promise that resolves to the executor and version. * @throws {Error} If the SDK accounts layerzero is undefined. */ async getDefaultExecutor(remoteChainId) { if (this.sdk.accounts.layerzero === void 0) { throw new Error("sdk accounts layerzero is undefined when invoke getDefaultExecutor"); } const resource = await this.sdk.client.getAccountResource( this.sdk.accounts.layerzero, `${this.module}::ConfigStore` ); const { config } = resource.data; try { const response = await this.sdk.client.getTableItem(config.handle, { key_type: "u64", value_type: `${this.module}::Config`, key: remoteChainId.toString() }); return [response.executor, response.version]; } catch (e) { if (isErrorOfApiError(e, 404)) { return ["", BigInt(0)]; } throw e; } } /** * Gets the executor for a given user address and remote chain ID. * * @param {aptos.MaybeHexString} uaAddress - The user address. * @param {aptos.BCS.Uint16} remoteChainId - The remote chain ID. * @param {Object} [query] - Optional query parameters. * @param {bigint | number} [query.ledgerVersion] - The ledger version. * @returns {Promise<[string, aptos.BCS.Uint64]>} A promise that resolves to the executor and version. */ async getExecutor(uaAddress, remoteChainId, query) { const resource = await this.sdk.client.getAccountResource(uaAddress, `${this.module}::ConfigStore`, query); const { config } = resource.data; try { const response = await this.sdk.client.getTableItem( config.handle, { key_type: "u64", value_type: `${this.module}::Config`, key: remoteChainId.toString() }, query ); return [response.executor, response.version]; } catch (e) { if (isErrorOfApiError(e, 404)) { return await this.getDefaultExecutor(remoteChainId); } throw e; } } /** * Creates a payload for setting the default executor. * * @param {aptos.BCS.Uint16} remoteChainId - The remote chain ID. * @param {aptos.BCS.Uint8} version - The version. * @param {aptos.MaybeHexString} executor - The executor address. * @returns {aptos.Types.EntryFunctionPayload} The payload. */ setDefaultExecutorPayload(remoteChainId, version, executor) { return { function: `${this.module}::set_default_executor`, type_arguments: [], arguments: [remoteChainId, version, executor] }; } }; var MsgLibAuth = class { /** * Creates an instance of the MsgLibAuth class. * * @param {SDK} sdk - The SDK instance. */ constructor(sdk) { this.sdk = sdk; this.module = `${sdk.accounts.msglib_auth}::msglib_cap`; this.moduleName = "msglib_auth::msglib_cap"; } /** * The module name. */ module; /** * The module name string. */ moduleName; /** * Checks if a message library receive address is allowed. * * @param {string} msglibReceive - The message library receive address. * @returns {Promise} A promise that resolves to true if allowed, false otherwise. * @throws Will throw an error if sdk accounts msglib_auth is undefined. */ async isAllowed(msglibReceive) { if (this.sdk.accounts.msglib_auth === void 0) { throw new Error("sdk accounts msglib_auth is undefined when invoke isAllowed"); } const resource = await this.sdk.client.getAccountResource( this.sdk.accounts.msglib_auth, `${this.module}::GlobalStore` ); const msglibAcl = resource.data.msglib_acl.list; const lib = aptos2__namespace.HexString.ensure(msglibReceive).toShortString(); return msglibAcl.includes(lib); } /** * Creates a payload to deny a message library receive address. * * @param {string} msglibReceive - The message library receive address. * @returns {aptos.Types.EntryFunctionPayload} The payload. */ denyPayload(msglibReceive) { return { function: `${this.module}::deny`, type_arguments: [], arguments: [msglibReceive] }; } /** * Creates a payload to allow a message library receive address. * * @param {string} msglibReceive - The message library receive address. * @returns {aptos.Types.EntryFunctionPayload} The payload. */ allowPayload(msglibReceive) { return { function: `${this.module}::allow`, type_arguments: [], arguments: [msglibReceive] }; } /** * Allows a message library receive address. * * @param {aptos.AptosAccount} signer - The signer account. * @param {string} msglibReceive - The message library receive address. * @returns {Promise} A promise that resolves to the transaction. */ async allow(signer, msglibReceive) { const transaction = this.allowPayload(msglibReceive); return this.sdk.sendAndConfirmTransaction(signer, transaction); } }; // src/modules/msglib_config.ts var MsgLibConfig = class { /** * Creates an instance of the MsgLibConfig class. * * @param {SDK} sdk - The SDK instance. */ constructor(sdk) { this.sdk = sdk; this.module = `${sdk.accounts.layerzero}::msglib_config`; this.moduleName = "layerzero::msglib_config"; this.semverModule = `${sdk.accounts.layerzero}::semver`; } /** * The module path. */ module; /** * The module name. */ moduleName; /** * The semver module path. */ semverModule; /** * Gets the default send message library version for a remote chain. * * @param {aptos.BCS.Uint16} remoteChainId - The remote chain ID. * @returns {Promise<{ major: aptos.BCS.Uint64; minor: aptos.BCS.Uint8 }>} A promise that resolves to the version. * @throws Will throw an error if the SDK accounts layerzero is undefined. */ async getDefaultSendMsgLib(remoteChainId) { if (this.sdk.accounts.layerzero === void 0) { throw new Error("sdk accounts layerzero is undefined when invoke getDefaultSendMsgLib"); } const resource = await this.sdk.client.getAccountResource( this.sdk.accounts.layerzero, `${this.module}::MsgLibConfig` ); const { send_version } = resource.data; try { const response = await this.sdk.client.getTableItem(send_version.handle, { key_type: "u64", value_type: `${this.semverModule}::SemVer`, key: remoteChainId.toString() }); return { major: BigInt(response.major), minor: Number(response.minor) }; } catch (e) { if (isErrorOfApiError(e, 404)) { return { major: BigInt(0), minor: 0 }; } throw e; } } /** * Gets the default receive message library version for a remote chain. * * @param {aptos.BCS.Uint16} remoteChainId - The remote chain ID. * @returns {Promise<{ major: aptos.BCS.Uint64; minor: aptos.BCS.Uint8 }>} A promise that resolves to the version. * @throws Will throw an error if the SDK accounts layerzero is undefined. */ async getDefaultReceiveMsgLib(remoteChainId) { if (this.sdk.accounts.layerzero === void 0) { throw new Error("sdk accounts layerzero is undefined when invoke getDefaultReceiveMsgLib"); } const resource = await this.sdk.client.getAccountResource( this.sdk.accounts.layerzero, `${this.module}::MsgLibConfig` ); const { receive_version } = resource.data; try { const response = await this.sdk.client.getTableItem(receive_version.handle, { key_type: "u64", value_type: `${this.semverModule}::SemVer`, key: remoteChainId.toString() }); return { major: BigInt(response.major), minor: Number(response.minor) }; } catch (e) { if (isErrorOfApiError(e, 404)) { return { major: BigInt(0), minor: 0 }; } throw e; } } /** * Creates a payload for setting the default send message library version. * * @param {aptos.BCS.Uint16} remoteChainId - The remote chain ID. * @param {aptos.BCS.Uint64} major - The major version. * @param {aptos.BCS.Uint8} minor - The minor version. * @returns {aptos.Types.EntryFunctionPayload} The payload. */ setDefaultSendMsgLibPayload(remoteChainId, major, minor) { return { function: `${this.module}::set_default_send_msglib`, type_arguments: [], arguments: [remoteChainId.toString(), major.toString(), minor.toString()] }; } /** * Creates a payload for setting the default receive message library version. * * @param {aptos.BCS.Uint16} remoteChainId - The remote chain ID. * @param {aptos.BCS.Uint64} major - The major version. * @param {aptos.BCS.Uint8} minor - The minor version. * @returns {aptos.Types.EntryFunctionPayload} The payload. */ setDefaultReceiveMsgLibPayload(remoteChainId, major, minor) { return { function: `${this.module}::set_default_receive_msglib`, type_arguments: [], arguments: [remoteChainId.toString(), major.toString(), minor.toString()] }; } }; // src/modules/uln/index.ts var uln_exports = {}; __export(uln_exports, { MsgLibV1_0: () => MsgLibV1_0, PacketEvent: () => PacketEvent, Uln: () => Uln, UlnConfig: () => UlnConfig, UlnReceive: () => UlnReceive, UlnSigner: () => UlnSigner }); // src/modules/uln/msglib_v1_0.ts var MsgLibV1_0 = class { /** * Creates an instance of the MsgLibV1_0 class. * * @param {SDK} sdk - The SDK instance. */ constructor(sdk) { this.sdk = sdk; this.module = `${sdk.accounts.layerzero}::msglib_v1_0`; } /** * The module name. */ module; }; var PacketEvent = class { /** * Creates an instance of the PacketEvent class. * * @param {SDK} sdk - The SDK instance. */ constructor(sdk) { this.sdk = sdk; this.module = `${sdk.accounts.layerzero}::packet_event`; this.OutboundEventType = `${this.module}::OutboundEvent`; this.InboundEventType = `${this.module}::InboundEvent`; } /** * The module name. */ module; /** * The outbound event type. */ OutboundEventType; /** * The inbound event type. */ InboundEventType; /** * Returns an array of VersionedEvent objects for inbound events. * * @param {bigint} start - The start index of the events, starting from 0. * @param {number} limit - The maximum number of events to return. * @returns {Promise} An array of VersionedEvent objects. * @throws {Error} If sdk accounts layerzero is undefined. * @example * [ * { * "version": "2527457", * "guid": { * "creation_number": "7", * "account_address": "0x54ad3d30af77b60d939ae356e6606de9a4da67583f02b962d2d3f2e481484e90" * }, * "sequence_number": "0", * "type": "0x54ad3d30af77b60d939ae356e6606de9a4da67583f02b962d2d3f2e481484e90::packet_event::InboundEvent", * "data": { * "packet": { * "dst_address": "0xf22bede237a07e121b56d91a491eb7bcdfd1f5907926a9e58338f964a01b17fa", * "dst_chain_id": "108", * "nonce": "1", * "payload": "0x00000000000000000000000000a0b86991c6218b36c1d19d4a2e9eb0ce3606eb4857203756ea4273c43f583acd5b7a72aa168098da3fb9ffe4f6505515aae8fc9b0000000002faf080", * "src_address": "0x50002cdfe7ccb0c41f519c6eb0653158d11cd907", * "src_chain_id": "101" * } * } * }, * { * "version": "2617627", * "guid": { * "creation_number": "7", * "account_address": "0x54ad3d30af77b60d939ae356e6606de9a4da67583f02b962d2d3f2e481484e90" * }, * "sequence_number": "1", * "type": "0x54ad3d30af77b60d939ae356e6606de9a4da67583f02b962d2d3f2e481484e90::packet_event::InboundEvent", * "data": { * "packet": { * "dst_address": "0xf22bede237a07e121b56d91a491eb7bcdfd1f5907926a9e58338f964a01b17fa", * "dst_chain_id": "108", * "nonce": "2", * "payload": "0x00000000000000000000000000dac17f958d2ee523a2206206994597c13d831ec7495f9f30a60c7cda8a60937b4281d00d8730596409820bbf59b2674624c76d9b00000000000f4240", * "src_address": "0x50002cdfe7ccb0c41f519c6eb0653158d11cd907", * "src_chain_id": "101" * } * } * } * ] */ async getInboundEvents(start, limit) { if (this.sdk.accounts.layerzero === void 0) { throw new Error("sdk accounts layerzero is undefined when invoke getInboundEvents"); } const events = await this.sdk.client.getEventsByEventHandle( this.sdk.accounts.layerzero, `${this.module}::EventStore`, "inbound_events", { start, limit } ); return events.map((event) => event); } /** * Returns the count of inbound events. * * @returns {Promise} The count of inbound events. * @throws {Error} If sdk accounts layerzero is undefined. */ async getInboundEventCount() { if (this.sdk.accounts.layerzero === void 0) { throw new Error("sdk accounts layerzero is undefined when invoke getInboundEventCount"); } const resource = await this.sdk.client.getAccountResource( this.sdk.accounts.layerzero, `${this.module}::EventStore` ); const { inbound_events } = resource.data; return new BN__default.default(inbound_events.counter).toNumber(); } /** * Returns an array of VersionedEvent objects for outbound events. * * @param {bigint} start - The start index of the events, starting from 0. * @param {number} limit - The maximum number of events to return. * @returns {Promise} An array of VersionedEvent objects. * @throws {Error} If sdk accounts layerzero is undefined. * @example * [ * { * version: '3290647', * guid: { * creation_number: '8', * account_address: '0x54ad3d30af77b60d939ae356e6606de9a4da67583f02b962d2d3f2e481484e90' * }, * sequence_number: '0', * type: '0x54ad3d30af77b60d939ae356e6606de9a4da67583f02b962d2d3f2e481484e90::packet_event::OutboundEvent', * data: { * encoded_packet: '0x0000000000000001006cf22bede237a07e121b56d91a491eb7bcdfd1f5907926a9e58338f964a01b17fa006f86bb63148d17d445ed5398ef26aa05bf76dd5b59010000000000000000000000007f5c764cbc14f9669b88837ca1490cca17c316070000000000000000000000003a983ffaa79e2d12ef94b50f68346a4b9c653a9a00000000001e848000' * } * }, * { * version: '3308828', * guid: { * creation_number: '8', * account_address: '0x54ad3d30af77b60d939ae356e6606de9a4da67583f02b962d2d3f2e481484e90' * }, * sequence_number: '1', * type: '0x54ad3d30af77b60d939ae356e6606de9a4da67583f02b962d2d3f2e481484e90::packet_event::OutboundEvent', * data: { * encoded_packet: '0x0000000000000001006cf22bede237a07e121b56d91a491eb7bcdfd1f5907926a9e58338f964a01b17fa006aa5972eee0c9b5bbb89a5b16d1d65f94c9ef25166010000000000000000000000009702230a8ea53601f5cd2dc00fdbc13d4df4a8c700000000000000000000000015028e41c7ed391674505f6ea1213045571564e4000000000000006400' * } * } * ] */ async getOutboundEvents(start, limit) { if (this.sdk.accounts.layerzero === void 0) { throw new Error("sdk accounts layerzero is undefined when invoke getOutboundEvents"); } const events = await this.sdk.client.getEventsByEventHandle( this.sdk.accounts.layerzero, `${this.module}::EventStore`, "outbound_events", { start, limit } ); return events.map((event) => event); } /** * Returns the count of outbound events. * * @returns {Promise} The count of outbound events. * @throws {Error} If sdk accounts layerzero is undefined. */ async getOutboundEventCount() { if (this.sdk.accounts.layerzero === void 0) { throw new Error("sdk accounts layerzero is undefined when invoke getOutboundEventCount"); } const resource = await this.sdk.client.getAccountResource( this.sdk.accounts.layerzero, `${this.module}::EventStore` ); const { outbound_events } = resource.data; return new BN__default.default(outbound_events.counter).toNumber(); } }; var UlnConfig = class { /** * Creates an instance of the UlnConfig class. * * @param {SDK} sdk - The SDK instance. */ constructor(sdk) { this.sdk = sdk; this.module = `${sdk.accounts.layerzero}::uln_config`; this.moduleName = "layerzero::uln_config"; } /** * Oracle type identifier. */ TYPE_ORACLE = 0; /** * Relayer type identifier. */ TYPE_RELAYER = 1; /** * Inbound confirmations type identifier. */ TYPE_INBOUND_CONFIRMATIONS = 2; /** * Outbound confirmations type identifier. */ TYPE_OUTBOUND_CONFIRMATIONS = 3; /** * The module name. */ module; /** * The module name with namespace. */ moduleName; /** * Creates a payload for setting the default app configuration. * * @param {aptos.BCS.Uint16} remoteChainId - The remote chain ID. * @param {UlnConfigType} config - The configuration. * @returns {aptos.Types.EntryFunctionPayload} The payload. */ setDefaultAppConfigPayload(remoteChainId, config) { return { function: `${this.module}::set_default_config`, type_arguments: [], arguments: [ remoteChainId, config.oracle, config.relayer, config.inbound_confirmations, config.outbound_confirmations ] }; } /** * Sets the default app configuration. * * @param {aptos.AptosAccount} signer - The signer account. * @param {aptos.BCS.Uint16} remoteChainId - The remote chain ID. * @param {UlnConfigType} config - The configuration. * @returns {Promise} A promise that resolves to the transaction. */ async setDefaultAppConfig(signer, remoteChainId, config) { const transaction = this.setDefaultAppConfigPayload(remoteChainId, config); return this.sdk.sendAndConfirmTransaction(signer, transaction); } /** * Creates a payload for setting the chain address size. * * @param {aptos.BCS.Uint16} remoteChainId - The remote chain ID. * @param {aptos.BCS.Uint8} addressSize - The address size. * @returns {aptos.Types.EntryFunctionPayload} The payload. */ setChainAddressSizePayload(remoteChainId, addressSize) { return { function: `${this.module}::set_chain_address_size`, type_arguments: [], arguments: [remoteChainId, addressSize] }; } /** * Sets the chain address size. * * @param {aptos.AptosAccount} signer - The signer account. * @param {aptos.BCS.Uint16} remoteChainId - The remote chain ID. * @param {aptos.BCS.Uint8} addressSize - The address size. * @returns {Promise} A promise that resolves to the transaction. */ async setChainAddressSize(signer, remoteChainId, addressSize) { const transaction = this.setChainAddressSizePayload(remoteChainId, addressSize); return this.sdk.sendAndConfirmTransaction(signer, transaction); } /** * Gets the chain address size for a given remote chain ID. * * @param {aptos.BCS.Uint16} remoteChainId - The remote chain ID. * @returns {Promise} A promise that resolves to the address size. * @throws {Error} If the SDK accounts layerzero is undefined. */ async getChainAddressSize(remoteChainId) { if (this.sdk.accounts.layerzero === void 0) { throw new Error("sdk accounts layerzero is undefined when invoke getChainAddressSize"); } const resource = await this.sdk.client.getAccountResource( this.sdk.accounts.layerzero, `${this.module}::ChainConfig` ); const { chain_address_size } = resource.data; const tableHandle = chain_address_size.handle; try { const response = await this.sdk.client.getTableItem(tableHandle, { key_type: "u64", value_type: "u64", key: remoteChainId.toString() }); return Number(response); } catch (e) { if (isErrorOfApiError(e, 404)) { return 0; } throw e; } } /** * Gets the default app configuration for a given remote chain ID. * * @param {aptos.BCS.Uint16} remoteChainId - The remote chain ID. * @param {object} [query] - Optional query parameters. * @param {bigint | number} [query.ledgerVersion] - The ledger version. * @returns {Promise} A promise that resolves to the configuration. * @throws {Error} If the SDK accounts layerzero is undefined. */ async getDefaultAppConfig(remoteChainId, query) { if (this.sdk.accounts.layerzero === void 0) { throw new Error("sdk accounts layerzero is undefined when invoke getDefaultAppConfig"); } const resource = await this.sdk.client.getAccountResource( this.sdk.accounts.layerzero, `${this.module}::DefaultUlnConfig`, query ); const { config } = resource.data; try { return await this.sdk.client.getTableItem( config.handle, { key_type: "u64", value_type: `${this.module}::UlnConfig`, key: remoteChainId.toString() }, query ); } catch (e) { if (isErrorOfApiError(e, 404)) { return { inbound_confirmations: BigInt(0), oracle: "", outbound_confirmations: BigInt(0), relayer: "" }; } throw e; } } /** * Gets the app configuration for a given user address and remote chain ID. * * @param {aptos.MaybeHexString} uaAddress - The user address. * @param {aptos.BCS.Uint16} remoteChainId - The remote chain ID. * @param {object} [query] - Optional query parameters. * @param {bigint | number} [query.ledgerVersion] - The ledger version. * @returns {Promise} A promise that resolves to the configuration. * @throws {Error} If the SDK accounts layerzero is undefined. */ async getAppConfig(uaAddress, remoteChainId, query) { const defaultConfig = await this.getDefaultAppConfig(remoteChainId, query); console.log(`defaultConfig`, defaultConfig); let mergedConfig = { ...defaultConfig }; try { if (this.sdk.accounts.layerzero === void 0) { throw new Error("sdk accounts layerzero is undefined when invoke getAppConfig"); } const resource = await this.sdk.client.getAccountResource( this.sdk.accounts.layerzero, `${this.module}::UaUlnConfig`, query ); const { config } = resource.data; const Config = await this.sdk.client.getTableItem( config.handle, { key_type: `${this.module}::UaConfigKey`, value_type: `${this.module}::UlnConfig`, key: { ua_address: aptos2__namespace.HexString.ensure(uaAddress).toString(), chain_id: remoteChainId.toString() } }, query ); console.log(`Config: `, Config); mergedConfig = this.mergeConfig(Config, defaultConfig); } catch (e) { if (!isErrorOfApiError(e, 404)) { throw e; } } mergedConfig.oracle = fullAddress(mergedConfig.oracle).toString(); mergedConfig.relayer = fullAddress(mergedConfig.relayer).toString(); mergedConfig.inbound_confirmations = BigInt(mergedConfig.inbound_confirmations); mergedConfig.outbound_confirmations = BigInt(mergedConfig.outbound_confirmations); return mergedConfig; } /** * Merges the given configuration with the default configuration. * * @param {UlnConfigType} config - The configuration. * @param {UlnConfigType} defaultConfig - The default configuration. * @returns {UlnConfigType} The merged configuration. */ mergeConfig(config, defaultConfig) { const mergedConfig = { ...defaultConfig }; if (!isZeroAddress(config.oracle)) { mergedConfig.oracle = config.oracle; } if (!isZeroAddress(config.relayer)) { mergedConfig.relayer = config.relayer; } if (config.inbound_confirmations > 0) { mergedConfig.inbound_confirmations = config.inbound_confirmations; } if (config.outbound_confirmations > 0) { mergedConfig.outbound_confirmations = config.outbound_confirmations; } return mergedConfig; } /** * Quotes the fee for a given user address, destination chain ID, and payload size. * * @param {aptos.MaybeHexString} uaAddress - The user address. * @param {aptos.BCS.Uint16} dstChainId - The destination chain ID. * @param {number} payloadSize - The payload size. * @param {object} [query] - Optional query parameters. * @param {bigint | number} [query.ledgerVersion] - The ledger version. * @returns {Promise} A promise that resolves to the fee. * @throws {Error} If the SDK accounts layerzero is undefined. */ async quoteFee(uaAddress, dstChainId, payloadSize, query) { const config = await this.getAppConfig(uaAddress, dstChainId, query); const oracleFee = await this.sdk.LayerzeroModule.Uln.Signer.getFee(config.oracle, dstChainId, query); const relayerFee = await this.sdk.LayerzeroModule.Uln.Signer.getFee(config.relayer, dstChainId, query); if (this.sdk.accounts.layerzero === void 0) { throw new Error("sdk accounts layerzero is undefined when invoke quoteFee"); } const treasuryConfigResource = await this.sdk.client.getAccountResource( this.sdk.accounts.layerzero, `${this.sdk.LayerzeroModule.Uln.MsgLibV1.module}::GlobalStore`, query ); console.log(`treasuryConfigResource`, treasuryConfigResource.data); const { treasury_fee_bps: treasuryFeeBps } = treasuryConfigResource.data; let totalFee = relayerFee.base_fee + relayerFee.fee_per_byte * BigInt(payloadSize); totalFee += oracleFee.base_fee + oracleFee.fee_per_byte * BigInt(payloadSize); totalFee += BigInt(treasuryFeeBps) * totalFee / BigInt(1e4); return totalFee; } }; var UlnReceive = class { /** * Creates an instance of the UlnReceive class. * * @param {SDK} sdk - The SDK instance. */ constructor(sdk) { this.sdk = sdk; this.module = `${sdk.accounts.layerzero}::uln_receive`; } /** * The module name. */ module; /** * Initializes the module. * * @param {aptos.AptosAccount} signer - The signer account. * @returns {Promise} A promise that resolves to the transaction. */ async initialize(signer) { const transaction = { function: `${this.module}::init`, type_arguments: [], arguments: [] }; return this.sdk.sendAndConfirmTransaction(signer, transaction); } /** * Checks if the module is initialized. * * @returns {Promise} A promise that resolves to true if the module is initialized, false otherwise. */ async isInitialize() { try { await this.sdk.client.getAccountResource(this.sdk.accounts.layerzero, `${this.module}::CapStore`); return true; } catch (err) { if (err instanceof aptos2.ApiError && err.errorCode === "resource_not_found") { return false; } throw err; } } /** * Gets the payload for the oracle propose transaction. * * @param {Uint8Array} hash - The hash. * @param {aptos.BCS.Uint64 | aptos.BCS.Uint32} confirmations - The number of confirmations. * @returns {Promise} A promise that resolves to the transaction payload. */ async getOracleProposePayload(hash, confirmations) { const transaction = { function: `${this.module}::oracle_propose`, type_arguments: [], arguments: [Array.from(hash), confirmations] }; return transaction; } /** * Proposes an oracle transaction. * * @param {aptos.AptosAccount} signer - The signer account. * @param {string} hash - The hash. * @param {aptos.BCS.Uint64 | aptos.BCS.Uint32} confirmations - The number of confirmations. * @returns {Promise} A promise that resolves to the transaction. */ async oraclePropose(signer, hash, confirmations) { const transaction = await this.getOracleProposePayload(aptos2.HexString.ensure(hash).toUint8Array(), confirmations); return this.sdk.sendAndConfirmTransaction(signer, transaction); } /** * Gets the proposal for a given oracle and hash. * * @param {aptos.MaybeHexString} oracle - The oracle address. * @param {string} hash - The hash. * @returns {Promise} A promise that resolves to the proposal. */ async getProposal(oracle, hash) { if (this.sdk.accounts.layerzero === void 0) { throw new Error("sdk accounts layerzero is undefined when invoke getProposal"); } const resource = await this.sdk.client.getAccountResource( this.sdk.accounts.layerzero, `${this.module}::ProposalStore` ); const { proposals } = resource.data; const response = await this.sdk.client.getTableItem(proposals.handle, { key_type: `${this.module}::ProposalKey`, value_type: "u64", key: { oracle, hash } }); return BigInt(response); } /** * Gets the payload for the relayer verify transaction. * * @param {Uint8Array} dstAddress - The destination address. * @param {Uint8Array} packetBytes - The packet bytes. * @param {aptos.BCS.Uint64 | aptos.BCS.Uint32} confirmations - The number of confirmations. * @returns {Promise} A promise that resolves to the transaction payload. */ async getRelayerVerifyPayload(dstAddress, packetBytes, confirmations) { const uaTypeInfo = await this.sdk.LayerzeroModule.Endpoint.getUATypeInfo( Buffer.from(dstAddress).toString("hex") ); const transaction = { function: `${this.module}::relayer_verify`, type_arguments: [uaTypeInfo.type], arguments: [Array.from(packetBytes), confirmations] }; return transaction; } /** * Verifies a relayer transaction. * * @param {aptos.AptosAccount} signer - The signer account. * @param {Uint8Array} dstAddress - The destination address. * @param {Uint8Array} packetBytes - The packet bytes. * @param {aptos.BCS.Uint64 | aptos.BCS.Uint32} confirmations - The number of confirmations. * @returns {Promise} A promise that resolves to the transaction. */ async relayerVerify(signer, dstAddress, packetBytes, confirmations) { const transaction = await this.getRelayerVerifyPayload(dstAddress, packetBytes, confirmations); return this.sdk.sendAndConfirmTransaction(signer, transaction); } /** * Gets the payload for the oracle propose transaction with multisig. * * @param {string} multisigAccountAddress - The multisig account address. * @param {Buffer} hash - The hash. * @param {aptos.BCS.Uint64 | aptos.BCS.Uint32} confirmations - The number of confirmations. * @returns {Promise} A promise that resolves to the transaction payload. */ async oracleProposePayloadMS(multisigAccountAddress, hash, confirmations) { const serializer = new aptos2__namespace.BCS.Serializer(); serializer.serializeBytes(Uint8Array.from(hash)); const payloadEntryFunction = new aptos2__namespace.TxnBuilderTypes.TransactionPayloadEntryFunction( aptos2__namespace.TxnBuilderTypes.EntryFunction.natural( this.module, "oracle_propose", [], [serializer.getBytes(), aptos2__namespace.BCS.bcsSerializeUint64(confirmations)] ) ); return payloadEntryFunction; } /** * Gets the raw transaction for the oracle propose transaction with multisig. * * @param {string} multisigAccountAddress - The multisig account address. * @param {Buffer} hash - The hash. * @param {aptos.BCS.Uint64 | aptos.BCS.Uint32} confirmations - The number of confirmations. * @returns {Promise} A promise that resolves to the raw transaction. */ async oracleProposeTxn(multisigAccountAddress, hash, confirmations) { const payloadEntryFunction = await this.oracleProposePayloadMS(multisigAccountAddress, hash, confirmations); const [{ sequence_number: sequenceNumber }, chainId] = await Promise.all([ this.sdk.client.getAccount(multisigAccountAddress), this.sdk.client.getChainId() ]); return new aptos2__namespace.TxnBuilderTypes.RawTransaction( aptos2__namespace.TxnBuilderTypes.AccountAddress.fromHex(multisigAccountAddress), BigInt(sequenceNumber), payloadEntryFunction, BigInt(1e3), BigInt(1), BigInt(Math.floor(Date.now() / 1e3) + 10), new aptos2__namespace.TxnBuilderTypes.ChainId(chainId) ); } /** * Gets the signing message for submitting a hash. * * @param {aptos.TxnBuilderTypes.RawTransaction} txn - The raw transaction. * @returns {aptos.TxnBuilderTypes.SigningMessage} The signing message. */ getSubmitHashSigningMessage(txn) { return aptos2__namespace.TransactionBuilderMultiEd25519.getSigningMessage(txn); } /** * Proposes an oracle transaction with multisig. * * @param {string} multisigAccountAddress - The multisig account address. * @param {aptos.TxnBuilderTypes.MultiEd25519PublicKey} multisigAccountPubkey - The multisig account public key. * @param {MultipleSignFunc} signFunc - The sign function. * @param {Buffer} hash - The hash. * @param {aptos.BCS.Uint64 | aptos.BCS.Uint32} confirmations - The number of confirmations. * @returns {Promise} A promise that resolves to the transaction. */ async oracleProposeMS(multisigAccountAddress, multisigAccountPubkey, signFunc, hash, confirmations) { const payload = await this.oracleProposePayloadMS(multisigAccountAddress, hash, confirmations); return this.sdk.sendAndConfirmMultiSigTransaction( this.sdk.client, multisigAccountAddress, multisigAccountPubkey, payload, signFunc ); } }; var UlnSigner = class { /** * Creates an instance of the UlnSigner class. * * @param {SDK} sdk - The SDK instance. */ constructor(sdk) { this.sdk = sdk; this.module = `${sdk.accounts.layerzero}::uln_signer`; this.moduleName = "layerzero::uln_signer"; } /** * The module name. */ module; /** * The module name with namespace. */ moduleName; /** * Creates a transaction payload for registering. * * @returns {Promise} The transaction payload. */ async register_TransactionPayload() { return new aptos2__namespace.TxnBuilderTypes.TransactionPayloadEntryFunction( aptos2__namespace.TxnBuilderTypes.EntryFunction.natural(this.module, "register", [], []) ); } /** * Registers a multisig account. * * @param {string} multisigAccountAddress - The multisig account address. * @param {aptos.TxnBuilderTypes.MultiEd25519PublicKey} multisigAccountPubkey - The multisig account public key. * @param {MultipleSignFunc} signFunc - The sign function. * @returns {Promise} The transaction. */ async registerMS(multisigAccountAddress, multisigAccountPubkey, signFunc) { const payload = await this.register_TransactionPayload(); return this.sdk.sendAndConfirmMultiSigTransaction( this.sdk.client, multisigAccountAddress, multisigAccountPubkey, payload, signFunc ); } /** * Checks if an address is registered. * * @param {aptos.MaybeHexString} address - The address to check. * @returns {Promise} True if the address is registered, false otherwise. */ async isRegistered(address) { try { await this.sdk.client.getAccountResource(address, `${this.module}::Config`); return true; } catch (e) { if (isErrorOfApiError(e, 404)) { return false; } throw e; } } /** * Creates a payload for registering. * * @returns {aptos.Types.EntryFunctionPayload} The payload. */ registerPayload() { return { function: `${this.module}::register`, type_arguments: [], arguments: [] }; } /** * Registers an account. * * @param {aptos.AptosAccount} signer - The signer account. * @returns {Promise} The transaction. */ async register(signer) { const transaction = this.registerPayload(); return this.sdk.sendAndConfirmTransaction(signer, transaction); } /** * Creates a transaction payload for setting a fee. * * @param {aptos.BCS.Uint16} dstChainId - The destination chain ID. * @param {aptos.BCS.Uint64 | aptos.BCS.Uint32} baseFee - The base fee. * @param {aptos.BCS.Uint64 | aptos.BCS.Uint32} feePerByte - The fee per byte. * @returns {Promise} The transaction payload. */ async getSetFee_TransactionPayload(dstChainId, baseFee, feePerByte) { return new aptos2__namespace.TxnBuilderTypes.TransactionPayloadEntryFunction( aptos2__namespace.TxnBuilderTypes.EntryFunction.natural( this.module, "set_fee", [], [ aptos2__namespace.BCS.bcsSerializeUint64(dstChainId), aptos2__namespace.BCS.bcsSerializeUint64(baseFee), aptos2__namespace.BCS.bcsSerializeUint64(feePerByte) ] ) ); } /** * Creates a payload for setting a fee. * * @param {aptos.BCS.Uint16} dstChainId - The destination chain ID. * @param {aptos.BCS.Uint64 | aptos.BCS.Uint32} baseFee - The base fee. * @param {aptos.BCS.Uint64 | aptos.BCS.Uint32} feePerByte - The fee per byte. * @returns {aptos.Types.EntryFunctionPayload} The payload. */ setFeePayload(dstChainId, baseFee, feePerByte) { return { function: `${this.module}::set_fee`, type_arguments: [], arguments: [dstChainId, baseFee, feePerByte] }; } /** * Sets a fee. * * @param {aptos.AptosAccount} signer - The signer account. * @param {aptos.BCS.Uint16} dstChainId - The destination chain ID. * @param {aptos.BCS.Uint64 | aptos.BCS.Uint32} baseFee - The base fee. * @param {aptos.BCS.Uint64 | aptos.BCS.Uint32} feePerByte - The fee per byte. * @returns {Promise} The transaction. */ async setFee(signer, dstChainId, baseFee, feePerByte) { const transaction = this.setFeePayload(dstChainId, baseFee, feePerByte); return this.sdk.sendAndConfirmTransaction(signer, transaction); } /** * Sets a fee for a multisig account. * * @param {string} multisigAccountAddress - The multisig account address. * @param {aptos.TxnBuilderTypes.MultiEd25519PublicKey} multisigAccountPubkey - The multisig account public key. * @param {MultipleSignFunc} signFunc - The sign function. * @param {aptos.BCS.Uint16} dstChainId - The destination chain ID. * @param {aptos.BCS.Uint64 | aptos.BCS.Uint32} baseFee - The base fee. * @param {aptos.BCS.Uint64 | aptos.BCS.Uint32} feePerByte - The fee per byte. * @returns {Promise} The transaction. */ async setFeeMS(multisigAccountAddress, multisigAccountPubkey, signFunc, dstChainId, baseFee, feePerByte) { const payload = await this.getSetFee_TransactionPayload(dstChainId, baseFee, feePerByte); return this.sdk.sendAndConfirmMultiSigTransaction( this.sdk.client, multisigAccountAddress, multisigAccountPubkey, payload, signFunc ); } /** * Gets the fee for a given address and destination chain ID. * * @param {aptos.MaybeHexString} address - The address. * @param {aptos.BCS.Uint16} dstChainId - The destination chain ID. * @param {Object} [query] - The query parameters. * @param {bigint | number} [query.ledgerVersion] - The ledger version. * @returns {Promise} The fee. */ async getFee(address, dstChainId, query) { try { const resource = await this.sdk.client.getAccountResource(address, `${this.module}::Config`, query); const { fees } = resource.data; const response = await this.sdk.client.getTableItem( fees.handle, { key_type: `u64`, value_type: `${this.module}::Fee`, key: dstChainId.toString() }, query ); return { base_fee: BigInt(response.base_fee), fee_per_byte: BigInt(response.fee_per_byte) }; } catch (e) { if (isErrorOfApiError(e, 404)) { return { base_fee: BigInt(0), fee_per_byte: BigInt(0) }; } throw e; } } }; // src/modules/uln/uln.ts var Uln = class { /** * Instance of UlnReceive. */ Receive; /** * Instance of UlnSigner. */ Signer; /** * Instance of UlnConfig. */ Config; /** * Instance of MsgLibV1_0. */ MsgLibV1; /** * Instance of PacketEvent. */ PacketEvent; /** * Creates an instance of the Uln class. * * @param {SDK} sdk - The SDK instance. */ constructor(sdk) { this.Receive = new UlnReceive(sdk); this.Signer = new UlnSigner(sdk); this.Config = new UlnConfig(sdk); this.MsgLibV1 = new MsgLibV1_0(sdk); this.PacketEvent = new PacketEvent(sdk); } }; // src/modules/index.ts var Layerzero = class { /** * The Channel instance. * @see {@link Channel} */ Channel; /** * The Executor instance. * @see {@link Executor} */ Executor; /** * The Endpoint instance. * @see {@link Endpoint} */ Endpoint; /** * The Uln instance. * @see {@link Uln} */ Uln; /** * The MsgLibConfig instance. * @see {@link MsgLibConfig} */ MsgLibConfig; /** * The MsgLibAuth instance. * @see {@link MsgLibAuth} */ MsgLibAuth; /** * The ExecutorConfig instance. * @see {@link ExecutorConfig} */ ExecutorConfig; /** * Creates an instance of the Layerzero class. * * @param {SDK} sdk - The SDK instance. */ constructor(sdk) { this.Channel = new Channel(sdk); this.Executor = new Executor(sdk); this.Endpoint = new Endpoint(sdk); this.MsgLibConfig = new MsgLibConfig(sdk); this.MsgLibAuth = new MsgLibAuth(sdk); this.ExecutorConfig = new ExecutorConfig(sdk); this.Uln = new Uln(sdk); } }; // src/types/index.ts var types_exports = {}; // src/modules/apps/index.ts var apps_exports = {}; __export(apps_exports, { Coin: () => Coin, Counter: () => Counter, LzApp: () => LzApp, MultisigOracle: () => MultisigOracle, MultisigOracleTss: () => MultisigOracleTss, OFT: () => OFT, Oracle: () => Oracle, PreCrime: () => PreCrime, bridge: () => bridge_exports }); // src/modules/apps/bridge.ts var bridge_exports = {}; __export(bridge_exports, { Bridge: () => Bridge, DEFAULT_LIMITER_CAP_SD: () => DEFAULT_LIMITER_CAP_SD, DEFAULT_LIMITER_WINDOW_SEC: () => DEFAULT_LIMITER_WINDOW_SEC, PacketType: () => PacketType }); var LzApp = class { /** * The SDK instance. */ sdk; /** * The LzApp address. */ lzApp; /** * The UA address. */ ua; /** * Creates an instance of the LzApp class. * * @param {SDK} sdk - The SDK instance. * @param {aptos.MaybeHexString} lzApp - The LzApp address. * @param {aptos.MaybeHexString} ua - The UA address. */ constructor(sdk, lzApp, ua) { this.sdk = sdk; this.lzApp = lzApp; this.ua = ua; } /** * Gets the remote address for a given remote chain ID. * * @param {aptos.BCS.Uint16} remoteChainId - The remote chain ID. * @returns {Promise} A promise that resolves to the remote address. */ async getRemote(remoteChainId) { const resource = await this.sdk.client.getAccountResource(this.ua, `${this.lzApp}::remote::Remotes`); const { peers } = resource.data; const trustedRemoteHandle = peers.handle; const response = await this.sdk.client.getTableItem(trustedRemoteHandle, { key_type: "u64", value_type: "vector", key: remoteChainId.toString() }); return Uint8Array.from(Buffer.from(aptos2__namespace.HexString.ensure(response).noPrefix(), "hex")); } /** * Gets the minimum destination gas for a given UA type, remote chain ID, and packet type. * * @param {string} uaType - The UA type. * @param {aptos.BCS.Uint16} remoteChainId - The remote chain ID. * @param {aptos.BCS.Uint64} packetType - The packet type. * @returns {Promise} A promise that resolves to the minimum destination gas. */ async getMinDstGas(uaType, remoteChainId, packetType) { const resource = await this.sdk.client.getAccountResource(this.ua, `${this.lzApp}::lzapp::Config`); const { min_dst_gas_lookup } = resource.data; try { const response = await this.sdk.client.getTableItem(min_dst_gas_lookup.handle, { key_type: `${this.lzApp}::lzapp::Path`, value_type: "u64", key: { chain_id: remoteChainId.toString(), packet_type: packetType.toString() } }); return response; } catch (e) { if (isErrorOfApiError(e, 404)) { return BigInt(0); } throw e; } } /** * Creates a payload for setting the minimum destination gas. * * @param {string} uaType - The UA type. * @param {aptos.BCS.Uint16} remoteChainId - The remote chain ID. * @param {aptos.BCS.Uint64} packetType - The packet type. * @param {aptos.BCS.Uint64} minDstGas - The minimum destination gas. * @returns {aptos.Types.EntryFunctionPayload} The payload. */ setMinDstPayload(uaType, remoteChainId, packetType, minDstGas) { return { function: `${this.lzApp}::lzapp::set_min_dst_gas`, type_arguments: [uaType], arguments: [remoteChainId, packetType.toString(), minDstGas.toString()] }; } /** * Sets the minimum destination gas. * * @param {aptos.AptosAccount} signer - The signer account. * @param {string} uaType - The UA type. * @param {aptos.BCS.Uint16} remoteChainId - The remote chain ID. * @param {aptos.BCS.Uint64} packetType - The packet type. * @param {aptos.BCS.Uint64} minDstGas - The minimum destination gas. * @returns {Promise} A promise that resolves to the transaction. */ async setMinDstGas(signer, uaType, remoteChainId, packetType, minDstGas) { const transaction = this.setMinDstPayload(uaType, remoteChainId, packetType, minDstGas); return this.sdk.sendAndConfirmTransaction(signer, transaction); } /** * Creates a payload for setting the remote address. * * @param {aptos.BCS.Uint16} remoteChainId - The remote chain ID. * @param {aptos.BCS.Bytes} remoteAddress - The remote address. * @returns {aptos.Types.EntryFunctionPayload} The payload. */ setRemotePaylaod(remoteChainId, remoteAddress) { return { function: `${this.lzApp}::remote::set`, type_arguments: [], arguments: [remoteChainId, Array.from(remoteAddress)] }; } /** * Sets the remote address. * * @param {aptos.AptosAccount} signer - The signer account. * @param {aptos.BCS.Uint16} remoteChainId - The remote chain ID. * @param {aptos.BCS.Bytes} remoteAddress - The remote address. * @returns {Promise} A promise that resolves to the transaction. */ async setRemote(signer, remoteChainId, remoteAddress) { const expectedAddressSize = await this.sdk.LayerzeroModule.Uln.Config.getChainAddressSize(remoteChainId); if (expectedAddressSize !== remoteAddress.length) { const address = Buffer.from(remoteAddress).toString("hex"); throw new Error(`address(${address}) doesn't match expected size(${expectedAddressSize})`); } const transaction = this.setRemotePaylaod(remoteChainId, remoteAddress); return this.sdk.sendAndConfirmTransaction(signer, transaction); } /** * Creates a payload for setting the configuration. * * @param {string} uaType - The UA type. * @param {aptos.BCS.Uint16} majorVersion - The major version. * @param {aptos.BCS.Uint8} minorVersion - The minor version. * @param {aptos.BCS.Uint16} remoteChainId - The remote chain ID. * @param {aptos.BCS.Uint8} configType - The configuration type. * @param {aptos.BCS.Bytes} configBytes - The configuration bytes. * @returns {aptos.Types.EntryFunctionPayload} The payload. */ setConfigPayload(uaType, majorVersion, minorVersion, remoteChainId, configType, configBytes) { return { function: `${this.lzApp}::lzapp::set_config`, type_arguments: [uaType], arguments: [majorVersion, minorVersion, remoteChainId, configType, Array.from(configBytes)] }; } /** * Sets the configuration. * * @param {aptos.AptosAccount} signer - The signer account. * @param {string} uaType - The UA type. * @param {aptos.BCS.Uint16} majorVersion - The major version. * @param {aptos.BCS.Uint8} minorVersion - The minor version. * @param {aptos.BCS.Uint16} remoteChainId - The remote chain ID. * @param {aptos.BCS.Uint8} configType - The configuration type. * @param {aptos.BCS.Bytes} configBytes - The configuration bytes. * @returns {Promise} A promise that resolves to the transaction. */ async setConfig(signer, uaType, majorVersion, minorVersion, remoteChainId, configType, configBytes) { console.log(`configType: ${configType}, configBytes: ${configBytes}`); const transaction = { function: `${this.lzApp}::lzapp::set_config`, type_arguments: [uaType], arguments: [majorVersion, minorVersion, remoteChainId, configType, Array.from(configBytes)] }; return this.sdk.sendAndConfirmTransaction(signer, transaction); } /** * Sets the configuration bundle. * * @param {aptos.AptosAccount} signer - The signer account. * @param {string} uaType - The UA type. * @param {aptos.BCS.Uint16} majorVersion - The major version. * @param {aptos.BCS.Uint8} minorVersion - The minor version. * @param {aptos.BCS.Uint16} remoteChainId - The remote chain ID. * @param {UlnConfigType} config - The configuration. * @returns {Promise} A promise that resolves when the configuration bundle is set. */ async setConfigBundle(signer, uaType, majorVersion, minorVersion, remoteChainId, config) { await this.setConfig( signer, uaType, majorVersion, minorVersion, remoteChainId, this.sdk.LayerzeroModule.Uln.Config.TYPE_ORACLE, Buffer.from(aptos2__namespace.HexString.ensure(config.oracle).noPrefix(), "hex") ); await this.setConfig( signer, uaType, majorVersion, minorVersion, remoteChainId, this.sdk.LayerzeroModule.Uln.Config.TYPE_RELAYER, Buffer.from(aptos2__namespace.HexString.ensure(config.relayer).noPrefix(), "hex") ); console.log(`setAppConfig inbound_confirmations: ${config.inbound_confirmations}`); await this.setConfig( signer, uaType, majorVersion, minorVersion, remoteChainId, this.sdk.LayerzeroModule.Uln.Config.TYPE_INBOUND_CONFIRMATIONS, aptos2__namespace.BCS.bcsSerializeUint64(config.inbound_confirmations).reverse() // BCS is little endian, but we want big endian ); await this.setConfig( signer, uaType, majorVersion, minorVersion, remoteChainId, this.sdk.LayerzeroModule.Uln.Config.TYPE_OUTBOUND_CONFIRMATIONS, aptos2__namespace.BCS.bcsSerializeUint64(config.outbound_confirmations).reverse() // BCS is little endian, but we want big endian ); } }; // src/modules/apps/bridge.ts var DEFAULT_LIMITER_CAP_SD = 1e12; var DEFAULT_LIMITER_WINDOW_SEC = 3600 * 4; var PacketType = /* @__PURE__ */ ((PacketType2) => { PacketType2[PacketType2["RECIEVE"] = 0] = "RECIEVE"; PacketType2[PacketType2["SEND"] = 1] = "SEND"; return PacketType2; })(PacketType || {}); var Bridge = class { sdk; coin; lzApp; uaType; address; module; moduleName; SEND_PAYLOAD_LENGTH = 74; /** * Creates an instance of Bridge. * * @param {SDK} sdk - The SDK instance. * @param {Coin} coin - The coin instance. * @param {aptos.MaybeHexString} [bridge] - The bridge address. * @param {aptos.MaybeHexString} [lzApp] - The LzApp address. */ constructor(sdk, coin, bridge, lzApp) { this.sdk = sdk; this.coin = coin; this.address = bridge ?? BRIDGE_ADDRESS[sdk.stage]; this.lzApp = new LzApp(sdk, lzApp || sdk.accounts.layerzero, this.address); this.uaType = `${this.address}::coin_bridge::BridgeUA`; this.module = `${this.address}::coin_bridge`; this.moduleName = "bridge::coin_bridge"; } /** * Sets the application configuration. * * @param {aptos.AptosAccount} signer - The signer account. * @param {aptos.BCS.Uint16} major - The major version. * @param {aptos.BCS.Uint8} minor - The minor version. * @param {aptos.BCS.Uint16} remoteChainId - The remote chain ID. * @param {aptos.BCS.Uint8} configType - The configuration type. * @param {aptos.BCS.Bytes} configBytes - The configuration bytes. * @returns {Promise} The transaction. */ async setAppConfig(signer, major, minor, remoteChainId, configType, configBytes) { return this.lzApp.setConfig(signer, this.uaType, major, minor, remoteChainId, configType, configBytes); } /** * Gets the minimum destination gas. * * @param {aptos.BCS.Uint16} dstChainId - The destination chain ID. * @param {aptos.BCS.Uint64} type - The type. * @returns {Promise} The minimum destination gas. */ async getMinDstGas(dstChainId, type) { return this.lzApp.getMinDstGas(this.uaType, dstChainId, type); } /** * Sets the minimum destination gas payload. * * @param {aptos.BCS.Uint16} dstChainId - The destination chain ID. * @param {aptos.BCS.Uint64} packetType - The packet type. * @param {aptos.BCS.Uint64} minGas - The minimum gas. * @returns {aptos.Types.EntryFunctionPayload} The entry function payload. */ setMinDstGasPayload(dstChainId, packetType, minGas) { return this.lzApp.setMinDstPayload(this.uaType, dstChainId, packetType, minGas); } /** * @deprecated use {@link isCustomAdapterParamsEnabled} instead */ async customAdapterParamsEnabled() { return this.isCustomAdapterParamsEnabled(); } /** * Checks if custom adapter parameters are enabled. * * @returns {Promise} True if custom adapter parameters are enabled, false otherwise. */ async isCustomAdapterParamsEnabled() { const resource = await this.sdk.client.getAccountResource(this.address, `${this.address}::coin_bridge::Config`); const { custom_adapter_params } = resource.data; return custom_adapter_params; } /** * Enables or disables custom adapter parameters. * * @param {boolean} enable - Whether to enable custom adapter parameters. * @returns {aptos.Types.EntryFunctionPayload} The entry function payload. */ enableCustomAdapterParamsPayload(enable) { return { function: `${this.module}::enable_custom_adapter_params`, type_arguments: [], arguments: [enable] }; } /** * Sets the remote bridge payload. * * @param {aptos.BCS.Uint16} remoteChainId - The remote chain ID. * @param {aptos.BCS.Bytes} remoteBridgeAddr - The remote bridge address. * @returns {aptos.Types.EntryFunctionPayload} The entry function payload. */ setRemoteBridgePayload(remoteChainId, remoteBridgeAddr) { return this.lzApp.setRemotePaylaod(remoteChainId, remoteBridgeAddr); } /** * Sets the remote bridge. * * @param {aptos.AptosAccount} signer - The signer account. * @param {aptos.BCS.Uint16} remoteChainId - The remote chain ID. * @param {aptos.BCS.Bytes} remoteBridgeAddr - The remote bridge address. * @returns {Promise} The transaction. */ async setRemoteBridge(signer, remoteChainId, remoteBridgeAddr) { return this.lzApp.setRemote(signer, remoteChainId, remoteBridgeAddr); } /** * Registers a coin payload. * * @param {BridgeCoinType} coin - The coin type. * @param {string} name - The name of the coin. * @param {string} symbol - The symbol of the coin. * @param {aptos.BCS.Uint8} decimals - The decimals of the coin. * @param {aptos.BCS.Uint32 | aptos.BCS.Uint64} limiterCapSD - The limiter cap in SD. * @returns {aptos.Types.EntryFunctionPayload} The entry function payload. */ registerCoinPayload(coin, name, symbol, decimals, limiterCapSD) { return { function: `${this.module}::register_coin`, type_arguments: [this.coin.getCoinType(coin)], arguments: [name, symbol, decimals, limiterCapSD] }; } /** * Registers a coin. * * @param {aptos.AptosAccount} signer - The signer account. * @param {BridgeCoinType} coin - The coin type. * @param {string} name - The name of the coin. * @param {string} symbol - The symbol of the coin. * @param {aptos.BCS.Uint8} decimals - The decimals of the coin. * @param {aptos.BCS.Uint32 | aptos.BCS.Uint64} limiterCapSD - The limiter cap in SD. * @returns {Promise} The transaction. */ async registerCoin(signer, coin, name, symbol, decimals, limiterCapSD) { const transaction = this.registerCoinPayload(coin, name, symbol, decimals, limiterCapSD); return this.sdk.sendAndConfirmTransaction(signer, transaction); } /** * Sets the remote coin payload. * * @param {BridgeCoinType} coin - The coin type. * @param {aptos.BCS.Uint16} remoteChainId - The remote chain ID. * @param {aptos.MaybeHexString} remoteCoinAddr - The remote coin address. * @param {boolean} unwrappable - Whether the coin is unwrappable. * @returns {aptos.Types.EntryFunctionPayload} The entry function payload. */ setRemoteCoinPayload(coin, remoteChainId, remoteCoinAddr, unwrappable) { const remoteCoinAddrBytes = stringToPaddedUint8Array(remoteCoinAddr.toString(), 32); return { function: `${this.module}::set_remote_coin`, type_arguments: [this.coin.getCoinType(coin)], arguments: [remoteChainId, Array.from(remoteCoinAddrBytes), unwrappable] }; } /** * Sets the remote coin. * * @param {aptos.AptosAccount} signer - The signer account. * @param {BridgeCoinType} coin - The coin type. * @param {aptos.BCS.Uint16} remoteChainId - The remote chain ID. * @param {aptos.MaybeHexString} remoteCoinAddr - The remote coin address. * @param {boolean} unwrappable - Whether the coin is unwrappable. * @returns {Promise} The transaction. */ async setRemoteCoin(signer, coin, remoteChainId, remoteCoinAddr, unwrappable) { const transaction = this.setRemoteCoinPayload(coin, remoteChainId, remoteCoinAddr, unwrappable); return this.sdk.sendAndConfirmTransaction(signer, transaction); } /** * Sets the force resume payload. * * @param {aptos.BCS.Uint16} srcChainId - The source chain ID. * @returns {aptos.Types.EntryFunctionPayload} The entry function payload. */ forceResumePayload(srcChainId) { return { function: `${this.module}::force_resume`, type_arguments: [], arguments: [srcChainId] }; } /** * Sets the force resume. * * @param {aptos.AptosAccount} signer - The signer account. * @param {aptos.BCS.Uint16} srcChainId - The source chain ID. * @returns {Promise} The transaction. */ async forceResume(signer, srcChainId) { const transaction = this.forceResumePayload(srcChainId); return this.sdk.sendAndConfirmTransaction(signer, transaction); } /** * Sets the pause state for a coin. * * @param {aptos.AptosAccount} signer - The signer account. * @param {BridgeCoinType} coin - The coin type. * @param {boolean} paused - Whether to pause the coin. * @returns {Promise} The transaction. */ async setPause(signer, coin, paused) { const transaction = { function: `${this.module}::set_pause`, type_arguments: [coin], arguments: [paused] }; return this.sdk.sendAndConfirmTransaction(signer, transaction); } /** * Sets the send coin payload. * * @param {BridgeCoinType} coin - The coin type. * @param {aptos.BCS.Uint16} dstChainId - The destination chain ID. * @param {aptos.BCS.Bytes} dstReceiver - The destination receiver address. * @param {aptos.BCS.Uint64 | aptos.BCS.Uint32} amountLD - The amount in LD. * @param {aptos.BCS.Uint64 | aptos.BCS.Uint32} nativeFee - The native fee. * @param {aptos.BCS.Uint64 | aptos.BCS.Uint32} zroFee - The ZRO fee. * @param {boolean} unwrap - Whether to unwrap the coin. * @param {aptos.BCS.Bytes} adapterParams - The adapter parameters. * @param {aptos.BCS.Bytes} msglibParams - The message library parameters. * @returns {aptos.Types.EntryFunctionPayload} The entry function payload. */ sendCoinPayload(coin, dstChainId, dstReceiver, amountLD, nativeFee, zroFee, unwrap, adapterParams, msglibPararms) { return { function: `${this.module}::send_coin_from`, type_arguments: [this.coin.getCoinType(coin)], arguments: [ dstChainId.toString(), Array.from(dstReceiver), amountLD.toString(), nativeFee.toString(), zroFee.toString(), unwrap.toString(), Array.from(adapterParams), Array.from(msglibPararms) ] }; } /** * Sends a coin. * * @param {aptos.AptosAccount} signer - The signer account. * @param {BridgeCoinType} coin - The coin type. * @param {aptos.BCS.Uint16} dstChainId - The destination chain ID. * @param {aptos.BCS.Bytes} dstReceiver - The destination receiver address. * @param {aptos.BCS.Uint64 | aptos.BCS.Uint32} amountLD - The amount in LD. * @param {aptos.BCS.Uint64 | aptos.BCS.Uint32} nativeFee - The native fee. * @param {aptos.BCS.Uint64 | aptos.BCS.Uint32} zroFee - The ZRO fee. * @param {boolean} unwrap - Whether to unwrap the coin. * @param {aptos.BCS.Bytes} adapterParams - The adapter parameters. * @param {aptos.BCS.Bytes} msglibParams - The message library parameters. * @returns {Promise} The transaction. */ async sendCoin(signer, coin, dstChainId, dstReceiver, amountLD, nativeFee, zroFee, unwrap, adapterParams, msglibParams) { const transaction = this.sendCoinPayload( coin, dstChainId, dstReceiver, amountLD, nativeFee, zroFee, unwrap, adapterParams, msglibParams ); return this.sdk.sendAndConfirmTransaction(signer, transaction); } /** * Sets the lz receive payload. * * @param {BridgeCoinType} coin - The coin type. * @param {aptos.BCS.Uint16} srcChainId - The source chain ID. * @param {aptos.BCS.Bytes} srcAddress - The source address. * @param {aptos.BCS.Bytes} payload - The payload. * @returns {aptos.Types.EntryFunctionPayload} The entry function payload. */ lzReceivePayload(coin, srcChainId, srcAddress, payload) { return { function: `${this.module}::lz_receive`, type_arguments: [this.coin.getCoinType(coin)], arguments: [srcChainId, Array.from(srcAddress), Array.from(payload)] }; } /** * Receives a LayerZero message. * * @param {aptos.AptosAccount} signer - The signer account. * @param {BridgeCoinType} coin - The coin type. * @param {aptos.BCS.Uint16} srcChainId - The source chain ID. * @param {aptos.BCS.Bytes} srcAddress - The source address. * @param {aptos.BCS.Bytes} payload - The payload. * @returns {Promise} A promise that resolves to the transaction. */ async lzReceive(signer, coin, srcChainId, srcAddress, payload) { const transaction = this.lzReceivePayload(coin, srcChainId, srcAddress, payload); return this.sdk.sendAndConfirmTransaction(signer, transaction); } /** * Gets the types from a packet. * * @param {Packet} packet - The packet. * @returns {Promise} A promise that resolves to the types. */ async getTypesFromPacket(packet) { const payload = decodePayload(packet.payload); const coinType = await this.getCoinTypeByRemoteCoin(packet.src_chain_id, payload.remoteCoinAddr); return [coinType.type]; } /** * Creates a payload for claiming a coin. * * @param {BridgeCoinType} coin - The coin type. * @returns {aptos.Types.EntryFunctionPayload} The payload. */ claimCoinPayload(coin) { return { function: `${this.module}::claim_coin`, type_arguments: [this.coin.getCoinType(coin)], arguments: [] }; } /** * Claims a coin. * * @param {aptos.AptosAccount} signer - The signer account. * @param {BridgeCoinType} coin - The coin type. * @returns {Promise} A promise that resolves to the transaction. */ async claimCoin(signer, coin) { const transaction = this.claimCoinPayload(coin); return this.sdk.sendAndConfirmTransaction(signer, transaction); } /** * Checks if the global pause is enabled. * * @returns {Promise} A promise that resolves to true if the global pause is enabled, false otherwise. */ async globalPaused() { const resource = await this.sdk.client.getAccountResource(this.address, `${this.module}::Config`); const { paused_global } = resource.data; return paused_global; } // todo: add version // async getAppConfig(remoteChainId: aptos.BCS.Uint16): Promise { // // } /** * Gets the remote bridge address for a given remote chain ID. * * @param {aptos.BCS.Uint16} remoteChainId - The remote chain ID. * @returns {Promise} A promise that resolves to the remote bridge address. */ async getRemoteBridge(remoteChainId) { try { return await this.lzApp.getRemote(remoteChainId); } catch (e) { if (isErrorOfApiError(e, 404)) { return new Uint8Array(0); } throw e; } } /** * Gets the coin type by remote coin address. * * @param {string | aptos.BCS.Uint16} remoteChainId - The remote chain ID. * @param {aptos.BCS.Bytes} remoteCoinAddr - The remote coin address. * @returns {Promise} A promise that resolves to the coin type information. */ async getCoinTypeByRemoteCoin(remoteChainId, remoteCoinAddr) { const resource = await this.getCoinTypeStore(); const { type_lookup } = resource.data; const coinInfosHandle = type_lookup.handle; const typeInfo = await this.sdk.client.getTableItem(coinInfosHandle, { key_type: `${this.module}::Path`, value_type: `0x1::type_info::TypeInfo`, key: { remote_chain_id: remoteChainId.toString(), remote_coin_addr: Buffer.from(remoteCoinAddr).toString("hex") } }); const info = normalizeTypeInfo(typeInfo); return { ...info, type: buildStructTagFromTypeInfo(info) }; } /** * Gets the remote coin information. * * @param {MayBeBridgeCoinType} coin - The coin type. * @param {aptos.BCS.Uint16} remoteChainId - The remote chain ID. * @returns {Promise} A promise that resolves to the remote coin information. */ async getRemoteCoin(coin, remoteChainId) { const resource = await this.getCoinStore(coin); const { remote_coins } = resource.data; const remoteCoinHandle = remote_coins.handle; const remoteCoin = await this.sdk.client.getTableItem(remoteCoinHandle, { key_type: "u64", value_type: `${this.module}::RemoteCoin`, key: remoteChainId.toString() }); const address = Uint8Array.from( Buffer.from(aptos2__namespace.HexString.ensure(remoteCoin.remote_address).noPrefix(), "hex") ); const tvlSD = BigInt(remoteCoin.tvl_sd); const { unwrappable } = remoteCoin; return { address, tvlSD, unwrappable }; } /** * Gets the coin store resource. * * @param {MayBeBridgeCoinType} coin - The coin type. * @returns {Promise} A promise that resolves to the coin store resource. */ async getCoinStore(coin) { return this.sdk.client.getAccountResource( this.address, `${this.module}::CoinStore<${this.coin.getCoinType(coin)}>` ); } /** * Gets the remote chains for a given coin. * * @param {MayBeBridgeCoinType} coin - The coin type. * @returns {Promise} A promise that resolves to the remote chains. */ async getRemoteChains(coin) { const resource = await this.getCoinStore(coin); const { remote_chains: remoteChains } = resource.data; return remoteChains; } /** * Gets the remote coins for a given coin. * * @param {MayBeBridgeCoinType} coin - The coin type. * @returns {Promise} A promise that resolves to the remote coins. */ async getRemoteCoins(coin) { const remoteChains = await this.getRemoteChains(coin); const rtn = []; for (const remoteChainId of remoteChains) { const remoteCoin = await this.getRemoteCoin(coin, parseInt(remoteChainId)); rtn.push(remoteCoin); } return rtn; } /** * Checks if a remote coin exists for a given coin and remote chain ID. * * @param {BridgeCoinType} coin - The coin type. * @param {aptos.BCS.Uint16} remoteChainId - The remote chain ID. * @returns {Promise} A promise that resolves to true if the remote coin exists, false otherwise. */ async hasRemoteCoin(coin, remoteChainId) { try { const remoteCoin = await this.getRemoteCoin(coin, remoteChainId); return remoteCoin !== void 0; } catch (e) { if (isErrorOfApiError(e, 404)) { return false; } throw e; } } /** * Gets the claimable coin amount for a given coin and owner. * * @param {BridgeCoinType} coin - The coin type. * @param {aptos.MaybeHexString} owner - The owner address. * @returns {Promise} A promise that resolves to the claimable coin amount. */ async getClaimableCoin(coin, owner) { const resource = await this.getCoinStore(coin); const { claimable_amt_ld } = resource.data; const claimableAmtLDHandle = claimable_amt_ld.handle; try { const response = await this.sdk.client.getTableItem(claimableAmtLDHandle, { key_type: "address", value_type: "u64", key: owner }); return BigInt(response); } catch (e) { if (isErrorOfApiError(e, 404)) { return BigInt(0); } throw e; } } /** * Checks if a coin is registered. * * @param {BridgeCoinType} coin - The coin type. * @returns {Promise} A promise that resolves to true if the coin is registered, false otherwise. */ async hasCoinRegistered(coin) { try { const resource = await this.getCoinStore(coin); return resource !== void 0; } catch (e) { if (isErrorOfApiError(e, 404)) { return false; } throw e; } } /** * Gets the LD to SD rate for a given coin. * * @param {BridgeCoinType} coin - The coin type. * @returns {Promise} A promise that resolves to the LD to SD rate. */ async getLd2SdRate(coin) { const resource = await this.getCoinStore(coin); const { ld2sd_rate } = resource.data; return ld2sd_rate; } /** * Converts an amount from SD to LD. * * @param {BridgeCoinType} coin - The coin type. * @param {aptos.BCS.Uint64 | aptos.BCS.Uint32} amountSD - The amount in SD. * @returns {Promise} A promise that resolves to the amount in LD. */ async convertAmountToLD(coin, amountSD) { const rate = await this.getLd2SdRate(coin); return BigInt(amountSD) * BigInt(rate); } /** * Converts an amount from LD to SD. * * @param {BridgeCoinType} coin - The coin type. * @param {aptos.BCS.Uint64 | aptos.BCS.Uint32} amountLD - The amount in LD. * @returns {Promise} A promise that resolves to the amount in SD. */ async convertAmountToSD(coin, amountLD) { const rate = await this.getLd2SdRate(coin); return BigInt(amountLD) / BigInt(rate); } /** * Creates a payload for registering a coin. * * @param {BridgeCoinType} coin - The coin type. * @returns {aptos.Types.EntryFunctionPayload} The payload. */ registerPayload(coin) { return { function: `0x1::managed_coin::register`, type_arguments: [this.coin.getCoinType(coin)], arguments: [] }; } /** * Registers a coin. * * @param {aptos.AptosAccount} signer - The signer account. * @param {BridgeCoinType} coin - The coin type. * @returns {Promise} A promise that resolves to the transaction. */ async coinRegister(signer, coin) { const transaction = this.registerPayload(coin); return this.sdk.sendAndConfirmTransaction(signer, transaction); } /** * Gets the coin type store resource. * * @returns {Promise} A promise that resolves to the coin type store resource. */ async getCoinTypeStore() { return this.sdk.client.getAccountResource(this.address, `${this.module}::CoinTypeStore`); } /** * Gets the coin types. * * @returns {Promise} A promise that resolves to the coin types. */ async getCoinTypes() { const resource = await this.getCoinTypeStore(); const { types: coinTypes } = resource.data; const rtn = []; for (const typeInfo of coinTypes) { const info = normalizeTypeInfo(typeInfo); rtn.push({ ...info, type: buildStructTagFromTypeInfo(info) }); } return rtn; } /** * Gets the coin information for a given coin type. * * @param {MayBeBridgeCoinType} coinType - The coin type. * @returns {Promise} A promise that resolves to the coin information. */ async getCoinInfo(coinType) { const coinStructTag = this.coin.getCoinType(coinType); const typeInfo = `0x1::coin::CoinInfo<${coinStructTag}>`; const resource = await this.sdk.client.getAccountResource(this.address, typeInfo); const coinInfo = resource; const { name } = coinInfo.data; const { symbol } = coinInfo.data; const { decimals } = coinInfo.data; const supply = coinInfo.data.supply.vec[0].integer.vec[0].value; return { name, symbol, decimals, supply: BigInt(supply), type: coinStructTag }; } /** * Gets the limited amount for a given coin. * * @param {BridgeCoinType} coin - The coin type. * @returns {Promise<{ limited: boolean; amount: aptos.BCS.Uint64 }>} A promise that resolves to the limited amount. */ async getLimitedAmount(coin) { const resource = await this.sdk.client.getAccountResource( this.address, `${this.address}::limiter::Limiter<${this.coin.getCoinType(coin)}>` ); const { enabled } = resource.data; if (!enabled) { return { limited: false, amount: BigInt(0) }; } const data = resource.data; const limiter = { t0Sec: BigInt(data.t0_sec), windowSec: BigInt(data.window_sec), sumSD: BigInt(data.sum_sd), capSD: BigInt(data.cap_sd) }; const now = await this.getCurrentTimestamp(); let count = (now - limiter.t0Sec) / limiter.windowSec; while (count > 0) { limiter.sumSD /= BigInt(2); count -= BigInt(1); } const limitedAmtSD = limiter.capSD - limiter.sumSD; return { limited: true, amount: await this.convertAmountToLD(coin, limitedAmtSD) }; } /** * Gets the current timestamp. * * @returns {Promise} A promise that resolves to the current timestamp. */ async getCurrentTimestamp() { const resource = await this.sdk.client.getAccountResource("0x1", "0x1::timestamp::CurrentTimeMicroseconds"); const { microseconds } = resource.data; return BigInt(microseconds) / BigInt(1e6); } /** * Creates a payload for setting the limiter cap. * * @param {BridgeCoinType} coin - The coin type. * @param {boolean} enable - Whether to enable the limiter. * @param {aptos.BCS.Uint32 | aptos.BCS.Uint64} capSD - The cap in SD. * @param {aptos.BCS.Uint32 | aptos.BCS.Uint64} windowSec - The window in seconds. * @returns {aptos.Types.EntryFunctionPayload} The payload. */ setLimiterCapPayload(coin, enable, capSD, windowSec) { return { function: `${this.module}::set_limiter_cap`, type_arguments: [this.coin.getCoinType(coin)], arguments: [enable, capSD.toString(), windowSec.toString()] }; } /** * Sets the limiter cap. * * @param {aptos.AptosAccount} signer - The signer account. * @param {BridgeCoinType} coin - The coin type. * @param {boolean} enable - Whether to enable the limiter. * @param {aptos.BCS.Uint32 | aptos.BCS.Uint64} capSD - The cap in SD. * @param {aptos.BCS.Uint32 | aptos.BCS.Uint64} windowSec - The window in seconds. * @returns {Promise} A promise that resolves to the transaction. */ async setLimiterCap(signer, coin, enable, capSD, windowSec) { const transaction = this.setLimiterCapPayload(coin, enable, capSD, windowSec); return this.sdk.sendAndConfirmTransaction(signer, transaction); } /** * Gets the limit cap for a given coin. * * @param {BridgeCoinType} coin - The coin type. * @returns {Promise<{ enabled: boolean; capSD: aptos.BCS.Uint64; windowSec: aptos.BCS.Uint64 }>} A promise that resolves to an object containing the limit cap information. * @throws {Error} If an error occurs while fetching the limit cap. */ async getLimitCap(coin) { try { const resource = await this.sdk.client.getAccountResource( this.address, `${this.address}::limiter::Limiter<${this.coin.getCoinType(coin)}>` ); const { enabled, cap_sd, window_sec } = resource.data; return { enabled, capSD: BigInt(cap_sd), windowSec: BigInt(window_sec) }; } catch (e) { if (isErrorOfApiError(e, 404)) { return { enabled: true, capSD: BigInt(DEFAULT_LIMITER_CAP_SD), windowSec: BigInt(DEFAULT_LIMITER_WINDOW_SEC) }; } throw e; } } /** * Sets the global pause state. * * @param {aptos.AptosAccount} signer - The signer account. * @param {boolean} pause - The pause state to set. * @returns {Promise} A promise that resolves to the transaction. */ async setGlobalPause(signer, pause) { const transaction = { function: `${this.module}::set_global_pause`, type_arguments: [], arguments: [pause] }; return this.sdk.sendAndConfirmTransaction(signer, transaction); } }; // src/modules/apps/coin.ts var CoinType = /* @__PURE__ */ ((CoinType2) => { CoinType2["APTOS"] = "AptosCoin"; CoinType2["WETH"] = "WETH"; CoinType2["WBTC"] = "WBTC"; CoinType2["USDC"] = "USDC"; CoinType2["USDT"] = "USDT"; CoinType2["BUSD"] = "BUSD"; CoinType2["USDD"] = "USDD"; return CoinType2; })(CoinType || {}); function isCoinType(value) { return Object.values(CoinType).includes(value); } var Coin = class { sdk; bridge; /** * Creates an instance of the Coin class. * * @param {SDK} sdk - The SDK instance. * @param {aptos.MaybeHexString} [bridge] - The bridge address. */ constructor(sdk, bridge) { this.sdk = sdk; this.bridge = bridge ?? BRIDGE_ADDRESS[sdk.stage]; } /** * Gets the coin type as a string. * * @param {CoinType | string | TypeInfo} coin - The coin type. * @returns {string} The coin type as a string. */ getCoinType(coin) { if (isTypeInfo(coin)) { return buildStructTagFromTypeInfo(coin); } if (isCoinType(coin)) { switch (coin) { case "AptosCoin" /* APTOS */: return `0x1::aptos_coin::${coin}`; default: return `${this.bridge}::asset::${coin}`; } } return coin; } /** * Creates a payload for transferring a coin. * * @param {CoinType} coin - The coin type. * @param {aptos.MaybeHexString} to - The recipient address. * @param {aptos.BCS.Uint64 | aptos.BCS.Uint32} amount - The amount to transfer. * @returns {aptos.Types.EntryFunctionPayload} The payload. */ transferPayload(coin, to, amount) { if (coin === "AptosCoin" /* APTOS */) { return { function: `0x1::aptos_account::transfer`, type_arguments: [], arguments: [to, amount] }; } else { return { function: `0x1::aptos_account::transfer_coins`, type_arguments: [this.getCoinType(coin)], arguments: [to, amount] }; } } /** * Transfers a coin. * * @param {aptos.AptosAccount} signer - The signer account. * @param {CoinType} coin - The coin type. * @param {aptos.MaybeHexString} to - The recipient address. * @param {aptos.BCS.Uint64 | aptos.BCS.Uint32} amount - The amount to transfer. * @returns {Promise} A promise that resolves to the transaction. */ async transfer(signer, coin, to, amount) { const transaction = this.transferPayload(coin, to, amount); return this.sdk.sendAndConfirmTransaction(signer, transaction); } // ------------------------------ view functions ------------------------------ /** * Gets the balance of a coin for a given owner. * * @param {CoinType} coin - The coin type. * @param {aptos.MaybeHexString} owner - The owner address. * @returns {Promise} A promise that resolves to the balance. */ async balance(coin, owner) { try { const resource = await this.sdk.client.getAccountResource( owner, `0x1::coin::CoinStore<${this.getCoinType(coin)}>` ); const { coin: c } = resource.data; return BigInt(c.value); } catch (e) { if (isErrorOfApiError(e, 404)) { return BigInt(0); } throw e; } } /** * Checks if an account is registered for a given coin. * * @param {CoinType} coin - The coin type. * @param {aptos.MaybeHexString} accountAddr - The account address. * @returns {Promise} A promise that resolves to true if the account is registered, false otherwise. */ async isAccountRegistered(coin, accountAddr) { try { await this.sdk.client.getAccountResource(accountAddr, `0x1::coin::CoinStore<${this.getCoinType(coin)}>`); return true; } catch (e) { if (isErrorOfApiError(e, 404)) { return false; } throw e; } } }; var Counter = class { /** * The SDK instance. */ sdk; /** * The LzApp instance. */ lzApp; /** * The user application type. */ uaType; /** * The address of the counter. */ address; /** * The length of the send payload. */ SEND_PAYLOAD_LENGTH = 4; /** * Creates an instance of Counter. * * @param {SDK} sdk - The SDK instance. * @param {aptos.MaybeHexString} counter - The counter address. * @param {aptos.MaybeHexString} [lzApp] - The LzApp address. */ constructor(sdk, counter, lzApp) { this.sdk = sdk; this.address = counter; this.lzApp = new LzApp(sdk, lzApp || sdk.accounts.layerzero, counter); this.uaType = `${this.address}::counter::CounterUA`; } /** * Initializes the counter. * * @param {aptos.AptosAccount} signer - The signer account. * @returns {Promise} The transaction result. */ async initialize(signer) { const transaction = { function: `${this.address}::counter::init`, type_arguments: [], arguments: [] }; return this.sdk.sendAndConfirmTransaction(signer, transaction); } /** * Gets the remote address for a given chain ID. * * @param {aptos.BCS.Uint16} remoteChainId - The remote chain ID. * @returns {Promise} The remote address. */ async getRemote(remoteChainId) { return this.lzApp.getRemote(remoteChainId); } /** * Gets the current count. * * @returns {Promise} The current count. */ async getCount() { const resource = await this.sdk.client.getAccountResource(this.address, `${this.address}::counter::Counter`); const { i } = resource.data; return BigInt(i); } /** * Creates a payload for creating a counter. * * @param {aptos.BCS.Uint64 | aptos.BCS.Uint32} i - The initial count value. * @returns {aptos.Types.EntryFunctionPayload} The entry function payload. */ createCounterPayload(i) { return { function: `${this.address}::counter::create_counter`, type_arguments: [], arguments: [i] }; } /** * Creates a counter. * * @param {aptos.AptosAccount} signer - The signer account. * @param {aptos.BCS.Uint64 | aptos.BCS.Uint32} i - The initial count value. * @returns {Promise} The transaction result. */ async createCounter(signer, i) { const transaction = this.createCounterPayload(i); return this.sdk.sendAndConfirmTransaction(signer, transaction); } /** * Creates a payload for setting a remote address. * * @param {aptos.BCS.Uint16} remoteChainId - The remote chain ID. * @param {aptos.BCS.Bytes} remoteAddress - The remote address. * @returns {aptos.Types.EntryFunctionPayload} The entry function payload. */ setRemotePayload(remoteChainId, remoteAddress) { return this.lzApp.setRemotePaylaod(remoteChainId, remoteAddress); } /** * Sets a remote address. * * @param {aptos.AptosAccount} signer - The signer account. * @param {aptos.BCS.Uint16} remoteChainId - The remote chain ID. * @param {aptos.BCS.Bytes} remoteAddress - The remote address. * @returns {Promise} The transaction result. */ async setRemote(signer, remoteChainId, remoteAddress) { return this.lzApp.setRemote(signer, remoteChainId, remoteAddress); } /** * Creates a payload for setting the application configuration. * * @param {aptos.BCS.Uint16} majorVersion - The major version. * @param {aptos.BCS.Uint8} minorVersion - The minor version. * @param {aptos.BCS.Uint16} remoteChainId - The remote chain ID. * @param {aptos.BCS.Uint8} configType - The configuration type. * @param {aptos.BCS.Bytes} configBytes - The configuration bytes. * @returns {aptos.Types.EntryFunctionPayload} The entry function payload. */ setAppConfigPayload(majorVersion, minorVersion, remoteChainId, configType, configBytes) { return this.lzApp.setConfigPayload( this.uaType, majorVersion, minorVersion, remoteChainId, configType, configBytes ); } /** * Sets the application configuration. * * @param {aptos.AptosAccount} signer - The signer account. * @param {aptos.BCS.Uint16} majorVersion - The major version. * @param {aptos.BCS.Uint8} minorVersion - The minor version. * @param {aptos.BCS.Uint16} remoteChainId - The remote chain ID. * @param {aptos.BCS.Uint8} configType - The configuration type. * @param {aptos.BCS.Bytes} configBytes - The configuration bytes. * @returns {Promise} The transaction result. */ async setAppConfig(signer, majorVersion, minorVersion, remoteChainId, configType, configBytes) { console.log(`configType: ${configType}, configBytes: ${configBytes}`); return this.lzApp.setConfig( signer, this.uaType, majorVersion, minorVersion, remoteChainId, configType, configBytes ); } /** * Sets the application configuration bundle. * * @param {aptos.AptosAccount} signer - The signer account. * @param {aptos.BCS.Uint16} majorVersion - The major version. * @param {aptos.BCS.Uint8} minorVersion - The minor version. * @param {aptos.BCS.Uint16} remoteChainId - The remote chain ID. * @param {UlnConfigType} config - The configuration bundle. * @returns {Promise} A promise that resolves when the configuration is set. */ async setAppConfigBundle(signer, majorVersion, minorVersion, remoteChainId, config) { await this.lzApp.setConfigBundle(signer, this.uaType, majorVersion, minorVersion, remoteChainId, config); } /** * Creates a payload for sending data to a remote chain. * * @param {aptos.BCS.Uint16} remoteChainId - The remote chain ID. * @param {aptos.BCS.Uint64 | aptos.BCS.Uint32} fee - The fee amount. * @param {Uint8Array} adapterParams - The adapter parameters. * @returns {aptos.Types.EntryFunctionPayload} The entry function payload. */ sendToRemotePayload(remoteChainId, fee, adapterParams) { const result = { function: `${this.address}::counter::send_to_remote`, type_arguments: [], arguments: [remoteChainId, fee, Array.from(adapterParams)] }; return result; } /** * Sends data to a remote chain. * * @param {aptos.AptosAccount} signer - The signer account. * @param {aptos.BCS.Uint16} remoteChainId - The remote chain ID. * @param {aptos.BCS.Uint64 | aptos.BCS.Uint32} fee - The fee amount. * @param {Uint8Array} adapterParams - The adapter parameters. * @returns {Promise} The transaction result. */ async sendToRemote(signer, remoteChainId, fee, adapterParams) { const transaction = { function: `${this.address}::counter::send_to_remote`, type_arguments: [], arguments: [remoteChainId, fee, Array.from(adapterParams)] }; return this.sdk.sendAndConfirmTransaction(signer, transaction); } /** * Receives data from a remote chain. * * @param {aptos.AptosAccount} signer - The signer account. * @param {aptos.BCS.Uint16} remoteChainId - The remote chain ID. * @param {aptos.BCS.Bytes} remoteAddress - The remote address. * @param {aptos.BCS.Bytes} payload - The payload data. * @returns {Promise} The transaction result. */ async lzReceive(signer, remoteChainId, remoteAddress, payload) { const transaction = { function: `${this.address}::counter::lz_receive`, type_arguments: [], arguments: [remoteChainId, Array.from(remoteAddress), Array.from(payload)] }; return this.sdk.sendAndConfirmTransaction(signer, transaction); } /** * Checks if a counter is created for a given address. * * @param {aptos.MaybeHexString} address - The address to check. * @returns {Promise} True if the counter is created, false otherwise. */ async isCounterCreated(address) { try { const owner = aptos2__namespace.HexString.ensure(address).toString(); await this.sdk.client.getAccountResource(this.address, `${owner}::counter::Counter`); return true; } catch (e) { if (isErrorOfApiError(e, 404)) { return false; } throw e; } } }; var MultisigOracle = class { /** * Creates an instance of the MultisigOracle class. * * @param {SDK} sdk - The SDK instance. * @param {aptos.MaybeHexString} address - The address of the multisig oracle. */ constructor(sdk, address) { this.sdk = sdk; this.address = address; this.module = `${this.address}::multisig_oracle`; this.moduleName = "multisig_oracle::multisig_oracle"; } address; module; moduleName; // Validator Functions /** * Gets the payload for proposing a transaction. * * @param {Uint8Array} hash - The hash of the transaction. * @param {aptos.BCS.Uint64 | aptos.BCS.Uint32} confirmations - The number of confirmations required. * @returns {aptos.Types.EntryFunctionPayload} The payload. */ getProposePayload(hash, confirmations) { return { function: `${this.module}::propose`, type_arguments: [], arguments: [hash, confirmations] }; } /** * Proposes a transaction. * * @param {aptos.AptosAccount} signer - The signer account. * @param {Uint8Array} hash - The hash of the transaction. * @param {aptos.BCS.Uint64 | aptos.BCS.Uint32} confirmations - The number of confirmations required. * @returns {Promise} A promise that resolves to the transaction. */ async propose(signer, hash, confirmations) { const transaction = this.getProposePayload(hash, confirmations); return this.sdk.sendAndConfirmTransaction(signer, transaction); } /** * Gets the entry function for proposing a transaction. * * @param {aptos.MaybeHexString} hash - The hash of the transaction. * @param {aptos.BCS.Uint64 | aptos.BCS.Uint32} confirmations - The number of confirmations required. * @returns {aptos.TxnBuilderTypes.TransactionPayloadEntryFunction} The entry function. */ getProposeEntryFunction(hash, confirmations) { const serializer = new aptos2__namespace.BCS.Serializer(); serializer.serializeBytes(Uint8Array.from(Buffer.from(hash.toString(), "hex"))); return new aptos2__namespace.TxnBuilderTypes.TransactionPayloadEntryFunction( aptos2__namespace.TxnBuilderTypes.EntryFunction.natural( this.module, "propose", [], [serializer.getBytes(), aptos2__namespace.BCS.bcsSerializeUint64(confirmations)] ) ); } /** * Gets the payload for transferring the validator role. * * @param {aptos.MaybeHexString} newValidator - The new validator address. * @returns {aptos.Types.EntryFunctionPayload} The payload. */ getTransferValidatorPayload(newValidator) { const result = { function: `${this.module}::transfer_validator`, type_arguments: [], arguments: [newValidator] }; return result; } /** * Sets the validator. * * @param {aptos.AptosAccount} signer - The signer account. * @param {aptos.MaybeHexString} newValidator - The new validator address. * @returns {Promise} A promise that resolves to the transaction. */ async setValidator(signer, newValidator) { const transaction = this.getTransferValidatorPayload(newValidator); return this.sdk.sendAndConfirmTransaction(signer, transaction); } /** * Gets the payload for setting an admin. * * @param {aptos.MaybeHexString} candidate - The candidate address. * @param {boolean} active - The active state. * @returns {aptos.Types.EntryFunctionPayload} The payload. */ getSetAdminPayload(candidate, active) { const result = { function: `${this.module}::set_admin`, type_arguments: [], arguments: [candidate, active] }; return result; } /** * Sets an admin. * * @param {aptos.AptosAccount} signer - The signer account. * @param {aptos.MaybeHexString} candidate - The candidate address. * @param {boolean} active - The active state. * @returns {Promise} A promise that resolves to the transaction. */ async setAdmin(signer, candidate, active) { const transaction = this.getSetAdminPayload(candidate, active); return this.sdk.sendAndConfirmTransaction(signer, transaction); } /** * Gets the payload for allowlisting a user address. * * @param {aptos.MaybeHexString} ua - The user address. * @returns {aptos.Types.EntryFunctionPayload} The payload. */ getAllowlistPayload(ua) { const result = { function: `${this.module}::allowlist`, type_arguments: [], arguments: [ua] }; return result; } /** * Allowlists a user address. * * @param {aptos.AptosAccount} signer - The signer account. * @param {aptos.MaybeHexString} ua - The user address. * @returns {Promise} A promise that resolves to the transaction. */ async allowlist(signer, ua) { const transaction = this.getAllowlistPayload(ua); return this.sdk.sendAndConfirmTransaction(signer, transaction); } /** * Gets the payload for denylisting a user address. * * @param {aptos.MaybeHexString} ua - The user address. * @returns {aptos.Types.EntryFunctionPayload} The payload. */ getDenylistPayload(ua) { const result = { function: `${this.module}::denylist`, type_arguments: [], arguments: [ua] }; return result; } /** * Denylists a user address. * * @param {aptos.AptosAccount} signer - The signer account. * @param {aptos.MaybeHexString} ua - The user address. * @returns {Promise} A promise that resolves to the transaction. */ async denylist(signer, ua) { const transaction = this.getDenylistPayload(ua); return this.sdk.sendAndConfirmTransaction(signer, transaction); } // Admin Functions /** * Gets the payload for setting the fee. * * @param {aptos.BCS.Uint64} remoteChainId - The remote chain ID. * @param {aptos.BCS.Uint64} baseFee - The base fee. * @returns {aptos.Types.EntryFunctionPayload} The payload. */ getSetFeePayload(remoteChainId, baseFee) { const result = { function: `${this.module}::set_fee`, type_arguments: [], arguments: [remoteChainId, baseFee] }; return result; } /** * Sets the fee. * * @param {aptos.AptosAccount} signer - The signer account. * @param {aptos.BCS.Uint64} remoteChainId - The remote chain ID. * @param {aptos.BCS.Uint64} baseFee - The base fee. * @returns {Promise} A promise that resolves to the transaction. */ async setFee(signer, remoteChainId, baseFee) { const transaction = this.getSetFeePayload(remoteChainId, baseFee); return this.sdk.sendAndConfirmTransaction(signer, transaction); } /** * Gets the payload for withdrawing the fee. * * @param {aptos.MaybeHexString} receiver - The receiver address. * @param {aptos.BCS.Uint64} amount - The amount to withdraw. * @returns {aptos.Types.EntryFunctionPayload} The payload. */ getWithdrawFeePayload(receiver, amount) { const result = { function: `${this.module}::withdraw_fee`, type_arguments: [], arguments: [receiver, amount] }; return result; } /** * Withdraws the fee. * * @param {aptos.AptosAccount} signer - The signer account. * @param {aptos.MaybeHexString} receiver - The receiver address. * @param {aptos.BCS.Uint64} amount - The amount to withdraw. * @returns {Promise} A promise that resolves to the transaction. */ async withdrawFee(signer, receiver, amount) { const transaction = this.getWithdrawFeePayload(receiver, amount); return this.sdk.sendAndConfirmTransaction(signer, transaction); } // View Functions /** * Checks if an account is an admin. * * @param {aptos.MaybeHexString} account - The account address. * @returns {Promise} A promise that resolves to true if the account is an admin, false otherwise. */ async isAdmin(account) { const resource = await this.sdk.client.getAccountResource(this.address, `${this.module}::Config`); const { admins } = resource.data; const acc = aptos2__namespace.HexString.ensure(account).toShortString(); return admins.includes(acc); } /** * Gets the validator address. * * @returns {Promise} A promise that resolves to the validator address. */ async getValidator() { const resource = await this.sdk.client.getAccountResource(this.address, `${this.module}::Config`); return resource.data.validator; } /** * Checks if an account is a validator. * * @param {aptos.MaybeHexString} validator - The validator address. * @returns {Promise} A promise that resolves to true if the account is a validator, false otherwise. */ async isValidator(validator) { const _validator = await this.getValidator(); const val = aptos2__namespace.HexString.ensure(validator).toShortString(); return _validator === val; } /** * Gets the multisig public key and address. * * @param {string[]} validatorPubKeys - The validator public keys. * @returns {Promise<[aptos.TxnBuilderTypes.MultiEd25519PublicKey, string]>} A promise that resolves to the multisig public key and address. */ async getMultisigPubKeyAndAddress(validatorPubKeys) { const pubKeys = Object.keys(validatorPubKeys).map((key) => stringToUint8Array(key)); return generateMultisig([...pubKeys], pubKeys.length); } /** * Gets the resource address. * * @returns {Promise} A promise that resolves to the resource address. */ async getResourceAddress() { const resource = await this.sdk.client.getAccountResource(this.address, `${this.module}::Config`); const { resource_addr } = resource.data; return fullAddress(resource_addr).toString(); } }; var MultisigOracleTss = class { /** * Creates an instance of the MultisigOracleTss class. * * @param {SDK} sdk - The SDK instance. * @param {aptos.MaybeHexString} address - The address of the multisig oracle. */ constructor(sdk, address) { this.sdk = sdk; this.address = address; this.module = `${this.address}::oracle`; this.moduleName = "oracle::oracle"; } address; module; moduleName; // Validator Functions /** * Gets the payload for proposing a transaction. * * @param {Uint8Array} hash - The hash of the transaction. * @param {aptos.BCS.Uint64 | aptos.BCS.Uint32} confirmations - The number of confirmations. * @param {aptos.BCS.Uint64 | aptos.BCS.Uint32} expiration - The expiration time. * @param {Uint8Array} signatures - The signatures. * @returns {aptos.Types.EntryFunctionPayload} The payload. */ getProposePayload(hash, confirmations, expiration, signatures) { return { function: `${this.module}::mso_propose`, type_arguments: [], arguments: [Array.from(hash), confirmations, expiration, Array.from(signatures)] }; } /** * Proposes a transaction. * * @param {aptos.AptosAccount} signer - The signer account. * @param {Uint8Array} hash - The hash of the transaction. * @param {aptos.BCS.Uint64 | aptos.BCS.Uint32} confirmations - The number of confirmations. * @param {aptos.BCS.Uint64 | aptos.BCS.Uint32} expiration - The expiration time. * @param {Uint8Array} signatures - The signatures. * @returns {Promise} A promise that resolves to the transaction. */ async propose(signer, hash, confirmations, expiration, signatures) { const transaction = this.getProposePayload(hash, confirmations, expiration, signatures); return this.sdk.sendAndConfirmTransaction(signer, transaction); } /** * Gets the payload for setting a validator. * * @param {Uint8Array} validator - The validator address. * @param {boolean} active - Whether the validator is active. * @param {aptos.BCS.Uint64 | aptos.BCS.Uint32} expiration - The expiration time. * @param {Uint8Array} signatures - The signatures. * @returns {aptos.Types.EntryFunctionPayload} The payload. */ getSetValidatorPayload(validator, active, expiration, signatures) { const result = { function: `${this.module}::mso_set_validator`, type_arguments: [], arguments: [Array.from(validator), active, expiration, Array.from(signatures)] }; return result; } /** * Sets a validator. * * @param {aptos.AptosAccount} signer - The signer account. * @param {Uint8Array} validator - The validator address. * @param {boolean} active - Whether the validator is active. * @param {aptos.BCS.Uint64 | aptos.BCS.Uint32} expiration - The expiration time. * @param {Uint8Array} signatures - The signatures. * @returns {Promise} A promise that resolves to the transaction. */ async setValidator(signer, validator, active, expiration, signatures) { const transaction = this.getSetValidatorPayload(validator, active, expiration, signatures); return this.sdk.sendAndConfirmTransaction(signer, transaction); } /** * Gets the payload for setting the threshold. * * @param {aptos.BCS.Uint8} threshold - The threshold. * @param {aptos.BCS.Uint64 | aptos.BCS.Uint32} expiration - The expiration time. * @param {Uint8Array} signatures - The signatures. * @returns {aptos.Types.EntryFunctionPayload} The payload. */ getSetThresholdPayload(threshold, expiration, signatures) { const result = { function: `${this.module}::mso_set_threshold`, type_arguments: [], arguments: [threshold, expiration, Array.from(signatures)] }; return result; } /** * Sets the threshold. * * @param {aptos.AptosAccount} signer - The signer account. * @param {aptos.BCS.Uint8} threshold - The threshold. * @param {aptos.BCS.Uint64 | aptos.BCS.Uint32} expiration - The expiration time. * @param {Uint8Array} signatures - The signatures. * @returns {Promise} A promise that resolves to the transaction. */ async setThreshold(signer, threshold, expiration, signatures) { const transaction = this.getSetThresholdPayload(threshold, expiration, signatures); return this.sdk.sendAndConfirmTransaction(signer, transaction); } /** * Gets the payload for setting an admin. * * @param {aptos.MaybeHexString} candidate - The candidate address. * @param {boolean} active - Whether the admin is active. * @param {aptos.BCS.Uint64 | aptos.BCS.Uint32} expiration - The expiration time. * @param {Uint8Array} signatures - The signatures. * @returns {aptos.Types.EntryFunctionPayload} The payload. */ getSetAdminPayload(candidate, active, expiration, signatures) { const result = { function: `${this.module}::mso_set_admin`, type_arguments: [], arguments: [candidate, active, expiration, Array.from(signatures)] }; return result; } /** * Sets an admin. * * @param {aptos.AptosAccount} signer - The signer account. * @param {aptos.MaybeHexString} candidate - The candidate address. * @param {boolean} active - Whether the admin is active. * @param {aptos.BCS.Uint64 | aptos.BCS.Uint32} expiration - The expiration time. * @param {Uint8Array} signatures - The signatures. * @returns {Promise} A promise that resolves to the transaction. */ async setAdmin(signer, candidate, active, expiration, signatures) { const transaction = this.getSetAdminPayload(candidate, active, expiration, signatures); return this.sdk.sendAndConfirmTransaction(signer, transaction); } /** * Gets the payload for allowlisting a user. * * @param {aptos.MaybeHexString} ua - The user address. * @param {aptos.BCS.Uint64 | aptos.BCS.Uint32} expiration - The expiration time. * @param {Uint8Array} signatures - The signatures. * @returns {aptos.Types.EntryFunctionPayload} The payload. */ getAllowlistPayload(ua, expiration, signatures) { const result = { function: `${this.module}::mso_allowlist`, type_arguments: [], arguments: [ua, expiration, Array.from(signatures)] }; return result; } /** * Allowlists a user. * * @param {aptos.AptosAccount} signer - The signer account. * @param {aptos.MaybeHexString} ua - The user address. * @param {aptos.BCS.Uint64 | aptos.BCS.Uint32} expiration - The expiration time. * @param {Uint8Array} signatures - The signatures. * @returns {Promise} A promise that resolves to the transaction. */ async allowlist(signer, ua, expiration, signatures) { const transaction = this.getAllowlistPayload(ua, expiration, signatures); return this.sdk.sendAndConfirmTransaction(signer, transaction); } /** * Gets the payload for denylisting a user. * * @param {aptos.MaybeHexString} ua - The user address. * @param {aptos.BCS.Uint64 | aptos.BCS.Uint32} expiration - The expiration time. * @param {Uint8Array} signatures - The signatures. * @returns {aptos.Types.EntryFunctionPayload} The payload. */ getDenylistPayload(ua, expiration, signatures) { const result = { function: `${this.module}::mso_denylist`, type_arguments: [], arguments: [ua, expiration, Array.from(signatures)] }; return result; } /** * Denylists a user. * * @param {aptos.AptosAccount} signer - The signer account. * @param {aptos.MaybeHexString} ua - The user address. * @param {aptos.BCS.Uint64 | aptos.BCS.Uint32} expiration - The expiration time. * @param {Uint8Array} signatures - The signatures. * @returns {Promise} A promise that resolves to the transaction. */ async denylist(signer, ua, expiration, signatures) { const transaction = this.getDenylistPayload(ua, expiration, signatures); return this.sdk.sendAndConfirmTransaction(signer, transaction); } // Admin Functions /** * Gets the payload for initializing the configuration. * * @param {Uint8Array[]} validators - The validators. * @param {aptos.BCS.Uint8} threshold - The threshold. * @param {aptos.MaybeHexString[]} admins - The admins. * @returns {aptos.Types.EntryFunctionPayload} The payload. */ getInitConfigPayload(validators, threshold, admins) { return { function: `${this.module}::mso_init_config`, type_arguments: [], arguments: [validators, threshold, admins] }; } /** * Initializes the configuration. * * @param {aptos.AptosAccount} signer - The signer account. * @param {Uint8Array[]} validators - The validators. * @param {aptos.BCS.Uint8} threshold - The threshold. * @param {aptos.MaybeHexString[]} admins - The admins. * @returns {Promise} A promise that resolves to the transaction. */ async initConfig(signer, validators, threshold, admins) { const transaction = this.getInitConfigPayload(validators, threshold, admins); return this.sdk.sendAndConfirmTransaction(signer, transaction); } /** * Gets the payload for setting the fee. * * @param {aptos.BCS.Uint64} remoteChainId - The remote chain ID. * @param {aptos.BCS.Uint64} baseFee - The base fee. * @returns {aptos.Types.EntryFunctionPayload} The payload. */ getSetFeePayload(remoteChainId, baseFee) { return { function: `${this.module}::mso_set_fee`, type_arguments: [], arguments: [remoteChainId, baseFee] }; } /** * Gets the payload for upgrading the contract. * * @returns {aptos.Types.EntryFunctionPayload} The payload. */ getUpgradePayload() { return { function: `${this.module}::upgrade`, type_arguments: [], arguments: [] }; } /** * Upgrades the contract. * * @param {aptos.AptosAccount} signer - The signer account. * @returns {Promise} A promise that resolves to the transaction. */ async upgrade(signer) { const transaction = this.getUpgradePayload(); return this.sdk.sendAndConfirmTransaction(signer, transaction); } /** * Gets the payload for setting the use of MSO. * * @param {boolean} useMso - Whether to use MSO. * @returns {aptos.Types.EntryFunctionPayload} The payload. */ getSetUseMsoPayload(useMso) { return { function: `${this.module}::mso_set_use_mso`, type_arguments: [], arguments: [useMso] }; } /** * Sets the use of MSO. * * @param {aptos.AptosAccount} signer - The signer account. * @param {boolean} useMso - Whether to use MSO. * @returns {Promise} A promise that resolves to the transaction. */ async setUseMso(signer, useMso) { const transaction = this.getSetUseMsoPayload(useMso); return this.sdk.sendAndConfirmTransaction(signer, transaction); } /** * Sets the fee. * * @param {aptos.AptosAccount} signer - The signer account. * @param {aptos.BCS.Uint64} remoteChainId - The remote chain ID. * @param {aptos.BCS.Uint64} baseFee - The base fee. * @returns {Promise} A promise that resolves to the transaction. */ async setFee(signer, remoteChainId, baseFee) { const transaction = this.getSetFeePayload(remoteChainId, baseFee); return this.sdk.sendAndConfirmTransaction(signer, transaction); } /** * Gets the payload for withdrawing the fee. * * @param {aptos.MaybeHexString} receiver - The receiver address. * @param {aptos.BCS.Uint64} amount - The amount to withdraw. * @returns {aptos.Types.EntryFunctionPayload} The payload. */ getWithdrawFeePayload(receiver, amount) { const result = { function: `${this.module}::mso_withdraw_fee`, type_arguments: [], arguments: [receiver, amount] }; return result; } /** * Withdraws the fee. * * @param {aptos.AptosAccount} signer - The signer account. * @param {aptos.MaybeHexString} receiver - The receiver address. * @param {aptos.BCS.Uint64} amount - The amount to withdraw. * @returns {Promise} A promise that resolves to the transaction. */ async withdrawFee(signer, receiver, amount) { const transaction = this.getWithdrawFeePayload(receiver, amount); return this.sdk.sendAndConfirmTransaction(signer, transaction); } // View Functions /** * Gets the list of admin addresses. * * @returns {Promise} A promise that resolves to the list of admin addresses. */ async getAdmins() { const resource = await this.sdk.client.getAccountResource( this.address, `${this.module}::MsoConfig` ); return resource.data.admins; } /** * Gets the list of validator addresses. * * @returns {Promise} A promise that resolves to the list of validator addresses. */ async getValidators() { const resource = await this.sdk.client.getAccountResource( this.address, `${this.module}::MsoConfig` ); return resource.data.validators; } /** * Gets the threshold value. * * @returns {Promise} A promise that resolves to the threshold value. */ async getThreshold() { const resource = await this.sdk.client.getAccountResource( this.address, `${this.module}::MsoConfig` ); return parseInt(resource.data.threshold); } /** * Gets the resource address. * * @returns {Promise} A promise that resolves to the resource address. */ async getResourceAddress() { const resource = await this.sdk.client.getAccountResource(this.address, `${this.module}::Config`); const { resource_addr } = resource.data; return fullAddress(resource_addr).toString(); } /** * Checks if an account is an admin. * * @param {aptos.MaybeHexString} account - The account address. * @returns {Promise} A promise that resolves to true if the account is an admin, false otherwise. */ async isAdmin(account) { const admins = await this.getAdmins(); const _admins = admins.map((a) => a.toString().toLowerCase()); const acc = aptos2__namespace.HexString.ensure(account).toShortString(); return _admins.includes(acc.toString().toLowerCase()); } /** * Checks if an account is a validator. * * @param {aptos.MaybeHexString} validator - The validator address. * @returns {Promise} A promise that resolves to true if the account is a validator, false otherwise. */ async isValidator(validator) { const validators = await this.getValidators(); const _validators = validators.map((v) => v.toString().toLowerCase()); const val = aptos2__namespace.HexString.ensure(validator); return _validators.includes(val.toString().toLowerCase()); } // Hashing functions /** * Hashes the propose function data. * * @param {aptos.MaybeHexString} hash - The hash. * @param {number} blockConfirmation - The block confirmation. * @param {number} expiration - The expiration time. * @returns {string} The hashed propose function data. */ hashPropose(hash, blockConfirmation, expiration) { const encoded_data = new extendedBuffer.ExtendedBuffer(); encoded_data.writeBuffer(Buffer.from(stringToUint8Array(getAptosFunctionSignature("propose")))); encoded_data.writeBuffer(Buffer.from(stringToUint8Array(hash.toString()))); encoded_data.writeBuffer(new BN__default.default(blockConfirmation.toString()).toArrayLike(Buffer, "be", 8)); encoded_data.writeBuffer(new BN__default.default(expiration.toString()).toArrayLike(Buffer, "be", 8)); return keccak256Hash(encoded_data.buffer.toString("hex")); } /** * Hashes the set validator function data. * * @param {aptos.MaybeHexString} validator - The validator address. * @param {boolean} active - The active state. * @param {number} expiration - The expiration time. * @returns {string} The hashed set validator function data. */ hashSetValidator(validator, active, expiration) { const encoded_data = new extendedBuffer.ExtendedBuffer(); encoded_data.writeBuffer(Buffer.from(stringToUint8Array(getAptosFunctionSignature("set_validator")))); encoded_data.writeBuffer(Buffer.from(stringToUint8Array(validator.toString()))); encoded_data.writeUInt8(active ? 1 : 0); encoded_data.writeBuffer(new BN__default.default(expiration.toString()).toArrayLike(Buffer, "be", 8)); return keccak256Hash(encoded_data.buffer.toString("hex")); } /** * Hashes the set threshold function data. * * @param {aptos.BCS.Uint8} threshold - The threshold value. * @param {number} expiration - The expiration time. * @returns {string} The hashed set threshold function data. */ hashSetThreshold(threshold, expiration) { const encoded_data = new extendedBuffer.ExtendedBuffer(); encoded_data.writeBuffer(Buffer.from(stringToUint8Array(getAptosFunctionSignature("set_threshold")))); encoded_data.writeBuffer(new BN__default.default(threshold).toArrayLike(Buffer, "be", 8)); encoded_data.writeBuffer(new BN__default.default(expiration.toString()).toArrayLike(Buffer, "be", 8)); return keccak256Hash(encoded_data.buffer.toString("hex")); } /** * Hashes the allowlist function data. * * @param {aptos.MaybeHexString} ua - The user address. * @param {number} expiration - The expiration time. * @returns {string} The hashed allowlist function data. */ hashAllowlist(ua, expiration) { const encoded_data = new extendedBuffer.ExtendedBuffer(); encoded_data.writeBuffer(Buffer.from(stringToUint8Array(getAptosFunctionSignature("allowlist")))); encoded_data.writeBuffer(Buffer.from(stringToUint8Array(ua.toString()))); encoded_data.writeBuffer(new BN__default.default(expiration.toString()).toArrayLike(Buffer, "be", 8)); return keccak256Hash(encoded_data.buffer.toString("hex")); } /** * Hashes the denylist function data. * * @param {aptos.MaybeHexString} ua - The user address. * @param {number} expiration - The expiration time. * @returns {string} The hashed denylist function data. */ hashDenylist(ua, expiration) { const encoded_data = new extendedBuffer.ExtendedBuffer(); encoded_data.writeBuffer(Buffer.from(stringToUint8Array(getAptosFunctionSignature("denylist")))); encoded_data.writeBuffer(Buffer.from(stringToUint8Array(ua.toString()))); encoded_data.writeBuffer(new BN__default.default(expiration.toString()).toArrayLike(Buffer, "be", 8)); return keccak256Hash(encoded_data.buffer.toString("hex")); } }; function getAptosFunctionSignature(funcName) { const encoded_data = new extendedBuffer.ExtendedBuffer(); const funcNameHexStr = Buffer.from(funcName).toString("hex"); const funcNameBcs = aptos2__namespace.BCS.bcsSerializeBytes(stringToUint8Array(funcNameHexStr)); encoded_data.writeBuffer(Buffer.from(funcNameBcs)); return utils.bytesToHex(sha3.keccak_256(encoded_data.buffer)).slice(0, 8); } function keccak256Hash(data) { const encoded_data = new extendedBuffer.ExtendedBuffer(); encoded_data.writeBuffer(Buffer.from(stringToUint8Array(data))); return utils.bytesToHex(sha3.keccak_256(encoded_data.buffer)); } var OFT = class { address; module; SEND_PAYLOAD_LENGTH = 41; // sdk; lzApp; /** * Creates an instance of the OFT class. * * @param {SDK} sdk - The SDK instance. */ constructor(sdk) { this.sdk = sdk; this.address = sdk.accounts.layerzero_apps; this.lzApp = sdk.accounts.layerzero; this.module = `${this.address}::oft`; } /** * Sets the application configuration. * * @param {aptos.AptosAccount} signer - The signer account. * @param {string} oftType - The OFT type. * @param {aptos.BCS.Uint16} major - The major version. * @param {aptos.BCS.Uint8} minor - The minor version. * @param {aptos.BCS.Uint16} remoteChainId - The remote chain ID. * @param {aptos.BCS.Uint8} configType - The configuration type. * @param {aptos.BCS.Bytes} configBytes - The configuration bytes. * @returns {Promise} A promise that resolves to the transaction. */ async setAppConfig(signer, oftType, major, minor, remoteChainId, configType, configBytes) { const address = this.getTypeAddress(oftType); const lzApp = new LzApp(this.sdk, this.lzApp, address); return lzApp.setConfig(signer, oftType, major, minor, remoteChainId, configType, configBytes); } /** * Gets the minimum destination gas. * * @param {string} oftType - The OFT type. * @param {aptos.BCS.Uint16} dstChainId - The destination chain ID. * @param {aptos.BCS.Uint64} type - The type. * @returns {Promise} A promise that resolves to the minimum destination gas. */ async getMinDstGas(oftType, dstChainId, type) { const address = this.getTypeAddress(oftType); const lzApp = new LzApp(this.sdk, this.lzApp, address); return lzApp.getMinDstGas(oftType, dstChainId, type); } /** * Gets the payload for setting the minimum destination gas. * * @param {string} oftType - The OFT type. * @param {aptos.BCS.Uint16} dstChainId - The destination chain ID. * @param {aptos.BCS.Uint64} packetType - The packet type. * @param {aptos.BCS.Uint64} minGas - The minimum gas. * @returns {aptos.Types.EntryFunctionPayload} The payload. */ setMinDstGasPayload(oftType, dstChainId, packetType, minGas) { const address = this.getTypeAddress(oftType); const lzApp = new LzApp(this.sdk, this.lzApp, address); return lzApp.setMinDstPayload(oftType, dstChainId, packetType, minGas); } /** * Checks if custom adapter parameters are enabled. * * @param {string} oftType - The OFT type. * @returns {Promise} A promise that resolves to true if custom adapter parameters are enabled, false otherwise. */ async customAdapterParamsEnabled(oftType) { const resource = await this.getGlobalStore(oftType); const { custom_adapter_params } = resource.data; return custom_adapter_params; } /** * Gets the payload for enabling custom adapter parameters. * * @param {string} oftType - The OFT type. * @param {boolean} enable - Whether to enable custom adapter parameters. * @returns {aptos.Types.EntryFunctionPayload} The payload. */ enableCustomAdapterParamsPayload(oftType, enable) { return { function: `${this.module}::enable_custom_adapter_params`, type_arguments: [oftType], arguments: [enable] }; } /** * Gets the payload for setting the remote address. * * @param {string} oftType - The OFT type. * @param {aptos.BCS.Uint16} remoteChainId - The remote chain ID. * @param {aptos.BCS.Bytes} remoteOftAddr - The remote OFT address. * @returns {aptos.Types.EntryFunctionPayload} The payload. */ setRemotePayload(oftType, remoteChainId, remoteOftAddr) { const address = this.getTypeAddress(oftType); const lzApp = new LzApp(this.sdk, this.lzApp, address); return lzApp.setRemotePaylaod(remoteChainId, remoteOftAddr); } /** * Sets the remote address. * * @param {aptos.AptosAccount} signer - The signer account. * @param {string} oftType - The OFT type. * @param {aptos.BCS.Uint16} remoteChainId - The remote chain ID. * @param {aptos.BCS.Bytes} remoteOftAddr - The remote OFT address. * @returns {Promise} A promise that resolves to the transaction. */ async setRemote(signer, oftType, remoteChainId, remoteOftAddr) { const address = this.getTypeAddress(oftType); const lzApp = new LzApp(this.sdk, this.lzApp, address); return lzApp.setRemote(signer, remoteChainId, remoteOftAddr); } /** * Gets the remote address. * * @param {string} oftType - The OFT type. * @param {aptos.BCS.Uint16} remoteChainId - The remote chain ID. * @returns {Promise} A promise that resolves to the remote address. */ async getRemote(oftType, remoteChainId) { try { const address = this.getTypeAddress(oftType); const lzApp = new LzApp(this.sdk, this.lzApp, address); return await lzApp.getRemote(remoteChainId); } catch (e) { if (isErrorOfApiError(e, 404)) { return new Uint8Array(0); } throw e; } } /** * Gets the payload for setting the default fee. * * @param {string} oftType - The OFT type. * @param {aptos.BCS.Uint64} feeBp - The fee basis points. * @returns {aptos.Types.EntryFunctionPayload} The payload. */ payloadOfSetDefaultFee(oftType, feeBp) { return { function: `${this.module}::set_default_fee`, type_arguments: [oftType], arguments: [feeBp.toString()] }; } /** * Sets the default fee. * * @param {aptos.AptosAccount} signer - The signer account. * @param {string} oftType - The OFT type. * @param {aptos.BCS.Uint64} feeBp - The fee basis points. * @returns {Promise} A promise that resolves to the transaction. */ async setDefaultFee(signer, oftType, feeBp) { const transaction = this.payloadOfSetDefaultFee(oftType, feeBp); return this.sdk.sendAndConfirmTransaction(signer, transaction); } /** * Gets the default fee. * * @param {string} oftType - The OFT type. * @returns {Promise} A promise that resolves to the default fee. */ async getDefaultFee(oftType) { const resource = await this.getGlobalStore(oftType); const { fee_config } = resource.data; return fee_config.default_fee_bp; } /** * Gets the payload for setting the fee. * * @param {string} oftType - The OFT type. * @param {aptos.BCS.Uint16} remoteChainId - The remote chain ID. * @param {boolean} enabled - Whether the fee is enabled. * @param {aptos.BCS.Uint64} feeBp - The fee basis points. * @returns {aptos.Types.EntryFunctionPayload} The payload. */ payloadOfSetFee(oftType, remoteChainId, enabled, feeBp) { return { function: `${this.module}::set_fee`, type_arguments: [oftType], arguments: [remoteChainId, enabled, feeBp] }; } /** * Sets the fee. * * @param {aptos.AptosAccount} signer - The signer account. * @param {string} oftType - The OFT type. * @param {aptos.BCS.Uint16} remoteChainId - The remote chain ID. * @param {boolean} enabled - Whether the fee is enabled. * @param {aptos.BCS.Uint64} feeBp - The fee basis points. * @returns {Promise} A promise that resolves to the transaction. */ async setFee(signer, oftType, remoteChainId, enabled, feeBp) { const transaction = this.payloadOfSetFee(oftType, remoteChainId, enabled, feeBp); return this.sdk.sendAndConfirmTransaction(signer, transaction); } /** * Gets the fee. * * @param {string} oftType - The OFT type. * @param {aptos.BCS.Uint16} remoteChainId - The remote chain ID. * @returns {Promise} A promise that resolves to the fee. */ async getFee(oftType, remoteChainId) { const resource = await this.getGlobalStore(oftType); const { fee_config } = resource.data; try { return await this.sdk.client.getTableItem(fee_config.chain_id_to_fee_bp.handle, { key_type: `u64`, value_type: `u64`, key: remoteChainId.toString() }); } catch (e) { if (isErrorOfApiError(e, 404)) { return fee_config.default_fee_bp; } throw e; } } /** * Gets the payload for setting the fee owner. * * @param {string} oftType - The OFT type. * @param {aptos.MaybeHexString} owner - The owner address. * @returns {aptos.Types.EntryFunctionPayload} The payload. */ payloadOfSetFeeOwner(oftType, owner) { return { function: `${this.module}::set_fee_owner`, type_arguments: [oftType], arguments: [owner] }; } /** * Sets the fee owner. * * @param {aptos.AptosAccount} signer - The signer account. * @param {string} oftType - The OFT type. * @param {aptos.MaybeHexString} owner - The owner address. * @returns {Promise} A promise that resolves to the transaction. */ async setFeeOwner(signer, oftType, owner) { const transaction = this.payloadOfSetFeeOwner(oftType, owner); return this.sdk.sendAndConfirmTransaction(signer, transaction); } /** * Gets the fee owner. * * @param {string} oftType - The OFT type. * @returns {Promise} A promise that resolves to the fee owner. */ async getFeeOwner(oftType) { const resource = await this.getGlobalStore(oftType); const { fee_config } = resource.data; return aptos2__namespace.HexString.ensure(fee_config.fee_owner); } /** * Gets the payload for sending a coin. * * @param {string} oftType - The OFT type. * @param {aptos.BCS.Uint16} dstChainId - The destination chain ID. * @param {aptos.BCS.Bytes} dstReceiver - The destination receiver address. * @param {aptos.BCS.Uint64 | aptos.BCS.Uint32} amount - The amount to send. * @param {aptos.BCS.Uint64 | aptos.BCS.Uint32} minAmount - The minimum amount. * @param {aptos.BCS.Uint64 | aptos.BCS.Uint32} nativeFee - The native fee. * @param {aptos.BCS.Uint64 | aptos.BCS.Uint32} zroFee - The ZRO fee. * @param {aptos.BCS.Bytes} adapterParams - The adapter parameters. * @param {aptos.BCS.Bytes} msglibParams - The message library parameters. * @returns {aptos.Types.EntryFunctionPayload} The payload. */ sendCoinPayload(oftType, dstChainId, dstReceiver, amount, minAmount, nativeFee, zroFee, adapterParams, msglibPararms) { return { function: `${this.module}::send`, type_arguments: [oftType], arguments: [ dstChainId.toString(), Array.from(dstReceiver), amount.toString(), minAmount.toString(), nativeFee.toString(), zroFee.toString(), Array.from(adapterParams), Array.from(msglibPararms) ] }; } /** * Sends a coin. * * @param {aptos.AptosAccount} signer - The signer account. * @param {string} oftType - The OFT type. * @param {aptos.BCS.Uint16} dstChainId - The destination chain ID. * @param {aptos.BCS.Bytes} dstReceiver - The destination receiver address. * @param {aptos.BCS.Uint64 | aptos.BCS.Uint32} amount - The amount to send. * @param {aptos.BCS.Uint64 | aptos.BCS.Uint32} minAmount - The minimum amount. * @param {aptos.BCS.Uint64 | aptos.BCS.Uint32} nativeFee - The native fee. * @param {aptos.BCS.Uint64 | aptos.BCS.Uint32} zroFee - The ZRO fee. * @param {aptos.BCS.Bytes} adapterParams - The adapter parameters. * @param {aptos.BCS.Bytes} msglibParams - The message library parameters. * @returns {Promise} A promise that resolves to the transaction. */ async sendCoin(signer, oftType, dstChainId, dstReceiver, amount, minAmount, nativeFee, zroFee, adapterParams, msglibParams) { const transaction = this.sendCoinPayload( oftType, dstChainId, dstReceiver, amount, minAmount, nativeFee, zroFee, adapterParams, msglibParams ); return this.sdk.sendAndConfirmTransaction(signer, transaction); } /** * Creates the payload for the LayerZero receive function. * * @param {string} oftType - The type of the OFT. * @param {aptos.BCS.Uint16} srcChainId - The source chain ID. * @param {aptos.BCS.Bytes} srcAddress - The source address. * @param {aptos.BCS.Bytes} payload - The payload. * @returns {aptos.Types.EntryFunctionPayload} The payload for the LayerZero receive function. */ payloadOfLzReceive(oftType, srcChainId, srcAddress, payload) { return { function: `${this.module}::lz_receive`, type_arguments: [oftType], arguments: [srcChainId, Array.from(srcAddress), Array.from(payload)] }; } /** * Executes the LayerZero receive function. * * @param {aptos.AptosAccount} signer - The signer account. * @param {string} oftType - The type of the OFT. * @param {aptos.BCS.Uint16} srcChainId - The source chain ID. * @param {aptos.BCS.Bytes} srcAddress - The source address. * @param {aptos.BCS.Bytes} payload - The payload. * @returns {Promise} A promise that resolves to the transaction. */ async lzReceive(signer, oftType, srcChainId, srcAddress, payload) { const transaction = this.payloadOfLzReceive(oftType, srcChainId, srcAddress, payload); return this.sdk.sendAndConfirmTransaction(signer, transaction); } /** * Creates the payload for claiming a coin. * * @param {string} oftType - The type of the OFT. * @returns {aptos.Types.EntryFunctionPayload} The payload for claiming a coin. */ payloadOfClaimCoin(oftType) { return { function: `${this.module}::claim`, type_arguments: [oftType], arguments: [] }; } /** * Claims a coin. * * @param {aptos.AptosAccount} signer - The signer account. * @param {string} oftType - The type of the OFT. * @returns {Promise} A promise that resolves to the transaction. */ async claimCoin(signer, oftType) { const transaction = this.payloadOfClaimCoin(oftType); return this.sdk.sendAndConfirmTransaction(signer, transaction); } /** * Checks if the OFT is initialized. * * @param {string} oftType - The type of the OFT. * @returns {Promise} A promise that resolves to true if the OFT is initialized, false otherwise. */ async isInitialized(oftType) { try { const remoteCoin = await this.getGlobalStore(oftType); return remoteCoin !== void 0; } catch (e) { if (isErrorOfApiError(e, 404)) { return false; } throw e; } } /** * Gets the claimable coin amount for a given owner. * * @param {string} oftType - The type of the OFT. * @param {aptos.MaybeHexString} owner - The owner address. * @returns {Promise} A promise that resolves to the claimable coin amount. */ async getClaimableCoin(oftType, owner) { const resource = await this.getCoinStore(oftType); const { claimable_amount } = resource.data; const claimableAmtLDHandle = claimable_amount.handle; try { const response = await this.sdk.client.getTableItem(claimableAmtLDHandle, { key_type: "address", value_type: "u64", key: owner }); return BigInt(response); } catch (e) { if (isErrorOfApiError(e, 404)) { return BigInt("0"); } throw e; } } /** * Gets the total value locked for the OFT. * * @param {string} oftType - The type of the OFT. * @returns {Promise} A promise that resolves to the total value locked. */ async getTotalValueLocked(oftType) { const resource = await this.getCoinStore(oftType); const { locked_coin } = resource.data; return BigInt(locked_coin.value); } /** * Gets the LD to SD rate for the OFT. * * @param {string} oftType - The type of the OFT. * @returns {Promise} A promise that resolves to the LD to SD rate. */ async getLd2SdRate(oftType) { const resource = await this.getGlobalStore(oftType); const { ld2sd_rate } = resource.data; return ld2sd_rate; } /** * Converts an amount from SD to LD. * * @param {string} oftType - The type of the OFT. * @param {aptos.BCS.Uint64 | aptos.BCS.Uint32} amountSD - The amount in SD. * @returns {Promise} A promise that resolves to the amount in LD. */ async convertAmountToLD(oftType, amountSD) { const rate = await this.getLd2SdRate(oftType); return BigInt(amountSD) * BigInt(rate); } /** * Converts an amount from LD to SD. * * @param {string} oftType - The type of the OFT. * @param {aptos.BCS.Uint64 | aptos.BCS.Uint32} amountLD - The amount in LD. * @returns {Promise} A promise that resolves to the amount in SD. */ async convertAmountToSD(oftType, amountLD) { const rate = await this.getLd2SdRate(oftType); return BigInt(amountLD) / BigInt(rate); } /** * Creates the payload for registering a coin. * * @param {string} oftType - The type of the OFT. * @returns {aptos.Types.EntryFunctionPayload} The payload for registering a coin. */ payloadOfCoinRegister(oftType) { return { function: `0x1::managed_coin::register`, type_arguments: [oftType], arguments: [] }; } /** * Registers a coin. * * @param {aptos.AptosAccount} signer - The signer account. * @param {string} oftType - The type of the OFT. * @returns {Promise} A promise that resolves to the transaction. */ async coinRegister(signer, oftType) { const transaction = this.payloadOfCoinRegister(oftType); return this.sdk.sendAndConfirmTransaction(signer, transaction); } /** * Gets the address from the OFT type. * * @param {string} oftType - The type of the OFT. * @returns {string} The address. * @throws {Error} If the OFT type is invalid. */ getTypeAddress(oftType) { const match = oftType.match(/0x(?
.*)::(?.*)::(?.*)/i); if (!match) { throw new Error(`Invalid oft type: ${oftType}`); } const { address } = match.groups; return address; } /** * Gets the global store resource for the OFT. * * @param {string} oftType - The type of the OFT. * @returns {Promise} A promise that resolves to the global store resource. */ async getGlobalStore(oftType) { const address = this.getTypeAddress(oftType); return this.sdk.client.getAccountResource(address, `${this.module}::GlobalStore<${oftType}>`); } /** * Gets the coin store resource for the OFT. * * @param {string} oftType - The type of the OFT. * @returns {Promise} A promise that resolves to the coin store resource. */ async getCoinStore(oftType) { const address = this.getTypeAddress(oftType); return this.sdk.client.getAccountResource(address, `${this.module}::CoinStore<${oftType}>`); } /** * Creates the payload for transferring a coin. * * @param {string} oftType - The type of the OFT. * @param {aptos.MaybeHexString} to - The recipient address. * @param {aptos.BCS.Uint64 | aptos.BCS.Uint32} amount - The amount to transfer. * @returns {aptos.Types.EntryFunctionPayload} The payload for transferring a coin. */ transferPayload(oftType, to, amount) { return { function: `0x1::coin::transfer`, type_arguments: [oftType], arguments: [to, amount] }; } /** * Transfers a coin. * * @param {aptos.AptosAccount} signer - The signer account. * @param {string} oftType - The type of the OFT. * @param {aptos.MaybeHexString} to - The recipient address. * @param {aptos.BCS.Uint64 | aptos.BCS.Uint32} amount - The amount to transfer. * @returns {Promise} A promise that resolves to the transaction. */ async transfer(signer, oftType, to, amount) { const transaction = this.transferPayload(oftType, to, amount); return this.sdk.sendAndConfirmTransaction(signer, transaction); } // ------------------------------ view functions ------------------------------ /** * Gets the balance of a coin for a given owner. * * @param {string} oftType - The type of the OFT. * @param {aptos.MaybeHexString} owner - The owner address. * @returns {Promise} A promise that resolves to the balance. */ async balance(oftType, owner) { try { const resource = await this.sdk.client.getAccountResource(owner, `0x1::coin::CoinStore<${oftType}>`); const { coin: c } = resource.data; return BigInt(c.value); } catch (e) { if (isErrorOfApiError(e, 404)) { return BigInt(0); } throw e; } } /** * Checks if an account is registered for a given coin. * * @param {string} oftType - The type of the OFT. * @param {aptos.MaybeHexString} accountAddr - The account address. * @returns {Promise} A promise that resolves to true if the account is registered, false otherwise. */ async isAccountRegistered(oftType, accountAddr) { try { await this.sdk.client.getAccountResource(accountAddr, `0x1::coin::CoinStore<${oftType}>`); return true; } catch (e) { if (isErrorOfApiError(e, 404)) { return false; } throw e; } } /** * Gets the current timestamp. * * @returns {Promise} A promise that resolves to the current timestamp. */ async getCurrentTimestamp() { const resource = await this.sdk.client.getAccountResource("0x1", "0x1::timestamp::CurrentTimeMicroseconds"); const { microseconds } = resource.data; return BigInt(microseconds) / BigInt(1e6); } /** * Gets the supply of a coin for a given owner. * * @param {string} oftType - The type of the OFT. * @param {aptos.MaybeHexString} oftOwner - The owner address. * @returns {Promise} A promise that resolves to the supply. */ async supply(oftType, oftOwner) { try { const resource = await this.sdk.client.getAccountResource( oftOwner, `0x1::coin::CoinInfo<${oftType}>` ); return BigInt(resource.data.supply.vec[0].integer.vec[0].value); } catch (e) { if (isErrorOfApiError(e, 404)) { return BigInt(0); } throw e; } } }; var Oracle = class { /** * Creates an instance of the Oracle class. * * @param {SDK} sdk - The SDK instance. * @param {aptos.MaybeHexString} address - The address of the Oracle. */ constructor(sdk, address) { this.sdk = sdk; this.address = address; this.module = `${this.address}::oracle`; this.moduleName = "oracle::oracle"; } /** * The address of the Oracle. */ address; /** * The module of the Oracle. */ module; /** * The module name of the Oracle. */ moduleName; /** * Gets the threshold value. * * @returns {Promise} A promise that resolves to the threshold value. */ async getThreshold() { const resource = await this.sdk.client.getAccountResource(this.address, `${this.module}::Config`); const { threshold } = resource.data; return Number(threshold); } /** * Creates a payload for setting the threshold. * * @param {aptos.BCS.Uint8} threshold - The threshold value. * @returns {aptos.Types.EntryFunctionPayload} The payload. */ setThresholdPayload(threshold) { return { function: `${this.module}::set_threshold`, type_arguments: [], arguments: [threshold] }; } /** * Sets the threshold value. * * @param {aptos.AptosAccount} signer - The signer account. * @param {aptos.BCS.Uint8} threshold - The threshold value. * @returns {Promise} A promise that resolves to the transaction. */ async setThreshold(signer, threshold) { const transaction = this.setThresholdPayload(threshold); return this.sdk.sendAndConfirmTransaction(signer, transaction); } /** * Checks if a validator is valid. * * @param {aptos.MaybeHexString} validator - The validator address. * @returns {Promise} A promise that resolves to true if the validator is valid, false otherwise. */ async isValidator(validator) { const resource = await this.sdk.client.getAccountResource(this.address, `${this.module}::Config`); const { validators } = resource.data; const val = aptos2__namespace.HexString.ensure(validator).toShortString(); return validators.includes(val); } /** * Creates a payload for setting a validator. * * @param {aptos.MaybeHexString} validator - The validator address. * @param {boolean} active - The active status of the validator. * @returns {aptos.Types.EntryFunctionPayload} The payload. */ setValidatorPayload(validator, active) { return { function: `${this.module}::set_validator`, type_arguments: [], arguments: [validator, active] }; } /** * Sets a validator. * * @param {aptos.AptosAccount} signer - The signer account. * @param {aptos.MaybeHexString} validator - The validator address. * @param {boolean} active - The active status of the validator. * @returns {Promise} A promise that resolves to the transaction. */ async setValidator(signer, validator, active) { const transaction = this.setValidatorPayload(validator, active); return this.sdk.sendAndConfirmTransaction(signer, transaction); } /** * Creates a payload for setting a fee. * * @param {aptos.BCS.Uint16} dstChainId - The destination chain ID. * @param {aptos.BCS.Uint64 | aptos.BCS.Uint32} baseFee - The base fee. * @returns {aptos.Types.EntryFunctionPayload} The payload. */ setFeePayload(dstChainId, baseFee) { return { function: `${this.module}::set_fee`, type_arguments: [], arguments: [dstChainId, baseFee] }; } /** * Sets a fee. * * @param {aptos.AptosAccount} signer - The signer account. * @param {aptos.BCS.Uint16} dstChainId - The destination chain ID. * @param {aptos.BCS.Uint64 | aptos.BCS.Uint32} baseFee - The base fee. * @returns {Promise} A promise that resolves to the transaction. */ async setFee(signer, dstChainId, baseFee) { const transaction = this.setFeePayload(dstChainId, baseFee); return this.sdk.sendAndConfirmTransaction(signer, transaction); } /** * Creates a payload for proposing a transaction. * * @param {Uint8Array} hash - The hash of the transaction. * @param {aptos.BCS.Uint64 | aptos.BCS.Uint32} confirmations - The number of confirmations. * @returns {aptos.Types.EntryFunctionPayload} The payload. */ getProposePayload(hash, confirmations) { return { function: `${this.module}::propose`, type_arguments: [], arguments: [Array.from(hash), confirmations] }; } /** * Proposes a transaction. * * @param {aptos.AptosAccount} signer - The signer account. * @param {Uint8Array} hash - The hash of the transaction. * @param {aptos.BCS.Uint64 | aptos.BCS.Uint32} confirmations - The number of confirmations. * @returns {Promise} A promise that resolves to the transaction. */ async propose(signer, hash, confirmations) { const transaction = this.getProposePayload(hash, confirmations); return this.sdk.sendAndConfirmTransaction(signer, transaction); } /** * Checks if a proposal is submitted. * * @param {aptos.MaybeHexString} validator - The validator address. * @param {string} hash - The hash of the transaction. * @param {aptos.BCS.Uint64 | aptos.BCS.Uint32} confirmations - The number of confirmations. * @returns {Promise} A promise that resolves to true if the proposal is submitted, false otherwise. */ async isSubmitted(validator, hash, confirmations) { const resource = await this.sdk.client.getAccountResource( this.address, `${this.module}::ProposalStore` ); const { proposals } = resource.data; try { const proposal = await this.sdk.client.getTableItem(proposals.handle, { key_type: `${this.module}::ProposalKey`, value_type: `${this.module}::Proposal`, key: { hash, confirmations: confirmations.toString() } }); if (proposal.submitted) { return true; } const val = aptos2__namespace.HexString.ensure(validator).toShortString(); return proposal.approved_by.includes(val); } catch (e) { if (isErrorOfApiError(e, 404)) { return false; } else { throw e; } } } /** * Gets the resource address. * * @returns {Promise} A promise that resolves to the resource address. */ async getResourceAddress() { const resource = await this.sdk.client.getAccountResource(this.address, `${this.module}::Config`); const { resource_addr } = resource.data; return fullAddress(resource_addr).toString(); } /** * Withdraws a fee. * * @param {aptos.AptosAccount} signer - The signer account. * @param {aptos.MaybeHexString} receiver - The receiver address. * @param {aptos.BCS.Uint64} amount - The amount to withdraw. * @returns {Promise} A promise that resolves to the transaction. */ async withdrawFee(signer, receiver, amount) { const transaction = { function: `${this.module}::withdraw_fee`, type_arguments: [], arguments: [receiver, amount] }; return this.sdk.sendAndConfirmTransaction(signer, transaction); } }; // src/modules/apps/precrime.ts var PreCrime = class { sdk; /** * The address of the PreCrime module. */ address; /** * The module path for the PreCrime module. */ module; /** * The module name for the PreCrime module. */ moduleName; /** * Creates an instance of the PreCrime class. * * @param {SDK} sdk - The SDK instance. * @param {aptos.MaybeHexString} address - The address of the PreCrime module. */ constructor(sdk, address) { this.sdk = sdk; this.address = address; this.module = `${this.address}::precrime`; this.moduleName = "oft_precrime::precrime"; } // --------------- admin --------------- /** * Set the precrime peers for a given OFT type. * * @param {string} oftType - The OFT type, e.g. 0x1::BTCbOFT::BTCb. * @param {aptos.BCS.Uint32[]} eids - The EIDs to set the precrime peers for, e.g. [101, 102, 106] for [ETHEREUM, BSC, AVALANCHE]. * @param {aptos.MaybeHexString[]} precrimePeers - The precrime peers to set. * @returns {aptos.Types.EntryFunctionPayload} The payload to be used in the transaction. */ setPreCrimePeersPayload(oftType, eids, precrimePeers) { this.assertType(oftType); const precrimePeerBytes = precrimePeers.map((peer) => { return Array.from(stringToPaddedUint8Array(peer.toString(), 32)); }); return { function: `${OFT_PRECRIME_ADDRESS[this.sdk.stage]}::oft_precrime::set_precrime_peers`, type_arguments: [oftType], arguments: [eids, Array.from(precrimePeerBytes)] }; } /** * Set the max batch size for a given OFT type. * * @param {string} oftType - The OFT type, e.g. 0x1::BTCbOFT::BTCb. * @param {aptos.BCS.Uint64} maxBatchSize - The max batch size to set. * @returns {aptos.Types.EntryFunctionPayload} The payload to be used in the transaction. */ setMaxBatchSizePayload(oftType, maxBatchSize) { this.assertType(oftType); return { function: `${OFT_PRECRIME_ADDRESS[this.sdk.stage]}::oft_precrime::set_max_batch_size`, type_arguments: [oftType], arguments: [maxBatchSize] }; } // --------------- workflow --------------- // 1. getConfig, parse precrime peers // 2. simulate to all precrime peers // 3. precrime with all precrime peers simulations /** * Get the configuration for the given packets. * * @param {aptos.MaybeHexString[]} packets - The packets to get the configuration for. * @param {string} [ledger_version] - The ledger version. * @returns {Promise} The configuration. */ async getConfig(packets, ledger_version) { const types = await this.getConfigTypes(packets, ledger_version); const payload = { function: `${this.module}::get_config`, type_arguments: types, arguments: [packets] }; const ret = await this.sdk.client.view(payload, ledger_version); return ret[0]; } /** * Simulate the given packets. * * @param {aptos.MaybeHexString[]} packets - The packets to simulate. * @param {string} [ledger_version] - The ledger version. * @returns {Promise} The simulation result. */ async simulate(packets, ledger_version) { const types = await this.getSimulateTypes(packets, ledger_version); const payload = { function: `${this.module}::simulate`, type_arguments: types, arguments: [packets] }; const ret = await this.sdk.client.view(payload, ledger_version); return ret[0]; } /** * Perform precrime with the given packets and simulations. * * @param {aptos.MaybeHexString[]} packets - The packets to precrime. * @param {aptos.MaybeHexString[]} simulations - The simulations to use for precrime. * @param {string} [ledger_version] - The ledger version. * @returns {Promise} The result of the precrime. */ async precrime(packets, simulations, ledger_version) { const types = await this.getPreCrimeTypes(packets, simulations, ledger_version); const payload = { function: `${this.module}::precrime`, type_arguments: types, arguments: [packets, simulations] }; const ret = await this.sdk.client.view(payload, ledger_version); return ret[0]; } /** * Get the configuration types for the given packets. * * @param {aptos.MaybeHexString[]} packets - The packets to get the configuration types for. * @param {string} [ledger_version] - The ledger version. * @returns {Promise} The configuration types. */ async getConfigTypes(packets, ledger_version) { const payload = { function: `${this.module}::get_config_types`, type_arguments: [], arguments: [packets] }; const ret = await this.sdk.client.view(payload, ledger_version); const types = ret[0]; return this.formatTypes(types); } /** * Get the simulation types for the given packets. * * @param {aptos.MaybeHexString[]} packets - The packets to get the simulation types for. * @param {string} [ledger_version] - The ledger version. * @returns {Promise} The simulation types. */ async getSimulateTypes(packets, ledger_version) { const payload = { function: `${this.module}::simulate_types`, type_arguments: [], arguments: [packets] }; const ret = await this.sdk.client.view(payload, ledger_version); const types = ret[0]; return this.formatTypes(types); } /** * Get the precrime types for the given packets and simulations. * * @param {aptos.MaybeHexString[]} packets - The packets to get the precrime types for. * @param {aptos.MaybeHexString[]} simulations - The simulations to use for precrime. * @param {string} [ledger_version] - The ledger version. * @returns {Promise} The precrime types. */ async getPreCrimeTypes(packets, simulations, ledger_version) { const payload = { function: `${this.module}::precrime_types`, type_arguments: [], arguments: [packets, simulations] }; const ret = await this.sdk.client.view(payload, ledger_version); const types = ret[0]; return this.formatTypes(types); } /** * Format the given types. * * @param {TypeInfo[]} types - The types to format. * @returns {string[]} The formatted types. */ formatTypes(types) { const rtn = []; for (const typeInfo of types) { const info = normalizeTypeInfo(typeInfo); rtn.push(buildStructTagFromTypeInfo(info)); } return rtn; } /** * Assert that the given OFT type is valid. * * @param {string} oftType - The OFT type to assert. * @throws {Error} If the OFT type is invalid. */ assertType(oftType) { const match = oftType.match(/0x(?
.*)::(?.*)::(?.*)/i); if (!match) { throw new Error(`Invalid oft type: ${oftType}`); } } }; // src/format/index.ts var format_exports = {}; __export(format_exports, { rebuildCompileScriptBytecode: () => rebuildCompileScriptBytecode }); // src/index.ts var SDK = class { /** * The stage of the SDK. */ stage; /** * The Aptos client instance. */ client; /** * The Layerzero module instance. */ LayerzeroModule; /** * The accounts options. */ accounts; /** * Creates an instance of the SDK class. * * @param {SdkOptions} options - The SDK options. */ constructor(options) { this.stage = options.stage ?? lzDefinitions.Stage.SANDBOX; this.accounts = options.accounts ?? { layerzero: LAYERZERO_ADDRESS[this.stage], msglib_auth: LAYERZERO_ADDRESS[this.stage], msglib_v1_1: LAYERZERO_ADDRESS[this.stage], msglib_v2: LAYERZERO_ADDRESS[this.stage], zro: LAYERZERO_ADDRESS[this.stage], executor_auth: LAYERZERO_ADDRESS[this.stage], executor_ext: EXECUTOR_EXT_ADDRESS[this.stage], executor_v2: LAYERZERO_ADDRESS[this.stage], layerzero_apps: LAYERZERO_APPS_ADDRESS[this.stage], layerzero_apps_pubkey: LAYERZERO_APPS_PUBKEY[this.stage], counter: COUNTER_ADDRESS[this.stage] }; this.client = options.provider; this.LayerzeroModule = new Layerzero(this); } /** * Sends and confirms a BCS transaction. * * @param {aptos.BCS.Bytes} bcsTransction - The BCS transaction. * @returns {Promise} The confirmed transaction. */ async sendAndConfirmBcsTransaction(bcsTransction) { const res = await this.client.submitSignedBCSTransaction(bcsTransction); return this.waitAndGetTransaction(res.hash); } /** * Sends and confirms a transaction. * * @param {aptos.AptosAccount} signer - The signer account. * @param {aptos.Types.EntryFunctionPayload} payload - The transaction payload. * @returns {Promise} The confirmed transaction. */ async sendAndConfirmTransaction(signer, payload) { const options = await this.estimateGas(signer, payload); const txnRequest = await this.client.generateTransaction(signer.address(), payload, options); const signedTxn = await this.client.signTransaction(signer, txnRequest); return this.sendAndConfirmRawTransaction(signedTxn); } /** * Estimates the gas for a transaction. * * @param {aptos.AptosAccount} signer - The signer account. * @param {aptos.Types.EntryFunctionPayload} payload - The transaction payload. * @returns {Promise<{ max_gas_amount: string, gas_unit_price: string }>} The gas estimation. */ async estimateGas(signer, payload) { const txnRequest = await this.client.generateTransaction(signer.address(), payload); const sim = await this.client.simulateTransaction(signer, txnRequest, { estimateGasUnitPrice: true, estimateMaxGasAmount: true, estimatePrioritizedGasUnitPrice: true }); const tx = sim[0]; invariant2__default.default(tx.success, `Transaction failed: ${tx.vm_status}}`); const max_gas_amount = applyGasLimitSafety(tx.gas_used).toString(); return { max_gas_amount, gas_unit_price: tx.gas_unit_price }; } /** * Sends and confirms a multi-signature transaction. * * @param {aptos.AptosClient} client - The Aptos client. * @param {string} multisigAccountAddress - The multi-signature account address. * @param {aptos.TxnBuilderTypes.MultiEd25519PublicKey} multisigAccountPubkey - The multi-signature account public key. * @param {aptos.TxnBuilderTypes.TransactionPayload} payload - The transaction payload. * @param {MultipleSignFunc} [signFunc] - The sign function. * @param {MutipleSignatureItem[]} [signedItems] - The signed items. * @returns {Promise} The confirmed transaction. */ async sendAndConfirmMultiSigTransaction(client, multisigAccountAddress, multisigAccountPubkey, payload, signFunc, signedItems) { const [{ sequence_number: sequenceNumber }, chainId] = await Promise.all([ client.getAccount(multisigAccountAddress), client.getChainId() ]); const rawTxn = new aptos2__namespace.TxnBuilderTypes.RawTransaction( aptos2__namespace.TxnBuilderTypes.AccountAddress.fromHex(multisigAccountAddress), BigInt(sequenceNumber), payload, BigInt(1e4), //todo: estimate gas, payload BigInt(100), //todo: get gas price BigInt(Math.floor(Date.now() / 1e3) + 10), new aptos2__namespace.TxnBuilderTypes.ChainId(chainId) ); const signingMessage = aptos2__namespace.TransactionBuilderMultiEd25519.getSigningMessage(rawTxn); let items; if (signedItems && signedItems.length > 0) { items = signedItems; } else if (signFunc) { items = await signFunc(signingMessage); } else { throw "No signFunc or signedItems provided"; } const signatures = items.map((item) => item.signature); const bitmap = items.map((item) => item.bitmap); const signedBCSTxn = multiSigSignedBCSTxn(multisigAccountPubkey, rawTxn, signatures, bitmap); const pendingTransaction = await client.submitSignedBCSTransaction(signedBCSTxn); const txnHash = pendingTransaction.hash; await client.waitForTransaction(pendingTransaction.hash); const txn = await client.getTransactionByHash(txnHash); invariant2__default.default(txn.type == "user_transaction", `Invalid response type: ${txn.type}`); invariant2__default.default(txn.success, `Transaction failed: ${txn.vm_status}`); return txn; } /** * Deploys a package. * * @param {aptos.AptosAccount} signer - The signer account. * @param {Uint8Array} metadata - The package metadata. * @param {aptos.TxnBuilderTypes.Module[]} modules - The modules to deploy. * @returns {Promise} The transaction hash. */ async deploy(signer, metadata, modules) { const gasUnitPrice = BigInt((await this.client.estimateGasPrice()).gas_estimate); const txnHash = await this.client.publishPackage(signer, metadata, modules, { maxGasAmount: BigInt(2e4 * modules.length), gasUnitPrice }); const txn = await this.client.waitForTransactionWithResult(txnHash); if (!txn.success) { throw new Error(txn.vm_status); } return txnHash; } /** * Waits for a transaction to be confirmed and retrieves it. * * @param {string} txnHash - The transaction hash. * @returns {Promise} The confirmed transaction. */ async waitAndGetTransaction(txnHash) { await this.client.waitForTransaction(txnHash); const tx = await this.client.getTransactionByHash(txnHash); invariant2__default.default(tx.type == "user_transaction", `Invalid response type: ${tx.type}`); const txn = tx; invariant2__default.default(txn.success, `Transaction failed: ${txn.vm_status}`); return tx; } /** * Sends and confirms a raw transaction. * * @param {Uint8Array} signedTransaction - The signed transaction. * @returns {Promise} The confirmed transaction. */ async sendAndConfirmRawTransaction(signedTransaction) { const res = await this.client.submitTransaction(signedTransaction); return this.waitAndGetTransaction(res.hash); } }; exports.SDK = SDK; exports.apps = apps_exports; exports.constants = constants_exports; exports.format = format_exports; exports.types = types_exports; exports.uln = uln_exports; exports.utils = utils_exports; //# sourceMappingURL=index.cjs.map //# sourceMappingURL=index.cjs.map