diff --git a/README.md b/README.md index eefbeea9..496d35ba 100644 --- a/README.md +++ b/README.md @@ -16,6 +16,10 @@ For details about documentation go to the original repo and check the documentat +### Lucid Fork + +Jucid is JSHy's fork of Lucid (Jshy + Lucid = Jucid). Lucid accidentally introduces memory leaks into applications due to incorrect memory management of WASM objects. Jucid handles internal memory correctly, exposes new interfaces to allow you to management objects you use correclty, and is a drop-in replacement for Lucid. Once this fork is merged into Lucid, it is unlikely it will be maintained. + ### Get started #### NPM diff --git a/build.ts b/build.ts index 8895e539..abec1e65 100644 --- a/build.ts +++ b/build.ts @@ -21,7 +21,7 @@ await dnt.build({ dependencies: { "node-fetch": "^3.2.3", "@peculiar/webcrypto": "^1.4.0", - "ws": "^8.10.0", + ws: "^8.10.0", }, main: "./esm/mod.js", type: "module", @@ -47,26 +47,30 @@ Deno.copyFileSync( const importPathPlugin = { name: "core-import-path", setup(build: any) { - build.onResolve({ - filter: - /^\.\/libs\/cardano_multiplatform_lib\/cardano_multiplatform_lib.generated.js$/, - }, (args: any) => { - return { - path: - "../esm/src/core/libs/cardano_multiplatform_lib/cardano_multiplatform_lib.generated.js", - external: true, - }; - }); - build.onResolve({ - filter: - /^\.\/libs\/cardano_message_signing\/cardano_message_signing.generated.js$/, - }, (args: any) => { - return { - path: - "../esm/src/core/libs/cardano_message_signing/cardano_message_signing.generated.js", - external: true, - }; - }); + build.onResolve( + { + filter: + /^\.\/libs\/cardano_multiplatform_lib\/cardano_multiplatform_lib.generated.js$/, + }, + (args: any) => { + return { + path: "../esm/src/core/libs/cardano_multiplatform_lib/cardano_multiplatform_lib.generated.js", + external: true, + }; + }, + ); + build.onResolve( + { + filter: + /^\.\/libs\/cardano_message_signing\/cardano_message_signing.generated.js$/, + }, + (args: any) => { + return { + path: "../esm/src/core/libs/cardano_message_signing/cardano_message_signing.generated.js", + external: true, + }; + }, + ); }, }; @@ -76,9 +80,7 @@ await esbuild.build({ entryPoints: ["./dist/esm/mod.js"], outfile: "./dist/web/mod.js", minify: true, - plugins: [ - importPathPlugin, - ], + plugins: [importPathPlugin], }); esbuild.stop(); @@ -146,8 +148,12 @@ export { C, M }; `; Deno.writeTextFileSync("dist/esm/src/core/core.js", coreFile); -Deno.mkdirSync("dist/esm/src/core/libs/cardano_message_signing/nodejs"); -Deno.mkdirSync("dist/esm/src/core/libs/cardano_multiplatform_lib/nodejs"); +Deno.mkdirSync("dist/esm/src/core/libs/cardano_message_signing/nodejs", { + recursive: true, +}); +Deno.mkdirSync("dist/esm/src/core/libs/cardano_multiplatform_lib/nodejs", { + recursive: true, +}); Deno.copyFileSync( "src/core/libs/cardano_message_signing/nodejs/cardano_message_signing.generated.js", diff --git a/dist/README.md b/dist/README.md index eefbeea9..496d35ba 100644 --- a/dist/README.md +++ b/dist/README.md @@ -16,6 +16,10 @@ For details about documentation go to the original repo and check the documentat +### Lucid Fork + +Jucid is JSHy's fork of Lucid (Jshy + Lucid = Jucid). Lucid accidentally introduces memory leaks into applications due to incorrect memory management of WASM objects. Jucid handles internal memory correctly, exposes new interfaces to allow you to management objects you use correclty, and is a drop-in replacement for Lucid. Once this fork is merged into Lucid, it is unlikely it will be maintained. + ### Get started #### NPM diff --git a/dist/esm/package.js b/dist/esm/package.js index 9e0a6851..613b50de 100644 --- a/dist/esm/package.js +++ b/dist/esm/package.js @@ -1,6 +1,6 @@ export default { "name": "@jpg-store/lucid-cardano", - "version": "0.10.12", + "version": "0.11.0", "license": "MIT", "description": "This is a fork of the original Lucid repo compiled into CommonJS. For more information check https://github.com/spacebudz/lucid", "repository": "https://github.com/jpg-store/lucid", diff --git a/dist/esm/src/core/libs/cardano_message_signing/cardano_message_signing.generated.js b/dist/esm/src/core/libs/cardano_message_signing/cardano_message_signing.generated.js index 412828a5..1ee2c363 100644 --- a/dist/esm/src/core/libs/cardano_message_signing/cardano_message_signing.generated.js +++ b/dist/esm/src/core/libs/cardano_message_signing/cardano_message_signing.generated.js @@ -1100,7 +1100,7 @@ export class COSEEncrypt { ciphertext() { try { const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); - wasm.coseencrypt0_ciphertext(retptr, this.ptr); + wasm.coseencrypt_ciphertext(retptr, this.ptr); var r0 = getInt32Memory0()[retptr / 4 + 0]; var r1 = getInt32Memory0()[retptr / 4 + 1]; let v0; @@ -1692,7 +1692,7 @@ export class COSESign { payload() { try { const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); - wasm.coseencrypt0_ciphertext(retptr, this.ptr); + wasm.coseencrypt_ciphertext(retptr, this.ptr); var r0 = getInt32Memory0()[retptr / 4 + 0]; var r1 = getInt32Memory0()[retptr / 4 + 1]; let v0; @@ -1801,7 +1801,7 @@ export class COSESign1 { payload() { try { const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); - wasm.coseencrypt0_ciphertext(retptr, this.ptr); + wasm.coseencrypt_ciphertext(retptr, this.ptr); var r0 = getInt32Memory0()[retptr / 4 + 0]; var r1 = getInt32Memory0()[retptr / 4 + 1]; let v0; @@ -2076,7 +2076,7 @@ export class COSESignature { signature() { try { const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); - wasm.cosesignature_signature(retptr, this.ptr); + wasm.cosesign1_signature(retptr, this.ptr); var r0 = getInt32Memory0()[retptr / 4 + 0]; var r1 = getInt32Memory0()[retptr / 4 + 1]; var v0 = getArrayU8FromWasm0(r0, r1).slice(); diff --git a/dist/esm/src/core/libs/cardano_message_signing/cardano_message_signing_bg.wasm b/dist/esm/src/core/libs/cardano_message_signing/cardano_message_signing_bg.wasm index 005b5601..9497ff2c 100644 Binary files a/dist/esm/src/core/libs/cardano_message_signing/cardano_message_signing_bg.wasm and b/dist/esm/src/core/libs/cardano_message_signing/cardano_message_signing_bg.wasm differ diff --git a/dist/esm/src/core/libs/cardano_message_signing/nodejs/cardano_message_signing.generated.js b/dist/esm/src/core/libs/cardano_message_signing/nodejs/cardano_message_signing.generated.js index edefd41a..6222db2d 100644 --- a/dist/esm/src/core/libs/cardano_message_signing/nodejs/cardano_message_signing.generated.js +++ b/dist/esm/src/core/libs/cardano_message_signing/nodejs/cardano_message_signing.generated.js @@ -1162,7 +1162,7 @@ class COSEEncrypt { ciphertext() { try { const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); - wasm.coseencrypt0_ciphertext(retptr, this.ptr); + wasm.coseencrypt_ciphertext(retptr, this.ptr); var r0 = getInt32Memory0()[retptr / 4 + 0]; var r1 = getInt32Memory0()[retptr / 4 + 1]; let v0; @@ -1768,7 +1768,7 @@ class COSESign { payload() { try { const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); - wasm.coseencrypt0_ciphertext(retptr, this.ptr); + wasm.coseencrypt_ciphertext(retptr, this.ptr); var r0 = getInt32Memory0()[retptr / 4 + 0]; var r1 = getInt32Memory0()[retptr / 4 + 1]; let v0; @@ -1880,7 +1880,7 @@ class COSESign1 { payload() { try { const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); - wasm.coseencrypt0_ciphertext(retptr, this.ptr); + wasm.coseencrypt_ciphertext(retptr, this.ptr); var r0 = getInt32Memory0()[retptr / 4 + 0]; var r1 = getInt32Memory0()[retptr / 4 + 1]; let v0; @@ -2181,7 +2181,7 @@ class COSESignature { signature() { try { const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); - wasm.cosesignature_signature(retptr, this.ptr); + wasm.cosesign1_signature(retptr, this.ptr); var r0 = getInt32Memory0()[retptr / 4 + 0]; var r1 = getInt32Memory0()[retptr / 4 + 1]; var v0 = getArrayU8FromWasm0(r0, r1).slice(); diff --git a/dist/esm/src/core/libs/cardano_multiplatform_lib/cardano_multiplatform_lib.generated.js b/dist/esm/src/core/libs/cardano_multiplatform_lib/cardano_multiplatform_lib.generated.js index 679e0ed5..3b8b1d1c 100644 --- a/dist/esm/src/core/libs/cardano_multiplatform_lib/cardano_multiplatform_lib.generated.js +++ b/dist/esm/src/core/libs/cardano_multiplatform_lib/cardano_multiplatform_lib.generated.js @@ -1,8 +1,25 @@ // @generated file from wasmbuild -- do not edit // deno-lint-ignore-file // deno-fmt-ignore-file -// source-hash: ab17726f2df5571be15d036e67423022ed8f63e4 +// source-hash: fea5fc75a13596f0eb0af3e358328b34adb4ded3 let wasm; +const heap = new Array(128).fill(undefined); +heap.push(undefined, null, true, false); +function getObject(idx) { + return heap[idx]; +} +let heap_next = heap.length; +function dropObject(idx) { + if (idx < 132) + return; + heap[idx] = heap_next; + heap_next = idx; +} +function takeObject(idx) { + const ret = getObject(idx); + dropObject(idx); + return ret; +} const cachedTextDecoder = new TextDecoder("utf-8", { ignoreBOM: true, fatal: true, @@ -18,9 +35,6 @@ function getUint8Memory0() { function getStringFromWasm0(ptr, len) { return cachedTextDecoder.decode(getUint8Memory0().subarray(ptr, ptr + len)); } -const heap = new Array(128).fill(undefined); -heap.push(undefined, null, true, false); -let heap_next = heap.length; function addHeapObject(obj) { if (heap_next === heap.length) heap.push(heap.length + 1); @@ -29,20 +43,6 @@ function addHeapObject(obj) { heap[idx] = obj; return idx; } -function getObject(idx) { - return heap[idx]; -} -function dropObject(idx) { - if (idx < 132) - return; - heap[idx] = heap_next; - heap_next = idx; -} -function takeObject(idx) { - const ret = getObject(idx); - dropObject(idx); - return ret; -} let WASM_VECTOR_LEN = 0; const cachedTextEncoder = new TextEncoder("utf-8"); const encodeString = function (arg, view) { @@ -186,8 +186,7 @@ function makeMutClosure(arg0, arg1, dtor, f) { return real; } function __wbg_adapter_30(arg0, arg1, arg2) { - wasm - ._dyn_core__ops__function__FnMut__A____Output___R_as_wasm_bindgen__closure__WasmClosure___describe__invoke__h9de9452916ac8cca(arg0, arg1, addHeapObject(arg2)); + wasm.wasm_bindgen__convert__closures__invoke1_mut__hee80fd123b909250(arg0, arg1, addHeapObject(arg2)); } function _assertClass(instance, klass) { if (!(instance instanceof klass)) { @@ -709,8 +708,8 @@ function handleError(f, args) { wasm.__wbindgen_exn_store(addHeapObject(e)); } } -function __wbg_adapter_1680(arg0, arg1, arg2, arg3) { - wasm.wasm_bindgen__convert__closures__invoke2_mut__h36afefe016e25d40(arg0, arg1, addHeapObject(arg2), addHeapObject(arg3)); +function __wbg_adapter_1681(arg0, arg1, arg2, arg3) { + wasm.wasm_bindgen__convert__closures__invoke2_mut__h5b4d9f16616fac4b(arg0, arg1, addHeapObject(arg2), addHeapObject(arg3)); } /** */ export const StakeCredKind = Object.freeze({ @@ -7534,7 +7533,7 @@ export class GovernanceActionId { * @returns {BigNum} */ governance_action_index() { - const ret = wasm.constrplutusdata_alternative(this.ptr); + const ret = wasm.governanceactionid_governance_action_index(this.ptr); return BigNum.__wrap(ret); } /** @@ -7975,7 +7974,7 @@ export class HeaderBody { * @returns {BigNum} */ slot() { - const ret = wasm.constrplutusdata_alternative(this.ptr); + const ret = wasm.headerbody_slot(this.ptr); return BigNum.__wrap(ret); } /** @@ -8216,7 +8215,7 @@ export class Int { as_i32_or_nothing() { try { const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); - wasm.int_as_i32(retptr, this.ptr); + wasm.int_as_i32_or_nothing(retptr, this.ptr); var r0 = getInt32Memory0()[retptr / 4 + 0]; var r1 = getInt32Memory0()[retptr / 4 + 1]; return r0 === 0 ? undefined : r1; @@ -9057,14 +9056,14 @@ export class LinearFee { * @returns {BigNum} */ constant() { - const ret = wasm.constrplutusdata_alternative(this.ptr); + const ret = wasm.linearfee_constant(this.ptr); return BigNum.__wrap(ret); } /** * @returns {BigNum} */ coefficient() { - const ret = wasm.exunits_steps(this.ptr); + const ret = wasm.linearfee_coefficient(this.ptr); return BigNum.__wrap(ret); } /** @@ -11259,7 +11258,7 @@ export class NewConstitution { * @returns {DataHash} */ hash() { - const ret = wasm.newconstitution_hash(this.ptr); + const ret = wasm.genesiskeydelegation_vrf_keyhash(this.ptr); return DataHash.__wrap(ret); } /** @@ -11515,7 +11514,7 @@ export class OperationalCert { * @returns {number} */ sequence_number() { - const ret = wasm.networkinfo_protocol_magic(this.ptr); + const ret = wasm.operationalcert_sequence_number(this.ptr); return ret >>> 0; } /** @@ -12863,28 +12862,28 @@ export class PoolParams { * @returns {VRFKeyHash} */ vrf_keyhash() { - const ret = wasm.poolparams_vrf_keyhash(this.ptr); + const ret = wasm.governanceactionid_transaction_id(this.ptr); return VRFKeyHash.__wrap(ret); } /** * @returns {BigNum} */ pledge() { - const ret = wasm.constrplutusdata_alternative(this.ptr); + const ret = wasm.governanceactionid_governance_action_index(this.ptr); return BigNum.__wrap(ret); } /** * @returns {BigNum} */ cost() { - const ret = wasm.exunits_steps(this.ptr); + const ret = wasm.poolparams_cost(this.ptr); return BigNum.__wrap(ret); } /** * @returns {UnitInterval} */ margin() { - const ret = wasm.drepvotingthresholds_committee_normal(this.ptr); + const ret = wasm.drepvotingthresholds_update_constitution(this.ptr); return UnitInterval.__wrap(ret); } /** @@ -13227,7 +13226,7 @@ export class PoolRetirement { * @returns {number} */ epoch() { - const ret = wasm.networkinfo_protocol_magic(this.ptr); + const ret = wasm.poolretirement_epoch(this.ptr); return ret >>> 0; } /** @@ -13758,7 +13757,7 @@ export class ProposalProcedure { * @returns {BigNum} */ deposit() { - const ret = wasm.constrplutusdata_alternative(this.ptr); + const ret = wasm.proposalprocedure_deposit(this.ptr); return BigNum.__wrap(ret); } /** @@ -14837,7 +14836,7 @@ export class ProtocolVersion { * @returns {number} */ minor() { - const ret = wasm.operationalcert_kes_period(this.ptr); + const ret = wasm.protocolversion_minor(this.ptr); return ret >>> 0; } /** @@ -15089,14 +15088,14 @@ export class Redeemer { * @returns {BigNum} */ index() { - const ret = wasm.constrplutusdata_alternative(this.ptr); + const ret = wasm.poolparams_cost(this.ptr); return BigNum.__wrap(ret); } /** * @returns {PlutusData} */ data() { - const ret = wasm.redeemer_data(this.ptr); + const ret = wasm.data_get(this.ptr); return PlutusData.__wrap(ret); } /** @@ -15634,14 +15633,14 @@ export class RegCommitteeHotKeyCert { * @returns {Ed25519KeyHash} */ committee_cold_keyhash() { - const ret = wasm.genesiskeydelegation_genesishash(this.ptr); + const ret = wasm.regcommitteehotkeycert_committee_cold_keyhash(this.ptr); return Ed25519KeyHash.__wrap(ret); } /** * @returns {Ed25519KeyHash} */ committee_hot_keyhash() { - const ret = wasm.genesiskeydelegation_genesis_delegate_hash(this.ptr); + const ret = wasm.regcommitteehotkeycert_committee_hot_keyhash(this.ptr); return Ed25519KeyHash.__wrap(ret); } /** @@ -16171,7 +16170,7 @@ export class RequiredWitnessSet { */ add_vkey_key(vkey) { _assertClass(vkey, Vkey); - wasm.requiredwitnessset_add_vkey(this.ptr, vkey.ptr); + wasm.requiredwitnessset_add_vkey_key(this.ptr, vkey.ptr); } /** * @param {Ed25519KeyHash} hash @@ -17540,14 +17539,14 @@ export class ScriptNOfK { * @returns {number} */ n() { - const ret = wasm.networkinfo_protocol_magic(this.ptr); + const ret = wasm.scriptnofk_n(this.ptr); return ret >>> 0; } /** * @returns {NativeScripts} */ native_scripts() { - const ret = wasm.scriptnofk_native_scripts(this.ptr); + const ret = wasm.scriptall_native_scripts(this.ptr); return NativeScripts.__wrap(ret); } /** @@ -17689,7 +17688,7 @@ export class ScriptPubkey { * @returns {Ed25519KeyHash} */ addr_keyhash() { - const ret = wasm.genesiskeydelegation_genesishash(this.ptr); + const ret = wasm.regcommitteehotkeycert_committee_cold_keyhash(this.ptr); return Ed25519KeyHash.__wrap(ret); } /** @@ -18269,7 +18268,7 @@ export class SingleHostName { * @returns {DNSRecordAorAAAA} */ dns_name() { - const ret = wasm.anchor_anchor_url(this.ptr); + const ret = wasm.singlehostname_dns_name(this.ptr); return DNSRecordAorAAAA.__wrap(ret); } /** @@ -18729,7 +18728,7 @@ export class StakeDelegation { * @returns {StakeCredential} */ stake_credential() { - const ret = wasm.stakedelegation_stake_credential(this.ptr); + const ret = wasm.baseaddress_payment_cred(this.ptr); return StakeCredential.__wrap(ret); } /** @@ -18879,7 +18878,7 @@ export class StakeDeregistration { * @returns {StakeCredential} */ stake_credential() { - const ret = wasm.stakedelegation_stake_credential(this.ptr); + const ret = wasm.baseaddress_payment_cred(this.ptr); return StakeCredential.__wrap(ret); } /** @@ -19020,7 +19019,7 @@ export class StakeRegDelegCert { * @returns {StakeCredential} */ stake_credential() { - const ret = wasm.regcert_stake_credential(this.ptr); + const ret = wasm.stakeregdelegcert_stake_credential(this.ptr); return StakeCredential.__wrap(ret); } /** @@ -19179,7 +19178,7 @@ export class StakeRegistration { * @returns {StakeCredential} */ stake_credential() { - const ret = wasm.stakedelegation_stake_credential(this.ptr); + const ret = wasm.baseaddress_payment_cred(this.ptr); return StakeCredential.__wrap(ret); } /** @@ -19320,14 +19319,14 @@ export class StakeVoteDelegCert { * @returns {StakeCredential} */ stake_credential() { - const ret = wasm.stakedelegation_stake_credential(this.ptr); + const ret = wasm.baseaddress_payment_cred(this.ptr); return StakeCredential.__wrap(ret); } /** * @returns {Ed25519KeyHash} */ pool_keyhash() { - const ret = wasm.stakedelegation_pool_keyhash(this.ptr); + const ret = wasm.stakevotedelegcert_pool_keyhash(this.ptr); return Ed25519KeyHash.__wrap(ret); } /** @@ -19479,7 +19478,7 @@ export class StakeVoteRegDelegCert { * @returns {StakeCredential} */ stake_credential() { - const ret = wasm.regcert_stake_credential(this.ptr); + const ret = wasm.stakevoteregdelegcert_stake_credential(this.ptr); return StakeCredential.__wrap(ret); } /** @@ -19706,7 +19705,7 @@ export class TimelockExpiry { * @returns {BigNum} */ slot() { - const ret = wasm.constrplutusdata_alternative(this.ptr); + const ret = wasm.linearfee_constant(this.ptr); return BigNum.__wrap(ret); } /** @@ -19847,7 +19846,7 @@ export class TimelockStart { * @returns {BigNum} */ slot() { - const ret = wasm.constrplutusdata_alternative(this.ptr); + const ret = wasm.linearfee_constant(this.ptr); return BigNum.__wrap(ret); } /** @@ -20332,7 +20331,7 @@ export class TransactionBody { * @returns {BigNum} */ fee() { - const ret = wasm.constrplutusdata_alternative(this.ptr); + const ret = wasm.transactionbody_fee(this.ptr); return BigNum.__wrap(ret); } /** @@ -20417,13 +20416,13 @@ export class TransactionBody { */ set_validity_start_interval(validity_start_interval) { _assertClass(validity_start_interval, BigNum); - wasm.transactionbody_set_validity_start_interval(this.ptr, validity_start_interval.ptr); + wasm.protocolparamupdate_set_minfee_b(this.ptr, validity_start_interval.ptr); } /** * @returns {BigNum | undefined} */ validity_start_interval() { - const ret = wasm.transactionbody_validity_start_interval(this.ptr); + const ret = wasm.protocolparamupdate_minfee_b(this.ptr); return ret === 0 ? undefined : BigNum.__wrap(ret); } /** @@ -20515,13 +20514,13 @@ export class TransactionBody { */ set_total_collateral(total_collateral) { _assertClass(total_collateral, BigNum); - wasm.transactionbody_set_total_collateral(this.ptr, total_collateral.ptr); + wasm.protocolparamupdate_set_key_deposit(this.ptr, total_collateral.ptr); } /** * @returns {BigNum | undefined} */ total_collateral() { - const ret = wasm.transactionbody_total_collateral(this.ptr); + const ret = wasm.protocolparamupdate_key_deposit(this.ptr); return ret === 0 ? undefined : BigNum.__wrap(ret); } /** @@ -20611,6 +20610,37 @@ export class TransactionBuilder { const ptr = this.__destroy_into_raw(); wasm.__wbg_transactionbuilder_free(ptr); } + /** + * This automatically selects and adds inputs from {inputs} consisting of just enough to cover + * the outputs that have already been added. + * This should be called after adding all certs/outputs/etc and will be an error otherwise. + * Adding a change output must be called after via TransactionBuilder::balance() + * inputs to cover the minimum fees. This does not, however, set the txbuilder's fee. + * + * change_address is required here in order to determine the min ada requirement precisely + * weights is a coma separated representation of a Uint32Arary + * @param {TransactionUnspentOutputs} inputs + * @param {Address} change_address + * @param {string} weights_str + */ + add_inputs_from_impl(inputs, change_address, weights_str) { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + _assertClass(inputs, TransactionUnspentOutputs); + _assertClass(change_address, Address); + const ptr0 = passStringToWasm0(weights_str, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc); + const len0 = WASM_VECTOR_LEN; + wasm.transactionbuilder_add_inputs_from_impl(retptr, this.ptr, inputs.ptr, change_address.ptr, ptr0, len0); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + if (r1) { + throw takeObject(r0); + } + } + finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } /** * This automatically selects and adds inputs from {inputs} consisting of just enough to cover * the outputs that have already been added. @@ -20779,7 +20809,7 @@ export class TransactionBuilder { */ set_ttl(ttl) { _assertClass(ttl, BigNum); - wasm.transactionbuilder_set_ttl(this.ptr, ttl.ptr); + wasm.protocolparamupdate_set_minfee_b(this.ptr, ttl.ptr); } /** * @param {BigNum} validity_start_interval @@ -21136,7 +21166,7 @@ export class TransactionBuilder { * @returns {BigNum | undefined} */ get_fee_if_set() { - const ret = wasm.transactionbuilder_get_fee_if_set(this.ptr); + const ret = wasm.protocolparamupdate_minfee_a(this.ptr); return ret === 0 ? undefined : BigNum.__wrap(ret); } /** @@ -21862,7 +21892,7 @@ export class TransactionInput { * @returns {BigNum} */ index() { - const ret = wasm.constrplutusdata_alternative(this.ptr); + const ret = wasm.governanceactionid_governance_action_index(this.ptr); return BigNum.__wrap(ret); } /** @@ -24286,7 +24316,7 @@ export class UnregCommitteeHotKeyCert { * @returns {Ed25519KeyHash} */ committee_cold_keyhash() { - const ret = wasm.genesiskeydelegation_genesishash(this.ptr); + const ret = wasm.regcommitteehotkeycert_committee_cold_keyhash(this.ptr); return Ed25519KeyHash.__wrap(ret); } /** @@ -25269,7 +25299,7 @@ export class Value { * @returns {BigNum} */ coin() { - const ret = wasm.constrplutusdata_alternative(this.ptr); + const ret = wasm.value_coin(this.ptr); return BigNum.__wrap(ret); } /** @@ -25618,7 +25648,7 @@ export class Vkeywitness { * @returns {Vkey} */ vkey() { - const ret = wasm.vkey_new(this.ptr); + const ret = wasm.vkeywitness_vkey(this.ptr); return Vkey.__wrap(ret); } /** @@ -25959,14 +25989,14 @@ export class VoteDelegCert { * @returns {StakeCredential} */ stake_credential() { - const ret = wasm.stakedelegation_stake_credential(this.ptr); + const ret = wasm.baseaddress_payment_cred(this.ptr); return StakeCredential.__wrap(ret); } /** * @returns {Drep} */ drep() { - const ret = wasm.votedelegcert_drep(this.ptr); + const ret = wasm.stakevotedelegcert_drep(this.ptr); return Drep.__wrap(ret); } /** @@ -26480,7 +26510,7 @@ export class VotingProcedure { * @returns {GovernanceActionId} */ governance_action_id() { - const ret = wasm.transactionunspentoutput_input(this.ptr); + const ret = wasm.votingprocedure_governance_action_id(this.ptr); return GovernanceActionId.__wrap(ret); } /** @@ -26776,10 +26806,6 @@ export class Withdrawals { } const imports = { __wbindgen_placeholder__: { - __wbindgen_string_new: function (arg0, arg1) { - const ret = getStringFromWasm0(arg0, arg1); - return addHeapObject(ret); - }, __wbindgen_object_drop_ref: function (arg0) { takeObject(arg0); }, @@ -26795,17 +26821,21 @@ const imports = { getInt32Memory0()[arg0 / 4 + 1] = len0; getInt32Memory0()[arg0 / 4 + 0] = ptr0; }, - __wbg_transaction_new: function (arg0) { - const ret = Transaction.__wrap(arg0); + __wbindgen_string_new: function (arg0, arg1) { + const ret = getStringFromWasm0(arg0, arg1); return addHeapObject(ret); }, __wbg_fetch_16f5dddfc5a913a4: function (arg0, arg1) { const ret = getObject(arg0).fetch(getObject(arg1)); return addHeapObject(ret); }, + __wbg_transaction_new: function (arg0) { + const ret = Transaction.__wrap(arg0); + return addHeapObject(ret); + }, __wbindgen_string_get: function (arg0, arg1) { const obj = getObject(arg1); - const ret = typeof (obj) === "string" ? obj : undefined; + const ret = typeof obj === "string" ? obj : undefined; var ptr0 = isLikeNone(ret) ? 0 : passStringToWasm0(ret, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc); @@ -26858,15 +26888,9 @@ const imports = { const ret = false; return ret; }, - __wbg_randomFillSync_2f6909f8132a175d: function () { - return handleError(function (arg0, arg1, arg2) { - getObject(arg0).randomFillSync(getArrayU8FromWasm0(arg1, arg2)); - }, arguments); - }, - __wbg_getRandomValues_11a236fbf9914290: function () { - return handleError(function (arg0, arg1) { - getObject(arg0).getRandomValues(getObject(arg1)); - }, arguments); + __wbg_static_accessor_NODE_MODULE_06b864c18e8ae506: function () { + const ret = module; + return addHeapObject(ret); }, __wbg_process_5615a087a47ba544: function (arg0) { const ret = getObject(arg0).process; @@ -26874,7 +26898,7 @@ const imports = { }, __wbindgen_is_object: function (arg0) { const val = getObject(arg0); - const ret = typeof (val) === "object" && val !== null; + const ret = typeof val === "object" && val !== null; return ret; }, __wbg_versions_8404a8b21b9337ae: function (arg0) { @@ -26903,9 +26927,15 @@ const imports = { const ret = getObject(arg0).msCrypto; return addHeapObject(ret); }, - __wbg_static_accessor_NODE_MODULE_06b864c18e8ae506: function () { - const ret = module; - return addHeapObject(ret); + __wbg_randomFillSync_2f6909f8132a175d: function () { + return handleError(function (arg0, arg1, arg2) { + getObject(arg0).randomFillSync(getArrayU8FromWasm0(arg1, arg2)); + }, arguments); + }, + __wbg_getRandomValues_11a236fbf9914290: function () { + return handleError(function (arg0, arg1) { + getObject(arg0).getRandomValues(getObject(arg1)); + }, arguments); }, __wbg_self_e7c1f827057f6584: function () { return handleError(function () { @@ -26972,7 +27002,7 @@ const imports = { const a = state0.a; state0.a = 0; try { - return __wbg_adapter_1680(a, state0.b, arg0, arg1); + return __wbg_adapter_1681(a, state0.b, arg0, arg1); } finally { state0.a = a; @@ -27032,6 +27062,10 @@ const imports = { const ret = getObject(arg0).self; return addHeapObject(ret); }, + __wbg_require_0993fe224bf8e202: function (arg0, arg1) { + const ret = require(getStringFromWasm0(arg0, arg1)); + return addHeapObject(ret); + }, __wbg_crypto_e95a6e54c5c2e37f: function (arg0) { const ret = getObject(arg0).crypto; return addHeapObject(ret); @@ -27040,10 +27074,6 @@ const imports = { const ret = getObject(arg0).getRandomValues; return addHeapObject(ret); }, - __wbg_require_0993fe224bf8e202: function (arg0, arg1) { - const ret = require(getStringFromWasm0(arg0, arg1)); - return addHeapObject(ret); - }, __wbg_randomFillSync_dd2297de5917c74e: function (arg0, arg1, arg2) { getObject(arg0).randomFillSync(getArrayU8FromWasm0(arg1, arg2)); }, @@ -27064,8 +27094,8 @@ const imports = { const ret = wasm.memory; return addHeapObject(ret); }, - __wbindgen_closure_wrapper7018: function (arg0, arg1, arg2) { - const ret = makeMutClosure(arg0, arg1, 216, __wbg_adapter_30); + __wbindgen_closure_wrapper7021: function (arg0, arg1, arg2) { + const ret = makeMutClosure(arg0, arg1, 186, __wbg_adapter_30); return addHeapObject(ret); }, }, diff --git a/dist/esm/src/core/libs/cardano_multiplatform_lib/cardano_multiplatform_lib_bg.wasm b/dist/esm/src/core/libs/cardano_multiplatform_lib/cardano_multiplatform_lib_bg.wasm index c3c2bd39..2f771624 100644 Binary files a/dist/esm/src/core/libs/cardano_multiplatform_lib/cardano_multiplatform_lib_bg.wasm and b/dist/esm/src/core/libs/cardano_multiplatform_lib/cardano_multiplatform_lib_bg.wasm differ diff --git a/dist/esm/src/core/libs/cardano_multiplatform_lib/nodejs/cardano_multiplatform_lib.generated.js b/dist/esm/src/core/libs/cardano_multiplatform_lib/nodejs/cardano_multiplatform_lib.generated.js index c3ba5c58..77aa01ba 100644 --- a/dist/esm/src/core/libs/cardano_multiplatform_lib/nodejs/cardano_multiplatform_lib.generated.js +++ b/dist/esm/src/core/libs/cardano_multiplatform_lib/nodejs/cardano_multiplatform_lib.generated.js @@ -1,13 +1,35 @@ // @generated file from wasmbuild -- do not edit // deno-lint-ignore-file // deno-fmt-ignore-file -// source-hash: ab17726f2df5571be15d036e67423022ed8f63e4 +// source-hash: fea5fc75a13596f0eb0af3e358328b34adb4ded3 let imports = {}; imports["__wbindgen_placeholder__"] = module.exports; let wasm; const { TextDecoder, TextEncoder } = require(`util`); +const heap = new Array(128).fill(undefined); + +heap.push(undefined, null, true, false); + +function getObject(idx) { + return heap[idx]; +} + +let heap_next = heap.length; + +function dropObject(idx) { + if (idx < 132) return; + heap[idx] = heap_next; + heap_next = idx; +} + +function takeObject(idx) { + const ret = getObject(idx); + dropObject(idx); + return ret; +} + let cachedTextDecoder = new TextDecoder("utf-8", { ignoreBOM: true, fatal: true, @@ -28,12 +50,6 @@ function getStringFromWasm0(ptr, len) { return cachedTextDecoder.decode(getUint8Memory0().subarray(ptr, ptr + len)); } -const heap = new Array(128).fill(undefined); - -heap.push(undefined, null, true, false); - -let heap_next = heap.length; - function addHeapObject(obj) { if (heap_next === heap.length) heap.push(heap.length + 1); const idx = heap_next; @@ -43,22 +59,6 @@ function addHeapObject(obj) { return idx; } -function getObject(idx) { - return heap[idx]; -} - -function dropObject(idx) { - if (idx < 132) return; - heap[idx] = heap_next; - heap_next = idx; -} - -function takeObject(idx) { - const ret = getObject(idx); - dropObject(idx); - return ret; -} - let WASM_VECTOR_LEN = 0; let cachedTextEncoder = new TextEncoder("utf-8"); @@ -220,12 +220,11 @@ function makeMutClosure(arg0, arg1, dtor, f) { return real; } function __wbg_adapter_30(arg0, arg1, arg2) { - wasm - ._dyn_core__ops__function__FnMut__A____Output___R_as_wasm_bindgen__closure__WasmClosure___describe__invoke__h9de9452916ac8cca( - arg0, - arg1, - addHeapObject(arg2), - ); + wasm.wasm_bindgen__convert__closures__invoke1_mut__hee80fd123b909250( + arg0, + arg1, + addHeapObject(arg2), + ); } function _assertClass(instance, klass) { @@ -849,8 +848,8 @@ function handleError(f, args) { wasm.__wbindgen_exn_store(addHeapObject(e)); } } -function __wbg_adapter_1680(arg0, arg1, arg2, arg3) { - wasm.wasm_bindgen__convert__closures__invoke2_mut__h36afefe016e25d40( +function __wbg_adapter_1681(arg0, arg1, arg2, arg3) { + wasm.wasm_bindgen__convert__closures__invoke2_mut__h5b4d9f16616fac4b( arg0, arg1, addHeapObject(arg2), @@ -8010,7 +8009,7 @@ class GovernanceActionId { * @returns {BigNum} */ governance_action_index() { - const ret = wasm.constrplutusdata_alternative(this.ptr); + const ret = wasm.governanceactionid_governance_action_index(this.ptr); return BigNum.__wrap(ret); } /** @@ -8469,7 +8468,7 @@ class HeaderBody { * @returns {BigNum} */ slot() { - const ret = wasm.constrplutusdata_alternative(this.ptr); + const ret = wasm.headerbody_slot(this.ptr); return BigNum.__wrap(ret); } /** @@ -8737,7 +8736,7 @@ class Int { as_i32_or_nothing() { try { const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); - wasm.int_as_i32(retptr, this.ptr); + wasm.int_as_i32_or_nothing(retptr, this.ptr); var r0 = getInt32Memory0()[retptr / 4 + 0]; var r1 = getInt32Memory0()[retptr / 4 + 1]; return r0 === 0 ? undefined : r1; @@ -9619,14 +9618,14 @@ class LinearFee { * @returns {BigNum} */ constant() { - const ret = wasm.constrplutusdata_alternative(this.ptr); + const ret = wasm.linearfee_constant(this.ptr); return BigNum.__wrap(ret); } /** * @returns {BigNum} */ coefficient() { - const ret = wasm.exunits_steps(this.ptr); + const ret = wasm.linearfee_coefficient(this.ptr); return BigNum.__wrap(ret); } /** @@ -11921,7 +11920,7 @@ class NewConstitution { * @returns {DataHash} */ hash() { - const ret = wasm.newconstitution_hash(this.ptr); + const ret = wasm.genesiskeydelegation_vrf_keyhash(this.ptr); return DataHash.__wrap(ret); } /** @@ -12184,7 +12183,7 @@ class OperationalCert { * @returns {number} */ sequence_number() { - const ret = wasm.networkinfo_protocol_magic(this.ptr); + const ret = wasm.operationalcert_sequence_number(this.ptr); return ret >>> 0; } /** @@ -13600,28 +13599,28 @@ class PoolParams { * @returns {VRFKeyHash} */ vrf_keyhash() { - const ret = wasm.poolparams_vrf_keyhash(this.ptr); + const ret = wasm.governanceactionid_transaction_id(this.ptr); return VRFKeyHash.__wrap(ret); } /** * @returns {BigNum} */ pledge() { - const ret = wasm.constrplutusdata_alternative(this.ptr); + const ret = wasm.governanceactionid_governance_action_index(this.ptr); return BigNum.__wrap(ret); } /** * @returns {BigNum} */ cost() { - const ret = wasm.exunits_steps(this.ptr); + const ret = wasm.poolparams_cost(this.ptr); return BigNum.__wrap(ret); } /** * @returns {UnitInterval} */ margin() { - const ret = wasm.drepvotingthresholds_committee_normal(this.ptr); + const ret = wasm.drepvotingthresholds_update_constitution(this.ptr); return UnitInterval.__wrap(ret); } /** @@ -13994,7 +13993,7 @@ class PoolRetirement { * @returns {number} */ epoch() { - const ret = wasm.networkinfo_protocol_magic(this.ptr); + const ret = wasm.poolretirement_epoch(this.ptr); return ret >>> 0; } /** @@ -14546,7 +14545,7 @@ class ProposalProcedure { * @returns {BigNum} */ deposit() { - const ret = wasm.constrplutusdata_alternative(this.ptr); + const ret = wasm.proposalprocedure_deposit(this.ptr); return BigNum.__wrap(ret); } /** @@ -15675,7 +15674,7 @@ class ProtocolVersion { * @returns {number} */ minor() { - const ret = wasm.operationalcert_kes_period(this.ptr); + const ret = wasm.protocolversion_minor(this.ptr); return ret >>> 0; } /** @@ -15943,14 +15942,14 @@ class Redeemer { * @returns {BigNum} */ index() { - const ret = wasm.constrplutusdata_alternative(this.ptr); + const ret = wasm.poolparams_cost(this.ptr); return BigNum.__wrap(ret); } /** * @returns {PlutusData} */ data() { - const ret = wasm.redeemer_data(this.ptr); + const ret = wasm.data_get(this.ptr); return PlutusData.__wrap(ret); } /** @@ -16512,14 +16511,14 @@ class RegCommitteeHotKeyCert { * @returns {Ed25519KeyHash} */ committee_cold_keyhash() { - const ret = wasm.genesiskeydelegation_genesishash(this.ptr); + const ret = wasm.regcommitteehotkeycert_committee_cold_keyhash(this.ptr); return Ed25519KeyHash.__wrap(ret); } /** * @returns {Ed25519KeyHash} */ committee_hot_keyhash() { - const ret = wasm.genesiskeydelegation_genesis_delegate_hash(this.ptr); + const ret = wasm.regcommitteehotkeycert_committee_hot_keyhash(this.ptr); return Ed25519KeyHash.__wrap(ret); } /** @@ -17073,7 +17072,7 @@ class RequiredWitnessSet { */ add_vkey_key(vkey) { _assertClass(vkey, Vkey); - wasm.requiredwitnessset_add_vkey(this.ptr, vkey.ptr); + wasm.requiredwitnessset_add_vkey_key(this.ptr, vkey.ptr); } /** * @param {Ed25519KeyHash} hash @@ -18502,14 +18501,14 @@ class ScriptNOfK { * @returns {number} */ n() { - const ret = wasm.networkinfo_protocol_magic(this.ptr); + const ret = wasm.scriptnofk_n(this.ptr); return ret >>> 0; } /** * @returns {NativeScripts} */ native_scripts() { - const ret = wasm.scriptnofk_native_scripts(this.ptr); + const ret = wasm.scriptall_native_scripts(this.ptr); return NativeScripts.__wrap(ret); } /** @@ -18656,7 +18655,7 @@ class ScriptPubkey { * @returns {Ed25519KeyHash} */ addr_keyhash() { - const ret = wasm.genesiskeydelegation_genesishash(this.ptr); + const ret = wasm.regcommitteehotkeycert_committee_cold_keyhash(this.ptr); return Ed25519KeyHash.__wrap(ret); } /** @@ -19262,7 +19261,7 @@ class SingleHostName { * @returns {DNSRecordAorAAAA} */ dns_name() { - const ret = wasm.anchor_anchor_url(this.ptr); + const ret = wasm.singlehostname_dns_name(this.ptr); return DNSRecordAorAAAA.__wrap(ret); } /** @@ -19740,7 +19739,7 @@ class StakeDelegation { * @returns {StakeCredential} */ stake_credential() { - const ret = wasm.stakedelegation_stake_credential(this.ptr); + const ret = wasm.baseaddress_payment_cred(this.ptr); return StakeCredential.__wrap(ret); } /** @@ -19898,7 +19897,7 @@ class StakeDeregistration { * @returns {StakeCredential} */ stake_credential() { - const ret = wasm.stakedelegation_stake_credential(this.ptr); + const ret = wasm.baseaddress_payment_cred(this.ptr); return StakeCredential.__wrap(ret); } /** @@ -20044,7 +20043,7 @@ class StakeRegDelegCert { * @returns {StakeCredential} */ stake_credential() { - const ret = wasm.regcert_stake_credential(this.ptr); + const ret = wasm.stakeregdelegcert_stake_credential(this.ptr); return StakeCredential.__wrap(ret); } /** @@ -20212,7 +20211,7 @@ class StakeRegistration { * @returns {StakeCredential} */ stake_credential() { - const ret = wasm.stakedelegation_stake_credential(this.ptr); + const ret = wasm.baseaddress_payment_cred(this.ptr); return StakeCredential.__wrap(ret); } /** @@ -20358,14 +20357,14 @@ class StakeVoteDelegCert { * @returns {StakeCredential} */ stake_credential() { - const ret = wasm.stakedelegation_stake_credential(this.ptr); + const ret = wasm.baseaddress_payment_cred(this.ptr); return StakeCredential.__wrap(ret); } /** * @returns {Ed25519KeyHash} */ pool_keyhash() { - const ret = wasm.stakedelegation_pool_keyhash(this.ptr); + const ret = wasm.stakevotedelegcert_pool_keyhash(this.ptr); return Ed25519KeyHash.__wrap(ret); } /** @@ -20526,7 +20525,7 @@ class StakeVoteRegDelegCert { * @returns {StakeCredential} */ stake_credential() { - const ret = wasm.regcert_stake_credential(this.ptr); + const ret = wasm.stakevoteregdelegcert_stake_credential(this.ptr); return StakeCredential.__wrap(ret); } /** @@ -20772,7 +20771,7 @@ class TimelockExpiry { * @returns {BigNum} */ slot() { - const ret = wasm.constrplutusdata_alternative(this.ptr); + const ret = wasm.linearfee_constant(this.ptr); return BigNum.__wrap(ret); } /** @@ -20918,7 +20917,7 @@ class TimelockStart { * @returns {BigNum} */ slot() { - const ret = wasm.constrplutusdata_alternative(this.ptr); + const ret = wasm.linearfee_constant(this.ptr); return BigNum.__wrap(ret); } /** @@ -21418,7 +21417,7 @@ class TransactionBody { * @returns {BigNum} */ fee() { - const ret = wasm.constrplutusdata_alternative(this.ptr); + const ret = wasm.transactionbody_fee(this.ptr); return BigNum.__wrap(ret); } /** @@ -21506,7 +21505,7 @@ class TransactionBody { */ set_validity_start_interval(validity_start_interval) { _assertClass(validity_start_interval, BigNum); - wasm.transactionbody_set_validity_start_interval( + wasm.protocolparamupdate_set_minfee_b( this.ptr, validity_start_interval.ptr, ); @@ -21515,7 +21514,7 @@ class TransactionBody { * @returns {BigNum | undefined} */ validity_start_interval() { - const ret = wasm.transactionbody_validity_start_interval(this.ptr); + const ret = wasm.protocolparamupdate_minfee_b(this.ptr); return ret === 0 ? undefined : BigNum.__wrap(ret); } /** @@ -21607,13 +21606,13 @@ class TransactionBody { */ set_total_collateral(total_collateral) { _assertClass(total_collateral, BigNum); - wasm.transactionbody_set_total_collateral(this.ptr, total_collateral.ptr); + wasm.protocolparamupdate_set_key_deposit(this.ptr, total_collateral.ptr); } /** * @returns {BigNum | undefined} */ total_collateral() { - const ret = wasm.transactionbody_total_collateral(this.ptr); + const ret = wasm.protocolparamupdate_key_deposit(this.ptr); return ret === 0 ? undefined : BigNum.__wrap(ret); } /** @@ -21716,6 +21715,47 @@ class TransactionBuilder { const ptr = this.__destroy_into_raw(); wasm.__wbg_transactionbuilder_free(ptr); } + /** + * This automatically selects and adds inputs from {inputs} consisting of just enough to cover + * the outputs that have already been added. + * This should be called after adding all certs/outputs/etc and will be an error otherwise. + * Adding a change output must be called after via TransactionBuilder::balance() + * inputs to cover the minimum fees. This does not, however, set the txbuilder's fee. + * + * change_address is required here in order to determine the min ada requirement precisely + * weights is a coma separated representation of a Uint32Arary + * @param {TransactionUnspentOutputs} inputs + * @param {Address} change_address + * @param {string} weights_str + */ + add_inputs_from_impl(inputs, change_address, weights_str) { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + _assertClass(inputs, TransactionUnspentOutputs); + _assertClass(change_address, Address); + const ptr0 = passStringToWasm0( + weights_str, + wasm.__wbindgen_malloc, + wasm.__wbindgen_realloc, + ); + const len0 = WASM_VECTOR_LEN; + wasm.transactionbuilder_add_inputs_from_impl( + retptr, + this.ptr, + inputs.ptr, + change_address.ptr, + ptr0, + len0, + ); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + if (r1) { + throw takeObject(r0); + } + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } /** * This automatically selects and adds inputs from {inputs} consisting of just enough to cover * the outputs that have already been added. @@ -21893,7 +21933,7 @@ class TransactionBuilder { */ set_ttl(ttl) { _assertClass(ttl, BigNum); - wasm.transactionbuilder_set_ttl(this.ptr, ttl.ptr); + wasm.protocolparamupdate_set_minfee_b(this.ptr, ttl.ptr); } /** * @param {BigNum} validity_start_interval @@ -22275,7 +22315,7 @@ class TransactionBuilder { * @returns {BigNum | undefined} */ get_fee_if_set() { - const ret = wasm.transactionbuilder_get_fee_if_set(this.ptr); + const ret = wasm.protocolparamupdate_minfee_a(this.ptr); return ret === 0 ? undefined : BigNum.__wrap(ret); } /** @@ -23079,7 +23119,7 @@ class TransactionInput { * @returns {BigNum} */ index() { - const ret = wasm.constrplutusdata_alternative(this.ptr); + const ret = wasm.governanceactionid_governance_action_index(this.ptr); return BigNum.__wrap(ret); } /** @@ -25622,7 +25662,7 @@ class UnregCommitteeHotKeyCert { * @returns {Ed25519KeyHash} */ committee_cold_keyhash() { - const ret = wasm.genesiskeydelegation_genesishash(this.ptr); + const ret = wasm.regcommitteehotkeycert_committee_cold_keyhash(this.ptr); return Ed25519KeyHash.__wrap(ret); } /** @@ -26646,7 +26686,7 @@ class Value { * @returns {BigNum} */ coin() { - const ret = wasm.constrplutusdata_alternative(this.ptr); + const ret = wasm.value_coin(this.ptr); return BigNum.__wrap(ret); } /** @@ -27008,7 +27048,7 @@ class Vkeywitness { * @returns {Vkey} */ vkey() { - const ret = wasm.vkey_new(this.ptr); + const ret = wasm.vkeywitness_vkey(this.ptr); return Vkey.__wrap(ret); } /** @@ -27365,14 +27405,14 @@ class VoteDelegCert { * @returns {StakeCredential} */ stake_credential() { - const ret = wasm.stakedelegation_stake_credential(this.ptr); + const ret = wasm.baseaddress_payment_cred(this.ptr); return StakeCredential.__wrap(ret); } /** * @returns {Drep} */ drep() { - const ret = wasm.votedelegcert_drep(this.ptr); + const ret = wasm.stakevotedelegcert_drep(this.ptr); return Drep.__wrap(ret); } /** @@ -27905,7 +27945,7 @@ class VotingProcedure { * @returns {GovernanceActionId} */ governance_action_id() { - const ret = wasm.transactionunspentoutput_input(this.ptr); + const ret = wasm.votingprocedure_governance_action_id(this.ptr); return GovernanceActionId.__wrap(ret); } /** @@ -28215,11 +28255,6 @@ class Withdrawals { } module.exports.Withdrawals = Withdrawals; -module.exports.__wbindgen_string_new = function (arg0, arg1) { - const ret = getStringFromWasm0(arg0, arg1); - return addHeapObject(ret); -}; - module.exports.__wbindgen_object_drop_ref = function (arg0) { takeObject(arg0); }; @@ -28242,8 +28277,8 @@ module.exports.__wbindgen_json_serialize = function (arg0, arg1) { getInt32Memory0()[arg0 / 4 + 0] = ptr0; }; -module.exports.__wbg_transaction_new = function (arg0) { - const ret = Transaction.__wrap(arg0); +module.exports.__wbindgen_string_new = function (arg0, arg1) { + const ret = getStringFromWasm0(arg0, arg1); return addHeapObject(ret); }; @@ -28252,9 +28287,14 @@ module.exports.__wbg_fetch_16f5dddfc5a913a4 = function (arg0, arg1) { return addHeapObject(ret); }; +module.exports.__wbg_transaction_new = function (arg0) { + const ret = Transaction.__wrap(arg0); + return addHeapObject(ret); +}; + module.exports.__wbindgen_string_get = function (arg0, arg1) { const obj = getObject(arg1); - const ret = typeof (obj) === "string" ? obj : undefined; + const ret = typeof obj === "string" ? obj : undefined; var ptr0 = isLikeNone(ret) ? 0 : passStringToWasm0(ret, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc); @@ -28317,17 +28357,11 @@ module.exports.__wbindgen_cb_drop = function (arg0) { return ret; }; -module.exports.__wbg_randomFillSync_2f6909f8132a175d = function () { - return handleError(function (arg0, arg1, arg2) { - getObject(arg0).randomFillSync(getArrayU8FromWasm0(arg1, arg2)); - }, arguments); -}; - -module.exports.__wbg_getRandomValues_11a236fbf9914290 = function () { - return handleError(function (arg0, arg1) { - getObject(arg0).getRandomValues(getObject(arg1)); - }, arguments); -}; +module.exports.__wbg_static_accessor_NODE_MODULE_06b864c18e8ae506 = + function () { + const ret = module; + return addHeapObject(ret); + }; module.exports.__wbg_process_5615a087a47ba544 = function (arg0) { const ret = getObject(arg0).process; @@ -28336,7 +28370,7 @@ module.exports.__wbg_process_5615a087a47ba544 = function (arg0) { module.exports.__wbindgen_is_object = function (arg0) { const val = getObject(arg0); - const ret = typeof (val) === "object" && val !== null; + const ret = typeof val === "object" && val !== null; return ret; }; @@ -28372,11 +28406,17 @@ module.exports.__wbg_msCrypto_1088c21440b2d7e4 = function (arg0) { return addHeapObject(ret); }; -module.exports.__wbg_static_accessor_NODE_MODULE_06b864c18e8ae506 = - function () { - const ret = module; - return addHeapObject(ret); - }; +module.exports.__wbg_randomFillSync_2f6909f8132a175d = function () { + return handleError(function (arg0, arg1, arg2) { + getObject(arg0).randomFillSync(getArrayU8FromWasm0(arg1, arg2)); + }, arguments); +}; + +module.exports.__wbg_getRandomValues_11a236fbf9914290 = function () { + return handleError(function (arg0, arg1) { + getObject(arg0).getRandomValues(getObject(arg1)); + }, arguments); +}; module.exports.__wbg_self_e7c1f827057f6584 = function () { return handleError(function () { @@ -28454,7 +28494,7 @@ module.exports.__wbg_new_9d3a9ce4282a18a8 = function (arg0, arg1) { const a = state0.a; state0.a = 0; try { - return __wbg_adapter_1680(a, state0.b, arg0, arg1); + return __wbg_adapter_1681(a, state0.b, arg0, arg1); } finally { state0.a = a; } @@ -28525,6 +28565,11 @@ module.exports.__wbg_self_e0b3266d2d9eba1a = function (arg0) { return addHeapObject(ret); }; +module.exports.__wbg_require_0993fe224bf8e202 = function (arg0, arg1) { + const ret = require(getStringFromWasm0(arg0, arg1)); + return addHeapObject(ret); +}; + module.exports.__wbg_crypto_e95a6e54c5c2e37f = function (arg0) { const ret = getObject(arg0).crypto; return addHeapObject(ret); @@ -28535,11 +28580,6 @@ module.exports.__wbg_getRandomValues_dc67302a7bd1aec5 = function (arg0) { return addHeapObject(ret); }; -module.exports.__wbg_require_0993fe224bf8e202 = function (arg0, arg1) { - const ret = require(getStringFromWasm0(arg0, arg1)); - return addHeapObject(ret); -}; - module.exports.__wbg_randomFillSync_dd2297de5917c74e = function ( arg0, arg1, @@ -28577,8 +28617,8 @@ module.exports.__wbindgen_memory = function () { return addHeapObject(ret); }; -module.exports.__wbindgen_closure_wrapper7018 = function (arg0, arg1, arg2) { - const ret = makeMutClosure(arg0, arg1, 216, __wbg_adapter_30); +module.exports.__wbindgen_closure_wrapper7021 = function (arg0, arg1, arg2) { + const ret = makeMutClosure(arg0, arg1, 186, __wbg_adapter_30); return addHeapObject(ret); }; diff --git a/dist/esm/src/lucid/lucid.js b/dist/esm/src/lucid/lucid.js index 12b0f831..650f8e74 100644 --- a/dist/esm/src/lucid/lucid.js +++ b/dist/esm/src/lucid/lucid.js @@ -1,5 +1,5 @@ import { C } from "../core/mod.js"; -import { coreToUtxo, createCostModels, fromHex, fromUnit, paymentCredentialOf, toHex, toUnit, Utils, utxoToCore, } from "../utils/mod.js"; +import { coreToUtxo, fromHex, fromUnit, paymentCredentialOf, toHex, toUnit, Utils, utxoToCore, } from "../utils/mod.js"; import { Tx } from "./tx.js"; import { TxComplete } from "./tx_complete.js"; import { discoverOwnUsedTxKeyHashes, walletFromSeed } from "../misc/wallet.js"; @@ -8,6 +8,8 @@ import { Message } from "./message.js"; import { SLOT_CONFIG_NETWORK } from "../plutus/time.js"; import { Data } from "../plutus/data.js"; import { Emulator } from "../provider/emulator.js"; +import { Freeables } from "../utils/freeable.js"; +import { getTransactionBuilderConfig } from "../utils/transaction_builder_config.js"; export class Lucid { constructor() { Object.defineProperty(this, "protocolParameters", { @@ -16,7 +18,7 @@ export class Lucid { writable: true, value: void 0 }); - Object.defineProperty(this, "txBuilderConfig", { + Object.defineProperty(this, "slotConfig", { enumerable: true, configurable: true, writable: true, @@ -65,37 +67,25 @@ export class Lucid { }; } } - if (provider && !protocolParameters) { - const protocolParams = await provider.getProtocolParameters(); - lucid.protocolParameters = protocolParams; - } - if (lucid.protocolParameters) { - const slotConfig = SLOT_CONFIG_NETWORK[lucid.network]; - lucid.txBuilderConfig = C.TransactionBuilderConfigBuilder.new() - .coins_per_utxo_byte(C.BigNum.from_str(lucid.protocolParameters.coinsPerUtxoByte.toString())) - .fee_algo(C.LinearFee.new(C.BigNum.from_str(lucid.protocolParameters.minFeeA.toString()), C.BigNum.from_str(lucid.protocolParameters.minFeeB.toString()))) - .key_deposit(C.BigNum.from_str(lucid.protocolParameters.keyDeposit.toString())) - .pool_deposit(C.BigNum.from_str(lucid.protocolParameters.poolDeposit.toString())) - .max_tx_size(lucid.protocolParameters.maxTxSize) - .max_value_size(lucid.protocolParameters.maxValSize) - .collateral_percentage(lucid.protocolParameters.collateralPercentage) - .max_collateral_inputs(lucid.protocolParameters.maxCollateralInputs) - .max_tx_ex_units(C.ExUnits.new(C.BigNum.from_str(lucid.protocolParameters.maxTxExMem.toString()), C.BigNum.from_str(lucid.protocolParameters.maxTxExSteps.toString()))) - .ex_unit_prices(C.ExUnitPrices.from_float(lucid.protocolParameters.priceMem, lucid.protocolParameters.priceStep)) - .slot_config(C.BigNum.from_str(slotConfig.zeroTime.toString()), C.BigNum.from_str(slotConfig.zeroSlot.toString()), slotConfig.slotLength) - .blockfrost( - // We have Aiken now as native plutus core engine (primary), but we still support blockfrost (secondary) in case of bugs. - C.Blockfrost.new( - // deno-lint-ignore no-explicit-any - (provider?.url || "") + "/utils/txs/evaluate", - // deno-lint-ignore no-explicit-any - provider?.projectId || "")) - .costmdls(createCostModels(lucid.protocolParameters.costModels)) - .build(); + if (provider && !lucid.protocolParameters) { + const protocolParameters = await provider.getProtocolParameters(); + lucid.protocolParameters = protocolParameters; } + lucid.slotConfig = SLOT_CONFIG_NETWORK[lucid.network]; lucid.utils = new Utils(lucid); return lucid; } + getTransactionBuilderConfig() { + if (!this.protocolParameters) { + throw new Error("Protocol parameters or slot config not set. Set a provider or iniatilize with protocol parameters."); + } + return getTransactionBuilderConfig(this.protocolParameters, this.slotConfig, { + // deno-lint-ignore no-explicit-any + url: this.provider?.url, + // deno-lint-ignore no-explicit-any + projectId: this.provider?.projectId, + }); + } /** * Switch provider and/or network. * If provider or network unset, no overwriting happens. Provider or network from current instance are taken then. @@ -104,9 +94,14 @@ export class Lucid { if (this.network === "Custom") { throw new Error("Cannot switch when on custom network."); } - const lucid = await Lucid.new(provider, network); - this.txBuilderConfig = lucid.txBuilderConfig; + const lucid = await Lucid.new({ provider, network }); + this.protocolParameters = lucid.protocolParameters; + this.slotConfig = lucid.slotConfig; this.provider = provider || this.provider; + // Given that protoclParameters and provider are optional we should fetch protocol parameters if they are not set when switiching providers + if (!this.protocolParameters && provider) { + this.protocolParameters = await provider.getProtocolParameters(); + } this.network = network || this.network; this.wallet = lucid.wallet; return this; @@ -181,14 +176,24 @@ export class Lucid { */ selectWalletFromPrivateKey(privateKey) { const priv = C.PrivateKey.from_bech32(privateKey); - const pubKeyHash = priv.to_public().hash(); + const publicKey = priv.to_public(); + priv.free(); + const pubKeyHash = publicKey.hash(); + publicKey.free(); this.wallet = { - // deno-lint-ignore require-await - address: async () => C.EnterpriseAddress.new(this.network === "Mainnet" ? 1 : 0, C.StakeCredential.from_keyhash(pubKeyHash)) - .to_address() - .to_bech32(undefined), - // deno-lint-ignore require-await - rewardAddress: async () => null, + address: () => { + const bucket = []; + const stakeCredential = C.StakeCredential.from_keyhash(pubKeyHash); + bucket.push(stakeCredential); + const enterpriseAddress = C.EnterpriseAddress.new(this.network === "Mainnet" ? 1 : 0, stakeCredential); + bucket.push(enterpriseAddress); + const address = enterpriseAddress.to_address(); + bucket.push(address); + const bech32 = address.to_bech32(undefined); + Freeables.free(...bucket); + return Promise.resolve(bech32); + }, + rewardAddress: () => Promise.resolve(null), getCollateralCore: () => { return undefined; }, @@ -199,30 +204,38 @@ export class Lucid { const utxos = await this.utxosAt(paymentCredentialOf(await this.wallet.address())); const coreUtxos = C.TransactionUnspentOutputs.new(); utxos.forEach((utxo) => { - coreUtxos.add(utxoToCore(utxo)); + const coreUtxo = utxoToCore(utxo); + coreUtxos.add(coreUtxo); + coreUtxo.free(); }); return coreUtxos; }, - // deno-lint-ignore require-await - getDelegation: async () => { - return { poolId: null, rewards: 0n }; + getDelegation: () => { + return Promise.resolve({ poolId: null, rewards: 0n }); }, - // deno-lint-ignore require-await - signTx: async (tx) => { - const witness = C.make_vkey_witness(C.hash_transaction(tx.body()), priv); + signTx: (tx) => { + const bucket = []; + const txBody = tx.body(); + bucket.push(txBody); + const hash = C.hash_transaction(txBody); + bucket.push(hash); + const witness = C.make_vkey_witness(hash, priv); + bucket.push(witness); const txWitnessSetBuilder = C.TransactionWitnessSetBuilder.new(); + bucket.push(txWitnessSetBuilder); txWitnessSetBuilder.add_vkey(witness); - return txWitnessSetBuilder.build(); + const witnessSet = txWitnessSetBuilder.build(); + Freeables.free(...bucket); + return Promise.resolve(witnessSet); }, - // deno-lint-ignore require-await - signMessage: async (address, payload) => { + signMessage: (address, payload) => { const { paymentCredential, address: { hex: hexAddress }, } = this.utils.getAddressDetails(address); const keyHash = paymentCredential?.hash; const originalKeyHash = pubKeyHash.to_hex(); if (!keyHash || keyHash !== originalKeyHash) { throw new Error(`Cannot sign message for address: ${address}.`); } - return signData(hexAddress, payload, privateKey); + return Promise.resolve(signData(hexAddress, payload, privateKey)); }, submitTx: async (tx) => { return await this.provider.submitTx(tx); @@ -239,15 +252,26 @@ export class Lucid { return unusedAddressHex; }; this.wallet = { - address: async () => C.Address.from_bytes(fromHex(await getAddressHex())).to_bech32(undefined), + address: async () => { + const addressHex = await getAddressHex(); + const address = C.Address.from_bytes(fromHex(addressHex)); + const bech32 = address.to_bech32(undefined); + address.free(); + return bech32; + }, rewardAddress: async () => { const [rewardAddressHex] = await api.getRewardAddresses(); - const rewardAddress = rewardAddressHex - ? C.RewardAddress.from_address(C.Address.from_bytes(fromHex(rewardAddressHex))) - .to_address() - .to_bech32(undefined) - : null; - return rewardAddress; + if (rewardAddressHex) { + const address = C.Address.from_bytes(fromHex(rewardAddressHex)); + const rewardAddress = C.RewardAddress.from_address(address); + address.free(); + const addr = rewardAddress.to_address(); + rewardAddress.free(); + const bech32 = addr.to_bech32(undefined); + addr.free(); + return bech32; + } + return null; }, getCollateralCore: () => { return undefined; @@ -255,14 +279,18 @@ export class Lucid { getUtxos: async () => { const utxos = ((await api.getUtxos()) || []).map((utxo) => { const parsedUtxo = C.TransactionUnspentOutput.from_bytes(fromHex(utxo)); - return coreToUtxo(parsedUtxo); + const finalUtxo = coreToUtxo(parsedUtxo); + parsedUtxo.free(); + return finalUtxo; }); return utxos; }, getUtxosCore: async () => { const utxos = C.TransactionUnspentOutputs.new(); ((await api.getUtxos()) || []).forEach((utxo) => { - utxos.add(C.TransactionUnspentOutput.from_bytes(fromHex(utxo))); + const coreUtxo = C.TransactionUnspentOutput.from_bytes(fromHex(utxo)); + utxos.add(coreUtxo); + coreUtxo.free(); }); return utxos; }, @@ -277,7 +305,9 @@ export class Lucid { return C.TransactionWitnessSet.from_bytes(fromHex(witnessSet)); }, signMessage: async (address, payload) => { - const hexAddress = toHex(C.Address.from_bech32(address).to_bytes()); + const cAddress = C.Address.from_bech32(address); + const hexAddress = toHex(cAddress.to_bytes()); + cAddress.free(); return await api.signData(hexAddress, payload); }, submitTx: async (tx) => { @@ -294,23 +324,23 @@ export class Lucid { selectWalletFrom({ address, utxos, rewardAddress, collateral, }) { const addressDetails = this.utils.getAddressDetails(address); this.wallet = { - // deno-lint-ignore require-await - address: async () => address, - // deno-lint-ignore require-await - rewardAddress: async () => { - const rewardAddr = !rewardAddress && addressDetails.stakeCredential - ? (() => { - if (addressDetails.stakeCredential.type === "Key") { - return C.RewardAddress.new(this.network === "Mainnet" ? 1 : 0, C.StakeCredential.from_keyhash(C.Ed25519KeyHash.from_hex(addressDetails.stakeCredential.hash))) - .to_address() - .to_bech32(undefined); - } - return C.RewardAddress.new(this.network === "Mainnet" ? 1 : 0, C.StakeCredential.from_scripthash(C.ScriptHash.from_hex(addressDetails.stakeCredential.hash))) - .to_address() - .to_bech32(undefined); - })() - : rewardAddress; - return rewardAddr || null; + address: () => Promise.resolve(address), + rewardAddress: () => { + if (!rewardAddress && addressDetails.stakeCredential) { + if (addressDetails.stakeCredential.type === "Key") { + const keyHash = C.Ed25519KeyHash.from_hex(addressDetails.stakeCredential.hash); + const stakeCredential = C.StakeCredential.from_keyhash(keyHash); + keyHash.free(); + const rewardAddress = C.RewardAddress.new(this.network === "Mainnet" ? 1 : 0, stakeCredential); + stakeCredential.free(); + const address = rewardAddress.to_address(); + rewardAddress.free(); + const bech32 = address.to_bech32(undefined); + address.free(); + return Promise.resolve(bech32); + } + } + return Promise.resolve(rewardAddress ?? null); }, getCollateralCore: () => { if (!collateral || !collateral.length) { @@ -327,7 +357,11 @@ export class Lucid { const coreUtxos = C.TransactionUnspentOutputs.new(); (utxos ? utxos - : await this.utxosAt(paymentCredentialOf(address))).forEach((utxo) => coreUtxos.add(utxoToCore(utxo))); + : await this.utxosAt(paymentCredentialOf(address))).forEach((utxo) => { + const coreUtxo = utxoToCore(utxo); + coreUtxos.add(coreUtxo); + coreUtxo.free(); + }); return coreUtxos; }, getDelegation: async () => { @@ -336,17 +370,9 @@ export class Lucid { ? await this.delegationAt(rewardAddr) : { poolId: null, rewards: 0n }; }, - // deno-lint-ignore require-await - signTx: async () => { - throw new Error("Not implemented"); - }, - // deno-lint-ignore require-await - signMessage: async () => { - throw new Error("Not implemented"); - }, - submitTx: async (tx) => { - return await this.provider.submitTx(tx); - }, + signTx: () => Promise.reject("Not implemented"), + signMessage: () => Promise.reject("Not implemented"), + submitTx: (tx) => this.provider.submitTx(tx), }; return this; } @@ -355,36 +381,49 @@ export class Lucid { * and Enterprise address (without stake credential). You can also decide which account index to derive. By default account 0 is derived. */ selectWalletFromSeed(seed, options) { + const bucket = []; const { address, rewardAddress, paymentKey, stakeKey } = walletFromSeed(seed, { addressType: options?.addressType || "Base", accountIndex: options?.accountIndex || 0, password: options?.password, network: this.network, }); - const paymentKeyHash = C.PrivateKey.from_bech32(paymentKey) - .to_public() - .hash() - .to_hex(); - const stakeKeyHash = stakeKey - ? C.PrivateKey.from_bech32(stakeKey).to_public().hash().to_hex() - : ""; + const paymentPrivateKey = C.PrivateKey.from_bech32(paymentKey); + bucket.push(paymentPrivateKey); + const paymentPublicKey = paymentPrivateKey.to_public(); + bucket.push(paymentPublicKey); + const paymentPubKeyHash = paymentPublicKey.hash(); + bucket.push(paymentPubKeyHash); + const paymentKeyHash = paymentPubKeyHash.to_hex(); + const getStakeKeyHash = (stakeKey) => { + const stakePrivateKey = C.PrivateKey.from_bech32(stakeKey); + bucket.push(stakePrivateKey); + const stakePublicKey = stakePrivateKey.to_public(); + bucket.push(stakePublicKey); + const stakePubKeyHash = stakePublicKey.hash(); + bucket.push(stakePubKeyHash); + const stakeKeyHash = stakePubKeyHash.to_hex(); + return stakeKeyHash; + }; + const stakeKeyHash = stakeKey ? getStakeKeyHash(stakeKey) : ""; const privKeyHashMap = { [paymentKeyHash]: paymentKey, [stakeKeyHash]: stakeKey, }; this.wallet = { - // deno-lint-ignore require-await - address: async () => address, - // deno-lint-ignore require-await - rewardAddress: async () => rewardAddress || null, + address: () => Promise.resolve(address), + rewardAddress: () => Promise.resolve(rewardAddress || null), + getUtxos: () => this.utxosAt(paymentCredentialOf(address)), getCollateralCore: () => { return undefined; }, - // deno-lint-ignore require-await - getUtxos: async () => this.utxosAt(paymentCredentialOf(address)), getUtxosCore: async () => { const coreUtxos = C.TransactionUnspentOutputs.new(); - (await this.utxosAt(paymentCredentialOf(address))).forEach((utxo) => coreUtxos.add(utxoToCore(utxo))); + (await this.utxosAt(paymentCredentialOf(address))).forEach((utxo) => { + const coreUtxo = utxoToCore(utxo); + coreUtxos.add(coreUtxo); + coreUtxo.free(); + }); return coreUtxos; }, getDelegation: async () => { @@ -399,25 +438,34 @@ export class Lucid { const usedKeyHashes = discoverOwnUsedTxKeyHashes(tx, ownKeyHashes, utxos); const txWitnessSetBuilder = C.TransactionWitnessSetBuilder.new(); usedKeyHashes.forEach((keyHash) => { - const witness = C.make_vkey_witness(C.hash_transaction(tx.body()), C.PrivateKey.from_bech32(privKeyHashMap[keyHash])); + const txBody = tx.body(); + const hash = C.hash_transaction(txBody); + txBody.free(); + const privateKey = C.PrivateKey.from_bech32(privKeyHashMap[keyHash]); + const witness = C.make_vkey_witness(hash, privateKey); + hash.free(); + privateKey.free(); txWitnessSetBuilder.add_vkey(witness); + witness.free(); }); - return txWitnessSetBuilder.build(); + const txWitnessSet = txWitnessSetBuilder.build(); + txWitnessSetBuilder.free(); + return txWitnessSet; }, - // deno-lint-ignore require-await - signMessage: async (address, payload) => { + signMessage: (address, payload) => { const { paymentCredential, stakeCredential, address: { hex: hexAddress }, } = this.utils.getAddressDetails(address); const keyHash = paymentCredential?.hash || stakeCredential?.hash; const privateKey = privKeyHashMap[keyHash]; if (!privateKey) { throw new Error(`Cannot sign message for address: ${address}.`); } - return signData(hexAddress, payload, privateKey); + return Promise.resolve(signData(hexAddress, payload, privateKey)); }, submitTx: async (tx) => { return await this.provider.submitTx(tx); }, }; + Freeables.free(...bucket); return this; } } diff --git a/dist/esm/src/lucid/message.js b/dist/esm/src/lucid/message.js index efbf0e5b..c605e013 100644 --- a/dist/esm/src/lucid/message.js +++ b/dist/esm/src/lucid/message.js @@ -1,5 +1,6 @@ import { signData } from "../misc/sign_data.js"; import { C } from "../mod.js"; +import { Freeables } from "../utils/freeable.js"; export class Message { constructor(lucid, address, payload) { Object.defineProperty(this, "lucid", { @@ -30,13 +31,24 @@ export class Message { } /** Sign message with a separate private key. */ signWithPrivateKey(privateKey) { - const { paymentCredential, stakeCredential, address: { hex: hexAddress } } = this.lucid.utils.getAddressDetails(this.address); - const keyHash = paymentCredential?.hash || stakeCredential?.hash; - const keyHashOriginal = C.PrivateKey.from_bech32(privateKey).to_public() - .hash().to_hex(); - if (!keyHash || keyHash !== keyHashOriginal) { - throw new Error(`Cannot sign message for address: ${this.address}.`); + const bucket = []; + try { + const { paymentCredential, stakeCredential, address: { hex: hexAddress }, } = this.lucid.utils.getAddressDetails(this.address); + const keyHash = paymentCredential?.hash || stakeCredential?.hash; + const skey = C.PrivateKey.from_bech32(privateKey); + bucket.push(skey); + const vkey = skey.to_public(); + bucket.push(vkey); + const hash = vkey.hash(); + bucket.push(hash); + const keyHashOriginal = hash.to_hex(); + if (!keyHash || keyHash !== keyHashOriginal) { + throw new Error(`Cannot sign message for address: ${this.address}.`); + } + return signData(hexAddress, this.payload, privateKey); + } + finally { + Freeables.free(...bucket); } - return signData(hexAddress, this.payload, privateKey); } } diff --git a/dist/esm/src/lucid/tx.js b/dist/esm/src/lucid/tx.js index a5943896..379ccdaa 100644 --- a/dist/esm/src/lucid/tx.js +++ b/dist/esm/src/lucid/tx.js @@ -1,7 +1,8 @@ import { C } from "../core/mod.js"; -import { Data } from "../mod.js"; -import { assetsToValue, fromHex, networkToId, toHex, toScriptRef, utxoToCore, valueToAssets, chunk, } from "../utils/mod.js"; -import { applyDoubleCborEncoding } from "../utils/utils.js"; +import { Data, PROTOCOL_PARAMETERS_DEFAULT } from "../mod.js"; +import { addressFromWithNetworkCheck, attachScript, createPoolRegistration, getDatumFromOutputData, getScriptWitness, getStakeCredential, } from "../utils/cml.js"; +import { Freeables } from "../utils/freeable.js"; +import { assetsToValue, fromHex, toHex, utxoToCore, valueToAssets, chunk, createOutput, } from "../utils/mod.js"; import { defaultConfig } from "./tx_config.js"; import { TxComplete } from "./tx_complete.js"; export class Tx { @@ -32,21 +33,29 @@ export class Tx { value: defaultConfig }); this.lucid = lucid; - this.txBuilder = C.TransactionBuilder.new(this.lucid.txBuilderConfig); + this.txBuilder = C.TransactionBuilder.new(lucid.getTransactionBuilderConfig()); this.tasks = []; } /** Read data from utxos. These utxos are only referenced and not spent. */ readFrom(utxos) { this.tasks.push(async (that) => { - for (const utxo of utxos) { - if (utxo.datumHash) { - utxo.datum = Data.to(await that.lucid.datumOf(utxo)); - // Add datum to witness set, so it can be read from validators - const plutusData = C.PlutusData.from_bytes(fromHex(utxo.datum)); - that.txBuilder.add_plutus_data(plutusData); + const bucket = []; + try { + for (const utxo of utxos) { + if (utxo.datumHash) { + utxo.datum = Data.to(await that.lucid.datumOf(utxo)); + // Add datum to witness set, so it can be read from validators + const plutusData = C.PlutusData.from_bytes(fromHex(utxo.datum)); + bucket.push(plutusData); + that.txBuilder.add_plutus_data(plutusData); + } + const coreUtxo = utxoToCore(utxo); + bucket.push(coreUtxo); + that.txBuilder.add_reference_input(coreUtxo); } - const coreUtxo = utxoToCore(utxo); - that.txBuilder.add_reference_input(coreUtxo); + } + finally { + Freeables.free(...bucket); } }); return this; @@ -64,15 +73,23 @@ export class Tx { */ collectFrom(utxos, redeemer) { this.tasks.push(async (that) => { - for (const utxo of utxos) { - if (utxo.datumHash && !utxo.datum) { - utxo.datum = Data.to(await that.lucid.datumOf(utxo)); + const bucket = []; + try { + for (const utxo of utxos) { + if (utxo.datumHash && !utxo.datum) { + utxo.datum = Data.to(await that.lucid.datumOf(utxo)); + } + const coreUtxo = utxoToCore(utxo); + bucket.push(coreUtxo); + // We don't free Options as the ownership is passed to the txBuilder + const scriptWitness = redeemer + ? getScriptWitness(redeemer, utxo.datumHash && utxo.datum ? utxo.datum : undefined) + : undefined; + that.txBuilder.add_input(coreUtxo, scriptWitness); } - const coreUtxo = utxoToCore(utxo); - that.txBuilder.add_input(coreUtxo, redeemer && - C.ScriptWitness.new_plutus_witness(C.PlutusWitness.new(C.PlutusData.from_bytes(fromHex(redeemer)), utxo.datumHash && utxo.datum - ? C.PlutusData.from_bytes(fromHex(utxo.datum)) - : undefined, undefined))); + } + finally { + Freeables.free(...bucket); } }); return this; @@ -84,68 +101,86 @@ export class Tx { */ mintAssets(assets, redeemer) { this.tasks.push((that) => { - const units = Object.keys(assets); - const policyId = units[0].slice(0, 56); - const mintAssets = C.MintAssets.new(); - units.forEach((unit) => { - if (unit.slice(0, 56) !== policyId) { - throw new Error("Only one policy id allowed. You can chain multiple mintAssets functions together if you need to mint assets with different policy ids."); - } - mintAssets.insert(C.AssetName.new(fromHex(unit.slice(56))), C.Int.from_str(assets[unit].toString())); - }); - const scriptHash = C.ScriptHash.from_bytes(fromHex(policyId)); - that.txBuilder.add_mint(scriptHash, mintAssets, redeemer - ? C.ScriptWitness.new_plutus_witness(C.PlutusWitness.new(C.PlutusData.from_bytes(fromHex(redeemer)), undefined, undefined)) - : undefined); + const bucket = []; + try { + const units = Object.keys(assets); + const policyId = units[0].slice(0, 56); + const mintAssets = C.MintAssets.new(); + bucket.push(mintAssets); + units.forEach((unit) => { + if (unit.slice(0, 56) !== policyId) { + throw new Error("Only one policy id allowed. You can chain multiple mintAssets functions together if you need to mint assets with different policy ids."); + } + const assetName = C.AssetName.new(fromHex(unit.slice(56))); + const int = C.Int.from_str(assets[unit].toString()); + // Int is being passed by value so we don't need to free it + bucket.push(assetName); + mintAssets.insert(assetName, int); + }); + const scriptHash = C.ScriptHash.from_bytes(fromHex(policyId)); + // We don't free Options as the ownership is passed to the txBuilder + const scriptWitness = redeemer ? getScriptWitness(redeemer) : undefined; + bucket.push(scriptHash); + that.txBuilder.add_mint(scriptHash, mintAssets, scriptWitness); + } + finally { + Freeables.free(...bucket); + } }); return this; } /** Pay to a public key or native script address. */ payToAddress(address, assets) { this.tasks.push((that) => { - let output = C.TransactionOutput.new(addressFromWithNetworkCheck(address, that.lucid), assetsToValue(assets)); + const addr = addressFromWithNetworkCheck(address, that.lucid); + const value = assetsToValue(assets); + const output = C.TransactionOutput.new(addr, value); const minAda = that.lucid.utils.getMinAdaForOutput(output); assets.lovelace = assets.lovelace > minAda ? assets.lovelace : minAda; - output = C.TransactionOutput.new(addressFromWithNetworkCheck(address, that.lucid), assetsToValue(assets)); - that.txBuilder.add_output(output); + const valueWithMinAda = assetsToValue(assets); + const outputWithMinAda = C.TransactionOutput.new(addr, valueWithMinAda); + that.txBuilder.add_output(outputWithMinAda); + Freeables.free(output, addr, value, valueWithMinAda, outputWithMinAda); }); return this; } /** Pay to a public key or native script address with datum or scriptRef. */ payToAddressWithData(address, outputData, assets) { this.tasks.push((that) => { - if (typeof outputData === "string") { - outputData = { asHash: outputData }; - } - if ([outputData.hash, outputData.asHash, outputData.inline].filter((b) => b) - .length > 1) { - throw new Error("Not allowed to set hash, asHash and inline at the same time."); - } - const createOutput = (_assets, _outputData) => { - const output = C.TransactionOutput.new(addressFromWithNetworkCheck(address, that.lucid), assetsToValue(_assets)); - if (_outputData.hash) { - output.set_datum(C.Datum.new_data_hash(C.DataHash.from_hex(_outputData.hash))); - } - else if (_outputData.asHash) { - const plutusData = C.PlutusData.from_bytes(fromHex(_outputData.asHash)); - output.set_datum(C.Datum.new_data_hash(C.hash_plutus_data(plutusData))); - that.txBuilder.add_plutus_data(plutusData); - } - else if (_outputData.inline) { - const plutusData = C.PlutusData.from_bytes(fromHex(_outputData.inline)); - output.set_datum(C.Datum.new_data(C.Data.new(plutusData))); + const bucket = []; + try { + if (typeof outputData === "string") { + outputData = { asHash: outputData }; } - const script = _outputData.scriptRef; - if (script) { - output.set_script_ref(toScriptRef(script)); + if ([outputData.hash, outputData.asHash, outputData.inline].filter((b) => b).length > 1) { + throw new Error("Not allowed to set hash, asHash and inline at the same time."); } - return output; - }; - let output = createOutput(assets, outputData); - const minAda = this.lucid.utils.getMinAdaForOutput(output); - assets.lovelace = assets.lovelace > minAda ? assets.lovelace : minAda; - output = createOutput(assets, outputData); - that.txBuilder.add_output(output); + const output = createOutput({ + bucket, + txBuilder: that.txBuilder, + lucid: that.lucid, + address, + outputData, + assets, + }); + const minAda = this.lucid.utils.getMinAdaForOutput(output); + const assetsWithMinAda = { ...assets }; + assetsWithMinAda.lovelace = + assets.lovelace > minAda ? assets.lovelace : minAda; + const outputWithMinAda = createOutput({ + bucket, + txBuilder: that.txBuilder, + lucid: that.lucid, + address, + outputData, + assets: assetsWithMinAda, + }); + bucket.push(output, outputWithMinAda); + that.txBuilder.add_output(outputWithMinAda); + } + finally { + Freeables.free(...bucket); + } }); return this; } @@ -166,12 +201,14 @@ export class Tx { if (addressDetails.type !== "Reward" || !addressDetails.stakeCredential) { throw new Error("Not a reward address provided."); } - const credential = addressDetails.stakeCredential.type === "Key" - ? C.StakeCredential.from_keyhash(C.Ed25519KeyHash.from_bytes(fromHex(addressDetails.stakeCredential.hash))) - : C.StakeCredential.from_scripthash(C.ScriptHash.from_bytes(fromHex(addressDetails.stakeCredential.hash))); - that.txBuilder.add_certificate(C.Certificate.new_stake_delegation(C.StakeDelegation.new(credential, C.Ed25519KeyHash.from_bech32(poolId))), redeemer - ? C.ScriptWitness.new_plutus_witness(C.PlutusWitness.new(C.PlutusData.from_bytes(fromHex(redeemer)), undefined, undefined)) - : undefined); + const credential = getStakeCredential(addressDetails.stakeCredential.hash, addressDetails.stakeCredential.type); + const keyHash = C.Ed25519KeyHash.from_bech32(poolId); + const delegation = C.StakeDelegation.new(credential, keyHash); + // We don't free Options as the ownership is passed to the txBuilder + const scriptWitness = redeemer ? getScriptWitness(redeemer) : undefined; + const certificate = C.Certificate.new_stake_delegation(delegation); + that.txBuilder.add_certificate(certificate, scriptWitness); + Freeables.free(keyHash, delegation, credential, certificate); }); return this; } @@ -182,10 +219,11 @@ export class Tx { if (addressDetails.type !== "Reward" || !addressDetails.stakeCredential) { throw new Error("Not a reward address provided."); } - const credential = addressDetails.stakeCredential.type === "Key" - ? C.StakeCredential.from_keyhash(C.Ed25519KeyHash.from_bytes(fromHex(addressDetails.stakeCredential.hash))) - : C.StakeCredential.from_scripthash(C.ScriptHash.from_bytes(fromHex(addressDetails.stakeCredential.hash))); - that.txBuilder.add_certificate(C.Certificate.new_stake_registration(C.StakeRegistration.new(credential)), undefined); + const credential = getStakeCredential(addressDetails.stakeCredential.hash, addressDetails.stakeCredential.type); + const stakeRegistration = C.StakeRegistration.new(credential); + const certificate = C.Certificate.new_stake_registration(stakeRegistration); + that.txBuilder.add_certificate(certificate, undefined); + Freeables.free(credential, stakeRegistration, certificate); }); return this; } @@ -196,12 +234,13 @@ export class Tx { if (addressDetails.type !== "Reward" || !addressDetails.stakeCredential) { throw new Error("Not a reward address provided."); } - const credential = addressDetails.stakeCredential.type === "Key" - ? C.StakeCredential.from_keyhash(C.Ed25519KeyHash.from_bytes(fromHex(addressDetails.stakeCredential.hash))) - : C.StakeCredential.from_scripthash(C.ScriptHash.from_bytes(fromHex(addressDetails.stakeCredential.hash))); - that.txBuilder.add_certificate(C.Certificate.new_stake_deregistration(C.StakeDeregistration.new(credential)), redeemer - ? C.ScriptWitness.new_plutus_witness(C.PlutusWitness.new(C.PlutusData.from_bytes(fromHex(redeemer)), undefined, undefined)) - : undefined); + const credential = getStakeCredential(addressDetails.stakeCredential.hash, addressDetails.stakeCredential.type); + const stakeDeregistration = C.StakeDeregistration.new(credential); + const certificate = C.Certificate.new_stake_deregistration(stakeDeregistration); + // We don't free Options as the ownership is passed to the txBuilder + const scriptWitness = redeemer ? getScriptWitness(redeemer) : undefined; + that.txBuilder.add_certificate(certificate, scriptWitness); + Freeables.free(credential, stakeDeregistration, certificate); }); return this; } @@ -211,6 +250,7 @@ export class Tx { const poolRegistration = await createPoolRegistration(poolParams, that.lucid); const certificate = C.Certificate.new_pool_registration(poolRegistration); that.txBuilder.add_certificate(certificate, undefined); + Freeables.free(certificate, poolRegistration); }); return this; } @@ -221,6 +261,7 @@ export class Tx { // This flag makes sure a pool deposit is not required poolRegistration.set_is_update(true); const certificate = C.Certificate.new_pool_registration(poolRegistration); + Freeables.free(poolRegistration, certificate); that.txBuilder.add_certificate(certificate, undefined); }); return this; @@ -231,16 +272,22 @@ export class Tx { */ retirePool(poolId, epoch) { this.tasks.push((that) => { - const certificate = C.Certificate.new_pool_retirement(C.PoolRetirement.new(C.Ed25519KeyHash.from_bech32(poolId), epoch)); + const keyHash = C.Ed25519KeyHash.from_bech32(poolId); + const poolRetirement = C.PoolRetirement.new(keyHash, epoch); + const certificate = C.Certificate.new_pool_retirement(poolRetirement); that.txBuilder.add_certificate(certificate, undefined); + Freeables.free(keyHash, poolRetirement, certificate); }); return this; } withdraw(rewardAddress, amount, redeemer) { this.tasks.push((that) => { - that.txBuilder.add_withdrawal(C.RewardAddress.from_address(addressFromWithNetworkCheck(rewardAddress, that.lucid)), C.BigNum.from_str(amount.toString()), redeemer - ? C.ScriptWitness.new_plutus_witness(C.PlutusWitness.new(C.PlutusData.from_bytes(fromHex(redeemer)), undefined, undefined)) - : undefined); + const addr = addressFromWithNetworkCheck(rewardAddress, that.lucid); + const rewardAddr = C.RewardAddress.from_address(addr); + const amountBigNum = C.BigNum.from_str(amount.toString()); + const scriptWitness = redeemer ? getScriptWitness(redeemer) : undefined; + that.txBuilder.add_withdrawal(rewardAddr, amountBigNum, scriptWitness); + Freeables.free(addr, rewardAddr, amountBigNum, scriptWitness); }); return this; } @@ -265,41 +312,53 @@ export class Tx { /** Add a payment or stake key hash as a required signer of the transaction. */ addSignerKey(keyHash) { this.tasks.push((that) => { - that.txBuilder.add_required_signer(C.Ed25519KeyHash.from_bytes(fromHex(keyHash))); + const key = C.Ed25519KeyHash.from_bytes(fromHex(keyHash)); + that.txBuilder.add_required_signer(key); + Freeables.free(key); }); return this; } validFrom(unixTime) { this.tasks.push((that) => { const slot = that.lucid.utils.unixTimeToSlot(unixTime); - that.txBuilder.set_validity_start_interval(C.BigNum.from_str(slot.toString())); + const slotNum = C.BigNum.from_str(slot.toString()); + that.txBuilder.set_validity_start_interval(slotNum); + Freeables.free(slotNum); }); return this; } validTo(unixTime) { this.tasks.push((that) => { const slot = that.lucid.utils.unixTimeToSlot(unixTime); - that.txBuilder.set_ttl(C.BigNum.from_str(slot.toString())); + const slotNum = C.BigNum.from_str(slot.toString()); + that.txBuilder.set_ttl(slotNum); + Freeables.free(slotNum); }); return this; } attachMetadata(label, metadata) { this.tasks.push((that) => { - that.txBuilder.add_json_metadatum(C.BigNum.from_str(label.toString()), JSON.stringify(metadata)); + const labelNum = C.BigNum.from_str(label.toString()); + that.txBuilder.add_json_metadatum(labelNum, JSON.stringify(metadata)); + Freeables.free(labelNum); }); return this; } /** Converts strings to bytes if prefixed with **'0x'**. */ attachMetadataWithConversion(label, metadata) { this.tasks.push((that) => { - that.txBuilder.add_json_metadatum_with_schema(C.BigNum.from_str(label.toString()), JSON.stringify(metadata), C.MetadataJsonSchema.BasicConversions); + const labelNum = C.BigNum.from_str(label.toString()); + that.txBuilder.add_json_metadatum_with_schema(labelNum, JSON.stringify(metadata), C.MetadataJsonSchema.BasicConversions); + Freeables.free(labelNum); }); return this; } /** Explicitely set the network id in the transaction body. */ addNetworkId(id) { this.tasks.push((that) => { - that.txBuilder.set_network_id(C.NetworkId.from_bytes(fromHex(id.toString(16).padStart(2, "0")))); + const networkId = C.NetworkId.from_bytes(fromHex(id.toString(16).padStart(2, "0"))); + that.txBuilder.set_network_id(networkId); + Freeables.free(networkId); }); return this; } @@ -344,52 +403,58 @@ export class Tx { this.tasks = this.tasks.concat(tx.tasks); return this; } + free() { + this.txBuilder.free(); + } + /** Completes the transaction. This might fail, you should free the txBuilder when you are done with it. */ async complete(options) { + const bucket = []; const { enableChangeSplitting } = this.configuration; - if ([ - options?.change?.outputData?.hash, - options?.change?.outputData?.asHash, - options?.change?.outputData?.inline, - ].filter((b) => b).length > 1) { - throw new Error("Not allowed to set hash, asHash and inline at the same time."); - } - let task = this.tasks.shift(); - while (task) { - await task(this); - task = this.tasks.shift(); - } - const utxos = await this.lucid.wallet.getUtxosCore(); - const collateral = await this.lucid.wallet.getCollateralCore(); - const changeAddress = addressFromWithNetworkCheck(options?.change?.address || (await this.lucid.wallet.address()), this.lucid); - if (options?.coinSelection || options?.coinSelection === undefined) { - this.txBuilder.add_inputs_from(utxos, changeAddress, Uint32Array.from([ - 200, - 1000, - 1500, - 800, - 800, - 5000, // weight utxos - ])); - } - if (enableChangeSplitting) { - await this.splitChange(); - } - this.txBuilder.balance(changeAddress, (() => { - if (options?.change?.outputData?.hash) { - return C.Datum.new_data_hash(C.DataHash.from_hex(options.change.outputData.hash)); + try { + if ([ + options?.change?.outputData?.hash, + options?.change?.outputData?.asHash, + options?.change?.outputData?.inline, + ].filter((b) => b).length > 1) { + throw new Error("Not allowed to set hash, asHash and inline at the same time."); } - else if (options?.change?.outputData?.asHash) { - this.txBuilder.add_plutus_data(C.PlutusData.from_bytes(fromHex(options.change.outputData.asHash))); - return C.Datum.new_data_hash(C.hash_plutus_data(C.PlutusData.from_bytes(fromHex(options.change.outputData.asHash)))); + let task = this.tasks.shift(); + while (task) { + await task(this); + task = this.tasks.shift(); } - else if (options?.change?.outputData?.inline) { - return C.Datum.new_data(C.Data.new(C.PlutusData.from_bytes(fromHex(options.change.outputData.inline)))); + // We don't free `utxos` as it is passed as an Option to the txBuilder and the ownership is passed when passing an Option + const utxos = await this.lucid.wallet.getUtxosCore(); + const collateral = this.lucid.wallet.getCollateralCore(); + // We don't free `changeAddress` as it is passed as an Option to the txBuilder and the ownership is passed when passing an Option + const changeAddress = addressFromWithNetworkCheck(options?.change?.address || (await this.lucid.wallet.address()), this.lucid); + if (options?.coinSelection || options?.coinSelection === undefined) { + this.txBuilder.add_inputs_from_impl(utxos, changeAddress, + // Uint32Array.from([ + // 200, // weight ideal > 100 inputs + // 1000, // weight ideal < 100 inputs + // 1500, // weight assets if plutus + // 800, // weight assets if not plutus + // 800, // weight distance if not plutus + // 5000, // weight utxos + // ]), + "200,1000,1500,800,800,5000"); } - else { - return undefined; + const { datum, plutusData } = getDatumFromOutputData(options?.change?.outputData); + if (plutusData) { + this.txBuilder.add_plutus_data(plutusData); } - })()); - return new TxComplete(this.lucid, await this.txBuilder.construct(collateral || utxos, changeAddress, options?.nativeUplc === undefined ? true : options?.nativeUplc)); + bucket.push(datum, plutusData); + if (enableChangeSplitting) { + await this.splitChange(); + } + this.txBuilder.balance(changeAddress, datum); + const tx = await this.txBuilder.construct(collateral || utxos, changeAddress, options?.nativeUplc === undefined ? true : options?.nativeUplc); + return new TxComplete(this.lucid, tx); + } + finally { + Freeables.free(...bucket); + } } /** Return the current transaction body in Hex encoded Cbor. */ async toString() { @@ -416,13 +481,16 @@ export class Tx { * This is the advanced UTxO management algorithm used by Eternl */ async splitChange() { - const { coinsPerUtxoByte } = await this.lucid.protocolParameters; + const bucket = []; + const { coinsPerUtxoByte } = this.lucid.protocolParameters || PROTOCOL_PARAMETERS_DEFAULT; const { changeNativeAssetChunkSize, changeMinUtxo } = this.configuration; - const change = this.txBuilder - .get_explicit_input() - .checked_sub(this.txBuilder.get_explicit_output()); + const txInputs = this.txBuilder.get_explicit_input(); + const txOutputs = this.txBuilder.get_explicit_output(); + bucket.push(txInputs, txOutputs); + const change = txInputs.checked_sub(txOutputs); let changeAda = change.coin(); let changeAssets = valueToAssets(change); + bucket.push(changeAda); const changeAssetsArray = Object.keys(changeAssets) .filter((v) => v !== "lovelace") // Sort canonically so we group policy IDs together @@ -430,22 +498,33 @@ export class Tx { changeAssets = changeAssetsArray.reduce((res, key) => Object.assign(res, { [key]: changeAssets[key] }), {}); const numOutputsWithNativeAssets = Math.ceil(changeAssetsArray.length / changeNativeAssetChunkSize); let longestAddress = C.Address.from_bech32(await this.lucid.wallet.address()); + bucket.push(longestAddress); const outputs = this.txBuilder.outputs(); + bucket.push(outputs); for (let i = 0; i < outputs.len(); i++) { const output = outputs.get(i); + bucket.push(output); + const outputAddress = output.address(); if (!longestAddress || - output.address().to_bech32(undefined).length > + outputAddress.to_bech32(undefined).length > longestAddress.to_bech32(undefined).length) { longestAddress = output.address(); } } - const minAdaPerOutput = C.min_ada_required(C.TransactionOutput.new(longestAddress, assetsToValue(changeAssets)), C.BigNum.from_str(coinsPerUtxoByte.toString())); + const txOutputValue = assetsToValue(changeAssets); + const transactionOutput = C.TransactionOutput.new(longestAddress, txOutputValue); + const coinUtxoByte = C.BigNum.from_str(coinsPerUtxoByte.toString()); + const minAdaPerOutput = C.min_ada_required(transactionOutput, coinUtxoByte); + bucket.push(txOutputValue, transactionOutput, coinUtxoByte, minAdaPerOutput); // Do we have enough ADA in the change to split and still // statisfy minADA requirements? - const shouldSplitChange = minAdaPerOutput - .checked_mul(C.BigNum.from_str(numOutputsWithNativeAssets.toString())) - .compare(changeAda) < 0; - if (change.multiasset() && shouldSplitChange) { + const numOutputsWithAssets = C.BigNum.from_str(numOutputsWithNativeAssets.toString()); + const changeAmount = minAdaPerOutput.checked_mul(numOutputsWithAssets); + bucket.push(numOutputsWithAssets, changeAmount); + const shouldSplitChange = changeAmount.compare(changeAda) < 0; + const changeMultiAsset = change.multiasset(); + bucket.push(changeMultiAsset); + if (changeMultiAsset && shouldSplitChange) { const assetChunks = chunk(changeAssetsArray, 20); const totalChunks = assetChunks.length; for (const [idx, piece] of assetChunks.entries()) { @@ -454,86 +533,33 @@ export class Tx { continue; } const val = assetsToValue(piece.reduce((res, key) => Object.assign(res, { [key]: changeAssets[key] }), {})); - const minAda = C.min_ada_required(C.TransactionOutput.new(C.Address.from_bech32(await this.lucid.wallet.address()), val), C.BigNum.from_str(coinsPerUtxoByte.toString())); - const coin = minAda; - val.set_coin(coin); - changeAda = changeAda.checked_sub(coin); - this.txBuilder.add_output(C.TransactionOutput.new(C.Address.from_bech32(await this.lucid.wallet.address()), val)); + bucket.push(val); + const changeAddress = C.Address.from_bech32(await this.lucid.wallet.address()); + const minAdaTxOutput = C.TransactionOutput.new(changeAddress, val); + const coinUtxoByte = C.BigNum.from_str(coinsPerUtxoByte.toString()); + const minAda = C.min_ada_required(minAdaTxOutput, coinUtxoByte); + val.set_coin(minAda); + changeAda = changeAda.checked_sub(minAda); + const txOutputWithMinAda = C.TransactionOutput.new(changeAddress, val); + bucket.push(changeAda, minAdaTxOutput); + this.txBuilder.add_output(txOutputWithMinAda); } } + const two = C.BigNum.from_str("2"); + const changeMinUtxoBigNum = C.BigNum.from_str(changeMinUtxo); + let split = changeAda.checked_div(two); + bucket.push(two, changeMinUtxoBigNum, split); while ( // If the half is more than the minimum, we can split it - changeAda - .checked_div(C.BigNum.from_str("2")) - .compare(C.BigNum.from_str(changeMinUtxo)) >= 0) { - const half = changeAda.checked_div(C.BigNum.from_str("2")); + split.compare(changeMinUtxoBigNum) >= 0) { + const half = changeAda.checked_div(two); changeAda = changeAda.checked_sub(half); - this.txBuilder.add_output(C.TransactionOutput.new(C.Address.from_bech32(await this.lucid.wallet.address()), C.Value.new(half))); + split = changeAda.checked_div(two); + const changeAddress = C.Address.from_bech32(await this.lucid.wallet.address()); + const halfValue = C.Value.new(half); + const changeOutput = C.TransactionOutput.new(changeAddress, halfValue); + bucket.push(half, changeAda, split, changeAddress, halfValue, changeOutput); + this.txBuilder.add_output(changeOutput); } } } -function attachScript(tx, { type, script, }) { - if (type === "Native") { - return tx.txBuilder.add_native_script(C.NativeScript.from_bytes(fromHex(script))); - } - else if (type === "PlutusV1") { - return tx.txBuilder.add_plutus_script(C.PlutusScript.from_bytes(fromHex(applyDoubleCborEncoding(script)))); - } - else if (type === "PlutusV2") { - return tx.txBuilder.add_plutus_v2_script(C.PlutusScript.from_bytes(fromHex(applyDoubleCborEncoding(script)))); - } - throw new Error("No variant matched."); -} -async function createPoolRegistration(poolParams, lucid) { - const poolOwners = C.Ed25519KeyHashes.new(); - poolParams.owners.forEach((owner) => { - const { stakeCredential } = lucid.utils.getAddressDetails(owner); - if (stakeCredential?.type === "Key") { - poolOwners.add(C.Ed25519KeyHash.from_hex(stakeCredential.hash)); - } - else - throw new Error("Only key hashes allowed for pool owners."); - }); - const metadata = poolParams.metadataUrl - ? await fetch(poolParams.metadataUrl).then((res) => res.arrayBuffer()) - : null; - const metadataHash = metadata - ? C.PoolMetadataHash.from_bytes(C.hash_blake2b256(new Uint8Array(metadata))) - : null; - const relays = C.Relays.new(); - poolParams.relays.forEach((relay) => { - switch (relay.type) { - case "SingleHostIp": { - const ipV4 = relay.ipV4 - ? C.Ipv4.new(new Uint8Array(relay.ipV4.split(".").map((b) => parseInt(b)))) - : undefined; - const ipV6 = relay.ipV6 - ? C.Ipv6.new(fromHex(relay.ipV6.replaceAll(":", ""))) - : undefined; - relays.add(C.Relay.new_single_host_addr(C.SingleHostAddr.new(relay.port, ipV4, ipV6))); - break; - } - case "SingleHostDomainName": { - relays.add(C.Relay.new_single_host_name(C.SingleHostName.new(relay.port, C.DNSRecordAorAAAA.new(relay.domainName)))); - break; - } - case "MultiHost": { - relays.add(C.Relay.new_multi_host_name(C.MultiHostName.new(C.DNSRecordSRV.new(relay.domainName)))); - break; - } - } - }); - return C.PoolRegistration.new(C.PoolParams.new(C.Ed25519KeyHash.from_bech32(poolParams.poolId), C.VRFKeyHash.from_hex(poolParams.vrfKeyHash), C.BigNum.from_str(poolParams.pledge.toString()), C.BigNum.from_str(poolParams.cost.toString()), C.UnitInterval.from_float(poolParams.margin), C.RewardAddress.from_address(addressFromWithNetworkCheck(poolParams.rewardAddress, lucid)), poolOwners, relays, metadataHash - ? C.PoolMetadata.new(C.Url.new(poolParams.metadataUrl), metadataHash) - : undefined)); -} -function addressFromWithNetworkCheck(address, lucid) { - const { type, networkId } = lucid.utils.getAddressDetails(address); - const actualNetworkId = networkToId(lucid.network); - if (networkId !== actualNetworkId) { - throw new Error(`Invalid address: Expected address with network id ${actualNetworkId}, but got ${networkId}`); - } - return type === "Byron" - ? C.ByronAddress.from_base58(address).to_address() - : C.Address.from_bech32(address); -} diff --git a/dist/esm/src/lucid/tx_complete.js b/dist/esm/src/lucid/tx_complete.js index 9643083f..e8bfe773 100644 --- a/dist/esm/src/lucid/tx_complete.js +++ b/dist/esm/src/lucid/tx_complete.js @@ -1,6 +1,7 @@ import { C } from "../core/mod.js"; import { TxSigned } from "./tx_signed.js"; import { fromHex, toHex } from "../utils/mod.js"; +import { Freeables } from "../utils/freeable.js"; export class TxComplete { constructor(lucid, tx) { Object.defineProperty(this, "txComplete", { @@ -39,59 +40,99 @@ export class TxComplete { writable: true, value: null }); + const bucket = []; this.lucid = lucid; this.txComplete = tx; this.witnessSetBuilder = C.TransactionWitnessSetBuilder.new(); this.tasks = []; - this.fee = parseInt(tx.body().fee().to_str()); - const redeemers = tx.witness_set().redeemers(); + const body = tx.body(); + bucket.push(body); + const fee = body.fee(); + bucket.push(fee); + const witnessSet = tx.witness_set(); + bucket.push(witnessSet); + this.fee = parseInt(fee.to_str()); + const redeemers = witnessSet.redeemers(); + bucket.push(redeemers); if (redeemers) { const exUnits = { cpu: 0, mem: 0 }; for (let i = 0; i < redeemers.len(); i++) { const redeemer = redeemers.get(i); - exUnits.cpu += parseInt(redeemer.ex_units().steps().to_str()); - exUnits.mem += parseInt(redeemer.ex_units().mem().to_str()); + bucket.push(redeemer); + const cExUnits = redeemer.ex_units(); + bucket.push(cExUnits); + const steps = cExUnits.steps(); + bucket.push(steps); + const mem = cExUnits.mem(); + bucket.push(mem); + exUnits.cpu += parseInt(steps.to_str()); + exUnits.mem += parseInt(mem.to_str()); } this.exUnits = exUnits; } + Freeables.free(...bucket); } sign() { this.tasks.push(async () => { const witnesses = await this.lucid.wallet.signTx(this.txComplete); this.witnessSetBuilder.add_existing(witnesses); + witnesses.free(); }); return this; } /** Add an extra signature from a private key. */ signWithPrivateKey(privateKey) { + const bucket = []; const priv = C.PrivateKey.from_bech32(privateKey); - const witness = C.make_vkey_witness(C.hash_transaction(this.txComplete.body()), priv); + bucket.push(priv); + const body = this.txComplete.body(); + bucket.push(body); + const hash = C.hash_transaction(body); + bucket.push(hash); + const witness = C.make_vkey_witness(hash, priv); + bucket.push(witness); this.witnessSetBuilder.add_vkey(witness); + Freeables.free(...bucket); return this; } /** Sign the transaction and return the witnesses that were just made. */ async partialSign() { const witnesses = await this.lucid.wallet.signTx(this.txComplete); this.witnessSetBuilder.add_existing(witnesses); - return toHex(witnesses.to_bytes()); + const bytes = witnesses.to_bytes(); + witnesses.free(); + return toHex(bytes); } /** * Sign the transaction and return the witnesses that were just made. * Add an extra signature from a private key. */ partialSignWithPrivateKey(privateKey) { + const bucket = []; const priv = C.PrivateKey.from_bech32(privateKey); - const witness = C.make_vkey_witness(C.hash_transaction(this.txComplete.body()), priv); + bucket.push(priv); + const body = this.txComplete.body(); + bucket.push(body); + const hash = C.hash_transaction(body); + bucket.push(hash); + const witness = C.make_vkey_witness(hash, priv); + bucket.push(witness); this.witnessSetBuilder.add_vkey(witness); const witnesses = C.TransactionWitnessSetBuilder.new(); + bucket.push(witnesses); witnesses.add_vkey(witness); - return toHex(witnesses.build().to_bytes()); + const witnessSet = witnesses.build(); + bucket.push(witnessSet); + const bytes = witnessSet.to_bytes(); + Freeables.free(...bucket); + return toHex(bytes); } /** Sign the transaction with the given witnesses. */ assemble(witnesses) { witnesses.forEach((witness) => { const witnessParsed = C.TransactionWitnessSet.from_bytes(fromHex(witness)); this.witnessSetBuilder.add_existing(witnessParsed); + witnessParsed.free(); }); return this; } @@ -99,8 +140,18 @@ export class TxComplete { for (const task of this.tasks) { await task(); } - this.witnessSetBuilder.add_existing(this.txComplete.witness_set()); - const signedTx = C.Transaction.new(this.txComplete.body(), this.witnessSetBuilder.build(), this.txComplete.auxiliary_data()); + const bucket = []; + const txCompleteWitnessSet = this.txComplete.witness_set(); + bucket.push(txCompleteWitnessSet); + this.witnessSetBuilder.add_existing(txCompleteWitnessSet); + const body = this.txComplete.body(); + bucket.push(body); + const witnessSet = this.witnessSetBuilder.build(); + bucket.push(witnessSet); + const auxiliaryData = this.txComplete.auxiliary_data(); + bucket.push(auxiliaryData); + const signedTx = C.Transaction.new(body, witnessSet, auxiliaryData); + Freeables.free(...bucket); return new TxSigned(this.lucid, signedTx); } /** Return the transaction in Hex encoded Cbor. */ @@ -109,6 +160,15 @@ export class TxComplete { } /** Return the transaction hash. */ toHash() { - return C.hash_transaction(this.txComplete.body()).to_hex(); + const body = this.txComplete.body(); + const hash = C.hash_transaction(body); + const txHash = hash.to_hex(); + Freeables.free(body, hash); + return txHash; + } + /** Since this object has WASM fields, we must use the free method to free the fields */ + free() { + this.txComplete.free(); + this.witnessSetBuilder.free(); } } diff --git a/dist/esm/src/lucid/tx_signed.js b/dist/esm/src/lucid/tx_signed.js index 5d905d4a..791519f3 100644 --- a/dist/esm/src/lucid/tx_signed.js +++ b/dist/esm/src/lucid/tx_signed.js @@ -26,6 +26,13 @@ export class TxSigned { } /** Return the transaction hash. */ toHash() { - return C.hash_transaction(this.txSigned.body()).to_hex(); + const hash = C.hash_transaction(this.txSigned.body()); + const txHash = hash.to_hex(); + hash.free(); + return txHash; + } + /** Since this object has WASM fields, we must use the free method to free the fields */ + free() { + this.txSigned.free(); } } diff --git a/dist/esm/src/plutus/data.js b/dist/esm/src/plutus/data.js index cc390d46..b1d2ef1c 100644 --- a/dist/esm/src/plutus/data.js +++ b/dist/esm/src/plutus/data.js @@ -1,6 +1,7 @@ import { Type, } from "../../deps/deno.land/x/typebox@0.25.13/src/typebox.js"; import { C } from "../core/mod.js"; import { fromHex, fromText, toHex } from "../utils/utils.js"; +import { Freeables } from "../utils/freeable.js"; export class Constr { constructor(index, fields) { Object.defineProperty(this, "index", { @@ -91,28 +92,30 @@ export const Data = { Object: function (properties, options) { const object = Type.Object(properties); replaceProperties(object, { - anyOf: [{ + anyOf: [ + { dataType: "constructor", index: 0, fields: Object.entries(properties).map(([title, p]) => ({ ...p, title, })), - }], + }, + ], }); - object.anyOf[0].hasConstr = typeof options?.hasConstr === "undefined" || - options.hasConstr; + object.anyOf[0].hasConstr = + typeof options?.hasConstr === "undefined" || options.hasConstr; return object; }, Enum: function (items) { const union = Type.Union(items); replaceProperties(union, { anyOf: items.map((item, index) => item.anyOf[0].fields.length === 0 - ? ({ + ? { ...item.anyOf[0], index, - }) - : ({ + } + : { dataType: "constructor", title: (() => { const title = item.anyOf[0].fields[0].title; @@ -125,7 +128,7 @@ export const Data = { index, fields: item.anyOf[0].fields[0].items || item.anyOf[0].fields[0].anyOf[0].fields, - })), + }), }); return union; }, @@ -152,12 +155,14 @@ export const Data = { } const literal = Type.Literal(title); replaceProperties(literal, { - anyOf: [{ + anyOf: [ + { dataType: "constructor", title, index: 0, fields: [], - }], + }, + ], }); return literal; }, @@ -169,9 +174,7 @@ export const Data = { description: "An optional value.", dataType: "constructor", index: 0, - fields: [ - item, - ], + fields: [item], }, { title: "None", @@ -211,9 +214,12 @@ export const Data = { */ function to(data, type) { function serialize(data) { + const bucket = []; try { if (typeof data === "bigint") { - return C.PlutusData.new_integer(C.BigInt.from_str(data.toString())); + const integer = C.BigInt.from_str(data.toString()); + bucket.push(integer); + return C.PlutusData.new_integer(integer); } else if (typeof data === "string") { return C.PlutusData.new_bytes(fromHex(data)); @@ -221,18 +227,37 @@ function to(data, type) { else if (data instanceof Constr) { const { index, fields } = data; const plutusList = C.PlutusList.new(); - fields.forEach((field) => plutusList.add(serialize(field))); - return C.PlutusData.new_constr_plutus_data(C.ConstrPlutusData.new(C.BigNum.from_str(index.toString()), plutusList)); + bucket.push(plutusList); + fields.forEach((field) => { + const serializedField = serialize(field); + plutusList.add(serializedField); + bucket.push(serializedField); + }); + const constrIndex = C.BigNum.from_str(index.toString()); + bucket.push(constrIndex); + const cosntrPlutusData = C.ConstrPlutusData.new(constrIndex, plutusList); + bucket.push(cosntrPlutusData); + return C.PlutusData.new_constr_plutus_data(cosntrPlutusData); } else if (data instanceof Array) { const plutusList = C.PlutusList.new(); - data.forEach((arg) => plutusList.add(serialize(arg))); + bucket.push(plutusList); + data.forEach((arg) => { + const serializedArg = serialize(arg); + plutusList.add(serializedArg); + bucket.push(serializedArg); + }); return C.PlutusData.new_list(plutusList); } else if (data instanceof Map) { const plutusMap = C.PlutusMap.new(); + bucket.push(plutusMap); for (const [key, value] of data.entries()) { - plutusMap.insert(serialize(key), serialize(value)); + const serializedKey = serialize(key); + bucket.push(serializedKey); + const serializedValue = serialize(value); + bucket.push(serializedValue); + plutusMap.insert(serializedKey, serializedValue); } return C.PlutusData.new_map(plutusMap); } @@ -241,9 +266,15 @@ function to(data, type) { catch (error) { throw new Error("Could not serialize the data: " + error); } + finally { + Freeables.free(...bucket); + } } const d = type ? castTo(data, type) : data; - return toHex(serialize(d).to_bytes()); + const serializedD = serialize(d); + const result = toHex(serializedD.to_bytes()); + serializedD.free(); + return result; } /** * Convert Cbor encoded data to Data.\ @@ -251,41 +282,66 @@ function to(data, type) { */ function from(raw, type) { function deserialize(data) { - if (data.kind() === 0) { - const constr = data.as_constr_plutus_data(); - const l = constr.data(); - const desL = []; - for (let i = 0; i < l.len(); i++) { - desL.push(deserialize(l.get(i))); - } - return new Constr(parseInt(constr.alternative().to_str()), desL); - } - else if (data.kind() === 1) { - const m = data.as_map(); - const desM = new Map(); - const keys = m.keys(); - for (let i = 0; i < keys.len(); i++) { - desM.set(deserialize(keys.get(i)), deserialize(m.get(keys.get(i)))); - } - return desM; - } - else if (data.kind() === 2) { - const l = data.as_list(); - const desL = []; - for (let i = 0; i < l.len(); i++) { - desL.push(deserialize(l.get(i))); + const bucket = []; + try { + if (data.kind() === 0) { + const constr = data.as_constr_plutus_data(); + bucket.push(constr); + const l = constr.data(); + bucket.push(l); + const desL = []; + for (let i = 0; i < l.len(); i++) { + const des = l.get(i); + bucket.push(des); + desL.push(deserialize(des)); + } + const alternativeConstr = constr.alternative(); + bucket.push(alternativeConstr); + return new Constr(parseInt(alternativeConstr.to_str()), desL); + } + else if (data.kind() === 1) { + const m = data.as_map(); + bucket.push(m); + const desM = new Map(); + const keys = m.keys(); + bucket.push(keys); + for (let i = 0; i < keys.len(); i++) { + const key = keys.get(i); + bucket.push(key); + const value = m.get(key); + bucket.push(value); + desM.set(deserialize(key), deserialize(value)); + } + return desM; + } + else if (data.kind() === 2) { + const l = data.as_list(); + bucket.push(l); + const desL = []; + for (let i = 0; i < l.len(); i++) { + const elem = l.get(i); + bucket.push(elem); + desL.push(deserialize(elem)); + } + return desL; } - return desL; - } - else if (data.kind() === 3) { - return BigInt(data.as_integer().to_str()); + else if (data.kind() === 3) { + const i = data.as_integer(); + bucket.push(i); + return BigInt(i.to_str()); + } + else if (data.kind() === 4) { + return toHex(data.as_bytes()); + } + throw new Error("Unsupported type"); } - else if (data.kind() === 4) { - return toHex(data.as_bytes()); + finally { + Freeables.free(...bucket); } - throw new Error("Unsupported type"); } - const data = deserialize(C.PlutusData.from_bytes(fromHex(raw))); + const plutusData = C.PlutusData.from_bytes(fromHex(raw)); + const data = deserialize(plutusData); + plutusData.free(); return type ? castFrom(data, type) : data; } /** @@ -326,9 +382,7 @@ function toJson(plutusData) { (typeof data === "string" && !isNaN(parseInt(data)) && data.slice(-1) === "n")) { - const bigint = typeof data === "string" - ? BigInt(data.slice(0, -1)) - : data; + const bigint = typeof data === "string" ? BigInt(data.slice(0, -1)) : data; return parseInt(bigint.toString()); } if (typeof data === "string") { @@ -379,13 +433,15 @@ function castFrom(data, type) { } case "constructor": { if (isVoid(shape)) { - if (!(data instanceof Constr) || data.index !== 0 || + if (!(data instanceof Constr) || + data.index !== 0 || data.fields.length !== 0) { throw new Error("Could not type cast to void."); } return undefined; } - else if (data instanceof Constr && data.index === shape.index && + else if (data instanceof Constr && + data.index === shape.index && (shape.hasConstr || shape.hasConstr === undefined)) { const fields = {}; if (shape.fields.length !== data.fields.length) { @@ -393,14 +449,15 @@ function castFrom(data, type) { } shape.fields.forEach((field, fieldIndex) => { const title = field.title || "wrapper"; - if ((/[A-Z]/.test(title[0]))) { + if (/[A-Z]/.test(title[0])) { throw new Error("Could not type cast to object. Object properties need to start with a lowercase letter."); } fields[title] = castFrom(data.fields[fieldIndex], field); }); return fields; } - else if (data instanceof Array && !shape.hasConstr && + else if (data instanceof Array && + !shape.hasConstr && shape.hasConstr !== undefined) { const fields = {}; if (shape.fields.length !== data.length) { @@ -408,7 +465,7 @@ function castFrom(data, type) { } shape.fields.forEach((field, fieldIndex) => { const title = field.title || "wrapper"; - if ((/[A-Z]/.test(title[0]))) { + if (/[A-Z]/.test(title[0])) { throw new Error("Could not type cast to object. Object properties need to start with a lowercase letter."); } fields[title] = castFrom(data[fieldIndex], field); @@ -467,7 +524,7 @@ function castFrom(data, type) { throw new Error("Could not type cast to enum."); } else { - if (!(/[A-Z]/.test(enumShape.title))) { + if (!/[A-Z]/.test(enumShape.title)) { throw new Error("Could not type cast to enum. Enums need to start with an uppercase letter."); } if (enumShape.fields.length !== data.fields.length) { @@ -475,7 +532,10 @@ function castFrom(data, type) { } // check if named args const args = enumShape.fields[0].title - ? Object.fromEntries(enumShape.fields.map((field, index) => [field.title, castFrom(data.fields[index], field)])) + ? Object.fromEntries(enumShape.fields.map((field, index) => [ + field.title, + castFrom(data.fields[index], field), + ])) : enumShape.fields.map((field, index) => castFrom(data.fields[index], field)); return { [enumShape.title]: args, @@ -488,9 +548,7 @@ function castFrom(data, type) { case "list": { if (shape.items instanceof Array) { // tuple - if (data instanceof Constr && - data.index === 0 && - shape.hasConstr) { + if (data instanceof Constr && data.index === 0 && shape.hasConstr) { return data.fields.map((field, index) => castFrom(field, shape.items[index])); } else if (data instanceof Array && !shape.hasConstr) { @@ -513,8 +571,7 @@ function castFrom(data, type) { } mapConstraints(data, shape); const map = new Map(); - for (const [key, value] of (data) - .entries()) { + for (const [key, value] of data.entries()) { map.set(castFrom(key, shape.keys), castFrom(value, shape.values)); } return map; @@ -552,12 +609,13 @@ function castTo(struct, type) { } return new Constr(0, []); } - else if (typeof struct !== "object" || struct === null || + else if (typeof struct !== "object" || + struct === null || shape.fields.length !== Object.keys(struct).length) { throw new Error("Could not type cast to constructor."); } const fields = shape.fields.map((field) => castTo(struct[field.title || "wrapper"], field)); - return (shape.hasConstr || shape.hasConstr === undefined) + return shape.hasConstr || shape.hasConstr === undefined ? new Constr(shape.index, fields) : fields; } @@ -580,14 +638,12 @@ function castTo(struct, type) { if (fields.length !== 1) { throw new Error("Could not type cast to nullable object."); } - return new Constr(0, [ - castTo(struct, fields[0]), - ]); + return new Constr(0, [castTo(struct, fields[0])]); } } switch (typeof struct) { case "string": { - if (!(/[A-Z]/.test(struct[0]))) { + if (!/[A-Z]/.test(struct[0])) { throw new Error("Could not type cast to enum. Enum needs to start with an uppercase letter."); } const enumIndex = shape.anyOf.findIndex((s) => s.dataType === "constructor" && @@ -601,11 +657,10 @@ function castTo(struct, type) { if (struct === null) throw new Error("Could not type cast to enum."); const structTitle = Object.keys(struct)[0]; - if (!(/[A-Z]/.test(structTitle))) { + if (!/[A-Z]/.test(structTitle)) { throw new Error("Could not type cast to enum. Enum needs to start with an uppercase letter."); } - const enumEntry = shape.anyOf.find((s) => s.dataType === "constructor" && - s.title === structTitle); + const enumEntry = shape.anyOf.find((s) => s.dataType === "constructor" && s.title === structTitle); if (!enumEntry) throw new Error("Could not type cast to enum."); const args = struct[structTitle]; @@ -642,8 +697,7 @@ function castTo(struct, type) { } mapConstraints(struct, shape); const map = new Map(); - for (const [key, value] of (struct) - .entries()) { + for (const [key, value] of struct.entries()) { map.set(castTo(key, shape.keys), castTo(value, shape.values)); } return map; @@ -669,8 +723,9 @@ function integerConstraints(integer, shape) { } } function bytesConstraints(bytes, shape) { - if (shape.enum && !shape.enum.some((keyword) => keyword === bytes)) + if (shape.enum && !shape.enum.some((keyword) => keyword === bytes)) { throw new Error(`None of the keywords match with '${bytes}'.`); + } if (shape.minLength && bytes.length / 2 < shape.minLength) { throw new Error(`Bytes need to have a length of at least ${shape.minLength} bytes.`); } @@ -685,7 +740,7 @@ function listConstraints(list, shape) { if (shape.maxItems && list.length > shape.maxItems) { throw new Error(`Array can contain at most ${shape.maxItems} items.`); } - if (shape.uniqueItems && (new Set(list)).size !== list.length) { + if (shape.uniqueItems && new Set(list).size !== list.length) { // Note this only works for primitive types like string and bigint. throw new Error("Array constains duplicates."); } @@ -699,15 +754,17 @@ function mapConstraints(map, shape) { } } function isBoolean(shape) { - return shape.anyOf && shape.anyOf[0]?.title === "False" && - shape.anyOf[1]?.title === "True"; + return (shape.anyOf && + shape.anyOf[0]?.title === "False" && + shape.anyOf[1]?.title === "True"); } function isVoid(shape) { return shape.index === 0 && shape.fields.length === 0; } function isNullable(shape) { - return shape.anyOf && shape.anyOf[0]?.title === "Some" && - shape.anyOf[1]?.title === "None"; + return (shape.anyOf && + shape.anyOf[0]?.title === "Some" && + shape.anyOf[1]?.title === "None"); } function replaceProperties(object, properties) { Object.keys(object).forEach((key) => { diff --git a/dist/esm/src/provider/blockfrost.js b/dist/esm/src/provider/blockfrost.js index dd72bf21..ce8ccd9a 100644 --- a/dist/esm/src/provider/blockfrost.js +++ b/dist/esm/src/provider/blockfrost.js @@ -1,6 +1,7 @@ import { C } from "../core/mod.js"; import { applyDoubleCborEncoding, fromHex, toHex } from "../utils/mod.js"; import packageJson from "../../package.js"; +import { Freeables } from "../utils/freeable.js"; export class Blockfrost { constructor(url, projectId) { Object.defineProperty(this, "url", { @@ -43,9 +44,11 @@ export class Blockfrost { const queryPredicate = (() => { if (typeof addressOrCredential === "string") return addressOrCredential; - const credentialBech32 = addressOrCredential.type === "Key" - ? C.Ed25519KeyHash.from_hex(addressOrCredential.hash).to_bech32("addr_vkh") - : C.ScriptHash.from_hex(addressOrCredential.hash).to_bech32("addr_vkh"); // should be 'script' (CIP-0005) + const hash = addressOrCredential.type === "Key" + ? C.Ed25519KeyHash.from_hex(addressOrCredential.hash) + : C.ScriptHash.from_hex(addressOrCredential.hash); + const credentialBech32 = hash.to_bech32("addr_vkh"); // should be 'script' according to CIP-0005, but to maintain bakcwards compatabiltiy I am not changing this + hash.free(); return credentialBech32; })(); let result = []; @@ -71,9 +74,11 @@ export class Blockfrost { const queryPredicate = (() => { if (typeof addressOrCredential === "string") return addressOrCredential; - const credentialBech32 = addressOrCredential.type === "Key" - ? C.Ed25519KeyHash.from_hex(addressOrCredential.hash).to_bech32("addr_vkh") - : C.ScriptHash.from_hex(addressOrCredential.hash).to_bech32("addr_vkh"); // should be 'script' (CIP-0005) + const hash = addressOrCredential.type === "Key" + ? C.Ed25519KeyHash.from_hex(addressOrCredential.hash) + : C.ScriptHash.from_hex(addressOrCredential.hash); + const credentialBech32 = hash.to_bech32("addr_vkh"); // should be 'script' according to CIP-0005, but to maintain bakcwards compatabiltiy I am not changing this + hash.free(); return credentialBech32; })(); let result = []; @@ -114,7 +119,9 @@ export class Blockfrost { // TODO: Make sure old already spent UTxOs are not retrievable. const queryHashes = [...new Set(outRefs.map((outRef) => outRef.txHash))]; const utxos = await Promise.all(queryHashes.map(async (txHash) => { - const result = await fetch(`${this.url}/txs/${txHash}/utxos`, { headers: { project_id: this.projectId, lucid } }).then((res) => res.json()); + const result = await fetch(`${this.url}/txs/${txHash}/utxos`, { + headers: { project_id: this.projectId, lucid }, + }).then((res) => res.json()); if (!result || result.error) { return []; } @@ -126,10 +133,15 @@ export class Blockfrost { })); return this.blockfrostUtxosToUtxos(utxosResult); })); - return utxos.reduce((acc, utxos) => acc.concat(utxos), []).filter((utxo) => outRefs.some((outRef) => utxo.txHash === outRef.txHash && utxo.outputIndex === outRef.outputIndex)); + return utxos + .reduce((acc, utxos) => acc.concat(utxos), []) + .filter((utxo) => outRefs.some((outRef) => utxo.txHash === outRef.txHash && + utxo.outputIndex === outRef.outputIndex)); } async getDelegation(rewardAddress) { - const result = await fetch(`${this.url}/accounts/${rewardAddress}`, { headers: { project_id: this.projectId, lucid } }).then((res) => res.json()); + const result = await fetch(`${this.url}/accounts/${rewardAddress}`, { + headers: { project_id: this.projectId, lucid }, + }).then((res) => res.json()); if (!result || result.error) { return { poolId: null, rewards: 0n }; } @@ -190,8 +202,8 @@ export class Blockfrost { datumHash: (!r.inline_datum && r.data_hash) || undefined, datum: r.inline_datum || undefined, scriptRef: r.reference_script_hash - ? (await (async () => { - const { type, } = await fetch(`${this.url}/scripts/${r.reference_script_hash}`, { + ? await (async () => { + const { type } = await fetch(`${this.url}/scripts/${r.reference_script_hash}`, { headers: { project_id: this.projectId, lucid }, }).then((res) => res.json()); // TODO: support native scripts @@ -203,7 +215,7 @@ export class Blockfrost { type: type === "plutusV1" ? "PlutusV1" : "PlutusV2", script: applyDoubleCborEncoding(script), }; - })()) + })() : undefined, })))); } @@ -214,35 +226,61 @@ export class Blockfrost { */ export function datumJsonToCbor(json) { const convert = (json) => { - if (!isNaN(json.int)) { - return C.PlutusData.new_integer(C.BigInt.from_str(json.int.toString())); - } - else if (json.bytes || !isNaN(Number(json.bytes))) { - return C.PlutusData.new_bytes(fromHex(json.bytes)); - } - else if (json.map) { - const m = C.PlutusMap.new(); - json.map.forEach(({ k, v }) => { - m.insert(convert(k), convert(v)); - }); - return C.PlutusData.new_map(m); - } - else if (json.list) { - const l = C.PlutusList.new(); - json.list.forEach((v) => { - l.add(convert(v)); - }); - return C.PlutusData.new_list(l); + const bucket = []; + try { + if (!isNaN(json.int)) { + const int = C.BigInt.from_str(json.int.toString()); + bucket.push(int); + return C.PlutusData.new_integer(int); + } + else if (json.bytes || !isNaN(Number(json.bytes))) { + return C.PlutusData.new_bytes(fromHex(json.bytes)); + } + else if (json.map) { + const m = C.PlutusMap.new(); + bucket.push(m); + json.map.forEach(({ k, v }) => { + const key = convert(k); + bucket.push(key); + const value = convert(v); + bucket.push(value); + m.insert(key, value); + }); + return C.PlutusData.new_map(m); + } + else if (json.list) { + const l = C.PlutusList.new(); + bucket.push(l); + json.list.forEach((v) => { + const value = convert(v); + bucket.push(value); + l.add(value); + }); + return C.PlutusData.new_list(l); + } + else if (!isNaN(json.constructor)) { + const l = C.PlutusList.new(); + bucket.push(l); + json.fields.forEach((v) => { + const value = convert(v); + bucket.push(value); + l.add(value); + }); + const constructorIndex = C.BigNum.from_str(json.constructor.toString()); + bucket.push(constructorIndex); + const plutusData = C.ConstrPlutusData.new(constructorIndex, l); + bucket.push(plutusData); + return C.PlutusData.new_constr_plutus_data(plutusData); + } + throw new Error("Unsupported type"); } - else if (!isNaN(json.constructor)) { - const l = C.PlutusList.new(); - json.fields.forEach((v) => { - l.add(convert(v)); - }); - return C.PlutusData.new_constr_plutus_data(C.ConstrPlutusData.new(C.BigNum.from_str(json.constructor.toString()), l)); + finally { + Freeables.free(...bucket); } - throw new Error("Unsupported type"); }; - return toHex(convert(json).to_bytes()); + const convertedJson = convert(json); + const cbor = convertedJson.to_bytes(); + convertedJson.free(); + return toHex(cbor); } const lucid = packageJson.version; // Lucid version diff --git a/dist/esm/src/provider/emulator.js b/dist/esm/src/provider/emulator.js index 477e73be..09f6f981 100644 --- a/dist/esm/src/provider/emulator.js +++ b/dist/esm/src/provider/emulator.js @@ -60,13 +60,21 @@ export class Emulator { this.slot = 0; this.time = Date.now(); this.ledger = {}; - accounts.forEach(({ address, assets }, index) => { + accounts.forEach(({ address, assets, outputData }, index) => { + if ([outputData?.hash, outputData?.asHash, outputData?.inline].filter((b) => b).length > 1) { + throw new Error("Not allowed to set hash, asHash and inline at the same time."); + } this.ledger[GENESIS_HASH + index] = { utxo: { txHash: GENESIS_HASH, outputIndex: index, address, assets, + datumHash: outputData?.asHash + ? C.hash_plutus_data(C.PlutusData.from_bytes(fromHex(outputData.asHash))).to_hex() + : outputData?.hash, + datum: outputData?.inline, + scriptRef: outputData?.scriptRef, }, spent: false, }; @@ -168,13 +176,13 @@ export class Emulator { * Stake keys need to be registered and delegated like on a real chain in order to receive rewards. */ distributeRewards(rewards) { - for (const [rewardAddress, { registeredStake, delegation }] of Object.entries(this.chain)) { + for (const [rewardAddress, { registeredStake, delegation },] of Object.entries(this.chain)) { if (registeredStake && delegation.poolId) { this.chain[rewardAddress] = { registeredStake, delegation: { poolId: delegation.poolId, - rewards: delegation.rewards += rewards, + rewards: (delegation.rewards += rewards), }, }; } @@ -198,18 +206,29 @@ export class Emulator { - Withdrawals - Validity interval */ + const bucket = []; const desTx = C.Transaction.from_bytes(fromHex(tx)); + bucket.push(desTx); const body = desTx.body(); + bucket.push(body); const witnesses = desTx.witness_set(); + bucket.push(witnesses); const datums = witnesses.plutus_data(); - const txHash = C.hash_transaction(body).to_hex(); + bucket.push(datums); + const transactionHash = C.hash_transaction(body); + bucket.push(transactionHash); + const txHash = transactionHash.to_hex(); // Validity interval // Lower bound is inclusive? // Upper bound is inclusive? - const lowerBound = body.validity_start_interval() - ? parseInt(body.validity_start_interval().to_str()) + const validityStartInterval = body.validity_start_interval(); + bucket.push(validityStartInterval); + const lowerBound = validityStartInterval + ? parseInt(validityStartInterval.to_str()) : null; - const upperBound = body.ttl() ? parseInt(body.ttl().to_str()) : null; + const ttl = body.ttl(); + bucket.push(ttl); + const upperBound = ttl ? parseInt(ttl.to_str()) : null; if (Number.isInteger(lowerBound) && this.slot < lowerBound) { throw new Error(`Lower bound (${lowerBound}) not in slot range (${this.slot}).`); } @@ -221,7 +240,10 @@ export class Emulator { const table = {}; for (let i = 0; i < (datums?.len() || 0); i++) { const datum = datums.get(i); - const datumHash = C.hash_plutus_data(datum).to_hex(); + bucket.push(datum); + const plutusDataHash = C.hash_plutus_data(datum); + bucket.push(plutusDataHash); + const datumHash = plutusDataHash.to_hex(); table[datumHash] = toHex(datum.to_bytes()); } return table; @@ -230,10 +252,18 @@ export class Emulator { // Witness keys const keyHashes = (() => { const keyHashes = []; - for (let i = 0; i < (witnesses.vkeys()?.len() || 0); i++) { - const witness = witnesses.vkeys().get(i); - const publicKey = witness.vkey().public_key(); - const keyHash = publicKey.hash().to_hex(); + const vkeys = witnesses.vkeys(); + bucket.push(vkeys); + for (let i = 0; i < (vkeys?.len() || 0); i++) { + const witness = vkeys.get(i); + bucket.push(witness); + const vkey = witness.vkey(); + bucket.push(vkey); + const publicKey = vkey.public_key(); + bucket.push(publicKey); + const hash = publicKey.hash(); + bucket.push(hash); + const keyHash = hash.to_hex(); if (!publicKey.verify(fromHex(txHash), witness.signature())) { throw new Error(`Invalid vkey witness. Key hash: ${keyHash}`); } @@ -243,22 +273,39 @@ export class Emulator { })(); // We only need this to verify native scripts. The check happens in the CML. const edKeyHashes = C.Ed25519KeyHashes.new(); - keyHashes.forEach((keyHash) => edKeyHashes.add(C.Ed25519KeyHash.from_hex(keyHash))); + bucket.push(edKeyHashes); + keyHashes.forEach((keyHash) => { + const ed25519KeyHash = C.Ed25519KeyHash.from_hex(keyHash); + bucket.push(ed25519KeyHash); + edKeyHashes.add(ed25519KeyHash); + }); const nativeHashes = (() => { const scriptHashes = []; - for (let i = 0; i < (witnesses.native_scripts()?.len() || 0); i++) { - const witness = witnesses.native_scripts().get(i); - const scriptHash = witness.hash(C.ScriptHashNamespace.NativeScript) - .to_hex(); - if (!witness.verify(Number.isInteger(lowerBound) + const nativeScripts = witnesses.native_scripts(); + bucket.push(nativeScripts); + for (let i = 0; i < (nativeScripts?.len() || 0); i++) { + const witness = nativeScripts.get(i); + bucket.push(witness); + const hash = witness.hash(C.ScriptHashNamespace.NativeScript); + bucket.push(hash); + const scriptHash = hash.to_hex(); + const lBound = Number.isInteger(lowerBound) ? C.BigNum.from_str(lowerBound.toString()) - : undefined, Number.isInteger(upperBound) + : undefined; + bucket.push(lBound); + const uBound = Number.isInteger(upperBound) ? C.BigNum.from_str(upperBound.toString()) - : undefined, edKeyHashes)) { + : undefined; + bucket.push(uBound); + if (!witness.verify(lBound, uBound, edKeyHashes)) { throw new Error(`Invalid native script witness. Script hash: ${scriptHash}`); } - for (let i = 0; i < witness.get_required_signers().len(); i++) { - const keyHash = witness.get_required_signers().get(i).to_hex(); + const requiredSigners = witness.get_required_signers(); + bucket.push(requiredSigners); + for (let i = 0; i < requiredSigners.len(); i++) { + const hash = requiredSigners.get(i); + bucket.push(hash); + const keyHash = hash.to_hex(); consumedHashes.add(keyHash); } scriptHashes.push(scriptHash); @@ -269,27 +316,41 @@ export class Emulator { const plutusHashesOptional = []; const plutusHashes = (() => { const scriptHashes = []; - for (let i = 0; i < (witnesses.plutus_scripts()?.len() || 0); i++) { - const script = witnesses.plutus_scripts().get(i); - const scriptHash = script.hash(C.ScriptHashNamespace.PlutusV1) - .to_hex(); + const plutusScripts = witnesses.plutus_scripts(); + bucket.push(plutusScripts); + for (let i = 0; i < (plutusScripts?.len() || 0); i++) { + const script = plutusScripts.get(i); + bucket.push(script); + const hash = script.hash(C.ScriptHashNamespace.PlutusV1); + bucket.push(hash); + const scriptHash = hash.to_hex(); scriptHashes.push(scriptHash); } - for (let i = 0; i < (witnesses.plutus_v2_scripts()?.len() || 0); i++) { - const script = witnesses.plutus_v2_scripts().get(i); - const scriptHash = script.hash(C.ScriptHashNamespace.PlutusV2) - .to_hex(); + const plutusV2Scripts = witnesses.plutus_v2_scripts(); + bucket.push(plutusV2Scripts); + for (let i = 0; i < (plutusV2Scripts?.len() || 0); i++) { + const script = plutusV2Scripts.get(i); + bucket.push(script); + const hash = script.hash(C.ScriptHashNamespace.PlutusV2); + bucket.push(hash); + const scriptHash = hash.to_hex(); scriptHashes.push(scriptHash); } return scriptHashes; })(); const inputs = body.inputs(); + bucket.push(inputs); inputs.sort(); const resolvedInputs = []; // Check existence of inputs and look for script refs. for (let i = 0; i < inputs.len(); i++) { const input = inputs.get(i); - const outRef = input.transaction_id().to_hex() + input.index().to_str(); + bucket.push(input); + const transactionId = input.transaction_id(); + bucket.push(transactionId); + const transactionIndex = input.index(); + bucket.push(transactionIndex); + const outRef = transactionId.to_hex() + transactionIndex.to_str(); const entryLedger = this.ledger[outRef]; const { entry, type } = !entryLedger ? { entry: this.mempool[outRef], type: "Mempool" } @@ -305,17 +366,26 @@ export class Emulator { switch (scriptRef.type) { case "Native": { const script = C.NativeScript.from_bytes(fromHex(scriptRef.script)); - nativeHashesOptional[script.hash(C.ScriptHashNamespace.NativeScript).to_hex()] = script; + bucket.push(script); + const hash = script.hash(C.ScriptHashNamespace.NativeScript); + bucket.push(hash); + nativeHashesOptional[hash.to_hex()] = script; break; } case "PlutusV1": { const script = C.PlutusScript.from_bytes(fromHex(scriptRef.script)); - plutusHashesOptional.push(script.hash(C.ScriptHashNamespace.PlutusV1).to_hex()); + bucket.push(script); + const hash = script.hash(C.ScriptHashNamespace.PlutusV1); + bucket.push(hash); + plutusHashesOptional.push(hash.to_hex()); break; } case "PlutusV2": { const script = C.PlutusScript.from_bytes(fromHex(scriptRef.script)); - plutusHashesOptional.push(script.hash(C.ScriptHashNamespace.PlutusV2).to_hex()); + bucket.push(script); + const hash = script.hash(C.ScriptHashNamespace.PlutusV2); + bucket.push(hash); + plutusHashesOptional.push(hash.to_hex()); break; } } @@ -325,9 +395,16 @@ export class Emulator { resolvedInputs.push({ entry, type }); } // Check existence of reference inputs and look for script refs. - for (let i = 0; i < (body.reference_inputs()?.len() || 0); i++) { - const input = body.reference_inputs().get(i); - const outRef = input.transaction_id().to_hex() + input.index().to_str(); + const referenceInputs = body.reference_inputs(); + bucket.push(referenceInputs); + for (let i = 0; i < (referenceInputs?.len() || 0); i++) { + const input = referenceInputs.get(i); + bucket.push(input); + const inputId = input.transaction_id(); + bucket.push(inputId); + const inputIndex = input.index(); + bucket.push(inputIndex); + const outRef = inputId.to_hex() + inputIndex.to_str(); const entry = this.ledger[outRef] || this.mempool[outRef]; if (!entry || entry.spent) { throw new Error(`Could not read UTxO: ${JSON.stringify({ @@ -340,17 +417,26 @@ export class Emulator { switch (scriptRef.type) { case "Native": { const script = C.NativeScript.from_bytes(fromHex(scriptRef.script)); - nativeHashesOptional[script.hash(C.ScriptHashNamespace.NativeScript).to_hex()] = script; + bucket.push(script); + const hash = script.hash(C.ScriptHashNamespace.NativeScript); + bucket.push(hash); + nativeHashesOptional[hash.to_hex()] = script; break; } case "PlutusV1": { const script = C.PlutusScript.from_bytes(fromHex(scriptRef.script)); - plutusHashesOptional.push(script.hash(C.ScriptHashNamespace.PlutusV1).to_hex()); + bucket.push(script); + const hash = script.hash(C.ScriptHashNamespace.PlutusV1); + bucket.push(hash); + plutusHashesOptional.push(hash.to_hex()); break; } case "PlutusV2": { const script = C.PlutusScript.from_bytes(fromHex(scriptRef.script)); - plutusHashesOptional.push(script.hash(C.ScriptHashNamespace.PlutusV2).to_hex()); + bucket.push(script); + const hash = script.hash(C.ScriptHashNamespace.PlutusV2); + bucket.push(hash); + plutusHashesOptional.push(hash.to_hex()); break; } } @@ -366,11 +452,18 @@ export class Emulator { 3: "Reward", }; const collected = []; - for (let i = 0; i < (witnesses.redeemers()?.len() || 0); i++) { - const redeemer = witnesses.redeemers().get(i); + const redeemers = witnesses.redeemers(); + bucket.push(redeemers); + for (let i = 0; i < (redeemers?.len() || 0); i++) { + const redeemer = redeemers.get(i); + bucket.push(redeemer); + const tag = redeemer.tag(); + bucket.push(tag); + const redeemerIndex = redeemer.index(); + bucket.push(redeemerIndex); collected.push({ - tag: tagMap[redeemer.tag().kind()], - index: parseInt(redeemer.index().to_str()), + tag: tagMap[tag.kind()], + index: parseInt(redeemerIndex.to_str()), }); } return collected; @@ -390,11 +483,15 @@ export class Emulator { break; } else if (nativeHashesOptional[credential.hash]) { - if (!nativeHashesOptional[credential.hash].verify(Number.isInteger(lowerBound) + const lBound = Number.isInteger(lowerBound) ? C.BigNum.from_str(lowerBound.toString()) - : undefined, Number.isInteger(upperBound) + : undefined; + bucket.push(lBound); + const uBound = Number.isInteger(upperBound) ? C.BigNum.from_str(upperBound.toString()) - : undefined, edKeyHashes)) { + : undefined; + bucket.push(uBound); + if (!nativeHashesOptional[credential.hash].verify(lBound, uBound, edKeyHashes)) { throw new Error(`Invalid native script witness. Script hash: ${credential.hash}`); } break; @@ -411,9 +508,16 @@ export class Emulator { } } // Check collateral inputs - for (let i = 0; i < (body.collateral()?.len() || 0); i++) { - const input = body.collateral().get(i); - const outRef = input.transaction_id().to_hex() + input.index().to_str(); + const collateral = body.collateral(); + bucket.push(collateral); + for (let i = 0; i < (collateral?.len() || 0); i++) { + const input = collateral.get(i); + bucket.push(input); + const transactionId = input.transaction_id(); + bucket.push(transactionId); + const transactionIndex = input.index(); + bucket.push(transactionIndex); + const outRef = transactionId.to_hex() + transactionIndex.to_str(); const entry = this.ledger[outRef] || this.mempool[outRef]; if (!entry || entry.spent) { throw new Error(`Could not read UTxO: ${JSON.stringify({ @@ -428,21 +532,37 @@ export class Emulator { checkAndConsumeHash(paymentCredential, null, null); } // Check required signers - for (let i = 0; i < (body.required_signers()?.len() || 0); i++) { - const signer = body.required_signers().get(i); + const requiredSigners = body.required_signers(); + bucket.push(requiredSigners); + for (let i = 0; i < (requiredSigners?.len() || 0); i++) { + const signer = requiredSigners.get(i); + bucket.push(signer); checkAndConsumeHash({ type: "Key", hash: signer.to_hex() }, null, null); } // Check mint witnesses - for (let index = 0; index < (body.mint()?.keys().len() || 0); index++) { - const policyId = body.mint().keys().get(index).to_hex(); - checkAndConsumeHash({ type: "Script", hash: policyId }, "Mint", index); + const mint = body.mint(); + bucket.push(mint); + const mintKeys = mint?.keys(); + bucket.push(mintKeys); + for (let index = 0; index < (mintKeys?.len() || 0); index++) { + const policy = mintKeys.get(index); + bucket.push(policy); + const hash = policy.to_hex(); + checkAndConsumeHash({ type: "Script", hash }, "Mint", index); } // Check withdrawal witnesses const withdrawalRequests = []; - for (let index = 0; index < (body.withdrawals()?.keys().len() || 0); index++) { - const rawAddress = body.withdrawals().keys().get(index); - const withdrawal = BigInt(body.withdrawals().get(rawAddress).to_str()); - const rewardAddress = rawAddress.to_address().to_bech32(undefined); + const withdrawals = body.withdrawals(); + const withdrawalKeys = withdrawals?.keys(); + for (let index = 0; index < (withdrawalKeys?.len() || 0); index++) { + const rawAddress = withdrawalKeys.get(index); + bucket.push(rawAddress); + const cWithdrawal = withdrawals.get(rawAddress); + bucket.push(cWithdrawal); + const withdrawal = BigInt(cWithdrawal.to_str()); + const cAddress = rawAddress.to_address(); + bucket.push(cAddress); + const rewardAddress = cAddress.to_bech32(undefined); const { stakeCredential } = getAddressDetails(rewardAddress); checkAndConsumeHash(stakeCredential, "Reward", index); if (this.chain[rewardAddress]?.delegation.rewards !== withdrawal) { @@ -452,7 +572,9 @@ export class Emulator { } // Check cert witnesses const certRequests = []; - for (let index = 0; index < (body.certs()?.len() || 0); index++) { + const certs = body.certs(); + bucket.push(certs); + for (let index = 0; index < (certs?.len() || 0); index++) { /* Checking only: 1. Stake registration @@ -461,11 +583,21 @@ export class Emulator { All other certificate types are not checked and considered valid. */ - const cert = body.certs().get(index); + const cert = certs.get(index); + bucket.push(cert); switch (cert.kind()) { case 0: { const registration = cert.as_stake_registration(); - const rewardAddress = C.RewardAddress.new(C.NetworkInfo.testnet().network_id(), registration.stake_credential()).to_address().to_bech32(undefined); + bucket.push(registration); + const networkInfo = C.NetworkInfo.testnet(); + bucket.push(networkInfo); + const stakeCredential = registration.stake_credential(); + bucket.push(stakeCredential); + const cRewardAddress = C.RewardAddress.new(networkInfo.network_id(), stakeCredential); + bucket.push(cRewardAddress); + const address = cRewardAddress.to_address(); + bucket.push(address); + const rewardAddress = address.to_bech32(undefined); if (this.chain[rewardAddress]?.registeredStake) { throw new Error(`Stake key is already registered. Reward address: ${rewardAddress}`); } @@ -474,7 +606,16 @@ export class Emulator { } case 1: { const deregistration = cert.as_stake_deregistration(); - const rewardAddress = C.RewardAddress.new(C.NetworkInfo.testnet().network_id(), deregistration.stake_credential()).to_address().to_bech32(undefined); + bucket.push(deregistration); + const networkInfo = C.NetworkInfo.testnet(); + bucket.push(networkInfo); + const cStakeCredential = deregistration.stake_credential(); + bucket.push(cStakeCredential); + const cRewardAddress = C.RewardAddress.new(networkInfo.network_id(), cStakeCredential); + bucket.push(cRewardAddress); + const address = cRewardAddress.to_address(); + bucket.push(address); + const rewardAddress = address.to_bech32(undefined); const { stakeCredential } = getAddressDetails(rewardAddress); checkAndConsumeHash(stakeCredential, "Cert", index); if (!this.chain[rewardAddress]?.registeredStake) { @@ -485,8 +626,19 @@ export class Emulator { } case 2: { const delegation = cert.as_stake_delegation(); - const rewardAddress = C.RewardAddress.new(C.NetworkInfo.testnet().network_id(), delegation.stake_credential()).to_address().to_bech32(undefined); - const poolId = delegation.pool_keyhash().to_bech32("pool"); + bucket.push(delegation); + const networkInfo = C.NetworkInfo.testnet(); + bucket.push(networkInfo); + const cStakeCredential = delegation.stake_credential(); + bucket.push(cStakeCredential); + const cRewardAddress = C.RewardAddress.new(networkInfo.network_id(), cStakeCredential); + bucket.push(cRewardAddress); + const address = cRewardAddress.to_address(); + bucket.push(address); + const rewardAddress = address.to_bech32(undefined); + const poolKeyHash = delegation.pool_keyhash(); + bucket.push(poolKeyHash); + const poolId = poolKeyHash.to_bech32("pool"); const { stakeCredential } = getAddressDetails(rewardAddress); checkAndConsumeHash(stakeCredential, "Cert", index); if (!this.chain[rewardAddress]?.registeredStake && @@ -506,10 +658,20 @@ export class Emulator { }); // Create outputs and consume datum hashes const outputs = (() => { + const outputs = body.outputs(); + bucket.push(outputs); const collected = []; - for (let i = 0; i < body.outputs().len(); i++) { - const output = body.outputs().get(i); - const unspentOutput = C.TransactionUnspentOutput.new(C.TransactionInput.new(C.TransactionHash.from_hex(txHash), C.BigNum.from_str(i.toString())), output); + for (let i = 0; i < outputs.len(); i++) { + const output = outputs.get(i); + bucket.push(output); + const transactionHash = C.TransactionHash.from_hex(txHash); + bucket.push(transactionHash); + const index = C.BigNum.from_str(i.toString()); + bucket.push(index); + const transactionInput = C.TransactionInput.new(transactionHash, index); + bucket.push(transactionInput); + const unspentOutput = C.TransactionUnspentOutput.new(transactionInput, output); + bucket.push(unspentOutput); const utxo = coreToUtxo(unspentOutput); if (utxo.datumHash) consumedHashes.add(utxo.datumHash); diff --git a/dist/esm/src/provider/kupmios.js b/dist/esm/src/provider/kupmios.js index 9eead227..fc51dbe0 100644 --- a/dist/esm/src/provider/kupmios.js +++ b/dist/esm/src/provider/kupmios.js @@ -67,8 +67,7 @@ export class Kupmios { const queryPredicate = isAddress ? addressOrCredential : addressOrCredential.hash; - const result = await fetch(`${this.kupoUrl}/matches/${queryPredicate}${isAddress ? "" : "/*"}?unspent`) - .then((res) => res.json()); + const result = await fetch(`${this.kupoUrl}/matches/${queryPredicate}${isAddress ? "" : "/*"}?unspent`).then((res) => res.json()); return this.kupmiosUtxosToUtxos(result); } async getUtxosWithUnit(addressOrCredential, unit) { @@ -77,14 +76,12 @@ export class Kupmios { ? addressOrCredential : addressOrCredential.hash; const { policyId, assetName } = fromUnit(unit); - const result = await fetch(`${this.kupoUrl}/matches/${queryPredicate}${isAddress ? "" : "/*"}?unspent&policy_id=${policyId}${assetName ? `&asset_name=${assetName}` : ""}`) - .then((res) => res.json()); + const result = await fetch(`${this.kupoUrl}/matches/${queryPredicate}${isAddress ? "" : "/*"}?unspent&policy_id=${policyId}${assetName ? `&asset_name=${assetName}` : ""}`).then((res) => res.json()); return this.kupmiosUtxosToUtxos(result); } async getUtxoByUnit(unit) { const { policyId, assetName } = fromUnit(unit); - const result = await fetch(`${this.kupoUrl}/matches/${policyId}.${assetName ? `${assetName}` : "*"}?unspent`) - .then((res) => res.json()); + const result = await fetch(`${this.kupoUrl}/matches/${policyId}.${assetName ? `${assetName}` : "*"}?unspent`).then((res) => res.json()); const utxos = await this.kupmiosUtxosToUtxos(result); if (utxos.length > 1) { throw new Error("Unit needs to be an NFT or only held by one address."); @@ -97,11 +94,14 @@ export class Kupmios { const result = await fetch(`${this.kupoUrl}/matches/*@${txHash}?unspent`).then((res) => res.json()); return this.kupmiosUtxosToUtxos(result); })); - return utxos.reduce((acc, utxos) => acc.concat(utxos), []).filter((utxo) => outRefs.some((outRef) => utxo.txHash === outRef.txHash && utxo.outputIndex === outRef.outputIndex)); + return utxos + .reduce((acc, utxos) => acc.concat(utxos), []) + .filter((utxo) => outRefs.some((outRef) => utxo.txHash === outRef.txHash && + utxo.outputIndex === outRef.outputIndex)); } async getDelegation(rewardAddress) { const client = await this.ogmiosWsp("Query", { - query: { "delegationsAndRewards": [rewardAddress] }, + query: { delegationsAndRewards: [rewardAddress] }, }); return new Promise((res, rej) => { client.addEventListener("message", (msg) => { @@ -160,9 +160,10 @@ export class Kupmios { }); } kupmiosUtxosToUtxos(utxos) { + return Promise.all( // deno-lint-ignore no-explicit-any - return Promise.all(utxos.map(async (utxo) => { - return ({ + utxos.map(async (utxo) => { + return { txHash: utxo.transaction_id, outputIndex: parseInt(utxo.output_index), address: utxo.address, @@ -179,24 +180,30 @@ export class Kupmios { : null, scriptRef: utxo.script_hash && (await (async () => { - const { script, language, } = await fetch(`${this.kupoUrl}/scripts/${utxo.script_hash}`).then((res) => res.json()); + const { script, language } = await fetch(`${this.kupoUrl}/scripts/${utxo.script_hash}`).then((res) => res.json()); if (language === "native") { return { type: "Native", script }; } else if (language === "plutus:v1") { + const plutusScript = C.PlutusScript.new(fromHex(script)); + const scriptBytes = plutusScript.to_bytes(); + plutusScript.free(); return { type: "PlutusV1", - script: toHex(C.PlutusScript.new(fromHex(script)).to_bytes()), + script: toHex(scriptBytes), }; } else if (language === "plutus:v2") { + const plutusScript = C.PlutusScript.new(fromHex(script)); + const scriptBytes = plutusScript.to_bytes(); + plutusScript.free(); return { type: "PlutusV2", - script: toHex(C.PlutusScript.new(fromHex(script)).to_bytes()), + script: toHex(scriptBytes), }; } })()), - }); + }; })); } async ogmiosWsp(methodname, args) { diff --git a/dist/esm/src/provider/maestro.js b/dist/esm/src/provider/maestro.js index f694b564..35ebf96e 100644 --- a/dist/esm/src/provider/maestro.js +++ b/dist/esm/src/provider/maestro.js @@ -33,12 +33,15 @@ export class Maestro { // Decimal numbers in Maestro are given as ratio of two numbers represented by string of format "firstNumber/secondNumber". const decimalFromRationalString = (str) => { const forwardSlashIndex = str.indexOf("/"); - return parseInt(str.slice(0, forwardSlashIndex)) / parseInt(str.slice(forwardSlashIndex + 1)); + return (parseInt(str.slice(0, forwardSlashIndex)) / + parseInt(str.slice(forwardSlashIndex + 1))); }; // To rename keys in an object by the given key-map. // deno-lint-ignore no-explicit-any const renameKeysAndSort = (obj, newKeys) => { - const entries = Object.keys(obj).sort().map((key) => { + const entries = Object.keys(obj) + .sort() + .map((key) => { const newKey = newKeys[key] || key; return { [newKey]: Object.fromEntries(Object.entries(obj[key]).sort(([k, _v], [k2, _v2]) => k.localeCompare(k2))), @@ -66,70 +69,70 @@ export class Maestro { }), }; } - async getUtxos(addressOrCredential) { + async getUtxosInternal(addressOrCredential, unit) { const queryPredicate = (() => { - if (typeof addressOrCredential === "string") + if (typeof addressOrCredential === "string") { return "/addresses/" + addressOrCredential; + } + const hash = addressOrCredential.type == "Key" + ? C.Ed25519KeyHash.from_hex(addressOrCredential.hash) + : C.ScriptHash.from_hex(addressOrCredential.hash); let credentialBech32Query = "/addresses/cred/"; - credentialBech32Query += addressOrCredential.type === "Key" - ? C.Ed25519KeyHash.from_hex(addressOrCredential.hash).to_bech32("addr_vkh") - : C.ScriptHash.from_hex(addressOrCredential.hash).to_bech32("addr_shared_vkh"); + credentialBech32Query += + addressOrCredential.type === "Key" + ? hash.to_bech32("addr_vkh") + : hash.to_bech32("addr_shared_vkh"); + hash.free(); return credentialBech32Query; })(); - let result = []; - let nextCursor = null; - while (true) { - const appendCursorString = nextCursor === null ? "" : `&cursor=${nextCursor}`; - const response = await fetch(`${this.url}${queryPredicate}/utxos?count=100${appendCursorString}`, { headers: this.commonHeaders() }); - const pageResult = await response.json(); - if (!response.ok) { - throw new Error("Could not fetch UTxOs from Maestro. Received status code: " + response.status); - } - nextCursor = pageResult.next_cursor; - result = result.concat(pageResult.data); - if (nextCursor == null) - break; - } + const qparams = new URLSearchParams({ + count: "100", + ...(unit && { asset: unit }), + }); + const result = await this.getAllPagesData(async (qry) => await fetch(qry, { headers: this.commonHeaders() }), `${this.url}${queryPredicate}/utxos`, qparams, "Location: getUtxosInternal. Error: Could not fetch UTxOs from Maestro"); return result.map(this.maestroUtxoToUtxo); } - async getUtxosWithUnit(addressOrCredential, unit) { - const utxos = await this.getUtxos(addressOrCredential); - return utxos.filter((utxo) => utxo.assets[unit]); + getUtxos(addressOrCredential) { + return this.getUtxosInternal(addressOrCredential); + } + getUtxosWithUnit(addressOrCredential, unit) { + return this.getUtxosInternal(addressOrCredential, unit); } async getUtxoByUnit(unit) { const timestampedAddressesResponse = await fetch(`${this.url}/assets/${unit}/addresses?count=2`, { headers: this.commonHeaders() }); const timestampedAddresses = await timestampedAddressesResponse.json(); if (!timestampedAddressesResponse.ok) { - if (timestampedAddresses.message) + if (timestampedAddresses.message) { throw new Error(timestampedAddresses.message); - throw new Error("Couldn't perform query. Received status code: " + timestampedAddressesResponse.status); + } + throw new Error("Location: getUtxoByUnit. Error: Couldn't perform query. Received status code: " + + timestampedAddressesResponse.status); } const addressesWithAmount = timestampedAddresses.data; if (addressesWithAmount.length === 0) { - throw new Error("Unit not found."); + throw new Error("Location: getUtxoByUnit. Error: Unit not found."); } if (addressesWithAmount.length > 1) { - throw new Error("Unit needs to be an NFT or only held by one address."); + throw new Error("Location: getUtxoByUnit. Error: Unit needs to be an NFT or only held by one address."); } const address = addressesWithAmount[0].address; const utxos = await this.getUtxosWithUnit(address, unit); if (utxos.length > 1) { - throw new Error("Unit needs to be an NFT or only held by one address."); + throw new Error("Location: getUtxoByUnit. Error: Unit needs to be an NFT or only held by one address."); } return utxos[0]; } async getUtxosByOutRef(outRefs) { - const response = await fetch(`${this.url}/transactions/outputs`, { + const qry = `${this.url}/transactions/outputs`; + const body = JSON.stringify(outRefs.map(({ txHash, outputIndex }) => `${txHash}#${outputIndex}`)); + const utxos = await this.getAllPagesData(async (qry) => await fetch(qry, { method: "POST", headers: { - 'Content-Type': 'application/json', - ...this.commonHeaders() + "Content-Type": "application/json", + ...this.commonHeaders(), }, - body: JSON.stringify(outRefs.map(({ txHash, outputIndex }) => `${txHash}#${outputIndex}`)), - }); - if (!response.ok) - return []; - const utxos = (await response.json()).data; + body: body, + }), qry, new URLSearchParams({}), "Location: getUtxosByOutRef. Error: Could not fetch UTxOs by references from Maestro"); return utxos.map(this.maestroUtxoToUtxo); } async getDelegation(rewardAddress) { @@ -149,10 +152,13 @@ export class Maestro { headers: this.commonHeaders(), }); if (!timestampedResultResponse.ok) { - if (timestampedResultResponse.status === 404) + if (timestampedResultResponse.status === 404) { throw new Error(`No datum found for datum hash: ${datumHash}`); - else - throw new Error("Couldn't successfully perform query. Received status code: " + timestampedResultResponse.status); + } + else { + throw new Error("Location: getDatum. Error: Couldn't successfully perform query. Received status code: " + + timestampedResultResponse.status); + } } const timestampedResult = await timestampedResultResponse.json(); return timestampedResult.data.bytes; @@ -174,12 +180,12 @@ export class Maestro { } async submitTx(tx) { let queryUrl = `${this.url}/txmanager`; - queryUrl += this.turboSubmit ? '/turbosubmit' : ''; + queryUrl += this.turboSubmit ? "/turbosubmit" : ""; const response = await fetch(queryUrl, { method: "POST", headers: { "Content-Type": "application/cbor", - "Accept": "text/plain", + Accept: "text/plain", ...this.commonHeaders(), }, body: fromHex(tx), @@ -188,8 +194,10 @@ export class Maestro { if (!response.ok) { if (response.status === 400) throw new Error(result); - else - throw new Error("Could not submit transaction. Received status code: " + response.status); + else { + throw new Error("Could not submit transaction. Received status code: " + + response.status); + } } return result; } @@ -209,18 +217,41 @@ export class Maestro { })(), address: result.address, datumHash: result.datum - ? result.datum.type == "inline" ? undefined : result.datum.hash + ? result.datum.type == "inline" + ? undefined + : result.datum.hash : undefined, datum: result.datum?.bytes, scriptRef: result.reference_script - ? result.reference_script.type == "native" ? undefined : { - type: result.reference_script.type == "plutusv1" - ? "PlutusV1" - : "PlutusV2", - script: applyDoubleCborEncoding(result.reference_script.bytes), - } + ? result.reference_script.type == "native" + ? undefined + : { + type: result.reference_script.type == "plutusv1" + ? "PlutusV1" + : "PlutusV2", + script: applyDoubleCborEncoding(result.reference_script.bytes), + } : undefined, }; } + async getAllPagesData(getResponse, qry, paramsGiven, errorMsg) { + let nextCursor = null; + let result = []; + while (true) { + if (nextCursor !== null) { + paramsGiven.set("cursor", nextCursor); + } + const response = await getResponse(`${qry}?` + paramsGiven); + const pageResult = await response.json(); + if (!response.ok) { + throw new Error(`${errorMsg}. Received status code: ${response.status}`); + } + nextCursor = pageResult.next_cursor; + result = result.concat(pageResult.data); + if (nextCursor == null) + break; + } + return result; + } } const lucid = packageJson.version; // Lucid version diff --git a/dist/esm/src/utils/cml.js b/dist/esm/src/utils/cml.js new file mode 100644 index 00000000..a349c23c --- /dev/null +++ b/dist/esm/src/utils/cml.js @@ -0,0 +1,201 @@ +import { C, applyDoubleCborEncoding, assetsToValue, fromHex, networkToId, toScriptRef, } from "../mod.js"; +import { Freeables } from "./freeable.js"; +export function getScriptWitness(redeemer, datum) { + const bucket = []; + try { + const plutusRedeemer = C.PlutusData.from_bytes(fromHex(redeemer)); + const plutusData = datum + ? C.PlutusData.from_bytes(fromHex(datum)) + : undefined; + const plutusWitness = C.PlutusWitness.new(plutusRedeemer, plutusData, undefined); + // We shouldn't free plutusData as it is an Option + bucket.push(plutusRedeemer, plutusWitness); + return C.ScriptWitness.new_plutus_witness(plutusWitness); + } + finally { + Freeables.free(...bucket); + } +} +export function getStakeCredential(hash, type) { + if (type === "Key") { + const keyHash = C.Ed25519KeyHash.from_bytes(fromHex(hash)); + const credential = C.StakeCredential.from_keyhash(keyHash); + Freeables.free(keyHash); + return credential; + } + const scriptHash = C.ScriptHash.from_bytes(fromHex(hash)); + const credential = C.StakeCredential.from_scripthash(scriptHash); + Freeables.free(scriptHash); + return credential; +} +export async function createPoolRegistration(poolParams, lucid) { + const bucket = []; + try { + const poolOwners = C.Ed25519KeyHashes.new(); + bucket.push(poolOwners); + poolParams.owners.forEach((owner) => { + const { stakeCredential } = lucid.utils.getAddressDetails(owner); + if (stakeCredential?.type === "Key") { + const keyHash = C.Ed25519KeyHash.from_hex(stakeCredential.hash); + poolOwners.add(keyHash); + bucket.push(keyHash); + } + else + throw new Error("Only key hashes allowed for pool owners."); + }); + const metadata = poolParams.metadataUrl + ? await fetch(poolParams.metadataUrl).then((res) => res.arrayBuffer()) + : null; + const metadataHash = metadata + ? C.PoolMetadataHash.from_bytes(C.hash_blake2b256(new Uint8Array(metadata))) + : null; + const relays = C.Relays.new(); + bucket.push(metadataHash, relays); + poolParams.relays.forEach((relay) => { + switch (relay.type) { + case "SingleHostIp": { + const ipV4 = relay.ipV4 + ? C.Ipv4.new(new Uint8Array(relay.ipV4.split(".").map((b) => parseInt(b)))) + : undefined; + const ipV6 = relay.ipV6 + ? C.Ipv6.new(fromHex(relay.ipV6.replaceAll(":", ""))) + : undefined; + const host = C.SingleHostAddr.new(relay.port, ipV4, ipV6); + const newRelay = C.Relay.new_single_host_addr(host); + //We shouldn't free ipV4 and ipV6 as they are optionals + bucket.push(host, newRelay); + relays.add(newRelay); + break; + } + case "SingleHostDomainName": { + const record = C.DNSRecordAorAAAA.new(relay.domainName); + const host = C.SingleHostName.new(relay.port, record); + const newRelay = C.Relay.new_single_host_name(host); + bucket.push(record, host, newRelay); + relays.add(newRelay); + break; + } + case "MultiHost": { + const record = C.DNSRecordSRV.new(relay.domainName); + const host = C.MultiHostName.new(record); + const newRelay = C.Relay.new_multi_host_name(host); + bucket.push(record, host, newRelay); + relays.add(newRelay); + break; + } + } + }); + const operator = C.Ed25519KeyHash.from_bech32(poolParams.poolId); + const vrfKeyHash = C.VRFKeyHash.from_hex(poolParams.vrfKeyHash); + const pledge = C.BigNum.from_str(poolParams.pledge.toString()); + const cost = C.BigNum.from_str(poolParams.cost.toString()); + const margin = C.UnitInterval.from_float(poolParams.margin); + const addr = addressFromWithNetworkCheck(poolParams.rewardAddress, lucid); + const rewardAddress = C.RewardAddress.from_address(addr); + const url = C.Url.new(poolParams.metadataUrl); + const poolMetadata = metadataHash + ? C.PoolMetadata.new(url, metadataHash) + : undefined; + bucket.push(operator, vrfKeyHash, pledge, cost, margin, addr, rewardAddress, url, poolMetadata); + const params = C.PoolParams.new(operator, vrfKeyHash, pledge, cost, margin, rewardAddress, poolOwners, relays, poolMetadata); + const poolRegistration = C.PoolRegistration.new(params); + return poolRegistration; + } + finally { + Freeables.free(...bucket); + } +} +export function attachScript(tx, { type, script, }) { + if (type === "Native") { + const nativeScript = C.NativeScript.from_bytes(fromHex(script)); + tx.txBuilder.add_native_script(nativeScript); + Freeables.free(nativeScript); + return; + } + else if (type === "PlutusV1") { + const plutusScript = C.PlutusScript.from_bytes(fromHex(applyDoubleCborEncoding(script))); + tx.txBuilder.add_plutus_script(plutusScript); + Freeables.free(plutusScript); + return; + } + else if (type === "PlutusV2") { + const plutusScript = C.PlutusScript.from_bytes(fromHex(applyDoubleCborEncoding(script))); + tx.txBuilder.add_plutus_v2_script(plutusScript); + Freeables.free(plutusScript); + return; + } + throw new Error("No variant matched."); +} +export function addressFromWithNetworkCheck(address, lucid) { + const { type, networkId } = lucid.utils.getAddressDetails(address); + const actualNetworkId = networkToId(lucid.network); + if (networkId !== actualNetworkId) { + throw new Error(`Invalid address: Expected address with network id ${actualNetworkId}, but got ${networkId}`); + } + if (type === "Byron") { + const byron = C.ByronAddress.from_base58(address); + const addr = byron.to_address(); + byron.free(); + return addr; + } + return C.Address.from_bech32(address); +} +export function getDatumFromOutputData(outputData) { + if (outputData?.hash) { + const hash = C.DataHash.from_hex(outputData.hash); + const datum = C.Datum.new_data_hash(hash); + hash.free(); + return { datum }; + } + else if (outputData?.asHash) { + const plutusData = C.PlutusData.from_bytes(fromHex(outputData.asHash)); + const dataHash = C.hash_plutus_data(plutusData); + const datum = C.Datum.new_data_hash(dataHash); + dataHash.free(); + return { plutusData, datum }; + } + else if (outputData?.inline) { + const plutusData = C.PlutusData.from_bytes(fromHex(outputData.inline)); + const data = C.Data.new(plutusData); + const datum = C.Datum.new_data(data); + Freeables.free(plutusData, data); + return { datum }; + } + else { + return {}; + } +} +export function createOutput({ bucket, address, assets, outputData, lucid, txBuilder, }) { + const addr = addressFromWithNetworkCheck(address, lucid); + const value = assetsToValue(assets); + const output = C.TransactionOutput.new(addr, value); + bucket.push(output, addr, value); + if (outputData.hash) { + const dataHash = C.DataHash.from_hex(outputData.hash); + const datum = C.Datum.new_data_hash(dataHash); + bucket.push(dataHash, datum); + output.set_datum(datum); + } + else if (outputData.asHash) { + const plutusData = C.PlutusData.from_bytes(fromHex(outputData.asHash)); + const dataHash = C.hash_plutus_data(plutusData); + const datum = C.Datum.new_data_hash(dataHash); + bucket.push(plutusData, dataHash, datum); + output.set_datum(datum); + txBuilder.add_plutus_data(plutusData); + } + else if (outputData.inline) { + const plutusData = C.PlutusData.from_bytes(fromHex(outputData.inline)); + const data = C.Data.new(plutusData); + const datum = C.Datum.new_data(data); + bucket.push(plutusData, data, datum); + output.set_datum(datum); + } + const script = outputData.scriptRef; + if (script) { + const scriptRef = toScriptRef(script); + bucket.push(scriptRef); + output.set_script_ref(toScriptRef(script)); + } + return output; +} diff --git a/dist/esm/src/utils/cost_model.js b/dist/esm/src/utils/cost_model.js index e394c1be..d3bf4945 100644 --- a/dist/esm/src/utils/cost_model.js +++ b/dist/esm/src/utils/cost_model.js @@ -1,19 +1,40 @@ import { C } from "../core/mod.js"; +import { Freeables } from "./freeable.js"; export function createCostModels(costModels) { - const costmdls = C.Costmdls.new(); - // add plutus v1 - const costmdlV1 = C.CostModel.new(); - Object.values(costModels.PlutusV1).forEach((cost, index) => { - costmdlV1.set(index, C.Int.new(C.BigNum.from_str(cost.toString()))); - }); - costmdls.insert(C.Language.new_plutus_v1(), costmdlV1); - // add plutus v2 - const costmdlV2 = C.CostModel.new_plutus_v2(); - Object.values(costModels.PlutusV2 || []).forEach((cost, index) => { - costmdlV2.set(index, C.Int.new(C.BigNum.from_str(cost.toString()))); - }); - costmdls.insert(C.Language.new_plutus_v2(), costmdlV2); - return costmdls; + const bucket = []; + try { + const costmdls = C.Costmdls.new(); + // add plutus v1 + const costmdlV1 = C.CostModel.new(); + bucket.push(costmdlV1); + Object.values(costModels.PlutusV1).forEach((cost, index) => { + const bigNumVal = C.BigNum.from_str(cost.toString()); + bucket.push(bigNumVal); + const intVal = C.Int.new(bigNumVal); + bucket.push(intVal); + costmdlV1.set(index, intVal); + }); + const plutusV1 = C.Language.new_plutus_v1(); + bucket.push(plutusV1); + costmdls.insert(plutusV1, costmdlV1); + // add plutus v2 + const costmdlV2 = C.CostModel.new_plutus_v2(); + bucket.push(costmdlV2); + Object.values(costModels.PlutusV2 || []).forEach((cost, index) => { + const bigNumVal = C.BigNum.from_str(cost.toString()); + bucket.push(bigNumVal); + const intVal = C.Int.new(bigNumVal); + bucket.push(intVal); + costmdlV2.set(index, intVal); + }); + const plutusV2 = C.Language.new_plutus_v2(); + bucket.push(plutusV2); + costmdls.insert(plutusV2, costmdlV2); + return costmdls; + } + finally { + Freeables.free(...bucket); + } } export const PROTOCOL_PARAMETERS_DEFAULT = { minFeeA: 44, diff --git a/dist/esm/src/utils/freeable.js b/dist/esm/src/utils/freeable.js new file mode 100644 index 00000000..3bcb2fc5 --- /dev/null +++ b/dist/esm/src/utils/freeable.js @@ -0,0 +1,25 @@ +/** + * These types and classes are used to help with freeing memory. + * Objects passed from the WASM to JS (Objects from Rust libraries, for example) are not freed automatically, or at least inconsistently. + * This can lead to memory leaks. + * In order to free these objects, we need to call the `free()` method on them. These types make it easier. + */ +/** This class makes it easier to free large sets of memory. It can be used like this: + * ```ts + * const bucket: FreeableBucket = []; + * try { + * const rustObject = C.some_rust_object(); + * bucket.push(rustObject); + * ... + * } finally { + * Freeables.free(...bucket); + * } + * ``` + */ +export class Freeables { + static free(...bucket) { + bucket.forEach((freeable) => { + freeable?.free(); + }); + } +} diff --git a/dist/esm/src/utils/mod.js b/dist/esm/src/utils/mod.js index 8e127d1d..04fe4189 100644 --- a/dist/esm/src/utils/mod.js +++ b/dist/esm/src/utils/mod.js @@ -1,3 +1,5 @@ export * from "./cost_model.js"; export * from "./utils.js"; export * from "./merkle_tree.js"; +export * from "./cml.js"; +export * from "./freeable.js"; diff --git a/dist/esm/src/utils/transaction_builder_config.js b/dist/esm/src/utils/transaction_builder_config.js new file mode 100644 index 00000000..3354eb14 --- /dev/null +++ b/dist/esm/src/utils/transaction_builder_config.js @@ -0,0 +1,64 @@ +import { C } from "../mod.js"; +import { createCostModels } from "./cost_model.js"; +import { Freeables } from "./freeable.js"; +export function getTransactionBuilderConfig(protocolParameters, slotConfig, blockfrostConfig) { + const bucket = []; + let builderA = C.TransactionBuilderConfigBuilder.new(); + const coinsPerUtxoByte = C.BigNum.from_str(protocolParameters.coinsPerUtxoByte.toString()); + bucket.push(coinsPerUtxoByte); + let builderB = builderA.coins_per_utxo_byte(coinsPerUtxoByte); + builderA.free(); + const minFeeA = C.BigNum.from_str(protocolParameters.minFeeA.toString()); + bucket.push(minFeeA); + const minFeeB = C.BigNum.from_str(protocolParameters.minFeeB.toString()); + bucket.push(minFeeB); + const linearFee = C.LinearFee.new(minFeeA, minFeeB); + bucket.push(linearFee); + builderA = builderB.fee_algo(linearFee); + builderB.free(); + const keyDeposit = C.BigNum.from_str(protocolParameters.keyDeposit.toString()); + bucket.push(keyDeposit); + builderB = builderA.key_deposit(keyDeposit); + builderA.free(); + const poolDeposit = C.BigNum.from_str(protocolParameters.poolDeposit.toString()); + bucket.push(poolDeposit); + builderA = builderB.pool_deposit(poolDeposit); + builderB.free(); + builderB = builderA.max_tx_size(protocolParameters.maxTxSize); + builderA.free(); + builderA = builderB.max_value_size(protocolParameters.maxValSize); + builderB.free(); + builderB = builderA.collateral_percentage(protocolParameters.collateralPercentage); + builderA.free(); + builderA = builderB.max_collateral_inputs(protocolParameters.maxCollateralInputs); + builderB.free(); + const maxTxExMem = C.BigNum.from_str(protocolParameters.maxTxExMem.toString()); + bucket.push(maxTxExMem); + const maxTxExSteps = C.BigNum.from_str(protocolParameters.maxTxExSteps.toString()); + bucket.push(maxTxExSteps); + const exUnits = C.ExUnits.new(maxTxExMem, maxTxExSteps); + bucket.push(exUnits); + builderB = builderA.max_tx_ex_units(exUnits); + builderA.free(); + const exUnitPrices = C.ExUnitPrices.from_float(protocolParameters.priceMem, protocolParameters.priceStep); + bucket.push(exUnitPrices); + builderA = builderB.ex_unit_prices(exUnitPrices); + builderB.free(); + const zeroTime = C.BigNum.from_str(slotConfig.zeroTime.toString()); + bucket.push(zeroTime); + const zeroSlot = C.BigNum.from_str(slotConfig.zeroSlot.toString()); + bucket.push(zeroSlot); + builderB = builderA.slot_config(zeroTime, zeroSlot, slotConfig.slotLength); + builderA.free(); + const blockfrost = C.Blockfrost.new(blockfrostConfig?.url ?? "" + "utils/tx/evaulate", blockfrostConfig?.projectId ?? ""); + bucket.push(blockfrost); + builderA = builderB.blockfrost(blockfrost); + builderB.free(); + const costModels = createCostModels(protocolParameters.costModels); + bucket.push(costModels); + builderB = builderA.costmdls(costModels); + const config = builderB.build(); + builderB.free(); + Freeables.free(...bucket); + return config; +} diff --git a/dist/esm/src/utils/utils.js b/dist/esm/src/utils/utils.js index 0467366e..1e4c46d1 100644 --- a/dist/esm/src/utils/utils.js +++ b/dist/esm/src/utils/utils.js @@ -4,6 +4,7 @@ import { generateMnemonic } from "../misc/bip39.js"; import { crc8 } from "../misc/crc8.js"; import { SLOT_CONFIG_NETWORK, slotToBeginUnixTime, unixTimeToEnclosingSlot, } from "../plutus/time.js"; import { Data } from "../plutus/data.js"; +import { Freeables } from "./freeable.js"; export class Utils { constructor(lucid) { Object.defineProperty(this, "lucid", { @@ -15,74 +16,188 @@ export class Utils { this.lucid = lucid; } validatorToAddress(validator, stakeCredential) { - const validatorHash = this.validatorToScriptHash(validator); - if (stakeCredential) { - return C.BaseAddress.new(networkToId(this.lucid.network), C.StakeCredential.from_scripthash(C.ScriptHash.from_hex(validatorHash)), stakeCredential.type === "Key" - ? C.StakeCredential.from_keyhash(C.Ed25519KeyHash.from_hex(stakeCredential.hash)) - : C.StakeCredential.from_scripthash(C.ScriptHash.from_hex(stakeCredential.hash))) - .to_address() - .to_bech32(undefined); + const bucket = []; + const networkId = networkToId(this.lucid.network); + try { + const validatorHash = this.validatorToScriptHash(validator); + if (stakeCredential) { + const validatorScriptHash = C.ScriptHash.from_hex(validatorHash); + bucket.push(validatorScriptHash); + const paymentPart = C.StakeCredential.from_scripthash(validatorScriptHash); + bucket.push(paymentPart); + let stakePart; + if (stakeCredential.type === "Key") { + const keyHash = C.Ed25519KeyHash.from_hex(stakeCredential.hash); + stakePart = C.StakeCredential.from_keyhash(keyHash); + keyHash.free(); + } + else { + const scriptHash = C.ScriptHash.from_hex(stakeCredential.hash); + stakePart = C.StakeCredential.from_scripthash(scriptHash); + scriptHash.free(); + } + bucket.push(stakePart); + const baseAddress = C.BaseAddress.new(networkId, paymentPart, stakePart); + bucket.push(baseAddress); + const address = baseAddress.to_address(); + bucket.push(address); + return address.to_bech32(undefined); + } + else { + const validatorScriptHash = C.ScriptHash.from_hex(validatorHash); + bucket.push(validatorScriptHash); + const paymentPart = C.StakeCredential.from_scripthash(validatorScriptHash); + bucket.push(paymentPart); + const enterpriseAddress = C.EnterpriseAddress.new(networkId, paymentPart); + bucket.push(enterpriseAddress); + const address = enterpriseAddress.to_address(); + bucket.push(address); + return address.to_bech32(undefined); + } } - else { - return C.EnterpriseAddress.new(networkToId(this.lucid.network), C.StakeCredential.from_scripthash(C.ScriptHash.from_hex(validatorHash))) - .to_address() - .to_bech32(undefined); + finally { + Freeables.free(...bucket); } } credentialToAddress(paymentCredential, stakeCredential) { - if (stakeCredential) { - return C.BaseAddress.new(networkToId(this.lucid.network), paymentCredential.type === "Key" - ? C.StakeCredential.from_keyhash(C.Ed25519KeyHash.from_hex(paymentCredential.hash)) - : C.StakeCredential.from_scripthash(C.ScriptHash.from_hex(paymentCredential.hash)), stakeCredential.type === "Key" - ? C.StakeCredential.from_keyhash(C.Ed25519KeyHash.from_hex(stakeCredential.hash)) - : C.StakeCredential.from_scripthash(C.ScriptHash.from_hex(stakeCredential.hash))) - .to_address() - .to_bech32(undefined); + const networkId = networkToId(this.lucid.network); + const bucket = []; + try { + if (stakeCredential) { + let paymentPart; + let stakePart; + if (paymentCredential.type === "Key") { + const keyHash = C.Ed25519KeyHash.from_hex(paymentCredential.hash); + bucket.push(keyHash); + paymentPart = C.StakeCredential.from_keyhash(keyHash); + } + else { + const scriptHash = C.ScriptHash.from_hex(paymentCredential.hash); + bucket.push(scriptHash); + paymentPart = C.StakeCredential.from_scripthash(scriptHash); + } + bucket.push(paymentPart); + if (stakeCredential.type === "Key") { + const keyHash = C.Ed25519KeyHash.from_hex(stakeCredential.hash); + bucket.push(keyHash); + stakePart = C.StakeCredential.from_keyhash(keyHash); + } + else { + const scriptHash = C.ScriptHash.from_hex(stakeCredential.hash); + bucket.push(scriptHash); + stakePart = C.StakeCredential.from_scripthash(scriptHash); + } + bucket.push(stakePart); + const baseAddress = C.BaseAddress.new(networkId, paymentPart, stakePart); + bucket.push(baseAddress); + const address = baseAddress.to_address(); + bucket.push(address); + return address.to_bech32(undefined); + } + else { + let paymentPart; + if (paymentCredential.type === "Key") { + const keyHash = C.Ed25519KeyHash.from_hex(paymentCredential.hash); + bucket.push(keyHash); + paymentPart = C.StakeCredential.from_keyhash(keyHash); + } + else { + const scriptHash = C.ScriptHash.from_hex(paymentCredential.hash); + bucket.push(scriptHash); + paymentPart = C.StakeCredential.from_scripthash(scriptHash); + } + bucket.push(paymentPart); + const enterpriseAddress = C.EnterpriseAddress.new(networkId, paymentPart); + bucket.push(enterpriseAddress); + const address = enterpriseAddress.to_address(); + bucket.push(address); + return address.to_bech32(undefined); + } } - else { - return C.EnterpriseAddress.new(networkToId(this.lucid.network), paymentCredential.type === "Key" - ? C.StakeCredential.from_keyhash(C.Ed25519KeyHash.from_hex(paymentCredential.hash)) - : C.StakeCredential.from_scripthash(C.ScriptHash.from_hex(paymentCredential.hash))) - .to_address() - .to_bech32(undefined); + finally { + Freeables.free(...bucket); } } validatorToRewardAddress(validator) { + const bucket = []; const validatorHash = this.validatorToScriptHash(validator); - return C.RewardAddress.new(networkToId(this.lucid.network), C.StakeCredential.from_scripthash(C.ScriptHash.from_hex(validatorHash))) - .to_address() - .to_bech32(undefined); + const scriptHash = C.ScriptHash.from_hex(validatorHash); + bucket.push(scriptHash); + const stakePart = C.StakeCredential.from_scripthash(scriptHash); + bucket.push(stakePart); + const rewardAddress = C.RewardAddress.new(networkToId(this.lucid.network), stakePart); + bucket.push(rewardAddress); + const address = rewardAddress.to_address(); + bucket.push(address); + const bech32 = address.to_bech32(undefined); + Freeables.free(...bucket); + return bech32; } credentialToRewardAddress(stakeCredential) { - return C.RewardAddress.new(networkToId(this.lucid.network), stakeCredential.type === "Key" - ? C.StakeCredential.from_keyhash(C.Ed25519KeyHash.from_hex(stakeCredential.hash)) - : C.StakeCredential.from_scripthash(C.ScriptHash.from_hex(stakeCredential.hash))) - .to_address() - .to_bech32(undefined); + const bucket = []; + let stakePart; + if (stakeCredential.type === "Key") { + const keyHash = C.Ed25519KeyHash.from_hex(stakeCredential.hash); + bucket.push(keyHash); + stakePart = C.StakeCredential.from_keyhash(keyHash); + } + else { + const scriptHash = C.ScriptHash.from_hex(stakeCredential.hash); + bucket.push(scriptHash); + stakePart = C.StakeCredential.from_scripthash(scriptHash); + } + bucket.push(stakePart); + const rewardAddress = C.RewardAddress.new(networkToId(this.lucid.network), stakePart); + bucket.push(rewardAddress); + const address = rewardAddress.to_address(); + bucket.push(address); + const bech32 = address.to_bech32(undefined); + Freeables.free(...bucket); + return bech32; } validatorToScriptHash(validator) { - switch (validator.type) { - case "Native": - return C.NativeScript.from_bytes(fromHex(validator.script)) - .hash(C.ScriptHashNamespace.NativeScript) - .to_hex(); - case "PlutusV1": - return C.PlutusScript.from_bytes(fromHex(applyDoubleCborEncoding(validator.script))) - .hash(C.ScriptHashNamespace.PlutusV1) - .to_hex(); - case "PlutusV2": - return C.PlutusScript.from_bytes(fromHex(applyDoubleCborEncoding(validator.script))) - .hash(C.ScriptHashNamespace.PlutusV2) - .to_hex(); - default: - throw new Error("No variant matched"); + const bucket = []; + try { + switch (validator.type) { + case "Native": { + const nativeScript = C.NativeScript.from_bytes(fromHex(validator.script)); + bucket.push(nativeScript); + const hash = nativeScript.hash(C.ScriptHashNamespace.NativeScript); + bucket.push(hash); + return hash.to_hex(); + } + case "PlutusV1": { + const plutusScript = C.PlutusScript.from_bytes(fromHex(applyDoubleCborEncoding(validator.script))); + bucket.push(plutusScript); + const hash = plutusScript.hash(C.ScriptHashNamespace.PlutusV1); + bucket.push(hash); + return hash.to_hex(); + } + case "PlutusV2": { + const plutusScript = C.PlutusScript.from_bytes(fromHex(applyDoubleCborEncoding(validator.script))); + bucket.push(plutusScript); + const hash = plutusScript.hash(C.ScriptHashNamespace.PlutusV2); + bucket.push(hash); + return hash.to_hex(); + } + default: + throw new Error("No variant matched"); + } + } + finally { + Freeables.free(...bucket); } } mintingPolicyToId(mintingPolicy) { return this.validatorToScriptHash(mintingPolicy); } datumToHash(datum) { - return C.hash_plutus_data(C.PlutusData.from_bytes(fromHex(datum))).to_hex(); + const plutusData = C.PlutusData.from_bytes(fromHex(datum)); + const hash = C.hash_plutus_data(plutusData); + plutusData.free(); + const datumHash = hash.to_hex(); + hash.free(); + return datumHash; } scriptHashToCredential(scriptHash) { return { @@ -145,142 +260,224 @@ function addressFromHexOrBech32(address) { } /** Address can be in Bech32 or Hex. */ export function getAddressDetails(address) { - // Base Address + const bucket = []; + // wrapped in an outer try to ensure that memory is freed try { - const parsedAddress = C.BaseAddress.from_address(addressFromHexOrBech32(address)); - const paymentCredential = parsedAddress.payment_cred().kind() === 0 - ? { - type: "Key", - hash: toHex(parsedAddress.payment_cred().to_keyhash().to_bytes()), + // Base Address + try { + const parsedAddress = addressFromHexOrBech32(address); + bucket.push(parsedAddress); + const baseAddress = C.BaseAddress.from_address(parsedAddress); + bucket.push(baseAddress); + let paymentCredential; + const paymentCred = baseAddress.payment_cred(); + bucket.push(paymentCred); + if (paymentCred.kind() === 0) { + const keyHash = paymentCred.to_keyhash(); + bucket.push(keyHash); + paymentCredential = { + type: "Key", + hash: toHex(keyHash.to_bytes()), + }; } - : { - type: "Script", - hash: toHex(parsedAddress.payment_cred().to_scripthash().to_bytes()), - }; - const stakeCredential = parsedAddress.stake_cred().kind() === 0 - ? { - type: "Key", - hash: toHex(parsedAddress.stake_cred().to_keyhash().to_bytes()), + else { + const scriptHash = paymentCred.to_scripthash(); + bucket.push(scriptHash); + paymentCredential = { + type: "Script", + hash: toHex(scriptHash.to_bytes()), + }; } - : { - type: "Script", - hash: toHex(parsedAddress.stake_cred().to_scripthash().to_bytes()), - }; - return { - type: "Base", - networkId: parsedAddress.to_address().network_id(), - address: { - bech32: parsedAddress.to_address().to_bech32(undefined), - hex: toHex(parsedAddress.to_address().to_bytes()), - }, - paymentCredential, - stakeCredential, - }; - } - catch (_e) { - /* pass */ - } - // Enterprise Address - try { - const parsedAddress = C.EnterpriseAddress.from_address(addressFromHexOrBech32(address)); - const paymentCredential = parsedAddress.payment_cred().kind() === 0 - ? { - type: "Key", - hash: toHex(parsedAddress.payment_cred().to_keyhash().to_bytes()), + let stakeCredential; + const stakeCred = baseAddress.stake_cred(); + bucket.push(stakeCred); + if (stakeCred.kind() === 0) { + const keyHash = stakeCred.to_keyhash(); + bucket.push(keyHash); + stakeCredential = { + type: "Key", + hash: toHex(keyHash.to_bytes()), + }; + } + else { + const scriptHash = stakeCred.to_scripthash(); + bucket.push(scriptHash); + stakeCredential = { + type: "Script", + hash: toHex(scriptHash.to_bytes()), + }; } - : { - type: "Script", - hash: toHex(parsedAddress.payment_cred().to_scripthash().to_bytes()), + const cAddress = baseAddress.to_address(); + bucket.push(cAddress); + return { + type: "Base", + networkId: cAddress.network_id(), + address: { + bech32: cAddress.to_bech32(undefined), + hex: toHex(cAddress.to_bytes()), + }, + paymentCredential, + stakeCredential, }; - return { - type: "Enterprise", - networkId: parsedAddress.to_address().network_id(), - address: { - bech32: parsedAddress.to_address().to_bech32(undefined), - hex: toHex(parsedAddress.to_address().to_bytes()), - }, - paymentCredential, - }; - } - catch (_e) { - /* pass */ - } - // Pointer Address - try { - const parsedAddress = C.PointerAddress.from_address(addressFromHexOrBech32(address)); - const paymentCredential = parsedAddress.payment_cred().kind() === 0 - ? { - type: "Key", - hash: toHex(parsedAddress.payment_cred().to_keyhash().to_bytes()), + } + catch (_e) { + /* pass */ + } + // Enterprise Address + try { + const parsedAddress = addressFromHexOrBech32(address); + bucket.push(parsedAddress); + const enterpriseAddress = C.EnterpriseAddress.from_address(parsedAddress); + bucket.push(enterpriseAddress); + let paymentCredential; + const paymentCred = enterpriseAddress.payment_cred(); + bucket.push(paymentCred); + if (paymentCred.kind() === 0) { + const keyHash = paymentCred.to_keyhash(); + bucket.push(keyHash); + paymentCredential = { + type: "Key", + hash: toHex(keyHash.to_bytes()), + }; + } + else { + const scriptHash = paymentCred.to_scripthash(); + bucket.push(scriptHash); + paymentCredential = { + type: "Script", + hash: toHex(scriptHash.to_bytes()), + }; } - : { - type: "Script", - hash: toHex(parsedAddress.payment_cred().to_scripthash().to_bytes()), + const cAddress = enterpriseAddress.to_address(); + bucket.push(cAddress); + return { + type: "Enterprise", + networkId: cAddress.network_id(), + address: { + bech32: cAddress.to_bech32(undefined), + hex: toHex(cAddress.to_bytes()), + }, + paymentCredential, }; - return { - type: "Pointer", - networkId: parsedAddress.to_address().network_id(), - address: { - bech32: parsedAddress.to_address().to_bech32(undefined), - hex: toHex(parsedAddress.to_address().to_bytes()), - }, - paymentCredential, - }; - } - catch (_e) { - /* pass */ - } - // Reward Address - try { - const parsedAddress = C.RewardAddress.from_address(addressFromHexOrBech32(address)); - const stakeCredential = parsedAddress.payment_cred().kind() === 0 - ? { - type: "Key", - hash: toHex(parsedAddress.payment_cred().to_keyhash().to_bytes()), + } + catch (_e) { + /* pass */ + } + // Pointer Address + try { + const parsedAddress = addressFromHexOrBech32(address); + bucket.push(parsedAddress); + const pointerAddress = C.PointerAddress.from_address(parsedAddress); + bucket.push(pointerAddress); + let paymentCredential; + const paymentCred = pointerAddress.payment_cred(); + bucket.push(paymentCred); + if (paymentCred.kind() === 0) { + const keyHash = paymentCred.to_keyhash(); + bucket.push(keyHash); + paymentCredential = { + type: "Key", + hash: toHex(keyHash.to_bytes()), + }; } - : { - type: "Script", - hash: toHex(parsedAddress.payment_cred().to_scripthash().to_bytes()), + else { + const scriptHash = paymentCred.to_scripthash(); + bucket.push(scriptHash); + paymentCredential = { + type: "Script", + hash: toHex(scriptHash.to_bytes()), + }; + } + const cAddress = pointerAddress.to_address(); + bucket.push(cAddress); + return { + type: "Pointer", + networkId: cAddress.network_id(), + address: { + bech32: cAddress.to_bech32(undefined), + hex: toHex(cAddress.to_bytes()), + }, + paymentCredential, }; - return { - type: "Reward", - networkId: parsedAddress.to_address().network_id(), - address: { - bech32: parsedAddress.to_address().to_bech32(undefined), - hex: toHex(parsedAddress.to_address().to_bytes()), - }, - stakeCredential, - }; - } - catch (_e) { - /* pass */ - } - // Limited support for Byron addresses - try { - const parsedAddress = ((address) => { - try { - return C.ByronAddress.from_bytes(fromHex(address)); + } + catch (_e) { + /* pass */ + } + // Reward Address + try { + const parsedAddress = addressFromHexOrBech32(address); + bucket.push(parsedAddress); + const rewardAddress = C.RewardAddress.from_address(parsedAddress); + bucket.push(rewardAddress); + let stakeCredential; + const paymentCred = rewardAddress.payment_cred(); + bucket.push(paymentCred); + if (paymentCred.kind() === 0) { + const keyHash = paymentCred.to_keyhash(); + bucket.push(keyHash); + stakeCredential = { + type: "Key", + hash: toHex(keyHash.to_bytes()), + }; } - catch (_e) { + else { + const scriptHash = paymentCred.to_scripthash(); + bucket.push(scriptHash); + stakeCredential = { + type: "Script", + hash: toHex(scriptHash.to_bytes()), + }; + } + const cAddress = rewardAddress.to_address(); + bucket.push(cAddress); + return { + type: "Reward", + networkId: cAddress.network_id(), + address: { + bech32: cAddress.to_bech32(undefined), + hex: toHex(cAddress.to_bytes()), + }, + stakeCredential, + }; + } + catch (_e) { + /* pass */ + } + // Limited support for Byron addresses + try { + const parsedAddress = ((address) => { try { - return C.ByronAddress.from_base58(address); + return C.ByronAddress.from_bytes(fromHex(address)); } catch (_e) { - throw new Error("Could not deserialize address."); + try { + return C.ByronAddress.from_base58(address); + } + catch (_e) { + throw new Error("Could not deserialize address."); + } } - } - })(address); - return { - type: "Byron", - networkId: parsedAddress.network_id(), - address: { - bech32: "", - hex: toHex(parsedAddress.to_address().to_bytes()), - }, - }; + })(address); + bucket.push(parsedAddress); + const cAddress = parsedAddress.to_address(); + bucket.push(cAddress); + return { + type: "Byron", + networkId: parsedAddress.network_id(), + address: { + bech32: "", + hex: toHex(cAddress.to_bytes()), + }, + }; + } + catch (_e) { + /* pass */ + } + throw new Error("No address type matched for: " + address); + } + finally { + Freeables.free(...bucket); } - catch (_e) { /* pass */ } - throw new Error("No address type matched for: " + address); } export function paymentCredentialOf(address) { const { paymentCredential } = getAddressDetails(address); @@ -297,33 +494,49 @@ export function stakeCredentialOf(rewardAddress) { return stakeCredential; } export function generatePrivateKey() { - return C.PrivateKey.generate_ed25519().to_bech32(); + const ed25519 = C.PrivateKey.generate_ed25519(); + const bech32 = ed25519.to_bech32(); + ed25519.free(); + return bech32; } export function generateSeedPhrase() { return generateMnemonic(256); } export function valueToAssets(value) { + const bucket = []; const assets = {}; - assets["lovelace"] = BigInt(value.coin().to_str()); + const lovelace = value.coin(); + bucket.push(lovelace); + assets["lovelace"] = BigInt(lovelace.to_str()); const ma = value.multiasset(); + bucket.push(ma); if (ma) { const multiAssets = ma.keys(); + bucket.push(multiAssets); for (let j = 0; j < multiAssets.len(); j++) { const policy = multiAssets.get(j); + bucket.push(policy); const policyAssets = ma.get(policy); + bucket.push(policyAssets); const assetNames = policyAssets.keys(); + bucket.push(assetNames); for (let k = 0; k < assetNames.len(); k++) { const policyAsset = assetNames.get(k); + bucket.push(policyAsset); const quantity = policyAssets.get(policyAsset); + bucket.push(quantity); const unit = toHex(policy.to_bytes()) + toHex(policyAsset.name()); assets[unit] = BigInt(quantity.to_str()); } } } + Freeables.free(...bucket); return assets; } export function assetsToValue(assets) { + const bucket = []; const multiAsset = C.MultiAsset.new(); + bucket.push(multiAsset); const lovelace = assets["lovelace"]; const units = Object.keys(assets); const policies = Array.from(new Set(units @@ -333,86 +546,192 @@ export function assetsToValue(assets) { const policyUnits = units.filter((unit) => unit.slice(0, 56) === policy); const assetsValue = C.Assets.new(); policyUnits.forEach((unit) => { - assetsValue.insert(C.AssetName.new(fromHex(unit.slice(56))), C.BigNum.from_str(assets[unit].toString())); + const assetName = C.AssetName.new(fromHex(unit.slice(56))); + bucket.push(assetName); + const quantity = C.BigNum.from_str(assets[unit].toString()); + bucket.push(quantity); + assetsValue.insert(assetName, quantity); }); - multiAsset.insert(C.ScriptHash.from_bytes(fromHex(policy)), assetsValue); + const policyId = C.ScriptHash.from_bytes(fromHex(policy)); + bucket.push(policyId); + multiAsset.insert(policyId, assetsValue); }); - const value = C.Value.new(C.BigNum.from_str(lovelace ? lovelace.toString() : "0")); + const coin = C.BigNum.from_str(lovelace ? lovelace.toString() : "0"); + bucket.push(coin); + const value = C.Value.new(coin); if (units.length > 1 || !lovelace) value.set_multiasset(multiAsset); + Freeables.free(...bucket); return value; } export function fromScriptRef(scriptRef) { - const kind = scriptRef.get().kind(); - switch (kind) { - case 0: - return { - type: "Native", - script: toHex(scriptRef.get().as_native().to_bytes()), - }; - case 1: - return { - type: "PlutusV1", - script: toHex(scriptRef.get().as_plutus_v1().to_bytes()), - }; - case 2: - return { - type: "PlutusV2", - script: toHex(scriptRef.get().as_plutus_v2().to_bytes()), - }; - default: - throw new Error("No variant matched."); + const bucket = []; + try { + const script = scriptRef.get(); + bucket.push(script); + const kind = script.kind(); + switch (kind) { + case 0: { + const native = script.as_native(); + bucket.push(native); + return { + type: "Native", + script: toHex(native.to_bytes()), + }; + } + case 1: { + const plutusV1 = script.as_plutus_v1(); + bucket.push(plutusV1); + return { + type: "PlutusV1", + script: toHex(plutusV1.to_bytes()), + }; + } + case 2: { + const plutusV2 = script.as_plutus_v2(); + bucket.push(plutusV2); + return { + type: "PlutusV2", + script: toHex(plutusV2.to_bytes()), + }; + } + default: + throw new Error("No variant matched."); + } + } + finally { + Freeables.free(...bucket); } } export function toScriptRef(script) { - switch (script.type) { - case "Native": - return C.ScriptRef.new(C.Script.new_native(C.NativeScript.from_bytes(fromHex(script.script)))); - case "PlutusV1": - return C.ScriptRef.new(C.Script.new_plutus_v1(C.PlutusScript.from_bytes(fromHex(applyDoubleCborEncoding(script.script))))); - case "PlutusV2": - return C.ScriptRef.new(C.Script.new_plutus_v2(C.PlutusScript.from_bytes(fromHex(applyDoubleCborEncoding(script.script))))); - default: - throw new Error("No variant matched."); + const bucket = []; + try { + switch (script.type) { + case "Native": { + const nativeScript = C.NativeScript.from_bytes(fromHex(script.script)); + bucket.push(nativeScript); + const cScript = C.Script.new_native(nativeScript); + bucket.push(cScript); + return C.ScriptRef.new(cScript); + } + case "PlutusV1": { + const plutusScript = C.PlutusScript.from_bytes(fromHex(applyDoubleCborEncoding(script.script))); + bucket.push(plutusScript); + const cScript = C.Script.new_plutus_v1(plutusScript); + bucket.push(cScript); + return C.ScriptRef.new(cScript); + } + case "PlutusV2": { + const plutusScript = C.PlutusScript.from_bytes(fromHex(applyDoubleCborEncoding(script.script))); + bucket.push(plutusScript); + const cScript = C.Script.new_plutus_v2(plutusScript); + bucket.push(cScript); + return C.ScriptRef.new(cScript); + } + default: + throw new Error("No variant matched."); + } + } + finally { + Freeables.free(...bucket); } } export function utxoToCore(utxo) { + const bucket = []; const address = (() => { try { + console.log("success"); return C.Address.from_bech32(utxo.address); } catch (_e) { - return C.ByronAddress.from_base58(utxo.address).to_address(); + const byronAddress = C.ByronAddress.from_base58(utxo.address); + bucket.push(byronAddress); + return byronAddress.to_address(); } })(); - const output = C.TransactionOutput.new(address, assetsToValue(utxo.assets)); + bucket.push(address); + const value = assetsToValue(utxo.assets); + bucket.push(value); + const output = C.TransactionOutput.new(address, value); + bucket.push(output); if (utxo.datumHash) { - output.set_datum(C.Datum.new_data_hash(C.DataHash.from_bytes(fromHex(utxo.datumHash)))); + const dataHash = C.DataHash.from_bytes(fromHex(utxo.datumHash)); + bucket.push(dataHash); + const datum = C.Datum.new_data_hash(dataHash); + bucket.push(datum); + output.set_datum(datum); } // inline datum if (!utxo.datumHash && utxo.datum) { - output.set_datum(C.Datum.new_data(C.Data.new(C.PlutusData.from_bytes(fromHex(utxo.datum))))); + const plutusData = C.PlutusData.from_bytes(fromHex(utxo.datum)); + bucket.push(plutusData); + const data = C.Data.new(plutusData); + bucket.push(data); + const datum = C.Datum.new_data(data); + bucket.push(datum); + output.set_datum(datum); } if (utxo.scriptRef) { - output.set_script_ref(toScriptRef(utxo.scriptRef)); - } - return C.TransactionUnspentOutput.new(C.TransactionInput.new(C.TransactionHash.from_bytes(fromHex(utxo.txHash)), C.BigNum.from_str(utxo.outputIndex.toString())), output); + const scriptRef = toScriptRef(utxo.scriptRef); + bucket.push(scriptRef); + output.set_script_ref(scriptRef); + } + const hash = C.TransactionHash.from_bytes(fromHex(utxo.txHash)); + bucket.push(hash); + const index = C.BigNum.from_str(utxo.outputIndex.toString()); + bucket.push(index); + const input = C.TransactionInput.new(hash, index); + bucket.push(input); + const coreUtxo = C.TransactionUnspentOutput.new(input, output); + Freeables.free(...bucket); + return coreUtxo; } export function coreToUtxo(coreUtxo) { - const datum = coreUtxo.output()?.datum()?.as_data()?.get(); - const datumHash = coreUtxo.output()?.datum()?.as_data_hash()?.to_hex(); - return { - txHash: toHex(coreUtxo.input().transaction_id().to_bytes()), - outputIndex: parseInt(coreUtxo.input().index().to_str()), - assets: valueToAssets(coreUtxo.output().amount()), - address: coreUtxo.output().address().as_byron() - ? coreUtxo.output().address().as_byron()?.to_base58() - : coreUtxo.output().address().to_bech32(undefined), - datumHash: datum ? C.hash_plutus_data(datum).to_hex() : datumHash, - datum: datum && toHex(datum.to_bytes()), - scriptRef: coreUtxo.output()?.script_ref() && - fromScriptRef(coreUtxo.output().script_ref()), + const bucket = []; + const input = coreUtxo.input(); + bucket.push(input); + const output = coreUtxo.output(); + bucket.push(output); + const txId = input.transaction_id(); + bucket.push(txId); + const txHash = toHex(txId.to_bytes()); + const index = input.index(); + bucket.push(index); + const outputIndex = parseInt(index.to_str()); + const amount = output.amount(); + bucket.push(amount); + const assets = valueToAssets(amount); + const cAddress = output.address(); + bucket.push(cAddress); + const byronAddress = cAddress.as_byron(); + bucket.push(byronAddress); + const address = byronAddress + ? byronAddress.to_base58() + : cAddress.to_bech32(undefined); + const cDatum = output.datum(); + bucket.push(cDatum); + const dataHash = cDatum?.as_data_hash(); + bucket.push(dataHash); + const datumHash = dataHash?.to_hex(); + const cDatumData = cDatum?.as_data(); + bucket.push(cDatumData); + const plutusData = cDatumData?.get(); + bucket.push(plutusData); + const datum = plutusData && toHex(plutusData.to_bytes()); + const cScriptRef = output.script_ref(); + bucket.push(cScriptRef); + const scriptRef = cScriptRef && fromScriptRef(cScriptRef); + const utxo = { + txHash, + outputIndex, + assets, + address, + datumHash, + datum, + scriptRef, }; + Freeables.free(...bucket); + return utxo; } export function networkToId(network) { switch (network) { @@ -443,7 +762,11 @@ export function fromText(text) { return toHex(new TextEncoder().encode(text)); } export function toPublicKey(privateKey) { - return C.PrivateKey.from_bech32(privateKey).to_public().to_bech32(); + const sKey = C.PrivateKey.from_bech32(privateKey); + const vKey = sKey.to_public(); + const bech32 = vKey.to_bech32(); + Freeables.free(sKey, vKey); + return bech32; } /** Padded number in Hex. */ function checksum(num) { @@ -498,14 +821,23 @@ export function fromUnit(unit) { * It follows this Json format: https://github.com/input-output-hk/cardano-node/blob/master/doc/reference/simple-scripts.md */ export function nativeScriptFromJson(nativeScript) { + const cNativeScript = C.encode_json_str_to_native_script(JSON.stringify(nativeScript), "", C.ScriptSchema.Node); + const script = toHex(cNativeScript.to_bytes()); + cNativeScript.free(); return { type: "Native", - script: toHex(C.encode_json_str_to_native_script(JSON.stringify(nativeScript), "", C.ScriptSchema.Node).to_bytes()), + script, }; } export function applyParamsToScript(plutusScript, params, type) { const p = (type ? Data.castTo(params, type) : params); - return toHex(C.apply_params_to_plutus_script(C.PlutusList.from_bytes(fromHex(Data.to(p))), C.PlutusScript.from_bytes(fromHex(applyDoubleCborEncoding(plutusScript)))).to_bytes()); + // cPlutusScript ownership is passed to rust, so don't free + const cPlutusScript = C.PlutusScript.from_bytes(fromHex(applyDoubleCborEncoding(plutusScript))); + const cParams = C.PlutusList.from_bytes(fromHex(Data.to(p))); + const cScript = C.apply_params_to_plutus_script(cParams, cPlutusScript); + const script = toHex(cScript.to_bytes()); + Freeables.free(cParams, cScript); + return script; } export const chunk = (array, size) => { const chunks = []; @@ -523,7 +855,10 @@ export function applyDoubleCborEncoding(script) { return script; } catch (_e) { - return toHex(C.PlutusScript.new(fromHex(script)).to_bytes()); + const plutusScript = C.PlutusScript.new(fromHex(script)); + const bytes = plutusScript.to_bytes(); + plutusScript.free(); + return toHex(bytes); } } export function addAssets(...assets) { diff --git a/dist/package-lock.json b/dist/package-lock.json index 43ea91e6..8932443b 100644 --- a/dist/package-lock.json +++ b/dist/package-lock.json @@ -1,12 +1,12 @@ { "name": "@jpg-store/lucid-cardano", - "version": "0.10.12", + "version": "0.11.0", "lockfileVersion": 2, "requires": true, "packages": { "": { "name": "@jpg-store/lucid-cardano", - "version": "0.10.12", + "version": "0.11.0", "license": "MIT", "dependencies": { "@peculiar/webcrypto": "^1.4.0", @@ -184,9 +184,9 @@ } }, "node_modules/ws": { - "version": "8.14.2", - "resolved": "https://registry.npmjs.org/ws/-/ws-8.14.2.tgz", - "integrity": "sha512-wEBG1ftX4jcglPxgFCMJmZ2PLtSbJ2Peg6TmpJFTbe9GZYOQCDPdMYu/Tm0/bGZkw8paZnJY45J4K2PZrLYq8g==", + "version": "8.15.1", + "resolved": "https://registry.npmjs.org/ws/-/ws-8.15.1.tgz", + "integrity": "sha512-W5OZiCjXEmk0yZ66ZN82beM5Sz7l7coYxpRkzS+p9PP+ToQry8szKh+61eNktr7EA9DOwvFGhfC605jDHbP6QQ==", "engines": { "node": ">=10.0.0" }, @@ -318,9 +318,9 @@ } }, "ws": { - "version": "8.14.2", - "resolved": "https://registry.npmjs.org/ws/-/ws-8.14.2.tgz", - "integrity": "sha512-wEBG1ftX4jcglPxgFCMJmZ2PLtSbJ2Peg6TmpJFTbe9GZYOQCDPdMYu/Tm0/bGZkw8paZnJY45J4K2PZrLYq8g==", + "version": "8.15.1", + "resolved": "https://registry.npmjs.org/ws/-/ws-8.15.1.tgz", + "integrity": "sha512-W5OZiCjXEmk0yZ66ZN82beM5Sz7l7coYxpRkzS+p9PP+ToQry8szKh+61eNktr7EA9DOwvFGhfC605jDHbP6QQ==", "requires": {} } } diff --git a/dist/package.json b/dist/package.json index 543350bd..706d252a 100644 --- a/dist/package.json +++ b/dist/package.json @@ -3,7 +3,7 @@ "main": "./esm/mod.js", "types": "./dist/types/mod.d.ts", "name": "@jpg-store/lucid-cardano", - "version": "0.10.12", + "version": "0.11.0", "license": "MIT", "description": "This is a fork of the original Lucid repo compiled into CommonJS. For more information check https://github.com/spacebudz/lucid", "repository": "https://github.com/jpg-store/lucid", diff --git a/dist/src/package.js b/dist/src/package.js index be5c8fa4..c88696ac 100644 --- a/dist/src/package.js +++ b/dist/src/package.js @@ -1,6 +1,6 @@ export default { "name": "@jpg-store/lucid-cardano", - "version": "0.10.12", + "version": "0.11.0", "license": "MIT", "description": "This is a fork of the original Lucid repo compiled into CommonJS. For more information check https://github.com/spacebudz/lucid", "repository": "https://github.com/jpg-store/lucid", diff --git a/dist/src/src/core/libs/cardano_message_signing/cardano_message_signing.generated.js b/dist/src/src/core/libs/cardano_message_signing/cardano_message_signing.generated.js index b7a65105..65870411 100644 --- a/dist/src/src/core/libs/cardano_message_signing/cardano_message_signing.generated.js +++ b/dist/src/src/core/libs/cardano_message_signing/cardano_message_signing.generated.js @@ -1144,7 +1144,7 @@ export class COSEEncrypt { ciphertext() { try { const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); - wasm.coseencrypt0_ciphertext(retptr, this.ptr); + wasm.coseencrypt_ciphertext(retptr, this.ptr); var r0 = getInt32Memory0()[retptr / 4 + 0]; var r1 = getInt32Memory0()[retptr / 4 + 1]; let v0; @@ -1745,7 +1745,7 @@ export class COSESign { payload() { try { const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); - wasm.coseencrypt0_ciphertext(retptr, this.ptr); + wasm.coseencrypt_ciphertext(retptr, this.ptr); var r0 = getInt32Memory0()[retptr / 4 + 0]; var r1 = getInt32Memory0()[retptr / 4 + 1]; let v0; @@ -1856,7 +1856,7 @@ export class COSESign1 { payload() { try { const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); - wasm.coseencrypt0_ciphertext(retptr, this.ptr); + wasm.coseencrypt_ciphertext(retptr, this.ptr); var r0 = getInt32Memory0()[retptr / 4 + 0]; var r1 = getInt32Memory0()[retptr / 4 + 1]; let v0; @@ -2154,7 +2154,7 @@ export class COSESignature { signature() { try { const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); - wasm.cosesignature_signature(retptr, this.ptr); + wasm.cosesign1_signature(retptr, this.ptr); var r0 = getInt32Memory0()[retptr / 4 + 0]; var r1 = getInt32Memory0()[retptr / 4 + 1]; var v0 = getArrayU8FromWasm0(r0, r1).slice(); diff --git a/dist/src/src/core/libs/cardano_multiplatform_lib/cardano_multiplatform_lib.generated.js b/dist/src/src/core/libs/cardano_multiplatform_lib/cardano_multiplatform_lib.generated.js index d12875b0..7fe83098 100644 --- a/dist/src/src/core/libs/cardano_multiplatform_lib/cardano_multiplatform_lib.generated.js +++ b/dist/src/src/core/libs/cardano_multiplatform_lib/cardano_multiplatform_lib.generated.js @@ -1,9 +1,31 @@ // @generated file from wasmbuild -- do not edit // deno-lint-ignore-file // deno-fmt-ignore-file -// source-hash: ab17726f2df5571be15d036e67423022ed8f63e4 +// source-hash: fea5fc75a13596f0eb0af3e358328b34adb4ded3 let wasm; +const heap = new Array(128).fill(undefined); + +heap.push(undefined, null, true, false); + +function getObject(idx) { + return heap[idx]; +} + +let heap_next = heap.length; + +function dropObject(idx) { + if (idx < 132) return; + heap[idx] = heap_next; + heap_next = idx; +} + +function takeObject(idx) { + const ret = getObject(idx); + dropObject(idx); + return ret; +} + const cachedTextDecoder = new TextDecoder("utf-8", { ignoreBOM: true, fatal: true, @@ -24,12 +46,6 @@ function getStringFromWasm0(ptr, len) { return cachedTextDecoder.decode(getUint8Memory0().subarray(ptr, ptr + len)); } -const heap = new Array(128).fill(undefined); - -heap.push(undefined, null, true, false); - -let heap_next = heap.length; - function addHeapObject(obj) { if (heap_next === heap.length) heap.push(heap.length + 1); const idx = heap_next; @@ -39,22 +55,6 @@ function addHeapObject(obj) { return idx; } -function getObject(idx) { - return heap[idx]; -} - -function dropObject(idx) { - if (idx < 132) return; - heap[idx] = heap_next; - heap_next = idx; -} - -function takeObject(idx) { - const ret = getObject(idx); - dropObject(idx); - return ret; -} - let WASM_VECTOR_LEN = 0; const cachedTextEncoder = new TextEncoder("utf-8"); @@ -207,12 +207,11 @@ function makeMutClosure(arg0, arg1, dtor, f) { return real; } function __wbg_adapter_30(arg0, arg1, arg2) { - wasm - ._dyn_core__ops__function__FnMut__A____Output___R_as_wasm_bindgen__closure__WasmClosure___describe__invoke__h9de9452916ac8cca( - arg0, - arg1, - addHeapObject(arg2), - ); + wasm.wasm_bindgen__convert__closures__invoke1_mut__hee80fd123b909250( + arg0, + arg1, + addHeapObject(arg2), + ); } function _assertClass(instance, klass) { @@ -817,8 +816,8 @@ function handleError(f, args) { wasm.__wbindgen_exn_store(addHeapObject(e)); } } -function __wbg_adapter_1680(arg0, arg1, arg2, arg3) { - wasm.wasm_bindgen__convert__closures__invoke2_mut__h36afefe016e25d40( +function __wbg_adapter_1681(arg0, arg1, arg2, arg3) { + wasm.wasm_bindgen__convert__closures__invoke2_mut__h5b4d9f16616fac4b( arg0, arg1, addHeapObject(arg2), @@ -7935,7 +7934,7 @@ export class GovernanceActionId { * @returns {BigNum} */ governance_action_index() { - const ret = wasm.constrplutusdata_alternative(this.ptr); + const ret = wasm.governanceactionid_governance_action_index(this.ptr); return BigNum.__wrap(ret); } /** @@ -8391,7 +8390,7 @@ export class HeaderBody { * @returns {BigNum} */ slot() { - const ret = wasm.constrplutusdata_alternative(this.ptr); + const ret = wasm.headerbody_slot(this.ptr); return BigNum.__wrap(ret); } /** @@ -8658,7 +8657,7 @@ export class Int { as_i32_or_nothing() { try { const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); - wasm.int_as_i32(retptr, this.ptr); + wasm.int_as_i32_or_nothing(retptr, this.ptr); var r0 = getInt32Memory0()[retptr / 4 + 0]; var r1 = getInt32Memory0()[retptr / 4 + 1]; return r0 === 0 ? undefined : r1; @@ -9532,14 +9531,14 @@ export class LinearFee { * @returns {BigNum} */ constant() { - const ret = wasm.constrplutusdata_alternative(this.ptr); + const ret = wasm.linearfee_constant(this.ptr); return BigNum.__wrap(ret); } /** * @returns {BigNum} */ coefficient() { - const ret = wasm.exunits_steps(this.ptr); + const ret = wasm.linearfee_coefficient(this.ptr); return BigNum.__wrap(ret); } /** @@ -11819,7 +11818,7 @@ export class NewConstitution { * @returns {DataHash} */ hash() { - const ret = wasm.newconstitution_hash(this.ptr); + const ret = wasm.genesiskeydelegation_vrf_keyhash(this.ptr); return DataHash.__wrap(ret); } /** @@ -12080,7 +12079,7 @@ export class OperationalCert { * @returns {number} */ sequence_number() { - const ret = wasm.networkinfo_protocol_magic(this.ptr); + const ret = wasm.operationalcert_sequence_number(this.ptr); return ret >>> 0; } /** @@ -13484,28 +13483,28 @@ export class PoolParams { * @returns {VRFKeyHash} */ vrf_keyhash() { - const ret = wasm.poolparams_vrf_keyhash(this.ptr); + const ret = wasm.governanceactionid_transaction_id(this.ptr); return VRFKeyHash.__wrap(ret); } /** * @returns {BigNum} */ pledge() { - const ret = wasm.constrplutusdata_alternative(this.ptr); + const ret = wasm.governanceactionid_governance_action_index(this.ptr); return BigNum.__wrap(ret); } /** * @returns {BigNum} */ cost() { - const ret = wasm.exunits_steps(this.ptr); + const ret = wasm.poolparams_cost(this.ptr); return BigNum.__wrap(ret); } /** * @returns {UnitInterval} */ margin() { - const ret = wasm.drepvotingthresholds_committee_normal(this.ptr); + const ret = wasm.drepvotingthresholds_update_constitution(this.ptr); return UnitInterval.__wrap(ret); } /** @@ -13876,7 +13875,7 @@ export class PoolRetirement { * @returns {number} */ epoch() { - const ret = wasm.networkinfo_protocol_magic(this.ptr); + const ret = wasm.poolretirement_epoch(this.ptr); return ret >>> 0; } /** @@ -14425,7 +14424,7 @@ export class ProposalProcedure { * @returns {BigNum} */ deposit() { - const ret = wasm.constrplutusdata_alternative(this.ptr); + const ret = wasm.proposalprocedure_deposit(this.ptr); return BigNum.__wrap(ret); } /** @@ -15549,7 +15548,7 @@ export class ProtocolVersion { * @returns {number} */ minor() { - const ret = wasm.operationalcert_kes_period(this.ptr); + const ret = wasm.protocolversion_minor(this.ptr); return ret >>> 0; } /** @@ -15814,14 +15813,14 @@ export class Redeemer { * @returns {BigNum} */ index() { - const ret = wasm.constrplutusdata_alternative(this.ptr); + const ret = wasm.poolparams_cost(this.ptr); return BigNum.__wrap(ret); } /** * @returns {PlutusData} */ data() { - const ret = wasm.redeemer_data(this.ptr); + const ret = wasm.data_get(this.ptr); return PlutusData.__wrap(ret); } /** @@ -16378,14 +16377,14 @@ export class RegCommitteeHotKeyCert { * @returns {Ed25519KeyHash} */ committee_cold_keyhash() { - const ret = wasm.genesiskeydelegation_genesishash(this.ptr); + const ret = wasm.regcommitteehotkeycert_committee_cold_keyhash(this.ptr); return Ed25519KeyHash.__wrap(ret); } /** * @returns {Ed25519KeyHash} */ committee_hot_keyhash() { - const ret = wasm.genesiskeydelegation_genesis_delegate_hash(this.ptr); + const ret = wasm.regcommitteehotkeycert_committee_hot_keyhash(this.ptr); return Ed25519KeyHash.__wrap(ret); } /** @@ -16935,7 +16934,7 @@ export class RequiredWitnessSet { */ add_vkey_key(vkey) { _assertClass(vkey, Vkey); - wasm.requiredwitnessset_add_vkey(this.ptr, vkey.ptr); + wasm.requiredwitnessset_add_vkey_key(this.ptr, vkey.ptr); } /** * @param {Ed25519KeyHash} hash @@ -18355,14 +18354,14 @@ export class ScriptNOfK { * @returns {number} */ n() { - const ret = wasm.networkinfo_protocol_magic(this.ptr); + const ret = wasm.scriptnofk_n(this.ptr); return ret >>> 0; } /** * @returns {NativeScripts} */ native_scripts() { - const ret = wasm.scriptnofk_native_scripts(this.ptr); + const ret = wasm.scriptall_native_scripts(this.ptr); return NativeScripts.__wrap(ret); } /** @@ -18508,7 +18507,7 @@ export class ScriptPubkey { * @returns {Ed25519KeyHash} */ addr_keyhash() { - const ret = wasm.genesiskeydelegation_genesishash(this.ptr); + const ret = wasm.regcommitteehotkeycert_committee_cold_keyhash(this.ptr); return Ed25519KeyHash.__wrap(ret); } /** @@ -19110,7 +19109,7 @@ export class SingleHostName { * @returns {DNSRecordAorAAAA} */ dns_name() { - const ret = wasm.anchor_anchor_url(this.ptr); + const ret = wasm.singlehostname_dns_name(this.ptr); return DNSRecordAorAAAA.__wrap(ret); } /** @@ -19585,7 +19584,7 @@ export class StakeDelegation { * @returns {StakeCredential} */ stake_credential() { - const ret = wasm.stakedelegation_stake_credential(this.ptr); + const ret = wasm.baseaddress_payment_cred(this.ptr); return StakeCredential.__wrap(ret); } /** @@ -19742,7 +19741,7 @@ export class StakeDeregistration { * @returns {StakeCredential} */ stake_credential() { - const ret = wasm.stakedelegation_stake_credential(this.ptr); + const ret = wasm.baseaddress_payment_cred(this.ptr); return StakeCredential.__wrap(ret); } /** @@ -19887,7 +19886,7 @@ export class StakeRegDelegCert { * @returns {StakeCredential} */ stake_credential() { - const ret = wasm.regcert_stake_credential(this.ptr); + const ret = wasm.stakeregdelegcert_stake_credential(this.ptr); return StakeCredential.__wrap(ret); } /** @@ -20054,7 +20053,7 @@ export class StakeRegistration { * @returns {StakeCredential} */ stake_credential() { - const ret = wasm.stakedelegation_stake_credential(this.ptr); + const ret = wasm.baseaddress_payment_cred(this.ptr); return StakeCredential.__wrap(ret); } /** @@ -20199,14 +20198,14 @@ export class StakeVoteDelegCert { * @returns {StakeCredential} */ stake_credential() { - const ret = wasm.stakedelegation_stake_credential(this.ptr); + const ret = wasm.baseaddress_payment_cred(this.ptr); return StakeCredential.__wrap(ret); } /** * @returns {Ed25519KeyHash} */ pool_keyhash() { - const ret = wasm.stakedelegation_pool_keyhash(this.ptr); + const ret = wasm.stakevotedelegcert_pool_keyhash(this.ptr); return Ed25519KeyHash.__wrap(ret); } /** @@ -20366,7 +20365,7 @@ export class StakeVoteRegDelegCert { * @returns {StakeCredential} */ stake_credential() { - const ret = wasm.regcert_stake_credential(this.ptr); + const ret = wasm.stakevoteregdelegcert_stake_credential(this.ptr); return StakeCredential.__wrap(ret); } /** @@ -20610,7 +20609,7 @@ export class TimelockExpiry { * @returns {BigNum} */ slot() { - const ret = wasm.constrplutusdata_alternative(this.ptr); + const ret = wasm.linearfee_constant(this.ptr); return BigNum.__wrap(ret); } /** @@ -20755,7 +20754,7 @@ export class TimelockStart { * @returns {BigNum} */ slot() { - const ret = wasm.constrplutusdata_alternative(this.ptr); + const ret = wasm.linearfee_constant(this.ptr); return BigNum.__wrap(ret); } /** @@ -21252,7 +21251,7 @@ export class TransactionBody { * @returns {BigNum} */ fee() { - const ret = wasm.constrplutusdata_alternative(this.ptr); + const ret = wasm.transactionbody_fee(this.ptr); return BigNum.__wrap(ret); } /** @@ -21340,7 +21339,7 @@ export class TransactionBody { */ set_validity_start_interval(validity_start_interval) { _assertClass(validity_start_interval, BigNum); - wasm.transactionbody_set_validity_start_interval( + wasm.protocolparamupdate_set_minfee_b( this.ptr, validity_start_interval.ptr, ); @@ -21349,7 +21348,7 @@ export class TransactionBody { * @returns {BigNum | undefined} */ validity_start_interval() { - const ret = wasm.transactionbody_validity_start_interval(this.ptr); + const ret = wasm.protocolparamupdate_minfee_b(this.ptr); return ret === 0 ? undefined : BigNum.__wrap(ret); } /** @@ -21441,13 +21440,13 @@ export class TransactionBody { */ set_total_collateral(total_collateral) { _assertClass(total_collateral, BigNum); - wasm.transactionbody_set_total_collateral(this.ptr, total_collateral.ptr); + wasm.protocolparamupdate_set_key_deposit(this.ptr, total_collateral.ptr); } /** * @returns {BigNum | undefined} */ total_collateral() { - const ret = wasm.transactionbody_total_collateral(this.ptr); + const ret = wasm.protocolparamupdate_key_deposit(this.ptr); return ret === 0 ? undefined : BigNum.__wrap(ret); } /** @@ -21549,6 +21548,47 @@ export class TransactionBuilder { const ptr = this.__destroy_into_raw(); wasm.__wbg_transactionbuilder_free(ptr); } + /** + * This automatically selects and adds inputs from {inputs} consisting of just enough to cover + * the outputs that have already been added. + * This should be called after adding all certs/outputs/etc and will be an error otherwise. + * Adding a change output must be called after via TransactionBuilder::balance() + * inputs to cover the minimum fees. This does not, however, set the txbuilder's fee. + * + * change_address is required here in order to determine the min ada requirement precisely + * weights is a coma separated representation of a Uint32Arary + * @param {TransactionUnspentOutputs} inputs + * @param {Address} change_address + * @param {string} weights_str + */ + add_inputs_from_impl(inputs, change_address, weights_str) { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + _assertClass(inputs, TransactionUnspentOutputs); + _assertClass(change_address, Address); + const ptr0 = passStringToWasm0( + weights_str, + wasm.__wbindgen_malloc, + wasm.__wbindgen_realloc, + ); + const len0 = WASM_VECTOR_LEN; + wasm.transactionbuilder_add_inputs_from_impl( + retptr, + this.ptr, + inputs.ptr, + change_address.ptr, + ptr0, + len0, + ); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + if (r1) { + throw takeObject(r0); + } + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } /** * This automatically selects and adds inputs from {inputs} consisting of just enough to cover * the outputs that have already been added. @@ -21726,7 +21766,7 @@ export class TransactionBuilder { */ set_ttl(ttl) { _assertClass(ttl, BigNum); - wasm.transactionbuilder_set_ttl(this.ptr, ttl.ptr); + wasm.protocolparamupdate_set_minfee_b(this.ptr, ttl.ptr); } /** * @param {BigNum} validity_start_interval @@ -22108,7 +22148,7 @@ export class TransactionBuilder { * @returns {BigNum | undefined} */ get_fee_if_set() { - const ret = wasm.transactionbuilder_get_fee_if_set(this.ptr); + const ret = wasm.protocolparamupdate_minfee_a(this.ptr); return ret === 0 ? undefined : BigNum.__wrap(ret); } /** @@ -22906,7 +22946,7 @@ export class TransactionInput { * @returns {BigNum} */ index() { - const ret = wasm.constrplutusdata_alternative(this.ptr); + const ret = wasm.governanceactionid_governance_action_index(this.ptr); return BigNum.__wrap(ret); } /** @@ -25432,7 +25472,7 @@ export class UnregCommitteeHotKeyCert { * @returns {Ed25519KeyHash} */ committee_cold_keyhash() { - const ret = wasm.genesiskeydelegation_genesishash(this.ptr); + const ret = wasm.regcommitteehotkeycert_committee_cold_keyhash(this.ptr); return Ed25519KeyHash.__wrap(ret); } /** @@ -26449,7 +26489,7 @@ export class Value { * @returns {BigNum} */ coin() { - const ret = wasm.constrplutusdata_alternative(this.ptr); + const ret = wasm.value_coin(this.ptr); return BigNum.__wrap(ret); } /** @@ -26808,7 +26848,7 @@ export class Vkeywitness { * @returns {Vkey} */ vkey() { - const ret = wasm.vkey_new(this.ptr); + const ret = wasm.vkeywitness_vkey(this.ptr); return Vkey.__wrap(ret); } /** @@ -27162,14 +27202,14 @@ export class VoteDelegCert { * @returns {StakeCredential} */ stake_credential() { - const ret = wasm.stakedelegation_stake_credential(this.ptr); + const ret = wasm.baseaddress_payment_cred(this.ptr); return StakeCredential.__wrap(ret); } /** * @returns {Drep} */ drep() { - const ret = wasm.votedelegcert_drep(this.ptr); + const ret = wasm.stakevotedelegcert_drep(this.ptr); return Drep.__wrap(ret); } /** @@ -27699,7 +27739,7 @@ export class VotingProcedure { * @returns {GovernanceActionId} */ governance_action_id() { - const ret = wasm.transactionunspentoutput_input(this.ptr); + const ret = wasm.votingprocedure_governance_action_id(this.ptr); return GovernanceActionId.__wrap(ret); } /** @@ -28008,10 +28048,6 @@ export class Withdrawals { const imports = { __wbindgen_placeholder__: { - __wbindgen_string_new: function (arg0, arg1) { - const ret = getStringFromWasm0(arg0, arg1); - return addHeapObject(ret); - }, __wbindgen_object_drop_ref: function (arg0) { takeObject(arg0); }, @@ -28031,17 +28067,21 @@ const imports = { getInt32Memory0()[arg0 / 4 + 1] = len0; getInt32Memory0()[arg0 / 4 + 0] = ptr0; }, - __wbg_transaction_new: function (arg0) { - const ret = Transaction.__wrap(arg0); + __wbindgen_string_new: function (arg0, arg1) { + const ret = getStringFromWasm0(arg0, arg1); return addHeapObject(ret); }, __wbg_fetch_16f5dddfc5a913a4: function (arg0, arg1) { const ret = getObject(arg0).fetch(getObject(arg1)); return addHeapObject(ret); }, + __wbg_transaction_new: function (arg0) { + const ret = Transaction.__wrap(arg0); + return addHeapObject(ret); + }, __wbindgen_string_get: function (arg0, arg1) { const obj = getObject(arg1); - const ret = typeof (obj) === "string" ? obj : undefined; + const ret = typeof obj === "string" ? obj : undefined; var ptr0 = isLikeNone(ret) ? 0 : passStringToWasm0( @@ -28103,15 +28143,9 @@ const imports = { const ret = false; return ret; }, - __wbg_randomFillSync_2f6909f8132a175d: function () { - return handleError(function (arg0, arg1, arg2) { - getObject(arg0).randomFillSync(getArrayU8FromWasm0(arg1, arg2)); - }, arguments); - }, - __wbg_getRandomValues_11a236fbf9914290: function () { - return handleError(function (arg0, arg1) { - getObject(arg0).getRandomValues(getObject(arg1)); - }, arguments); + __wbg_static_accessor_NODE_MODULE_06b864c18e8ae506: function () { + const ret = module; + return addHeapObject(ret); }, __wbg_process_5615a087a47ba544: function (arg0) { const ret = getObject(arg0).process; @@ -28119,7 +28153,7 @@ const imports = { }, __wbindgen_is_object: function (arg0) { const val = getObject(arg0); - const ret = typeof (val) === "object" && val !== null; + const ret = typeof val === "object" && val !== null; return ret; }, __wbg_versions_8404a8b21b9337ae: function (arg0) { @@ -28148,9 +28182,15 @@ const imports = { const ret = getObject(arg0).msCrypto; return addHeapObject(ret); }, - __wbg_static_accessor_NODE_MODULE_06b864c18e8ae506: function () { - const ret = module; - return addHeapObject(ret); + __wbg_randomFillSync_2f6909f8132a175d: function () { + return handleError(function (arg0, arg1, arg2) { + getObject(arg0).randomFillSync(getArrayU8FromWasm0(arg1, arg2)); + }, arguments); + }, + __wbg_getRandomValues_11a236fbf9914290: function () { + return handleError(function (arg0, arg1) { + getObject(arg0).getRandomValues(getObject(arg1)); + }, arguments); }, __wbg_self_e7c1f827057f6584: function () { return handleError(function () { @@ -28221,7 +28261,7 @@ const imports = { const a = state0.a; state0.a = 0; try { - return __wbg_adapter_1680(a, state0.b, arg0, arg1); + return __wbg_adapter_1681(a, state0.b, arg0, arg1); } finally { state0.a = a; } @@ -28279,6 +28319,10 @@ const imports = { const ret = getObject(arg0).self; return addHeapObject(ret); }, + __wbg_require_0993fe224bf8e202: function (arg0, arg1) { + const ret = require(getStringFromWasm0(arg0, arg1)); + return addHeapObject(ret); + }, __wbg_crypto_e95a6e54c5c2e37f: function (arg0) { const ret = getObject(arg0).crypto; return addHeapObject(ret); @@ -28287,10 +28331,6 @@ const imports = { const ret = getObject(arg0).getRandomValues; return addHeapObject(ret); }, - __wbg_require_0993fe224bf8e202: function (arg0, arg1) { - const ret = require(getStringFromWasm0(arg0, arg1)); - return addHeapObject(ret); - }, __wbg_randomFillSync_dd2297de5917c74e: function (arg0, arg1, arg2) { getObject(arg0).randomFillSync(getArrayU8FromWasm0(arg1, arg2)); }, @@ -28315,8 +28355,8 @@ const imports = { const ret = wasm.memory; return addHeapObject(ret); }, - __wbindgen_closure_wrapper7018: function (arg0, arg1, arg2) { - const ret = makeMutClosure(arg0, arg1, 216, __wbg_adapter_30); + __wbindgen_closure_wrapper7021: function (arg0, arg1, arg2) { + const ret = makeMutClosure(arg0, arg1, 186, __wbg_adapter_30); return addHeapObject(ret); }, }, diff --git a/dist/src/src/core/libs/cardano_multiplatform_lib/nodejs/cardano_multiplatform_lib.generated.js b/dist/src/src/core/libs/cardano_multiplatform_lib/nodejs/cardano_multiplatform_lib.generated.js new file mode 100644 index 00000000..f9a260fa --- /dev/null +++ b/dist/src/src/core/libs/cardano_multiplatform_lib/nodejs/cardano_multiplatform_lib.generated.js @@ -0,0 +1,28634 @@ +// @generated file from wasmbuild -- do not edit +// deno-lint-ignore-file +// deno-fmt-ignore-file +// source-hash: fea5fc75a13596f0eb0af3e358328b34adb4ded3 + +let imports = {}; +imports["__wbindgen_placeholder__"] = module.exports; +let wasm; +const { TextDecoder, TextEncoder } = require(`util`); + +const heap = new Array(128).fill(undefined); + +heap.push(undefined, null, true, false); + +function getObject(idx) { + return heap[idx]; +} + +let heap_next = heap.length; + +function dropObject(idx) { + if (idx < 132) return; + heap[idx] = heap_next; + heap_next = idx; +} + +function takeObject(idx) { + const ret = getObject(idx); + dropObject(idx); + return ret; +} + +let cachedTextDecoder = new TextDecoder("utf-8", { + ignoreBOM: true, + fatal: true, +}); + +cachedTextDecoder.decode(); + +let cachedUint8Memory0 = null; + +function getUint8Memory0() { + if (cachedUint8Memory0 === null || cachedUint8Memory0.byteLength === 0) { + cachedUint8Memory0 = new Uint8Array(wasm.memory.buffer); + } + return cachedUint8Memory0; +} + +function getStringFromWasm0(ptr, len) { + return cachedTextDecoder.decode(getUint8Memory0().subarray(ptr, ptr + len)); +} + +function addHeapObject(obj) { + if (heap_next === heap.length) heap.push(heap.length + 1); + const idx = heap_next; + heap_next = heap[idx]; + + heap[idx] = obj; + return idx; +} + +let WASM_VECTOR_LEN = 0; + +let cachedTextEncoder = new TextEncoder("utf-8"); + +const encodeString = typeof cachedTextEncoder.encodeInto === "function" + ? function (arg, view) { + return cachedTextEncoder.encodeInto(arg, view); + } + : function (arg, view) { + const buf = cachedTextEncoder.encode(arg); + view.set(buf); + return { + read: arg.length, + written: buf.length, + }; + }; + +function passStringToWasm0(arg, malloc, realloc) { + if (realloc === undefined) { + const buf = cachedTextEncoder.encode(arg); + const ptr = malloc(buf.length); + getUint8Memory0().subarray(ptr, ptr + buf.length).set(buf); + WASM_VECTOR_LEN = buf.length; + return ptr; + } + + let len = arg.length; + let ptr = malloc(len); + + const mem = getUint8Memory0(); + + let offset = 0; + + for (; offset < len; offset++) { + const code = arg.charCodeAt(offset); + if (code > 0x7F) break; + mem[ptr + offset] = code; + } + + if (offset !== len) { + if (offset !== 0) { + arg = arg.slice(offset); + } + ptr = realloc(ptr, len, len = offset + arg.length * 3); + const view = getUint8Memory0().subarray(ptr + offset, ptr + len); + const ret = encodeString(arg, view); + + offset += ret.written; + } + + WASM_VECTOR_LEN = offset; + return ptr; +} + +let cachedInt32Memory0 = null; + +function getInt32Memory0() { + if (cachedInt32Memory0 === null || cachedInt32Memory0.byteLength === 0) { + cachedInt32Memory0 = new Int32Array(wasm.memory.buffer); + } + return cachedInt32Memory0; +} + +function isLikeNone(x) { + return x === undefined || x === null; +} + +function debugString(val) { + // primitive types + const type = typeof val; + if (type == "number" || type == "boolean" || val == null) { + return `${val}`; + } + if (type == "string") { + return `"${val}"`; + } + if (type == "symbol") { + const description = val.description; + if (description == null) { + return "Symbol"; + } else { + return `Symbol(${description})`; + } + } + if (type == "function") { + const name = val.name; + if (typeof name == "string" && name.length > 0) { + return `Function(${name})`; + } else { + return "Function"; + } + } + // objects + if (Array.isArray(val)) { + const length = val.length; + let debug = "["; + if (length > 0) { + debug += debugString(val[0]); + } + for (let i = 1; i < length; i++) { + debug += ", " + debugString(val[i]); + } + debug += "]"; + return debug; + } + // Test for built-in + const builtInMatches = /\[object ([^\]]+)\]/.exec(toString.call(val)); + let className; + if (builtInMatches.length > 1) { + className = builtInMatches[1]; + } else { + // Failed to match the standard '[object ClassName]' + return toString.call(val); + } + if (className == "Object") { + // we're a user defined class or Object + // JSON.stringify avoids problems with cycles, and is generally much + // easier than looping through ownProperties of `val`. + try { + return "Object(" + JSON.stringify(val) + ")"; + } catch (_) { + return "Object"; + } + } + // errors + if (val instanceof Error) { + return `${val.name}: ${val.message}\n${val.stack}`; + } + // TODO we could test for more things here, like `Set`s and `Map`s. + return className; +} + +const CLOSURE_DTORS = new FinalizationRegistry((state) => { + wasm.__wbindgen_export_2.get(state.dtor)(state.a, state.b); +}); + +function makeMutClosure(arg0, arg1, dtor, f) { + const state = { a: arg0, b: arg1, cnt: 1, dtor }; + const real = (...args) => { + // First up with a closure we increment the internal reference + // count. This ensures that the Rust closure environment won't + // be deallocated while we're invoking it. + state.cnt++; + const a = state.a; + state.a = 0; + try { + return f(a, state.b, ...args); + } finally { + if (--state.cnt === 0) { + wasm.__wbindgen_export_2.get(state.dtor)(a, state.b); + CLOSURE_DTORS.unregister(state); + } else { + state.a = a; + } + } + }; + real.original = state; + CLOSURE_DTORS.register(real, state, state); + return real; +} +function __wbg_adapter_30(arg0, arg1, arg2) { + wasm.wasm_bindgen__convert__closures__invoke1_mut__hee80fd123b909250( + arg0, + arg1, + addHeapObject(arg2), + ); +} + +function _assertClass(instance, klass) { + if (!(instance instanceof klass)) { + throw new Error(`expected instance of ${klass.name}`); + } + return instance.ptr; +} + +function getArrayU8FromWasm0(ptr, len) { + return getUint8Memory0().subarray(ptr / 1, ptr / 1 + len); +} + +function passArray8ToWasm0(arg, malloc) { + const ptr = malloc(arg.length * 1); + getUint8Memory0().set(arg, ptr / 1); + WASM_VECTOR_LEN = arg.length; + return ptr; +} +/** + * @param {string} password + * @param {string} salt + * @param {string} nonce + * @param {string} data + * @returns {string} + */ +module.exports.encrypt_with_password = function (password, salt, nonce, data) { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + const ptr0 = passStringToWasm0( + password, + wasm.__wbindgen_malloc, + wasm.__wbindgen_realloc, + ); + const len0 = WASM_VECTOR_LEN; + const ptr1 = passStringToWasm0( + salt, + wasm.__wbindgen_malloc, + wasm.__wbindgen_realloc, + ); + const len1 = WASM_VECTOR_LEN; + const ptr2 = passStringToWasm0( + nonce, + wasm.__wbindgen_malloc, + wasm.__wbindgen_realloc, + ); + const len2 = WASM_VECTOR_LEN; + const ptr3 = passStringToWasm0( + data, + wasm.__wbindgen_malloc, + wasm.__wbindgen_realloc, + ); + const len3 = WASM_VECTOR_LEN; + wasm.encrypt_with_password( + retptr, + ptr0, + len0, + ptr1, + len1, + ptr2, + len2, + ptr3, + len3, + ); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + var r3 = getInt32Memory0()[retptr / 4 + 3]; + var ptr4 = r0; + var len4 = r1; + if (r3) { + ptr4 = 0; + len4 = 0; + throw takeObject(r2); + } + return getStringFromWasm0(ptr4, len4); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + wasm.__wbindgen_free(ptr4, len4); + } +}; + +/** + * @param {string} password + * @param {string} data + * @returns {string} + */ +module.exports.decrypt_with_password = function (password, data) { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + const ptr0 = passStringToWasm0( + password, + wasm.__wbindgen_malloc, + wasm.__wbindgen_realloc, + ); + const len0 = WASM_VECTOR_LEN; + const ptr1 = passStringToWasm0( + data, + wasm.__wbindgen_malloc, + wasm.__wbindgen_realloc, + ); + const len1 = WASM_VECTOR_LEN; + wasm.decrypt_with_password(retptr, ptr0, len0, ptr1, len1); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + var r3 = getInt32Memory0()[retptr / 4 + 3]; + var ptr2 = r0; + var len2 = r1; + if (r3) { + ptr2 = 0; + len2 = 0; + throw takeObject(r2); + } + return getStringFromWasm0(ptr2, len2); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + wasm.__wbindgen_free(ptr2, len2); + } +}; + +/** + * @param {Transaction} tx + * @param {LinearFee} linear_fee + * @param {ExUnitPrices} ex_unit_prices + * @returns {BigNum} + */ +module.exports.min_fee = function (tx, linear_fee, ex_unit_prices) { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + _assertClass(tx, Transaction); + _assertClass(linear_fee, LinearFee); + _assertClass(ex_unit_prices, ExUnitPrices); + wasm.min_fee(retptr, tx.ptr, linear_fee.ptr, ex_unit_prices.ptr); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + if (r2) { + throw takeObject(r1); + } + return BigNum.__wrap(r0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } +}; + +/** + * @param {Uint8Array} bytes + * @returns {TransactionMetadatum} + */ +module.exports.encode_arbitrary_bytes_as_metadatum = function (bytes) { + const ptr0 = passArray8ToWasm0(bytes, wasm.__wbindgen_malloc); + const len0 = WASM_VECTOR_LEN; + const ret = wasm.encode_arbitrary_bytes_as_metadatum(ptr0, len0); + return TransactionMetadatum.__wrap(ret); +}; + +/** + * @param {TransactionMetadatum} metadata + * @returns {Uint8Array} + */ +module.exports.decode_arbitrary_bytes_from_metadatum = function (metadata) { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + _assertClass(metadata, TransactionMetadatum); + wasm.decode_arbitrary_bytes_from_metadatum(retptr, metadata.ptr); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + var r3 = getInt32Memory0()[retptr / 4 + 3]; + if (r3) { + throw takeObject(r2); + } + var v0 = getArrayU8FromWasm0(r0, r1).slice(); + wasm.__wbindgen_free(r0, r1 * 1); + return v0; + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } +}; + +/** + * @param {string} json + * @param {number} schema + * @returns {TransactionMetadatum} + */ +module.exports.encode_json_str_to_metadatum = function (json, schema) { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + const ptr0 = passStringToWasm0( + json, + wasm.__wbindgen_malloc, + wasm.__wbindgen_realloc, + ); + const len0 = WASM_VECTOR_LEN; + wasm.encode_json_str_to_metadatum(retptr, ptr0, len0, schema); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + if (r2) { + throw takeObject(r1); + } + return TransactionMetadatum.__wrap(r0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } +}; + +/** + * @param {TransactionMetadatum} metadatum + * @param {number} schema + * @returns {string} + */ +module.exports.decode_metadatum_to_json_str = function (metadatum, schema) { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + _assertClass(metadatum, TransactionMetadatum); + wasm.decode_metadatum_to_json_str(retptr, metadatum.ptr, schema); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + var r3 = getInt32Memory0()[retptr / 4 + 3]; + var ptr0 = r0; + var len0 = r1; + if (r3) { + ptr0 = 0; + len0 = 0; + throw takeObject(r2); + } + return getStringFromWasm0(ptr0, len0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + wasm.__wbindgen_free(ptr0, len0); + } +}; + +/** + * @param {string} json + * @param {number} schema + * @returns {PlutusData} + */ +module.exports.encode_json_str_to_plutus_datum = function (json, schema) { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + const ptr0 = passStringToWasm0( + json, + wasm.__wbindgen_malloc, + wasm.__wbindgen_realloc, + ); + const len0 = WASM_VECTOR_LEN; + wasm.encode_json_str_to_plutus_datum(retptr, ptr0, len0, schema); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + if (r2) { + throw takeObject(r1); + } + return PlutusData.__wrap(r0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } +}; + +/** + * @param {PlutusData} datum + * @param {number} schema + * @returns {string} + */ +module.exports.decode_plutus_datum_to_json_str = function (datum, schema) { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + _assertClass(datum, PlutusData); + wasm.decode_plutus_datum_to_json_str(retptr, datum.ptr, schema); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + var r3 = getInt32Memory0()[retptr / 4 + 3]; + var ptr0 = r0; + var len0 = r1; + if (r3) { + ptr0 = 0; + len0 = 0; + throw takeObject(r2); + } + return getStringFromWasm0(ptr0, len0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + wasm.__wbindgen_free(ptr0, len0); + } +}; + +let cachedUint32Memory0 = null; + +function getUint32Memory0() { + if (cachedUint32Memory0 === null || cachedUint32Memory0.byteLength === 0) { + cachedUint32Memory0 = new Uint32Array(wasm.memory.buffer); + } + return cachedUint32Memory0; +} + +function passArray32ToWasm0(arg, malloc) { + const ptr = malloc(arg.length * 4); + getUint32Memory0().set(arg, ptr / 4); + WASM_VECTOR_LEN = arg.length; + return ptr; +} + +function getArrayU32FromWasm0(ptr, len) { + return getUint32Memory0().subarray(ptr / 4, ptr / 4 + len); +} +/** + * @param {TransactionHash} tx_body_hash + * @param {ByronAddress} addr + * @param {LegacyDaedalusPrivateKey} key + * @returns {BootstrapWitness} + */ +module.exports.make_daedalus_bootstrap_witness = function ( + tx_body_hash, + addr, + key, +) { + _assertClass(tx_body_hash, TransactionHash); + _assertClass(addr, ByronAddress); + _assertClass(key, LegacyDaedalusPrivateKey); + const ret = wasm.make_daedalus_bootstrap_witness( + tx_body_hash.ptr, + addr.ptr, + key.ptr, + ); + return BootstrapWitness.__wrap(ret); +}; + +/** + * @param {TransactionHash} tx_body_hash + * @param {ByronAddress} addr + * @param {Bip32PrivateKey} key + * @returns {BootstrapWitness} + */ +module.exports.make_icarus_bootstrap_witness = function ( + tx_body_hash, + addr, + key, +) { + _assertClass(tx_body_hash, TransactionHash); + _assertClass(addr, ByronAddress); + _assertClass(key, Bip32PrivateKey); + const ret = wasm.make_icarus_bootstrap_witness( + tx_body_hash.ptr, + addr.ptr, + key.ptr, + ); + return BootstrapWitness.__wrap(ret); +}; + +/** + * @param {TransactionHash} tx_body_hash + * @param {PrivateKey} sk + * @returns {Vkeywitness} + */ +module.exports.make_vkey_witness = function (tx_body_hash, sk) { + _assertClass(tx_body_hash, TransactionHash); + _assertClass(sk, PrivateKey); + const ret = wasm.make_vkey_witness(tx_body_hash.ptr, sk.ptr); + return Vkeywitness.__wrap(ret); +}; + +/** + * @param {AuxiliaryData} auxiliary_data + * @returns {AuxiliaryDataHash} + */ +module.exports.hash_auxiliary_data = function (auxiliary_data) { + _assertClass(auxiliary_data, AuxiliaryData); + const ret = wasm.hash_auxiliary_data(auxiliary_data.ptr); + return AuxiliaryDataHash.__wrap(ret); +}; + +/** + * @param {TransactionBody} tx_body + * @returns {TransactionHash} + */ +module.exports.hash_transaction = function (tx_body) { + _assertClass(tx_body, TransactionBody); + const ret = wasm.hash_transaction(tx_body.ptr); + return TransactionHash.__wrap(ret); +}; + +/** + * @param {PlutusData} plutus_data + * @returns {DataHash} + */ +module.exports.hash_plutus_data = function (plutus_data) { + _assertClass(plutus_data, PlutusData); + const ret = wasm.hash_plutus_data(plutus_data.ptr); + return DataHash.__wrap(ret); +}; + +/** + * @param {Uint8Array} data + * @returns {Uint8Array} + */ +module.exports.hash_blake2b256 = function (data) { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + const ptr0 = passArray8ToWasm0(data, wasm.__wbindgen_malloc); + const len0 = WASM_VECTOR_LEN; + wasm.hash_blake2b256(retptr, ptr0, len0); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var v1 = getArrayU8FromWasm0(r0, r1).slice(); + wasm.__wbindgen_free(r0, r1 * 1); + return v1; + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } +}; + +/** + * @param {Uint8Array} data + * @returns {Uint8Array} + */ +module.exports.hash_blake2b224 = function (data) { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + const ptr0 = passArray8ToWasm0(data, wasm.__wbindgen_malloc); + const len0 = WASM_VECTOR_LEN; + wasm.hash_blake2b224(retptr, ptr0, len0); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var v1 = getArrayU8FromWasm0(r0, r1).slice(); + wasm.__wbindgen_free(r0, r1 * 1); + return v1; + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } +}; + +/** + * @param {Redeemers} redeemers + * @param {Costmdls} cost_models + * @param {PlutusList | undefined} datums + * @returns {ScriptDataHash} + */ +module.exports.hash_script_data = function (redeemers, cost_models, datums) { + _assertClass(redeemers, Redeemers); + _assertClass(cost_models, Costmdls); + let ptr0 = 0; + if (!isLikeNone(datums)) { + _assertClass(datums, PlutusList); + ptr0 = datums.__destroy_into_raw(); + } + const ret = wasm.hash_script_data(redeemers.ptr, cost_models.ptr, ptr0); + return ScriptDataHash.__wrap(ret); +}; + +/** + * @param {TransactionBody} txbody + * @param {BigNum} pool_deposit + * @param {BigNum} key_deposit + * @returns {Value} + */ +module.exports.get_implicit_input = function ( + txbody, + pool_deposit, + key_deposit, +) { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + _assertClass(txbody, TransactionBody); + _assertClass(pool_deposit, BigNum); + _assertClass(key_deposit, BigNum); + wasm.get_implicit_input( + retptr, + txbody.ptr, + pool_deposit.ptr, + key_deposit.ptr, + ); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + if (r2) { + throw takeObject(r1); + } + return Value.__wrap(r0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } +}; + +/** + * @param {TransactionBody} txbody + * @param {BigNum} pool_deposit + * @param {BigNum} key_deposit + * @returns {BigNum} + */ +module.exports.get_deposit = function (txbody, pool_deposit, key_deposit) { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + _assertClass(txbody, TransactionBody); + _assertClass(pool_deposit, BigNum); + _assertClass(key_deposit, BigNum); + wasm.get_deposit(retptr, txbody.ptr, pool_deposit.ptr, key_deposit.ptr); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + if (r2) { + throw takeObject(r1); + } + return BigNum.__wrap(r0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } +}; + +/** + * @param {TransactionOutput} output + * @param {BigNum} coins_per_utxo_byte + * @returns {BigNum} + */ +module.exports.min_ada_required = function (output, coins_per_utxo_byte) { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + _assertClass(output, TransactionOutput); + _assertClass(coins_per_utxo_byte, BigNum); + wasm.min_ada_required(retptr, output.ptr, coins_per_utxo_byte.ptr); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + if (r2) { + throw takeObject(r1); + } + return BigNum.__wrap(r0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } +}; + +/** + * Receives a script JSON string + * and returns a NativeScript. + * Cardano Wallet and Node styles are supported. + * + * * wallet: https://github.com/input-output-hk/cardano-wallet/blob/master/specifications/api/swagger.yaml + * * node: https://github.com/input-output-hk/cardano-node/blob/master/doc/reference/simple-scripts.md + * + * self_xpub is expected to be a Bip32PublicKey as hex-encoded bytes + * @param {string} json + * @param {string} self_xpub + * @param {number} schema + * @returns {NativeScript} + */ +module.exports.encode_json_str_to_native_script = function ( + json, + self_xpub, + schema, +) { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + const ptr0 = passStringToWasm0( + json, + wasm.__wbindgen_malloc, + wasm.__wbindgen_realloc, + ); + const len0 = WASM_VECTOR_LEN; + const ptr1 = passStringToWasm0( + self_xpub, + wasm.__wbindgen_malloc, + wasm.__wbindgen_realloc, + ); + const len1 = WASM_VECTOR_LEN; + wasm.encode_json_str_to_native_script( + retptr, + ptr0, + len0, + ptr1, + len1, + schema, + ); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + if (r2) { + throw takeObject(r1); + } + return NativeScript.__wrap(r0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } +}; + +/** + * @param {PlutusList} params + * @param {PlutusScript} plutus_script + * @returns {PlutusScript} + */ +module.exports.apply_params_to_plutus_script = function ( + params, + plutus_script, +) { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + _assertClass(params, PlutusList); + _assertClass(plutus_script, PlutusScript); + var ptr0 = plutus_script.__destroy_into_raw(); + wasm.apply_params_to_plutus_script(retptr, params.ptr, ptr0); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + if (r2) { + throw takeObject(r1); + } + return PlutusScript.__wrap(r0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } +}; + +function handleError(f, args) { + try { + return f.apply(this, args); + } catch (e) { + wasm.__wbindgen_exn_store(addHeapObject(e)); + } +} +function __wbg_adapter_1681(arg0, arg1, arg2, arg3) { + wasm.wasm_bindgen__convert__closures__invoke2_mut__h5b4d9f16616fac4b( + arg0, + arg1, + addHeapObject(arg2), + addHeapObject(arg3), + ); +} + +/** */ +module.exports.StakeCredKind = Object.freeze({ + Key: 0, + "0": "Key", + Script: 1, + "1": "Script", +}); +/** */ +module.exports.GovernanceActionKind = Object.freeze({ + ParameterChangeAction: 0, + "0": "ParameterChangeAction", + HardForkInitiationAction: 1, + "1": "HardForkInitiationAction", + TreasuryWithdrawalsAction: 2, + "2": "TreasuryWithdrawalsAction", + NoConfidence: 3, + "3": "NoConfidence", + NewCommittee: 4, + "4": "NewCommittee", + NewConstitution: 5, + "5": "NewConstitution", + InfoAction: 6, + "6": "InfoAction", +}); +/** */ +module.exports.VoterKind = Object.freeze({ + CommitteeHotKeyHash: 0, + "0": "CommitteeHotKeyHash", + CommitteeHotScriptHash: 1, + "1": "CommitteeHotScriptHash", + DrepKeyHash: 2, + "2": "DrepKeyHash", + DrepScriptHash: 3, + "3": "DrepScriptHash", + StakingPoolKeyHash: 4, + "4": "StakingPoolKeyHash", +}); +/** */ +module.exports.VoteKind = Object.freeze({ + No: 0, + "0": "No", + Yes: 1, + "1": "Yes", + Abstain: 2, + "2": "Abstain", +}); +/** */ +module.exports.DrepKind = Object.freeze({ + KeyHash: 0, + "0": "KeyHash", + ScriptHash: 1, + "1": "ScriptHash", + Abstain: 2, + "2": "Abstain", + NoConfidence: 3, + "3": "NoConfidence", +}); +/** */ +module.exports.TransactionMetadatumKind = Object.freeze({ + MetadataMap: 0, + "0": "MetadataMap", + MetadataList: 1, + "1": "MetadataList", + Int: 2, + "2": "Int", + Bytes: 3, + "3": "Bytes", + Text: 4, + "4": "Text", +}); +/** */ +module.exports.MetadataJsonSchema = Object.freeze({ + NoConversions: 0, + "0": "NoConversions", + BasicConversions: 1, + "1": "BasicConversions", + DetailedSchema: 2, + "2": "DetailedSchema", +}); +/** */ +module.exports.LanguageKind = Object.freeze({ + PlutusV1: 0, + "0": "PlutusV1", + PlutusV2: 1, + "1": "PlutusV2", + PlutusV3: 2, + "2": "PlutusV3", +}); +/** */ +module.exports.PlutusDataKind = Object.freeze({ + ConstrPlutusData: 0, + "0": "ConstrPlutusData", + Map: 1, + "1": "Map", + List: 2, + "2": "List", + Integer: 3, + "3": "Integer", + Bytes: 4, + "4": "Bytes", +}); +/** */ +module.exports.RedeemerTagKind = Object.freeze({ + Spend: 0, + "0": "Spend", + Mint: 1, + "1": "Mint", + Cert: 2, + "2": "Cert", + Reward: 3, + "3": "Reward", + Drep: 4, + "4": "Drep", +}); +/** + * JSON <-> PlutusData conversion schemas. + * Follows ScriptDataJsonSchema in cardano-cli defined at: + * https://github.com/input-output-hk/cardano-node/blob/master/cardano-api/src/Cardano/Api/ScriptData.hs#L254 + * + * All methods here have the following restrictions due to limitations on dependencies: + * * JSON numbers above u64::MAX (positive) or below i64::MIN (negative) will throw errors + * * Hex strings for bytes don't accept odd-length (half-byte) strings. + * cardano-cli seems to support these however but it seems to be different than just 0-padding + * on either side when tested so proceed with caution + */ +module.exports.PlutusDatumSchema = Object.freeze({ + /** + * ScriptDataJsonNoSchema in cardano-node. + * + * This is the format used by --script-data-value in cardano-cli + * This tries to accept most JSON but does not support the full spectrum of Plutus datums. + * From JSON: + * * null/true/false/floats NOT supported + * * strings starting with 0x are treated as hex bytes. All other strings are encoded as their utf8 bytes. + * To JSON: + * * ConstrPlutusData not supported in ANY FORM (neither keys nor values) + * * Lists not supported in keys + * * Maps not supported in keys + */ + BasicConversions: 0, + "0": "BasicConversions", + /** + * ScriptDataJsonDetailedSchema in cardano-node. + * + * This is the format used by --script-data-file in cardano-cli + * This covers almost all (only minor exceptions) Plutus datums, but the JSON must conform to a strict schema. + * The schema specifies that ALL keys and ALL values must be contained in a JSON map with 2 cases: + * 1. For ConstrPlutusData there must be two fields "constructor" contianing a number and "fields" containing its fields + * e.g. { "constructor": 2, "fields": [{"int": 2}, {"list": [{"bytes": "CAFEF00D"}]}]} + * 2. For all other cases there must be only one field named "int", "bytes", "list" or "map" + * Integer's value is a JSON number e.g. {"int": 100} + * Bytes' value is a hex string representing the bytes WITHOUT any prefix e.g. {"bytes": "CAFEF00D"} + * Lists' value is a JSON list of its elements encoded via the same schema e.g. {"list": [{"bytes": "CAFEF00D"}]} + * Maps' value is a JSON list of objects, one for each key-value pair in the map, with keys "k" and "v" + * respectively with their values being the plutus datum encoded via this same schema + * e.g. {"map": [ + * {"k": {"int": 2}, "v": {"int": 5}}, + * {"k": {"map": [{"k": {"list": [{"int": 1}]}, "v": {"bytes": "FF03"}}]}, "v": {"list": []}} + * ]} + * From JSON: + * * null/true/false/floats NOT supported + * * the JSON must conform to a very specific schema + * To JSON: + * * all Plutus datums should be fully supported outside of the integer range limitations outlined above. + */ + DetailedSchema: 1, + "1": "DetailedSchema", +}); +/** */ +module.exports.ScriptKind = Object.freeze({ + NativeScript: 0, + "0": "NativeScript", + PlutusScriptV1: 1, + "1": "PlutusScriptV1", + PlutusScriptV2: 2, + "2": "PlutusScriptV2", + PlutusScriptV3: 3, + "3": "PlutusScriptV3", +}); +/** */ +module.exports.DatumKind = Object.freeze({ + Hash: 0, + "0": "Hash", + Data: 1, + "1": "Data", +}); +/** + * Each new language uses a different namespace for hashing its script + * This is because you could have a language where the same bytes have different semantics + * So this avoids scripts in different languages mapping to the same hash + * Note that the enum value here is different than the enum value for deciding the cost model of a script + * https://github.com/input-output-hk/cardano-ledger/blob/9c3b4737b13b30f71529e76c5330f403165e28a6/eras/alonzo/impl/src/Cardano/Ledger/Alonzo.hs#L127 + */ +module.exports.ScriptHashNamespace = Object.freeze({ + NativeScript: 0, + "0": "NativeScript", + PlutusV1: 1, + "1": "PlutusV1", + PlutusV2: 2, + "2": "PlutusV2", +}); +/** + * Used to choose the schema for a script JSON string + */ +module.exports.ScriptSchema = Object.freeze({ + Wallet: 0, + "0": "Wallet", + Node: 1, + "1": "Node", +}); +/** */ +module.exports.ScriptWitnessKind = Object.freeze({ + NativeWitness: 0, + "0": "NativeWitness", + PlutusWitness: 1, + "1": "PlutusWitness", +}); +/** */ +module.exports.CertificateKind = Object.freeze({ + StakeRegistration: 0, + "0": "StakeRegistration", + StakeDeregistration: 1, + "1": "StakeDeregistration", + StakeDelegation: 2, + "2": "StakeDelegation", + PoolRegistration: 3, + "3": "PoolRegistration", + PoolRetirement: 4, + "4": "PoolRetirement", + GenesisKeyDelegation: 5, + "5": "GenesisKeyDelegation", + MoveInstantaneousRewardsCert: 6, + "6": "MoveInstantaneousRewardsCert", + RegCert: 7, + "7": "RegCert", + UnregCert: 8, + "8": "UnregCert", + VoteDelegCert: 9, + "9": "VoteDelegCert", + StakeVoteDelegCert: 10, + "10": "StakeVoteDelegCert", + StakeRegDelegCert: 11, + "11": "StakeRegDelegCert", + VoteRegDelegCert: 12, + "12": "VoteRegDelegCert", + StakeVoteRegDelegCert: 13, + "13": "StakeVoteRegDelegCert", + RegCommitteeHotKeyCert: 14, + "14": "RegCommitteeHotKeyCert", + UnregCommitteeHotKeyCert: 15, + "15": "UnregCommitteeHotKeyCert", + RegDrepCert: 16, + "16": "RegDrepCert", + UnregDrepCert: 17, + "17": "UnregDrepCert", +}); +/** */ +module.exports.MIRPot = Object.freeze({ + Reserves: 0, + "0": "Reserves", + Treasury: 1, + "1": "Treasury", +}); +/** */ +module.exports.MIRKind = Object.freeze({ + ToOtherPot: 0, + "0": "ToOtherPot", + ToStakeCredentials: 1, + "1": "ToStakeCredentials", +}); +/** */ +module.exports.RelayKind = Object.freeze({ + SingleHostAddr: 0, + "0": "SingleHostAddr", + SingleHostName: 1, + "1": "SingleHostName", + MultiHostName: 2, + "2": "MultiHostName", +}); +/** */ +module.exports.NativeScriptKind = Object.freeze({ + ScriptPubkey: 0, + "0": "ScriptPubkey", + ScriptAll: 1, + "1": "ScriptAll", + ScriptAny: 2, + "2": "ScriptAny", + ScriptNOfK: 3, + "3": "ScriptNOfK", + TimelockStart: 4, + "4": "TimelockStart", + TimelockExpiry: 5, + "5": "TimelockExpiry", +}); +/** */ +module.exports.NetworkIdKind = Object.freeze({ + Testnet: 0, + "0": "Testnet", + Mainnet: 1, + "1": "Mainnet", +}); + +const AddressFinalization = new FinalizationRegistry((ptr) => + wasm.__wbg_address_free(ptr) +); +/** */ +class Address { + static __wrap(ptr) { + const obj = Object.create(Address.prototype); + obj.ptr = ptr; + AddressFinalization.register(obj, obj.ptr, obj); + return obj; + } + + __destroy_into_raw() { + const ptr = this.ptr; + this.ptr = 0; + AddressFinalization.unregister(this); + return ptr; + } + + free() { + const ptr = this.__destroy_into_raw(); + wasm.__wbg_address_free(ptr); + } + /** + * @param {Uint8Array} data + * @returns {Address} + */ + static from_bytes(data) { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + const ptr0 = passArray8ToWasm0(data, wasm.__wbindgen_malloc); + const len0 = WASM_VECTOR_LEN; + wasm.address_from_bytes(retptr, ptr0, len0); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + if (r2) { + throw takeObject(r1); + } + return Address.__wrap(r0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @returns {string} + */ + to_json() { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + wasm.address_to_json(retptr, this.ptr); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + var r3 = getInt32Memory0()[retptr / 4 + 3]; + var ptr0 = r0; + var len0 = r1; + if (r3) { + ptr0 = 0; + len0 = 0; + throw takeObject(r2); + } + return getStringFromWasm0(ptr0, len0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + wasm.__wbindgen_free(ptr0, len0); + } + } + /** + * @returns {any} + */ + to_js_value() { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + wasm.address_to_js_value(retptr, this.ptr); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + if (r2) { + throw takeObject(r1); + } + return takeObject(r0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @param {string} json + * @returns {Address} + */ + static from_json(json) { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + const ptr0 = passStringToWasm0( + json, + wasm.__wbindgen_malloc, + wasm.__wbindgen_realloc, + ); + const len0 = WASM_VECTOR_LEN; + wasm.address_from_json(retptr, ptr0, len0); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + if (r2) { + throw takeObject(r1); + } + return Address.__wrap(r0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @returns {Uint8Array} + */ + to_bytes() { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + wasm.address_to_bytes(retptr, this.ptr); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var v0 = getArrayU8FromWasm0(r0, r1).slice(); + wasm.__wbindgen_free(r0, r1 * 1); + return v0; + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @param {string | undefined} prefix + * @returns {string} + */ + to_bech32(prefix) { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + var ptr0 = isLikeNone(prefix) + ? 0 + : passStringToWasm0( + prefix, + wasm.__wbindgen_malloc, + wasm.__wbindgen_realloc, + ); + var len0 = WASM_VECTOR_LEN; + wasm.address_to_bech32(retptr, this.ptr, ptr0, len0); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + var r3 = getInt32Memory0()[retptr / 4 + 3]; + var ptr1 = r0; + var len1 = r1; + if (r3) { + ptr1 = 0; + len1 = 0; + throw takeObject(r2); + } + return getStringFromWasm0(ptr1, len1); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + wasm.__wbindgen_free(ptr1, len1); + } + } + /** + * @param {string} bech_str + * @returns {Address} + */ + static from_bech32(bech_str) { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + const ptr0 = passStringToWasm0( + bech_str, + wasm.__wbindgen_malloc, + wasm.__wbindgen_realloc, + ); + const len0 = WASM_VECTOR_LEN; + wasm.address_from_bech32(retptr, ptr0, len0); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + if (r2) { + throw takeObject(r1); + } + return Address.__wrap(r0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @returns {number} + */ + network_id() { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + wasm.address_network_id(retptr, this.ptr); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + if (r2) { + throw takeObject(r1); + } + return r0; + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @returns {ByronAddress | undefined} + */ + as_byron() { + const ret = wasm.address_as_byron(this.ptr); + return ret === 0 ? undefined : ByronAddress.__wrap(ret); + } + /** + * @returns {RewardAddress | undefined} + */ + as_reward() { + const ret = wasm.address_as_reward(this.ptr); + return ret === 0 ? undefined : RewardAddress.__wrap(ret); + } + /** + * @returns {PointerAddress | undefined} + */ + as_pointer() { + const ret = wasm.address_as_pointer(this.ptr); + return ret === 0 ? undefined : PointerAddress.__wrap(ret); + } + /** + * @returns {EnterpriseAddress | undefined} + */ + as_enterprise() { + const ret = wasm.address_as_enterprise(this.ptr); + return ret === 0 ? undefined : EnterpriseAddress.__wrap(ret); + } + /** + * @returns {BaseAddress | undefined} + */ + as_base() { + const ret = wasm.address_as_base(this.ptr); + return ret === 0 ? undefined : BaseAddress.__wrap(ret); + } +} +module.exports.Address = Address; + +const AnchorFinalization = new FinalizationRegistry((ptr) => + wasm.__wbg_anchor_free(ptr) +); +/** */ +class Anchor { + static __wrap(ptr) { + const obj = Object.create(Anchor.prototype); + obj.ptr = ptr; + AnchorFinalization.register(obj, obj.ptr, obj); + return obj; + } + + __destroy_into_raw() { + const ptr = this.ptr; + this.ptr = 0; + AnchorFinalization.unregister(this); + return ptr; + } + + free() { + const ptr = this.__destroy_into_raw(); + wasm.__wbg_anchor_free(ptr); + } + /** + * @returns {Uint8Array} + */ + to_bytes() { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + wasm.anchor_to_bytes(retptr, this.ptr); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var v0 = getArrayU8FromWasm0(r0, r1).slice(); + wasm.__wbindgen_free(r0, r1 * 1); + return v0; + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @param {Uint8Array} bytes + * @returns {Anchor} + */ + static from_bytes(bytes) { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + const ptr0 = passArray8ToWasm0(bytes, wasm.__wbindgen_malloc); + const len0 = WASM_VECTOR_LEN; + wasm.anchor_from_bytes(retptr, ptr0, len0); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + if (r2) { + throw takeObject(r1); + } + return Anchor.__wrap(r0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @returns {string} + */ + to_json() { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + wasm.anchor_to_json(retptr, this.ptr); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + var r3 = getInt32Memory0()[retptr / 4 + 3]; + var ptr0 = r0; + var len0 = r1; + if (r3) { + ptr0 = 0; + len0 = 0; + throw takeObject(r2); + } + return getStringFromWasm0(ptr0, len0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + wasm.__wbindgen_free(ptr0, len0); + } + } + /** + * @returns {any} + */ + to_js_value() { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + wasm.anchor_to_js_value(retptr, this.ptr); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + if (r2) { + throw takeObject(r1); + } + return takeObject(r0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @param {string} json + * @returns {Anchor} + */ + static from_json(json) { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + const ptr0 = passStringToWasm0( + json, + wasm.__wbindgen_malloc, + wasm.__wbindgen_realloc, + ); + const len0 = WASM_VECTOR_LEN; + wasm.anchor_from_json(retptr, ptr0, len0); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + if (r2) { + throw takeObject(r1); + } + return Anchor.__wrap(r0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @returns {Url} + */ + anchor_url() { + const ret = wasm.anchor_anchor_url(this.ptr); + return Url.__wrap(ret); + } + /** + * @returns {DataHash} + */ + anchor_data_hash() { + const ret = wasm.anchor_anchor_data_hash(this.ptr); + return DataHash.__wrap(ret); + } + /** + * @param {Url} anchor_url + * @param {DataHash} anchor_data_hash + * @returns {Anchor} + */ + static new(anchor_url, anchor_data_hash) { + _assertClass(anchor_url, Url); + _assertClass(anchor_data_hash, DataHash); + const ret = wasm.anchor_new(anchor_url.ptr, anchor_data_hash.ptr); + return Anchor.__wrap(ret); + } +} +module.exports.Anchor = Anchor; + +const AssetNameFinalization = new FinalizationRegistry((ptr) => + wasm.__wbg_assetname_free(ptr) +); +/** */ +class AssetName { + static __wrap(ptr) { + const obj = Object.create(AssetName.prototype); + obj.ptr = ptr; + AssetNameFinalization.register(obj, obj.ptr, obj); + return obj; + } + + __destroy_into_raw() { + const ptr = this.ptr; + this.ptr = 0; + AssetNameFinalization.unregister(this); + return ptr; + } + + free() { + const ptr = this.__destroy_into_raw(); + wasm.__wbg_assetname_free(ptr); + } + /** + * @returns {Uint8Array} + */ + to_bytes() { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + wasm.assetname_to_bytes(retptr, this.ptr); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var v0 = getArrayU8FromWasm0(r0, r1).slice(); + wasm.__wbindgen_free(r0, r1 * 1); + return v0; + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @param {Uint8Array} bytes + * @returns {AssetName} + */ + static from_bytes(bytes) { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + const ptr0 = passArray8ToWasm0(bytes, wasm.__wbindgen_malloc); + const len0 = WASM_VECTOR_LEN; + wasm.assetname_from_bytes(retptr, ptr0, len0); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + if (r2) { + throw takeObject(r1); + } + return AssetName.__wrap(r0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @returns {string} + */ + to_json() { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + wasm.assetname_to_json(retptr, this.ptr); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + var r3 = getInt32Memory0()[retptr / 4 + 3]; + var ptr0 = r0; + var len0 = r1; + if (r3) { + ptr0 = 0; + len0 = 0; + throw takeObject(r2); + } + return getStringFromWasm0(ptr0, len0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + wasm.__wbindgen_free(ptr0, len0); + } + } + /** + * @returns {any} + */ + to_js_value() { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + wasm.assetname_to_js_value(retptr, this.ptr); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + if (r2) { + throw takeObject(r1); + } + return takeObject(r0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @param {string} json + * @returns {AssetName} + */ + static from_json(json) { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + const ptr0 = passStringToWasm0( + json, + wasm.__wbindgen_malloc, + wasm.__wbindgen_realloc, + ); + const len0 = WASM_VECTOR_LEN; + wasm.assetname_from_json(retptr, ptr0, len0); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + if (r2) { + throw takeObject(r1); + } + return AssetName.__wrap(r0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @param {Uint8Array} name + * @returns {AssetName} + */ + static new(name) { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + const ptr0 = passArray8ToWasm0(name, wasm.__wbindgen_malloc); + const len0 = WASM_VECTOR_LEN; + wasm.assetname_new(retptr, ptr0, len0); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + if (r2) { + throw takeObject(r1); + } + return AssetName.__wrap(r0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @returns {Uint8Array} + */ + name() { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + wasm.assetname_name(retptr, this.ptr); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var v0 = getArrayU8FromWasm0(r0, r1).slice(); + wasm.__wbindgen_free(r0, r1 * 1); + return v0; + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } +} +module.exports.AssetName = AssetName; + +const AssetNamesFinalization = new FinalizationRegistry((ptr) => + wasm.__wbg_assetnames_free(ptr) +); +/** */ +class AssetNames { + static __wrap(ptr) { + const obj = Object.create(AssetNames.prototype); + obj.ptr = ptr; + AssetNamesFinalization.register(obj, obj.ptr, obj); + return obj; + } + + __destroy_into_raw() { + const ptr = this.ptr; + this.ptr = 0; + AssetNamesFinalization.unregister(this); + return ptr; + } + + free() { + const ptr = this.__destroy_into_raw(); + wasm.__wbg_assetnames_free(ptr); + } + /** + * @returns {Uint8Array} + */ + to_bytes() { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + wasm.assetnames_to_bytes(retptr, this.ptr); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var v0 = getArrayU8FromWasm0(r0, r1).slice(); + wasm.__wbindgen_free(r0, r1 * 1); + return v0; + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @param {Uint8Array} bytes + * @returns {AssetNames} + */ + static from_bytes(bytes) { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + const ptr0 = passArray8ToWasm0(bytes, wasm.__wbindgen_malloc); + const len0 = WASM_VECTOR_LEN; + wasm.assetnames_from_bytes(retptr, ptr0, len0); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + if (r2) { + throw takeObject(r1); + } + return AssetNames.__wrap(r0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @returns {string} + */ + to_json() { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + wasm.assetnames_to_json(retptr, this.ptr); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + var r3 = getInt32Memory0()[retptr / 4 + 3]; + var ptr0 = r0; + var len0 = r1; + if (r3) { + ptr0 = 0; + len0 = 0; + throw takeObject(r2); + } + return getStringFromWasm0(ptr0, len0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + wasm.__wbindgen_free(ptr0, len0); + } + } + /** + * @returns {any} + */ + to_js_value() { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + wasm.assetnames_to_js_value(retptr, this.ptr); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + if (r2) { + throw takeObject(r1); + } + return takeObject(r0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @param {string} json + * @returns {AssetNames} + */ + static from_json(json) { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + const ptr0 = passStringToWasm0( + json, + wasm.__wbindgen_malloc, + wasm.__wbindgen_realloc, + ); + const len0 = WASM_VECTOR_LEN; + wasm.assetnames_from_json(retptr, ptr0, len0); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + if (r2) { + throw takeObject(r1); + } + return AssetNames.__wrap(r0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @returns {AssetNames} + */ + static new() { + const ret = wasm.assetnames_new(); + return AssetNames.__wrap(ret); + } + /** + * @returns {number} + */ + len() { + const ret = wasm.assetnames_len(this.ptr); + return ret >>> 0; + } + /** + * @param {number} index + * @returns {AssetName} + */ + get(index) { + const ret = wasm.assetnames_get(this.ptr, index); + return AssetName.__wrap(ret); + } + /** + * @param {AssetName} elem + */ + add(elem) { + _assertClass(elem, AssetName); + wasm.assetnames_add(this.ptr, elem.ptr); + } +} +module.exports.AssetNames = AssetNames; + +const AssetsFinalization = new FinalizationRegistry((ptr) => + wasm.__wbg_assets_free(ptr) +); +/** */ +class Assets { + static __wrap(ptr) { + const obj = Object.create(Assets.prototype); + obj.ptr = ptr; + AssetsFinalization.register(obj, obj.ptr, obj); + return obj; + } + + __destroy_into_raw() { + const ptr = this.ptr; + this.ptr = 0; + AssetsFinalization.unregister(this); + return ptr; + } + + free() { + const ptr = this.__destroy_into_raw(); + wasm.__wbg_assets_free(ptr); + } + /** + * @returns {Uint8Array} + */ + to_bytes() { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + wasm.assets_to_bytes(retptr, this.ptr); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var v0 = getArrayU8FromWasm0(r0, r1).slice(); + wasm.__wbindgen_free(r0, r1 * 1); + return v0; + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @param {Uint8Array} bytes + * @returns {Assets} + */ + static from_bytes(bytes) { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + const ptr0 = passArray8ToWasm0(bytes, wasm.__wbindgen_malloc); + const len0 = WASM_VECTOR_LEN; + wasm.assets_from_bytes(retptr, ptr0, len0); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + if (r2) { + throw takeObject(r1); + } + return Assets.__wrap(r0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @returns {string} + */ + to_json() { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + wasm.assets_to_json(retptr, this.ptr); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + var r3 = getInt32Memory0()[retptr / 4 + 3]; + var ptr0 = r0; + var len0 = r1; + if (r3) { + ptr0 = 0; + len0 = 0; + throw takeObject(r2); + } + return getStringFromWasm0(ptr0, len0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + wasm.__wbindgen_free(ptr0, len0); + } + } + /** + * @returns {any} + */ + to_js_value() { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + wasm.assets_to_js_value(retptr, this.ptr); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + if (r2) { + throw takeObject(r1); + } + return takeObject(r0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @param {string} json + * @returns {Assets} + */ + static from_json(json) { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + const ptr0 = passStringToWasm0( + json, + wasm.__wbindgen_malloc, + wasm.__wbindgen_realloc, + ); + const len0 = WASM_VECTOR_LEN; + wasm.assets_from_json(retptr, ptr0, len0); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + if (r2) { + throw takeObject(r1); + } + return Assets.__wrap(r0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @returns {Assets} + */ + static new() { + const ret = wasm.assets_new(); + return Assets.__wrap(ret); + } + /** + * @returns {number} + */ + len() { + const ret = wasm.assetnames_len(this.ptr); + return ret >>> 0; + } + /** + * @param {AssetName} key + * @param {BigNum} value + * @returns {BigNum | undefined} + */ + insert(key, value) { + _assertClass(key, AssetName); + _assertClass(value, BigNum); + const ret = wasm.assets_insert(this.ptr, key.ptr, value.ptr); + return ret === 0 ? undefined : BigNum.__wrap(ret); + } + /** + * @param {AssetName} key + * @returns {BigNum | undefined} + */ + get(key) { + _assertClass(key, AssetName); + const ret = wasm.assets_get(this.ptr, key.ptr); + return ret === 0 ? undefined : BigNum.__wrap(ret); + } + /** + * @returns {AssetNames} + */ + keys() { + const ret = wasm.assets_keys(this.ptr); + return AssetNames.__wrap(ret); + } +} +module.exports.Assets = Assets; + +const AuxiliaryDataFinalization = new FinalizationRegistry((ptr) => + wasm.__wbg_auxiliarydata_free(ptr) +); +/** */ +class AuxiliaryData { + static __wrap(ptr) { + const obj = Object.create(AuxiliaryData.prototype); + obj.ptr = ptr; + AuxiliaryDataFinalization.register(obj, obj.ptr, obj); + return obj; + } + + __destroy_into_raw() { + const ptr = this.ptr; + this.ptr = 0; + AuxiliaryDataFinalization.unregister(this); + return ptr; + } + + free() { + const ptr = this.__destroy_into_raw(); + wasm.__wbg_auxiliarydata_free(ptr); + } + /** + * @returns {Uint8Array} + */ + to_bytes() { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + wasm.auxiliarydata_to_bytes(retptr, this.ptr); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var v0 = getArrayU8FromWasm0(r0, r1).slice(); + wasm.__wbindgen_free(r0, r1 * 1); + return v0; + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @param {Uint8Array} bytes + * @returns {AuxiliaryData} + */ + static from_bytes(bytes) { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + const ptr0 = passArray8ToWasm0(bytes, wasm.__wbindgen_malloc); + const len0 = WASM_VECTOR_LEN; + wasm.auxiliarydata_from_bytes(retptr, ptr0, len0); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + if (r2) { + throw takeObject(r1); + } + return AuxiliaryData.__wrap(r0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @returns {string} + */ + to_json() { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + wasm.auxiliarydata_to_json(retptr, this.ptr); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + var r3 = getInt32Memory0()[retptr / 4 + 3]; + var ptr0 = r0; + var len0 = r1; + if (r3) { + ptr0 = 0; + len0 = 0; + throw takeObject(r2); + } + return getStringFromWasm0(ptr0, len0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + wasm.__wbindgen_free(ptr0, len0); + } + } + /** + * @returns {any} + */ + to_js_value() { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + wasm.auxiliarydata_to_js_value(retptr, this.ptr); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + if (r2) { + throw takeObject(r1); + } + return takeObject(r0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @param {string} json + * @returns {AuxiliaryData} + */ + static from_json(json) { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + const ptr0 = passStringToWasm0( + json, + wasm.__wbindgen_malloc, + wasm.__wbindgen_realloc, + ); + const len0 = WASM_VECTOR_LEN; + wasm.auxiliarydata_from_json(retptr, ptr0, len0); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + if (r2) { + throw takeObject(r1); + } + return AuxiliaryData.__wrap(r0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @returns {AuxiliaryData} + */ + static new() { + const ret = wasm.auxiliarydata_new(); + return AuxiliaryData.__wrap(ret); + } + /** + * @returns {GeneralTransactionMetadata | undefined} + */ + metadata() { + const ret = wasm.auxiliarydata_metadata(this.ptr); + return ret === 0 ? undefined : GeneralTransactionMetadata.__wrap(ret); + } + /** + * @param {GeneralTransactionMetadata} metadata + */ + set_metadata(metadata) { + _assertClass(metadata, GeneralTransactionMetadata); + wasm.auxiliarydata_set_metadata(this.ptr, metadata.ptr); + } + /** + * @returns {NativeScripts | undefined} + */ + native_scripts() { + const ret = wasm.auxiliarydata_native_scripts(this.ptr); + return ret === 0 ? undefined : NativeScripts.__wrap(ret); + } + /** + * @param {NativeScripts} native_scripts + */ + set_native_scripts(native_scripts) { + _assertClass(native_scripts, NativeScripts); + wasm.auxiliarydata_set_native_scripts(this.ptr, native_scripts.ptr); + } + /** + * @returns {PlutusScripts | undefined} + */ + plutus_scripts() { + const ret = wasm.auxiliarydata_plutus_scripts(this.ptr); + return ret === 0 ? undefined : PlutusScripts.__wrap(ret); + } + /** + * @returns {PlutusScripts | undefined} + */ + plutus_v2_scripts() { + const ret = wasm.auxiliarydata_plutus_v2_scripts(this.ptr); + return ret === 0 ? undefined : PlutusScripts.__wrap(ret); + } + /** + * @returns {PlutusScripts | undefined} + */ + plutus_v3_scripts() { + const ret = wasm.auxiliarydata_plutus_v3_scripts(this.ptr); + return ret === 0 ? undefined : PlutusScripts.__wrap(ret); + } + /** + * @param {PlutusScripts} plutus_scripts + */ + set_plutus_scripts(plutus_scripts) { + _assertClass(plutus_scripts, PlutusScripts); + wasm.auxiliarydata_set_plutus_scripts(this.ptr, plutus_scripts.ptr); + } + /** + * @param {PlutusScripts} plutus_scripts + */ + set_plutus_v2_scripts(plutus_scripts) { + _assertClass(plutus_scripts, PlutusScripts); + wasm.auxiliarydata_set_plutus_v2_scripts(this.ptr, plutus_scripts.ptr); + } + /** + * @param {PlutusScripts} plutus_scripts + */ + set_plutus_v3_scripts(plutus_scripts) { + _assertClass(plutus_scripts, PlutusScripts); + wasm.auxiliarydata_set_plutus_v3_scripts(this.ptr, plutus_scripts.ptr); + } +} +module.exports.AuxiliaryData = AuxiliaryData; + +const AuxiliaryDataHashFinalization = new FinalizationRegistry((ptr) => + wasm.__wbg_auxiliarydatahash_free(ptr) +); +/** */ +class AuxiliaryDataHash { + static __wrap(ptr) { + const obj = Object.create(AuxiliaryDataHash.prototype); + obj.ptr = ptr; + AuxiliaryDataHashFinalization.register(obj, obj.ptr, obj); + return obj; + } + + __destroy_into_raw() { + const ptr = this.ptr; + this.ptr = 0; + AuxiliaryDataHashFinalization.unregister(this); + return ptr; + } + + free() { + const ptr = this.__destroy_into_raw(); + wasm.__wbg_auxiliarydatahash_free(ptr); + } + /** + * @param {Uint8Array} bytes + * @returns {AuxiliaryDataHash} + */ + static from_bytes(bytes) { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + const ptr0 = passArray8ToWasm0(bytes, wasm.__wbindgen_malloc); + const len0 = WASM_VECTOR_LEN; + wasm.auxiliarydatahash_from_bytes(retptr, ptr0, len0); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + if (r2) { + throw takeObject(r1); + } + return AuxiliaryDataHash.__wrap(r0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @returns {Uint8Array} + */ + to_bytes() { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + wasm.auxiliarydatahash_to_bytes(retptr, this.ptr); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var v0 = getArrayU8FromWasm0(r0, r1).slice(); + wasm.__wbindgen_free(r0, r1 * 1); + return v0; + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @param {string} prefix + * @returns {string} + */ + to_bech32(prefix) { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + const ptr0 = passStringToWasm0( + prefix, + wasm.__wbindgen_malloc, + wasm.__wbindgen_realloc, + ); + const len0 = WASM_VECTOR_LEN; + wasm.auxiliarydatahash_to_bech32(retptr, this.ptr, ptr0, len0); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + var r3 = getInt32Memory0()[retptr / 4 + 3]; + var ptr1 = r0; + var len1 = r1; + if (r3) { + ptr1 = 0; + len1 = 0; + throw takeObject(r2); + } + return getStringFromWasm0(ptr1, len1); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + wasm.__wbindgen_free(ptr1, len1); + } + } + /** + * @param {string} bech_str + * @returns {AuxiliaryDataHash} + */ + static from_bech32(bech_str) { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + const ptr0 = passStringToWasm0( + bech_str, + wasm.__wbindgen_malloc, + wasm.__wbindgen_realloc, + ); + const len0 = WASM_VECTOR_LEN; + wasm.auxiliarydatahash_from_bech32(retptr, ptr0, len0); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + if (r2) { + throw takeObject(r1); + } + return AuxiliaryDataHash.__wrap(r0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @returns {string} + */ + to_hex() { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + wasm.auxiliarydatahash_to_hex(retptr, this.ptr); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + return getStringFromWasm0(r0, r1); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + wasm.__wbindgen_free(r0, r1); + } + } + /** + * @param {string} hex + * @returns {AuxiliaryDataHash} + */ + static from_hex(hex) { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + const ptr0 = passStringToWasm0( + hex, + wasm.__wbindgen_malloc, + wasm.__wbindgen_realloc, + ); + const len0 = WASM_VECTOR_LEN; + wasm.auxiliarydatahash_from_hex(retptr, ptr0, len0); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + if (r2) { + throw takeObject(r1); + } + return AuxiliaryDataHash.__wrap(r0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } +} +module.exports.AuxiliaryDataHash = AuxiliaryDataHash; + +const AuxiliaryDataSetFinalization = new FinalizationRegistry((ptr) => + wasm.__wbg_auxiliarydataset_free(ptr) +); +/** */ +class AuxiliaryDataSet { + static __wrap(ptr) { + const obj = Object.create(AuxiliaryDataSet.prototype); + obj.ptr = ptr; + AuxiliaryDataSetFinalization.register(obj, obj.ptr, obj); + return obj; + } + + __destroy_into_raw() { + const ptr = this.ptr; + this.ptr = 0; + AuxiliaryDataSetFinalization.unregister(this); + return ptr; + } + + free() { + const ptr = this.__destroy_into_raw(); + wasm.__wbg_auxiliarydataset_free(ptr); + } + /** + * @returns {AuxiliaryDataSet} + */ + static new() { + const ret = wasm.auxiliarydataset_new(); + return AuxiliaryDataSet.__wrap(ret); + } + /** + * @returns {number} + */ + len() { + const ret = wasm.auxiliarydataset_len(this.ptr); + return ret >>> 0; + } + /** + * @param {BigNum} tx_index + * @param {AuxiliaryData} data + * @returns {AuxiliaryData | undefined} + */ + insert(tx_index, data) { + _assertClass(tx_index, BigNum); + _assertClass(data, AuxiliaryData); + const ret = wasm.auxiliarydataset_insert(this.ptr, tx_index.ptr, data.ptr); + return ret === 0 ? undefined : AuxiliaryData.__wrap(ret); + } + /** + * @param {BigNum} tx_index + * @returns {AuxiliaryData | undefined} + */ + get(tx_index) { + _assertClass(tx_index, BigNum); + const ret = wasm.auxiliarydataset_get(this.ptr, tx_index.ptr); + return ret === 0 ? undefined : AuxiliaryData.__wrap(ret); + } + /** + * @returns {TransactionIndexes} + */ + indices() { + const ret = wasm.auxiliarydataset_indices(this.ptr); + return TransactionIndexes.__wrap(ret); + } +} +module.exports.AuxiliaryDataSet = AuxiliaryDataSet; + +const BaseAddressFinalization = new FinalizationRegistry((ptr) => + wasm.__wbg_baseaddress_free(ptr) +); +/** */ +class BaseAddress { + static __wrap(ptr) { + const obj = Object.create(BaseAddress.prototype); + obj.ptr = ptr; + BaseAddressFinalization.register(obj, obj.ptr, obj); + return obj; + } + + __destroy_into_raw() { + const ptr = this.ptr; + this.ptr = 0; + BaseAddressFinalization.unregister(this); + return ptr; + } + + free() { + const ptr = this.__destroy_into_raw(); + wasm.__wbg_baseaddress_free(ptr); + } + /** + * @param {number} network + * @param {StakeCredential} payment + * @param {StakeCredential} stake + * @returns {BaseAddress} + */ + static new(network, payment, stake) { + _assertClass(payment, StakeCredential); + _assertClass(stake, StakeCredential); + const ret = wasm.baseaddress_new(network, payment.ptr, stake.ptr); + return BaseAddress.__wrap(ret); + } + /** + * @returns {StakeCredential} + */ + payment_cred() { + const ret = wasm.baseaddress_payment_cred(this.ptr); + return StakeCredential.__wrap(ret); + } + /** + * @returns {StakeCredential} + */ + stake_cred() { + const ret = wasm.baseaddress_stake_cred(this.ptr); + return StakeCredential.__wrap(ret); + } + /** + * @returns {Address} + */ + to_address() { + const ret = wasm.baseaddress_to_address(this.ptr); + return Address.__wrap(ret); + } + /** + * @param {Address} addr + * @returns {BaseAddress | undefined} + */ + static from_address(addr) { + _assertClass(addr, Address); + const ret = wasm.address_as_base(addr.ptr); + return ret === 0 ? undefined : BaseAddress.__wrap(ret); + } +} +module.exports.BaseAddress = BaseAddress; + +const BigIntFinalization = new FinalizationRegistry((ptr) => + wasm.__wbg_bigint_free(ptr) +); +/** */ +class BigInt { + static __wrap(ptr) { + const obj = Object.create(BigInt.prototype); + obj.ptr = ptr; + BigIntFinalization.register(obj, obj.ptr, obj); + return obj; + } + + __destroy_into_raw() { + const ptr = this.ptr; + this.ptr = 0; + BigIntFinalization.unregister(this); + return ptr; + } + + free() { + const ptr = this.__destroy_into_raw(); + wasm.__wbg_bigint_free(ptr); + } + /** + * @returns {Uint8Array} + */ + to_bytes() { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + wasm.bigint_to_bytes(retptr, this.ptr); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var v0 = getArrayU8FromWasm0(r0, r1).slice(); + wasm.__wbindgen_free(r0, r1 * 1); + return v0; + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @param {Uint8Array} bytes + * @returns {BigInt} + */ + static from_bytes(bytes) { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + const ptr0 = passArray8ToWasm0(bytes, wasm.__wbindgen_malloc); + const len0 = WASM_VECTOR_LEN; + wasm.bigint_from_bytes(retptr, ptr0, len0); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + if (r2) { + throw takeObject(r1); + } + return BigInt.__wrap(r0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @returns {BigNum | undefined} + */ + as_u64() { + const ret = wasm.bigint_as_u64(this.ptr); + return ret === 0 ? undefined : BigNum.__wrap(ret); + } + /** + * @returns {Int | undefined} + */ + as_int() { + const ret = wasm.bigint_as_int(this.ptr); + return ret === 0 ? undefined : Int.__wrap(ret); + } + /** + * @param {string} text + * @returns {BigInt} + */ + static from_str(text) { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + const ptr0 = passStringToWasm0( + text, + wasm.__wbindgen_malloc, + wasm.__wbindgen_realloc, + ); + const len0 = WASM_VECTOR_LEN; + wasm.bigint_from_str(retptr, ptr0, len0); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + if (r2) { + throw takeObject(r1); + } + return BigInt.__wrap(r0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @returns {string} + */ + to_str() { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + wasm.bigint_to_str(retptr, this.ptr); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + return getStringFromWasm0(r0, r1); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + wasm.__wbindgen_free(r0, r1); + } + } +} +module.exports.BigInt = BigInt; + +const BigNumFinalization = new FinalizationRegistry((ptr) => + wasm.__wbg_bignum_free(ptr) +); +/** */ +class BigNum { + static __wrap(ptr) { + const obj = Object.create(BigNum.prototype); + obj.ptr = ptr; + BigNumFinalization.register(obj, obj.ptr, obj); + return obj; + } + + __destroy_into_raw() { + const ptr = this.ptr; + this.ptr = 0; + BigNumFinalization.unregister(this); + return ptr; + } + + free() { + const ptr = this.__destroy_into_raw(); + wasm.__wbg_bignum_free(ptr); + } + /** + * @returns {Uint8Array} + */ + to_bytes() { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + wasm.bignum_to_bytes(retptr, this.ptr); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var v0 = getArrayU8FromWasm0(r0, r1).slice(); + wasm.__wbindgen_free(r0, r1 * 1); + return v0; + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @param {Uint8Array} bytes + * @returns {BigNum} + */ + static from_bytes(bytes) { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + const ptr0 = passArray8ToWasm0(bytes, wasm.__wbindgen_malloc); + const len0 = WASM_VECTOR_LEN; + wasm.bignum_from_bytes(retptr, ptr0, len0); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + if (r2) { + throw takeObject(r1); + } + return BigNum.__wrap(r0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @param {string} string + * @returns {BigNum} + */ + static from_str(string) { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + const ptr0 = passStringToWasm0( + string, + wasm.__wbindgen_malloc, + wasm.__wbindgen_realloc, + ); + const len0 = WASM_VECTOR_LEN; + wasm.bignum_from_str(retptr, ptr0, len0); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + if (r2) { + throw takeObject(r1); + } + return BigNum.__wrap(r0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @returns {string} + */ + to_str() { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + wasm.bignum_to_str(retptr, this.ptr); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + return getStringFromWasm0(r0, r1); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + wasm.__wbindgen_free(r0, r1); + } + } + /** + * @returns {BigNum} + */ + static zero() { + const ret = wasm.bignum_zero(); + return BigNum.__wrap(ret); + } + /** + * @returns {boolean} + */ + is_zero() { + const ret = wasm.bignum_is_zero(this.ptr); + return ret !== 0; + } + /** + * @param {BigNum} other + * @returns {BigNum} + */ + checked_mul(other) { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + _assertClass(other, BigNum); + wasm.bignum_checked_mul(retptr, this.ptr, other.ptr); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + if (r2) { + throw takeObject(r1); + } + return BigNum.__wrap(r0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @param {BigNum} other + * @returns {BigNum} + */ + checked_add(other) { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + _assertClass(other, BigNum); + wasm.bignum_checked_add(retptr, this.ptr, other.ptr); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + if (r2) { + throw takeObject(r1); + } + return BigNum.__wrap(r0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @param {BigNum} other + * @returns {BigNum} + */ + checked_sub(other) { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + _assertClass(other, BigNum); + wasm.bignum_checked_sub(retptr, this.ptr, other.ptr); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + if (r2) { + throw takeObject(r1); + } + return BigNum.__wrap(r0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @param {BigNum} other + * @returns {BigNum} + */ + checked_div(other) { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + _assertClass(other, BigNum); + wasm.bignum_checked_div(retptr, this.ptr, other.ptr); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + if (r2) { + throw takeObject(r1); + } + return BigNum.__wrap(r0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @param {BigNum} other + * @returns {BigNum} + */ + checked_div_ceil(other) { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + _assertClass(other, BigNum); + wasm.bignum_checked_div_ceil(retptr, this.ptr, other.ptr); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + if (r2) { + throw takeObject(r1); + } + return BigNum.__wrap(r0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * returns 0 if it would otherwise underflow + * @param {BigNum} other + * @returns {BigNum} + */ + clamped_sub(other) { + _assertClass(other, BigNum); + const ret = wasm.bignum_clamped_sub(this.ptr, other.ptr); + return BigNum.__wrap(ret); + } + /** + * @param {BigNum} rhs_value + * @returns {number} + */ + compare(rhs_value) { + _assertClass(rhs_value, BigNum); + const ret = wasm.bignum_compare(this.ptr, rhs_value.ptr); + return ret; + } +} +module.exports.BigNum = BigNum; + +const Bip32PrivateKeyFinalization = new FinalizationRegistry((ptr) => + wasm.__wbg_bip32privatekey_free(ptr) +); +/** */ +class Bip32PrivateKey { + static __wrap(ptr) { + const obj = Object.create(Bip32PrivateKey.prototype); + obj.ptr = ptr; + Bip32PrivateKeyFinalization.register(obj, obj.ptr, obj); + return obj; + } + + __destroy_into_raw() { + const ptr = this.ptr; + this.ptr = 0; + Bip32PrivateKeyFinalization.unregister(this); + return ptr; + } + + free() { + const ptr = this.__destroy_into_raw(); + wasm.__wbg_bip32privatekey_free(ptr); + } + /** + * derive this private key with the given index. + * + * # Security considerations + * + * * hard derivation index cannot be soft derived with the public key + * + * # Hard derivation vs Soft derivation + * + * If you pass an index below 0x80000000 then it is a soft derivation. + * The advantage of soft derivation is that it is possible to derive the + * public key too. I.e. derivation the private key with a soft derivation + * index and then retrieving the associated public key is equivalent to + * deriving the public key associated to the parent private key. + * + * Hard derivation index does not allow public key derivation. + * + * This is why deriving the private key should not fail while deriving + * the public key may fail (if the derivation index is invalid). + * @param {number} index + * @returns {Bip32PrivateKey} + */ + derive(index) { + const ret = wasm.bip32privatekey_derive(this.ptr, index); + return Bip32PrivateKey.__wrap(ret); + } + /** + * 128-byte xprv a key format in Cardano that some software still uses or requires + * the traditional 96-byte xprv is simply encoded as + * prv | chaincode + * however, because some software may not know how to compute a public key from a private key, + * the 128-byte inlines the public key in the following format + * prv | pub | chaincode + * so be careful if you see the term "xprv" as it could refer to either one + * our library does not require the pub (instead we compute the pub key when needed) + * @param {Uint8Array} bytes + * @returns {Bip32PrivateKey} + */ + static from_128_xprv(bytes) { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + const ptr0 = passArray8ToWasm0(bytes, wasm.__wbindgen_malloc); + const len0 = WASM_VECTOR_LEN; + wasm.bip32privatekey_from_128_xprv(retptr, ptr0, len0); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + if (r2) { + throw takeObject(r1); + } + return Bip32PrivateKey.__wrap(r0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * see from_128_xprv + * @returns {Uint8Array} + */ + to_128_xprv() { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + wasm.bip32privatekey_to_128_xprv(retptr, this.ptr); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var v0 = getArrayU8FromWasm0(r0, r1).slice(); + wasm.__wbindgen_free(r0, r1 * 1); + return v0; + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @returns {Bip32PrivateKey} + */ + static generate_ed25519_bip32() { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + wasm.bip32privatekey_generate_ed25519_bip32(retptr); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + if (r2) { + throw takeObject(r1); + } + return Bip32PrivateKey.__wrap(r0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @returns {PrivateKey} + */ + to_raw_key() { + const ret = wasm.bip32privatekey_to_raw_key(this.ptr); + return PrivateKey.__wrap(ret); + } + /** + * @returns {Bip32PublicKey} + */ + to_public() { + const ret = wasm.bip32privatekey_to_public(this.ptr); + return Bip32PublicKey.__wrap(ret); + } + /** + * @param {Uint8Array} bytes + * @returns {Bip32PrivateKey} + */ + static from_bytes(bytes) { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + const ptr0 = passArray8ToWasm0(bytes, wasm.__wbindgen_malloc); + const len0 = WASM_VECTOR_LEN; + wasm.bip32privatekey_from_bytes(retptr, ptr0, len0); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + if (r2) { + throw takeObject(r1); + } + return Bip32PrivateKey.__wrap(r0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @returns {Uint8Array} + */ + as_bytes() { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + wasm.bip32privatekey_as_bytes(retptr, this.ptr); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var v0 = getArrayU8FromWasm0(r0, r1).slice(); + wasm.__wbindgen_free(r0, r1 * 1); + return v0; + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @param {string} bech32_str + * @returns {Bip32PrivateKey} + */ + static from_bech32(bech32_str) { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + const ptr0 = passStringToWasm0( + bech32_str, + wasm.__wbindgen_malloc, + wasm.__wbindgen_realloc, + ); + const len0 = WASM_VECTOR_LEN; + wasm.bip32privatekey_from_bech32(retptr, ptr0, len0); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + if (r2) { + throw takeObject(r1); + } + return Bip32PrivateKey.__wrap(r0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @returns {string} + */ + to_bech32() { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + wasm.bip32privatekey_to_bech32(retptr, this.ptr); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + return getStringFromWasm0(r0, r1); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + wasm.__wbindgen_free(r0, r1); + } + } + /** + * @param {Uint8Array} entropy + * @param {Uint8Array} password + * @returns {Bip32PrivateKey} + */ + static from_bip39_entropy(entropy, password) { + const ptr0 = passArray8ToWasm0(entropy, wasm.__wbindgen_malloc); + const len0 = WASM_VECTOR_LEN; + const ptr1 = passArray8ToWasm0(password, wasm.__wbindgen_malloc); + const len1 = WASM_VECTOR_LEN; + const ret = wasm.bip32privatekey_from_bip39_entropy(ptr0, len0, ptr1, len1); + return Bip32PrivateKey.__wrap(ret); + } + /** + * @returns {Uint8Array} + */ + chaincode() { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + wasm.bip32privatekey_chaincode(retptr, this.ptr); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var v0 = getArrayU8FromWasm0(r0, r1).slice(); + wasm.__wbindgen_free(r0, r1 * 1); + return v0; + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } +} +module.exports.Bip32PrivateKey = Bip32PrivateKey; + +const Bip32PublicKeyFinalization = new FinalizationRegistry((ptr) => + wasm.__wbg_bip32publickey_free(ptr) +); +/** */ +class Bip32PublicKey { + static __wrap(ptr) { + const obj = Object.create(Bip32PublicKey.prototype); + obj.ptr = ptr; + Bip32PublicKeyFinalization.register(obj, obj.ptr, obj); + return obj; + } + + __destroy_into_raw() { + const ptr = this.ptr; + this.ptr = 0; + Bip32PublicKeyFinalization.unregister(this); + return ptr; + } + + free() { + const ptr = this.__destroy_into_raw(); + wasm.__wbg_bip32publickey_free(ptr); + } + /** + * derive this public key with the given index. + * + * # Errors + * + * If the index is not a soft derivation index (< 0x80000000) then + * calling this method will fail. + * + * # Security considerations + * + * * hard derivation index cannot be soft derived with the public key + * + * # Hard derivation vs Soft derivation + * + * If you pass an index below 0x80000000 then it is a soft derivation. + * The advantage of soft derivation is that it is possible to derive the + * public key too. I.e. derivation the private key with a soft derivation + * index and then retrieving the associated public key is equivalent to + * deriving the public key associated to the parent private key. + * + * Hard derivation index does not allow public key derivation. + * + * This is why deriving the private key should not fail while deriving + * the public key may fail (if the derivation index is invalid). + * @param {number} index + * @returns {Bip32PublicKey} + */ + derive(index) { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + wasm.bip32publickey_derive(retptr, this.ptr, index); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + if (r2) { + throw takeObject(r1); + } + return Bip32PublicKey.__wrap(r0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @returns {PublicKey} + */ + to_raw_key() { + const ret = wasm.bip32publickey_to_raw_key(this.ptr); + return PublicKey.__wrap(ret); + } + /** + * @param {Uint8Array} bytes + * @returns {Bip32PublicKey} + */ + static from_bytes(bytes) { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + const ptr0 = passArray8ToWasm0(bytes, wasm.__wbindgen_malloc); + const len0 = WASM_VECTOR_LEN; + wasm.bip32publickey_from_bytes(retptr, ptr0, len0); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + if (r2) { + throw takeObject(r1); + } + return Bip32PublicKey.__wrap(r0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @returns {Uint8Array} + */ + as_bytes() { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + wasm.bip32publickey_as_bytes(retptr, this.ptr); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var v0 = getArrayU8FromWasm0(r0, r1).slice(); + wasm.__wbindgen_free(r0, r1 * 1); + return v0; + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @param {string} bech32_str + * @returns {Bip32PublicKey} + */ + static from_bech32(bech32_str) { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + const ptr0 = passStringToWasm0( + bech32_str, + wasm.__wbindgen_malloc, + wasm.__wbindgen_realloc, + ); + const len0 = WASM_VECTOR_LEN; + wasm.bip32publickey_from_bech32(retptr, ptr0, len0); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + if (r2) { + throw takeObject(r1); + } + return Bip32PublicKey.__wrap(r0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @returns {string} + */ + to_bech32() { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + wasm.bip32publickey_to_bech32(retptr, this.ptr); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + return getStringFromWasm0(r0, r1); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + wasm.__wbindgen_free(r0, r1); + } + } + /** + * @returns {Uint8Array} + */ + chaincode() { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + wasm.bip32publickey_chaincode(retptr, this.ptr); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var v0 = getArrayU8FromWasm0(r0, r1).slice(); + wasm.__wbindgen_free(r0, r1 * 1); + return v0; + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } +} +module.exports.Bip32PublicKey = Bip32PublicKey; + +const BlockFinalization = new FinalizationRegistry((ptr) => + wasm.__wbg_block_free(ptr) +); +/** */ +class Block { + static __wrap(ptr) { + const obj = Object.create(Block.prototype); + obj.ptr = ptr; + BlockFinalization.register(obj, obj.ptr, obj); + return obj; + } + + __destroy_into_raw() { + const ptr = this.ptr; + this.ptr = 0; + BlockFinalization.unregister(this); + return ptr; + } + + free() { + const ptr = this.__destroy_into_raw(); + wasm.__wbg_block_free(ptr); + } + /** + * @returns {Uint8Array} + */ + to_bytes() { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + wasm.block_to_bytes(retptr, this.ptr); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var v0 = getArrayU8FromWasm0(r0, r1).slice(); + wasm.__wbindgen_free(r0, r1 * 1); + return v0; + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @param {Uint8Array} bytes + * @returns {Block} + */ + static from_bytes(bytes) { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + const ptr0 = passArray8ToWasm0(bytes, wasm.__wbindgen_malloc); + const len0 = WASM_VECTOR_LEN; + wasm.block_from_bytes(retptr, ptr0, len0); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + if (r2) { + throw takeObject(r1); + } + return Block.__wrap(r0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @returns {string} + */ + to_json() { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + wasm.block_to_json(retptr, this.ptr); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + var r3 = getInt32Memory0()[retptr / 4 + 3]; + var ptr0 = r0; + var len0 = r1; + if (r3) { + ptr0 = 0; + len0 = 0; + throw takeObject(r2); + } + return getStringFromWasm0(ptr0, len0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + wasm.__wbindgen_free(ptr0, len0); + } + } + /** + * @returns {any} + */ + to_js_value() { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + wasm.block_to_js_value(retptr, this.ptr); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + if (r2) { + throw takeObject(r1); + } + return takeObject(r0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @param {string} json + * @returns {Block} + */ + static from_json(json) { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + const ptr0 = passStringToWasm0( + json, + wasm.__wbindgen_malloc, + wasm.__wbindgen_realloc, + ); + const len0 = WASM_VECTOR_LEN; + wasm.block_from_json(retptr, ptr0, len0); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + if (r2) { + throw takeObject(r1); + } + return Block.__wrap(r0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @returns {Header} + */ + header() { + const ret = wasm.block_header(this.ptr); + return Header.__wrap(ret); + } + /** + * @returns {TransactionBodies} + */ + transaction_bodies() { + const ret = wasm.block_transaction_bodies(this.ptr); + return TransactionBodies.__wrap(ret); + } + /** + * @returns {TransactionWitnessSets} + */ + transaction_witness_sets() { + const ret = wasm.block_transaction_witness_sets(this.ptr); + return TransactionWitnessSets.__wrap(ret); + } + /** + * @returns {AuxiliaryDataSet} + */ + auxiliary_data_set() { + const ret = wasm.block_auxiliary_data_set(this.ptr); + return AuxiliaryDataSet.__wrap(ret); + } + /** + * @returns {TransactionIndexes} + */ + invalid_transactions() { + const ret = wasm.block_invalid_transactions(this.ptr); + return TransactionIndexes.__wrap(ret); + } + /** + * @param {Header} header + * @param {TransactionBodies} transaction_bodies + * @param {TransactionWitnessSets} transaction_witness_sets + * @param {AuxiliaryDataSet} auxiliary_data_set + * @param {TransactionIndexes} invalid_transactions + * @returns {Block} + */ + static new( + header, + transaction_bodies, + transaction_witness_sets, + auxiliary_data_set, + invalid_transactions, + ) { + _assertClass(header, Header); + _assertClass(transaction_bodies, TransactionBodies); + _assertClass(transaction_witness_sets, TransactionWitnessSets); + _assertClass(auxiliary_data_set, AuxiliaryDataSet); + _assertClass(invalid_transactions, TransactionIndexes); + const ret = wasm.block_new( + header.ptr, + transaction_bodies.ptr, + transaction_witness_sets.ptr, + auxiliary_data_set.ptr, + invalid_transactions.ptr, + ); + return Block.__wrap(ret); + } +} +module.exports.Block = Block; + +const BlockHashFinalization = new FinalizationRegistry((ptr) => + wasm.__wbg_blockhash_free(ptr) +); +/** */ +class BlockHash { + static __wrap(ptr) { + const obj = Object.create(BlockHash.prototype); + obj.ptr = ptr; + BlockHashFinalization.register(obj, obj.ptr, obj); + return obj; + } + + __destroy_into_raw() { + const ptr = this.ptr; + this.ptr = 0; + BlockHashFinalization.unregister(this); + return ptr; + } + + free() { + const ptr = this.__destroy_into_raw(); + wasm.__wbg_blockhash_free(ptr); + } + /** + * @param {Uint8Array} bytes + * @returns {BlockHash} + */ + static from_bytes(bytes) { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + const ptr0 = passArray8ToWasm0(bytes, wasm.__wbindgen_malloc); + const len0 = WASM_VECTOR_LEN; + wasm.blockhash_from_bytes(retptr, ptr0, len0); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + if (r2) { + throw takeObject(r1); + } + return BlockHash.__wrap(r0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @returns {Uint8Array} + */ + to_bytes() { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + wasm.auxiliarydatahash_to_bytes(retptr, this.ptr); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var v0 = getArrayU8FromWasm0(r0, r1).slice(); + wasm.__wbindgen_free(r0, r1 * 1); + return v0; + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @param {string} prefix + * @returns {string} + */ + to_bech32(prefix) { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + const ptr0 = passStringToWasm0( + prefix, + wasm.__wbindgen_malloc, + wasm.__wbindgen_realloc, + ); + const len0 = WASM_VECTOR_LEN; + wasm.auxiliarydatahash_to_bech32(retptr, this.ptr, ptr0, len0); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + var r3 = getInt32Memory0()[retptr / 4 + 3]; + var ptr1 = r0; + var len1 = r1; + if (r3) { + ptr1 = 0; + len1 = 0; + throw takeObject(r2); + } + return getStringFromWasm0(ptr1, len1); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + wasm.__wbindgen_free(ptr1, len1); + } + } + /** + * @param {string} bech_str + * @returns {BlockHash} + */ + static from_bech32(bech_str) { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + const ptr0 = passStringToWasm0( + bech_str, + wasm.__wbindgen_malloc, + wasm.__wbindgen_realloc, + ); + const len0 = WASM_VECTOR_LEN; + wasm.blockhash_from_bech32(retptr, ptr0, len0); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + if (r2) { + throw takeObject(r1); + } + return BlockHash.__wrap(r0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @returns {string} + */ + to_hex() { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + wasm.auxiliarydatahash_to_hex(retptr, this.ptr); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + return getStringFromWasm0(r0, r1); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + wasm.__wbindgen_free(r0, r1); + } + } + /** + * @param {string} hex + * @returns {BlockHash} + */ + static from_hex(hex) { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + const ptr0 = passStringToWasm0( + hex, + wasm.__wbindgen_malloc, + wasm.__wbindgen_realloc, + ); + const len0 = WASM_VECTOR_LEN; + wasm.blockhash_from_hex(retptr, ptr0, len0); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + if (r2) { + throw takeObject(r1); + } + return BlockHash.__wrap(r0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } +} +module.exports.BlockHash = BlockHash; + +const BlockfrostFinalization = new FinalizationRegistry((ptr) => + wasm.__wbg_blockfrost_free(ptr) +); +/** */ +class Blockfrost { + static __wrap(ptr) { + const obj = Object.create(Blockfrost.prototype); + obj.ptr = ptr; + BlockfrostFinalization.register(obj, obj.ptr, obj); + return obj; + } + + __destroy_into_raw() { + const ptr = this.ptr; + this.ptr = 0; + BlockfrostFinalization.unregister(this); + return ptr; + } + + free() { + const ptr = this.__destroy_into_raw(); + wasm.__wbg_blockfrost_free(ptr); + } + /** + * @param {string} url + * @param {string} project_id + * @returns {Blockfrost} + */ + static new(url, project_id) { + const ptr0 = passStringToWasm0( + url, + wasm.__wbindgen_malloc, + wasm.__wbindgen_realloc, + ); + const len0 = WASM_VECTOR_LEN; + const ptr1 = passStringToWasm0( + project_id, + wasm.__wbindgen_malloc, + wasm.__wbindgen_realloc, + ); + const len1 = WASM_VECTOR_LEN; + const ret = wasm.blockfrost_new(ptr0, len0, ptr1, len1); + return Blockfrost.__wrap(ret); + } + /** + * @returns {string} + */ + url() { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + wasm.blockfrost_url(retptr, this.ptr); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + return getStringFromWasm0(r0, r1); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + wasm.__wbindgen_free(r0, r1); + } + } + /** + * @returns {string} + */ + project_id() { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + wasm.blockfrost_project_id(retptr, this.ptr); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + return getStringFromWasm0(r0, r1); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + wasm.__wbindgen_free(r0, r1); + } + } +} +module.exports.Blockfrost = Blockfrost; + +const BootstrapWitnessFinalization = new FinalizationRegistry((ptr) => + wasm.__wbg_bootstrapwitness_free(ptr) +); +/** */ +class BootstrapWitness { + static __wrap(ptr) { + const obj = Object.create(BootstrapWitness.prototype); + obj.ptr = ptr; + BootstrapWitnessFinalization.register(obj, obj.ptr, obj); + return obj; + } + + __destroy_into_raw() { + const ptr = this.ptr; + this.ptr = 0; + BootstrapWitnessFinalization.unregister(this); + return ptr; + } + + free() { + const ptr = this.__destroy_into_raw(); + wasm.__wbg_bootstrapwitness_free(ptr); + } + /** + * @returns {Uint8Array} + */ + to_bytes() { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + wasm.bootstrapwitness_to_bytes(retptr, this.ptr); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var v0 = getArrayU8FromWasm0(r0, r1).slice(); + wasm.__wbindgen_free(r0, r1 * 1); + return v0; + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @param {Uint8Array} bytes + * @returns {BootstrapWitness} + */ + static from_bytes(bytes) { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + const ptr0 = passArray8ToWasm0(bytes, wasm.__wbindgen_malloc); + const len0 = WASM_VECTOR_LEN; + wasm.bootstrapwitness_from_bytes(retptr, ptr0, len0); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + if (r2) { + throw takeObject(r1); + } + return BootstrapWitness.__wrap(r0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @returns {string} + */ + to_json() { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + wasm.bootstrapwitness_to_json(retptr, this.ptr); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + var r3 = getInt32Memory0()[retptr / 4 + 3]; + var ptr0 = r0; + var len0 = r1; + if (r3) { + ptr0 = 0; + len0 = 0; + throw takeObject(r2); + } + return getStringFromWasm0(ptr0, len0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + wasm.__wbindgen_free(ptr0, len0); + } + } + /** + * @returns {any} + */ + to_js_value() { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + wasm.bootstrapwitness_to_js_value(retptr, this.ptr); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + if (r2) { + throw takeObject(r1); + } + return takeObject(r0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @param {string} json + * @returns {BootstrapWitness} + */ + static from_json(json) { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + const ptr0 = passStringToWasm0( + json, + wasm.__wbindgen_malloc, + wasm.__wbindgen_realloc, + ); + const len0 = WASM_VECTOR_LEN; + wasm.bootstrapwitness_from_json(retptr, ptr0, len0); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + if (r2) { + throw takeObject(r1); + } + return BootstrapWitness.__wrap(r0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @returns {Vkey} + */ + vkey() { + const ret = wasm.bootstrapwitness_vkey(this.ptr); + return Vkey.__wrap(ret); + } + /** + * @returns {Ed25519Signature} + */ + signature() { + const ret = wasm.bootstrapwitness_signature(this.ptr); + return Ed25519Signature.__wrap(ret); + } + /** + * @returns {Uint8Array} + */ + chain_code() { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + wasm.assetname_name(retptr, this.ptr); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var v0 = getArrayU8FromWasm0(r0, r1).slice(); + wasm.__wbindgen_free(r0, r1 * 1); + return v0; + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @returns {Uint8Array} + */ + attributes() { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + wasm.bootstrapwitness_attributes(retptr, this.ptr); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var v0 = getArrayU8FromWasm0(r0, r1).slice(); + wasm.__wbindgen_free(r0, r1 * 1); + return v0; + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @param {Vkey} vkey + * @param {Ed25519Signature} signature + * @param {Uint8Array} chain_code + * @param {Uint8Array} attributes + * @returns {BootstrapWitness} + */ + static new(vkey, signature, chain_code, attributes) { + _assertClass(vkey, Vkey); + _assertClass(signature, Ed25519Signature); + const ptr0 = passArray8ToWasm0(chain_code, wasm.__wbindgen_malloc); + const len0 = WASM_VECTOR_LEN; + const ptr1 = passArray8ToWasm0(attributes, wasm.__wbindgen_malloc); + const len1 = WASM_VECTOR_LEN; + const ret = wasm.bootstrapwitness_new( + vkey.ptr, + signature.ptr, + ptr0, + len0, + ptr1, + len1, + ); + return BootstrapWitness.__wrap(ret); + } +} +module.exports.BootstrapWitness = BootstrapWitness; + +const BootstrapWitnessesFinalization = new FinalizationRegistry((ptr) => + wasm.__wbg_bootstrapwitnesses_free(ptr) +); +/** */ +class BootstrapWitnesses { + static __wrap(ptr) { + const obj = Object.create(BootstrapWitnesses.prototype); + obj.ptr = ptr; + BootstrapWitnessesFinalization.register(obj, obj.ptr, obj); + return obj; + } + + __destroy_into_raw() { + const ptr = this.ptr; + this.ptr = 0; + BootstrapWitnessesFinalization.unregister(this); + return ptr; + } + + free() { + const ptr = this.__destroy_into_raw(); + wasm.__wbg_bootstrapwitnesses_free(ptr); + } + /** + * @returns {BootstrapWitnesses} + */ + static new() { + const ret = wasm.assetnames_new(); + return BootstrapWitnesses.__wrap(ret); + } + /** + * @returns {number} + */ + len() { + const ret = wasm.assetnames_len(this.ptr); + return ret >>> 0; + } + /** + * @param {number} index + * @returns {BootstrapWitness} + */ + get(index) { + const ret = wasm.bootstrapwitnesses_get(this.ptr, index); + return BootstrapWitness.__wrap(ret); + } + /** + * @param {BootstrapWitness} elem + */ + add(elem) { + _assertClass(elem, BootstrapWitness); + wasm.bootstrapwitnesses_add(this.ptr, elem.ptr); + } +} +module.exports.BootstrapWitnesses = BootstrapWitnesses; + +const ByronAddressFinalization = new FinalizationRegistry((ptr) => + wasm.__wbg_byronaddress_free(ptr) +); +/** */ +class ByronAddress { + static __wrap(ptr) { + const obj = Object.create(ByronAddress.prototype); + obj.ptr = ptr; + ByronAddressFinalization.register(obj, obj.ptr, obj); + return obj; + } + + __destroy_into_raw() { + const ptr = this.ptr; + this.ptr = 0; + ByronAddressFinalization.unregister(this); + return ptr; + } + + free() { + const ptr = this.__destroy_into_raw(); + wasm.__wbg_byronaddress_free(ptr); + } + /** + * @returns {string} + */ + to_base58() { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + wasm.byronaddress_to_base58(retptr, this.ptr); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + return getStringFromWasm0(r0, r1); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + wasm.__wbindgen_free(r0, r1); + } + } + /** + * @returns {Uint8Array} + */ + to_bytes() { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + wasm.byronaddress_to_bytes(retptr, this.ptr); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var v0 = getArrayU8FromWasm0(r0, r1).slice(); + wasm.__wbindgen_free(r0, r1 * 1); + return v0; + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @param {Uint8Array} bytes + * @returns {ByronAddress} + */ + static from_bytes(bytes) { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + const ptr0 = passArray8ToWasm0(bytes, wasm.__wbindgen_malloc); + const len0 = WASM_VECTOR_LEN; + wasm.byronaddress_from_bytes(retptr, ptr0, len0); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + if (r2) { + throw takeObject(r1); + } + return ByronAddress.__wrap(r0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * returns the byron protocol magic embedded in the address, or mainnet id if none is present + * note: for bech32 addresses, you need to use network_id instead + * @returns {number} + */ + byron_protocol_magic() { + const ret = wasm.byronaddress_byron_protocol_magic(this.ptr); + return ret >>> 0; + } + /** + * @returns {Uint8Array} + */ + attributes() { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + wasm.byronaddress_attributes(retptr, this.ptr); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var v0 = getArrayU8FromWasm0(r0, r1).slice(); + wasm.__wbindgen_free(r0, r1 * 1); + return v0; + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @returns {number} + */ + network_id() { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + wasm.byronaddress_network_id(retptr, this.ptr); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + if (r2) { + throw takeObject(r1); + } + return r0; + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @param {string} s + * @returns {ByronAddress} + */ + static from_base58(s) { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + const ptr0 = passStringToWasm0( + s, + wasm.__wbindgen_malloc, + wasm.__wbindgen_realloc, + ); + const len0 = WASM_VECTOR_LEN; + wasm.byronaddress_from_base58(retptr, ptr0, len0); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + if (r2) { + throw takeObject(r1); + } + return ByronAddress.__wrap(r0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @param {Bip32PublicKey} key + * @param {number} protocol_magic + * @returns {ByronAddress} + */ + static icarus_from_key(key, protocol_magic) { + _assertClass(key, Bip32PublicKey); + const ret = wasm.byronaddress_icarus_from_key(key.ptr, protocol_magic); + return ByronAddress.__wrap(ret); + } + /** + * @param {string} s + * @returns {boolean} + */ + static is_valid(s) { + const ptr0 = passStringToWasm0( + s, + wasm.__wbindgen_malloc, + wasm.__wbindgen_realloc, + ); + const len0 = WASM_VECTOR_LEN; + const ret = wasm.byronaddress_is_valid(ptr0, len0); + return ret !== 0; + } + /** + * @returns {Address} + */ + to_address() { + const ret = wasm.byronaddress_to_address(this.ptr); + return Address.__wrap(ret); + } + /** + * @param {Address} addr + * @returns {ByronAddress | undefined} + */ + static from_address(addr) { + _assertClass(addr, Address); + const ret = wasm.address_as_byron(addr.ptr); + return ret === 0 ? undefined : ByronAddress.__wrap(ret); + } +} +module.exports.ByronAddress = ByronAddress; + +const CertificateFinalization = new FinalizationRegistry((ptr) => + wasm.__wbg_certificate_free(ptr) +); +/** */ +class Certificate { + static __wrap(ptr) { + const obj = Object.create(Certificate.prototype); + obj.ptr = ptr; + CertificateFinalization.register(obj, obj.ptr, obj); + return obj; + } + + __destroy_into_raw() { + const ptr = this.ptr; + this.ptr = 0; + CertificateFinalization.unregister(this); + return ptr; + } + + free() { + const ptr = this.__destroy_into_raw(); + wasm.__wbg_certificate_free(ptr); + } + /** + * @returns {Uint8Array} + */ + to_bytes() { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + wasm.certificate_to_bytes(retptr, this.ptr); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var v0 = getArrayU8FromWasm0(r0, r1).slice(); + wasm.__wbindgen_free(r0, r1 * 1); + return v0; + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @param {Uint8Array} bytes + * @returns {Certificate} + */ + static from_bytes(bytes) { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + const ptr0 = passArray8ToWasm0(bytes, wasm.__wbindgen_malloc); + const len0 = WASM_VECTOR_LEN; + wasm.certificate_from_bytes(retptr, ptr0, len0); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + if (r2) { + throw takeObject(r1); + } + return Certificate.__wrap(r0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @returns {string} + */ + to_json() { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + wasm.certificate_to_json(retptr, this.ptr); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + var r3 = getInt32Memory0()[retptr / 4 + 3]; + var ptr0 = r0; + var len0 = r1; + if (r3) { + ptr0 = 0; + len0 = 0; + throw takeObject(r2); + } + return getStringFromWasm0(ptr0, len0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + wasm.__wbindgen_free(ptr0, len0); + } + } + /** + * @returns {any} + */ + to_js_value() { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + wasm.certificate_to_js_value(retptr, this.ptr); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + if (r2) { + throw takeObject(r1); + } + return takeObject(r0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @param {string} json + * @returns {Certificate} + */ + static from_json(json) { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + const ptr0 = passStringToWasm0( + json, + wasm.__wbindgen_malloc, + wasm.__wbindgen_realloc, + ); + const len0 = WASM_VECTOR_LEN; + wasm.certificate_from_json(retptr, ptr0, len0); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + if (r2) { + throw takeObject(r1); + } + return Certificate.__wrap(r0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @param {StakeRegistration} stake_registration + * @returns {Certificate} + */ + static new_stake_registration(stake_registration) { + _assertClass(stake_registration, StakeRegistration); + const ret = wasm.certificate_new_stake_registration(stake_registration.ptr); + return Certificate.__wrap(ret); + } + /** + * @param {StakeDeregistration} stake_deregistration + * @returns {Certificate} + */ + static new_stake_deregistration(stake_deregistration) { + _assertClass(stake_deregistration, StakeDeregistration); + const ret = wasm.certificate_new_stake_deregistration( + stake_deregistration.ptr, + ); + return Certificate.__wrap(ret); + } + /** + * @param {StakeDelegation} stake_delegation + * @returns {Certificate} + */ + static new_stake_delegation(stake_delegation) { + _assertClass(stake_delegation, StakeDelegation); + const ret = wasm.certificate_new_stake_delegation(stake_delegation.ptr); + return Certificate.__wrap(ret); + } + /** + * @param {PoolRegistration} pool_registration + * @returns {Certificate} + */ + static new_pool_registration(pool_registration) { + _assertClass(pool_registration, PoolRegistration); + const ret = wasm.certificate_new_pool_registration(pool_registration.ptr); + return Certificate.__wrap(ret); + } + /** + * @param {PoolRetirement} pool_retirement + * @returns {Certificate} + */ + static new_pool_retirement(pool_retirement) { + _assertClass(pool_retirement, PoolRetirement); + const ret = wasm.certificate_new_pool_retirement(pool_retirement.ptr); + return Certificate.__wrap(ret); + } + /** + * @param {GenesisKeyDelegation} genesis_key_delegation + * @returns {Certificate} + */ + static new_genesis_key_delegation(genesis_key_delegation) { + _assertClass(genesis_key_delegation, GenesisKeyDelegation); + const ret = wasm.certificate_new_genesis_key_delegation( + genesis_key_delegation.ptr, + ); + return Certificate.__wrap(ret); + } + /** + * @param {MoveInstantaneousRewardsCert} move_instantaneous_rewards_cert + * @returns {Certificate} + */ + static new_move_instantaneous_rewards_cert(move_instantaneous_rewards_cert) { + _assertClass(move_instantaneous_rewards_cert, MoveInstantaneousRewardsCert); + const ret = wasm.certificate_new_move_instantaneous_rewards_cert( + move_instantaneous_rewards_cert.ptr, + ); + return Certificate.__wrap(ret); + } + /** + * @returns {number} + */ + kind() { + const ret = wasm.certificate_kind(this.ptr); + return ret >>> 0; + } + /** + * @returns {StakeRegistration | undefined} + */ + as_stake_registration() { + const ret = wasm.certificate_as_stake_registration(this.ptr); + return ret === 0 ? undefined : StakeRegistration.__wrap(ret); + } + /** + * @returns {StakeDeregistration | undefined} + */ + as_stake_deregistration() { + const ret = wasm.certificate_as_stake_deregistration(this.ptr); + return ret === 0 ? undefined : StakeDeregistration.__wrap(ret); + } + /** + * @returns {StakeDelegation | undefined} + */ + as_stake_delegation() { + const ret = wasm.certificate_as_stake_delegation(this.ptr); + return ret === 0 ? undefined : StakeDelegation.__wrap(ret); + } + /** + * @returns {PoolRegistration | undefined} + */ + as_pool_registration() { + const ret = wasm.certificate_as_pool_registration(this.ptr); + return ret === 0 ? undefined : PoolRegistration.__wrap(ret); + } + /** + * @returns {PoolRetirement | undefined} + */ + as_pool_retirement() { + const ret = wasm.certificate_as_pool_retirement(this.ptr); + return ret === 0 ? undefined : PoolRetirement.__wrap(ret); + } + /** + * @returns {GenesisKeyDelegation | undefined} + */ + as_genesis_key_delegation() { + const ret = wasm.certificate_as_genesis_key_delegation(this.ptr); + return ret === 0 ? undefined : GenesisKeyDelegation.__wrap(ret); + } + /** + * @returns {MoveInstantaneousRewardsCert | undefined} + */ + as_move_instantaneous_rewards_cert() { + const ret = wasm.certificate_as_move_instantaneous_rewards_cert(this.ptr); + return ret === 0 ? undefined : MoveInstantaneousRewardsCert.__wrap(ret); + } + /** + * @returns {RegCert | undefined} + */ + as_reg_cert() { + const ret = wasm.certificate_as_reg_cert(this.ptr); + return ret === 0 ? undefined : RegCert.__wrap(ret); + } + /** + * @returns {UnregCert | undefined} + */ + as_unreg_cert() { + const ret = wasm.certificate_as_unreg_cert(this.ptr); + return ret === 0 ? undefined : UnregCert.__wrap(ret); + } + /** + * @returns {VoteDelegCert | undefined} + */ + as_vote_deleg_cert() { + const ret = wasm.certificate_as_vote_deleg_cert(this.ptr); + return ret === 0 ? undefined : VoteDelegCert.__wrap(ret); + } + /** + * @returns {StakeVoteDelegCert | undefined} + */ + as_stake_vote_deleg_cert() { + const ret = wasm.certificate_as_stake_vote_deleg_cert(this.ptr); + return ret === 0 ? undefined : StakeVoteDelegCert.__wrap(ret); + } + /** + * @returns {StakeRegDelegCert | undefined} + */ + as_stake_reg_deleg_cert() { + const ret = wasm.certificate_as_stake_reg_deleg_cert(this.ptr); + return ret === 0 ? undefined : StakeRegDelegCert.__wrap(ret); + } + /** + * @returns {VoteRegDelegCert | undefined} + */ + as_vote_reg_deleg_cert() { + const ret = wasm.certificate_as_vote_reg_deleg_cert(this.ptr); + return ret === 0 ? undefined : VoteRegDelegCert.__wrap(ret); + } + /** + * @returns {StakeVoteRegDelegCert | undefined} + */ + as_stake_vote_reg_deleg_cert() { + const ret = wasm.certificate_as_stake_vote_reg_deleg_cert(this.ptr); + return ret === 0 ? undefined : StakeVoteRegDelegCert.__wrap(ret); + } + /** + * @returns {RegCommitteeHotKeyCert | undefined} + */ + as_reg_committee_hot_key_cert() { + const ret = wasm.certificate_as_reg_committee_hot_key_cert(this.ptr); + return ret === 0 ? undefined : RegCommitteeHotKeyCert.__wrap(ret); + } + /** + * @returns {UnregCommitteeHotKeyCert | undefined} + */ + as_unreg_committee_hot_key_cert() { + const ret = wasm.certificate_as_unreg_committee_hot_key_cert(this.ptr); + return ret === 0 ? undefined : UnregCommitteeHotKeyCert.__wrap(ret); + } + /** + * @returns {RegDrepCert | undefined} + */ + as_reg_drep_cert() { + const ret = wasm.certificate_as_reg_drep_cert(this.ptr); + return ret === 0 ? undefined : RegDrepCert.__wrap(ret); + } + /** + * @returns {UnregDrepCert | undefined} + */ + as_unreg_drep_cert() { + const ret = wasm.certificate_as_unreg_drep_cert(this.ptr); + return ret === 0 ? undefined : UnregDrepCert.__wrap(ret); + } +} +module.exports.Certificate = Certificate; + +const CertificatesFinalization = new FinalizationRegistry((ptr) => + wasm.__wbg_certificates_free(ptr) +); +/** */ +class Certificates { + static __wrap(ptr) { + const obj = Object.create(Certificates.prototype); + obj.ptr = ptr; + CertificatesFinalization.register(obj, obj.ptr, obj); + return obj; + } + + __destroy_into_raw() { + const ptr = this.ptr; + this.ptr = 0; + CertificatesFinalization.unregister(this); + return ptr; + } + + free() { + const ptr = this.__destroy_into_raw(); + wasm.__wbg_certificates_free(ptr); + } + /** + * @returns {Uint8Array} + */ + to_bytes() { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + wasm.certificates_to_bytes(retptr, this.ptr); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var v0 = getArrayU8FromWasm0(r0, r1).slice(); + wasm.__wbindgen_free(r0, r1 * 1); + return v0; + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @param {Uint8Array} bytes + * @returns {Certificates} + */ + static from_bytes(bytes) { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + const ptr0 = passArray8ToWasm0(bytes, wasm.__wbindgen_malloc); + const len0 = WASM_VECTOR_LEN; + wasm.certificates_from_bytes(retptr, ptr0, len0); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + if (r2) { + throw takeObject(r1); + } + return Certificates.__wrap(r0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @returns {string} + */ + to_json() { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + wasm.certificates_to_json(retptr, this.ptr); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + var r3 = getInt32Memory0()[retptr / 4 + 3]; + var ptr0 = r0; + var len0 = r1; + if (r3) { + ptr0 = 0; + len0 = 0; + throw takeObject(r2); + } + return getStringFromWasm0(ptr0, len0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + wasm.__wbindgen_free(ptr0, len0); + } + } + /** + * @returns {any} + */ + to_js_value() { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + wasm.certificates_to_js_value(retptr, this.ptr); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + if (r2) { + throw takeObject(r1); + } + return takeObject(r0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @param {string} json + * @returns {Certificates} + */ + static from_json(json) { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + const ptr0 = passStringToWasm0( + json, + wasm.__wbindgen_malloc, + wasm.__wbindgen_realloc, + ); + const len0 = WASM_VECTOR_LEN; + wasm.certificates_from_json(retptr, ptr0, len0); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + if (r2) { + throw takeObject(r1); + } + return Certificates.__wrap(r0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @returns {Certificates} + */ + static new() { + const ret = wasm.certificates_new(); + return Certificates.__wrap(ret); + } + /** + * @returns {number} + */ + len() { + const ret = wasm.assetnames_len(this.ptr); + return ret >>> 0; + } + /** + * @param {number} index + * @returns {Certificate} + */ + get(index) { + const ret = wasm.certificates_get(this.ptr, index); + return Certificate.__wrap(ret); + } + /** + * @param {Certificate} elem + */ + add(elem) { + _assertClass(elem, Certificate); + wasm.certificates_add(this.ptr, elem.ptr); + } +} +module.exports.Certificates = Certificates; + +const ConstrPlutusDataFinalization = new FinalizationRegistry((ptr) => + wasm.__wbg_constrplutusdata_free(ptr) +); +/** */ +class ConstrPlutusData { + static __wrap(ptr) { + const obj = Object.create(ConstrPlutusData.prototype); + obj.ptr = ptr; + ConstrPlutusDataFinalization.register(obj, obj.ptr, obj); + return obj; + } + + __destroy_into_raw() { + const ptr = this.ptr; + this.ptr = 0; + ConstrPlutusDataFinalization.unregister(this); + return ptr; + } + + free() { + const ptr = this.__destroy_into_raw(); + wasm.__wbg_constrplutusdata_free(ptr); + } + /** + * @returns {Uint8Array} + */ + to_bytes() { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + wasm.constrplutusdata_to_bytes(retptr, this.ptr); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var v0 = getArrayU8FromWasm0(r0, r1).slice(); + wasm.__wbindgen_free(r0, r1 * 1); + return v0; + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @param {Uint8Array} bytes + * @returns {ConstrPlutusData} + */ + static from_bytes(bytes) { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + const ptr0 = passArray8ToWasm0(bytes, wasm.__wbindgen_malloc); + const len0 = WASM_VECTOR_LEN; + wasm.constrplutusdata_from_bytes(retptr, ptr0, len0); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + if (r2) { + throw takeObject(r1); + } + return ConstrPlutusData.__wrap(r0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @returns {BigNum} + */ + alternative() { + const ret = wasm.constrplutusdata_alternative(this.ptr); + return BigNum.__wrap(ret); + } + /** + * @returns {PlutusList} + */ + data() { + const ret = wasm.constrplutusdata_data(this.ptr); + return PlutusList.__wrap(ret); + } + /** + * @param {BigNum} alternative + * @param {PlutusList} data + * @returns {ConstrPlutusData} + */ + static new(alternative, data) { + _assertClass(alternative, BigNum); + _assertClass(data, PlutusList); + const ret = wasm.constrplutusdata_new(alternative.ptr, data.ptr); + return ConstrPlutusData.__wrap(ret); + } +} +module.exports.ConstrPlutusData = ConstrPlutusData; + +const CostModelFinalization = new FinalizationRegistry((ptr) => + wasm.__wbg_costmodel_free(ptr) +); +/** */ +class CostModel { + static __wrap(ptr) { + const obj = Object.create(CostModel.prototype); + obj.ptr = ptr; + CostModelFinalization.register(obj, obj.ptr, obj); + return obj; + } + + __destroy_into_raw() { + const ptr = this.ptr; + this.ptr = 0; + CostModelFinalization.unregister(this); + return ptr; + } + + free() { + const ptr = this.__destroy_into_raw(); + wasm.__wbg_costmodel_free(ptr); + } + /** + * @returns {Uint8Array} + */ + to_bytes() { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + wasm.costmodel_to_bytes(retptr, this.ptr); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var v0 = getArrayU8FromWasm0(r0, r1).slice(); + wasm.__wbindgen_free(r0, r1 * 1); + return v0; + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @param {Uint8Array} bytes + * @returns {CostModel} + */ + static from_bytes(bytes) { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + const ptr0 = passArray8ToWasm0(bytes, wasm.__wbindgen_malloc); + const len0 = WASM_VECTOR_LEN; + wasm.costmodel_from_bytes(retptr, ptr0, len0); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + if (r2) { + throw takeObject(r1); + } + return CostModel.__wrap(r0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @returns {CostModel} + */ + static new() { + const ret = wasm.costmodel_new(); + return CostModel.__wrap(ret); + } + /** + * @returns {CostModel} + */ + static new_plutus_v2() { + const ret = wasm.costmodel_new_plutus_v2(); + return CostModel.__wrap(ret); + } + /** + * @returns {CostModel} + */ + static new_plutus_v3() { + const ret = wasm.costmodel_new_plutus_v3(); + return CostModel.__wrap(ret); + } + /** + * @param {number} operation + * @param {Int} cost + * @returns {Int} + */ + set(operation, cost) { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + _assertClass(cost, Int); + wasm.costmodel_set(retptr, this.ptr, operation, cost.ptr); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + if (r2) { + throw takeObject(r1); + } + return Int.__wrap(r0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @param {number} operation + * @returns {Int} + */ + get(operation) { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + wasm.costmodel_get(retptr, this.ptr, operation); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + if (r2) { + throw takeObject(r1); + } + return Int.__wrap(r0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @returns {number} + */ + len() { + const ret = wasm.assetnames_len(this.ptr); + return ret >>> 0; + } +} +module.exports.CostModel = CostModel; + +const CostmdlsFinalization = new FinalizationRegistry((ptr) => + wasm.__wbg_costmdls_free(ptr) +); +/** */ +class Costmdls { + static __wrap(ptr) { + const obj = Object.create(Costmdls.prototype); + obj.ptr = ptr; + CostmdlsFinalization.register(obj, obj.ptr, obj); + return obj; + } + + __destroy_into_raw() { + const ptr = this.ptr; + this.ptr = 0; + CostmdlsFinalization.unregister(this); + return ptr; + } + + free() { + const ptr = this.__destroy_into_raw(); + wasm.__wbg_costmdls_free(ptr); + } + /** + * @returns {Uint8Array} + */ + to_bytes() { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + wasm.costmdls_to_bytes(retptr, this.ptr); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var v0 = getArrayU8FromWasm0(r0, r1).slice(); + wasm.__wbindgen_free(r0, r1 * 1); + return v0; + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @param {Uint8Array} bytes + * @returns {Costmdls} + */ + static from_bytes(bytes) { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + const ptr0 = passArray8ToWasm0(bytes, wasm.__wbindgen_malloc); + const len0 = WASM_VECTOR_LEN; + wasm.costmdls_from_bytes(retptr, ptr0, len0); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + if (r2) { + throw takeObject(r1); + } + return Costmdls.__wrap(r0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @returns {Costmdls} + */ + static new() { + const ret = wasm.assets_new(); + return Costmdls.__wrap(ret); + } + /** + * @returns {number} + */ + len() { + const ret = wasm.assetnames_len(this.ptr); + return ret >>> 0; + } + /** + * @param {Language} key + * @param {CostModel} value + * @returns {CostModel | undefined} + */ + insert(key, value) { + _assertClass(key, Language); + _assertClass(value, CostModel); + const ret = wasm.costmdls_insert(this.ptr, key.ptr, value.ptr); + return ret === 0 ? undefined : CostModel.__wrap(ret); + } + /** + * @param {Language} key + * @returns {CostModel | undefined} + */ + get(key) { + _assertClass(key, Language); + const ret = wasm.costmdls_get(this.ptr, key.ptr); + return ret === 0 ? undefined : CostModel.__wrap(ret); + } + /** + * @returns {Languages} + */ + keys() { + const ret = wasm.costmdls_keys(this.ptr); + return Languages.__wrap(ret); + } +} +module.exports.Costmdls = Costmdls; + +const DNSRecordAorAAAAFinalization = new FinalizationRegistry((ptr) => + wasm.__wbg_dnsrecordaoraaaa_free(ptr) +); +/** */ +class DNSRecordAorAAAA { + static __wrap(ptr) { + const obj = Object.create(DNSRecordAorAAAA.prototype); + obj.ptr = ptr; + DNSRecordAorAAAAFinalization.register(obj, obj.ptr, obj); + return obj; + } + + __destroy_into_raw() { + const ptr = this.ptr; + this.ptr = 0; + DNSRecordAorAAAAFinalization.unregister(this); + return ptr; + } + + free() { + const ptr = this.__destroy_into_raw(); + wasm.__wbg_dnsrecordaoraaaa_free(ptr); + } + /** + * @returns {Uint8Array} + */ + to_bytes() { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + wasm.dnsrecordaoraaaa_to_bytes(retptr, this.ptr); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var v0 = getArrayU8FromWasm0(r0, r1).slice(); + wasm.__wbindgen_free(r0, r1 * 1); + return v0; + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @param {Uint8Array} bytes + * @returns {DNSRecordAorAAAA} + */ + static from_bytes(bytes) { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + const ptr0 = passArray8ToWasm0(bytes, wasm.__wbindgen_malloc); + const len0 = WASM_VECTOR_LEN; + wasm.dnsrecordaoraaaa_from_bytes(retptr, ptr0, len0); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + if (r2) { + throw takeObject(r1); + } + return DNSRecordAorAAAA.__wrap(r0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @param {string} dns_name + * @returns {DNSRecordAorAAAA} + */ + static new(dns_name) { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + const ptr0 = passStringToWasm0( + dns_name, + wasm.__wbindgen_malloc, + wasm.__wbindgen_realloc, + ); + const len0 = WASM_VECTOR_LEN; + wasm.dnsrecordaoraaaa_new(retptr, ptr0, len0); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + if (r2) { + throw takeObject(r1); + } + return DNSRecordAorAAAA.__wrap(r0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @returns {string} + */ + record() { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + wasm.blockfrost_url(retptr, this.ptr); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + return getStringFromWasm0(r0, r1); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + wasm.__wbindgen_free(r0, r1); + } + } +} +module.exports.DNSRecordAorAAAA = DNSRecordAorAAAA; + +const DNSRecordSRVFinalization = new FinalizationRegistry((ptr) => + wasm.__wbg_dnsrecordsrv_free(ptr) +); +/** */ +class DNSRecordSRV { + static __wrap(ptr) { + const obj = Object.create(DNSRecordSRV.prototype); + obj.ptr = ptr; + DNSRecordSRVFinalization.register(obj, obj.ptr, obj); + return obj; + } + + __destroy_into_raw() { + const ptr = this.ptr; + this.ptr = 0; + DNSRecordSRVFinalization.unregister(this); + return ptr; + } + + free() { + const ptr = this.__destroy_into_raw(); + wasm.__wbg_dnsrecordsrv_free(ptr); + } + /** + * @returns {Uint8Array} + */ + to_bytes() { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + wasm.dnsrecordsrv_to_bytes(retptr, this.ptr); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var v0 = getArrayU8FromWasm0(r0, r1).slice(); + wasm.__wbindgen_free(r0, r1 * 1); + return v0; + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @param {Uint8Array} bytes + * @returns {DNSRecordSRV} + */ + static from_bytes(bytes) { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + const ptr0 = passArray8ToWasm0(bytes, wasm.__wbindgen_malloc); + const len0 = WASM_VECTOR_LEN; + wasm.dnsrecordsrv_from_bytes(retptr, ptr0, len0); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + if (r2) { + throw takeObject(r1); + } + return DNSRecordSRV.__wrap(r0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @param {string} dns_name + * @returns {DNSRecordSRV} + */ + static new(dns_name) { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + const ptr0 = passStringToWasm0( + dns_name, + wasm.__wbindgen_malloc, + wasm.__wbindgen_realloc, + ); + const len0 = WASM_VECTOR_LEN; + wasm.dnsrecordsrv_new(retptr, ptr0, len0); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + if (r2) { + throw takeObject(r1); + } + return DNSRecordSRV.__wrap(r0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @returns {string} + */ + record() { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + wasm.blockfrost_url(retptr, this.ptr); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + return getStringFromWasm0(r0, r1); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + wasm.__wbindgen_free(r0, r1); + } + } +} +module.exports.DNSRecordSRV = DNSRecordSRV; + +const DataFinalization = new FinalizationRegistry((ptr) => + wasm.__wbg_data_free(ptr) +); +/** */ +class Data { + static __wrap(ptr) { + const obj = Object.create(Data.prototype); + obj.ptr = ptr; + DataFinalization.register(obj, obj.ptr, obj); + return obj; + } + + __destroy_into_raw() { + const ptr = this.ptr; + this.ptr = 0; + DataFinalization.unregister(this); + return ptr; + } + + free() { + const ptr = this.__destroy_into_raw(); + wasm.__wbg_data_free(ptr); + } + /** + * @returns {Uint8Array} + */ + to_bytes() { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + wasm.data_to_bytes(retptr, this.ptr); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var v0 = getArrayU8FromWasm0(r0, r1).slice(); + wasm.__wbindgen_free(r0, r1 * 1); + return v0; + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @param {Uint8Array} bytes + * @returns {Data} + */ + static from_bytes(bytes) { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + const ptr0 = passArray8ToWasm0(bytes, wasm.__wbindgen_malloc); + const len0 = WASM_VECTOR_LEN; + wasm.data_from_bytes(retptr, ptr0, len0); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + if (r2) { + throw takeObject(r1); + } + return Data.__wrap(r0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @returns {string} + */ + to_json() { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + wasm.data_to_json(retptr, this.ptr); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + var r3 = getInt32Memory0()[retptr / 4 + 3]; + var ptr0 = r0; + var len0 = r1; + if (r3) { + ptr0 = 0; + len0 = 0; + throw takeObject(r2); + } + return getStringFromWasm0(ptr0, len0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + wasm.__wbindgen_free(ptr0, len0); + } + } + /** + * @returns {any} + */ + to_js_value() { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + wasm.data_to_js_value(retptr, this.ptr); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + if (r2) { + throw takeObject(r1); + } + return takeObject(r0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @param {string} json + * @returns {Data} + */ + static from_json(json) { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + const ptr0 = passStringToWasm0( + json, + wasm.__wbindgen_malloc, + wasm.__wbindgen_realloc, + ); + const len0 = WASM_VECTOR_LEN; + wasm.data_from_json(retptr, ptr0, len0); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + if (r2) { + throw takeObject(r1); + } + return Data.__wrap(r0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @param {PlutusData} plutus_data + * @returns {Data} + */ + static new(plutus_data) { + _assertClass(plutus_data, PlutusData); + const ret = wasm.data_new(plutus_data.ptr); + return Data.__wrap(ret); + } + /** + * @returns {PlutusData} + */ + get() { + const ret = wasm.data_get(this.ptr); + return PlutusData.__wrap(ret); + } +} +module.exports.Data = Data; + +const DataHashFinalization = new FinalizationRegistry((ptr) => + wasm.__wbg_datahash_free(ptr) +); +/** */ +class DataHash { + static __wrap(ptr) { + const obj = Object.create(DataHash.prototype); + obj.ptr = ptr; + DataHashFinalization.register(obj, obj.ptr, obj); + return obj; + } + + __destroy_into_raw() { + const ptr = this.ptr; + this.ptr = 0; + DataHashFinalization.unregister(this); + return ptr; + } + + free() { + const ptr = this.__destroy_into_raw(); + wasm.__wbg_datahash_free(ptr); + } + /** + * @param {Uint8Array} bytes + * @returns {DataHash} + */ + static from_bytes(bytes) { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + const ptr0 = passArray8ToWasm0(bytes, wasm.__wbindgen_malloc); + const len0 = WASM_VECTOR_LEN; + wasm.datahash_from_bytes(retptr, ptr0, len0); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + if (r2) { + throw takeObject(r1); + } + return DataHash.__wrap(r0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @returns {Uint8Array} + */ + to_bytes() { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + wasm.auxiliarydatahash_to_bytes(retptr, this.ptr); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var v0 = getArrayU8FromWasm0(r0, r1).slice(); + wasm.__wbindgen_free(r0, r1 * 1); + return v0; + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @param {string} prefix + * @returns {string} + */ + to_bech32(prefix) { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + const ptr0 = passStringToWasm0( + prefix, + wasm.__wbindgen_malloc, + wasm.__wbindgen_realloc, + ); + const len0 = WASM_VECTOR_LEN; + wasm.auxiliarydatahash_to_bech32(retptr, this.ptr, ptr0, len0); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + var r3 = getInt32Memory0()[retptr / 4 + 3]; + var ptr1 = r0; + var len1 = r1; + if (r3) { + ptr1 = 0; + len1 = 0; + throw takeObject(r2); + } + return getStringFromWasm0(ptr1, len1); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + wasm.__wbindgen_free(ptr1, len1); + } + } + /** + * @param {string} bech_str + * @returns {DataHash} + */ + static from_bech32(bech_str) { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + const ptr0 = passStringToWasm0( + bech_str, + wasm.__wbindgen_malloc, + wasm.__wbindgen_realloc, + ); + const len0 = WASM_VECTOR_LEN; + wasm.datahash_from_bech32(retptr, ptr0, len0); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + if (r2) { + throw takeObject(r1); + } + return DataHash.__wrap(r0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @returns {string} + */ + to_hex() { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + wasm.auxiliarydatahash_to_hex(retptr, this.ptr); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + return getStringFromWasm0(r0, r1); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + wasm.__wbindgen_free(r0, r1); + } + } + /** + * @param {string} hex + * @returns {DataHash} + */ + static from_hex(hex) { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + const ptr0 = passStringToWasm0( + hex, + wasm.__wbindgen_malloc, + wasm.__wbindgen_realloc, + ); + const len0 = WASM_VECTOR_LEN; + wasm.datahash_from_hex(retptr, ptr0, len0); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + if (r2) { + throw takeObject(r1); + } + return DataHash.__wrap(r0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } +} +module.exports.DataHash = DataHash; + +const DatumFinalization = new FinalizationRegistry((ptr) => + wasm.__wbg_datum_free(ptr) +); +/** */ +class Datum { + static __wrap(ptr) { + const obj = Object.create(Datum.prototype); + obj.ptr = ptr; + DatumFinalization.register(obj, obj.ptr, obj); + return obj; + } + + __destroy_into_raw() { + const ptr = this.ptr; + this.ptr = 0; + DatumFinalization.unregister(this); + return ptr; + } + + free() { + const ptr = this.__destroy_into_raw(); + wasm.__wbg_datum_free(ptr); + } + /** + * @returns {Uint8Array} + */ + to_bytes() { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + wasm.datum_to_bytes(retptr, this.ptr); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var v0 = getArrayU8FromWasm0(r0, r1).slice(); + wasm.__wbindgen_free(r0, r1 * 1); + return v0; + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @param {Uint8Array} bytes + * @returns {Datum} + */ + static from_bytes(bytes) { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + const ptr0 = passArray8ToWasm0(bytes, wasm.__wbindgen_malloc); + const len0 = WASM_VECTOR_LEN; + wasm.datum_from_bytes(retptr, ptr0, len0); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + if (r2) { + throw takeObject(r1); + } + return Datum.__wrap(r0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @returns {string} + */ + to_json() { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + wasm.datum_to_json(retptr, this.ptr); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + var r3 = getInt32Memory0()[retptr / 4 + 3]; + var ptr0 = r0; + var len0 = r1; + if (r3) { + ptr0 = 0; + len0 = 0; + throw takeObject(r2); + } + return getStringFromWasm0(ptr0, len0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + wasm.__wbindgen_free(ptr0, len0); + } + } + /** + * @returns {any} + */ + to_js_value() { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + wasm.datum_to_js_value(retptr, this.ptr); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + if (r2) { + throw takeObject(r1); + } + return takeObject(r0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @param {string} json + * @returns {Datum} + */ + static from_json(json) { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + const ptr0 = passStringToWasm0( + json, + wasm.__wbindgen_malloc, + wasm.__wbindgen_realloc, + ); + const len0 = WASM_VECTOR_LEN; + wasm.datum_from_json(retptr, ptr0, len0); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + if (r2) { + throw takeObject(r1); + } + return Datum.__wrap(r0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @param {DataHash} data_hash + * @returns {Datum} + */ + static new_data_hash(data_hash) { + _assertClass(data_hash, DataHash); + const ret = wasm.datum_new_data_hash(data_hash.ptr); + return Datum.__wrap(ret); + } + /** + * @param {Data} data + * @returns {Datum} + */ + static new_data(data) { + _assertClass(data, Data); + const ret = wasm.datum_new_data(data.ptr); + return Datum.__wrap(ret); + } + /** + * @returns {number} + */ + kind() { + const ret = wasm.datum_kind(this.ptr); + return ret >>> 0; + } + /** + * @returns {DataHash | undefined} + */ + as_data_hash() { + const ret = wasm.datum_as_data_hash(this.ptr); + return ret === 0 ? undefined : DataHash.__wrap(ret); + } + /** + * @returns {Data | undefined} + */ + as_data() { + const ret = wasm.datum_as_data(this.ptr); + return ret === 0 ? undefined : Data.__wrap(ret); + } +} +module.exports.Datum = Datum; + +const DrepFinalization = new FinalizationRegistry((ptr) => + wasm.__wbg_drep_free(ptr) +); +/** */ +class Drep { + static __wrap(ptr) { + const obj = Object.create(Drep.prototype); + obj.ptr = ptr; + DrepFinalization.register(obj, obj.ptr, obj); + return obj; + } + + __destroy_into_raw() { + const ptr = this.ptr; + this.ptr = 0; + DrepFinalization.unregister(this); + return ptr; + } + + free() { + const ptr = this.__destroy_into_raw(); + wasm.__wbg_drep_free(ptr); + } + /** + * @returns {Uint8Array} + */ + to_bytes() { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + wasm.drep_to_bytes(retptr, this.ptr); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var v0 = getArrayU8FromWasm0(r0, r1).slice(); + wasm.__wbindgen_free(r0, r1 * 1); + return v0; + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @param {Uint8Array} bytes + * @returns {Drep} + */ + static from_bytes(bytes) { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + const ptr0 = passArray8ToWasm0(bytes, wasm.__wbindgen_malloc); + const len0 = WASM_VECTOR_LEN; + wasm.drep_from_bytes(retptr, ptr0, len0); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + if (r2) { + throw takeObject(r1); + } + return Drep.__wrap(r0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @returns {string} + */ + to_json() { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + wasm.drep_to_json(retptr, this.ptr); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + var r3 = getInt32Memory0()[retptr / 4 + 3]; + var ptr0 = r0; + var len0 = r1; + if (r3) { + ptr0 = 0; + len0 = 0; + throw takeObject(r2); + } + return getStringFromWasm0(ptr0, len0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + wasm.__wbindgen_free(ptr0, len0); + } + } + /** + * @returns {any} + */ + to_js_value() { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + wasm.drep_to_js_value(retptr, this.ptr); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + if (r2) { + throw takeObject(r1); + } + return takeObject(r0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @param {string} json + * @returns {Drep} + */ + static from_json(json) { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + const ptr0 = passStringToWasm0( + json, + wasm.__wbindgen_malloc, + wasm.__wbindgen_realloc, + ); + const len0 = WASM_VECTOR_LEN; + wasm.drep_from_json(retptr, ptr0, len0); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + if (r2) { + throw takeObject(r1); + } + return Drep.__wrap(r0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @param {Ed25519KeyHash} keyhash + * @returns {Drep} + */ + static new_keyhash(keyhash) { + _assertClass(keyhash, Ed25519KeyHash); + const ret = wasm.drep_new_keyhash(keyhash.ptr); + return Drep.__wrap(ret); + } + /** + * @param {ScriptHash} scripthash + * @returns {Drep} + */ + static new_scripthash(scripthash) { + _assertClass(scripthash, ScriptHash); + const ret = wasm.drep_new_scripthash(scripthash.ptr); + return Drep.__wrap(ret); + } + /** + * @returns {Drep} + */ + static new_abstain() { + const ret = wasm.drep_new_abstain(); + return Drep.__wrap(ret); + } + /** + * @returns {Drep} + */ + static new_no_confidence() { + const ret = wasm.drep_new_no_confidence(); + return Drep.__wrap(ret); + } + /** + * @returns {number} + */ + kind() { + const ret = wasm.drep_kind(this.ptr); + return ret >>> 0; + } + /** + * @returns {Ed25519KeyHash | undefined} + */ + as_keyhash() { + const ret = wasm.drep_as_keyhash(this.ptr); + return ret === 0 ? undefined : Ed25519KeyHash.__wrap(ret); + } + /** + * @returns {ScriptHash | undefined} + */ + as_scripthash() { + const ret = wasm.drep_as_scripthash(this.ptr); + return ret === 0 ? undefined : ScriptHash.__wrap(ret); + } +} +module.exports.Drep = Drep; + +const DrepVotingThresholdsFinalization = new FinalizationRegistry((ptr) => + wasm.__wbg_drepvotingthresholds_free(ptr) +); +/** */ +class DrepVotingThresholds { + static __wrap(ptr) { + const obj = Object.create(DrepVotingThresholds.prototype); + obj.ptr = ptr; + DrepVotingThresholdsFinalization.register(obj, obj.ptr, obj); + return obj; + } + + __destroy_into_raw() { + const ptr = this.ptr; + this.ptr = 0; + DrepVotingThresholdsFinalization.unregister(this); + return ptr; + } + + free() { + const ptr = this.__destroy_into_raw(); + wasm.__wbg_drepvotingthresholds_free(ptr); + } + /** + * @returns {Uint8Array} + */ + to_bytes() { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + wasm.drepvotingthresholds_to_bytes(retptr, this.ptr); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var v0 = getArrayU8FromWasm0(r0, r1).slice(); + wasm.__wbindgen_free(r0, r1 * 1); + return v0; + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @param {Uint8Array} bytes + * @returns {DrepVotingThresholds} + */ + static from_bytes(bytes) { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + const ptr0 = passArray8ToWasm0(bytes, wasm.__wbindgen_malloc); + const len0 = WASM_VECTOR_LEN; + wasm.drepvotingthresholds_from_bytes(retptr, ptr0, len0); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + if (r2) { + throw takeObject(r1); + } + return DrepVotingThresholds.__wrap(r0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @returns {string} + */ + to_json() { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + wasm.drepvotingthresholds_to_json(retptr, this.ptr); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + var r3 = getInt32Memory0()[retptr / 4 + 3]; + var ptr0 = r0; + var len0 = r1; + if (r3) { + ptr0 = 0; + len0 = 0; + throw takeObject(r2); + } + return getStringFromWasm0(ptr0, len0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + wasm.__wbindgen_free(ptr0, len0); + } + } + /** + * @returns {any} + */ + to_js_value() { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + wasm.drepvotingthresholds_to_js_value(retptr, this.ptr); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + if (r2) { + throw takeObject(r1); + } + return takeObject(r0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @param {string} json + * @returns {DrepVotingThresholds} + */ + static from_json(json) { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + const ptr0 = passStringToWasm0( + json, + wasm.__wbindgen_malloc, + wasm.__wbindgen_realloc, + ); + const len0 = WASM_VECTOR_LEN; + wasm.drepvotingthresholds_from_json(retptr, ptr0, len0); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + if (r2) { + throw takeObject(r1); + } + return DrepVotingThresholds.__wrap(r0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @returns {UnitInterval} + */ + motion_no_confidence() { + const ret = wasm.drepvotingthresholds_motion_no_confidence(this.ptr); + return UnitInterval.__wrap(ret); + } + /** + * @returns {UnitInterval} + */ + committee_normal() { + const ret = wasm.drepvotingthresholds_committee_normal(this.ptr); + return UnitInterval.__wrap(ret); + } + /** + * @returns {UnitInterval} + */ + committee_no_confidence() { + const ret = wasm.drepvotingthresholds_committee_no_confidence(this.ptr); + return UnitInterval.__wrap(ret); + } + /** + * @returns {UnitInterval} + */ + update_constitution() { + const ret = wasm.drepvotingthresholds_update_constitution(this.ptr); + return UnitInterval.__wrap(ret); + } + /** + * @returns {UnitInterval} + */ + hard_fork_initiation() { + const ret = wasm.drepvotingthresholds_hard_fork_initiation(this.ptr); + return UnitInterval.__wrap(ret); + } + /** + * @returns {UnitInterval} + */ + pp_network_group() { + const ret = wasm.drepvotingthresholds_pp_network_group(this.ptr); + return UnitInterval.__wrap(ret); + } + /** + * @returns {UnitInterval} + */ + pp_economic_group() { + const ret = wasm.drepvotingthresholds_pp_economic_group(this.ptr); + return UnitInterval.__wrap(ret); + } + /** + * @returns {UnitInterval} + */ + pp_technical_group() { + const ret = wasm.drepvotingthresholds_pp_technical_group(this.ptr); + return UnitInterval.__wrap(ret); + } + /** + * @returns {UnitInterval} + */ + pp_governance_group() { + const ret = wasm.drepvotingthresholds_pp_governance_group(this.ptr); + return UnitInterval.__wrap(ret); + } + /** + * @returns {UnitInterval} + */ + treasury_withdrawal() { + const ret = wasm.drepvotingthresholds_treasury_withdrawal(this.ptr); + return UnitInterval.__wrap(ret); + } + /** + * @param {UnitInterval} motion_no_confidence + * @param {UnitInterval} committee_normal + * @param {UnitInterval} committee_no_confidence + * @param {UnitInterval} update_constitution + * @param {UnitInterval} hard_fork_initiation + * @param {UnitInterval} pp_network_group + * @param {UnitInterval} pp_economic_group + * @param {UnitInterval} pp_technical_group + * @param {UnitInterval} pp_governance_group + * @param {UnitInterval} treasury_withdrawal + * @returns {DrepVotingThresholds} + */ + static new( + motion_no_confidence, + committee_normal, + committee_no_confidence, + update_constitution, + hard_fork_initiation, + pp_network_group, + pp_economic_group, + pp_technical_group, + pp_governance_group, + treasury_withdrawal, + ) { + _assertClass(motion_no_confidence, UnitInterval); + _assertClass(committee_normal, UnitInterval); + _assertClass(committee_no_confidence, UnitInterval); + _assertClass(update_constitution, UnitInterval); + _assertClass(hard_fork_initiation, UnitInterval); + _assertClass(pp_network_group, UnitInterval); + _assertClass(pp_economic_group, UnitInterval); + _assertClass(pp_technical_group, UnitInterval); + _assertClass(pp_governance_group, UnitInterval); + _assertClass(treasury_withdrawal, UnitInterval); + const ret = wasm.drepvotingthresholds_new( + motion_no_confidence.ptr, + committee_normal.ptr, + committee_no_confidence.ptr, + update_constitution.ptr, + hard_fork_initiation.ptr, + pp_network_group.ptr, + pp_economic_group.ptr, + pp_technical_group.ptr, + pp_governance_group.ptr, + treasury_withdrawal.ptr, + ); + return DrepVotingThresholds.__wrap(ret); + } +} +module.exports.DrepVotingThresholds = DrepVotingThresholds; + +const Ed25519KeyHashFinalization = new FinalizationRegistry((ptr) => + wasm.__wbg_ed25519keyhash_free(ptr) +); +/** */ +class Ed25519KeyHash { + static __wrap(ptr) { + const obj = Object.create(Ed25519KeyHash.prototype); + obj.ptr = ptr; + Ed25519KeyHashFinalization.register(obj, obj.ptr, obj); + return obj; + } + + __destroy_into_raw() { + const ptr = this.ptr; + this.ptr = 0; + Ed25519KeyHashFinalization.unregister(this); + return ptr; + } + + free() { + const ptr = this.__destroy_into_raw(); + wasm.__wbg_ed25519keyhash_free(ptr); + } + /** + * @param {Uint8Array} bytes + * @returns {Ed25519KeyHash} + */ + static from_bytes(bytes) { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + const ptr0 = passArray8ToWasm0(bytes, wasm.__wbindgen_malloc); + const len0 = WASM_VECTOR_LEN; + wasm.ed25519keyhash_from_bytes(retptr, ptr0, len0); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + if (r2) { + throw takeObject(r1); + } + return Ed25519KeyHash.__wrap(r0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @returns {Uint8Array} + */ + to_bytes() { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + wasm.ed25519keyhash_to_bytes(retptr, this.ptr); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var v0 = getArrayU8FromWasm0(r0, r1).slice(); + wasm.__wbindgen_free(r0, r1 * 1); + return v0; + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @param {string} prefix + * @returns {string} + */ + to_bech32(prefix) { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + const ptr0 = passStringToWasm0( + prefix, + wasm.__wbindgen_malloc, + wasm.__wbindgen_realloc, + ); + const len0 = WASM_VECTOR_LEN; + wasm.ed25519keyhash_to_bech32(retptr, this.ptr, ptr0, len0); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + var r3 = getInt32Memory0()[retptr / 4 + 3]; + var ptr1 = r0; + var len1 = r1; + if (r3) { + ptr1 = 0; + len1 = 0; + throw takeObject(r2); + } + return getStringFromWasm0(ptr1, len1); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + wasm.__wbindgen_free(ptr1, len1); + } + } + /** + * @param {string} bech_str + * @returns {Ed25519KeyHash} + */ + static from_bech32(bech_str) { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + const ptr0 = passStringToWasm0( + bech_str, + wasm.__wbindgen_malloc, + wasm.__wbindgen_realloc, + ); + const len0 = WASM_VECTOR_LEN; + wasm.ed25519keyhash_from_bech32(retptr, ptr0, len0); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + if (r2) { + throw takeObject(r1); + } + return Ed25519KeyHash.__wrap(r0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @returns {string} + */ + to_hex() { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + wasm.ed25519keyhash_to_hex(retptr, this.ptr); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + return getStringFromWasm0(r0, r1); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + wasm.__wbindgen_free(r0, r1); + } + } + /** + * @param {string} hex + * @returns {Ed25519KeyHash} + */ + static from_hex(hex) { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + const ptr0 = passStringToWasm0( + hex, + wasm.__wbindgen_malloc, + wasm.__wbindgen_realloc, + ); + const len0 = WASM_VECTOR_LEN; + wasm.ed25519keyhash_from_hex(retptr, ptr0, len0); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + if (r2) { + throw takeObject(r1); + } + return Ed25519KeyHash.__wrap(r0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } +} +module.exports.Ed25519KeyHash = Ed25519KeyHash; + +const Ed25519KeyHashesFinalization = new FinalizationRegistry((ptr) => + wasm.__wbg_ed25519keyhashes_free(ptr) +); +/** */ +class Ed25519KeyHashes { + static __wrap(ptr) { + const obj = Object.create(Ed25519KeyHashes.prototype); + obj.ptr = ptr; + Ed25519KeyHashesFinalization.register(obj, obj.ptr, obj); + return obj; + } + + __destroy_into_raw() { + const ptr = this.ptr; + this.ptr = 0; + Ed25519KeyHashesFinalization.unregister(this); + return ptr; + } + + free() { + const ptr = this.__destroy_into_raw(); + wasm.__wbg_ed25519keyhashes_free(ptr); + } + /** + * @returns {Uint8Array} + */ + to_bytes() { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + wasm.ed25519keyhashes_to_bytes(retptr, this.ptr); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var v0 = getArrayU8FromWasm0(r0, r1).slice(); + wasm.__wbindgen_free(r0, r1 * 1); + return v0; + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @param {Uint8Array} bytes + * @returns {Ed25519KeyHashes} + */ + static from_bytes(bytes) { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + const ptr0 = passArray8ToWasm0(bytes, wasm.__wbindgen_malloc); + const len0 = WASM_VECTOR_LEN; + wasm.ed25519keyhashes_from_bytes(retptr, ptr0, len0); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + if (r2) { + throw takeObject(r1); + } + return Ed25519KeyHashes.__wrap(r0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @returns {string} + */ + to_json() { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + wasm.ed25519keyhashes_to_json(retptr, this.ptr); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + var r3 = getInt32Memory0()[retptr / 4 + 3]; + var ptr0 = r0; + var len0 = r1; + if (r3) { + ptr0 = 0; + len0 = 0; + throw takeObject(r2); + } + return getStringFromWasm0(ptr0, len0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + wasm.__wbindgen_free(ptr0, len0); + } + } + /** + * @returns {any} + */ + to_js_value() { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + wasm.ed25519keyhashes_to_js_value(retptr, this.ptr); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + if (r2) { + throw takeObject(r1); + } + return takeObject(r0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @param {string} json + * @returns {Ed25519KeyHashes} + */ + static from_json(json) { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + const ptr0 = passStringToWasm0( + json, + wasm.__wbindgen_malloc, + wasm.__wbindgen_realloc, + ); + const len0 = WASM_VECTOR_LEN; + wasm.ed25519keyhashes_from_json(retptr, ptr0, len0); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + if (r2) { + throw takeObject(r1); + } + return Ed25519KeyHashes.__wrap(r0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @returns {Ed25519KeyHashes} + */ + static new() { + const ret = wasm.ed25519keyhashes_new(); + return Ed25519KeyHashes.__wrap(ret); + } + /** + * @returns {number} + */ + len() { + const ret = wasm.assetnames_len(this.ptr); + return ret >>> 0; + } + /** + * @param {number} index + * @returns {Ed25519KeyHash} + */ + get(index) { + const ret = wasm.ed25519keyhashes_get(this.ptr, index); + return Ed25519KeyHash.__wrap(ret); + } + /** + * @param {Ed25519KeyHash} elem + */ + add(elem) { + _assertClass(elem, Ed25519KeyHash); + wasm.ed25519keyhashes_add(this.ptr, elem.ptr); + } +} +module.exports.Ed25519KeyHashes = Ed25519KeyHashes; + +const Ed25519SignatureFinalization = new FinalizationRegistry((ptr) => + wasm.__wbg_ed25519signature_free(ptr) +); +/** */ +class Ed25519Signature { + static __wrap(ptr) { + const obj = Object.create(Ed25519Signature.prototype); + obj.ptr = ptr; + Ed25519SignatureFinalization.register(obj, obj.ptr, obj); + return obj; + } + + __destroy_into_raw() { + const ptr = this.ptr; + this.ptr = 0; + Ed25519SignatureFinalization.unregister(this); + return ptr; + } + + free() { + const ptr = this.__destroy_into_raw(); + wasm.__wbg_ed25519signature_free(ptr); + } + /** + * @returns {Uint8Array} + */ + to_bytes() { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + wasm.ed25519signature_to_bytes(retptr, this.ptr); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var v0 = getArrayU8FromWasm0(r0, r1).slice(); + wasm.__wbindgen_free(r0, r1 * 1); + return v0; + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @returns {string} + */ + to_bech32() { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + wasm.ed25519signature_to_bech32(retptr, this.ptr); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + return getStringFromWasm0(r0, r1); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + wasm.__wbindgen_free(r0, r1); + } + } + /** + * @returns {string} + */ + to_hex() { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + wasm.ed25519signature_to_hex(retptr, this.ptr); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + return getStringFromWasm0(r0, r1); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + wasm.__wbindgen_free(r0, r1); + } + } + /** + * @param {string} bech32_str + * @returns {Ed25519Signature} + */ + static from_bech32(bech32_str) { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + const ptr0 = passStringToWasm0( + bech32_str, + wasm.__wbindgen_malloc, + wasm.__wbindgen_realloc, + ); + const len0 = WASM_VECTOR_LEN; + wasm.ed25519signature_from_bech32(retptr, ptr0, len0); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + if (r2) { + throw takeObject(r1); + } + return Ed25519Signature.__wrap(r0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @param {string} input + * @returns {Ed25519Signature} + */ + static from_hex(input) { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + const ptr0 = passStringToWasm0( + input, + wasm.__wbindgen_malloc, + wasm.__wbindgen_realloc, + ); + const len0 = WASM_VECTOR_LEN; + wasm.ed25519signature_from_hex(retptr, ptr0, len0); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + if (r2) { + throw takeObject(r1); + } + return Ed25519Signature.__wrap(r0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @param {Uint8Array} bytes + * @returns {Ed25519Signature} + */ + static from_bytes(bytes) { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + const ptr0 = passArray8ToWasm0(bytes, wasm.__wbindgen_malloc); + const len0 = WASM_VECTOR_LEN; + wasm.ed25519signature_from_bytes(retptr, ptr0, len0); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + if (r2) { + throw takeObject(r1); + } + return Ed25519Signature.__wrap(r0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } +} +module.exports.Ed25519Signature = Ed25519Signature; + +const EnterpriseAddressFinalization = new FinalizationRegistry((ptr) => + wasm.__wbg_enterpriseaddress_free(ptr) +); +/** */ +class EnterpriseAddress { + static __wrap(ptr) { + const obj = Object.create(EnterpriseAddress.prototype); + obj.ptr = ptr; + EnterpriseAddressFinalization.register(obj, obj.ptr, obj); + return obj; + } + + __destroy_into_raw() { + const ptr = this.ptr; + this.ptr = 0; + EnterpriseAddressFinalization.unregister(this); + return ptr; + } + + free() { + const ptr = this.__destroy_into_raw(); + wasm.__wbg_enterpriseaddress_free(ptr); + } + /** + * @param {number} network + * @param {StakeCredential} payment + * @returns {EnterpriseAddress} + */ + static new(network, payment) { + _assertClass(payment, StakeCredential); + const ret = wasm.enterpriseaddress_new(network, payment.ptr); + return EnterpriseAddress.__wrap(ret); + } + /** + * @returns {StakeCredential} + */ + payment_cred() { + const ret = wasm.baseaddress_payment_cred(this.ptr); + return StakeCredential.__wrap(ret); + } + /** + * @returns {Address} + */ + to_address() { + const ret = wasm.enterpriseaddress_to_address(this.ptr); + return Address.__wrap(ret); + } + /** + * @param {Address} addr + * @returns {EnterpriseAddress | undefined} + */ + static from_address(addr) { + _assertClass(addr, Address); + const ret = wasm.address_as_enterprise(addr.ptr); + return ret === 0 ? undefined : EnterpriseAddress.__wrap(ret); + } +} +module.exports.EnterpriseAddress = EnterpriseAddress; + +const ExUnitPricesFinalization = new FinalizationRegistry((ptr) => + wasm.__wbg_exunitprices_free(ptr) +); +/** */ +class ExUnitPrices { + static __wrap(ptr) { + const obj = Object.create(ExUnitPrices.prototype); + obj.ptr = ptr; + ExUnitPricesFinalization.register(obj, obj.ptr, obj); + return obj; + } + + __destroy_into_raw() { + const ptr = this.ptr; + this.ptr = 0; + ExUnitPricesFinalization.unregister(this); + return ptr; + } + + free() { + const ptr = this.__destroy_into_raw(); + wasm.__wbg_exunitprices_free(ptr); + } + /** + * @returns {Uint8Array} + */ + to_bytes() { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + wasm.exunitprices_to_bytes(retptr, this.ptr); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var v0 = getArrayU8FromWasm0(r0, r1).slice(); + wasm.__wbindgen_free(r0, r1 * 1); + return v0; + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @param {Uint8Array} bytes + * @returns {ExUnitPrices} + */ + static from_bytes(bytes) { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + const ptr0 = passArray8ToWasm0(bytes, wasm.__wbindgen_malloc); + const len0 = WASM_VECTOR_LEN; + wasm.exunitprices_from_bytes(retptr, ptr0, len0); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + if (r2) { + throw takeObject(r1); + } + return ExUnitPrices.__wrap(r0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @returns {UnitInterval} + */ + mem_price() { + const ret = wasm.drepvotingthresholds_motion_no_confidence(this.ptr); + return UnitInterval.__wrap(ret); + } + /** + * @returns {UnitInterval} + */ + step_price() { + const ret = wasm.drepvotingthresholds_committee_normal(this.ptr); + return UnitInterval.__wrap(ret); + } + /** + * @param {UnitInterval} mem_price + * @param {UnitInterval} step_price + * @returns {ExUnitPrices} + */ + static new(mem_price, step_price) { + _assertClass(mem_price, UnitInterval); + _assertClass(step_price, UnitInterval); + const ret = wasm.exunitprices_new(mem_price.ptr, step_price.ptr); + return ExUnitPrices.__wrap(ret); + } + /** + * @param {number} mem_price + * @param {number} step_price + * @returns {ExUnitPrices} + */ + static from_float(mem_price, step_price) { + const ret = wasm.exunitprices_from_float(mem_price, step_price); + return ExUnitPrices.__wrap(ret); + } +} +module.exports.ExUnitPrices = ExUnitPrices; + +const ExUnitsFinalization = new FinalizationRegistry((ptr) => + wasm.__wbg_exunits_free(ptr) +); +/** */ +class ExUnits { + static __wrap(ptr) { + const obj = Object.create(ExUnits.prototype); + obj.ptr = ptr; + ExUnitsFinalization.register(obj, obj.ptr, obj); + return obj; + } + + __destroy_into_raw() { + const ptr = this.ptr; + this.ptr = 0; + ExUnitsFinalization.unregister(this); + return ptr; + } + + free() { + const ptr = this.__destroy_into_raw(); + wasm.__wbg_exunits_free(ptr); + } + /** + * @returns {Uint8Array} + */ + to_bytes() { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + wasm.exunits_to_bytes(retptr, this.ptr); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var v0 = getArrayU8FromWasm0(r0, r1).slice(); + wasm.__wbindgen_free(r0, r1 * 1); + return v0; + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @param {Uint8Array} bytes + * @returns {ExUnits} + */ + static from_bytes(bytes) { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + const ptr0 = passArray8ToWasm0(bytes, wasm.__wbindgen_malloc); + const len0 = WASM_VECTOR_LEN; + wasm.exunits_from_bytes(retptr, ptr0, len0); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + if (r2) { + throw takeObject(r1); + } + return ExUnits.__wrap(r0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @returns {BigNum} + */ + mem() { + const ret = wasm.constrplutusdata_alternative(this.ptr); + return BigNum.__wrap(ret); + } + /** + * @returns {BigNum} + */ + steps() { + const ret = wasm.exunits_steps(this.ptr); + return BigNum.__wrap(ret); + } + /** + * @param {BigNum} mem + * @param {BigNum} steps + * @returns {ExUnits} + */ + static new(mem, steps) { + _assertClass(mem, BigNum); + _assertClass(steps, BigNum); + const ret = wasm.exunits_new(mem.ptr, steps.ptr); + return ExUnits.__wrap(ret); + } +} +module.exports.ExUnits = ExUnits; + +const GeneralTransactionMetadataFinalization = new FinalizationRegistry((ptr) => + wasm.__wbg_generaltransactionmetadata_free(ptr) +); +/** */ +class GeneralTransactionMetadata { + static __wrap(ptr) { + const obj = Object.create(GeneralTransactionMetadata.prototype); + obj.ptr = ptr; + GeneralTransactionMetadataFinalization.register(obj, obj.ptr, obj); + return obj; + } + + __destroy_into_raw() { + const ptr = this.ptr; + this.ptr = 0; + GeneralTransactionMetadataFinalization.unregister(this); + return ptr; + } + + free() { + const ptr = this.__destroy_into_raw(); + wasm.__wbg_generaltransactionmetadata_free(ptr); + } + /** + * @returns {Uint8Array} + */ + to_bytes() { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + wasm.generaltransactionmetadata_to_bytes(retptr, this.ptr); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var v0 = getArrayU8FromWasm0(r0, r1).slice(); + wasm.__wbindgen_free(r0, r1 * 1); + return v0; + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @param {Uint8Array} bytes + * @returns {GeneralTransactionMetadata} + */ + static from_bytes(bytes) { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + const ptr0 = passArray8ToWasm0(bytes, wasm.__wbindgen_malloc); + const len0 = WASM_VECTOR_LEN; + wasm.generaltransactionmetadata_from_bytes(retptr, ptr0, len0); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + if (r2) { + throw takeObject(r1); + } + return GeneralTransactionMetadata.__wrap(r0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @returns {string} + */ + to_json() { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + wasm.generaltransactionmetadata_to_json(retptr, this.ptr); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + var r3 = getInt32Memory0()[retptr / 4 + 3]; + var ptr0 = r0; + var len0 = r1; + if (r3) { + ptr0 = 0; + len0 = 0; + throw takeObject(r2); + } + return getStringFromWasm0(ptr0, len0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + wasm.__wbindgen_free(ptr0, len0); + } + } + /** + * @returns {any} + */ + to_js_value() { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + wasm.generaltransactionmetadata_to_js_value(retptr, this.ptr); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + if (r2) { + throw takeObject(r1); + } + return takeObject(r0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @param {string} json + * @returns {GeneralTransactionMetadata} + */ + static from_json(json) { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + const ptr0 = passStringToWasm0( + json, + wasm.__wbindgen_malloc, + wasm.__wbindgen_realloc, + ); + const len0 = WASM_VECTOR_LEN; + wasm.generaltransactionmetadata_from_json(retptr, ptr0, len0); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + if (r2) { + throw takeObject(r1); + } + return GeneralTransactionMetadata.__wrap(r0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @returns {GeneralTransactionMetadata} + */ + static new() { + const ret = wasm.auxiliarydataset_new(); + return GeneralTransactionMetadata.__wrap(ret); + } + /** + * @returns {number} + */ + len() { + const ret = wasm.auxiliarydataset_len(this.ptr); + return ret >>> 0; + } + /** + * @param {BigNum} key + * @param {TransactionMetadatum} value + * @returns {TransactionMetadatum | undefined} + */ + insert(key, value) { + _assertClass(key, BigNum); + _assertClass(value, TransactionMetadatum); + const ret = wasm.generaltransactionmetadata_insert( + this.ptr, + key.ptr, + value.ptr, + ); + return ret === 0 ? undefined : TransactionMetadatum.__wrap(ret); + } + /** + * @param {BigNum} key + * @returns {TransactionMetadatum | undefined} + */ + get(key) { + _assertClass(key, BigNum); + const ret = wasm.generaltransactionmetadata_get(this.ptr, key.ptr); + return ret === 0 ? undefined : TransactionMetadatum.__wrap(ret); + } + /** + * @returns {TransactionMetadatumLabels} + */ + keys() { + const ret = wasm.generaltransactionmetadata_keys(this.ptr); + return TransactionMetadatumLabels.__wrap(ret); + } +} +module.exports.GeneralTransactionMetadata = GeneralTransactionMetadata; + +const GenesisDelegateHashFinalization = new FinalizationRegistry((ptr) => + wasm.__wbg_genesisdelegatehash_free(ptr) +); +/** */ +class GenesisDelegateHash { + static __wrap(ptr) { + const obj = Object.create(GenesisDelegateHash.prototype); + obj.ptr = ptr; + GenesisDelegateHashFinalization.register(obj, obj.ptr, obj); + return obj; + } + + __destroy_into_raw() { + const ptr = this.ptr; + this.ptr = 0; + GenesisDelegateHashFinalization.unregister(this); + return ptr; + } + + free() { + const ptr = this.__destroy_into_raw(); + wasm.__wbg_genesisdelegatehash_free(ptr); + } + /** + * @param {Uint8Array} bytes + * @returns {GenesisDelegateHash} + */ + static from_bytes(bytes) { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + const ptr0 = passArray8ToWasm0(bytes, wasm.__wbindgen_malloc); + const len0 = WASM_VECTOR_LEN; + wasm.genesisdelegatehash_from_bytes(retptr, ptr0, len0); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + if (r2) { + throw takeObject(r1); + } + return GenesisDelegateHash.__wrap(r0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @returns {Uint8Array} + */ + to_bytes() { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + wasm.ed25519keyhash_to_bytes(retptr, this.ptr); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var v0 = getArrayU8FromWasm0(r0, r1).slice(); + wasm.__wbindgen_free(r0, r1 * 1); + return v0; + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @param {string} prefix + * @returns {string} + */ + to_bech32(prefix) { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + const ptr0 = passStringToWasm0( + prefix, + wasm.__wbindgen_malloc, + wasm.__wbindgen_realloc, + ); + const len0 = WASM_VECTOR_LEN; + wasm.ed25519keyhash_to_bech32(retptr, this.ptr, ptr0, len0); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + var r3 = getInt32Memory0()[retptr / 4 + 3]; + var ptr1 = r0; + var len1 = r1; + if (r3) { + ptr1 = 0; + len1 = 0; + throw takeObject(r2); + } + return getStringFromWasm0(ptr1, len1); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + wasm.__wbindgen_free(ptr1, len1); + } + } + /** + * @param {string} bech_str + * @returns {GenesisDelegateHash} + */ + static from_bech32(bech_str) { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + const ptr0 = passStringToWasm0( + bech_str, + wasm.__wbindgen_malloc, + wasm.__wbindgen_realloc, + ); + const len0 = WASM_VECTOR_LEN; + wasm.genesisdelegatehash_from_bech32(retptr, ptr0, len0); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + if (r2) { + throw takeObject(r1); + } + return GenesisDelegateHash.__wrap(r0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @returns {string} + */ + to_hex() { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + wasm.ed25519keyhash_to_hex(retptr, this.ptr); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + return getStringFromWasm0(r0, r1); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + wasm.__wbindgen_free(r0, r1); + } + } + /** + * @param {string} hex + * @returns {GenesisDelegateHash} + */ + static from_hex(hex) { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + const ptr0 = passStringToWasm0( + hex, + wasm.__wbindgen_malloc, + wasm.__wbindgen_realloc, + ); + const len0 = WASM_VECTOR_LEN; + wasm.genesisdelegatehash_from_hex(retptr, ptr0, len0); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + if (r2) { + throw takeObject(r1); + } + return GenesisDelegateHash.__wrap(r0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } +} +module.exports.GenesisDelegateHash = GenesisDelegateHash; + +const GenesisHashFinalization = new FinalizationRegistry((ptr) => + wasm.__wbg_genesishash_free(ptr) +); +/** */ +class GenesisHash { + static __wrap(ptr) { + const obj = Object.create(GenesisHash.prototype); + obj.ptr = ptr; + GenesisHashFinalization.register(obj, obj.ptr, obj); + return obj; + } + + __destroy_into_raw() { + const ptr = this.ptr; + this.ptr = 0; + GenesisHashFinalization.unregister(this); + return ptr; + } + + free() { + const ptr = this.__destroy_into_raw(); + wasm.__wbg_genesishash_free(ptr); + } + /** + * @param {Uint8Array} bytes + * @returns {GenesisHash} + */ + static from_bytes(bytes) { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + const ptr0 = passArray8ToWasm0(bytes, wasm.__wbindgen_malloc); + const len0 = WASM_VECTOR_LEN; + wasm.genesishash_from_bytes(retptr, ptr0, len0); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + if (r2) { + throw takeObject(r1); + } + return GenesisHash.__wrap(r0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @returns {Uint8Array} + */ + to_bytes() { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + wasm.ed25519keyhash_to_bytes(retptr, this.ptr); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var v0 = getArrayU8FromWasm0(r0, r1).slice(); + wasm.__wbindgen_free(r0, r1 * 1); + return v0; + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @param {string} prefix + * @returns {string} + */ + to_bech32(prefix) { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + const ptr0 = passStringToWasm0( + prefix, + wasm.__wbindgen_malloc, + wasm.__wbindgen_realloc, + ); + const len0 = WASM_VECTOR_LEN; + wasm.ed25519keyhash_to_bech32(retptr, this.ptr, ptr0, len0); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + var r3 = getInt32Memory0()[retptr / 4 + 3]; + var ptr1 = r0; + var len1 = r1; + if (r3) { + ptr1 = 0; + len1 = 0; + throw takeObject(r2); + } + return getStringFromWasm0(ptr1, len1); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + wasm.__wbindgen_free(ptr1, len1); + } + } + /** + * @param {string} bech_str + * @returns {GenesisHash} + */ + static from_bech32(bech_str) { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + const ptr0 = passStringToWasm0( + bech_str, + wasm.__wbindgen_malloc, + wasm.__wbindgen_realloc, + ); + const len0 = WASM_VECTOR_LEN; + wasm.genesishash_from_bech32(retptr, ptr0, len0); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + if (r2) { + throw takeObject(r1); + } + return GenesisHash.__wrap(r0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @returns {string} + */ + to_hex() { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + wasm.ed25519keyhash_to_hex(retptr, this.ptr); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + return getStringFromWasm0(r0, r1); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + wasm.__wbindgen_free(r0, r1); + } + } + /** + * @param {string} hex + * @returns {GenesisHash} + */ + static from_hex(hex) { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + const ptr0 = passStringToWasm0( + hex, + wasm.__wbindgen_malloc, + wasm.__wbindgen_realloc, + ); + const len0 = WASM_VECTOR_LEN; + wasm.genesishash_from_hex(retptr, ptr0, len0); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + if (r2) { + throw takeObject(r1); + } + return GenesisHash.__wrap(r0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } +} +module.exports.GenesisHash = GenesisHash; + +const GenesisHashesFinalization = new FinalizationRegistry((ptr) => + wasm.__wbg_genesishashes_free(ptr) +); +/** */ +class GenesisHashes { + static __wrap(ptr) { + const obj = Object.create(GenesisHashes.prototype); + obj.ptr = ptr; + GenesisHashesFinalization.register(obj, obj.ptr, obj); + return obj; + } + + __destroy_into_raw() { + const ptr = this.ptr; + this.ptr = 0; + GenesisHashesFinalization.unregister(this); + return ptr; + } + + free() { + const ptr = this.__destroy_into_raw(); + wasm.__wbg_genesishashes_free(ptr); + } + /** + * @returns {Uint8Array} + */ + to_bytes() { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + wasm.genesishashes_to_bytes(retptr, this.ptr); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var v0 = getArrayU8FromWasm0(r0, r1).slice(); + wasm.__wbindgen_free(r0, r1 * 1); + return v0; + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @param {Uint8Array} bytes + * @returns {GenesisHashes} + */ + static from_bytes(bytes) { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + const ptr0 = passArray8ToWasm0(bytes, wasm.__wbindgen_malloc); + const len0 = WASM_VECTOR_LEN; + wasm.genesishashes_from_bytes(retptr, ptr0, len0); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + if (r2) { + throw takeObject(r1); + } + return GenesisHashes.__wrap(r0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @returns {string} + */ + to_json() { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + wasm.ed25519keyhashes_to_json(retptr, this.ptr); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + var r3 = getInt32Memory0()[retptr / 4 + 3]; + var ptr0 = r0; + var len0 = r1; + if (r3) { + ptr0 = 0; + len0 = 0; + throw takeObject(r2); + } + return getStringFromWasm0(ptr0, len0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + wasm.__wbindgen_free(ptr0, len0); + } + } + /** + * @returns {any} + */ + to_js_value() { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + wasm.ed25519keyhashes_to_js_value(retptr, this.ptr); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + if (r2) { + throw takeObject(r1); + } + return takeObject(r0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @param {string} json + * @returns {GenesisHashes} + */ + static from_json(json) { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + const ptr0 = passStringToWasm0( + json, + wasm.__wbindgen_malloc, + wasm.__wbindgen_realloc, + ); + const len0 = WASM_VECTOR_LEN; + wasm.genesishashes_from_json(retptr, ptr0, len0); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + if (r2) { + throw takeObject(r1); + } + return GenesisHashes.__wrap(r0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @returns {GenesisHashes} + */ + static new() { + const ret = wasm.ed25519keyhashes_new(); + return GenesisHashes.__wrap(ret); + } + /** + * @returns {number} + */ + len() { + const ret = wasm.assetnames_len(this.ptr); + return ret >>> 0; + } + /** + * @param {number} index + * @returns {GenesisHash} + */ + get(index) { + const ret = wasm.genesishashes_get(this.ptr, index); + return GenesisHash.__wrap(ret); + } + /** + * @param {GenesisHash} elem + */ + add(elem) { + _assertClass(elem, GenesisHash); + wasm.ed25519keyhashes_add(this.ptr, elem.ptr); + } +} +module.exports.GenesisHashes = GenesisHashes; + +const GenesisKeyDelegationFinalization = new FinalizationRegistry((ptr) => + wasm.__wbg_genesiskeydelegation_free(ptr) +); +/** */ +class GenesisKeyDelegation { + static __wrap(ptr) { + const obj = Object.create(GenesisKeyDelegation.prototype); + obj.ptr = ptr; + GenesisKeyDelegationFinalization.register(obj, obj.ptr, obj); + return obj; + } + + __destroy_into_raw() { + const ptr = this.ptr; + this.ptr = 0; + GenesisKeyDelegationFinalization.unregister(this); + return ptr; + } + + free() { + const ptr = this.__destroy_into_raw(); + wasm.__wbg_genesiskeydelegation_free(ptr); + } + /** + * @returns {Uint8Array} + */ + to_bytes() { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + wasm.genesiskeydelegation_to_bytes(retptr, this.ptr); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var v0 = getArrayU8FromWasm0(r0, r1).slice(); + wasm.__wbindgen_free(r0, r1 * 1); + return v0; + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @param {Uint8Array} bytes + * @returns {GenesisKeyDelegation} + */ + static from_bytes(bytes) { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + const ptr0 = passArray8ToWasm0(bytes, wasm.__wbindgen_malloc); + const len0 = WASM_VECTOR_LEN; + wasm.genesiskeydelegation_from_bytes(retptr, ptr0, len0); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + if (r2) { + throw takeObject(r1); + } + return GenesisKeyDelegation.__wrap(r0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @returns {string} + */ + to_json() { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + wasm.genesiskeydelegation_to_json(retptr, this.ptr); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + var r3 = getInt32Memory0()[retptr / 4 + 3]; + var ptr0 = r0; + var len0 = r1; + if (r3) { + ptr0 = 0; + len0 = 0; + throw takeObject(r2); + } + return getStringFromWasm0(ptr0, len0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + wasm.__wbindgen_free(ptr0, len0); + } + } + /** + * @returns {any} + */ + to_js_value() { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + wasm.genesiskeydelegation_to_js_value(retptr, this.ptr); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + if (r2) { + throw takeObject(r1); + } + return takeObject(r0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @param {string} json + * @returns {GenesisKeyDelegation} + */ + static from_json(json) { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + const ptr0 = passStringToWasm0( + json, + wasm.__wbindgen_malloc, + wasm.__wbindgen_realloc, + ); + const len0 = WASM_VECTOR_LEN; + wasm.genesiskeydelegation_from_json(retptr, ptr0, len0); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + if (r2) { + throw takeObject(r1); + } + return GenesisKeyDelegation.__wrap(r0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @returns {GenesisHash} + */ + genesishash() { + const ret = wasm.genesiskeydelegation_genesishash(this.ptr); + return GenesisHash.__wrap(ret); + } + /** + * @returns {GenesisDelegateHash} + */ + genesis_delegate_hash() { + const ret = wasm.genesiskeydelegation_genesis_delegate_hash(this.ptr); + return GenesisDelegateHash.__wrap(ret); + } + /** + * @returns {VRFKeyHash} + */ + vrf_keyhash() { + const ret = wasm.genesiskeydelegation_vrf_keyhash(this.ptr); + return VRFKeyHash.__wrap(ret); + } + /** + * @param {GenesisHash} genesishash + * @param {GenesisDelegateHash} genesis_delegate_hash + * @param {VRFKeyHash} vrf_keyhash + * @returns {GenesisKeyDelegation} + */ + static new(genesishash, genesis_delegate_hash, vrf_keyhash) { + _assertClass(genesishash, GenesisHash); + _assertClass(genesis_delegate_hash, GenesisDelegateHash); + _assertClass(vrf_keyhash, VRFKeyHash); + const ret = wasm.genesiskeydelegation_new( + genesishash.ptr, + genesis_delegate_hash.ptr, + vrf_keyhash.ptr, + ); + return GenesisKeyDelegation.__wrap(ret); + } +} +module.exports.GenesisKeyDelegation = GenesisKeyDelegation; + +const GovernanceActionFinalization = new FinalizationRegistry((ptr) => + wasm.__wbg_governanceaction_free(ptr) +); +/** */ +class GovernanceAction { + static __wrap(ptr) { + const obj = Object.create(GovernanceAction.prototype); + obj.ptr = ptr; + GovernanceActionFinalization.register(obj, obj.ptr, obj); + return obj; + } + + __destroy_into_raw() { + const ptr = this.ptr; + this.ptr = 0; + GovernanceActionFinalization.unregister(this); + return ptr; + } + + free() { + const ptr = this.__destroy_into_raw(); + wasm.__wbg_governanceaction_free(ptr); + } + /** + * @returns {Uint8Array} + */ + to_bytes() { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + wasm.governanceaction_to_bytes(retptr, this.ptr); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var v0 = getArrayU8FromWasm0(r0, r1).slice(); + wasm.__wbindgen_free(r0, r1 * 1); + return v0; + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @param {Uint8Array} bytes + * @returns {GovernanceAction} + */ + static from_bytes(bytes) { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + const ptr0 = passArray8ToWasm0(bytes, wasm.__wbindgen_malloc); + const len0 = WASM_VECTOR_LEN; + wasm.governanceaction_from_bytes(retptr, ptr0, len0); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + if (r2) { + throw takeObject(r1); + } + return GovernanceAction.__wrap(r0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @returns {string} + */ + to_json() { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + wasm.governanceaction_to_json(retptr, this.ptr); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + var r3 = getInt32Memory0()[retptr / 4 + 3]; + var ptr0 = r0; + var len0 = r1; + if (r3) { + ptr0 = 0; + len0 = 0; + throw takeObject(r2); + } + return getStringFromWasm0(ptr0, len0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + wasm.__wbindgen_free(ptr0, len0); + } + } + /** + * @returns {any} + */ + to_js_value() { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + wasm.governanceaction_to_js_value(retptr, this.ptr); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + if (r2) { + throw takeObject(r1); + } + return takeObject(r0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @param {string} json + * @returns {GovernanceAction} + */ + static from_json(json) { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + const ptr0 = passStringToWasm0( + json, + wasm.__wbindgen_malloc, + wasm.__wbindgen_realloc, + ); + const len0 = WASM_VECTOR_LEN; + wasm.governanceaction_from_json(retptr, ptr0, len0); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + if (r2) { + throw takeObject(r1); + } + return GovernanceAction.__wrap(r0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @param {ParameterChangeAction} parameter_change_action + * @returns {GovernanceAction} + */ + static new_parameter_change_action(parameter_change_action) { + _assertClass(parameter_change_action, ParameterChangeAction); + const ret = wasm.governanceaction_new_parameter_change_action( + parameter_change_action.ptr, + ); + return GovernanceAction.__wrap(ret); + } + /** + * @param {HardForkInitiationAction} hard_fork_initiation_action + * @returns {GovernanceAction} + */ + static new_hard_fork_initiation_action(hard_fork_initiation_action) { + _assertClass(hard_fork_initiation_action, HardForkInitiationAction); + const ret = wasm.governanceaction_new_hard_fork_initiation_action( + hard_fork_initiation_action.ptr, + ); + return GovernanceAction.__wrap(ret); + } + /** + * @param {TreasuryWithdrawalsAction} treasury_withdrawals_action + * @returns {GovernanceAction} + */ + static new_treasury_withdrawals_action(treasury_withdrawals_action) { + _assertClass(treasury_withdrawals_action, TreasuryWithdrawalsAction); + const ret = wasm.governanceaction_new_treasury_withdrawals_action( + treasury_withdrawals_action.ptr, + ); + return GovernanceAction.__wrap(ret); + } + /** + * @returns {GovernanceAction} + */ + static new_no_confidence() { + const ret = wasm.governanceaction_new_no_confidence(); + return GovernanceAction.__wrap(ret); + } + /** + * @param {NewCommittee} new_committe + * @returns {GovernanceAction} + */ + static new_new_committee(new_committe) { + _assertClass(new_committe, NewCommittee); + const ret = wasm.governanceaction_new_new_committee(new_committe.ptr); + return GovernanceAction.__wrap(ret); + } + /** + * @param {NewConstitution} new_constitution + * @returns {GovernanceAction} + */ + static new_new_constitution(new_constitution) { + _assertClass(new_constitution, NewConstitution); + const ret = wasm.governanceaction_new_new_constitution( + new_constitution.ptr, + ); + return GovernanceAction.__wrap(ret); + } + /** + * @returns {GovernanceAction} + */ + static new_info_action() { + const ret = wasm.governanceaction_new_info_action(); + return GovernanceAction.__wrap(ret); + } + /** + * @returns {number} + */ + kind() { + const ret = wasm.governanceaction_kind(this.ptr); + return ret >>> 0; + } + /** + * @returns {ParameterChangeAction | undefined} + */ + as_parameter_change_action() { + const ret = wasm.governanceaction_as_parameter_change_action(this.ptr); + return ret === 0 ? undefined : ParameterChangeAction.__wrap(ret); + } + /** + * @returns {HardForkInitiationAction | undefined} + */ + as_hard_fork_initiation_action() { + const ret = wasm.governanceaction_as_hard_fork_initiation_action(this.ptr); + return ret === 0 ? undefined : HardForkInitiationAction.__wrap(ret); + } + /** + * @returns {TreasuryWithdrawalsAction | undefined} + */ + as_treasury_withdrawals_action() { + const ret = wasm.governanceaction_as_treasury_withdrawals_action(this.ptr); + return ret === 0 ? undefined : TreasuryWithdrawalsAction.__wrap(ret); + } + /** + * @returns {NewCommittee | undefined} + */ + as_new_committee() { + const ret = wasm.governanceaction_as_new_committee(this.ptr); + return ret === 0 ? undefined : NewCommittee.__wrap(ret); + } + /** + * @returns {NewConstitution | undefined} + */ + as_new_constitution() { + const ret = wasm.governanceaction_as_new_constitution(this.ptr); + return ret === 0 ? undefined : NewConstitution.__wrap(ret); + } +} +module.exports.GovernanceAction = GovernanceAction; + +const GovernanceActionIdFinalization = new FinalizationRegistry((ptr) => + wasm.__wbg_governanceactionid_free(ptr) +); +/** */ +class GovernanceActionId { + static __wrap(ptr) { + const obj = Object.create(GovernanceActionId.prototype); + obj.ptr = ptr; + GovernanceActionIdFinalization.register(obj, obj.ptr, obj); + return obj; + } + + __destroy_into_raw() { + const ptr = this.ptr; + this.ptr = 0; + GovernanceActionIdFinalization.unregister(this); + return ptr; + } + + free() { + const ptr = this.__destroy_into_raw(); + wasm.__wbg_governanceactionid_free(ptr); + } + /** + * @returns {Uint8Array} + */ + to_bytes() { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + wasm.governanceactionid_to_bytes(retptr, this.ptr); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var v0 = getArrayU8FromWasm0(r0, r1).slice(); + wasm.__wbindgen_free(r0, r1 * 1); + return v0; + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @param {Uint8Array} bytes + * @returns {GovernanceActionId} + */ + static from_bytes(bytes) { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + const ptr0 = passArray8ToWasm0(bytes, wasm.__wbindgen_malloc); + const len0 = WASM_VECTOR_LEN; + wasm.governanceactionid_from_bytes(retptr, ptr0, len0); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + if (r2) { + throw takeObject(r1); + } + return GovernanceActionId.__wrap(r0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @returns {string} + */ + to_json() { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + wasm.governanceactionid_to_json(retptr, this.ptr); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + var r3 = getInt32Memory0()[retptr / 4 + 3]; + var ptr0 = r0; + var len0 = r1; + if (r3) { + ptr0 = 0; + len0 = 0; + throw takeObject(r2); + } + return getStringFromWasm0(ptr0, len0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + wasm.__wbindgen_free(ptr0, len0); + } + } + /** + * @returns {any} + */ + to_js_value() { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + wasm.governanceactionid_to_js_value(retptr, this.ptr); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + if (r2) { + throw takeObject(r1); + } + return takeObject(r0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @param {string} json + * @returns {GovernanceActionId} + */ + static from_json(json) { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + const ptr0 = passStringToWasm0( + json, + wasm.__wbindgen_malloc, + wasm.__wbindgen_realloc, + ); + const len0 = WASM_VECTOR_LEN; + wasm.governanceactionid_from_json(retptr, ptr0, len0); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + if (r2) { + throw takeObject(r1); + } + return GovernanceActionId.__wrap(r0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @returns {TransactionHash} + */ + transaction_id() { + const ret = wasm.governanceactionid_transaction_id(this.ptr); + return TransactionHash.__wrap(ret); + } + /** + * @returns {BigNum} + */ + governance_action_index() { + const ret = wasm.governanceactionid_governance_action_index(this.ptr); + return BigNum.__wrap(ret); + } + /** + * @param {TransactionHash} transaction_id + * @param {BigNum} governance_action_index + * @returns {GovernanceActionId} + */ + static new(transaction_id, governance_action_index) { + _assertClass(transaction_id, TransactionHash); + _assertClass(governance_action_index, BigNum); + const ret = wasm.governanceactionid_new( + transaction_id.ptr, + governance_action_index.ptr, + ); + return GovernanceActionId.__wrap(ret); + } +} +module.exports.GovernanceActionId = GovernanceActionId; + +const HardForkInitiationActionFinalization = new FinalizationRegistry((ptr) => + wasm.__wbg_hardforkinitiationaction_free(ptr) +); +/** */ +class HardForkInitiationAction { + static __wrap(ptr) { + const obj = Object.create(HardForkInitiationAction.prototype); + obj.ptr = ptr; + HardForkInitiationActionFinalization.register(obj, obj.ptr, obj); + return obj; + } + + __destroy_into_raw() { + const ptr = this.ptr; + this.ptr = 0; + HardForkInitiationActionFinalization.unregister(this); + return ptr; + } + + free() { + const ptr = this.__destroy_into_raw(); + wasm.__wbg_hardforkinitiationaction_free(ptr); + } + /** + * @returns {Uint8Array} + */ + to_bytes() { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + wasm.hardforkinitiationaction_to_bytes(retptr, this.ptr); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var v0 = getArrayU8FromWasm0(r0, r1).slice(); + wasm.__wbindgen_free(r0, r1 * 1); + return v0; + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @param {Uint8Array} bytes + * @returns {HardForkInitiationAction} + */ + static from_bytes(bytes) { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + const ptr0 = passArray8ToWasm0(bytes, wasm.__wbindgen_malloc); + const len0 = WASM_VECTOR_LEN; + wasm.hardforkinitiationaction_from_bytes(retptr, ptr0, len0); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + if (r2) { + throw takeObject(r1); + } + return HardForkInitiationAction.__wrap(r0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @returns {string} + */ + to_json() { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + wasm.hardforkinitiationaction_to_json(retptr, this.ptr); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + var r3 = getInt32Memory0()[retptr / 4 + 3]; + var ptr0 = r0; + var len0 = r1; + if (r3) { + ptr0 = 0; + len0 = 0; + throw takeObject(r2); + } + return getStringFromWasm0(ptr0, len0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + wasm.__wbindgen_free(ptr0, len0); + } + } + /** + * @returns {any} + */ + to_js_value() { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + wasm.hardforkinitiationaction_to_js_value(retptr, this.ptr); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + if (r2) { + throw takeObject(r1); + } + return takeObject(r0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @param {string} json + * @returns {HardForkInitiationAction} + */ + static from_json(json) { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + const ptr0 = passStringToWasm0( + json, + wasm.__wbindgen_malloc, + wasm.__wbindgen_realloc, + ); + const len0 = WASM_VECTOR_LEN; + wasm.hardforkinitiationaction_from_json(retptr, ptr0, len0); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + if (r2) { + throw takeObject(r1); + } + return HardForkInitiationAction.__wrap(r0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @returns {ProtocolVersion} + */ + protocol_version() { + const ret = wasm.hardforkinitiationaction_new(this.ptr); + return ProtocolVersion.__wrap(ret); + } + /** + * @param {ProtocolVersion} protocol_version + * @returns {HardForkInitiationAction} + */ + static new(protocol_version) { + _assertClass(protocol_version, ProtocolVersion); + const ret = wasm.hardforkinitiationaction_new(protocol_version.ptr); + return HardForkInitiationAction.__wrap(ret); + } +} +module.exports.HardForkInitiationAction = HardForkInitiationAction; + +const HeaderFinalization = new FinalizationRegistry((ptr) => + wasm.__wbg_header_free(ptr) +); +/** */ +class Header { + static __wrap(ptr) { + const obj = Object.create(Header.prototype); + obj.ptr = ptr; + HeaderFinalization.register(obj, obj.ptr, obj); + return obj; + } + + __destroy_into_raw() { + const ptr = this.ptr; + this.ptr = 0; + HeaderFinalization.unregister(this); + return ptr; + } + + free() { + const ptr = this.__destroy_into_raw(); + wasm.__wbg_header_free(ptr); + } + /** + * @returns {Uint8Array} + */ + to_bytes() { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + wasm.header_to_bytes(retptr, this.ptr); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var v0 = getArrayU8FromWasm0(r0, r1).slice(); + wasm.__wbindgen_free(r0, r1 * 1); + return v0; + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @param {Uint8Array} bytes + * @returns {Header} + */ + static from_bytes(bytes) { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + const ptr0 = passArray8ToWasm0(bytes, wasm.__wbindgen_malloc); + const len0 = WASM_VECTOR_LEN; + wasm.header_from_bytes(retptr, ptr0, len0); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + if (r2) { + throw takeObject(r1); + } + return Header.__wrap(r0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @returns {string} + */ + to_json() { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + wasm.header_to_json(retptr, this.ptr); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + var r3 = getInt32Memory0()[retptr / 4 + 3]; + var ptr0 = r0; + var len0 = r1; + if (r3) { + ptr0 = 0; + len0 = 0; + throw takeObject(r2); + } + return getStringFromWasm0(ptr0, len0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + wasm.__wbindgen_free(ptr0, len0); + } + } + /** + * @returns {any} + */ + to_js_value() { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + wasm.header_to_js_value(retptr, this.ptr); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + if (r2) { + throw takeObject(r1); + } + return takeObject(r0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @param {string} json + * @returns {Header} + */ + static from_json(json) { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + const ptr0 = passStringToWasm0( + json, + wasm.__wbindgen_malloc, + wasm.__wbindgen_realloc, + ); + const len0 = WASM_VECTOR_LEN; + wasm.header_from_json(retptr, ptr0, len0); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + if (r2) { + throw takeObject(r1); + } + return Header.__wrap(r0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @returns {HeaderBody} + */ + header_body() { + const ret = wasm.header_header_body(this.ptr); + return HeaderBody.__wrap(ret); + } + /** + * @returns {KESSignature} + */ + body_signature() { + const ret = wasm.header_body_signature(this.ptr); + return KESSignature.__wrap(ret); + } + /** + * @param {HeaderBody} header_body + * @param {KESSignature} body_signature + * @returns {Header} + */ + static new(header_body, body_signature) { + _assertClass(header_body, HeaderBody); + _assertClass(body_signature, KESSignature); + const ret = wasm.header_new(header_body.ptr, body_signature.ptr); + return Header.__wrap(ret); + } +} +module.exports.Header = Header; + +const HeaderBodyFinalization = new FinalizationRegistry((ptr) => + wasm.__wbg_headerbody_free(ptr) +); +/** */ +class HeaderBody { + static __wrap(ptr) { + const obj = Object.create(HeaderBody.prototype); + obj.ptr = ptr; + HeaderBodyFinalization.register(obj, obj.ptr, obj); + return obj; + } + + __destroy_into_raw() { + const ptr = this.ptr; + this.ptr = 0; + HeaderBodyFinalization.unregister(this); + return ptr; + } + + free() { + const ptr = this.__destroy_into_raw(); + wasm.__wbg_headerbody_free(ptr); + } + /** + * @returns {Uint8Array} + */ + to_bytes() { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + wasm.headerbody_to_bytes(retptr, this.ptr); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var v0 = getArrayU8FromWasm0(r0, r1).slice(); + wasm.__wbindgen_free(r0, r1 * 1); + return v0; + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @param {Uint8Array} bytes + * @returns {HeaderBody} + */ + static from_bytes(bytes) { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + const ptr0 = passArray8ToWasm0(bytes, wasm.__wbindgen_malloc); + const len0 = WASM_VECTOR_LEN; + wasm.headerbody_from_bytes(retptr, ptr0, len0); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + if (r2) { + throw takeObject(r1); + } + return HeaderBody.__wrap(r0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @returns {string} + */ + to_json() { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + wasm.headerbody_to_json(retptr, this.ptr); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + var r3 = getInt32Memory0()[retptr / 4 + 3]; + var ptr0 = r0; + var len0 = r1; + if (r3) { + ptr0 = 0; + len0 = 0; + throw takeObject(r2); + } + return getStringFromWasm0(ptr0, len0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + wasm.__wbindgen_free(ptr0, len0); + } + } + /** + * @returns {any} + */ + to_js_value() { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + wasm.headerbody_to_js_value(retptr, this.ptr); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + if (r2) { + throw takeObject(r1); + } + return takeObject(r0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @param {string} json + * @returns {HeaderBody} + */ + static from_json(json) { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + const ptr0 = passStringToWasm0( + json, + wasm.__wbindgen_malloc, + wasm.__wbindgen_realloc, + ); + const len0 = WASM_VECTOR_LEN; + wasm.headerbody_from_json(retptr, ptr0, len0); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + if (r2) { + throw takeObject(r1); + } + return HeaderBody.__wrap(r0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @returns {number} + */ + block_number() { + const ret = wasm.headerbody_block_number(this.ptr); + return ret >>> 0; + } + /** + * @returns {BigNum} + */ + slot() { + const ret = wasm.headerbody_slot(this.ptr); + return BigNum.__wrap(ret); + } + /** + * @returns {BlockHash | undefined} + */ + prev_hash() { + const ret = wasm.headerbody_prev_hash(this.ptr); + return ret === 0 ? undefined : BlockHash.__wrap(ret); + } + /** + * @returns {Vkey} + */ + issuer_vkey() { + const ret = wasm.headerbody_issuer_vkey(this.ptr); + return Vkey.__wrap(ret); + } + /** + * @returns {VRFVKey} + */ + vrf_vkey() { + const ret = wasm.headerbody_vrf_vkey(this.ptr); + return VRFVKey.__wrap(ret); + } + /** + * @returns {VRFCert} + */ + nonce_vrf() { + const ret = wasm.headerbody_nonce_vrf(this.ptr); + return VRFCert.__wrap(ret); + } + /** + * @returns {VRFCert} + */ + leader_vrf() { + const ret = wasm.headerbody_leader_vrf(this.ptr); + return VRFCert.__wrap(ret); + } + /** + * @returns {number} + */ + block_body_size() { + const ret = wasm.headerbody_block_body_size(this.ptr); + return ret >>> 0; + } + /** + * @returns {BlockHash} + */ + block_body_hash() { + const ret = wasm.headerbody_block_body_hash(this.ptr); + return BlockHash.__wrap(ret); + } + /** + * @returns {OperationalCert} + */ + operational_cert() { + const ret = wasm.headerbody_operational_cert(this.ptr); + return OperationalCert.__wrap(ret); + } + /** + * @returns {ProtocolVersion} + */ + protocol_version() { + const ret = wasm.headerbody_protocol_version(this.ptr); + return ProtocolVersion.__wrap(ret); + } + /** + * @param {number} block_number + * @param {BigNum} slot + * @param {BlockHash | undefined} prev_hash + * @param {Vkey} issuer_vkey + * @param {VRFVKey} vrf_vkey + * @param {VRFCert} nonce_vrf + * @param {VRFCert} leader_vrf + * @param {number} block_body_size + * @param {BlockHash} block_body_hash + * @param {OperationalCert} operational_cert + * @param {ProtocolVersion} protocol_version + * @returns {HeaderBody} + */ + static new( + block_number, + slot, + prev_hash, + issuer_vkey, + vrf_vkey, + nonce_vrf, + leader_vrf, + block_body_size, + block_body_hash, + operational_cert, + protocol_version, + ) { + _assertClass(slot, BigNum); + let ptr0 = 0; + if (!isLikeNone(prev_hash)) { + _assertClass(prev_hash, BlockHash); + ptr0 = prev_hash.__destroy_into_raw(); + } + _assertClass(issuer_vkey, Vkey); + _assertClass(vrf_vkey, VRFVKey); + _assertClass(nonce_vrf, VRFCert); + _assertClass(leader_vrf, VRFCert); + _assertClass(block_body_hash, BlockHash); + _assertClass(operational_cert, OperationalCert); + _assertClass(protocol_version, ProtocolVersion); + const ret = wasm.headerbody_new( + block_number, + slot.ptr, + ptr0, + issuer_vkey.ptr, + vrf_vkey.ptr, + nonce_vrf.ptr, + leader_vrf.ptr, + block_body_size, + block_body_hash.ptr, + operational_cert.ptr, + protocol_version.ptr, + ); + return HeaderBody.__wrap(ret); + } +} +module.exports.HeaderBody = HeaderBody; + +const IntFinalization = new FinalizationRegistry((ptr) => + wasm.__wbg_int_free(ptr) +); +/** */ +class Int { + static __wrap(ptr) { + const obj = Object.create(Int.prototype); + obj.ptr = ptr; + IntFinalization.register(obj, obj.ptr, obj); + return obj; + } + + __destroy_into_raw() { + const ptr = this.ptr; + this.ptr = 0; + IntFinalization.unregister(this); + return ptr; + } + + free() { + const ptr = this.__destroy_into_raw(); + wasm.__wbg_int_free(ptr); + } + /** + * @returns {Uint8Array} + */ + to_bytes() { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + wasm.int_to_bytes(retptr, this.ptr); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var v0 = getArrayU8FromWasm0(r0, r1).slice(); + wasm.__wbindgen_free(r0, r1 * 1); + return v0; + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @param {Uint8Array} bytes + * @returns {Int} + */ + static from_bytes(bytes) { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + const ptr0 = passArray8ToWasm0(bytes, wasm.__wbindgen_malloc); + const len0 = WASM_VECTOR_LEN; + wasm.int_from_bytes(retptr, ptr0, len0); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + if (r2) { + throw takeObject(r1); + } + return Int.__wrap(r0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @param {BigNum} x + * @returns {Int} + */ + static new(x) { + _assertClass(x, BigNum); + const ret = wasm.int_new(x.ptr); + return Int.__wrap(ret); + } + /** + * @param {BigNum} x + * @returns {Int} + */ + static new_negative(x) { + _assertClass(x, BigNum); + const ret = wasm.int_new_negative(x.ptr); + return Int.__wrap(ret); + } + /** + * @param {number} x + * @returns {Int} + */ + static new_i32(x) { + const ret = wasm.int_new_i32(x); + return Int.__wrap(ret); + } + /** + * @returns {boolean} + */ + is_positive() { + const ret = wasm.int_is_positive(this.ptr); + return ret !== 0; + } + /** + * BigNum can only contain unsigned u64 values + * + * This function will return the BigNum representation + * only in case the underlying i128 value is positive. + * + * Otherwise nothing will be returned (undefined). + * @returns {BigNum | undefined} + */ + as_positive() { + const ret = wasm.int_as_positive(this.ptr); + return ret === 0 ? undefined : BigNum.__wrap(ret); + } + /** + * BigNum can only contain unsigned u64 values + * + * This function will return the *absolute* BigNum representation + * only in case the underlying i128 value is negative. + * + * Otherwise nothing will be returned (undefined). + * @returns {BigNum | undefined} + */ + as_negative() { + const ret = wasm.int_as_negative(this.ptr); + return ret === 0 ? undefined : BigNum.__wrap(ret); + } + /** + * !!! DEPRECATED !!! + * Returns an i32 value in case the underlying original i128 value is within the limits. + * Otherwise will just return an empty value (undefined). + * @returns {number | undefined} + */ + as_i32() { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + wasm.int_as_i32(retptr, this.ptr); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + return r0 === 0 ? undefined : r1; + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * Returns the underlying value converted to i32 if possible (within limits) + * Otherwise will just return an empty value (undefined). + * @returns {number | undefined} + */ + as_i32_or_nothing() { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + wasm.int_as_i32_or_nothing(retptr, this.ptr); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + return r0 === 0 ? undefined : r1; + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * Returns the underlying value converted to i32 if possible (within limits) + * JsError in case of out of boundary overflow + * @returns {number} + */ + as_i32_or_fail() { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + wasm.int_as_i32_or_fail(retptr, this.ptr); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + if (r2) { + throw takeObject(r1); + } + return r0; + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * Returns string representation of the underlying i128 value directly. + * Might contain the minus sign (-) in case of negative value. + * @returns {string} + */ + to_str() { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + wasm.int_to_str(retptr, this.ptr); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + return getStringFromWasm0(r0, r1); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + wasm.__wbindgen_free(r0, r1); + } + } + /** + * @param {string} string + * @returns {Int} + */ + static from_str(string) { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + const ptr0 = passStringToWasm0( + string, + wasm.__wbindgen_malloc, + wasm.__wbindgen_realloc, + ); + const len0 = WASM_VECTOR_LEN; + wasm.int_from_str(retptr, ptr0, len0); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + if (r2) { + throw takeObject(r1); + } + return Int.__wrap(r0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } +} +module.exports.Int = Int; + +const Ipv4Finalization = new FinalizationRegistry((ptr) => + wasm.__wbg_ipv4_free(ptr) +); +/** */ +class Ipv4 { + static __wrap(ptr) { + const obj = Object.create(Ipv4.prototype); + obj.ptr = ptr; + Ipv4Finalization.register(obj, obj.ptr, obj); + return obj; + } + + __destroy_into_raw() { + const ptr = this.ptr; + this.ptr = 0; + Ipv4Finalization.unregister(this); + return ptr; + } + + free() { + const ptr = this.__destroy_into_raw(); + wasm.__wbg_ipv4_free(ptr); + } + /** + * @returns {Uint8Array} + */ + to_bytes() { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + wasm.ipv4_to_bytes(retptr, this.ptr); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var v0 = getArrayU8FromWasm0(r0, r1).slice(); + wasm.__wbindgen_free(r0, r1 * 1); + return v0; + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @param {Uint8Array} bytes + * @returns {Ipv4} + */ + static from_bytes(bytes) { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + const ptr0 = passArray8ToWasm0(bytes, wasm.__wbindgen_malloc); + const len0 = WASM_VECTOR_LEN; + wasm.ipv4_from_bytes(retptr, ptr0, len0); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + if (r2) { + throw takeObject(r1); + } + return Ipv4.__wrap(r0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @returns {string} + */ + to_json() { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + wasm.ipv4_to_json(retptr, this.ptr); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + var r3 = getInt32Memory0()[retptr / 4 + 3]; + var ptr0 = r0; + var len0 = r1; + if (r3) { + ptr0 = 0; + len0 = 0; + throw takeObject(r2); + } + return getStringFromWasm0(ptr0, len0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + wasm.__wbindgen_free(ptr0, len0); + } + } + /** + * @returns {any} + */ + to_js_value() { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + wasm.ipv4_to_js_value(retptr, this.ptr); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + if (r2) { + throw takeObject(r1); + } + return takeObject(r0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @param {string} json + * @returns {Ipv4} + */ + static from_json(json) { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + const ptr0 = passStringToWasm0( + json, + wasm.__wbindgen_malloc, + wasm.__wbindgen_realloc, + ); + const len0 = WASM_VECTOR_LEN; + wasm.ipv4_from_json(retptr, ptr0, len0); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + if (r2) { + throw takeObject(r1); + } + return Ipv4.__wrap(r0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @param {Uint8Array} data + * @returns {Ipv4} + */ + static new(data) { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + const ptr0 = passArray8ToWasm0(data, wasm.__wbindgen_malloc); + const len0 = WASM_VECTOR_LEN; + wasm.ipv4_new(retptr, ptr0, len0); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + if (r2) { + throw takeObject(r1); + } + return Ipv4.__wrap(r0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @returns {Uint8Array} + */ + ip() { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + wasm.ipv4_ip(retptr, this.ptr); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var v0 = getArrayU8FromWasm0(r0, r1).slice(); + wasm.__wbindgen_free(r0, r1 * 1); + return v0; + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } +} +module.exports.Ipv4 = Ipv4; + +const Ipv6Finalization = new FinalizationRegistry((ptr) => + wasm.__wbg_ipv6_free(ptr) +); +/** */ +class Ipv6 { + static __wrap(ptr) { + const obj = Object.create(Ipv6.prototype); + obj.ptr = ptr; + Ipv6Finalization.register(obj, obj.ptr, obj); + return obj; + } + + __destroy_into_raw() { + const ptr = this.ptr; + this.ptr = 0; + Ipv6Finalization.unregister(this); + return ptr; + } + + free() { + const ptr = this.__destroy_into_raw(); + wasm.__wbg_ipv6_free(ptr); + } + /** + * @returns {Uint8Array} + */ + to_bytes() { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + wasm.ipv6_to_bytes(retptr, this.ptr); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var v0 = getArrayU8FromWasm0(r0, r1).slice(); + wasm.__wbindgen_free(r0, r1 * 1); + return v0; + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @param {Uint8Array} bytes + * @returns {Ipv6} + */ + static from_bytes(bytes) { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + const ptr0 = passArray8ToWasm0(bytes, wasm.__wbindgen_malloc); + const len0 = WASM_VECTOR_LEN; + wasm.ipv6_from_bytes(retptr, ptr0, len0); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + if (r2) { + throw takeObject(r1); + } + return Ipv6.__wrap(r0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @returns {string} + */ + to_json() { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + wasm.ipv6_to_json(retptr, this.ptr); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + var r3 = getInt32Memory0()[retptr / 4 + 3]; + var ptr0 = r0; + var len0 = r1; + if (r3) { + ptr0 = 0; + len0 = 0; + throw takeObject(r2); + } + return getStringFromWasm0(ptr0, len0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + wasm.__wbindgen_free(ptr0, len0); + } + } + /** + * @returns {any} + */ + to_js_value() { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + wasm.ipv6_to_js_value(retptr, this.ptr); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + if (r2) { + throw takeObject(r1); + } + return takeObject(r0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @param {string} json + * @returns {Ipv6} + */ + static from_json(json) { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + const ptr0 = passStringToWasm0( + json, + wasm.__wbindgen_malloc, + wasm.__wbindgen_realloc, + ); + const len0 = WASM_VECTOR_LEN; + wasm.ipv6_from_json(retptr, ptr0, len0); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + if (r2) { + throw takeObject(r1); + } + return Ipv6.__wrap(r0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @param {Uint8Array} data + * @returns {Ipv6} + */ + static new(data) { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + const ptr0 = passArray8ToWasm0(data, wasm.__wbindgen_malloc); + const len0 = WASM_VECTOR_LEN; + wasm.ipv6_new(retptr, ptr0, len0); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + if (r2) { + throw takeObject(r1); + } + return Ipv6.__wrap(r0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @returns {Uint8Array} + */ + ip() { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + wasm.ipv6_ip(retptr, this.ptr); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var v0 = getArrayU8FromWasm0(r0, r1).slice(); + wasm.__wbindgen_free(r0, r1 * 1); + return v0; + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } +} +module.exports.Ipv6 = Ipv6; + +const KESSignatureFinalization = new FinalizationRegistry((ptr) => + wasm.__wbg_kessignature_free(ptr) +); +/** */ +class KESSignature { + static __wrap(ptr) { + const obj = Object.create(KESSignature.prototype); + obj.ptr = ptr; + KESSignatureFinalization.register(obj, obj.ptr, obj); + return obj; + } + + __destroy_into_raw() { + const ptr = this.ptr; + this.ptr = 0; + KESSignatureFinalization.unregister(this); + return ptr; + } + + free() { + const ptr = this.__destroy_into_raw(); + wasm.__wbg_kessignature_free(ptr); + } + /** + * @returns {Uint8Array} + */ + to_bytes() { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + wasm.assetname_name(retptr, this.ptr); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var v0 = getArrayU8FromWasm0(r0, r1).slice(); + wasm.__wbindgen_free(r0, r1 * 1); + return v0; + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @param {Uint8Array} bytes + * @returns {KESSignature} + */ + static from_bytes(bytes) { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + const ptr0 = passArray8ToWasm0(bytes, wasm.__wbindgen_malloc); + const len0 = WASM_VECTOR_LEN; + wasm.kessignature_from_bytes(retptr, ptr0, len0); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + if (r2) { + throw takeObject(r1); + } + return KESSignature.__wrap(r0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } +} +module.exports.KESSignature = KESSignature; + +const KESVKeyFinalization = new FinalizationRegistry((ptr) => + wasm.__wbg_kesvkey_free(ptr) +); +/** */ +class KESVKey { + static __wrap(ptr) { + const obj = Object.create(KESVKey.prototype); + obj.ptr = ptr; + KESVKeyFinalization.register(obj, obj.ptr, obj); + return obj; + } + + __destroy_into_raw() { + const ptr = this.ptr; + this.ptr = 0; + KESVKeyFinalization.unregister(this); + return ptr; + } + + free() { + const ptr = this.__destroy_into_raw(); + wasm.__wbg_kesvkey_free(ptr); + } + /** + * @param {Uint8Array} bytes + * @returns {KESVKey} + */ + static from_bytes(bytes) { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + const ptr0 = passArray8ToWasm0(bytes, wasm.__wbindgen_malloc); + const len0 = WASM_VECTOR_LEN; + wasm.kesvkey_from_bytes(retptr, ptr0, len0); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + if (r2) { + throw takeObject(r1); + } + return KESVKey.__wrap(r0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @returns {Uint8Array} + */ + to_bytes() { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + wasm.auxiliarydatahash_to_bytes(retptr, this.ptr); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var v0 = getArrayU8FromWasm0(r0, r1).slice(); + wasm.__wbindgen_free(r0, r1 * 1); + return v0; + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @param {string} prefix + * @returns {string} + */ + to_bech32(prefix) { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + const ptr0 = passStringToWasm0( + prefix, + wasm.__wbindgen_malloc, + wasm.__wbindgen_realloc, + ); + const len0 = WASM_VECTOR_LEN; + wasm.auxiliarydatahash_to_bech32(retptr, this.ptr, ptr0, len0); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + var r3 = getInt32Memory0()[retptr / 4 + 3]; + var ptr1 = r0; + var len1 = r1; + if (r3) { + ptr1 = 0; + len1 = 0; + throw takeObject(r2); + } + return getStringFromWasm0(ptr1, len1); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + wasm.__wbindgen_free(ptr1, len1); + } + } + /** + * @param {string} bech_str + * @returns {KESVKey} + */ + static from_bech32(bech_str) { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + const ptr0 = passStringToWasm0( + bech_str, + wasm.__wbindgen_malloc, + wasm.__wbindgen_realloc, + ); + const len0 = WASM_VECTOR_LEN; + wasm.kesvkey_from_bech32(retptr, ptr0, len0); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + if (r2) { + throw takeObject(r1); + } + return KESVKey.__wrap(r0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @returns {string} + */ + to_hex() { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + wasm.auxiliarydatahash_to_hex(retptr, this.ptr); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + return getStringFromWasm0(r0, r1); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + wasm.__wbindgen_free(r0, r1); + } + } + /** + * @param {string} hex + * @returns {KESVKey} + */ + static from_hex(hex) { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + const ptr0 = passStringToWasm0( + hex, + wasm.__wbindgen_malloc, + wasm.__wbindgen_realloc, + ); + const len0 = WASM_VECTOR_LEN; + wasm.kesvkey_from_hex(retptr, ptr0, len0); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + if (r2) { + throw takeObject(r1); + } + return KESVKey.__wrap(r0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } +} +module.exports.KESVKey = KESVKey; + +const LanguageFinalization = new FinalizationRegistry((ptr) => + wasm.__wbg_language_free(ptr) +); +/** */ +class Language { + static __wrap(ptr) { + const obj = Object.create(Language.prototype); + obj.ptr = ptr; + LanguageFinalization.register(obj, obj.ptr, obj); + return obj; + } + + __destroy_into_raw() { + const ptr = this.ptr; + this.ptr = 0; + LanguageFinalization.unregister(this); + return ptr; + } + + free() { + const ptr = this.__destroy_into_raw(); + wasm.__wbg_language_free(ptr); + } + /** + * @returns {Uint8Array} + */ + to_bytes() { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + wasm.language_to_bytes(retptr, this.ptr); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var v0 = getArrayU8FromWasm0(r0, r1).slice(); + wasm.__wbindgen_free(r0, r1 * 1); + return v0; + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @param {Uint8Array} bytes + * @returns {Language} + */ + static from_bytes(bytes) { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + const ptr0 = passArray8ToWasm0(bytes, wasm.__wbindgen_malloc); + const len0 = WASM_VECTOR_LEN; + wasm.language_from_bytes(retptr, ptr0, len0); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + if (r2) { + throw takeObject(r1); + } + return Language.__wrap(r0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @returns {Language} + */ + static new_plutus_v1() { + const ret = wasm.language_new_plutus_v1(); + return Language.__wrap(ret); + } + /** + * @returns {Language} + */ + static new_plutus_v2() { + const ret = wasm.language_new_plutus_v2(); + return Language.__wrap(ret); + } + /** + * @returns {Language} + */ + static new_plutus_v3() { + const ret = wasm.language_new_plutus_v3(); + return Language.__wrap(ret); + } + /** + * @returns {number} + */ + kind() { + const ret = wasm.language_kind(this.ptr); + return ret >>> 0; + } +} +module.exports.Language = Language; + +const LanguagesFinalization = new FinalizationRegistry((ptr) => + wasm.__wbg_languages_free(ptr) +); +/** */ +class Languages { + static __wrap(ptr) { + const obj = Object.create(Languages.prototype); + obj.ptr = ptr; + LanguagesFinalization.register(obj, obj.ptr, obj); + return obj; + } + + __destroy_into_raw() { + const ptr = this.ptr; + this.ptr = 0; + LanguagesFinalization.unregister(this); + return ptr; + } + + free() { + const ptr = this.__destroy_into_raw(); + wasm.__wbg_languages_free(ptr); + } + /** + * @returns {Languages} + */ + static new() { + const ret = wasm.ed25519keyhashes_new(); + return Languages.__wrap(ret); + } + /** + * @returns {number} + */ + len() { + const ret = wasm.assetnames_len(this.ptr); + return ret >>> 0; + } + /** + * @param {number} index + * @returns {Language} + */ + get(index) { + const ret = wasm.languages_get(this.ptr, index); + return Language.__wrap(ret); + } + /** + * @param {Language} elem + */ + add(elem) { + _assertClass(elem, Language); + var ptr0 = elem.__destroy_into_raw(); + wasm.languages_add(this.ptr, ptr0); + } +} +module.exports.Languages = Languages; + +const LegacyDaedalusPrivateKeyFinalization = new FinalizationRegistry((ptr) => + wasm.__wbg_legacydaedalusprivatekey_free(ptr) +); +/** */ +class LegacyDaedalusPrivateKey { + static __wrap(ptr) { + const obj = Object.create(LegacyDaedalusPrivateKey.prototype); + obj.ptr = ptr; + LegacyDaedalusPrivateKeyFinalization.register(obj, obj.ptr, obj); + return obj; + } + + __destroy_into_raw() { + const ptr = this.ptr; + this.ptr = 0; + LegacyDaedalusPrivateKeyFinalization.unregister(this); + return ptr; + } + + free() { + const ptr = this.__destroy_into_raw(); + wasm.__wbg_legacydaedalusprivatekey_free(ptr); + } + /** + * @param {Uint8Array} bytes + * @returns {LegacyDaedalusPrivateKey} + */ + static from_bytes(bytes) { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + const ptr0 = passArray8ToWasm0(bytes, wasm.__wbindgen_malloc); + const len0 = WASM_VECTOR_LEN; + wasm.legacydaedalusprivatekey_from_bytes(retptr, ptr0, len0); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + if (r2) { + throw takeObject(r1); + } + return LegacyDaedalusPrivateKey.__wrap(r0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @returns {Uint8Array} + */ + as_bytes() { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + wasm.legacydaedalusprivatekey_as_bytes(retptr, this.ptr); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var v0 = getArrayU8FromWasm0(r0, r1).slice(); + wasm.__wbindgen_free(r0, r1 * 1); + return v0; + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @returns {Uint8Array} + */ + chaincode() { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + wasm.legacydaedalusprivatekey_chaincode(retptr, this.ptr); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var v0 = getArrayU8FromWasm0(r0, r1).slice(); + wasm.__wbindgen_free(r0, r1 * 1); + return v0; + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } +} +module.exports.LegacyDaedalusPrivateKey = LegacyDaedalusPrivateKey; + +const LinearFeeFinalization = new FinalizationRegistry((ptr) => + wasm.__wbg_linearfee_free(ptr) +); +/** */ +class LinearFee { + static __wrap(ptr) { + const obj = Object.create(LinearFee.prototype); + obj.ptr = ptr; + LinearFeeFinalization.register(obj, obj.ptr, obj); + return obj; + } + + __destroy_into_raw() { + const ptr = this.ptr; + this.ptr = 0; + LinearFeeFinalization.unregister(this); + return ptr; + } + + free() { + const ptr = this.__destroy_into_raw(); + wasm.__wbg_linearfee_free(ptr); + } + /** + * @returns {BigNum} + */ + constant() { + const ret = wasm.linearfee_constant(this.ptr); + return BigNum.__wrap(ret); + } + /** + * @returns {BigNum} + */ + coefficient() { + const ret = wasm.linearfee_coefficient(this.ptr); + return BigNum.__wrap(ret); + } + /** + * @param {BigNum} coefficient + * @param {BigNum} constant + * @returns {LinearFee} + */ + static new(coefficient, constant) { + _assertClass(coefficient, BigNum); + _assertClass(constant, BigNum); + const ret = wasm.linearfee_new(coefficient.ptr, constant.ptr); + return LinearFee.__wrap(ret); + } +} +module.exports.LinearFee = LinearFee; + +const MIRToStakeCredentialsFinalization = new FinalizationRegistry((ptr) => + wasm.__wbg_mirtostakecredentials_free(ptr) +); +/** */ +class MIRToStakeCredentials { + static __wrap(ptr) { + const obj = Object.create(MIRToStakeCredentials.prototype); + obj.ptr = ptr; + MIRToStakeCredentialsFinalization.register(obj, obj.ptr, obj); + return obj; + } + + __destroy_into_raw() { + const ptr = this.ptr; + this.ptr = 0; + MIRToStakeCredentialsFinalization.unregister(this); + return ptr; + } + + free() { + const ptr = this.__destroy_into_raw(); + wasm.__wbg_mirtostakecredentials_free(ptr); + } + /** + * @returns {Uint8Array} + */ + to_bytes() { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + wasm.mirtostakecredentials_to_bytes(retptr, this.ptr); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var v0 = getArrayU8FromWasm0(r0, r1).slice(); + wasm.__wbindgen_free(r0, r1 * 1); + return v0; + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @param {Uint8Array} bytes + * @returns {MIRToStakeCredentials} + */ + static from_bytes(bytes) { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + const ptr0 = passArray8ToWasm0(bytes, wasm.__wbindgen_malloc); + const len0 = WASM_VECTOR_LEN; + wasm.mirtostakecredentials_from_bytes(retptr, ptr0, len0); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + if (r2) { + throw takeObject(r1); + } + return MIRToStakeCredentials.__wrap(r0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @returns {string} + */ + to_json() { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + wasm.mirtostakecredentials_to_json(retptr, this.ptr); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + var r3 = getInt32Memory0()[retptr / 4 + 3]; + var ptr0 = r0; + var len0 = r1; + if (r3) { + ptr0 = 0; + len0 = 0; + throw takeObject(r2); + } + return getStringFromWasm0(ptr0, len0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + wasm.__wbindgen_free(ptr0, len0); + } + } + /** + * @returns {any} + */ + to_js_value() { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + wasm.mirtostakecredentials_to_js_value(retptr, this.ptr); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + if (r2) { + throw takeObject(r1); + } + return takeObject(r0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @param {string} json + * @returns {MIRToStakeCredentials} + */ + static from_json(json) { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + const ptr0 = passStringToWasm0( + json, + wasm.__wbindgen_malloc, + wasm.__wbindgen_realloc, + ); + const len0 = WASM_VECTOR_LEN; + wasm.mirtostakecredentials_from_json(retptr, ptr0, len0); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + if (r2) { + throw takeObject(r1); + } + return MIRToStakeCredentials.__wrap(r0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @returns {MIRToStakeCredentials} + */ + static new() { + const ret = wasm.auxiliarydataset_new(); + return MIRToStakeCredentials.__wrap(ret); + } + /** + * @returns {number} + */ + len() { + const ret = wasm.auxiliarydataset_len(this.ptr); + return ret >>> 0; + } + /** + * @param {StakeCredential} cred + * @param {Int} delta + * @returns {Int | undefined} + */ + insert(cred, delta) { + _assertClass(cred, StakeCredential); + _assertClass(delta, Int); + const ret = wasm.mirtostakecredentials_insert( + this.ptr, + cred.ptr, + delta.ptr, + ); + return ret === 0 ? undefined : Int.__wrap(ret); + } + /** + * @param {StakeCredential} cred + * @returns {Int | undefined} + */ + get(cred) { + _assertClass(cred, StakeCredential); + const ret = wasm.mirtostakecredentials_get(this.ptr, cred.ptr); + return ret === 0 ? undefined : Int.__wrap(ret); + } + /** + * @returns {StakeCredentials} + */ + keys() { + const ret = wasm.mirtostakecredentials_keys(this.ptr); + return StakeCredentials.__wrap(ret); + } +} +module.exports.MIRToStakeCredentials = MIRToStakeCredentials; + +const MetadataListFinalization = new FinalizationRegistry((ptr) => + wasm.__wbg_metadatalist_free(ptr) +); +/** */ +class MetadataList { + static __wrap(ptr) { + const obj = Object.create(MetadataList.prototype); + obj.ptr = ptr; + MetadataListFinalization.register(obj, obj.ptr, obj); + return obj; + } + + __destroy_into_raw() { + const ptr = this.ptr; + this.ptr = 0; + MetadataListFinalization.unregister(this); + return ptr; + } + + free() { + const ptr = this.__destroy_into_raw(); + wasm.__wbg_metadatalist_free(ptr); + } + /** + * @returns {Uint8Array} + */ + to_bytes() { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + wasm.metadatalist_to_bytes(retptr, this.ptr); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var v0 = getArrayU8FromWasm0(r0, r1).slice(); + wasm.__wbindgen_free(r0, r1 * 1); + return v0; + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @param {Uint8Array} bytes + * @returns {MetadataList} + */ + static from_bytes(bytes) { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + const ptr0 = passArray8ToWasm0(bytes, wasm.__wbindgen_malloc); + const len0 = WASM_VECTOR_LEN; + wasm.metadatalist_from_bytes(retptr, ptr0, len0); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + if (r2) { + throw takeObject(r1); + } + return MetadataList.__wrap(r0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @returns {MetadataList} + */ + static new() { + const ret = wasm.certificates_new(); + return MetadataList.__wrap(ret); + } + /** + * @returns {number} + */ + len() { + const ret = wasm.assetnames_len(this.ptr); + return ret >>> 0; + } + /** + * @param {number} index + * @returns {TransactionMetadatum} + */ + get(index) { + const ret = wasm.metadatalist_get(this.ptr, index); + return TransactionMetadatum.__wrap(ret); + } + /** + * @param {TransactionMetadatum} elem + */ + add(elem) { + _assertClass(elem, TransactionMetadatum); + wasm.metadatalist_add(this.ptr, elem.ptr); + } +} +module.exports.MetadataList = MetadataList; + +const MetadataMapFinalization = new FinalizationRegistry((ptr) => + wasm.__wbg_metadatamap_free(ptr) +); +/** */ +class MetadataMap { + static __wrap(ptr) { + const obj = Object.create(MetadataMap.prototype); + obj.ptr = ptr; + MetadataMapFinalization.register(obj, obj.ptr, obj); + return obj; + } + + __destroy_into_raw() { + const ptr = this.ptr; + this.ptr = 0; + MetadataMapFinalization.unregister(this); + return ptr; + } + + free() { + const ptr = this.__destroy_into_raw(); + wasm.__wbg_metadatamap_free(ptr); + } + /** + * @returns {Uint8Array} + */ + to_bytes() { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + wasm.metadatamap_to_bytes(retptr, this.ptr); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var v0 = getArrayU8FromWasm0(r0, r1).slice(); + wasm.__wbindgen_free(r0, r1 * 1); + return v0; + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @param {Uint8Array} bytes + * @returns {MetadataMap} + */ + static from_bytes(bytes) { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + const ptr0 = passArray8ToWasm0(bytes, wasm.__wbindgen_malloc); + const len0 = WASM_VECTOR_LEN; + wasm.metadatamap_from_bytes(retptr, ptr0, len0); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + if (r2) { + throw takeObject(r1); + } + return MetadataMap.__wrap(r0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @returns {MetadataMap} + */ + static new() { + const ret = wasm.auxiliarydataset_new(); + return MetadataMap.__wrap(ret); + } + /** + * @returns {number} + */ + len() { + const ret = wasm.auxiliarydataset_len(this.ptr); + return ret >>> 0; + } + /** + * @param {TransactionMetadatum} key + * @param {TransactionMetadatum} value + * @returns {TransactionMetadatum | undefined} + */ + insert(key, value) { + _assertClass(key, TransactionMetadatum); + _assertClass(value, TransactionMetadatum); + const ret = wasm.metadatamap_insert(this.ptr, key.ptr, value.ptr); + return ret === 0 ? undefined : TransactionMetadatum.__wrap(ret); + } + /** + * @param {string} key + * @param {TransactionMetadatum} value + * @returns {TransactionMetadatum | undefined} + */ + insert_str(key, value) { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + const ptr0 = passStringToWasm0( + key, + wasm.__wbindgen_malloc, + wasm.__wbindgen_realloc, + ); + const len0 = WASM_VECTOR_LEN; + _assertClass(value, TransactionMetadatum); + wasm.metadatamap_insert_str(retptr, this.ptr, ptr0, len0, value.ptr); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + if (r2) { + throw takeObject(r1); + } + return r0 === 0 ? undefined : TransactionMetadatum.__wrap(r0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @param {number} key + * @param {TransactionMetadatum} value + * @returns {TransactionMetadatum | undefined} + */ + insert_i32(key, value) { + _assertClass(value, TransactionMetadatum); + const ret = wasm.metadatamap_insert_i32(this.ptr, key, value.ptr); + return ret === 0 ? undefined : TransactionMetadatum.__wrap(ret); + } + /** + * @param {TransactionMetadatum} key + * @returns {TransactionMetadatum} + */ + get(key) { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + _assertClass(key, TransactionMetadatum); + wasm.metadatamap_get(retptr, this.ptr, key.ptr); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + if (r2) { + throw takeObject(r1); + } + return TransactionMetadatum.__wrap(r0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @param {string} key + * @returns {TransactionMetadatum} + */ + get_str(key) { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + const ptr0 = passStringToWasm0( + key, + wasm.__wbindgen_malloc, + wasm.__wbindgen_realloc, + ); + const len0 = WASM_VECTOR_LEN; + wasm.metadatamap_get_str(retptr, this.ptr, ptr0, len0); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + if (r2) { + throw takeObject(r1); + } + return TransactionMetadatum.__wrap(r0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @param {number} key + * @returns {TransactionMetadatum} + */ + get_i32(key) { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + wasm.metadatamap_get_i32(retptr, this.ptr, key); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + if (r2) { + throw takeObject(r1); + } + return TransactionMetadatum.__wrap(r0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @param {TransactionMetadatum} key + * @returns {boolean} + */ + has(key) { + _assertClass(key, TransactionMetadatum); + const ret = wasm.metadatamap_has(this.ptr, key.ptr); + return ret !== 0; + } + /** + * @returns {MetadataList} + */ + keys() { + const ret = wasm.metadatamap_keys(this.ptr); + return MetadataList.__wrap(ret); + } +} +module.exports.MetadataMap = MetadataMap; + +const MintFinalization = new FinalizationRegistry((ptr) => + wasm.__wbg_mint_free(ptr) +); +/** */ +class Mint { + static __wrap(ptr) { + const obj = Object.create(Mint.prototype); + obj.ptr = ptr; + MintFinalization.register(obj, obj.ptr, obj); + return obj; + } + + __destroy_into_raw() { + const ptr = this.ptr; + this.ptr = 0; + MintFinalization.unregister(this); + return ptr; + } + + free() { + const ptr = this.__destroy_into_raw(); + wasm.__wbg_mint_free(ptr); + } + /** + * @returns {Uint8Array} + */ + to_bytes() { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + wasm.mint_to_bytes(retptr, this.ptr); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var v0 = getArrayU8FromWasm0(r0, r1).slice(); + wasm.__wbindgen_free(r0, r1 * 1); + return v0; + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @param {Uint8Array} bytes + * @returns {Mint} + */ + static from_bytes(bytes) { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + const ptr0 = passArray8ToWasm0(bytes, wasm.__wbindgen_malloc); + const len0 = WASM_VECTOR_LEN; + wasm.mint_from_bytes(retptr, ptr0, len0); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + if (r2) { + throw takeObject(r1); + } + return Mint.__wrap(r0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @returns {string} + */ + to_json() { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + wasm.mint_to_json(retptr, this.ptr); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + var r3 = getInt32Memory0()[retptr / 4 + 3]; + var ptr0 = r0; + var len0 = r1; + if (r3) { + ptr0 = 0; + len0 = 0; + throw takeObject(r2); + } + return getStringFromWasm0(ptr0, len0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + wasm.__wbindgen_free(ptr0, len0); + } + } + /** + * @returns {any} + */ + to_js_value() { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + wasm.mint_to_js_value(retptr, this.ptr); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + if (r2) { + throw takeObject(r1); + } + return takeObject(r0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @param {string} json + * @returns {Mint} + */ + static from_json(json) { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + const ptr0 = passStringToWasm0( + json, + wasm.__wbindgen_malloc, + wasm.__wbindgen_realloc, + ); + const len0 = WASM_VECTOR_LEN; + wasm.mint_from_json(retptr, ptr0, len0); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + if (r2) { + throw takeObject(r1); + } + return Mint.__wrap(r0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @returns {Mint} + */ + static new() { + const ret = wasm.assets_new(); + return Mint.__wrap(ret); + } + /** + * @param {ScriptHash} key + * @param {MintAssets} value + * @returns {Mint} + */ + static new_from_entry(key, value) { + _assertClass(key, ScriptHash); + _assertClass(value, MintAssets); + const ret = wasm.mint_new_from_entry(key.ptr, value.ptr); + return Mint.__wrap(ret); + } + /** + * @returns {number} + */ + len() { + const ret = wasm.assetnames_len(this.ptr); + return ret >>> 0; + } + /** + * @param {ScriptHash} key + * @param {MintAssets} value + * @returns {MintAssets | undefined} + */ + insert(key, value) { + _assertClass(key, ScriptHash); + _assertClass(value, MintAssets); + const ret = wasm.mint_insert(this.ptr, key.ptr, value.ptr); + return ret === 0 ? undefined : MintAssets.__wrap(ret); + } + /** + * @param {ScriptHash} key + * @returns {MintAssets | undefined} + */ + get(key) { + _assertClass(key, ScriptHash); + const ret = wasm.mint_get(this.ptr, key.ptr); + return ret === 0 ? undefined : MintAssets.__wrap(ret); + } + /** + * @returns {ScriptHashes} + */ + keys() { + const ret = wasm.mint_keys(this.ptr); + return ScriptHashes.__wrap(ret); + } + /** + * Returns the multiasset where only positive (minting) entries are present + * @returns {MultiAsset} + */ + as_positive_multiasset() { + const ret = wasm.mint_as_positive_multiasset(this.ptr); + return MultiAsset.__wrap(ret); + } + /** + * Returns the multiasset where only negative (burning) entries are present + * @returns {MultiAsset} + */ + as_negative_multiasset() { + const ret = wasm.mint_as_negative_multiasset(this.ptr); + return MultiAsset.__wrap(ret); + } +} +module.exports.Mint = Mint; + +const MintAssetsFinalization = new FinalizationRegistry((ptr) => + wasm.__wbg_mintassets_free(ptr) +); +/** */ +class MintAssets { + static __wrap(ptr) { + const obj = Object.create(MintAssets.prototype); + obj.ptr = ptr; + MintAssetsFinalization.register(obj, obj.ptr, obj); + return obj; + } + + __destroy_into_raw() { + const ptr = this.ptr; + this.ptr = 0; + MintAssetsFinalization.unregister(this); + return ptr; + } + + free() { + const ptr = this.__destroy_into_raw(); + wasm.__wbg_mintassets_free(ptr); + } + /** + * @returns {MintAssets} + */ + static new() { + const ret = wasm.assets_new(); + return MintAssets.__wrap(ret); + } + /** + * @param {AssetName} key + * @param {Int} value + * @returns {MintAssets} + */ + static new_from_entry(key, value) { + _assertClass(key, AssetName); + _assertClass(value, Int); + var ptr0 = value.__destroy_into_raw(); + const ret = wasm.mintassets_new_from_entry(key.ptr, ptr0); + return MintAssets.__wrap(ret); + } + /** + * @returns {number} + */ + len() { + const ret = wasm.assetnames_len(this.ptr); + return ret >>> 0; + } + /** + * @param {AssetName} key + * @param {Int} value + * @returns {Int | undefined} + */ + insert(key, value) { + _assertClass(key, AssetName); + _assertClass(value, Int); + var ptr0 = value.__destroy_into_raw(); + const ret = wasm.mintassets_insert(this.ptr, key.ptr, ptr0); + return ret === 0 ? undefined : Int.__wrap(ret); + } + /** + * @param {AssetName} key + * @returns {Int | undefined} + */ + get(key) { + _assertClass(key, AssetName); + const ret = wasm.mintassets_get(this.ptr, key.ptr); + return ret === 0 ? undefined : Int.__wrap(ret); + } + /** + * @returns {AssetNames} + */ + keys() { + const ret = wasm.mintassets_keys(this.ptr); + return AssetNames.__wrap(ret); + } +} +module.exports.MintAssets = MintAssets; + +const MoveInstantaneousRewardFinalization = new FinalizationRegistry((ptr) => + wasm.__wbg_moveinstantaneousreward_free(ptr) +); +/** */ +class MoveInstantaneousReward { + static __wrap(ptr) { + const obj = Object.create(MoveInstantaneousReward.prototype); + obj.ptr = ptr; + MoveInstantaneousRewardFinalization.register(obj, obj.ptr, obj); + return obj; + } + + __destroy_into_raw() { + const ptr = this.ptr; + this.ptr = 0; + MoveInstantaneousRewardFinalization.unregister(this); + return ptr; + } + + free() { + const ptr = this.__destroy_into_raw(); + wasm.__wbg_moveinstantaneousreward_free(ptr); + } + /** + * @returns {Uint8Array} + */ + to_bytes() { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + wasm.moveinstantaneousreward_to_bytes(retptr, this.ptr); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var v0 = getArrayU8FromWasm0(r0, r1).slice(); + wasm.__wbindgen_free(r0, r1 * 1); + return v0; + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @param {Uint8Array} bytes + * @returns {MoveInstantaneousReward} + */ + static from_bytes(bytes) { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + const ptr0 = passArray8ToWasm0(bytes, wasm.__wbindgen_malloc); + const len0 = WASM_VECTOR_LEN; + wasm.moveinstantaneousreward_from_bytes(retptr, ptr0, len0); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + if (r2) { + throw takeObject(r1); + } + return MoveInstantaneousReward.__wrap(r0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @returns {string} + */ + to_json() { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + wasm.moveinstantaneousreward_to_json(retptr, this.ptr); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + var r3 = getInt32Memory0()[retptr / 4 + 3]; + var ptr0 = r0; + var len0 = r1; + if (r3) { + ptr0 = 0; + len0 = 0; + throw takeObject(r2); + } + return getStringFromWasm0(ptr0, len0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + wasm.__wbindgen_free(ptr0, len0); + } + } + /** + * @returns {any} + */ + to_js_value() { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + wasm.moveinstantaneousreward_to_js_value(retptr, this.ptr); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + if (r2) { + throw takeObject(r1); + } + return takeObject(r0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @param {string} json + * @returns {MoveInstantaneousReward} + */ + static from_json(json) { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + const ptr0 = passStringToWasm0( + json, + wasm.__wbindgen_malloc, + wasm.__wbindgen_realloc, + ); + const len0 = WASM_VECTOR_LEN; + wasm.moveinstantaneousreward_from_json(retptr, ptr0, len0); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + if (r2) { + throw takeObject(r1); + } + return MoveInstantaneousReward.__wrap(r0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @param {number} pot + * @param {BigNum} amount + * @returns {MoveInstantaneousReward} + */ + static new_to_other_pot(pot, amount) { + _assertClass(amount, BigNum); + const ret = wasm.moveinstantaneousreward_new_to_other_pot(pot, amount.ptr); + return MoveInstantaneousReward.__wrap(ret); + } + /** + * @param {number} pot + * @param {MIRToStakeCredentials} amounts + * @returns {MoveInstantaneousReward} + */ + static new_to_stake_creds(pot, amounts) { + _assertClass(amounts, MIRToStakeCredentials); + const ret = wasm.moveinstantaneousreward_new_to_stake_creds( + pot, + amounts.ptr, + ); + return MoveInstantaneousReward.__wrap(ret); + } + /** + * @returns {number} + */ + pot() { + const ret = wasm.moveinstantaneousreward_pot(this.ptr); + return ret >>> 0; + } + /** + * @returns {number} + */ + kind() { + const ret = wasm.moveinstantaneousreward_kind(this.ptr); + return ret >>> 0; + } + /** + * @returns {BigNum | undefined} + */ + as_to_other_pot() { + const ret = wasm.moveinstantaneousreward_as_to_other_pot(this.ptr); + return ret === 0 ? undefined : BigNum.__wrap(ret); + } + /** + * @returns {MIRToStakeCredentials | undefined} + */ + as_to_stake_creds() { + const ret = wasm.moveinstantaneousreward_as_to_stake_creds(this.ptr); + return ret === 0 ? undefined : MIRToStakeCredentials.__wrap(ret); + } +} +module.exports.MoveInstantaneousReward = MoveInstantaneousReward; + +const MoveInstantaneousRewardsCertFinalization = new FinalizationRegistry( + (ptr) => wasm.__wbg_moveinstantaneousrewardscert_free(ptr) +); +/** */ +class MoveInstantaneousRewardsCert { + static __wrap(ptr) { + const obj = Object.create(MoveInstantaneousRewardsCert.prototype); + obj.ptr = ptr; + MoveInstantaneousRewardsCertFinalization.register(obj, obj.ptr, obj); + return obj; + } + + __destroy_into_raw() { + const ptr = this.ptr; + this.ptr = 0; + MoveInstantaneousRewardsCertFinalization.unregister(this); + return ptr; + } + + free() { + const ptr = this.__destroy_into_raw(); + wasm.__wbg_moveinstantaneousrewardscert_free(ptr); + } + /** + * @returns {Uint8Array} + */ + to_bytes() { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + wasm.moveinstantaneousrewardscert_to_bytes(retptr, this.ptr); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var v0 = getArrayU8FromWasm0(r0, r1).slice(); + wasm.__wbindgen_free(r0, r1 * 1); + return v0; + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @param {Uint8Array} bytes + * @returns {MoveInstantaneousRewardsCert} + */ + static from_bytes(bytes) { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + const ptr0 = passArray8ToWasm0(bytes, wasm.__wbindgen_malloc); + const len0 = WASM_VECTOR_LEN; + wasm.moveinstantaneousrewardscert_from_bytes(retptr, ptr0, len0); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + if (r2) { + throw takeObject(r1); + } + return MoveInstantaneousRewardsCert.__wrap(r0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @returns {string} + */ + to_json() { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + wasm.moveinstantaneousrewardscert_to_json(retptr, this.ptr); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + var r3 = getInt32Memory0()[retptr / 4 + 3]; + var ptr0 = r0; + var len0 = r1; + if (r3) { + ptr0 = 0; + len0 = 0; + throw takeObject(r2); + } + return getStringFromWasm0(ptr0, len0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + wasm.__wbindgen_free(ptr0, len0); + } + } + /** + * @returns {any} + */ + to_js_value() { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + wasm.moveinstantaneousrewardscert_to_js_value(retptr, this.ptr); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + if (r2) { + throw takeObject(r1); + } + return takeObject(r0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @param {string} json + * @returns {MoveInstantaneousRewardsCert} + */ + static from_json(json) { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + const ptr0 = passStringToWasm0( + json, + wasm.__wbindgen_malloc, + wasm.__wbindgen_realloc, + ); + const len0 = WASM_VECTOR_LEN; + wasm.moveinstantaneousrewardscert_from_json(retptr, ptr0, len0); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + if (r2) { + throw takeObject(r1); + } + return MoveInstantaneousRewardsCert.__wrap(r0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @returns {MoveInstantaneousReward} + */ + move_instantaneous_reward() { + const ret = wasm.moveinstantaneousrewardscert_move_instantaneous_reward( + this.ptr, + ); + return MoveInstantaneousReward.__wrap(ret); + } + /** + * @param {MoveInstantaneousReward} move_instantaneous_reward + * @returns {MoveInstantaneousRewardsCert} + */ + static new(move_instantaneous_reward) { + _assertClass(move_instantaneous_reward, MoveInstantaneousReward); + const ret = wasm.moveinstantaneousrewardscert_new( + move_instantaneous_reward.ptr, + ); + return MoveInstantaneousRewardsCert.__wrap(ret); + } +} +module.exports.MoveInstantaneousRewardsCert = MoveInstantaneousRewardsCert; + +const MultiAssetFinalization = new FinalizationRegistry((ptr) => + wasm.__wbg_multiasset_free(ptr) +); +/** */ +class MultiAsset { + static __wrap(ptr) { + const obj = Object.create(MultiAsset.prototype); + obj.ptr = ptr; + MultiAssetFinalization.register(obj, obj.ptr, obj); + return obj; + } + + __destroy_into_raw() { + const ptr = this.ptr; + this.ptr = 0; + MultiAssetFinalization.unregister(this); + return ptr; + } + + free() { + const ptr = this.__destroy_into_raw(); + wasm.__wbg_multiasset_free(ptr); + } + /** + * @returns {Uint8Array} + */ + to_bytes() { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + wasm.multiasset_to_bytes(retptr, this.ptr); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var v0 = getArrayU8FromWasm0(r0, r1).slice(); + wasm.__wbindgen_free(r0, r1 * 1); + return v0; + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @param {Uint8Array} bytes + * @returns {MultiAsset} + */ + static from_bytes(bytes) { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + const ptr0 = passArray8ToWasm0(bytes, wasm.__wbindgen_malloc); + const len0 = WASM_VECTOR_LEN; + wasm.multiasset_from_bytes(retptr, ptr0, len0); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + if (r2) { + throw takeObject(r1); + } + return MultiAsset.__wrap(r0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @returns {string} + */ + to_json() { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + wasm.multiasset_to_json(retptr, this.ptr); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + var r3 = getInt32Memory0()[retptr / 4 + 3]; + var ptr0 = r0; + var len0 = r1; + if (r3) { + ptr0 = 0; + len0 = 0; + throw takeObject(r2); + } + return getStringFromWasm0(ptr0, len0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + wasm.__wbindgen_free(ptr0, len0); + } + } + /** + * @returns {any} + */ + to_js_value() { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + wasm.multiasset_to_js_value(retptr, this.ptr); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + if (r2) { + throw takeObject(r1); + } + return takeObject(r0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @param {string} json + * @returns {MultiAsset} + */ + static from_json(json) { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + const ptr0 = passStringToWasm0( + json, + wasm.__wbindgen_malloc, + wasm.__wbindgen_realloc, + ); + const len0 = WASM_VECTOR_LEN; + wasm.multiasset_from_json(retptr, ptr0, len0); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + if (r2) { + throw takeObject(r1); + } + return MultiAsset.__wrap(r0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @returns {MultiAsset} + */ + static new() { + const ret = wasm.assets_new(); + return MultiAsset.__wrap(ret); + } + /** + * the number of unique policy IDs in the multiasset + * @returns {number} + */ + len() { + const ret = wasm.assetnames_len(this.ptr); + return ret >>> 0; + } + /** + * set (and replace if it exists) all assets with policy {policy_id} to a copy of {assets} + * @param {ScriptHash} policy_id + * @param {Assets} assets + * @returns {Assets | undefined} + */ + insert(policy_id, assets) { + _assertClass(policy_id, ScriptHash); + _assertClass(assets, Assets); + const ret = wasm.multiasset_insert(this.ptr, policy_id.ptr, assets.ptr); + return ret === 0 ? undefined : Assets.__wrap(ret); + } + /** + * all assets under {policy_id}, if any exist, or else None (undefined in JS) + * @param {ScriptHash} policy_id + * @returns {Assets | undefined} + */ + get(policy_id) { + _assertClass(policy_id, ScriptHash); + const ret = wasm.multiasset_get(this.ptr, policy_id.ptr); + return ret === 0 ? undefined : Assets.__wrap(ret); + } + /** + * sets the asset {asset_name} to {value} under policy {policy_id} + * returns the previous amount if it was set, or else None (undefined in JS) + * @param {ScriptHash} policy_id + * @param {AssetName} asset_name + * @param {BigNum} value + * @returns {BigNum | undefined} + */ + set_asset(policy_id, asset_name, value) { + _assertClass(policy_id, ScriptHash); + _assertClass(asset_name, AssetName); + _assertClass(value, BigNum); + var ptr0 = value.__destroy_into_raw(); + const ret = wasm.multiasset_set_asset( + this.ptr, + policy_id.ptr, + asset_name.ptr, + ptr0, + ); + return ret === 0 ? undefined : BigNum.__wrap(ret); + } + /** + * returns the amount of asset {asset_name} under policy {policy_id} + * If such an asset does not exist, 0 is returned. + * @param {ScriptHash} policy_id + * @param {AssetName} asset_name + * @returns {BigNum} + */ + get_asset(policy_id, asset_name) { + _assertClass(policy_id, ScriptHash); + _assertClass(asset_name, AssetName); + const ret = wasm.multiasset_get_asset( + this.ptr, + policy_id.ptr, + asset_name.ptr, + ); + return BigNum.__wrap(ret); + } + /** + * returns all policy IDs used by assets in this multiasset + * @returns {ScriptHashes} + */ + keys() { + const ret = wasm.mint_keys(this.ptr); + return ScriptHashes.__wrap(ret); + } + /** + * removes an asset from the list if the result is 0 or less + * does not modify this object, instead the result is returned + * @param {MultiAsset} rhs_ma + * @returns {MultiAsset} + */ + sub(rhs_ma) { + _assertClass(rhs_ma, MultiAsset); + const ret = wasm.multiasset_sub(this.ptr, rhs_ma.ptr); + return MultiAsset.__wrap(ret); + } +} +module.exports.MultiAsset = MultiAsset; + +const MultiHostNameFinalization = new FinalizationRegistry((ptr) => + wasm.__wbg_multihostname_free(ptr) +); +/** */ +class MultiHostName { + static __wrap(ptr) { + const obj = Object.create(MultiHostName.prototype); + obj.ptr = ptr; + MultiHostNameFinalization.register(obj, obj.ptr, obj); + return obj; + } + + __destroy_into_raw() { + const ptr = this.ptr; + this.ptr = 0; + MultiHostNameFinalization.unregister(this); + return ptr; + } + + free() { + const ptr = this.__destroy_into_raw(); + wasm.__wbg_multihostname_free(ptr); + } + /** + * @returns {Uint8Array} + */ + to_bytes() { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + wasm.multihostname_to_bytes(retptr, this.ptr); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var v0 = getArrayU8FromWasm0(r0, r1).slice(); + wasm.__wbindgen_free(r0, r1 * 1); + return v0; + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @param {Uint8Array} bytes + * @returns {MultiHostName} + */ + static from_bytes(bytes) { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + const ptr0 = passArray8ToWasm0(bytes, wasm.__wbindgen_malloc); + const len0 = WASM_VECTOR_LEN; + wasm.multihostname_from_bytes(retptr, ptr0, len0); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + if (r2) { + throw takeObject(r1); + } + return MultiHostName.__wrap(r0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @returns {string} + */ + to_json() { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + wasm.multihostname_to_json(retptr, this.ptr); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + var r3 = getInt32Memory0()[retptr / 4 + 3]; + var ptr0 = r0; + var len0 = r1; + if (r3) { + ptr0 = 0; + len0 = 0; + throw takeObject(r2); + } + return getStringFromWasm0(ptr0, len0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + wasm.__wbindgen_free(ptr0, len0); + } + } + /** + * @returns {any} + */ + to_js_value() { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + wasm.multihostname_to_js_value(retptr, this.ptr); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + if (r2) { + throw takeObject(r1); + } + return takeObject(r0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @param {string} json + * @returns {MultiHostName} + */ + static from_json(json) { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + const ptr0 = passStringToWasm0( + json, + wasm.__wbindgen_malloc, + wasm.__wbindgen_realloc, + ); + const len0 = WASM_VECTOR_LEN; + wasm.multihostname_from_json(retptr, ptr0, len0); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + if (r2) { + throw takeObject(r1); + } + return MultiHostName.__wrap(r0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @returns {DNSRecordSRV} + */ + dns_name() { + const ret = wasm.anchor_anchor_url(this.ptr); + return DNSRecordSRV.__wrap(ret); + } + /** + * @param {DNSRecordSRV} dns_name + * @returns {MultiHostName} + */ + static new(dns_name) { + _assertClass(dns_name, DNSRecordSRV); + const ret = wasm.multihostname_new(dns_name.ptr); + return MultiHostName.__wrap(ret); + } +} +module.exports.MultiHostName = MultiHostName; + +const NativeScriptFinalization = new FinalizationRegistry((ptr) => + wasm.__wbg_nativescript_free(ptr) +); +/** */ +class NativeScript { + static __wrap(ptr) { + const obj = Object.create(NativeScript.prototype); + obj.ptr = ptr; + NativeScriptFinalization.register(obj, obj.ptr, obj); + return obj; + } + + __destroy_into_raw() { + const ptr = this.ptr; + this.ptr = 0; + NativeScriptFinalization.unregister(this); + return ptr; + } + + free() { + const ptr = this.__destroy_into_raw(); + wasm.__wbg_nativescript_free(ptr); + } + /** + * @returns {Uint8Array} + */ + to_bytes() { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + wasm.nativescript_to_bytes(retptr, this.ptr); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var v0 = getArrayU8FromWasm0(r0, r1).slice(); + wasm.__wbindgen_free(r0, r1 * 1); + return v0; + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @param {Uint8Array} bytes + * @returns {NativeScript} + */ + static from_bytes(bytes) { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + const ptr0 = passArray8ToWasm0(bytes, wasm.__wbindgen_malloc); + const len0 = WASM_VECTOR_LEN; + wasm.nativescript_from_bytes(retptr, ptr0, len0); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + if (r2) { + throw takeObject(r1); + } + return NativeScript.__wrap(r0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @returns {string} + */ + to_json() { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + wasm.nativescript_to_json(retptr, this.ptr); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + var r3 = getInt32Memory0()[retptr / 4 + 3]; + var ptr0 = r0; + var len0 = r1; + if (r3) { + ptr0 = 0; + len0 = 0; + throw takeObject(r2); + } + return getStringFromWasm0(ptr0, len0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + wasm.__wbindgen_free(ptr0, len0); + } + } + /** + * @returns {any} + */ + to_js_value() { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + wasm.nativescript_to_js_value(retptr, this.ptr); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + if (r2) { + throw takeObject(r1); + } + return takeObject(r0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @param {string} json + * @returns {NativeScript} + */ + static from_json(json) { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + const ptr0 = passStringToWasm0( + json, + wasm.__wbindgen_malloc, + wasm.__wbindgen_realloc, + ); + const len0 = WASM_VECTOR_LEN; + wasm.nativescript_from_json(retptr, ptr0, len0); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + if (r2) { + throw takeObject(r1); + } + return NativeScript.__wrap(r0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @param {number} namespace + * @returns {ScriptHash} + */ + hash(namespace) { + const ret = wasm.nativescript_hash(this.ptr, namespace); + return ScriptHash.__wrap(ret); + } + /** + * @param {ScriptPubkey} script_pubkey + * @returns {NativeScript} + */ + static new_script_pubkey(script_pubkey) { + _assertClass(script_pubkey, ScriptPubkey); + const ret = wasm.nativescript_new_script_pubkey(script_pubkey.ptr); + return NativeScript.__wrap(ret); + } + /** + * @param {ScriptAll} script_all + * @returns {NativeScript} + */ + static new_script_all(script_all) { + _assertClass(script_all, ScriptAll); + const ret = wasm.nativescript_new_script_all(script_all.ptr); + return NativeScript.__wrap(ret); + } + /** + * @param {ScriptAny} script_any + * @returns {NativeScript} + */ + static new_script_any(script_any) { + _assertClass(script_any, ScriptAny); + const ret = wasm.nativescript_new_script_any(script_any.ptr); + return NativeScript.__wrap(ret); + } + /** + * @param {ScriptNOfK} script_n_of_k + * @returns {NativeScript} + */ + static new_script_n_of_k(script_n_of_k) { + _assertClass(script_n_of_k, ScriptNOfK); + const ret = wasm.nativescript_new_script_n_of_k(script_n_of_k.ptr); + return NativeScript.__wrap(ret); + } + /** + * @param {TimelockStart} timelock_start + * @returns {NativeScript} + */ + static new_timelock_start(timelock_start) { + _assertClass(timelock_start, TimelockStart); + const ret = wasm.nativescript_new_timelock_start(timelock_start.ptr); + return NativeScript.__wrap(ret); + } + /** + * @param {TimelockExpiry} timelock_expiry + * @returns {NativeScript} + */ + static new_timelock_expiry(timelock_expiry) { + _assertClass(timelock_expiry, TimelockExpiry); + const ret = wasm.nativescript_new_timelock_expiry(timelock_expiry.ptr); + return NativeScript.__wrap(ret); + } + /** + * @returns {number} + */ + kind() { + const ret = wasm.nativescript_kind(this.ptr); + return ret >>> 0; + } + /** + * @returns {ScriptPubkey | undefined} + */ + as_script_pubkey() { + const ret = wasm.nativescript_as_script_pubkey(this.ptr); + return ret === 0 ? undefined : ScriptPubkey.__wrap(ret); + } + /** + * @returns {ScriptAll | undefined} + */ + as_script_all() { + const ret = wasm.nativescript_as_script_all(this.ptr); + return ret === 0 ? undefined : ScriptAll.__wrap(ret); + } + /** + * @returns {ScriptAny | undefined} + */ + as_script_any() { + const ret = wasm.nativescript_as_script_any(this.ptr); + return ret === 0 ? undefined : ScriptAny.__wrap(ret); + } + /** + * @returns {ScriptNOfK | undefined} + */ + as_script_n_of_k() { + const ret = wasm.nativescript_as_script_n_of_k(this.ptr); + return ret === 0 ? undefined : ScriptNOfK.__wrap(ret); + } + /** + * @returns {TimelockStart | undefined} + */ + as_timelock_start() { + const ret = wasm.nativescript_as_timelock_start(this.ptr); + return ret === 0 ? undefined : TimelockStart.__wrap(ret); + } + /** + * @returns {TimelockExpiry | undefined} + */ + as_timelock_expiry() { + const ret = wasm.nativescript_as_timelock_expiry(this.ptr); + return ret === 0 ? undefined : TimelockExpiry.__wrap(ret); + } + /** + * Returns an array of unique Ed25519KeyHashes + * contained within this script recursively on any depth level. + * The order of the keys in the result is not determined in any way. + * @returns {Ed25519KeyHashes} + */ + get_required_signers() { + const ret = wasm.nativescript_get_required_signers(this.ptr); + return Ed25519KeyHashes.__wrap(ret); + } + /** + * @param {BigNum | undefined} lower_bound + * @param {BigNum | undefined} upper_bound + * @param {Ed25519KeyHashes} key_hashes + * @returns {boolean} + */ + verify(lower_bound, upper_bound, key_hashes) { + let ptr0 = 0; + if (!isLikeNone(lower_bound)) { + _assertClass(lower_bound, BigNum); + ptr0 = lower_bound.__destroy_into_raw(); + } + let ptr1 = 0; + if (!isLikeNone(upper_bound)) { + _assertClass(upper_bound, BigNum); + ptr1 = upper_bound.__destroy_into_raw(); + } + _assertClass(key_hashes, Ed25519KeyHashes); + const ret = wasm.nativescript_verify(this.ptr, ptr0, ptr1, key_hashes.ptr); + return ret !== 0; + } +} +module.exports.NativeScript = NativeScript; + +const NativeScriptsFinalization = new FinalizationRegistry((ptr) => + wasm.__wbg_nativescripts_free(ptr) +); +/** */ +class NativeScripts { + static __wrap(ptr) { + const obj = Object.create(NativeScripts.prototype); + obj.ptr = ptr; + NativeScriptsFinalization.register(obj, obj.ptr, obj); + return obj; + } + + __destroy_into_raw() { + const ptr = this.ptr; + this.ptr = 0; + NativeScriptsFinalization.unregister(this); + return ptr; + } + + free() { + const ptr = this.__destroy_into_raw(); + wasm.__wbg_nativescripts_free(ptr); + } + /** + * @returns {NativeScripts} + */ + static new() { + const ret = wasm.certificates_new(); + return NativeScripts.__wrap(ret); + } + /** + * @returns {number} + */ + len() { + const ret = wasm.assetnames_len(this.ptr); + return ret >>> 0; + } + /** + * @param {number} index + * @returns {NativeScript} + */ + get(index) { + const ret = wasm.nativescripts_get(this.ptr, index); + return NativeScript.__wrap(ret); + } + /** + * @param {NativeScript} elem + */ + add(elem) { + _assertClass(elem, NativeScript); + wasm.nativescripts_add(this.ptr, elem.ptr); + } +} +module.exports.NativeScripts = NativeScripts; + +const NetworkIdFinalization = new FinalizationRegistry((ptr) => + wasm.__wbg_networkid_free(ptr) +); +/** */ +class NetworkId { + static __wrap(ptr) { + const obj = Object.create(NetworkId.prototype); + obj.ptr = ptr; + NetworkIdFinalization.register(obj, obj.ptr, obj); + return obj; + } + + __destroy_into_raw() { + const ptr = this.ptr; + this.ptr = 0; + NetworkIdFinalization.unregister(this); + return ptr; + } + + free() { + const ptr = this.__destroy_into_raw(); + wasm.__wbg_networkid_free(ptr); + } + /** + * @returns {Uint8Array} + */ + to_bytes() { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + wasm.networkid_to_bytes(retptr, this.ptr); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var v0 = getArrayU8FromWasm0(r0, r1).slice(); + wasm.__wbindgen_free(r0, r1 * 1); + return v0; + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @param {Uint8Array} bytes + * @returns {NetworkId} + */ + static from_bytes(bytes) { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + const ptr0 = passArray8ToWasm0(bytes, wasm.__wbindgen_malloc); + const len0 = WASM_VECTOR_LEN; + wasm.networkid_from_bytes(retptr, ptr0, len0); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + if (r2) { + throw takeObject(r1); + } + return NetworkId.__wrap(r0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @returns {string} + */ + to_json() { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + wasm.networkid_to_json(retptr, this.ptr); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + var r3 = getInt32Memory0()[retptr / 4 + 3]; + var ptr0 = r0; + var len0 = r1; + if (r3) { + ptr0 = 0; + len0 = 0; + throw takeObject(r2); + } + return getStringFromWasm0(ptr0, len0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + wasm.__wbindgen_free(ptr0, len0); + } + } + /** + * @returns {any} + */ + to_js_value() { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + wasm.networkid_to_js_value(retptr, this.ptr); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + if (r2) { + throw takeObject(r1); + } + return takeObject(r0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @param {string} json + * @returns {NetworkId} + */ + static from_json(json) { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + const ptr0 = passStringToWasm0( + json, + wasm.__wbindgen_malloc, + wasm.__wbindgen_realloc, + ); + const len0 = WASM_VECTOR_LEN; + wasm.networkid_from_json(retptr, ptr0, len0); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + if (r2) { + throw takeObject(r1); + } + return NetworkId.__wrap(r0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @returns {NetworkId} + */ + static testnet() { + const ret = wasm.networkid_testnet(); + return NetworkId.__wrap(ret); + } + /** + * @returns {NetworkId} + */ + static mainnet() { + const ret = wasm.networkid_mainnet(); + return NetworkId.__wrap(ret); + } + /** + * @returns {number} + */ + kind() { + const ret = wasm.networkid_kind(this.ptr); + return ret >>> 0; + } +} +module.exports.NetworkId = NetworkId; + +const NetworkInfoFinalization = new FinalizationRegistry((ptr) => + wasm.__wbg_networkinfo_free(ptr) +); +/** */ +class NetworkInfo { + static __wrap(ptr) { + const obj = Object.create(NetworkInfo.prototype); + obj.ptr = ptr; + NetworkInfoFinalization.register(obj, obj.ptr, obj); + return obj; + } + + __destroy_into_raw() { + const ptr = this.ptr; + this.ptr = 0; + NetworkInfoFinalization.unregister(this); + return ptr; + } + + free() { + const ptr = this.__destroy_into_raw(); + wasm.__wbg_networkinfo_free(ptr); + } + /** + * @param {number} network_id + * @param {number} protocol_magic + * @returns {NetworkInfo} + */ + static new(network_id, protocol_magic) { + const ret = wasm.networkinfo_new(network_id, protocol_magic); + return NetworkInfo.__wrap(ret); + } + /** + * @returns {number} + */ + network_id() { + const ret = wasm.networkinfo_network_id(this.ptr); + return ret; + } + /** + * @returns {number} + */ + protocol_magic() { + const ret = wasm.networkinfo_protocol_magic(this.ptr); + return ret >>> 0; + } + /** + * @returns {NetworkInfo} + */ + static testnet() { + const ret = wasm.networkinfo_testnet(); + return NetworkInfo.__wrap(ret); + } + /** + * @returns {NetworkInfo} + */ + static mainnet() { + const ret = wasm.networkinfo_mainnet(); + return NetworkInfo.__wrap(ret); + } +} +module.exports.NetworkInfo = NetworkInfo; + +const NewCommitteeFinalization = new FinalizationRegistry((ptr) => + wasm.__wbg_newcommittee_free(ptr) +); +/** */ +class NewCommittee { + static __wrap(ptr) { + const obj = Object.create(NewCommittee.prototype); + obj.ptr = ptr; + NewCommitteeFinalization.register(obj, obj.ptr, obj); + return obj; + } + + __destroy_into_raw() { + const ptr = this.ptr; + this.ptr = 0; + NewCommitteeFinalization.unregister(this); + return ptr; + } + + free() { + const ptr = this.__destroy_into_raw(); + wasm.__wbg_newcommittee_free(ptr); + } + /** + * @returns {Uint8Array} + */ + to_bytes() { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + wasm.newcommittee_to_bytes(retptr, this.ptr); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var v0 = getArrayU8FromWasm0(r0, r1).slice(); + wasm.__wbindgen_free(r0, r1 * 1); + return v0; + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @param {Uint8Array} bytes + * @returns {NewCommittee} + */ + static from_bytes(bytes) { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + const ptr0 = passArray8ToWasm0(bytes, wasm.__wbindgen_malloc); + const len0 = WASM_VECTOR_LEN; + wasm.newcommittee_from_bytes(retptr, ptr0, len0); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + if (r2) { + throw takeObject(r1); + } + return NewCommittee.__wrap(r0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @returns {string} + */ + to_json() { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + wasm.newcommittee_to_json(retptr, this.ptr); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + var r3 = getInt32Memory0()[retptr / 4 + 3]; + var ptr0 = r0; + var len0 = r1; + if (r3) { + ptr0 = 0; + len0 = 0; + throw takeObject(r2); + } + return getStringFromWasm0(ptr0, len0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + wasm.__wbindgen_free(ptr0, len0); + } + } + /** + * @returns {any} + */ + to_js_value() { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + wasm.newcommittee_to_js_value(retptr, this.ptr); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + if (r2) { + throw takeObject(r1); + } + return takeObject(r0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @param {string} json + * @returns {NewCommittee} + */ + static from_json(json) { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + const ptr0 = passStringToWasm0( + json, + wasm.__wbindgen_malloc, + wasm.__wbindgen_realloc, + ); + const len0 = WASM_VECTOR_LEN; + wasm.newcommittee_from_json(retptr, ptr0, len0); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + if (r2) { + throw takeObject(r1); + } + return NewCommittee.__wrap(r0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @returns {Ed25519KeyHashes} + */ + committee() { + const ret = wasm.newcommittee_committee(this.ptr); + return Ed25519KeyHashes.__wrap(ret); + } + /** + * @returns {UnitInterval} + */ + rational() { + const ret = wasm.drepvotingthresholds_motion_no_confidence(this.ptr); + return UnitInterval.__wrap(ret); + } + /** + * @param {Ed25519KeyHashes} committee + * @param {UnitInterval} rational + * @returns {NewCommittee} + */ + static new(committee, rational) { + _assertClass(committee, Ed25519KeyHashes); + _assertClass(rational, UnitInterval); + const ret = wasm.newcommittee_new(committee.ptr, rational.ptr); + return NewCommittee.__wrap(ret); + } +} +module.exports.NewCommittee = NewCommittee; + +const NewConstitutionFinalization = new FinalizationRegistry((ptr) => + wasm.__wbg_newconstitution_free(ptr) +); +/** */ +class NewConstitution { + static __wrap(ptr) { + const obj = Object.create(NewConstitution.prototype); + obj.ptr = ptr; + NewConstitutionFinalization.register(obj, obj.ptr, obj); + return obj; + } + + __destroy_into_raw() { + const ptr = this.ptr; + this.ptr = 0; + NewConstitutionFinalization.unregister(this); + return ptr; + } + + free() { + const ptr = this.__destroy_into_raw(); + wasm.__wbg_newconstitution_free(ptr); + } + /** + * @returns {Uint8Array} + */ + to_bytes() { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + wasm.newconstitution_to_bytes(retptr, this.ptr); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var v0 = getArrayU8FromWasm0(r0, r1).slice(); + wasm.__wbindgen_free(r0, r1 * 1); + return v0; + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @param {Uint8Array} bytes + * @returns {NewConstitution} + */ + static from_bytes(bytes) { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + const ptr0 = passArray8ToWasm0(bytes, wasm.__wbindgen_malloc); + const len0 = WASM_VECTOR_LEN; + wasm.newconstitution_from_bytes(retptr, ptr0, len0); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + if (r2) { + throw takeObject(r1); + } + return NewConstitution.__wrap(r0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @returns {string} + */ + to_json() { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + wasm.newconstitution_to_json(retptr, this.ptr); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + var r3 = getInt32Memory0()[retptr / 4 + 3]; + var ptr0 = r0; + var len0 = r1; + if (r3) { + ptr0 = 0; + len0 = 0; + throw takeObject(r2); + } + return getStringFromWasm0(ptr0, len0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + wasm.__wbindgen_free(ptr0, len0); + } + } + /** + * @returns {any} + */ + to_js_value() { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + wasm.newconstitution_to_js_value(retptr, this.ptr); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + if (r2) { + throw takeObject(r1); + } + return takeObject(r0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @param {string} json + * @returns {NewConstitution} + */ + static from_json(json) { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + const ptr0 = passStringToWasm0( + json, + wasm.__wbindgen_malloc, + wasm.__wbindgen_realloc, + ); + const len0 = WASM_VECTOR_LEN; + wasm.newconstitution_from_json(retptr, ptr0, len0); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + if (r2) { + throw takeObject(r1); + } + return NewConstitution.__wrap(r0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @returns {DataHash} + */ + hash() { + const ret = wasm.genesiskeydelegation_vrf_keyhash(this.ptr); + return DataHash.__wrap(ret); + } + /** + * @param {DataHash} hash + * @returns {NewConstitution} + */ + static new(hash) { + _assertClass(hash, DataHash); + const ret = wasm.newconstitution_new(hash.ptr); + return NewConstitution.__wrap(ret); + } +} +module.exports.NewConstitution = NewConstitution; + +const NonceFinalization = new FinalizationRegistry((ptr) => + wasm.__wbg_nonce_free(ptr) +); +/** */ +class Nonce { + static __wrap(ptr) { + const obj = Object.create(Nonce.prototype); + obj.ptr = ptr; + NonceFinalization.register(obj, obj.ptr, obj); + return obj; + } + + __destroy_into_raw() { + const ptr = this.ptr; + this.ptr = 0; + NonceFinalization.unregister(this); + return ptr; + } + + free() { + const ptr = this.__destroy_into_raw(); + wasm.__wbg_nonce_free(ptr); + } + /** + * @returns {Uint8Array} + */ + to_bytes() { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + wasm.nonce_to_bytes(retptr, this.ptr); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var v0 = getArrayU8FromWasm0(r0, r1).slice(); + wasm.__wbindgen_free(r0, r1 * 1); + return v0; + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @param {Uint8Array} bytes + * @returns {Nonce} + */ + static from_bytes(bytes) { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + const ptr0 = passArray8ToWasm0(bytes, wasm.__wbindgen_malloc); + const len0 = WASM_VECTOR_LEN; + wasm.nonce_from_bytes(retptr, ptr0, len0); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + if (r2) { + throw takeObject(r1); + } + return Nonce.__wrap(r0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @returns {Nonce} + */ + static new_identity() { + const ret = wasm.nonce_new_identity(); + return Nonce.__wrap(ret); + } + /** + * @param {Uint8Array} hash + * @returns {Nonce} + */ + static new_from_hash(hash) { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + const ptr0 = passArray8ToWasm0(hash, wasm.__wbindgen_malloc); + const len0 = WASM_VECTOR_LEN; + wasm.nonce_new_from_hash(retptr, ptr0, len0); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + if (r2) { + throw takeObject(r1); + } + return Nonce.__wrap(r0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @returns {Uint8Array | undefined} + */ + get_hash() { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + wasm.nonce_get_hash(retptr, this.ptr); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + let v0; + if (r0 !== 0) { + v0 = getArrayU8FromWasm0(r0, r1).slice(); + wasm.__wbindgen_free(r0, r1 * 1); + } + return v0; + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } +} +module.exports.Nonce = Nonce; + +const OperationalCertFinalization = new FinalizationRegistry((ptr) => + wasm.__wbg_operationalcert_free(ptr) +); +/** */ +class OperationalCert { + static __wrap(ptr) { + const obj = Object.create(OperationalCert.prototype); + obj.ptr = ptr; + OperationalCertFinalization.register(obj, obj.ptr, obj); + return obj; + } + + __destroy_into_raw() { + const ptr = this.ptr; + this.ptr = 0; + OperationalCertFinalization.unregister(this); + return ptr; + } + + free() { + const ptr = this.__destroy_into_raw(); + wasm.__wbg_operationalcert_free(ptr); + } + /** + * @returns {Uint8Array} + */ + to_bytes() { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + wasm.operationalcert_to_bytes(retptr, this.ptr); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var v0 = getArrayU8FromWasm0(r0, r1).slice(); + wasm.__wbindgen_free(r0, r1 * 1); + return v0; + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @param {Uint8Array} bytes + * @returns {OperationalCert} + */ + static from_bytes(bytes) { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + const ptr0 = passArray8ToWasm0(bytes, wasm.__wbindgen_malloc); + const len0 = WASM_VECTOR_LEN; + wasm.operationalcert_from_bytes(retptr, ptr0, len0); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + if (r2) { + throw takeObject(r1); + } + return OperationalCert.__wrap(r0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @returns {string} + */ + to_json() { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + wasm.operationalcert_to_json(retptr, this.ptr); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + var r3 = getInt32Memory0()[retptr / 4 + 3]; + var ptr0 = r0; + var len0 = r1; + if (r3) { + ptr0 = 0; + len0 = 0; + throw takeObject(r2); + } + return getStringFromWasm0(ptr0, len0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + wasm.__wbindgen_free(ptr0, len0); + } + } + /** + * @returns {any} + */ + to_js_value() { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + wasm.operationalcert_to_js_value(retptr, this.ptr); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + if (r2) { + throw takeObject(r1); + } + return takeObject(r0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @param {string} json + * @returns {OperationalCert} + */ + static from_json(json) { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + const ptr0 = passStringToWasm0( + json, + wasm.__wbindgen_malloc, + wasm.__wbindgen_realloc, + ); + const len0 = WASM_VECTOR_LEN; + wasm.operationalcert_from_json(retptr, ptr0, len0); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + if (r2) { + throw takeObject(r1); + } + return OperationalCert.__wrap(r0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @returns {KESVKey} + */ + hot_vkey() { + const ret = wasm.operationalcert_hot_vkey(this.ptr); + return KESVKey.__wrap(ret); + } + /** + * @returns {number} + */ + sequence_number() { + const ret = wasm.operationalcert_sequence_number(this.ptr); + return ret >>> 0; + } + /** + * @returns {number} + */ + kes_period() { + const ret = wasm.operationalcert_kes_period(this.ptr); + return ret >>> 0; + } + /** + * @returns {Ed25519Signature} + */ + sigma() { + const ret = wasm.operationalcert_sigma(this.ptr); + return Ed25519Signature.__wrap(ret); + } + /** + * @param {KESVKey} hot_vkey + * @param {number} sequence_number + * @param {number} kes_period + * @param {Ed25519Signature} sigma + * @returns {OperationalCert} + */ + static new(hot_vkey, sequence_number, kes_period, sigma) { + _assertClass(hot_vkey, KESVKey); + _assertClass(sigma, Ed25519Signature); + const ret = wasm.operationalcert_new( + hot_vkey.ptr, + sequence_number, + kes_period, + sigma.ptr, + ); + return OperationalCert.__wrap(ret); + } +} +module.exports.OperationalCert = OperationalCert; + +const ParameterChangeActionFinalization = new FinalizationRegistry((ptr) => + wasm.__wbg_parameterchangeaction_free(ptr) +); +/** */ +class ParameterChangeAction { + static __wrap(ptr) { + const obj = Object.create(ParameterChangeAction.prototype); + obj.ptr = ptr; + ParameterChangeActionFinalization.register(obj, obj.ptr, obj); + return obj; + } + + __destroy_into_raw() { + const ptr = this.ptr; + this.ptr = 0; + ParameterChangeActionFinalization.unregister(this); + return ptr; + } + + free() { + const ptr = this.__destroy_into_raw(); + wasm.__wbg_parameterchangeaction_free(ptr); + } + /** + * @returns {Uint8Array} + */ + to_bytes() { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + wasm.parameterchangeaction_to_bytes(retptr, this.ptr); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var v0 = getArrayU8FromWasm0(r0, r1).slice(); + wasm.__wbindgen_free(r0, r1 * 1); + return v0; + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @param {Uint8Array} bytes + * @returns {ParameterChangeAction} + */ + static from_bytes(bytes) { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + const ptr0 = passArray8ToWasm0(bytes, wasm.__wbindgen_malloc); + const len0 = WASM_VECTOR_LEN; + wasm.parameterchangeaction_from_bytes(retptr, ptr0, len0); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + if (r2) { + throw takeObject(r1); + } + return ParameterChangeAction.__wrap(r0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @returns {string} + */ + to_json() { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + wasm.parameterchangeaction_to_json(retptr, this.ptr); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + var r3 = getInt32Memory0()[retptr / 4 + 3]; + var ptr0 = r0; + var len0 = r1; + if (r3) { + ptr0 = 0; + len0 = 0; + throw takeObject(r2); + } + return getStringFromWasm0(ptr0, len0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + wasm.__wbindgen_free(ptr0, len0); + } + } + /** + * @returns {any} + */ + to_js_value() { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + wasm.parameterchangeaction_to_js_value(retptr, this.ptr); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + if (r2) { + throw takeObject(r1); + } + return takeObject(r0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @param {string} json + * @returns {ParameterChangeAction} + */ + static from_json(json) { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + const ptr0 = passStringToWasm0( + json, + wasm.__wbindgen_malloc, + wasm.__wbindgen_realloc, + ); + const len0 = WASM_VECTOR_LEN; + wasm.parameterchangeaction_from_json(retptr, ptr0, len0); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + if (r2) { + throw takeObject(r1); + } + return ParameterChangeAction.__wrap(r0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @returns {ProtocolParamUpdate} + */ + protocol_param_update() { + const ret = wasm.parameterchangeaction_protocol_param_update(this.ptr); + return ProtocolParamUpdate.__wrap(ret); + } + /** + * @param {ProtocolParamUpdate} protocol_param_update + * @returns {ParameterChangeAction} + */ + static new(protocol_param_update) { + _assertClass(protocol_param_update, ProtocolParamUpdate); + const ret = wasm.parameterchangeaction_new(protocol_param_update.ptr); + return ParameterChangeAction.__wrap(ret); + } +} +module.exports.ParameterChangeAction = ParameterChangeAction; + +const PlutusDataFinalization = new FinalizationRegistry((ptr) => + wasm.__wbg_plutusdata_free(ptr) +); +/** */ +class PlutusData { + static __wrap(ptr) { + const obj = Object.create(PlutusData.prototype); + obj.ptr = ptr; + PlutusDataFinalization.register(obj, obj.ptr, obj); + return obj; + } + + __destroy_into_raw() { + const ptr = this.ptr; + this.ptr = 0; + PlutusDataFinalization.unregister(this); + return ptr; + } + + free() { + const ptr = this.__destroy_into_raw(); + wasm.__wbg_plutusdata_free(ptr); + } + /** + * @returns {Uint8Array} + */ + to_bytes() { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + wasm.plutusdata_to_bytes(retptr, this.ptr); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var v0 = getArrayU8FromWasm0(r0, r1).slice(); + wasm.__wbindgen_free(r0, r1 * 1); + return v0; + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @param {Uint8Array} bytes + * @returns {PlutusData} + */ + static from_bytes(bytes) { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + const ptr0 = passArray8ToWasm0(bytes, wasm.__wbindgen_malloc); + const len0 = WASM_VECTOR_LEN; + wasm.plutusdata_from_bytes(retptr, ptr0, len0); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + if (r2) { + throw takeObject(r1); + } + return PlutusData.__wrap(r0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @param {ConstrPlutusData} constr_plutus_data + * @returns {PlutusData} + */ + static new_constr_plutus_data(constr_plutus_data) { + _assertClass(constr_plutus_data, ConstrPlutusData); + const ret = wasm.plutusdata_new_constr_plutus_data(constr_plutus_data.ptr); + return PlutusData.__wrap(ret); + } + /** + * @param {PlutusMap} map + * @returns {PlutusData} + */ + static new_map(map) { + _assertClass(map, PlutusMap); + const ret = wasm.plutusdata_new_map(map.ptr); + return PlutusData.__wrap(ret); + } + /** + * @param {PlutusList} list + * @returns {PlutusData} + */ + static new_list(list) { + _assertClass(list, PlutusList); + const ret = wasm.plutusdata_new_list(list.ptr); + return PlutusData.__wrap(ret); + } + /** + * @param {BigInt} integer + * @returns {PlutusData} + */ + static new_integer(integer) { + _assertClass(integer, BigInt); + const ret = wasm.plutusdata_new_integer(integer.ptr); + return PlutusData.__wrap(ret); + } + /** + * @param {Uint8Array} bytes + * @returns {PlutusData} + */ + static new_bytes(bytes) { + const ptr0 = passArray8ToWasm0(bytes, wasm.__wbindgen_malloc); + const len0 = WASM_VECTOR_LEN; + const ret = wasm.plutusdata_new_bytes(ptr0, len0); + return PlutusData.__wrap(ret); + } + /** + * @returns {number} + */ + kind() { + const ret = wasm.plutusdata_kind(this.ptr); + return ret >>> 0; + } + /** + * @returns {ConstrPlutusData | undefined} + */ + as_constr_plutus_data() { + const ret = wasm.plutusdata_as_constr_plutus_data(this.ptr); + return ret === 0 ? undefined : ConstrPlutusData.__wrap(ret); + } + /** + * @returns {PlutusMap | undefined} + */ + as_map() { + const ret = wasm.plutusdata_as_map(this.ptr); + return ret === 0 ? undefined : PlutusMap.__wrap(ret); + } + /** + * @returns {PlutusList | undefined} + */ + as_list() { + const ret = wasm.plutusdata_as_list(this.ptr); + return ret === 0 ? undefined : PlutusList.__wrap(ret); + } + /** + * @returns {BigInt | undefined} + */ + as_integer() { + const ret = wasm.plutusdata_as_integer(this.ptr); + return ret === 0 ? undefined : BigInt.__wrap(ret); + } + /** + * @returns {Uint8Array | undefined} + */ + as_bytes() { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + wasm.plutusdata_as_bytes(retptr, this.ptr); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + let v0; + if (r0 !== 0) { + v0 = getArrayU8FromWasm0(r0, r1).slice(); + wasm.__wbindgen_free(r0, r1 * 1); + } + return v0; + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } +} +module.exports.PlutusData = PlutusData; + +const PlutusListFinalization = new FinalizationRegistry((ptr) => + wasm.__wbg_plutuslist_free(ptr) +); +/** */ +class PlutusList { + static __wrap(ptr) { + const obj = Object.create(PlutusList.prototype); + obj.ptr = ptr; + PlutusListFinalization.register(obj, obj.ptr, obj); + return obj; + } + + __destroy_into_raw() { + const ptr = this.ptr; + this.ptr = 0; + PlutusListFinalization.unregister(this); + return ptr; + } + + free() { + const ptr = this.__destroy_into_raw(); + wasm.__wbg_plutuslist_free(ptr); + } + /** + * @returns {Uint8Array} + */ + to_bytes() { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + wasm.plutuslist_to_bytes(retptr, this.ptr); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var v0 = getArrayU8FromWasm0(r0, r1).slice(); + wasm.__wbindgen_free(r0, r1 * 1); + return v0; + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @param {Uint8Array} bytes + * @returns {PlutusList} + */ + static from_bytes(bytes) { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + const ptr0 = passArray8ToWasm0(bytes, wasm.__wbindgen_malloc); + const len0 = WASM_VECTOR_LEN; + wasm.plutuslist_from_bytes(retptr, ptr0, len0); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + if (r2) { + throw takeObject(r1); + } + return PlutusList.__wrap(r0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @returns {PlutusList} + */ + static new() { + const ret = wasm.plutuslist_new(); + return PlutusList.__wrap(ret); + } + /** + * @returns {number} + */ + len() { + const ret = wasm.assetnames_len(this.ptr); + return ret >>> 0; + } + /** + * @param {number} index + * @returns {PlutusData} + */ + get(index) { + const ret = wasm.plutuslist_get(this.ptr, index); + return PlutusData.__wrap(ret); + } + /** + * @param {PlutusData} elem + */ + add(elem) { + _assertClass(elem, PlutusData); + wasm.plutuslist_add(this.ptr, elem.ptr); + } +} +module.exports.PlutusList = PlutusList; + +const PlutusMapFinalization = new FinalizationRegistry((ptr) => + wasm.__wbg_plutusmap_free(ptr) +); +/** */ +class PlutusMap { + static __wrap(ptr) { + const obj = Object.create(PlutusMap.prototype); + obj.ptr = ptr; + PlutusMapFinalization.register(obj, obj.ptr, obj); + return obj; + } + + __destroy_into_raw() { + const ptr = this.ptr; + this.ptr = 0; + PlutusMapFinalization.unregister(this); + return ptr; + } + + free() { + const ptr = this.__destroy_into_raw(); + wasm.__wbg_plutusmap_free(ptr); + } + /** + * @returns {Uint8Array} + */ + to_bytes() { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + wasm.plutusmap_to_bytes(retptr, this.ptr); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var v0 = getArrayU8FromWasm0(r0, r1).slice(); + wasm.__wbindgen_free(r0, r1 * 1); + return v0; + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @param {Uint8Array} bytes + * @returns {PlutusMap} + */ + static from_bytes(bytes) { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + const ptr0 = passArray8ToWasm0(bytes, wasm.__wbindgen_malloc); + const len0 = WASM_VECTOR_LEN; + wasm.plutusmap_from_bytes(retptr, ptr0, len0); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + if (r2) { + throw takeObject(r1); + } + return PlutusMap.__wrap(r0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @returns {PlutusMap} + */ + static new() { + const ret = wasm.certificates_new(); + return PlutusMap.__wrap(ret); + } + /** + * @returns {number} + */ + len() { + const ret = wasm.assetnames_len(this.ptr); + return ret >>> 0; + } + /** + * @param {PlutusData} key + * @param {PlutusData} value + * @returns {PlutusData | undefined} + */ + insert(key, value) { + _assertClass(key, PlutusData); + _assertClass(value, PlutusData); + const ret = wasm.plutusmap_insert(this.ptr, key.ptr, value.ptr); + return ret === 0 ? undefined : PlutusData.__wrap(ret); + } + /** + * @param {PlutusData} key + * @returns {PlutusData | undefined} + */ + get(key) { + _assertClass(key, PlutusData); + const ret = wasm.plutusmap_get(this.ptr, key.ptr); + return ret === 0 ? undefined : PlutusData.__wrap(ret); + } + /** + * @returns {PlutusList} + */ + keys() { + const ret = wasm.plutusmap_keys(this.ptr); + return PlutusList.__wrap(ret); + } +} +module.exports.PlutusMap = PlutusMap; + +const PlutusScriptFinalization = new FinalizationRegistry((ptr) => + wasm.__wbg_plutusscript_free(ptr) +); +/** */ +class PlutusScript { + static __wrap(ptr) { + const obj = Object.create(PlutusScript.prototype); + obj.ptr = ptr; + PlutusScriptFinalization.register(obj, obj.ptr, obj); + return obj; + } + + __destroy_into_raw() { + const ptr = this.ptr; + this.ptr = 0; + PlutusScriptFinalization.unregister(this); + return ptr; + } + + free() { + const ptr = this.__destroy_into_raw(); + wasm.__wbg_plutusscript_free(ptr); + } + /** + * @returns {Uint8Array} + */ + to_bytes() { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + wasm.plutusscript_to_bytes(retptr, this.ptr); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var v0 = getArrayU8FromWasm0(r0, r1).slice(); + wasm.__wbindgen_free(r0, r1 * 1); + return v0; + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @param {Uint8Array} bytes + * @returns {PlutusScript} + */ + static from_bytes(bytes) { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + const ptr0 = passArray8ToWasm0(bytes, wasm.__wbindgen_malloc); + const len0 = WASM_VECTOR_LEN; + wasm.plutusscript_from_bytes(retptr, ptr0, len0); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + if (r2) { + throw takeObject(r1); + } + return PlutusScript.__wrap(r0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @param {number} namespace + * @returns {ScriptHash} + */ + hash(namespace) { + const ret = wasm.plutusscript_hash(this.ptr, namespace); + return ScriptHash.__wrap(ret); + } + /** + * * Creates a new Plutus script from the RAW bytes of the compiled script. + * * This does NOT include any CBOR encoding around these bytes (e.g. from "cborBytes" in cardano-cli) + * * If you creating this from those you should use PlutusScript::from_bytes() instead. + * + * @param {Uint8Array} bytes + * @returns {PlutusScript} + */ + static new(bytes) { + const ptr0 = passArray8ToWasm0(bytes, wasm.__wbindgen_malloc); + const len0 = WASM_VECTOR_LEN; + const ret = wasm.plutusscript_new(ptr0, len0); + return PlutusScript.__wrap(ret); + } + /** + * * The raw bytes of this compiled Plutus script. + * * If you need "cborBytes" for cardano-cli use PlutusScript::to_bytes() instead. + * + * @returns {Uint8Array} + */ + bytes() { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + wasm.assetname_name(retptr, this.ptr); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var v0 = getArrayU8FromWasm0(r0, r1).slice(); + wasm.__wbindgen_free(r0, r1 * 1); + return v0; + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } +} +module.exports.PlutusScript = PlutusScript; + +const PlutusScriptsFinalization = new FinalizationRegistry((ptr) => + wasm.__wbg_plutusscripts_free(ptr) +); +/** */ +class PlutusScripts { + static __wrap(ptr) { + const obj = Object.create(PlutusScripts.prototype); + obj.ptr = ptr; + PlutusScriptsFinalization.register(obj, obj.ptr, obj); + return obj; + } + + __destroy_into_raw() { + const ptr = this.ptr; + this.ptr = 0; + PlutusScriptsFinalization.unregister(this); + return ptr; + } + + free() { + const ptr = this.__destroy_into_raw(); + wasm.__wbg_plutusscripts_free(ptr); + } + /** + * @returns {Uint8Array} + */ + to_bytes() { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + wasm.plutusscripts_to_bytes(retptr, this.ptr); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var v0 = getArrayU8FromWasm0(r0, r1).slice(); + wasm.__wbindgen_free(r0, r1 * 1); + return v0; + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @param {Uint8Array} bytes + * @returns {PlutusScripts} + */ + static from_bytes(bytes) { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + const ptr0 = passArray8ToWasm0(bytes, wasm.__wbindgen_malloc); + const len0 = WASM_VECTOR_LEN; + wasm.plutusscripts_from_bytes(retptr, ptr0, len0); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + if (r2) { + throw takeObject(r1); + } + return PlutusScripts.__wrap(r0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @returns {PlutusScripts} + */ + static new() { + const ret = wasm.assetnames_new(); + return PlutusScripts.__wrap(ret); + } + /** + * @returns {number} + */ + len() { + const ret = wasm.assetnames_len(this.ptr); + return ret >>> 0; + } + /** + * @param {number} index + * @returns {PlutusScript} + */ + get(index) { + const ret = wasm.plutusscripts_get(this.ptr, index); + return PlutusScript.__wrap(ret); + } + /** + * @param {PlutusScript} elem + */ + add(elem) { + _assertClass(elem, PlutusScript); + wasm.assetnames_add(this.ptr, elem.ptr); + } +} +module.exports.PlutusScripts = PlutusScripts; + +const PlutusWitnessFinalization = new FinalizationRegistry((ptr) => + wasm.__wbg_plutuswitness_free(ptr) +); +/** */ +class PlutusWitness { + static __wrap(ptr) { + const obj = Object.create(PlutusWitness.prototype); + obj.ptr = ptr; + PlutusWitnessFinalization.register(obj, obj.ptr, obj); + return obj; + } + + __destroy_into_raw() { + const ptr = this.ptr; + this.ptr = 0; + PlutusWitnessFinalization.unregister(this); + return ptr; + } + + free() { + const ptr = this.__destroy_into_raw(); + wasm.__wbg_plutuswitness_free(ptr); + } + /** + * Plutus V1 witness or witness where no script is attached and so version doesn't matter + * @param {PlutusData} redeemer + * @param {PlutusData | undefined} plutus_data + * @param {PlutusScript | undefined} script + * @returns {PlutusWitness} + */ + static new(redeemer, plutus_data, script) { + _assertClass(redeemer, PlutusData); + let ptr0 = 0; + if (!isLikeNone(plutus_data)) { + _assertClass(plutus_data, PlutusData); + ptr0 = plutus_data.__destroy_into_raw(); + } + let ptr1 = 0; + if (!isLikeNone(script)) { + _assertClass(script, PlutusScript); + ptr1 = script.__destroy_into_raw(); + } + const ret = wasm.plutuswitness_new(redeemer.ptr, ptr0, ptr1); + return PlutusWitness.__wrap(ret); + } + /** + * @param {PlutusData} redeemer + * @param {PlutusData | undefined} plutus_data + * @param {PlutusScript | undefined} script + * @returns {PlutusWitness} + */ + static new_plutus_v2(redeemer, plutus_data, script) { + _assertClass(redeemer, PlutusData); + let ptr0 = 0; + if (!isLikeNone(plutus_data)) { + _assertClass(plutus_data, PlutusData); + ptr0 = plutus_data.__destroy_into_raw(); + } + let ptr1 = 0; + if (!isLikeNone(script)) { + _assertClass(script, PlutusScript); + ptr1 = script.__destroy_into_raw(); + } + const ret = wasm.plutuswitness_new_plutus_v2(redeemer.ptr, ptr0, ptr1); + return PlutusWitness.__wrap(ret); + } + /** + * @returns {PlutusData | undefined} + */ + plutus_data() { + const ret = wasm.plutuswitness_plutus_data(this.ptr); + return ret === 0 ? undefined : PlutusData.__wrap(ret); + } + /** + * @returns {PlutusData} + */ + redeemer() { + const ret = wasm.data_get(this.ptr); + return PlutusData.__wrap(ret); + } + /** + * @returns {PlutusScript | undefined} + */ + script() { + const ret = wasm.plutuswitness_script(this.ptr); + return ret === 0 ? undefined : PlutusScript.__wrap(ret); + } + /** + * @returns {number} + */ + version() { + const ret = wasm.plutuswitness_version(this.ptr); + return ret >>> 0; + } +} +module.exports.PlutusWitness = PlutusWitness; + +const PointerFinalization = new FinalizationRegistry((ptr) => + wasm.__wbg_pointer_free(ptr) +); +/** */ +class Pointer { + static __wrap(ptr) { + const obj = Object.create(Pointer.prototype); + obj.ptr = ptr; + PointerFinalization.register(obj, obj.ptr, obj); + return obj; + } + + __destroy_into_raw() { + const ptr = this.ptr; + this.ptr = 0; + PointerFinalization.unregister(this); + return ptr; + } + + free() { + const ptr = this.__destroy_into_raw(); + wasm.__wbg_pointer_free(ptr); + } + /** + * @param {BigNum} slot + * @param {BigNum} tx_index + * @param {BigNum} cert_index + * @returns {Pointer} + */ + static new(slot, tx_index, cert_index) { + _assertClass(slot, BigNum); + _assertClass(tx_index, BigNum); + _assertClass(cert_index, BigNum); + const ret = wasm.pointer_new(slot.ptr, tx_index.ptr, cert_index.ptr); + return Pointer.__wrap(ret); + } + /** + * @returns {BigNum} + */ + slot() { + const ret = wasm.constrplutusdata_alternative(this.ptr); + return BigNum.__wrap(ret); + } + /** + * @returns {BigNum} + */ + tx_index() { + const ret = wasm.exunits_steps(this.ptr); + return BigNum.__wrap(ret); + } + /** + * @returns {BigNum} + */ + cert_index() { + const ret = wasm.pointer_cert_index(this.ptr); + return BigNum.__wrap(ret); + } +} +module.exports.Pointer = Pointer; + +const PointerAddressFinalization = new FinalizationRegistry((ptr) => + wasm.__wbg_pointeraddress_free(ptr) +); +/** */ +class PointerAddress { + static __wrap(ptr) { + const obj = Object.create(PointerAddress.prototype); + obj.ptr = ptr; + PointerAddressFinalization.register(obj, obj.ptr, obj); + return obj; + } + + __destroy_into_raw() { + const ptr = this.ptr; + this.ptr = 0; + PointerAddressFinalization.unregister(this); + return ptr; + } + + free() { + const ptr = this.__destroy_into_raw(); + wasm.__wbg_pointeraddress_free(ptr); + } + /** + * @param {number} network + * @param {StakeCredential} payment + * @param {Pointer} stake + * @returns {PointerAddress} + */ + static new(network, payment, stake) { + _assertClass(payment, StakeCredential); + _assertClass(stake, Pointer); + const ret = wasm.pointeraddress_new(network, payment.ptr, stake.ptr); + return PointerAddress.__wrap(ret); + } + /** + * @returns {StakeCredential} + */ + payment_cred() { + const ret = wasm.pointeraddress_payment_cred(this.ptr); + return StakeCredential.__wrap(ret); + } + /** + * @returns {Pointer} + */ + stake_pointer() { + const ret = wasm.pointeraddress_stake_pointer(this.ptr); + return Pointer.__wrap(ret); + } + /** + * @returns {Address} + */ + to_address() { + const ret = wasm.pointeraddress_to_address(this.ptr); + return Address.__wrap(ret); + } + /** + * @param {Address} addr + * @returns {PointerAddress | undefined} + */ + static from_address(addr) { + _assertClass(addr, Address); + const ret = wasm.address_as_pointer(addr.ptr); + return ret === 0 ? undefined : PointerAddress.__wrap(ret); + } +} +module.exports.PointerAddress = PointerAddress; + +const PoolMetadataFinalization = new FinalizationRegistry((ptr) => + wasm.__wbg_poolmetadata_free(ptr) +); +/** */ +class PoolMetadata { + static __wrap(ptr) { + const obj = Object.create(PoolMetadata.prototype); + obj.ptr = ptr; + PoolMetadataFinalization.register(obj, obj.ptr, obj); + return obj; + } + + __destroy_into_raw() { + const ptr = this.ptr; + this.ptr = 0; + PoolMetadataFinalization.unregister(this); + return ptr; + } + + free() { + const ptr = this.__destroy_into_raw(); + wasm.__wbg_poolmetadata_free(ptr); + } + /** + * @returns {Uint8Array} + */ + to_bytes() { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + wasm.poolmetadata_to_bytes(retptr, this.ptr); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var v0 = getArrayU8FromWasm0(r0, r1).slice(); + wasm.__wbindgen_free(r0, r1 * 1); + return v0; + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @param {Uint8Array} bytes + * @returns {PoolMetadata} + */ + static from_bytes(bytes) { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + const ptr0 = passArray8ToWasm0(bytes, wasm.__wbindgen_malloc); + const len0 = WASM_VECTOR_LEN; + wasm.poolmetadata_from_bytes(retptr, ptr0, len0); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + if (r2) { + throw takeObject(r1); + } + return PoolMetadata.__wrap(r0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @returns {string} + */ + to_json() { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + wasm.poolmetadata_to_json(retptr, this.ptr); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + var r3 = getInt32Memory0()[retptr / 4 + 3]; + var ptr0 = r0; + var len0 = r1; + if (r3) { + ptr0 = 0; + len0 = 0; + throw takeObject(r2); + } + return getStringFromWasm0(ptr0, len0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + wasm.__wbindgen_free(ptr0, len0); + } + } + /** + * @returns {any} + */ + to_js_value() { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + wasm.poolmetadata_to_js_value(retptr, this.ptr); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + if (r2) { + throw takeObject(r1); + } + return takeObject(r0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @param {string} json + * @returns {PoolMetadata} + */ + static from_json(json) { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + const ptr0 = passStringToWasm0( + json, + wasm.__wbindgen_malloc, + wasm.__wbindgen_realloc, + ); + const len0 = WASM_VECTOR_LEN; + wasm.poolmetadata_from_json(retptr, ptr0, len0); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + if (r2) { + throw takeObject(r1); + } + return PoolMetadata.__wrap(r0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @returns {Url} + */ + url() { + const ret = wasm.anchor_anchor_url(this.ptr); + return Url.__wrap(ret); + } + /** + * @returns {PoolMetadataHash} + */ + pool_metadata_hash() { + const ret = wasm.anchor_anchor_data_hash(this.ptr); + return PoolMetadataHash.__wrap(ret); + } + /** + * @param {Url} url + * @param {PoolMetadataHash} pool_metadata_hash + * @returns {PoolMetadata} + */ + static new(url, pool_metadata_hash) { + _assertClass(url, Url); + _assertClass(pool_metadata_hash, PoolMetadataHash); + const ret = wasm.anchor_new(url.ptr, pool_metadata_hash.ptr); + return PoolMetadata.__wrap(ret); + } +} +module.exports.PoolMetadata = PoolMetadata; + +const PoolMetadataHashFinalization = new FinalizationRegistry((ptr) => + wasm.__wbg_poolmetadatahash_free(ptr) +); +/** */ +class PoolMetadataHash { + static __wrap(ptr) { + const obj = Object.create(PoolMetadataHash.prototype); + obj.ptr = ptr; + PoolMetadataHashFinalization.register(obj, obj.ptr, obj); + return obj; + } + + __destroy_into_raw() { + const ptr = this.ptr; + this.ptr = 0; + PoolMetadataHashFinalization.unregister(this); + return ptr; + } + + free() { + const ptr = this.__destroy_into_raw(); + wasm.__wbg_poolmetadatahash_free(ptr); + } + /** + * @param {Uint8Array} bytes + * @returns {PoolMetadataHash} + */ + static from_bytes(bytes) { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + const ptr0 = passArray8ToWasm0(bytes, wasm.__wbindgen_malloc); + const len0 = WASM_VECTOR_LEN; + wasm.poolmetadatahash_from_bytes(retptr, ptr0, len0); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + if (r2) { + throw takeObject(r1); + } + return PoolMetadataHash.__wrap(r0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @returns {Uint8Array} + */ + to_bytes() { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + wasm.auxiliarydatahash_to_bytes(retptr, this.ptr); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var v0 = getArrayU8FromWasm0(r0, r1).slice(); + wasm.__wbindgen_free(r0, r1 * 1); + return v0; + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @param {string} prefix + * @returns {string} + */ + to_bech32(prefix) { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + const ptr0 = passStringToWasm0( + prefix, + wasm.__wbindgen_malloc, + wasm.__wbindgen_realloc, + ); + const len0 = WASM_VECTOR_LEN; + wasm.auxiliarydatahash_to_bech32(retptr, this.ptr, ptr0, len0); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + var r3 = getInt32Memory0()[retptr / 4 + 3]; + var ptr1 = r0; + var len1 = r1; + if (r3) { + ptr1 = 0; + len1 = 0; + throw takeObject(r2); + } + return getStringFromWasm0(ptr1, len1); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + wasm.__wbindgen_free(ptr1, len1); + } + } + /** + * @param {string} bech_str + * @returns {PoolMetadataHash} + */ + static from_bech32(bech_str) { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + const ptr0 = passStringToWasm0( + bech_str, + wasm.__wbindgen_malloc, + wasm.__wbindgen_realloc, + ); + const len0 = WASM_VECTOR_LEN; + wasm.poolmetadatahash_from_bech32(retptr, ptr0, len0); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + if (r2) { + throw takeObject(r1); + } + return PoolMetadataHash.__wrap(r0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @returns {string} + */ + to_hex() { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + wasm.auxiliarydatahash_to_hex(retptr, this.ptr); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + return getStringFromWasm0(r0, r1); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + wasm.__wbindgen_free(r0, r1); + } + } + /** + * @param {string} hex + * @returns {PoolMetadataHash} + */ + static from_hex(hex) { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + const ptr0 = passStringToWasm0( + hex, + wasm.__wbindgen_malloc, + wasm.__wbindgen_realloc, + ); + const len0 = WASM_VECTOR_LEN; + wasm.poolmetadatahash_from_hex(retptr, ptr0, len0); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + if (r2) { + throw takeObject(r1); + } + return PoolMetadataHash.__wrap(r0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } +} +module.exports.PoolMetadataHash = PoolMetadataHash; + +const PoolParamsFinalization = new FinalizationRegistry((ptr) => + wasm.__wbg_poolparams_free(ptr) +); +/** */ +class PoolParams { + static __wrap(ptr) { + const obj = Object.create(PoolParams.prototype); + obj.ptr = ptr; + PoolParamsFinalization.register(obj, obj.ptr, obj); + return obj; + } + + __destroy_into_raw() { + const ptr = this.ptr; + this.ptr = 0; + PoolParamsFinalization.unregister(this); + return ptr; + } + + free() { + const ptr = this.__destroy_into_raw(); + wasm.__wbg_poolparams_free(ptr); + } + /** + * @returns {Uint8Array} + */ + to_bytes() { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + wasm.poolparams_to_bytes(retptr, this.ptr); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var v0 = getArrayU8FromWasm0(r0, r1).slice(); + wasm.__wbindgen_free(r0, r1 * 1); + return v0; + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @param {Uint8Array} bytes + * @returns {PoolParams} + */ + static from_bytes(bytes) { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + const ptr0 = passArray8ToWasm0(bytes, wasm.__wbindgen_malloc); + const len0 = WASM_VECTOR_LEN; + wasm.poolparams_from_bytes(retptr, ptr0, len0); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + if (r2) { + throw takeObject(r1); + } + return PoolParams.__wrap(r0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @returns {string} + */ + to_json() { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + wasm.poolparams_to_json(retptr, this.ptr); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + var r3 = getInt32Memory0()[retptr / 4 + 3]; + var ptr0 = r0; + var len0 = r1; + if (r3) { + ptr0 = 0; + len0 = 0; + throw takeObject(r2); + } + return getStringFromWasm0(ptr0, len0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + wasm.__wbindgen_free(ptr0, len0); + } + } + /** + * @returns {any} + */ + to_js_value() { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + wasm.poolparams_to_js_value(retptr, this.ptr); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + if (r2) { + throw takeObject(r1); + } + return takeObject(r0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @param {string} json + * @returns {PoolParams} + */ + static from_json(json) { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + const ptr0 = passStringToWasm0( + json, + wasm.__wbindgen_malloc, + wasm.__wbindgen_realloc, + ); + const len0 = WASM_VECTOR_LEN; + wasm.poolparams_from_json(retptr, ptr0, len0); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + if (r2) { + throw takeObject(r1); + } + return PoolParams.__wrap(r0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @returns {Ed25519KeyHash} + */ + operator() { + const ret = wasm.poolparams_operator(this.ptr); + return Ed25519KeyHash.__wrap(ret); + } + /** + * @returns {VRFKeyHash} + */ + vrf_keyhash() { + const ret = wasm.governanceactionid_transaction_id(this.ptr); + return VRFKeyHash.__wrap(ret); + } + /** + * @returns {BigNum} + */ + pledge() { + const ret = wasm.governanceactionid_governance_action_index(this.ptr); + return BigNum.__wrap(ret); + } + /** + * @returns {BigNum} + */ + cost() { + const ret = wasm.poolparams_cost(this.ptr); + return BigNum.__wrap(ret); + } + /** + * @returns {UnitInterval} + */ + margin() { + const ret = wasm.drepvotingthresholds_update_constitution(this.ptr); + return UnitInterval.__wrap(ret); + } + /** + * @returns {RewardAddress} + */ + reward_account() { + const ret = wasm.poolparams_reward_account(this.ptr); + return RewardAddress.__wrap(ret); + } + /** + * @returns {Ed25519KeyHashes} + */ + pool_owners() { + const ret = wasm.poolparams_pool_owners(this.ptr); + return Ed25519KeyHashes.__wrap(ret); + } + /** + * @returns {Relays} + */ + relays() { + const ret = wasm.poolparams_relays(this.ptr); + return Relays.__wrap(ret); + } + /** + * @returns {PoolMetadata | undefined} + */ + pool_metadata() { + const ret = wasm.poolparams_pool_metadata(this.ptr); + return ret === 0 ? undefined : PoolMetadata.__wrap(ret); + } + /** + * @param {Ed25519KeyHash} operator + * @param {VRFKeyHash} vrf_keyhash + * @param {BigNum} pledge + * @param {BigNum} cost + * @param {UnitInterval} margin + * @param {RewardAddress} reward_account + * @param {Ed25519KeyHashes} pool_owners + * @param {Relays} relays + * @param {PoolMetadata | undefined} pool_metadata + * @returns {PoolParams} + */ + static new( + operator, + vrf_keyhash, + pledge, + cost, + margin, + reward_account, + pool_owners, + relays, + pool_metadata, + ) { + _assertClass(operator, Ed25519KeyHash); + _assertClass(vrf_keyhash, VRFKeyHash); + _assertClass(pledge, BigNum); + _assertClass(cost, BigNum); + _assertClass(margin, UnitInterval); + _assertClass(reward_account, RewardAddress); + _assertClass(pool_owners, Ed25519KeyHashes); + _assertClass(relays, Relays); + let ptr0 = 0; + if (!isLikeNone(pool_metadata)) { + _assertClass(pool_metadata, PoolMetadata); + ptr0 = pool_metadata.__destroy_into_raw(); + } + const ret = wasm.poolparams_new( + operator.ptr, + vrf_keyhash.ptr, + pledge.ptr, + cost.ptr, + margin.ptr, + reward_account.ptr, + pool_owners.ptr, + relays.ptr, + ptr0, + ); + return PoolParams.__wrap(ret); + } +} +module.exports.PoolParams = PoolParams; + +const PoolRegistrationFinalization = new FinalizationRegistry((ptr) => + wasm.__wbg_poolregistration_free(ptr) +); +/** */ +class PoolRegistration { + static __wrap(ptr) { + const obj = Object.create(PoolRegistration.prototype); + obj.ptr = ptr; + PoolRegistrationFinalization.register(obj, obj.ptr, obj); + return obj; + } + + __destroy_into_raw() { + const ptr = this.ptr; + this.ptr = 0; + PoolRegistrationFinalization.unregister(this); + return ptr; + } + + free() { + const ptr = this.__destroy_into_raw(); + wasm.__wbg_poolregistration_free(ptr); + } + /** + * @returns {Uint8Array} + */ + to_bytes() { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + wasm.poolregistration_to_bytes(retptr, this.ptr); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var v0 = getArrayU8FromWasm0(r0, r1).slice(); + wasm.__wbindgen_free(r0, r1 * 1); + return v0; + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @param {Uint8Array} bytes + * @returns {PoolRegistration} + */ + static from_bytes(bytes) { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + const ptr0 = passArray8ToWasm0(bytes, wasm.__wbindgen_malloc); + const len0 = WASM_VECTOR_LEN; + wasm.poolregistration_from_bytes(retptr, ptr0, len0); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + if (r2) { + throw takeObject(r1); + } + return PoolRegistration.__wrap(r0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @returns {string} + */ + to_json() { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + wasm.poolregistration_to_json(retptr, this.ptr); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + var r3 = getInt32Memory0()[retptr / 4 + 3]; + var ptr0 = r0; + var len0 = r1; + if (r3) { + ptr0 = 0; + len0 = 0; + throw takeObject(r2); + } + return getStringFromWasm0(ptr0, len0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + wasm.__wbindgen_free(ptr0, len0); + } + } + /** + * @returns {any} + */ + to_js_value() { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + wasm.poolregistration_to_js_value(retptr, this.ptr); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + if (r2) { + throw takeObject(r1); + } + return takeObject(r0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @param {string} json + * @returns {PoolRegistration} + */ + static from_json(json) { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + const ptr0 = passStringToWasm0( + json, + wasm.__wbindgen_malloc, + wasm.__wbindgen_realloc, + ); + const len0 = WASM_VECTOR_LEN; + wasm.poolregistration_from_json(retptr, ptr0, len0); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + if (r2) { + throw takeObject(r1); + } + return PoolRegistration.__wrap(r0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @returns {PoolParams} + */ + pool_params() { + const ret = wasm.poolregistration_pool_params(this.ptr); + return PoolParams.__wrap(ret); + } + /** + * @param {PoolParams} pool_params + * @returns {PoolRegistration} + */ + static new(pool_params) { + _assertClass(pool_params, PoolParams); + const ret = wasm.poolregistration_new(pool_params.ptr); + return PoolRegistration.__wrap(ret); + } + /** + * @param {boolean} update + */ + set_is_update(update) { + wasm.poolregistration_set_is_update(this.ptr, update); + } +} +module.exports.PoolRegistration = PoolRegistration; + +const PoolRetirementFinalization = new FinalizationRegistry((ptr) => + wasm.__wbg_poolretirement_free(ptr) +); +/** */ +class PoolRetirement { + static __wrap(ptr) { + const obj = Object.create(PoolRetirement.prototype); + obj.ptr = ptr; + PoolRetirementFinalization.register(obj, obj.ptr, obj); + return obj; + } + + __destroy_into_raw() { + const ptr = this.ptr; + this.ptr = 0; + PoolRetirementFinalization.unregister(this); + return ptr; + } + + free() { + const ptr = this.__destroy_into_raw(); + wasm.__wbg_poolretirement_free(ptr); + } + /** + * @returns {Uint8Array} + */ + to_bytes() { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + wasm.poolretirement_to_bytes(retptr, this.ptr); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var v0 = getArrayU8FromWasm0(r0, r1).slice(); + wasm.__wbindgen_free(r0, r1 * 1); + return v0; + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @param {Uint8Array} bytes + * @returns {PoolRetirement} + */ + static from_bytes(bytes) { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + const ptr0 = passArray8ToWasm0(bytes, wasm.__wbindgen_malloc); + const len0 = WASM_VECTOR_LEN; + wasm.poolretirement_from_bytes(retptr, ptr0, len0); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + if (r2) { + throw takeObject(r1); + } + return PoolRetirement.__wrap(r0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @returns {string} + */ + to_json() { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + wasm.poolretirement_to_json(retptr, this.ptr); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + var r3 = getInt32Memory0()[retptr / 4 + 3]; + var ptr0 = r0; + var len0 = r1; + if (r3) { + ptr0 = 0; + len0 = 0; + throw takeObject(r2); + } + return getStringFromWasm0(ptr0, len0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + wasm.__wbindgen_free(ptr0, len0); + } + } + /** + * @returns {any} + */ + to_js_value() { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + wasm.poolretirement_to_js_value(retptr, this.ptr); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + if (r2) { + throw takeObject(r1); + } + return takeObject(r0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @param {string} json + * @returns {PoolRetirement} + */ + static from_json(json) { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + const ptr0 = passStringToWasm0( + json, + wasm.__wbindgen_malloc, + wasm.__wbindgen_realloc, + ); + const len0 = WASM_VECTOR_LEN; + wasm.poolretirement_from_json(retptr, ptr0, len0); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + if (r2) { + throw takeObject(r1); + } + return PoolRetirement.__wrap(r0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @returns {Ed25519KeyHash} + */ + pool_keyhash() { + const ret = wasm.poolretirement_pool_keyhash(this.ptr); + return Ed25519KeyHash.__wrap(ret); + } + /** + * @returns {number} + */ + epoch() { + const ret = wasm.poolretirement_epoch(this.ptr); + return ret >>> 0; + } + /** + * @param {Ed25519KeyHash} pool_keyhash + * @param {number} epoch + * @returns {PoolRetirement} + */ + static new(pool_keyhash, epoch) { + _assertClass(pool_keyhash, Ed25519KeyHash); + const ret = wasm.poolretirement_new(pool_keyhash.ptr, epoch); + return PoolRetirement.__wrap(ret); + } +} +module.exports.PoolRetirement = PoolRetirement; + +const PoolVotingThresholdsFinalization = new FinalizationRegistry((ptr) => + wasm.__wbg_poolvotingthresholds_free(ptr) +); +/** */ +class PoolVotingThresholds { + static __wrap(ptr) { + const obj = Object.create(PoolVotingThresholds.prototype); + obj.ptr = ptr; + PoolVotingThresholdsFinalization.register(obj, obj.ptr, obj); + return obj; + } + + __destroy_into_raw() { + const ptr = this.ptr; + this.ptr = 0; + PoolVotingThresholdsFinalization.unregister(this); + return ptr; + } + + free() { + const ptr = this.__destroy_into_raw(); + wasm.__wbg_poolvotingthresholds_free(ptr); + } + /** + * @returns {Uint8Array} + */ + to_bytes() { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + wasm.poolvotingthresholds_to_bytes(retptr, this.ptr); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var v0 = getArrayU8FromWasm0(r0, r1).slice(); + wasm.__wbindgen_free(r0, r1 * 1); + return v0; + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @param {Uint8Array} bytes + * @returns {PoolVotingThresholds} + */ + static from_bytes(bytes) { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + const ptr0 = passArray8ToWasm0(bytes, wasm.__wbindgen_malloc); + const len0 = WASM_VECTOR_LEN; + wasm.poolvotingthresholds_from_bytes(retptr, ptr0, len0); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + if (r2) { + throw takeObject(r1); + } + return PoolVotingThresholds.__wrap(r0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @returns {string} + */ + to_json() { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + wasm.poolvotingthresholds_to_json(retptr, this.ptr); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + var r3 = getInt32Memory0()[retptr / 4 + 3]; + var ptr0 = r0; + var len0 = r1; + if (r3) { + ptr0 = 0; + len0 = 0; + throw takeObject(r2); + } + return getStringFromWasm0(ptr0, len0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + wasm.__wbindgen_free(ptr0, len0); + } + } + /** + * @returns {any} + */ + to_js_value() { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + wasm.poolvotingthresholds_to_js_value(retptr, this.ptr); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + if (r2) { + throw takeObject(r1); + } + return takeObject(r0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @param {string} json + * @returns {PoolVotingThresholds} + */ + static from_json(json) { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + const ptr0 = passStringToWasm0( + json, + wasm.__wbindgen_malloc, + wasm.__wbindgen_realloc, + ); + const len0 = WASM_VECTOR_LEN; + wasm.poolvotingthresholds_from_json(retptr, ptr0, len0); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + if (r2) { + throw takeObject(r1); + } + return PoolVotingThresholds.__wrap(r0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @returns {UnitInterval} + */ + motion_no_confidence() { + const ret = wasm.drepvotingthresholds_motion_no_confidence(this.ptr); + return UnitInterval.__wrap(ret); + } + /** + * @returns {UnitInterval} + */ + committee_normal() { + const ret = wasm.drepvotingthresholds_committee_normal(this.ptr); + return UnitInterval.__wrap(ret); + } + /** + * @returns {UnitInterval} + */ + committee_no_confidence() { + const ret = wasm.drepvotingthresholds_committee_no_confidence(this.ptr); + return UnitInterval.__wrap(ret); + } + /** + * @returns {UnitInterval} + */ + hard_fork_initiation() { + const ret = wasm.drepvotingthresholds_update_constitution(this.ptr); + return UnitInterval.__wrap(ret); + } + /** + * @param {UnitInterval} motion_no_confidence + * @param {UnitInterval} committee_normal + * @param {UnitInterval} committee_no_confidence + * @param {UnitInterval} hard_fork_initiation + * @returns {PoolVotingThresholds} + */ + static new( + motion_no_confidence, + committee_normal, + committee_no_confidence, + hard_fork_initiation, + ) { + _assertClass(motion_no_confidence, UnitInterval); + _assertClass(committee_normal, UnitInterval); + _assertClass(committee_no_confidence, UnitInterval); + _assertClass(hard_fork_initiation, UnitInterval); + const ret = wasm.poolvotingthresholds_new( + motion_no_confidence.ptr, + committee_normal.ptr, + committee_no_confidence.ptr, + hard_fork_initiation.ptr, + ); + return PoolVotingThresholds.__wrap(ret); + } +} +module.exports.PoolVotingThresholds = PoolVotingThresholds; + +const PrivateKeyFinalization = new FinalizationRegistry((ptr) => + wasm.__wbg_privatekey_free(ptr) +); +/** */ +class PrivateKey { + static __wrap(ptr) { + const obj = Object.create(PrivateKey.prototype); + obj.ptr = ptr; + PrivateKeyFinalization.register(obj, obj.ptr, obj); + return obj; + } + + __destroy_into_raw() { + const ptr = this.ptr; + this.ptr = 0; + PrivateKeyFinalization.unregister(this); + return ptr; + } + + free() { + const ptr = this.__destroy_into_raw(); + wasm.__wbg_privatekey_free(ptr); + } + /** + * @returns {PublicKey} + */ + to_public() { + const ret = wasm.privatekey_to_public(this.ptr); + return PublicKey.__wrap(ret); + } + /** + * @returns {PrivateKey} + */ + static generate_ed25519() { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + wasm.privatekey_generate_ed25519(retptr); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + if (r2) { + throw takeObject(r1); + } + return PrivateKey.__wrap(r0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @returns {PrivateKey} + */ + static generate_ed25519extended() { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + wasm.privatekey_generate_ed25519extended(retptr); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + if (r2) { + throw takeObject(r1); + } + return PrivateKey.__wrap(r0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * Get private key from its bech32 representation + * ```javascript + * PrivateKey.from_bech32('ed25519_sk1ahfetf02qwwg4dkq7mgp4a25lx5vh9920cr5wnxmpzz9906qvm8qwvlts0'); + * ``` + * For an extended 25519 key + * ```javascript + * PrivateKey.from_bech32('ed25519e_sk1gqwl4szuwwh6d0yk3nsqcc6xxc3fpvjlevgwvt60df59v8zd8f8prazt8ln3lmz096ux3xvhhvm3ca9wj2yctdh3pnw0szrma07rt5gl748fp'); + * ``` + * @param {string} bech32_str + * @returns {PrivateKey} + */ + static from_bech32(bech32_str) { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + const ptr0 = passStringToWasm0( + bech32_str, + wasm.__wbindgen_malloc, + wasm.__wbindgen_realloc, + ); + const len0 = WASM_VECTOR_LEN; + wasm.privatekey_from_bech32(retptr, ptr0, len0); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + if (r2) { + throw takeObject(r1); + } + return PrivateKey.__wrap(r0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @returns {string} + */ + to_bech32() { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + wasm.privatekey_to_bech32(retptr, this.ptr); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + return getStringFromWasm0(r0, r1); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + wasm.__wbindgen_free(r0, r1); + } + } + /** + * @returns {Uint8Array} + */ + as_bytes() { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + wasm.privatekey_as_bytes(retptr, this.ptr); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var v0 = getArrayU8FromWasm0(r0, r1).slice(); + wasm.__wbindgen_free(r0, r1 * 1); + return v0; + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @param {Uint8Array} bytes + * @returns {PrivateKey} + */ + static from_extended_bytes(bytes) { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + const ptr0 = passArray8ToWasm0(bytes, wasm.__wbindgen_malloc); + const len0 = WASM_VECTOR_LEN; + wasm.privatekey_from_extended_bytes(retptr, ptr0, len0); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + if (r2) { + throw takeObject(r1); + } + return PrivateKey.__wrap(r0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @param {Uint8Array} bytes + * @returns {PrivateKey} + */ + static from_normal_bytes(bytes) { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + const ptr0 = passArray8ToWasm0(bytes, wasm.__wbindgen_malloc); + const len0 = WASM_VECTOR_LEN; + wasm.privatekey_from_normal_bytes(retptr, ptr0, len0); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + if (r2) { + throw takeObject(r1); + } + return PrivateKey.__wrap(r0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @param {Uint8Array} message + * @returns {Ed25519Signature} + */ + sign(message) { + const ptr0 = passArray8ToWasm0(message, wasm.__wbindgen_malloc); + const len0 = WASM_VECTOR_LEN; + const ret = wasm.privatekey_sign(this.ptr, ptr0, len0); + return Ed25519Signature.__wrap(ret); + } + /** + * @param {Uint8Array} bytes + * @returns {PrivateKey} + */ + static from_bytes(bytes) { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + const ptr0 = passArray8ToWasm0(bytes, wasm.__wbindgen_malloc); + const len0 = WASM_VECTOR_LEN; + wasm.privatekey_from_bytes(retptr, ptr0, len0); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + if (r2) { + throw takeObject(r1); + } + return PrivateKey.__wrap(r0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @returns {Uint8Array} + */ + to_bytes() { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + wasm.privatekey_to_bytes(retptr, this.ptr); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var v0 = getArrayU8FromWasm0(r0, r1).slice(); + wasm.__wbindgen_free(r0, r1 * 1); + return v0; + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } +} +module.exports.PrivateKey = PrivateKey; + +const ProposalProcedureFinalization = new FinalizationRegistry((ptr) => + wasm.__wbg_proposalprocedure_free(ptr) +); +/** */ +class ProposalProcedure { + static __wrap(ptr) { + const obj = Object.create(ProposalProcedure.prototype); + obj.ptr = ptr; + ProposalProcedureFinalization.register(obj, obj.ptr, obj); + return obj; + } + + __destroy_into_raw() { + const ptr = this.ptr; + this.ptr = 0; + ProposalProcedureFinalization.unregister(this); + return ptr; + } + + free() { + const ptr = this.__destroy_into_raw(); + wasm.__wbg_proposalprocedure_free(ptr); + } + /** + * @returns {Uint8Array} + */ + to_bytes() { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + wasm.proposalprocedure_to_bytes(retptr, this.ptr); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var v0 = getArrayU8FromWasm0(r0, r1).slice(); + wasm.__wbindgen_free(r0, r1 * 1); + return v0; + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @param {Uint8Array} bytes + * @returns {ProposalProcedure} + */ + static from_bytes(bytes) { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + const ptr0 = passArray8ToWasm0(bytes, wasm.__wbindgen_malloc); + const len0 = WASM_VECTOR_LEN; + wasm.proposalprocedure_from_bytes(retptr, ptr0, len0); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + if (r2) { + throw takeObject(r1); + } + return ProposalProcedure.__wrap(r0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @returns {string} + */ + to_json() { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + wasm.proposalprocedure_to_json(retptr, this.ptr); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + var r3 = getInt32Memory0()[retptr / 4 + 3]; + var ptr0 = r0; + var len0 = r1; + if (r3) { + ptr0 = 0; + len0 = 0; + throw takeObject(r2); + } + return getStringFromWasm0(ptr0, len0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + wasm.__wbindgen_free(ptr0, len0); + } + } + /** + * @returns {any} + */ + to_js_value() { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + wasm.proposalprocedure_to_js_value(retptr, this.ptr); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + if (r2) { + throw takeObject(r1); + } + return takeObject(r0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @param {string} json + * @returns {ProposalProcedure} + */ + static from_json(json) { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + const ptr0 = passStringToWasm0( + json, + wasm.__wbindgen_malloc, + wasm.__wbindgen_realloc, + ); + const len0 = WASM_VECTOR_LEN; + wasm.proposalprocedure_from_json(retptr, ptr0, len0); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + if (r2) { + throw takeObject(r1); + } + return ProposalProcedure.__wrap(r0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @returns {BigNum} + */ + deposit() { + const ret = wasm.proposalprocedure_deposit(this.ptr); + return BigNum.__wrap(ret); + } + /** + * @returns {ScriptHash} + */ + hash() { + const ret = wasm.proposalprocedure_hash(this.ptr); + return ScriptHash.__wrap(ret); + } + /** + * @returns {GovernanceAction} + */ + governance_action() { + const ret = wasm.proposalprocedure_governance_action(this.ptr); + return GovernanceAction.__wrap(ret); + } + /** + * @returns {Anchor} + */ + anchor() { + const ret = wasm.proposalprocedure_anchor(this.ptr); + return Anchor.__wrap(ret); + } + /** + * @param {BigNum} deposit + * @param {ScriptHash} hash + * @param {GovernanceAction} governance_action + * @param {Anchor} anchor + * @returns {ProposalProcedure} + */ + static new(deposit, hash, governance_action, anchor) { + _assertClass(deposit, BigNum); + _assertClass(hash, ScriptHash); + _assertClass(governance_action, GovernanceAction); + _assertClass(anchor, Anchor); + const ret = wasm.proposalprocedure_new( + deposit.ptr, + hash.ptr, + governance_action.ptr, + anchor.ptr, + ); + return ProposalProcedure.__wrap(ret); + } +} +module.exports.ProposalProcedure = ProposalProcedure; + +const ProposalProceduresFinalization = new FinalizationRegistry((ptr) => + wasm.__wbg_proposalprocedures_free(ptr) +); +/** */ +class ProposalProcedures { + static __wrap(ptr) { + const obj = Object.create(ProposalProcedures.prototype); + obj.ptr = ptr; + ProposalProceduresFinalization.register(obj, obj.ptr, obj); + return obj; + } + + __destroy_into_raw() { + const ptr = this.ptr; + this.ptr = 0; + ProposalProceduresFinalization.unregister(this); + return ptr; + } + + free() { + const ptr = this.__destroy_into_raw(); + wasm.__wbg_proposalprocedures_free(ptr); + } + /** + * @returns {Uint8Array} + */ + to_bytes() { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + wasm.proposalprocedures_to_bytes(retptr, this.ptr); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var v0 = getArrayU8FromWasm0(r0, r1).slice(); + wasm.__wbindgen_free(r0, r1 * 1); + return v0; + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @param {Uint8Array} bytes + * @returns {ProposalProcedures} + */ + static from_bytes(bytes) { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + const ptr0 = passArray8ToWasm0(bytes, wasm.__wbindgen_malloc); + const len0 = WASM_VECTOR_LEN; + wasm.proposalprocedures_from_bytes(retptr, ptr0, len0); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + if (r2) { + throw takeObject(r1); + } + return ProposalProcedures.__wrap(r0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @returns {ProposalProcedures} + */ + static new() { + const ret = wasm.certificates_new(); + return ProposalProcedures.__wrap(ret); + } + /** + * @returns {number} + */ + len() { + const ret = wasm.assetnames_len(this.ptr); + return ret >>> 0; + } + /** + * @param {number} index + * @returns {ProposalProcedure} + */ + get(index) { + const ret = wasm.proposalprocedures_get(this.ptr, index); + return ProposalProcedure.__wrap(ret); + } + /** + * @param {ProposalProcedure} elem + */ + add(elem) { + _assertClass(elem, ProposalProcedure); + wasm.proposalprocedures_add(this.ptr, elem.ptr); + } +} +module.exports.ProposalProcedures = ProposalProcedures; + +const ProposedProtocolParameterUpdatesFinalization = new FinalizationRegistry( + (ptr) => wasm.__wbg_proposedprotocolparameterupdates_free(ptr) +); +/** */ +class ProposedProtocolParameterUpdates { + static __wrap(ptr) { + const obj = Object.create(ProposedProtocolParameterUpdates.prototype); + obj.ptr = ptr; + ProposedProtocolParameterUpdatesFinalization.register(obj, obj.ptr, obj); + return obj; + } + + __destroy_into_raw() { + const ptr = this.ptr; + this.ptr = 0; + ProposedProtocolParameterUpdatesFinalization.unregister(this); + return ptr; + } + + free() { + const ptr = this.__destroy_into_raw(); + wasm.__wbg_proposedprotocolparameterupdates_free(ptr); + } + /** + * @returns {Uint8Array} + */ + to_bytes() { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + wasm.proposedprotocolparameterupdates_to_bytes(retptr, this.ptr); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var v0 = getArrayU8FromWasm0(r0, r1).slice(); + wasm.__wbindgen_free(r0, r1 * 1); + return v0; + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @param {Uint8Array} bytes + * @returns {ProposedProtocolParameterUpdates} + */ + static from_bytes(bytes) { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + const ptr0 = passArray8ToWasm0(bytes, wasm.__wbindgen_malloc); + const len0 = WASM_VECTOR_LEN; + wasm.proposedprotocolparameterupdates_from_bytes(retptr, ptr0, len0); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + if (r2) { + throw takeObject(r1); + } + return ProposedProtocolParameterUpdates.__wrap(r0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @returns {string} + */ + to_json() { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + wasm.proposedprotocolparameterupdates_to_json(retptr, this.ptr); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + var r3 = getInt32Memory0()[retptr / 4 + 3]; + var ptr0 = r0; + var len0 = r1; + if (r3) { + ptr0 = 0; + len0 = 0; + throw takeObject(r2); + } + return getStringFromWasm0(ptr0, len0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + wasm.__wbindgen_free(ptr0, len0); + } + } + /** + * @returns {any} + */ + to_js_value() { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + wasm.proposedprotocolparameterupdates_to_js_value(retptr, this.ptr); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + if (r2) { + throw takeObject(r1); + } + return takeObject(r0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @param {string} json + * @returns {ProposedProtocolParameterUpdates} + */ + static from_json(json) { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + const ptr0 = passStringToWasm0( + json, + wasm.__wbindgen_malloc, + wasm.__wbindgen_realloc, + ); + const len0 = WASM_VECTOR_LEN; + wasm.proposedprotocolparameterupdates_from_json(retptr, ptr0, len0); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + if (r2) { + throw takeObject(r1); + } + return ProposedProtocolParameterUpdates.__wrap(r0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @returns {ProposedProtocolParameterUpdates} + */ + static new() { + const ret = wasm.auxiliarydataset_new(); + return ProposedProtocolParameterUpdates.__wrap(ret); + } + /** + * @returns {number} + */ + len() { + const ret = wasm.auxiliarydataset_len(this.ptr); + return ret >>> 0; + } + /** + * @param {GenesisHash} key + * @param {ProtocolParamUpdate} value + * @returns {ProtocolParamUpdate | undefined} + */ + insert(key, value) { + _assertClass(key, GenesisHash); + _assertClass(value, ProtocolParamUpdate); + const ret = wasm.proposedprotocolparameterupdates_insert( + this.ptr, + key.ptr, + value.ptr, + ); + return ret === 0 ? undefined : ProtocolParamUpdate.__wrap(ret); + } + /** + * @param {GenesisHash} key + * @returns {ProtocolParamUpdate | undefined} + */ + get(key) { + _assertClass(key, GenesisHash); + const ret = wasm.proposedprotocolparameterupdates_get(this.ptr, key.ptr); + return ret === 0 ? undefined : ProtocolParamUpdate.__wrap(ret); + } + /** + * @returns {GenesisHashes} + */ + keys() { + const ret = wasm.proposedprotocolparameterupdates_keys(this.ptr); + return GenesisHashes.__wrap(ret); + } +} +module.exports.ProposedProtocolParameterUpdates = + ProposedProtocolParameterUpdates; + +const ProtocolParamUpdateFinalization = new FinalizationRegistry((ptr) => + wasm.__wbg_protocolparamupdate_free(ptr) +); +/** */ +class ProtocolParamUpdate { + static __wrap(ptr) { + const obj = Object.create(ProtocolParamUpdate.prototype); + obj.ptr = ptr; + ProtocolParamUpdateFinalization.register(obj, obj.ptr, obj); + return obj; + } + + __destroy_into_raw() { + const ptr = this.ptr; + this.ptr = 0; + ProtocolParamUpdateFinalization.unregister(this); + return ptr; + } + + free() { + const ptr = this.__destroy_into_raw(); + wasm.__wbg_protocolparamupdate_free(ptr); + } + /** + * @returns {Uint8Array} + */ + to_bytes() { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + wasm.protocolparamupdate_to_bytes(retptr, this.ptr); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var v0 = getArrayU8FromWasm0(r0, r1).slice(); + wasm.__wbindgen_free(r0, r1 * 1); + return v0; + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @param {Uint8Array} bytes + * @returns {ProtocolParamUpdate} + */ + static from_bytes(bytes) { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + const ptr0 = passArray8ToWasm0(bytes, wasm.__wbindgen_malloc); + const len0 = WASM_VECTOR_LEN; + wasm.protocolparamupdate_from_bytes(retptr, ptr0, len0); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + if (r2) { + throw takeObject(r1); + } + return ProtocolParamUpdate.__wrap(r0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @returns {string} + */ + to_json() { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + wasm.protocolparamupdate_to_json(retptr, this.ptr); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + var r3 = getInt32Memory0()[retptr / 4 + 3]; + var ptr0 = r0; + var len0 = r1; + if (r3) { + ptr0 = 0; + len0 = 0; + throw takeObject(r2); + } + return getStringFromWasm0(ptr0, len0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + wasm.__wbindgen_free(ptr0, len0); + } + } + /** + * @returns {any} + */ + to_js_value() { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + wasm.protocolparamupdate_to_js_value(retptr, this.ptr); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + if (r2) { + throw takeObject(r1); + } + return takeObject(r0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @param {string} json + * @returns {ProtocolParamUpdate} + */ + static from_json(json) { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + const ptr0 = passStringToWasm0( + json, + wasm.__wbindgen_malloc, + wasm.__wbindgen_realloc, + ); + const len0 = WASM_VECTOR_LEN; + wasm.protocolparamupdate_from_json(retptr, ptr0, len0); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + if (r2) { + throw takeObject(r1); + } + return ProtocolParamUpdate.__wrap(r0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @param {BigNum} minfee_a + */ + set_minfee_a(minfee_a) { + _assertClass(minfee_a, BigNum); + wasm.protocolparamupdate_set_minfee_a(this.ptr, minfee_a.ptr); + } + /** + * @returns {BigNum | undefined} + */ + minfee_a() { + const ret = wasm.protocolparamupdate_minfee_a(this.ptr); + return ret === 0 ? undefined : BigNum.__wrap(ret); + } + /** + * @param {BigNum} minfee_b + */ + set_minfee_b(minfee_b) { + _assertClass(minfee_b, BigNum); + wasm.protocolparamupdate_set_minfee_b(this.ptr, minfee_b.ptr); + } + /** + * @returns {BigNum | undefined} + */ + minfee_b() { + const ret = wasm.protocolparamupdate_minfee_b(this.ptr); + return ret === 0 ? undefined : BigNum.__wrap(ret); + } + /** + * @param {number} max_block_body_size + */ + set_max_block_body_size(max_block_body_size) { + wasm.protocolparamupdate_set_max_block_body_size( + this.ptr, + max_block_body_size, + ); + } + /** + * @returns {number | undefined} + */ + max_block_body_size() { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + wasm.protocolparamupdate_max_block_body_size(retptr, this.ptr); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + return r0 === 0 ? undefined : r1 >>> 0; + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @param {number} max_tx_size + */ + set_max_tx_size(max_tx_size) { + wasm.protocolparamupdate_set_max_tx_size(this.ptr, max_tx_size); + } + /** + * @returns {number | undefined} + */ + max_tx_size() { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + wasm.protocolparamupdate_max_tx_size(retptr, this.ptr); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + return r0 === 0 ? undefined : r1 >>> 0; + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @param {number} max_block_header_size + */ + set_max_block_header_size(max_block_header_size) { + wasm.protocolparamupdate_set_max_block_header_size( + this.ptr, + max_block_header_size, + ); + } + /** + * @returns {number | undefined} + */ + max_block_header_size() { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + wasm.protocolparamupdate_max_block_header_size(retptr, this.ptr); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + return r0 === 0 ? undefined : r1 >>> 0; + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @param {BigNum} key_deposit + */ + set_key_deposit(key_deposit) { + _assertClass(key_deposit, BigNum); + wasm.protocolparamupdate_set_key_deposit(this.ptr, key_deposit.ptr); + } + /** + * @returns {BigNum | undefined} + */ + key_deposit() { + const ret = wasm.protocolparamupdate_key_deposit(this.ptr); + return ret === 0 ? undefined : BigNum.__wrap(ret); + } + /** + * @param {BigNum} pool_deposit + */ + set_pool_deposit(pool_deposit) { + _assertClass(pool_deposit, BigNum); + wasm.protocolparamupdate_set_pool_deposit(this.ptr, pool_deposit.ptr); + } + /** + * @returns {BigNum | undefined} + */ + pool_deposit() { + const ret = wasm.protocolparamupdate_pool_deposit(this.ptr); + return ret === 0 ? undefined : BigNum.__wrap(ret); + } + /** + * @param {number} max_epoch + */ + set_max_epoch(max_epoch) { + wasm.protocolparamupdate_set_max_epoch(this.ptr, max_epoch); + } + /** + * @returns {number | undefined} + */ + max_epoch() { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + wasm.protocolparamupdate_max_epoch(retptr, this.ptr); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + return r0 === 0 ? undefined : r1 >>> 0; + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @param {number} n_opt + */ + set_n_opt(n_opt) { + wasm.protocolparamupdate_set_n_opt(this.ptr, n_opt); + } + /** + * @returns {number | undefined} + */ + n_opt() { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + wasm.protocolparamupdate_n_opt(retptr, this.ptr); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + return r0 === 0 ? undefined : r1 >>> 0; + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @param {UnitInterval} pool_pledge_influence + */ + set_pool_pledge_influence(pool_pledge_influence) { + _assertClass(pool_pledge_influence, UnitInterval); + wasm.protocolparamupdate_set_pool_pledge_influence( + this.ptr, + pool_pledge_influence.ptr, + ); + } + /** + * @returns {UnitInterval | undefined} + */ + pool_pledge_influence() { + const ret = wasm.protocolparamupdate_pool_pledge_influence(this.ptr); + return ret === 0 ? undefined : UnitInterval.__wrap(ret); + } + /** + * @param {UnitInterval} expansion_rate + */ + set_expansion_rate(expansion_rate) { + _assertClass(expansion_rate, UnitInterval); + wasm.protocolparamupdate_set_expansion_rate(this.ptr, expansion_rate.ptr); + } + /** + * @returns {UnitInterval | undefined} + */ + expansion_rate() { + const ret = wasm.protocolparamupdate_expansion_rate(this.ptr); + return ret === 0 ? undefined : UnitInterval.__wrap(ret); + } + /** + * @param {UnitInterval} treasury_growth_rate + */ + set_treasury_growth_rate(treasury_growth_rate) { + _assertClass(treasury_growth_rate, UnitInterval); + wasm.protocolparamupdate_set_treasury_growth_rate( + this.ptr, + treasury_growth_rate.ptr, + ); + } + /** + * @returns {UnitInterval | undefined} + */ + treasury_growth_rate() { + const ret = wasm.protocolparamupdate_treasury_growth_rate(this.ptr); + return ret === 0 ? undefined : UnitInterval.__wrap(ret); + } + /** + * @param {UnitInterval} d + */ + set_d(d) { + _assertClass(d, UnitInterval); + wasm.protocolparamupdate_set_d(this.ptr, d.ptr); + } + /** + * @returns {UnitInterval | undefined} + */ + d() { + const ret = wasm.protocolparamupdate_d(this.ptr); + return ret === 0 ? undefined : UnitInterval.__wrap(ret); + } + /** + * @param {Nonce} extra_entropy + */ + set_extra_entropy(extra_entropy) { + _assertClass(extra_entropy, Nonce); + wasm.protocolparamupdate_set_extra_entropy(this.ptr, extra_entropy.ptr); + } + /** + * @returns {Nonce | undefined} + */ + extra_entropy() { + const ret = wasm.protocolparamupdate_extra_entropy(this.ptr); + return ret === 0 ? undefined : Nonce.__wrap(ret); + } + /** + * @param {ProtocolVersion} protocol_version + */ + set_protocol_version(protocol_version) { + _assertClass(protocol_version, ProtocolVersion); + wasm.protocolparamupdate_set_protocol_version( + this.ptr, + protocol_version.ptr, + ); + } + /** + * @returns {ProtocolVersion | undefined} + */ + protocol_version() { + const ret = wasm.protocolparamupdate_protocol_version(this.ptr); + return ret === 0 ? undefined : ProtocolVersion.__wrap(ret); + } + /** + * @param {BigNum} min_pool_cost + */ + set_min_pool_cost(min_pool_cost) { + _assertClass(min_pool_cost, BigNum); + wasm.protocolparamupdate_set_min_pool_cost(this.ptr, min_pool_cost.ptr); + } + /** + * @returns {BigNum | undefined} + */ + min_pool_cost() { + const ret = wasm.protocolparamupdate_min_pool_cost(this.ptr); + return ret === 0 ? undefined : BigNum.__wrap(ret); + } + /** + * @param {BigNum} ada_per_utxo_byte + */ + set_ada_per_utxo_byte(ada_per_utxo_byte) { + _assertClass(ada_per_utxo_byte, BigNum); + wasm.protocolparamupdate_set_ada_per_utxo_byte( + this.ptr, + ada_per_utxo_byte.ptr, + ); + } + /** + * @returns {BigNum | undefined} + */ + ada_per_utxo_byte() { + const ret = wasm.protocolparamupdate_ada_per_utxo_byte(this.ptr); + return ret === 0 ? undefined : BigNum.__wrap(ret); + } + /** + * @param {Costmdls} cost_models + */ + set_cost_models(cost_models) { + _assertClass(cost_models, Costmdls); + wasm.protocolparamupdate_set_cost_models(this.ptr, cost_models.ptr); + } + /** + * @returns {Costmdls | undefined} + */ + cost_models() { + const ret = wasm.protocolparamupdate_cost_models(this.ptr); + return ret === 0 ? undefined : Costmdls.__wrap(ret); + } + /** + * @param {ExUnitPrices} execution_costs + */ + set_execution_costs(execution_costs) { + _assertClass(execution_costs, ExUnitPrices); + wasm.protocolparamupdate_set_execution_costs(this.ptr, execution_costs.ptr); + } + /** + * @returns {ExUnitPrices | undefined} + */ + execution_costs() { + const ret = wasm.protocolparamupdate_execution_costs(this.ptr); + return ret === 0 ? undefined : ExUnitPrices.__wrap(ret); + } + /** + * @param {ExUnits} max_tx_ex_units + */ + set_max_tx_ex_units(max_tx_ex_units) { + _assertClass(max_tx_ex_units, ExUnits); + wasm.protocolparamupdate_set_max_tx_ex_units(this.ptr, max_tx_ex_units.ptr); + } + /** + * @returns {ExUnits | undefined} + */ + max_tx_ex_units() { + const ret = wasm.protocolparamupdate_max_tx_ex_units(this.ptr); + return ret === 0 ? undefined : ExUnits.__wrap(ret); + } + /** + * @param {ExUnits} max_block_ex_units + */ + set_max_block_ex_units(max_block_ex_units) { + _assertClass(max_block_ex_units, ExUnits); + wasm.protocolparamupdate_set_max_block_ex_units( + this.ptr, + max_block_ex_units.ptr, + ); + } + /** + * @returns {ExUnits | undefined} + */ + max_block_ex_units() { + const ret = wasm.protocolparamupdate_max_block_ex_units(this.ptr); + return ret === 0 ? undefined : ExUnits.__wrap(ret); + } + /** + * @param {number} max_value_size + */ + set_max_value_size(max_value_size) { + wasm.protocolparamupdate_set_max_value_size(this.ptr, max_value_size); + } + /** + * @returns {number | undefined} + */ + max_value_size() { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + wasm.protocolparamupdate_max_value_size(retptr, this.ptr); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + return r0 === 0 ? undefined : r1 >>> 0; + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @param {number} collateral_percentage + */ + set_collateral_percentage(collateral_percentage) { + wasm.protocolparamupdate_set_collateral_percentage( + this.ptr, + collateral_percentage, + ); + } + /** + * @returns {number | undefined} + */ + collateral_percentage() { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + wasm.protocolparamupdate_collateral_percentage(retptr, this.ptr); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + return r0 === 0 ? undefined : r1 >>> 0; + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @param {number} max_collateral_inputs + */ + set_max_collateral_inputs(max_collateral_inputs) { + wasm.protocolparamupdate_set_max_collateral_inputs( + this.ptr, + max_collateral_inputs, + ); + } + /** + * @returns {number | undefined} + */ + max_collateral_inputs() { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + wasm.protocolparamupdate_max_collateral_inputs(retptr, this.ptr); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + return r0 === 0 ? undefined : r1 >>> 0; + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @param {PoolVotingThresholds} pool_voting_thresholds + */ + set_pool_voting_thresholds(pool_voting_thresholds) { + _assertClass(pool_voting_thresholds, PoolVotingThresholds); + var ptr0 = pool_voting_thresholds.__destroy_into_raw(); + wasm.protocolparamupdate_set_pool_voting_thresholds(this.ptr, ptr0); + } + /** + * @returns {PoolVotingThresholds | undefined} + */ + pool_voting_thresholds() { + const ret = wasm.protocolparamupdate_pool_voting_thresholds(this.ptr); + return ret === 0 ? undefined : PoolVotingThresholds.__wrap(ret); + } + /** + * @param {DrepVotingThresholds} drep_voting_thresholds + */ + set_drep_voting_thresholds(drep_voting_thresholds) { + _assertClass(drep_voting_thresholds, DrepVotingThresholds); + var ptr0 = drep_voting_thresholds.__destroy_into_raw(); + wasm.protocolparamupdate_set_drep_voting_thresholds(this.ptr, ptr0); + } + /** + * @returns {DrepVotingThresholds | undefined} + */ + drep_voting_thresholds() { + const ret = wasm.protocolparamupdate_drep_voting_thresholds(this.ptr); + return ret === 0 ? undefined : DrepVotingThresholds.__wrap(ret); + } + /** + * @param {BigNum} min_committee_size + */ + set_min_committee_size(min_committee_size) { + _assertClass(min_committee_size, BigNum); + var ptr0 = min_committee_size.__destroy_into_raw(); + wasm.protocolparamupdate_set_min_committee_size(this.ptr, ptr0); + } + /** + * @returns {BigNum | undefined} + */ + min_committee_size() { + const ret = wasm.protocolparamupdate_min_committee_size(this.ptr); + return ret === 0 ? undefined : BigNum.__wrap(ret); + } + /** + * @param {BigNum} committee_term_limit + */ + set_committee_term_limit(committee_term_limit) { + _assertClass(committee_term_limit, BigNum); + var ptr0 = committee_term_limit.__destroy_into_raw(); + wasm.protocolparamupdate_set_committee_term_limit(this.ptr, ptr0); + } + /** + * @returns {BigNum | undefined} + */ + committee_term_limit() { + const ret = wasm.protocolparamupdate_committee_term_limit(this.ptr); + return ret === 0 ? undefined : BigNum.__wrap(ret); + } + /** + * @param {BigNum} governance_action_expiration + */ + set_governance_action_expiration(governance_action_expiration) { + _assertClass(governance_action_expiration, BigNum); + var ptr0 = governance_action_expiration.__destroy_into_raw(); + wasm.protocolparamupdate_set_governance_action_expiration(this.ptr, ptr0); + } + /** + * @returns {BigNum | undefined} + */ + governance_action_expiration() { + const ret = wasm.protocolparamupdate_governance_action_expiration(this.ptr); + return ret === 0 ? undefined : BigNum.__wrap(ret); + } + /** + * @param {BigNum} governance_action_deposit + */ + set_governance_action_deposit(governance_action_deposit) { + _assertClass(governance_action_deposit, BigNum); + var ptr0 = governance_action_deposit.__destroy_into_raw(); + wasm.protocolparamupdate_set_governance_action_deposit(this.ptr, ptr0); + } + /** + * @returns {BigNum | undefined} + */ + governance_action_deposit() { + const ret = wasm.protocolparamupdate_governance_action_deposit(this.ptr); + return ret === 0 ? undefined : BigNum.__wrap(ret); + } + /** + * @param {BigNum} drep_deposit + */ + set_drep_deposit(drep_deposit) { + _assertClass(drep_deposit, BigNum); + var ptr0 = drep_deposit.__destroy_into_raw(); + wasm.protocolparamupdate_set_drep_deposit(this.ptr, ptr0); + } + /** + * @returns {BigNum | undefined} + */ + drep_deposit() { + const ret = wasm.protocolparamupdate_drep_deposit(this.ptr); + return ret === 0 ? undefined : BigNum.__wrap(ret); + } + /** + * @param {number} drep_inactivity_period + */ + set_drep_inactivity_period(drep_inactivity_period) { + wasm.protocolparamupdate_set_drep_inactivity_period( + this.ptr, + drep_inactivity_period, + ); + } + /** + * @returns {number | undefined} + */ + drep_inactivity_period() { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + wasm.protocolparamupdate_drep_inactivity_period(retptr, this.ptr); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + return r0 === 0 ? undefined : r1 >>> 0; + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @returns {ProtocolParamUpdate} + */ + static new() { + const ret = wasm.protocolparamupdate_new(); + return ProtocolParamUpdate.__wrap(ret); + } +} +module.exports.ProtocolParamUpdate = ProtocolParamUpdate; + +const ProtocolVersionFinalization = new FinalizationRegistry((ptr) => + wasm.__wbg_protocolversion_free(ptr) +); +/** */ +class ProtocolVersion { + static __wrap(ptr) { + const obj = Object.create(ProtocolVersion.prototype); + obj.ptr = ptr; + ProtocolVersionFinalization.register(obj, obj.ptr, obj); + return obj; + } + + __destroy_into_raw() { + const ptr = this.ptr; + this.ptr = 0; + ProtocolVersionFinalization.unregister(this); + return ptr; + } + + free() { + const ptr = this.__destroy_into_raw(); + wasm.__wbg_protocolversion_free(ptr); + } + /** + * @returns {Uint8Array} + */ + to_bytes() { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + wasm.protocolversion_to_bytes(retptr, this.ptr); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var v0 = getArrayU8FromWasm0(r0, r1).slice(); + wasm.__wbindgen_free(r0, r1 * 1); + return v0; + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @param {Uint8Array} bytes + * @returns {ProtocolVersion} + */ + static from_bytes(bytes) { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + const ptr0 = passArray8ToWasm0(bytes, wasm.__wbindgen_malloc); + const len0 = WASM_VECTOR_LEN; + wasm.protocolversion_from_bytes(retptr, ptr0, len0); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + if (r2) { + throw takeObject(r1); + } + return ProtocolVersion.__wrap(r0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @returns {string} + */ + to_json() { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + wasm.protocolversion_to_json(retptr, this.ptr); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + var r3 = getInt32Memory0()[retptr / 4 + 3]; + var ptr0 = r0; + var len0 = r1; + if (r3) { + ptr0 = 0; + len0 = 0; + throw takeObject(r2); + } + return getStringFromWasm0(ptr0, len0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + wasm.__wbindgen_free(ptr0, len0); + } + } + /** + * @returns {any} + */ + to_js_value() { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + wasm.protocolversion_to_js_value(retptr, this.ptr); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + if (r2) { + throw takeObject(r1); + } + return takeObject(r0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @param {string} json + * @returns {ProtocolVersion} + */ + static from_json(json) { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + const ptr0 = passStringToWasm0( + json, + wasm.__wbindgen_malloc, + wasm.__wbindgen_realloc, + ); + const len0 = WASM_VECTOR_LEN; + wasm.protocolversion_from_json(retptr, ptr0, len0); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + if (r2) { + throw takeObject(r1); + } + return ProtocolVersion.__wrap(r0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @returns {number} + */ + major() { + const ret = wasm.networkinfo_protocol_magic(this.ptr); + return ret >>> 0; + } + /** + * @returns {number} + */ + minor() { + const ret = wasm.protocolversion_minor(this.ptr); + return ret >>> 0; + } + /** + * @param {number} major + * @param {number} minor + * @returns {ProtocolVersion} + */ + static new(major, minor) { + const ret = wasm.protocolversion_new(major, minor); + return ProtocolVersion.__wrap(ret); + } +} +module.exports.ProtocolVersion = ProtocolVersion; + +const PublicKeyFinalization = new FinalizationRegistry((ptr) => + wasm.__wbg_publickey_free(ptr) +); +/** + * ED25519 key used as public key + */ +class PublicKey { + static __wrap(ptr) { + const obj = Object.create(PublicKey.prototype); + obj.ptr = ptr; + PublicKeyFinalization.register(obj, obj.ptr, obj); + return obj; + } + + __destroy_into_raw() { + const ptr = this.ptr; + this.ptr = 0; + PublicKeyFinalization.unregister(this); + return ptr; + } + + free() { + const ptr = this.__destroy_into_raw(); + wasm.__wbg_publickey_free(ptr); + } + /** + * Get public key from its bech32 representation + * Example: + * ```javascript + * const pkey = PublicKey.from_bech32('ed25519_pk1dgaagyh470y66p899txcl3r0jaeaxu6yd7z2dxyk55qcycdml8gszkxze2'); + * ``` + * @param {string} bech32_str + * @returns {PublicKey} + */ + static from_bech32(bech32_str) { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + const ptr0 = passStringToWasm0( + bech32_str, + wasm.__wbindgen_malloc, + wasm.__wbindgen_realloc, + ); + const len0 = WASM_VECTOR_LEN; + wasm.publickey_from_bech32(retptr, ptr0, len0); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + if (r2) { + throw takeObject(r1); + } + return PublicKey.__wrap(r0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @returns {string} + */ + to_bech32() { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + wasm.publickey_to_bech32(retptr, this.ptr); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + return getStringFromWasm0(r0, r1); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + wasm.__wbindgen_free(r0, r1); + } + } + /** + * @returns {Uint8Array} + */ + as_bytes() { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + wasm.auxiliarydatahash_to_bytes(retptr, this.ptr); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var v0 = getArrayU8FromWasm0(r0, r1).slice(); + wasm.__wbindgen_free(r0, r1 * 1); + return v0; + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @param {Uint8Array} bytes + * @returns {PublicKey} + */ + static from_bytes(bytes) { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + const ptr0 = passArray8ToWasm0(bytes, wasm.__wbindgen_malloc); + const len0 = WASM_VECTOR_LEN; + wasm.publickey_from_bytes(retptr, ptr0, len0); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + if (r2) { + throw takeObject(r1); + } + return PublicKey.__wrap(r0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @param {Uint8Array} data + * @param {Ed25519Signature} signature + * @returns {boolean} + */ + verify(data, signature) { + const ptr0 = passArray8ToWasm0(data, wasm.__wbindgen_malloc); + const len0 = WASM_VECTOR_LEN; + _assertClass(signature, Ed25519Signature); + const ret = wasm.publickey_verify(this.ptr, ptr0, len0, signature.ptr); + return ret !== 0; + } + /** + * @returns {Ed25519KeyHash} + */ + hash() { + const ret = wasm.publickey_hash(this.ptr); + return Ed25519KeyHash.__wrap(ret); + } +} +module.exports.PublicKey = PublicKey; + +const PublicKeysFinalization = new FinalizationRegistry((ptr) => + wasm.__wbg_publickeys_free(ptr) +); +/** */ +class PublicKeys { + static __wrap(ptr) { + const obj = Object.create(PublicKeys.prototype); + obj.ptr = ptr; + PublicKeysFinalization.register(obj, obj.ptr, obj); + return obj; + } + + __destroy_into_raw() { + const ptr = this.ptr; + this.ptr = 0; + PublicKeysFinalization.unregister(this); + return ptr; + } + + free() { + const ptr = this.__destroy_into_raw(); + wasm.__wbg_publickeys_free(ptr); + } + /** */ + constructor() { + const ret = wasm.ed25519keyhashes_new(); + return PublicKeys.__wrap(ret); + } + /** + * @returns {number} + */ + size() { + const ret = wasm.assetnames_len(this.ptr); + return ret >>> 0; + } + /** + * @param {number} index + * @returns {PublicKey} + */ + get(index) { + const ret = wasm.publickeys_get(this.ptr, index); + return PublicKey.__wrap(ret); + } + /** + * @param {PublicKey} key + */ + add(key) { + _assertClass(key, PublicKey); + wasm.publickeys_add(this.ptr, key.ptr); + } +} +module.exports.PublicKeys = PublicKeys; + +const RedeemerFinalization = new FinalizationRegistry((ptr) => + wasm.__wbg_redeemer_free(ptr) +); +/** */ +class Redeemer { + static __wrap(ptr) { + const obj = Object.create(Redeemer.prototype); + obj.ptr = ptr; + RedeemerFinalization.register(obj, obj.ptr, obj); + return obj; + } + + __destroy_into_raw() { + const ptr = this.ptr; + this.ptr = 0; + RedeemerFinalization.unregister(this); + return ptr; + } + + free() { + const ptr = this.__destroy_into_raw(); + wasm.__wbg_redeemer_free(ptr); + } + /** + * @returns {Uint8Array} + */ + to_bytes() { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + wasm.redeemer_to_bytes(retptr, this.ptr); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var v0 = getArrayU8FromWasm0(r0, r1).slice(); + wasm.__wbindgen_free(r0, r1 * 1); + return v0; + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @param {Uint8Array} bytes + * @returns {Redeemer} + */ + static from_bytes(bytes) { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + const ptr0 = passArray8ToWasm0(bytes, wasm.__wbindgen_malloc); + const len0 = WASM_VECTOR_LEN; + wasm.redeemer_from_bytes(retptr, ptr0, len0); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + if (r2) { + throw takeObject(r1); + } + return Redeemer.__wrap(r0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @returns {RedeemerTag} + */ + tag() { + const ret = wasm.redeemer_tag(this.ptr); + return RedeemerTag.__wrap(ret); + } + /** + * @returns {BigNum} + */ + index() { + const ret = wasm.poolparams_cost(this.ptr); + return BigNum.__wrap(ret); + } + /** + * @returns {PlutusData} + */ + data() { + const ret = wasm.data_get(this.ptr); + return PlutusData.__wrap(ret); + } + /** + * @returns {ExUnits} + */ + ex_units() { + const ret = wasm.drepvotingthresholds_update_constitution(this.ptr); + return ExUnits.__wrap(ret); + } + /** + * @param {RedeemerTag} tag + * @param {BigNum} index + * @param {PlutusData} data + * @param {ExUnits} ex_units + * @returns {Redeemer} + */ + static new(tag, index, data, ex_units) { + _assertClass(tag, RedeemerTag); + _assertClass(index, BigNum); + _assertClass(data, PlutusData); + _assertClass(ex_units, ExUnits); + const ret = wasm.redeemer_new(tag.ptr, index.ptr, data.ptr, ex_units.ptr); + return Redeemer.__wrap(ret); + } +} +module.exports.Redeemer = Redeemer; + +const RedeemerTagFinalization = new FinalizationRegistry((ptr) => + wasm.__wbg_redeemertag_free(ptr) +); +/** */ +class RedeemerTag { + static __wrap(ptr) { + const obj = Object.create(RedeemerTag.prototype); + obj.ptr = ptr; + RedeemerTagFinalization.register(obj, obj.ptr, obj); + return obj; + } + + __destroy_into_raw() { + const ptr = this.ptr; + this.ptr = 0; + RedeemerTagFinalization.unregister(this); + return ptr; + } + + free() { + const ptr = this.__destroy_into_raw(); + wasm.__wbg_redeemertag_free(ptr); + } + /** + * @returns {Uint8Array} + */ + to_bytes() { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + wasm.redeemertag_to_bytes(retptr, this.ptr); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var v0 = getArrayU8FromWasm0(r0, r1).slice(); + wasm.__wbindgen_free(r0, r1 * 1); + return v0; + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @param {Uint8Array} bytes + * @returns {RedeemerTag} + */ + static from_bytes(bytes) { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + const ptr0 = passArray8ToWasm0(bytes, wasm.__wbindgen_malloc); + const len0 = WASM_VECTOR_LEN; + wasm.redeemertag_from_bytes(retptr, ptr0, len0); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + if (r2) { + throw takeObject(r1); + } + return RedeemerTag.__wrap(r0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @returns {RedeemerTag} + */ + static new_spend() { + const ret = wasm.language_new_plutus_v1(); + return RedeemerTag.__wrap(ret); + } + /** + * @returns {RedeemerTag} + */ + static new_mint() { + const ret = wasm.language_new_plutus_v2(); + return RedeemerTag.__wrap(ret); + } + /** + * @returns {RedeemerTag} + */ + static new_cert() { + const ret = wasm.language_new_plutus_v3(); + return RedeemerTag.__wrap(ret); + } + /** + * @returns {RedeemerTag} + */ + static new_reward() { + const ret = wasm.redeemertag_new_reward(); + return RedeemerTag.__wrap(ret); + } + /** + * @returns {RedeemerTag} + */ + static new_drep() { + const ret = wasm.redeemertag_new_drep(); + return RedeemerTag.__wrap(ret); + } + /** + * @returns {number} + */ + kind() { + const ret = wasm.redeemertag_kind(this.ptr); + return ret >>> 0; + } +} +module.exports.RedeemerTag = RedeemerTag; + +const RedeemerWitnessKeyFinalization = new FinalizationRegistry((ptr) => + wasm.__wbg_redeemerwitnesskey_free(ptr) +); +/** */ +class RedeemerWitnessKey { + static __wrap(ptr) { + const obj = Object.create(RedeemerWitnessKey.prototype); + obj.ptr = ptr; + RedeemerWitnessKeyFinalization.register(obj, obj.ptr, obj); + return obj; + } + + __destroy_into_raw() { + const ptr = this.ptr; + this.ptr = 0; + RedeemerWitnessKeyFinalization.unregister(this); + return ptr; + } + + free() { + const ptr = this.__destroy_into_raw(); + wasm.__wbg_redeemerwitnesskey_free(ptr); + } + /** + * @returns {RedeemerTag} + */ + tag() { + const ret = wasm.redeemerwitnesskey_tag(this.ptr); + return RedeemerTag.__wrap(ret); + } + /** + * @returns {BigNum} + */ + index() { + const ret = wasm.constrplutusdata_alternative(this.ptr); + return BigNum.__wrap(ret); + } + /** + * @param {RedeemerTag} tag + * @param {BigNum} index + * @returns {RedeemerWitnessKey} + */ + static new(tag, index) { + _assertClass(tag, RedeemerTag); + _assertClass(index, BigNum); + const ret = wasm.redeemerwitnesskey_new(tag.ptr, index.ptr); + return RedeemerWitnessKey.__wrap(ret); + } +} +module.exports.RedeemerWitnessKey = RedeemerWitnessKey; + +const RedeemersFinalization = new FinalizationRegistry((ptr) => + wasm.__wbg_redeemers_free(ptr) +); +/** */ +class Redeemers { + static __wrap(ptr) { + const obj = Object.create(Redeemers.prototype); + obj.ptr = ptr; + RedeemersFinalization.register(obj, obj.ptr, obj); + return obj; + } + + __destroy_into_raw() { + const ptr = this.ptr; + this.ptr = 0; + RedeemersFinalization.unregister(this); + return ptr; + } + + free() { + const ptr = this.__destroy_into_raw(); + wasm.__wbg_redeemers_free(ptr); + } + /** + * @returns {Uint8Array} + */ + to_bytes() { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + wasm.redeemers_to_bytes(retptr, this.ptr); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var v0 = getArrayU8FromWasm0(r0, r1).slice(); + wasm.__wbindgen_free(r0, r1 * 1); + return v0; + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @param {Uint8Array} bytes + * @returns {Redeemers} + */ + static from_bytes(bytes) { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + const ptr0 = passArray8ToWasm0(bytes, wasm.__wbindgen_malloc); + const len0 = WASM_VECTOR_LEN; + wasm.redeemers_from_bytes(retptr, ptr0, len0); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + if (r2) { + throw takeObject(r1); + } + return Redeemers.__wrap(r0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @returns {Redeemers} + */ + static new() { + const ret = wasm.certificates_new(); + return Redeemers.__wrap(ret); + } + /** + * @returns {number} + */ + len() { + const ret = wasm.assetnames_len(this.ptr); + return ret >>> 0; + } + /** + * @param {number} index + * @returns {Redeemer} + */ + get(index) { + const ret = wasm.redeemers_get(this.ptr, index); + return Redeemer.__wrap(ret); + } + /** + * @param {Redeemer} elem + */ + add(elem) { + _assertClass(elem, Redeemer); + wasm.redeemers_add(this.ptr, elem.ptr); + } +} +module.exports.Redeemers = Redeemers; + +const RegCertFinalization = new FinalizationRegistry((ptr) => + wasm.__wbg_regcert_free(ptr) +); +/** */ +class RegCert { + static __wrap(ptr) { + const obj = Object.create(RegCert.prototype); + obj.ptr = ptr; + RegCertFinalization.register(obj, obj.ptr, obj); + return obj; + } + + __destroy_into_raw() { + const ptr = this.ptr; + this.ptr = 0; + RegCertFinalization.unregister(this); + return ptr; + } + + free() { + const ptr = this.__destroy_into_raw(); + wasm.__wbg_regcert_free(ptr); + } + /** + * @returns {Uint8Array} + */ + to_bytes() { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + wasm.regcert_to_bytes(retptr, this.ptr); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var v0 = getArrayU8FromWasm0(r0, r1).slice(); + wasm.__wbindgen_free(r0, r1 * 1); + return v0; + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @param {Uint8Array} bytes + * @returns {RegCert} + */ + static from_bytes(bytes) { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + const ptr0 = passArray8ToWasm0(bytes, wasm.__wbindgen_malloc); + const len0 = WASM_VECTOR_LEN; + wasm.regcert_from_bytes(retptr, ptr0, len0); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + if (r2) { + throw takeObject(r1); + } + return RegCert.__wrap(r0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @returns {string} + */ + to_json() { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + wasm.regcert_to_json(retptr, this.ptr); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + var r3 = getInt32Memory0()[retptr / 4 + 3]; + var ptr0 = r0; + var len0 = r1; + if (r3) { + ptr0 = 0; + len0 = 0; + throw takeObject(r2); + } + return getStringFromWasm0(ptr0, len0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + wasm.__wbindgen_free(ptr0, len0); + } + } + /** + * @returns {any} + */ + to_js_value() { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + wasm.regcert_to_js_value(retptr, this.ptr); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + if (r2) { + throw takeObject(r1); + } + return takeObject(r0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @param {string} json + * @returns {RegCert} + */ + static from_json(json) { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + const ptr0 = passStringToWasm0( + json, + wasm.__wbindgen_malloc, + wasm.__wbindgen_realloc, + ); + const len0 = WASM_VECTOR_LEN; + wasm.regcert_from_json(retptr, ptr0, len0); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + if (r2) { + throw takeObject(r1); + } + return RegCert.__wrap(r0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @returns {StakeCredential} + */ + stake_credential() { + const ret = wasm.regcert_stake_credential(this.ptr); + return StakeCredential.__wrap(ret); + } + /** + * @returns {BigNum} + */ + coin() { + const ret = wasm.constrplutusdata_alternative(this.ptr); + return BigNum.__wrap(ret); + } + /** + * @param {StakeCredential} stake_credential + * @param {BigNum} coin + * @returns {RegCert} + */ + static new(stake_credential, coin) { + _assertClass(stake_credential, StakeCredential); + _assertClass(coin, BigNum); + const ret = wasm.regcert_new(stake_credential.ptr, coin.ptr); + return RegCert.__wrap(ret); + } +} +module.exports.RegCert = RegCert; + +const RegCommitteeHotKeyCertFinalization = new FinalizationRegistry((ptr) => + wasm.__wbg_regcommitteehotkeycert_free(ptr) +); +/** */ +class RegCommitteeHotKeyCert { + static __wrap(ptr) { + const obj = Object.create(RegCommitteeHotKeyCert.prototype); + obj.ptr = ptr; + RegCommitteeHotKeyCertFinalization.register(obj, obj.ptr, obj); + return obj; + } + + __destroy_into_raw() { + const ptr = this.ptr; + this.ptr = 0; + RegCommitteeHotKeyCertFinalization.unregister(this); + return ptr; + } + + free() { + const ptr = this.__destroy_into_raw(); + wasm.__wbg_regcommitteehotkeycert_free(ptr); + } + /** + * @returns {Uint8Array} + */ + to_bytes() { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + wasm.regcommitteehotkeycert_to_bytes(retptr, this.ptr); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var v0 = getArrayU8FromWasm0(r0, r1).slice(); + wasm.__wbindgen_free(r0, r1 * 1); + return v0; + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @param {Uint8Array} bytes + * @returns {RegCommitteeHotKeyCert} + */ + static from_bytes(bytes) { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + const ptr0 = passArray8ToWasm0(bytes, wasm.__wbindgen_malloc); + const len0 = WASM_VECTOR_LEN; + wasm.regcommitteehotkeycert_from_bytes(retptr, ptr0, len0); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + if (r2) { + throw takeObject(r1); + } + return RegCommitteeHotKeyCert.__wrap(r0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @returns {string} + */ + to_json() { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + wasm.regcommitteehotkeycert_to_json(retptr, this.ptr); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + var r3 = getInt32Memory0()[retptr / 4 + 3]; + var ptr0 = r0; + var len0 = r1; + if (r3) { + ptr0 = 0; + len0 = 0; + throw takeObject(r2); + } + return getStringFromWasm0(ptr0, len0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + wasm.__wbindgen_free(ptr0, len0); + } + } + /** + * @returns {any} + */ + to_js_value() { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + wasm.regcommitteehotkeycert_to_js_value(retptr, this.ptr); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + if (r2) { + throw takeObject(r1); + } + return takeObject(r0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @param {string} json + * @returns {RegCommitteeHotKeyCert} + */ + static from_json(json) { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + const ptr0 = passStringToWasm0( + json, + wasm.__wbindgen_malloc, + wasm.__wbindgen_realloc, + ); + const len0 = WASM_VECTOR_LEN; + wasm.regcommitteehotkeycert_from_json(retptr, ptr0, len0); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + if (r2) { + throw takeObject(r1); + } + return RegCommitteeHotKeyCert.__wrap(r0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @returns {Ed25519KeyHash} + */ + committee_cold_keyhash() { + const ret = wasm.regcommitteehotkeycert_committee_cold_keyhash(this.ptr); + return Ed25519KeyHash.__wrap(ret); + } + /** + * @returns {Ed25519KeyHash} + */ + committee_hot_keyhash() { + const ret = wasm.regcommitteehotkeycert_committee_hot_keyhash(this.ptr); + return Ed25519KeyHash.__wrap(ret); + } + /** + * @param {Ed25519KeyHash} committee_cold_keyhash + * @param {Ed25519KeyHash} committee_hot_keyhash + * @returns {RegCommitteeHotKeyCert} + */ + static new(committee_cold_keyhash, committee_hot_keyhash) { + _assertClass(committee_cold_keyhash, Ed25519KeyHash); + _assertClass(committee_hot_keyhash, Ed25519KeyHash); + const ret = wasm.regcommitteehotkeycert_new( + committee_cold_keyhash.ptr, + committee_hot_keyhash.ptr, + ); + return RegCommitteeHotKeyCert.__wrap(ret); + } +} +module.exports.RegCommitteeHotKeyCert = RegCommitteeHotKeyCert; + +const RegDrepCertFinalization = new FinalizationRegistry((ptr) => + wasm.__wbg_regdrepcert_free(ptr) +); +/** */ +class RegDrepCert { + static __wrap(ptr) { + const obj = Object.create(RegDrepCert.prototype); + obj.ptr = ptr; + RegDrepCertFinalization.register(obj, obj.ptr, obj); + return obj; + } + + __destroy_into_raw() { + const ptr = this.ptr; + this.ptr = 0; + RegDrepCertFinalization.unregister(this); + return ptr; + } + + free() { + const ptr = this.__destroy_into_raw(); + wasm.__wbg_regdrepcert_free(ptr); + } + /** + * @returns {Uint8Array} + */ + to_bytes() { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + wasm.regdrepcert_to_bytes(retptr, this.ptr); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var v0 = getArrayU8FromWasm0(r0, r1).slice(); + wasm.__wbindgen_free(r0, r1 * 1); + return v0; + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @param {Uint8Array} bytes + * @returns {RegDrepCert} + */ + static from_bytes(bytes) { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + const ptr0 = passArray8ToWasm0(bytes, wasm.__wbindgen_malloc); + const len0 = WASM_VECTOR_LEN; + wasm.regdrepcert_from_bytes(retptr, ptr0, len0); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + if (r2) { + throw takeObject(r1); + } + return RegDrepCert.__wrap(r0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @returns {string} + */ + to_json() { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + wasm.regdrepcert_to_json(retptr, this.ptr); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + var r3 = getInt32Memory0()[retptr / 4 + 3]; + var ptr0 = r0; + var len0 = r1; + if (r3) { + ptr0 = 0; + len0 = 0; + throw takeObject(r2); + } + return getStringFromWasm0(ptr0, len0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + wasm.__wbindgen_free(ptr0, len0); + } + } + /** + * @returns {any} + */ + to_js_value() { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + wasm.regdrepcert_to_js_value(retptr, this.ptr); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + if (r2) { + throw takeObject(r1); + } + return takeObject(r0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @param {string} json + * @returns {RegDrepCert} + */ + static from_json(json) { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + const ptr0 = passStringToWasm0( + json, + wasm.__wbindgen_malloc, + wasm.__wbindgen_realloc, + ); + const len0 = WASM_VECTOR_LEN; + wasm.regdrepcert_from_json(retptr, ptr0, len0); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + if (r2) { + throw takeObject(r1); + } + return RegDrepCert.__wrap(r0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @returns {StakeCredential} + */ + voting_credential() { + const ret = wasm.regcert_stake_credential(this.ptr); + return StakeCredential.__wrap(ret); + } + /** + * @returns {BigNum} + */ + coin() { + const ret = wasm.constrplutusdata_alternative(this.ptr); + return BigNum.__wrap(ret); + } + /** + * @param {StakeCredential} voting_credential + * @param {BigNum} coin + * @returns {RegDrepCert} + */ + static new(voting_credential, coin) { + _assertClass(voting_credential, StakeCredential); + _assertClass(coin, BigNum); + const ret = wasm.regcert_new(voting_credential.ptr, coin.ptr); + return RegDrepCert.__wrap(ret); + } +} +module.exports.RegDrepCert = RegDrepCert; + +const RelayFinalization = new FinalizationRegistry((ptr) => + wasm.__wbg_relay_free(ptr) +); +/** */ +class Relay { + static __wrap(ptr) { + const obj = Object.create(Relay.prototype); + obj.ptr = ptr; + RelayFinalization.register(obj, obj.ptr, obj); + return obj; + } + + __destroy_into_raw() { + const ptr = this.ptr; + this.ptr = 0; + RelayFinalization.unregister(this); + return ptr; + } + + free() { + const ptr = this.__destroy_into_raw(); + wasm.__wbg_relay_free(ptr); + } + /** + * @returns {Uint8Array} + */ + to_bytes() { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + wasm.relay_to_bytes(retptr, this.ptr); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var v0 = getArrayU8FromWasm0(r0, r1).slice(); + wasm.__wbindgen_free(r0, r1 * 1); + return v0; + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @param {Uint8Array} bytes + * @returns {Relay} + */ + static from_bytes(bytes) { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + const ptr0 = passArray8ToWasm0(bytes, wasm.__wbindgen_malloc); + const len0 = WASM_VECTOR_LEN; + wasm.relay_from_bytes(retptr, ptr0, len0); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + if (r2) { + throw takeObject(r1); + } + return Relay.__wrap(r0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @returns {string} + */ + to_json() { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + wasm.relay_to_json(retptr, this.ptr); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + var r3 = getInt32Memory0()[retptr / 4 + 3]; + var ptr0 = r0; + var len0 = r1; + if (r3) { + ptr0 = 0; + len0 = 0; + throw takeObject(r2); + } + return getStringFromWasm0(ptr0, len0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + wasm.__wbindgen_free(ptr0, len0); + } + } + /** + * @returns {any} + */ + to_js_value() { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + wasm.relay_to_js_value(retptr, this.ptr); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + if (r2) { + throw takeObject(r1); + } + return takeObject(r0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @param {string} json + * @returns {Relay} + */ + static from_json(json) { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + const ptr0 = passStringToWasm0( + json, + wasm.__wbindgen_malloc, + wasm.__wbindgen_realloc, + ); + const len0 = WASM_VECTOR_LEN; + wasm.relay_from_json(retptr, ptr0, len0); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + if (r2) { + throw takeObject(r1); + } + return Relay.__wrap(r0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @param {SingleHostAddr} single_host_addr + * @returns {Relay} + */ + static new_single_host_addr(single_host_addr) { + _assertClass(single_host_addr, SingleHostAddr); + const ret = wasm.relay_new_single_host_addr(single_host_addr.ptr); + return Relay.__wrap(ret); + } + /** + * @param {SingleHostName} single_host_name + * @returns {Relay} + */ + static new_single_host_name(single_host_name) { + _assertClass(single_host_name, SingleHostName); + const ret = wasm.relay_new_single_host_name(single_host_name.ptr); + return Relay.__wrap(ret); + } + /** + * @param {MultiHostName} multi_host_name + * @returns {Relay} + */ + static new_multi_host_name(multi_host_name) { + _assertClass(multi_host_name, MultiHostName); + const ret = wasm.relay_new_multi_host_name(multi_host_name.ptr); + return Relay.__wrap(ret); + } + /** + * @returns {number} + */ + kind() { + const ret = wasm.relay_kind(this.ptr); + return ret >>> 0; + } + /** + * @returns {SingleHostAddr | undefined} + */ + as_single_host_addr() { + const ret = wasm.relay_as_single_host_addr(this.ptr); + return ret === 0 ? undefined : SingleHostAddr.__wrap(ret); + } + /** + * @returns {SingleHostName | undefined} + */ + as_single_host_name() { + const ret = wasm.relay_as_single_host_name(this.ptr); + return ret === 0 ? undefined : SingleHostName.__wrap(ret); + } + /** + * @returns {MultiHostName | undefined} + */ + as_multi_host_name() { + const ret = wasm.relay_as_multi_host_name(this.ptr); + return ret === 0 ? undefined : MultiHostName.__wrap(ret); + } +} +module.exports.Relay = Relay; + +const RelaysFinalization = new FinalizationRegistry((ptr) => + wasm.__wbg_relays_free(ptr) +); +/** */ +class Relays { + static __wrap(ptr) { + const obj = Object.create(Relays.prototype); + obj.ptr = ptr; + RelaysFinalization.register(obj, obj.ptr, obj); + return obj; + } + + __destroy_into_raw() { + const ptr = this.ptr; + this.ptr = 0; + RelaysFinalization.unregister(this); + return ptr; + } + + free() { + const ptr = this.__destroy_into_raw(); + wasm.__wbg_relays_free(ptr); + } + /** + * @returns {Uint8Array} + */ + to_bytes() { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + wasm.relays_to_bytes(retptr, this.ptr); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var v0 = getArrayU8FromWasm0(r0, r1).slice(); + wasm.__wbindgen_free(r0, r1 * 1); + return v0; + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @param {Uint8Array} bytes + * @returns {Relays} + */ + static from_bytes(bytes) { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + const ptr0 = passArray8ToWasm0(bytes, wasm.__wbindgen_malloc); + const len0 = WASM_VECTOR_LEN; + wasm.relays_from_bytes(retptr, ptr0, len0); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + if (r2) { + throw takeObject(r1); + } + return Relays.__wrap(r0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @returns {string} + */ + to_json() { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + wasm.relays_to_json(retptr, this.ptr); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + var r3 = getInt32Memory0()[retptr / 4 + 3]; + var ptr0 = r0; + var len0 = r1; + if (r3) { + ptr0 = 0; + len0 = 0; + throw takeObject(r2); + } + return getStringFromWasm0(ptr0, len0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + wasm.__wbindgen_free(ptr0, len0); + } + } + /** + * @returns {any} + */ + to_js_value() { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + wasm.relays_to_js_value(retptr, this.ptr); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + if (r2) { + throw takeObject(r1); + } + return takeObject(r0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @param {string} json + * @returns {Relays} + */ + static from_json(json) { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + const ptr0 = passStringToWasm0( + json, + wasm.__wbindgen_malloc, + wasm.__wbindgen_realloc, + ); + const len0 = WASM_VECTOR_LEN; + wasm.relays_from_json(retptr, ptr0, len0); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + if (r2) { + throw takeObject(r1); + } + return Relays.__wrap(r0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @returns {Relays} + */ + static new() { + const ret = wasm.assetnames_new(); + return Relays.__wrap(ret); + } + /** + * @returns {number} + */ + len() { + const ret = wasm.assetnames_len(this.ptr); + return ret >>> 0; + } + /** + * @param {number} index + * @returns {Relay} + */ + get(index) { + const ret = wasm.relays_get(this.ptr, index); + return Relay.__wrap(ret); + } + /** + * @param {Relay} elem + */ + add(elem) { + _assertClass(elem, Relay); + wasm.relays_add(this.ptr, elem.ptr); + } +} +module.exports.Relays = Relays; + +const RequiredWitnessSetFinalization = new FinalizationRegistry((ptr) => + wasm.__wbg_requiredwitnessset_free(ptr) +); +/** */ +class RequiredWitnessSet { + static __wrap(ptr) { + const obj = Object.create(RequiredWitnessSet.prototype); + obj.ptr = ptr; + RequiredWitnessSetFinalization.register(obj, obj.ptr, obj); + return obj; + } + + __destroy_into_raw() { + const ptr = this.ptr; + this.ptr = 0; + RequiredWitnessSetFinalization.unregister(this); + return ptr; + } + + free() { + const ptr = this.__destroy_into_raw(); + wasm.__wbg_requiredwitnessset_free(ptr); + } + /** + * @param {Vkeywitness} vkey + */ + add_vkey(vkey) { + _assertClass(vkey, Vkeywitness); + wasm.requiredwitnessset_add_vkey(this.ptr, vkey.ptr); + } + /** + * @param {Vkey} vkey + */ + add_vkey_key(vkey) { + _assertClass(vkey, Vkey); + wasm.requiredwitnessset_add_vkey_key(this.ptr, vkey.ptr); + } + /** + * @param {Ed25519KeyHash} hash + */ + add_vkey_key_hash(hash) { + _assertClass(hash, Ed25519KeyHash); + wasm.requiredwitnessset_add_vkey_key_hash(this.ptr, hash.ptr); + } + /** + * @param {BootstrapWitness} bootstrap + */ + add_bootstrap(bootstrap) { + _assertClass(bootstrap, BootstrapWitness); + wasm.requiredwitnessset_add_bootstrap(this.ptr, bootstrap.ptr); + } + /** + * @param {Vkey} bootstrap + */ + add_bootstrap_key(bootstrap) { + _assertClass(bootstrap, Vkey); + wasm.requiredwitnessset_add_bootstrap_key(this.ptr, bootstrap.ptr); + } + /** + * @param {Ed25519KeyHash} hash + */ + add_bootstrap_key_hash(hash) { + _assertClass(hash, Ed25519KeyHash); + wasm.requiredwitnessset_add_bootstrap_key_hash(this.ptr, hash.ptr); + } + /** + * @param {NativeScript} native_script + */ + add_native_script(native_script) { + _assertClass(native_script, NativeScript); + wasm.requiredwitnessset_add_native_script(this.ptr, native_script.ptr); + } + /** + * @param {ScriptHash} native_script + */ + add_native_script_hash(native_script) { + _assertClass(native_script, ScriptHash); + wasm.requiredwitnessset_add_native_script_hash(this.ptr, native_script.ptr); + } + /** + * @param {PlutusScript} plutus_script + */ + add_plutus_script(plutus_script) { + _assertClass(plutus_script, PlutusScript); + wasm.requiredwitnessset_add_plutus_script(this.ptr, plutus_script.ptr); + } + /** + * @param {PlutusScript} plutus_script + */ + add_plutus_v2_script(plutus_script) { + _assertClass(plutus_script, PlutusScript); + wasm.requiredwitnessset_add_plutus_v2_script(this.ptr, plutus_script.ptr); + } + /** + * @param {ScriptHash} plutus_script + */ + add_plutus_hash(plutus_script) { + _assertClass(plutus_script, ScriptHash); + wasm.requiredwitnessset_add_plutus_hash(this.ptr, plutus_script.ptr); + } + /** + * @param {PlutusData} plutus_datum + */ + add_plutus_datum(plutus_datum) { + _assertClass(plutus_datum, PlutusData); + wasm.requiredwitnessset_add_plutus_datum(this.ptr, plutus_datum.ptr); + } + /** + * @param {DataHash} plutus_datum + */ + add_plutus_datum_hash(plutus_datum) { + _assertClass(plutus_datum, DataHash); + wasm.requiredwitnessset_add_plutus_datum_hash(this.ptr, plutus_datum.ptr); + } + /** + * @param {Redeemer} redeemer + */ + add_redeemer(redeemer) { + _assertClass(redeemer, Redeemer); + wasm.requiredwitnessset_add_redeemer(this.ptr, redeemer.ptr); + } + /** + * @param {RedeemerWitnessKey} redeemer + */ + add_redeemer_tag(redeemer) { + _assertClass(redeemer, RedeemerWitnessKey); + wasm.requiredwitnessset_add_redeemer_tag(this.ptr, redeemer.ptr); + } + /** + * @param {RequiredWitnessSet} requirements + */ + add_all(requirements) { + _assertClass(requirements, RequiredWitnessSet); + wasm.requiredwitnessset_add_all(this.ptr, requirements.ptr); + } + /** + * @returns {RequiredWitnessSet} + */ + static new() { + const ret = wasm.requiredwitnessset_new(); + return RequiredWitnessSet.__wrap(ret); + } +} +module.exports.RequiredWitnessSet = RequiredWitnessSet; + +const RewardAddressFinalization = new FinalizationRegistry((ptr) => + wasm.__wbg_rewardaddress_free(ptr) +); +/** */ +class RewardAddress { + static __wrap(ptr) { + const obj = Object.create(RewardAddress.prototype); + obj.ptr = ptr; + RewardAddressFinalization.register(obj, obj.ptr, obj); + return obj; + } + + __destroy_into_raw() { + const ptr = this.ptr; + this.ptr = 0; + RewardAddressFinalization.unregister(this); + return ptr; + } + + free() { + const ptr = this.__destroy_into_raw(); + wasm.__wbg_rewardaddress_free(ptr); + } + /** + * @param {number} network + * @param {StakeCredential} payment + * @returns {RewardAddress} + */ + static new(network, payment) { + _assertClass(payment, StakeCredential); + const ret = wasm.enterpriseaddress_new(network, payment.ptr); + return RewardAddress.__wrap(ret); + } + /** + * @returns {StakeCredential} + */ + payment_cred() { + const ret = wasm.baseaddress_payment_cred(this.ptr); + return StakeCredential.__wrap(ret); + } + /** + * @returns {Address} + */ + to_address() { + const ret = wasm.rewardaddress_to_address(this.ptr); + return Address.__wrap(ret); + } + /** + * @param {Address} addr + * @returns {RewardAddress | undefined} + */ + static from_address(addr) { + _assertClass(addr, Address); + const ret = wasm.address_as_reward(addr.ptr); + return ret === 0 ? undefined : RewardAddress.__wrap(ret); + } +} +module.exports.RewardAddress = RewardAddress; + +const RewardAddressesFinalization = new FinalizationRegistry((ptr) => + wasm.__wbg_rewardaddresses_free(ptr) +); +/** */ +class RewardAddresses { + static __wrap(ptr) { + const obj = Object.create(RewardAddresses.prototype); + obj.ptr = ptr; + RewardAddressesFinalization.register(obj, obj.ptr, obj); + return obj; + } + + __destroy_into_raw() { + const ptr = this.ptr; + this.ptr = 0; + RewardAddressesFinalization.unregister(this); + return ptr; + } + + free() { + const ptr = this.__destroy_into_raw(); + wasm.__wbg_rewardaddresses_free(ptr); + } + /** + * @returns {Uint8Array} + */ + to_bytes() { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + wasm.rewardaddresses_to_bytes(retptr, this.ptr); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var v0 = getArrayU8FromWasm0(r0, r1).slice(); + wasm.__wbindgen_free(r0, r1 * 1); + return v0; + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @param {Uint8Array} bytes + * @returns {RewardAddresses} + */ + static from_bytes(bytes) { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + const ptr0 = passArray8ToWasm0(bytes, wasm.__wbindgen_malloc); + const len0 = WASM_VECTOR_LEN; + wasm.rewardaddresses_from_bytes(retptr, ptr0, len0); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + if (r2) { + throw takeObject(r1); + } + return RewardAddresses.__wrap(r0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @returns {string} + */ + to_json() { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + wasm.rewardaddresses_to_json(retptr, this.ptr); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + var r3 = getInt32Memory0()[retptr / 4 + 3]; + var ptr0 = r0; + var len0 = r1; + if (r3) { + ptr0 = 0; + len0 = 0; + throw takeObject(r2); + } + return getStringFromWasm0(ptr0, len0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + wasm.__wbindgen_free(ptr0, len0); + } + } + /** + * @returns {any} + */ + to_js_value() { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + wasm.rewardaddresses_to_js_value(retptr, this.ptr); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + if (r2) { + throw takeObject(r1); + } + return takeObject(r0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @param {string} json + * @returns {RewardAddresses} + */ + static from_json(json) { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + const ptr0 = passStringToWasm0( + json, + wasm.__wbindgen_malloc, + wasm.__wbindgen_realloc, + ); + const len0 = WASM_VECTOR_LEN; + wasm.rewardaddresses_from_json(retptr, ptr0, len0); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + if (r2) { + throw takeObject(r1); + } + return RewardAddresses.__wrap(r0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @returns {RewardAddresses} + */ + static new() { + const ret = wasm.ed25519keyhashes_new(); + return RewardAddresses.__wrap(ret); + } + /** + * @returns {number} + */ + len() { + const ret = wasm.assetnames_len(this.ptr); + return ret >>> 0; + } + /** + * @param {number} index + * @returns {RewardAddress} + */ + get(index) { + const ret = wasm.rewardaddresses_get(this.ptr, index); + return RewardAddress.__wrap(ret); + } + /** + * @param {RewardAddress} elem + */ + add(elem) { + _assertClass(elem, RewardAddress); + wasm.rewardaddresses_add(this.ptr, elem.ptr); + } +} +module.exports.RewardAddresses = RewardAddresses; + +const ScriptFinalization = new FinalizationRegistry((ptr) => + wasm.__wbg_script_free(ptr) +); +/** */ +class Script { + static __wrap(ptr) { + const obj = Object.create(Script.prototype); + obj.ptr = ptr; + ScriptFinalization.register(obj, obj.ptr, obj); + return obj; + } + + __destroy_into_raw() { + const ptr = this.ptr; + this.ptr = 0; + ScriptFinalization.unregister(this); + return ptr; + } + + free() { + const ptr = this.__destroy_into_raw(); + wasm.__wbg_script_free(ptr); + } + /** + * @returns {Uint8Array} + */ + to_bytes() { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + wasm.script_to_bytes(retptr, this.ptr); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var v0 = getArrayU8FromWasm0(r0, r1).slice(); + wasm.__wbindgen_free(r0, r1 * 1); + return v0; + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @param {Uint8Array} bytes + * @returns {Script} + */ + static from_bytes(bytes) { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + const ptr0 = passArray8ToWasm0(bytes, wasm.__wbindgen_malloc); + const len0 = WASM_VECTOR_LEN; + wasm.script_from_bytes(retptr, ptr0, len0); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + if (r2) { + throw takeObject(r1); + } + return Script.__wrap(r0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @returns {string} + */ + to_json() { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + wasm.script_to_json(retptr, this.ptr); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + var r3 = getInt32Memory0()[retptr / 4 + 3]; + var ptr0 = r0; + var len0 = r1; + if (r3) { + ptr0 = 0; + len0 = 0; + throw takeObject(r2); + } + return getStringFromWasm0(ptr0, len0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + wasm.__wbindgen_free(ptr0, len0); + } + } + /** + * @returns {any} + */ + to_js_value() { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + wasm.script_to_js_value(retptr, this.ptr); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + if (r2) { + throw takeObject(r1); + } + return takeObject(r0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @param {string} json + * @returns {Script} + */ + static from_json(json) { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + const ptr0 = passStringToWasm0( + json, + wasm.__wbindgen_malloc, + wasm.__wbindgen_realloc, + ); + const len0 = WASM_VECTOR_LEN; + wasm.script_from_json(retptr, ptr0, len0); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + if (r2) { + throw takeObject(r1); + } + return Script.__wrap(r0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @param {NativeScript} native_script + * @returns {Script} + */ + static new_native(native_script) { + _assertClass(native_script, NativeScript); + const ret = wasm.script_new_native(native_script.ptr); + return Script.__wrap(ret); + } + /** + * @param {PlutusScript} plutus_script + * @returns {Script} + */ + static new_plutus_v1(plutus_script) { + _assertClass(plutus_script, PlutusScript); + const ret = wasm.script_new_plutus_v1(plutus_script.ptr); + return Script.__wrap(ret); + } + /** + * @param {PlutusScript} plutus_script + * @returns {Script} + */ + static new_plutus_v2(plutus_script) { + _assertClass(plutus_script, PlutusScript); + const ret = wasm.script_new_plutus_v2(plutus_script.ptr); + return Script.__wrap(ret); + } + /** + * @param {PlutusScript} plutus_script + * @returns {Script} + */ + static new_plutus_v3(plutus_script) { + _assertClass(plutus_script, PlutusScript); + const ret = wasm.script_new_plutus_v3(plutus_script.ptr); + return Script.__wrap(ret); + } + /** + * @returns {number} + */ + kind() { + const ret = wasm.script_kind(this.ptr); + return ret >>> 0; + } + /** + * @returns {NativeScript | undefined} + */ + as_native() { + const ret = wasm.script_as_native(this.ptr); + return ret === 0 ? undefined : NativeScript.__wrap(ret); + } + /** + * @returns {PlutusScript | undefined} + */ + as_plutus_v1() { + const ret = wasm.script_as_plutus_v1(this.ptr); + return ret === 0 ? undefined : PlutusScript.__wrap(ret); + } + /** + * @returns {PlutusScript | undefined} + */ + as_plutus_v2() { + const ret = wasm.script_as_plutus_v2(this.ptr); + return ret === 0 ? undefined : PlutusScript.__wrap(ret); + } + /** + * @returns {PlutusScript | undefined} + */ + as_plutus_v3() { + const ret = wasm.script_as_plutus_v3(this.ptr); + return ret === 0 ? undefined : PlutusScript.__wrap(ret); + } +} +module.exports.Script = Script; + +const ScriptAllFinalization = new FinalizationRegistry((ptr) => + wasm.__wbg_scriptall_free(ptr) +); +/** */ +class ScriptAll { + static __wrap(ptr) { + const obj = Object.create(ScriptAll.prototype); + obj.ptr = ptr; + ScriptAllFinalization.register(obj, obj.ptr, obj); + return obj; + } + + __destroy_into_raw() { + const ptr = this.ptr; + this.ptr = 0; + ScriptAllFinalization.unregister(this); + return ptr; + } + + free() { + const ptr = this.__destroy_into_raw(); + wasm.__wbg_scriptall_free(ptr); + } + /** + * @returns {Uint8Array} + */ + to_bytes() { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + wasm.scriptall_to_bytes(retptr, this.ptr); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var v0 = getArrayU8FromWasm0(r0, r1).slice(); + wasm.__wbindgen_free(r0, r1 * 1); + return v0; + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @param {Uint8Array} bytes + * @returns {ScriptAll} + */ + static from_bytes(bytes) { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + const ptr0 = passArray8ToWasm0(bytes, wasm.__wbindgen_malloc); + const len0 = WASM_VECTOR_LEN; + wasm.scriptall_from_bytes(retptr, ptr0, len0); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + if (r2) { + throw takeObject(r1); + } + return ScriptAll.__wrap(r0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @returns {string} + */ + to_json() { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + wasm.scriptall_to_json(retptr, this.ptr); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + var r3 = getInt32Memory0()[retptr / 4 + 3]; + var ptr0 = r0; + var len0 = r1; + if (r3) { + ptr0 = 0; + len0 = 0; + throw takeObject(r2); + } + return getStringFromWasm0(ptr0, len0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + wasm.__wbindgen_free(ptr0, len0); + } + } + /** + * @returns {any} + */ + to_js_value() { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + wasm.scriptall_to_js_value(retptr, this.ptr); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + if (r2) { + throw takeObject(r1); + } + return takeObject(r0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @param {string} json + * @returns {ScriptAll} + */ + static from_json(json) { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + const ptr0 = passStringToWasm0( + json, + wasm.__wbindgen_malloc, + wasm.__wbindgen_realloc, + ); + const len0 = WASM_VECTOR_LEN; + wasm.scriptall_from_json(retptr, ptr0, len0); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + if (r2) { + throw takeObject(r1); + } + return ScriptAll.__wrap(r0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @returns {NativeScripts} + */ + native_scripts() { + const ret = wasm.scriptall_native_scripts(this.ptr); + return NativeScripts.__wrap(ret); + } + /** + * @param {NativeScripts} native_scripts + * @returns {ScriptAll} + */ + static new(native_scripts) { + _assertClass(native_scripts, NativeScripts); + const ret = wasm.scriptall_new(native_scripts.ptr); + return ScriptAll.__wrap(ret); + } +} +module.exports.ScriptAll = ScriptAll; + +const ScriptAnyFinalization = new FinalizationRegistry((ptr) => + wasm.__wbg_scriptany_free(ptr) +); +/** */ +class ScriptAny { + static __wrap(ptr) { + const obj = Object.create(ScriptAny.prototype); + obj.ptr = ptr; + ScriptAnyFinalization.register(obj, obj.ptr, obj); + return obj; + } + + __destroy_into_raw() { + const ptr = this.ptr; + this.ptr = 0; + ScriptAnyFinalization.unregister(this); + return ptr; + } + + free() { + const ptr = this.__destroy_into_raw(); + wasm.__wbg_scriptany_free(ptr); + } + /** + * @returns {Uint8Array} + */ + to_bytes() { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + wasm.scriptany_to_bytes(retptr, this.ptr); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var v0 = getArrayU8FromWasm0(r0, r1).slice(); + wasm.__wbindgen_free(r0, r1 * 1); + return v0; + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @param {Uint8Array} bytes + * @returns {ScriptAny} + */ + static from_bytes(bytes) { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + const ptr0 = passArray8ToWasm0(bytes, wasm.__wbindgen_malloc); + const len0 = WASM_VECTOR_LEN; + wasm.scriptany_from_bytes(retptr, ptr0, len0); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + if (r2) { + throw takeObject(r1); + } + return ScriptAny.__wrap(r0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @returns {string} + */ + to_json() { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + wasm.scriptall_to_json(retptr, this.ptr); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + var r3 = getInt32Memory0()[retptr / 4 + 3]; + var ptr0 = r0; + var len0 = r1; + if (r3) { + ptr0 = 0; + len0 = 0; + throw takeObject(r2); + } + return getStringFromWasm0(ptr0, len0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + wasm.__wbindgen_free(ptr0, len0); + } + } + /** + * @returns {any} + */ + to_js_value() { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + wasm.scriptall_to_js_value(retptr, this.ptr); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + if (r2) { + throw takeObject(r1); + } + return takeObject(r0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @param {string} json + * @returns {ScriptAny} + */ + static from_json(json) { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + const ptr0 = passStringToWasm0( + json, + wasm.__wbindgen_malloc, + wasm.__wbindgen_realloc, + ); + const len0 = WASM_VECTOR_LEN; + wasm.scriptany_from_json(retptr, ptr0, len0); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + if (r2) { + throw takeObject(r1); + } + return ScriptAny.__wrap(r0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @returns {NativeScripts} + */ + native_scripts() { + const ret = wasm.scriptall_native_scripts(this.ptr); + return NativeScripts.__wrap(ret); + } + /** + * @param {NativeScripts} native_scripts + * @returns {ScriptAny} + */ + static new(native_scripts) { + _assertClass(native_scripts, NativeScripts); + const ret = wasm.scriptall_new(native_scripts.ptr); + return ScriptAny.__wrap(ret); + } +} +module.exports.ScriptAny = ScriptAny; + +const ScriptDataHashFinalization = new FinalizationRegistry((ptr) => + wasm.__wbg_scriptdatahash_free(ptr) +); +/** */ +class ScriptDataHash { + static __wrap(ptr) { + const obj = Object.create(ScriptDataHash.prototype); + obj.ptr = ptr; + ScriptDataHashFinalization.register(obj, obj.ptr, obj); + return obj; + } + + __destroy_into_raw() { + const ptr = this.ptr; + this.ptr = 0; + ScriptDataHashFinalization.unregister(this); + return ptr; + } + + free() { + const ptr = this.__destroy_into_raw(); + wasm.__wbg_scriptdatahash_free(ptr); + } + /** + * @param {Uint8Array} bytes + * @returns {ScriptDataHash} + */ + static from_bytes(bytes) { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + const ptr0 = passArray8ToWasm0(bytes, wasm.__wbindgen_malloc); + const len0 = WASM_VECTOR_LEN; + wasm.scriptdatahash_from_bytes(retptr, ptr0, len0); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + if (r2) { + throw takeObject(r1); + } + return ScriptDataHash.__wrap(r0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @returns {Uint8Array} + */ + to_bytes() { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + wasm.auxiliarydatahash_to_bytes(retptr, this.ptr); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var v0 = getArrayU8FromWasm0(r0, r1).slice(); + wasm.__wbindgen_free(r0, r1 * 1); + return v0; + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @param {string} prefix + * @returns {string} + */ + to_bech32(prefix) { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + const ptr0 = passStringToWasm0( + prefix, + wasm.__wbindgen_malloc, + wasm.__wbindgen_realloc, + ); + const len0 = WASM_VECTOR_LEN; + wasm.auxiliarydatahash_to_bech32(retptr, this.ptr, ptr0, len0); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + var r3 = getInt32Memory0()[retptr / 4 + 3]; + var ptr1 = r0; + var len1 = r1; + if (r3) { + ptr1 = 0; + len1 = 0; + throw takeObject(r2); + } + return getStringFromWasm0(ptr1, len1); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + wasm.__wbindgen_free(ptr1, len1); + } + } + /** + * @param {string} bech_str + * @returns {ScriptDataHash} + */ + static from_bech32(bech_str) { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + const ptr0 = passStringToWasm0( + bech_str, + wasm.__wbindgen_malloc, + wasm.__wbindgen_realloc, + ); + const len0 = WASM_VECTOR_LEN; + wasm.scriptdatahash_from_bech32(retptr, ptr0, len0); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + if (r2) { + throw takeObject(r1); + } + return ScriptDataHash.__wrap(r0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @returns {string} + */ + to_hex() { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + wasm.auxiliarydatahash_to_hex(retptr, this.ptr); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + return getStringFromWasm0(r0, r1); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + wasm.__wbindgen_free(r0, r1); + } + } + /** + * @param {string} hex + * @returns {ScriptDataHash} + */ + static from_hex(hex) { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + const ptr0 = passStringToWasm0( + hex, + wasm.__wbindgen_malloc, + wasm.__wbindgen_realloc, + ); + const len0 = WASM_VECTOR_LEN; + wasm.scriptdatahash_from_hex(retptr, ptr0, len0); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + if (r2) { + throw takeObject(r1); + } + return ScriptDataHash.__wrap(r0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } +} +module.exports.ScriptDataHash = ScriptDataHash; + +const ScriptHashFinalization = new FinalizationRegistry((ptr) => + wasm.__wbg_scripthash_free(ptr) +); +/** */ +class ScriptHash { + static __wrap(ptr) { + const obj = Object.create(ScriptHash.prototype); + obj.ptr = ptr; + ScriptHashFinalization.register(obj, obj.ptr, obj); + return obj; + } + + __destroy_into_raw() { + const ptr = this.ptr; + this.ptr = 0; + ScriptHashFinalization.unregister(this); + return ptr; + } + + free() { + const ptr = this.__destroy_into_raw(); + wasm.__wbg_scripthash_free(ptr); + } + /** + * @param {Uint8Array} bytes + * @returns {ScriptHash} + */ + static from_bytes(bytes) { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + const ptr0 = passArray8ToWasm0(bytes, wasm.__wbindgen_malloc); + const len0 = WASM_VECTOR_LEN; + wasm.scripthash_from_bytes(retptr, ptr0, len0); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + if (r2) { + throw takeObject(r1); + } + return ScriptHash.__wrap(r0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @returns {Uint8Array} + */ + to_bytes() { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + wasm.ed25519keyhash_to_bytes(retptr, this.ptr); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var v0 = getArrayU8FromWasm0(r0, r1).slice(); + wasm.__wbindgen_free(r0, r1 * 1); + return v0; + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @param {string} prefix + * @returns {string} + */ + to_bech32(prefix) { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + const ptr0 = passStringToWasm0( + prefix, + wasm.__wbindgen_malloc, + wasm.__wbindgen_realloc, + ); + const len0 = WASM_VECTOR_LEN; + wasm.ed25519keyhash_to_bech32(retptr, this.ptr, ptr0, len0); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + var r3 = getInt32Memory0()[retptr / 4 + 3]; + var ptr1 = r0; + var len1 = r1; + if (r3) { + ptr1 = 0; + len1 = 0; + throw takeObject(r2); + } + return getStringFromWasm0(ptr1, len1); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + wasm.__wbindgen_free(ptr1, len1); + } + } + /** + * @param {string} bech_str + * @returns {ScriptHash} + */ + static from_bech32(bech_str) { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + const ptr0 = passStringToWasm0( + bech_str, + wasm.__wbindgen_malloc, + wasm.__wbindgen_realloc, + ); + const len0 = WASM_VECTOR_LEN; + wasm.scripthash_from_bech32(retptr, ptr0, len0); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + if (r2) { + throw takeObject(r1); + } + return ScriptHash.__wrap(r0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @returns {string} + */ + to_hex() { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + wasm.ed25519keyhash_to_hex(retptr, this.ptr); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + return getStringFromWasm0(r0, r1); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + wasm.__wbindgen_free(r0, r1); + } + } + /** + * @param {string} hex + * @returns {ScriptHash} + */ + static from_hex(hex) { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + const ptr0 = passStringToWasm0( + hex, + wasm.__wbindgen_malloc, + wasm.__wbindgen_realloc, + ); + const len0 = WASM_VECTOR_LEN; + wasm.scripthash_from_hex(retptr, ptr0, len0); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + if (r2) { + throw takeObject(r1); + } + return ScriptHash.__wrap(r0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } +} +module.exports.ScriptHash = ScriptHash; + +const ScriptHashesFinalization = new FinalizationRegistry((ptr) => + wasm.__wbg_scripthashes_free(ptr) +); +/** */ +class ScriptHashes { + static __wrap(ptr) { + const obj = Object.create(ScriptHashes.prototype); + obj.ptr = ptr; + ScriptHashesFinalization.register(obj, obj.ptr, obj); + return obj; + } + + __destroy_into_raw() { + const ptr = this.ptr; + this.ptr = 0; + ScriptHashesFinalization.unregister(this); + return ptr; + } + + free() { + const ptr = this.__destroy_into_raw(); + wasm.__wbg_scripthashes_free(ptr); + } + /** + * @returns {Uint8Array} + */ + to_bytes() { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + wasm.scripthashes_to_bytes(retptr, this.ptr); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var v0 = getArrayU8FromWasm0(r0, r1).slice(); + wasm.__wbindgen_free(r0, r1 * 1); + return v0; + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @param {Uint8Array} bytes + * @returns {ScriptHashes} + */ + static from_bytes(bytes) { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + const ptr0 = passArray8ToWasm0(bytes, wasm.__wbindgen_malloc); + const len0 = WASM_VECTOR_LEN; + wasm.scripthashes_from_bytes(retptr, ptr0, len0); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + if (r2) { + throw takeObject(r1); + } + return ScriptHashes.__wrap(r0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @returns {string} + */ + to_json() { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + wasm.ed25519keyhashes_to_json(retptr, this.ptr); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + var r3 = getInt32Memory0()[retptr / 4 + 3]; + var ptr0 = r0; + var len0 = r1; + if (r3) { + ptr0 = 0; + len0 = 0; + throw takeObject(r2); + } + return getStringFromWasm0(ptr0, len0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + wasm.__wbindgen_free(ptr0, len0); + } + } + /** + * @returns {any} + */ + to_js_value() { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + wasm.ed25519keyhashes_to_js_value(retptr, this.ptr); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + if (r2) { + throw takeObject(r1); + } + return takeObject(r0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @param {string} json + * @returns {ScriptHashes} + */ + static from_json(json) { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + const ptr0 = passStringToWasm0( + json, + wasm.__wbindgen_malloc, + wasm.__wbindgen_realloc, + ); + const len0 = WASM_VECTOR_LEN; + wasm.scripthashes_from_json(retptr, ptr0, len0); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + if (r2) { + throw takeObject(r1); + } + return ScriptHashes.__wrap(r0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @returns {ScriptHashes} + */ + static new() { + const ret = wasm.ed25519keyhashes_new(); + return ScriptHashes.__wrap(ret); + } + /** + * @returns {number} + */ + len() { + const ret = wasm.assetnames_len(this.ptr); + return ret >>> 0; + } + /** + * @param {number} index + * @returns {ScriptHash} + */ + get(index) { + const ret = wasm.scripthashes_get(this.ptr, index); + return ScriptHash.__wrap(ret); + } + /** + * @param {ScriptHash} elem + */ + add(elem) { + _assertClass(elem, ScriptHash); + wasm.ed25519keyhashes_add(this.ptr, elem.ptr); + } +} +module.exports.ScriptHashes = ScriptHashes; + +const ScriptNOfKFinalization = new FinalizationRegistry((ptr) => + wasm.__wbg_scriptnofk_free(ptr) +); +/** */ +class ScriptNOfK { + static __wrap(ptr) { + const obj = Object.create(ScriptNOfK.prototype); + obj.ptr = ptr; + ScriptNOfKFinalization.register(obj, obj.ptr, obj); + return obj; + } + + __destroy_into_raw() { + const ptr = this.ptr; + this.ptr = 0; + ScriptNOfKFinalization.unregister(this); + return ptr; + } + + free() { + const ptr = this.__destroy_into_raw(); + wasm.__wbg_scriptnofk_free(ptr); + } + /** + * @returns {Uint8Array} + */ + to_bytes() { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + wasm.scriptnofk_to_bytes(retptr, this.ptr); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var v0 = getArrayU8FromWasm0(r0, r1).slice(); + wasm.__wbindgen_free(r0, r1 * 1); + return v0; + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @param {Uint8Array} bytes + * @returns {ScriptNOfK} + */ + static from_bytes(bytes) { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + const ptr0 = passArray8ToWasm0(bytes, wasm.__wbindgen_malloc); + const len0 = WASM_VECTOR_LEN; + wasm.scriptnofk_from_bytes(retptr, ptr0, len0); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + if (r2) { + throw takeObject(r1); + } + return ScriptNOfK.__wrap(r0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @returns {string} + */ + to_json() { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + wasm.scriptnofk_to_json(retptr, this.ptr); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + var r3 = getInt32Memory0()[retptr / 4 + 3]; + var ptr0 = r0; + var len0 = r1; + if (r3) { + ptr0 = 0; + len0 = 0; + throw takeObject(r2); + } + return getStringFromWasm0(ptr0, len0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + wasm.__wbindgen_free(ptr0, len0); + } + } + /** + * @returns {any} + */ + to_js_value() { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + wasm.scriptnofk_to_js_value(retptr, this.ptr); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + if (r2) { + throw takeObject(r1); + } + return takeObject(r0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @param {string} json + * @returns {ScriptNOfK} + */ + static from_json(json) { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + const ptr0 = passStringToWasm0( + json, + wasm.__wbindgen_malloc, + wasm.__wbindgen_realloc, + ); + const len0 = WASM_VECTOR_LEN; + wasm.scriptnofk_from_json(retptr, ptr0, len0); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + if (r2) { + throw takeObject(r1); + } + return ScriptNOfK.__wrap(r0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @returns {number} + */ + n() { + const ret = wasm.scriptnofk_n(this.ptr); + return ret >>> 0; + } + /** + * @returns {NativeScripts} + */ + native_scripts() { + const ret = wasm.scriptall_native_scripts(this.ptr); + return NativeScripts.__wrap(ret); + } + /** + * @param {number} n + * @param {NativeScripts} native_scripts + * @returns {ScriptNOfK} + */ + static new(n, native_scripts) { + _assertClass(native_scripts, NativeScripts); + const ret = wasm.scriptnofk_new(n, native_scripts.ptr); + return ScriptNOfK.__wrap(ret); + } +} +module.exports.ScriptNOfK = ScriptNOfK; + +const ScriptPubkeyFinalization = new FinalizationRegistry((ptr) => + wasm.__wbg_scriptpubkey_free(ptr) +); +/** */ +class ScriptPubkey { + static __wrap(ptr) { + const obj = Object.create(ScriptPubkey.prototype); + obj.ptr = ptr; + ScriptPubkeyFinalization.register(obj, obj.ptr, obj); + return obj; + } + + __destroy_into_raw() { + const ptr = this.ptr; + this.ptr = 0; + ScriptPubkeyFinalization.unregister(this); + return ptr; + } + + free() { + const ptr = this.__destroy_into_raw(); + wasm.__wbg_scriptpubkey_free(ptr); + } + /** + * @returns {Uint8Array} + */ + to_bytes() { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + wasm.scriptpubkey_to_bytes(retptr, this.ptr); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var v0 = getArrayU8FromWasm0(r0, r1).slice(); + wasm.__wbindgen_free(r0, r1 * 1); + return v0; + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @param {Uint8Array} bytes + * @returns {ScriptPubkey} + */ + static from_bytes(bytes) { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + const ptr0 = passArray8ToWasm0(bytes, wasm.__wbindgen_malloc); + const len0 = WASM_VECTOR_LEN; + wasm.scriptpubkey_from_bytes(retptr, ptr0, len0); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + if (r2) { + throw takeObject(r1); + } + return ScriptPubkey.__wrap(r0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @returns {string} + */ + to_json() { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + wasm.scriptpubkey_to_json(retptr, this.ptr); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + var r3 = getInt32Memory0()[retptr / 4 + 3]; + var ptr0 = r0; + var len0 = r1; + if (r3) { + ptr0 = 0; + len0 = 0; + throw takeObject(r2); + } + return getStringFromWasm0(ptr0, len0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + wasm.__wbindgen_free(ptr0, len0); + } + } + /** + * @returns {any} + */ + to_js_value() { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + wasm.scriptpubkey_to_js_value(retptr, this.ptr); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + if (r2) { + throw takeObject(r1); + } + return takeObject(r0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @param {string} json + * @returns {ScriptPubkey} + */ + static from_json(json) { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + const ptr0 = passStringToWasm0( + json, + wasm.__wbindgen_malloc, + wasm.__wbindgen_realloc, + ); + const len0 = WASM_VECTOR_LEN; + wasm.scriptpubkey_from_json(retptr, ptr0, len0); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + if (r2) { + throw takeObject(r1); + } + return ScriptPubkey.__wrap(r0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @returns {Ed25519KeyHash} + */ + addr_keyhash() { + const ret = wasm.regcommitteehotkeycert_committee_cold_keyhash(this.ptr); + return Ed25519KeyHash.__wrap(ret); + } + /** + * @param {Ed25519KeyHash} addr_keyhash + * @returns {ScriptPubkey} + */ + static new(addr_keyhash) { + _assertClass(addr_keyhash, Ed25519KeyHash); + const ret = wasm.scriptpubkey_new(addr_keyhash.ptr); + return ScriptPubkey.__wrap(ret); + } +} +module.exports.ScriptPubkey = ScriptPubkey; + +const ScriptRefFinalization = new FinalizationRegistry((ptr) => + wasm.__wbg_scriptref_free(ptr) +); +/** */ +class ScriptRef { + static __wrap(ptr) { + const obj = Object.create(ScriptRef.prototype); + obj.ptr = ptr; + ScriptRefFinalization.register(obj, obj.ptr, obj); + return obj; + } + + __destroy_into_raw() { + const ptr = this.ptr; + this.ptr = 0; + ScriptRefFinalization.unregister(this); + return ptr; + } + + free() { + const ptr = this.__destroy_into_raw(); + wasm.__wbg_scriptref_free(ptr); + } + /** + * @returns {Uint8Array} + */ + to_bytes() { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + wasm.scriptref_to_bytes(retptr, this.ptr); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var v0 = getArrayU8FromWasm0(r0, r1).slice(); + wasm.__wbindgen_free(r0, r1 * 1); + return v0; + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @param {Uint8Array} bytes + * @returns {ScriptRef} + */ + static from_bytes(bytes) { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + const ptr0 = passArray8ToWasm0(bytes, wasm.__wbindgen_malloc); + const len0 = WASM_VECTOR_LEN; + wasm.scriptref_from_bytes(retptr, ptr0, len0); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + if (r2) { + throw takeObject(r1); + } + return ScriptRef.__wrap(r0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @returns {string} + */ + to_json() { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + wasm.script_to_json(retptr, this.ptr); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + var r3 = getInt32Memory0()[retptr / 4 + 3]; + var ptr0 = r0; + var len0 = r1; + if (r3) { + ptr0 = 0; + len0 = 0; + throw takeObject(r2); + } + return getStringFromWasm0(ptr0, len0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + wasm.__wbindgen_free(ptr0, len0); + } + } + /** + * @returns {any} + */ + to_js_value() { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + wasm.script_to_js_value(retptr, this.ptr); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + if (r2) { + throw takeObject(r1); + } + return takeObject(r0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @param {string} json + * @returns {ScriptRef} + */ + static from_json(json) { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + const ptr0 = passStringToWasm0( + json, + wasm.__wbindgen_malloc, + wasm.__wbindgen_realloc, + ); + const len0 = WASM_VECTOR_LEN; + wasm.scriptref_from_json(retptr, ptr0, len0); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + if (r2) { + throw takeObject(r1); + } + return ScriptRef.__wrap(r0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @param {Script} script + * @returns {ScriptRef} + */ + static new(script) { + _assertClass(script, Script); + const ret = wasm.scriptref_new(script.ptr); + return ScriptRef.__wrap(ret); + } + /** + * @returns {Script} + */ + get() { + const ret = wasm.scriptref_get(this.ptr); + return Script.__wrap(ret); + } +} +module.exports.ScriptRef = ScriptRef; + +const ScriptWitnessFinalization = new FinalizationRegistry((ptr) => + wasm.__wbg_scriptwitness_free(ptr) +); +/** */ +class ScriptWitness { + static __wrap(ptr) { + const obj = Object.create(ScriptWitness.prototype); + obj.ptr = ptr; + ScriptWitnessFinalization.register(obj, obj.ptr, obj); + return obj; + } + + __destroy_into_raw() { + const ptr = this.ptr; + this.ptr = 0; + ScriptWitnessFinalization.unregister(this); + return ptr; + } + + free() { + const ptr = this.__destroy_into_raw(); + wasm.__wbg_scriptwitness_free(ptr); + } + /** + * @returns {string} + */ + to_json() { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + wasm.scriptwitness_to_json(retptr, this.ptr); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + var r3 = getInt32Memory0()[retptr / 4 + 3]; + var ptr0 = r0; + var len0 = r1; + if (r3) { + ptr0 = 0; + len0 = 0; + throw takeObject(r2); + } + return getStringFromWasm0(ptr0, len0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + wasm.__wbindgen_free(ptr0, len0); + } + } + /** + * @returns {any} + */ + to_js_value() { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + wasm.scriptwitness_to_js_value(retptr, this.ptr); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + if (r2) { + throw takeObject(r1); + } + return takeObject(r0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @param {string} json + * @returns {ScriptWitness} + */ + static from_json(json) { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + const ptr0 = passStringToWasm0( + json, + wasm.__wbindgen_malloc, + wasm.__wbindgen_realloc, + ); + const len0 = WASM_VECTOR_LEN; + wasm.scriptwitness_from_json(retptr, ptr0, len0); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + if (r2) { + throw takeObject(r1); + } + return ScriptWitness.__wrap(r0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @param {NativeScript} native_script + * @returns {ScriptWitness} + */ + static new_native_witness(native_script) { + _assertClass(native_script, NativeScript); + const ret = wasm.scriptwitness_new_native_witness(native_script.ptr); + return ScriptWitness.__wrap(ret); + } + /** + * @param {PlutusWitness} plutus_witness + * @returns {ScriptWitness} + */ + static new_plutus_witness(plutus_witness) { + _assertClass(plutus_witness, PlutusWitness); + const ret = wasm.scriptwitness_new_plutus_witness(plutus_witness.ptr); + return ScriptWitness.__wrap(ret); + } + /** + * @returns {number} + */ + kind() { + const ret = wasm.scriptwitness_kind(this.ptr); + return ret >>> 0; + } + /** + * @returns {NativeScript | undefined} + */ + as_native_witness() { + const ret = wasm.scriptwitness_as_native_witness(this.ptr); + return ret === 0 ? undefined : NativeScript.__wrap(ret); + } + /** + * @returns {PlutusWitness | undefined} + */ + as_plutus_witness() { + const ret = wasm.scriptwitness_as_plutus_witness(this.ptr); + return ret === 0 ? undefined : PlutusWitness.__wrap(ret); + } +} +module.exports.ScriptWitness = ScriptWitness; + +const SingleHostAddrFinalization = new FinalizationRegistry((ptr) => + wasm.__wbg_singlehostaddr_free(ptr) +); +/** */ +class SingleHostAddr { + static __wrap(ptr) { + const obj = Object.create(SingleHostAddr.prototype); + obj.ptr = ptr; + SingleHostAddrFinalization.register(obj, obj.ptr, obj); + return obj; + } + + __destroy_into_raw() { + const ptr = this.ptr; + this.ptr = 0; + SingleHostAddrFinalization.unregister(this); + return ptr; + } + + free() { + const ptr = this.__destroy_into_raw(); + wasm.__wbg_singlehostaddr_free(ptr); + } + /** + * @returns {Uint8Array} + */ + to_bytes() { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + wasm.singlehostaddr_to_bytes(retptr, this.ptr); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var v0 = getArrayU8FromWasm0(r0, r1).slice(); + wasm.__wbindgen_free(r0, r1 * 1); + return v0; + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @param {Uint8Array} bytes + * @returns {SingleHostAddr} + */ + static from_bytes(bytes) { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + const ptr0 = passArray8ToWasm0(bytes, wasm.__wbindgen_malloc); + const len0 = WASM_VECTOR_LEN; + wasm.singlehostaddr_from_bytes(retptr, ptr0, len0); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + if (r2) { + throw takeObject(r1); + } + return SingleHostAddr.__wrap(r0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @returns {string} + */ + to_json() { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + wasm.singlehostaddr_to_json(retptr, this.ptr); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + var r3 = getInt32Memory0()[retptr / 4 + 3]; + var ptr0 = r0; + var len0 = r1; + if (r3) { + ptr0 = 0; + len0 = 0; + throw takeObject(r2); + } + return getStringFromWasm0(ptr0, len0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + wasm.__wbindgen_free(ptr0, len0); + } + } + /** + * @returns {any} + */ + to_js_value() { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + wasm.singlehostaddr_to_js_value(retptr, this.ptr); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + if (r2) { + throw takeObject(r1); + } + return takeObject(r0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @param {string} json + * @returns {SingleHostAddr} + */ + static from_json(json) { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + const ptr0 = passStringToWasm0( + json, + wasm.__wbindgen_malloc, + wasm.__wbindgen_realloc, + ); + const len0 = WASM_VECTOR_LEN; + wasm.singlehostaddr_from_json(retptr, ptr0, len0); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + if (r2) { + throw takeObject(r1); + } + return SingleHostAddr.__wrap(r0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @returns {number | undefined} + */ + port() { + const ret = wasm.singlehostaddr_port(this.ptr); + return ret === 0xFFFFFF ? undefined : ret; + } + /** + * @returns {Ipv4 | undefined} + */ + ipv4() { + const ret = wasm.singlehostaddr_ipv4(this.ptr); + return ret === 0 ? undefined : Ipv4.__wrap(ret); + } + /** + * @returns {Ipv6 | undefined} + */ + ipv6() { + const ret = wasm.singlehostaddr_ipv6(this.ptr); + return ret === 0 ? undefined : Ipv6.__wrap(ret); + } + /** + * @param {number | undefined} port + * @param {Ipv4 | undefined} ipv4 + * @param {Ipv6 | undefined} ipv6 + * @returns {SingleHostAddr} + */ + static new(port, ipv4, ipv6) { + let ptr0 = 0; + if (!isLikeNone(ipv4)) { + _assertClass(ipv4, Ipv4); + ptr0 = ipv4.__destroy_into_raw(); + } + let ptr1 = 0; + if (!isLikeNone(ipv6)) { + _assertClass(ipv6, Ipv6); + ptr1 = ipv6.__destroy_into_raw(); + } + const ret = wasm.singlehostaddr_new( + isLikeNone(port) ? 0xFFFFFF : port, + ptr0, + ptr1, + ); + return SingleHostAddr.__wrap(ret); + } +} +module.exports.SingleHostAddr = SingleHostAddr; + +const SingleHostNameFinalization = new FinalizationRegistry((ptr) => + wasm.__wbg_singlehostname_free(ptr) +); +/** */ +class SingleHostName { + static __wrap(ptr) { + const obj = Object.create(SingleHostName.prototype); + obj.ptr = ptr; + SingleHostNameFinalization.register(obj, obj.ptr, obj); + return obj; + } + + __destroy_into_raw() { + const ptr = this.ptr; + this.ptr = 0; + SingleHostNameFinalization.unregister(this); + return ptr; + } + + free() { + const ptr = this.__destroy_into_raw(); + wasm.__wbg_singlehostname_free(ptr); + } + /** + * @returns {Uint8Array} + */ + to_bytes() { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + wasm.singlehostname_to_bytes(retptr, this.ptr); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var v0 = getArrayU8FromWasm0(r0, r1).slice(); + wasm.__wbindgen_free(r0, r1 * 1); + return v0; + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @param {Uint8Array} bytes + * @returns {SingleHostName} + */ + static from_bytes(bytes) { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + const ptr0 = passArray8ToWasm0(bytes, wasm.__wbindgen_malloc); + const len0 = WASM_VECTOR_LEN; + wasm.singlehostname_from_bytes(retptr, ptr0, len0); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + if (r2) { + throw takeObject(r1); + } + return SingleHostName.__wrap(r0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @returns {string} + */ + to_json() { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + wasm.singlehostname_to_json(retptr, this.ptr); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + var r3 = getInt32Memory0()[retptr / 4 + 3]; + var ptr0 = r0; + var len0 = r1; + if (r3) { + ptr0 = 0; + len0 = 0; + throw takeObject(r2); + } + return getStringFromWasm0(ptr0, len0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + wasm.__wbindgen_free(ptr0, len0); + } + } + /** + * @returns {any} + */ + to_js_value() { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + wasm.singlehostname_to_js_value(retptr, this.ptr); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + if (r2) { + throw takeObject(r1); + } + return takeObject(r0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @param {string} json + * @returns {SingleHostName} + */ + static from_json(json) { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + const ptr0 = passStringToWasm0( + json, + wasm.__wbindgen_malloc, + wasm.__wbindgen_realloc, + ); + const len0 = WASM_VECTOR_LEN; + wasm.singlehostname_from_json(retptr, ptr0, len0); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + if (r2) { + throw takeObject(r1); + } + return SingleHostName.__wrap(r0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @returns {number | undefined} + */ + port() { + const ret = wasm.singlehostname_port(this.ptr); + return ret === 0xFFFFFF ? undefined : ret; + } + /** + * @returns {DNSRecordAorAAAA} + */ + dns_name() { + const ret = wasm.singlehostname_dns_name(this.ptr); + return DNSRecordAorAAAA.__wrap(ret); + } + /** + * @param {number | undefined} port + * @param {DNSRecordAorAAAA} dns_name + * @returns {SingleHostName} + */ + static new(port, dns_name) { + _assertClass(dns_name, DNSRecordAorAAAA); + const ret = wasm.singlehostname_new( + isLikeNone(port) ? 0xFFFFFF : port, + dns_name.ptr, + ); + return SingleHostName.__wrap(ret); + } +} +module.exports.SingleHostName = SingleHostName; + +const StakeCredentialFinalization = new FinalizationRegistry((ptr) => + wasm.__wbg_stakecredential_free(ptr) +); +/** */ +class StakeCredential { + static __wrap(ptr) { + const obj = Object.create(StakeCredential.prototype); + obj.ptr = ptr; + StakeCredentialFinalization.register(obj, obj.ptr, obj); + return obj; + } + + __destroy_into_raw() { + const ptr = this.ptr; + this.ptr = 0; + StakeCredentialFinalization.unregister(this); + return ptr; + } + + free() { + const ptr = this.__destroy_into_raw(); + wasm.__wbg_stakecredential_free(ptr); + } + /** + * @param {Ed25519KeyHash} hash + * @returns {StakeCredential} + */ + static from_keyhash(hash) { + _assertClass(hash, Ed25519KeyHash); + const ret = wasm.drep_new_keyhash(hash.ptr); + return StakeCredential.__wrap(ret); + } + /** + * @param {ScriptHash} hash + * @returns {StakeCredential} + */ + static from_scripthash(hash) { + _assertClass(hash, ScriptHash); + const ret = wasm.drep_new_scripthash(hash.ptr); + return StakeCredential.__wrap(ret); + } + /** + * @returns {Ed25519KeyHash | undefined} + */ + to_keyhash() { + const ret = wasm.stakecredential_to_keyhash(this.ptr); + return ret === 0 ? undefined : Ed25519KeyHash.__wrap(ret); + } + /** + * @returns {ScriptHash | undefined} + */ + to_scripthash() { + const ret = wasm.stakecredential_to_scripthash(this.ptr); + return ret === 0 ? undefined : ScriptHash.__wrap(ret); + } + /** + * @returns {number} + */ + kind() { + const ret = wasm.networkid_kind(this.ptr); + return ret >>> 0; + } + /** + * @returns {Uint8Array} + */ + to_bytes() { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + wasm.stakecredential_to_bytes(retptr, this.ptr); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var v0 = getArrayU8FromWasm0(r0, r1).slice(); + wasm.__wbindgen_free(r0, r1 * 1); + return v0; + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @param {Uint8Array} bytes + * @returns {StakeCredential} + */ + static from_bytes(bytes) { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + const ptr0 = passArray8ToWasm0(bytes, wasm.__wbindgen_malloc); + const len0 = WASM_VECTOR_LEN; + wasm.stakecredential_from_bytes(retptr, ptr0, len0); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + if (r2) { + throw takeObject(r1); + } + return StakeCredential.__wrap(r0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @returns {string} + */ + to_json() { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + wasm.stakecredential_to_json(retptr, this.ptr); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + var r3 = getInt32Memory0()[retptr / 4 + 3]; + var ptr0 = r0; + var len0 = r1; + if (r3) { + ptr0 = 0; + len0 = 0; + throw takeObject(r2); + } + return getStringFromWasm0(ptr0, len0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + wasm.__wbindgen_free(ptr0, len0); + } + } + /** + * @returns {any} + */ + to_js_value() { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + wasm.stakecredential_to_js_value(retptr, this.ptr); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + if (r2) { + throw takeObject(r1); + } + return takeObject(r0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @param {string} json + * @returns {StakeCredential} + */ + static from_json(json) { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + const ptr0 = passStringToWasm0( + json, + wasm.__wbindgen_malloc, + wasm.__wbindgen_realloc, + ); + const len0 = WASM_VECTOR_LEN; + wasm.stakecredential_from_json(retptr, ptr0, len0); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + if (r2) { + throw takeObject(r1); + } + return StakeCredential.__wrap(r0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } +} +module.exports.StakeCredential = StakeCredential; + +const StakeCredentialsFinalization = new FinalizationRegistry((ptr) => + wasm.__wbg_stakecredentials_free(ptr) +); +/** */ +class StakeCredentials { + static __wrap(ptr) { + const obj = Object.create(StakeCredentials.prototype); + obj.ptr = ptr; + StakeCredentialsFinalization.register(obj, obj.ptr, obj); + return obj; + } + + __destroy_into_raw() { + const ptr = this.ptr; + this.ptr = 0; + StakeCredentialsFinalization.unregister(this); + return ptr; + } + + free() { + const ptr = this.__destroy_into_raw(); + wasm.__wbg_stakecredentials_free(ptr); + } + /** + * @returns {Uint8Array} + */ + to_bytes() { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + wasm.stakecredentials_to_bytes(retptr, this.ptr); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var v0 = getArrayU8FromWasm0(r0, r1).slice(); + wasm.__wbindgen_free(r0, r1 * 1); + return v0; + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @param {Uint8Array} bytes + * @returns {StakeCredentials} + */ + static from_bytes(bytes) { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + const ptr0 = passArray8ToWasm0(bytes, wasm.__wbindgen_malloc); + const len0 = WASM_VECTOR_LEN; + wasm.stakecredentials_from_bytes(retptr, ptr0, len0); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + if (r2) { + throw takeObject(r1); + } + return StakeCredentials.__wrap(r0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @returns {string} + */ + to_json() { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + wasm.stakecredentials_to_json(retptr, this.ptr); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + var r3 = getInt32Memory0()[retptr / 4 + 3]; + var ptr0 = r0; + var len0 = r1; + if (r3) { + ptr0 = 0; + len0 = 0; + throw takeObject(r2); + } + return getStringFromWasm0(ptr0, len0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + wasm.__wbindgen_free(ptr0, len0); + } + } + /** + * @returns {any} + */ + to_js_value() { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + wasm.stakecredentials_to_js_value(retptr, this.ptr); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + if (r2) { + throw takeObject(r1); + } + return takeObject(r0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @param {string} json + * @returns {StakeCredentials} + */ + static from_json(json) { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + const ptr0 = passStringToWasm0( + json, + wasm.__wbindgen_malloc, + wasm.__wbindgen_realloc, + ); + const len0 = WASM_VECTOR_LEN; + wasm.stakecredentials_from_json(retptr, ptr0, len0); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + if (r2) { + throw takeObject(r1); + } + return StakeCredentials.__wrap(r0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @returns {StakeCredentials} + */ + static new() { + const ret = wasm.ed25519keyhashes_new(); + return StakeCredentials.__wrap(ret); + } + /** + * @returns {number} + */ + len() { + const ret = wasm.assetnames_len(this.ptr); + return ret >>> 0; + } + /** + * @param {number} index + * @returns {StakeCredential} + */ + get(index) { + const ret = wasm.stakecredentials_get(this.ptr, index); + return StakeCredential.__wrap(ret); + } + /** + * @param {StakeCredential} elem + */ + add(elem) { + _assertClass(elem, StakeCredential); + wasm.stakecredentials_add(this.ptr, elem.ptr); + } +} +module.exports.StakeCredentials = StakeCredentials; + +const StakeDelegationFinalization = new FinalizationRegistry((ptr) => + wasm.__wbg_stakedelegation_free(ptr) +); +/** */ +class StakeDelegation { + static __wrap(ptr) { + const obj = Object.create(StakeDelegation.prototype); + obj.ptr = ptr; + StakeDelegationFinalization.register(obj, obj.ptr, obj); + return obj; + } + + __destroy_into_raw() { + const ptr = this.ptr; + this.ptr = 0; + StakeDelegationFinalization.unregister(this); + return ptr; + } + + free() { + const ptr = this.__destroy_into_raw(); + wasm.__wbg_stakedelegation_free(ptr); + } + /** + * @returns {Uint8Array} + */ + to_bytes() { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + wasm.stakedelegation_to_bytes(retptr, this.ptr); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var v0 = getArrayU8FromWasm0(r0, r1).slice(); + wasm.__wbindgen_free(r0, r1 * 1); + return v0; + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @param {Uint8Array} bytes + * @returns {StakeDelegation} + */ + static from_bytes(bytes) { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + const ptr0 = passArray8ToWasm0(bytes, wasm.__wbindgen_malloc); + const len0 = WASM_VECTOR_LEN; + wasm.stakedelegation_from_bytes(retptr, ptr0, len0); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + if (r2) { + throw takeObject(r1); + } + return StakeDelegation.__wrap(r0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @returns {string} + */ + to_json() { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + wasm.stakedelegation_to_json(retptr, this.ptr); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + var r3 = getInt32Memory0()[retptr / 4 + 3]; + var ptr0 = r0; + var len0 = r1; + if (r3) { + ptr0 = 0; + len0 = 0; + throw takeObject(r2); + } + return getStringFromWasm0(ptr0, len0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + wasm.__wbindgen_free(ptr0, len0); + } + } + /** + * @returns {any} + */ + to_js_value() { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + wasm.stakedelegation_to_js_value(retptr, this.ptr); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + if (r2) { + throw takeObject(r1); + } + return takeObject(r0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @param {string} json + * @returns {StakeDelegation} + */ + static from_json(json) { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + const ptr0 = passStringToWasm0( + json, + wasm.__wbindgen_malloc, + wasm.__wbindgen_realloc, + ); + const len0 = WASM_VECTOR_LEN; + wasm.stakedelegation_from_json(retptr, ptr0, len0); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + if (r2) { + throw takeObject(r1); + } + return StakeDelegation.__wrap(r0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @returns {StakeCredential} + */ + stake_credential() { + const ret = wasm.baseaddress_payment_cred(this.ptr); + return StakeCredential.__wrap(ret); + } + /** + * @returns {Ed25519KeyHash} + */ + pool_keyhash() { + const ret = wasm.stakedelegation_pool_keyhash(this.ptr); + return Ed25519KeyHash.__wrap(ret); + } + /** + * @param {StakeCredential} stake_credential + * @param {Ed25519KeyHash} pool_keyhash + * @returns {StakeDelegation} + */ + static new(stake_credential, pool_keyhash) { + _assertClass(stake_credential, StakeCredential); + _assertClass(pool_keyhash, Ed25519KeyHash); + const ret = wasm.stakedelegation_new( + stake_credential.ptr, + pool_keyhash.ptr, + ); + return StakeDelegation.__wrap(ret); + } +} +module.exports.StakeDelegation = StakeDelegation; + +const StakeDeregistrationFinalization = new FinalizationRegistry((ptr) => + wasm.__wbg_stakederegistration_free(ptr) +); +/** */ +class StakeDeregistration { + static __wrap(ptr) { + const obj = Object.create(StakeDeregistration.prototype); + obj.ptr = ptr; + StakeDeregistrationFinalization.register(obj, obj.ptr, obj); + return obj; + } + + __destroy_into_raw() { + const ptr = this.ptr; + this.ptr = 0; + StakeDeregistrationFinalization.unregister(this); + return ptr; + } + + free() { + const ptr = this.__destroy_into_raw(); + wasm.__wbg_stakederegistration_free(ptr); + } + /** + * @returns {Uint8Array} + */ + to_bytes() { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + wasm.stakederegistration_to_bytes(retptr, this.ptr); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var v0 = getArrayU8FromWasm0(r0, r1).slice(); + wasm.__wbindgen_free(r0, r1 * 1); + return v0; + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @param {Uint8Array} bytes + * @returns {StakeDeregistration} + */ + static from_bytes(bytes) { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + const ptr0 = passArray8ToWasm0(bytes, wasm.__wbindgen_malloc); + const len0 = WASM_VECTOR_LEN; + wasm.stakederegistration_from_bytes(retptr, ptr0, len0); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + if (r2) { + throw takeObject(r1); + } + return StakeDeregistration.__wrap(r0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @returns {string} + */ + to_json() { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + wasm.stakederegistration_to_json(retptr, this.ptr); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + var r3 = getInt32Memory0()[retptr / 4 + 3]; + var ptr0 = r0; + var len0 = r1; + if (r3) { + ptr0 = 0; + len0 = 0; + throw takeObject(r2); + } + return getStringFromWasm0(ptr0, len0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + wasm.__wbindgen_free(ptr0, len0); + } + } + /** + * @returns {any} + */ + to_js_value() { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + wasm.stakederegistration_to_js_value(retptr, this.ptr); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + if (r2) { + throw takeObject(r1); + } + return takeObject(r0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @param {string} json + * @returns {StakeDeregistration} + */ + static from_json(json) { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + const ptr0 = passStringToWasm0( + json, + wasm.__wbindgen_malloc, + wasm.__wbindgen_realloc, + ); + const len0 = WASM_VECTOR_LEN; + wasm.stakederegistration_from_json(retptr, ptr0, len0); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + if (r2) { + throw takeObject(r1); + } + return StakeDeregistration.__wrap(r0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @returns {StakeCredential} + */ + stake_credential() { + const ret = wasm.baseaddress_payment_cred(this.ptr); + return StakeCredential.__wrap(ret); + } + /** + * @param {StakeCredential} stake_credential + * @returns {StakeDeregistration} + */ + static new(stake_credential) { + _assertClass(stake_credential, StakeCredential); + const ret = wasm.stakederegistration_new(stake_credential.ptr); + return StakeDeregistration.__wrap(ret); + } +} +module.exports.StakeDeregistration = StakeDeregistration; + +const StakeRegDelegCertFinalization = new FinalizationRegistry((ptr) => + wasm.__wbg_stakeregdelegcert_free(ptr) +); +/** */ +class StakeRegDelegCert { + static __wrap(ptr) { + const obj = Object.create(StakeRegDelegCert.prototype); + obj.ptr = ptr; + StakeRegDelegCertFinalization.register(obj, obj.ptr, obj); + return obj; + } + + __destroy_into_raw() { + const ptr = this.ptr; + this.ptr = 0; + StakeRegDelegCertFinalization.unregister(this); + return ptr; + } + + free() { + const ptr = this.__destroy_into_raw(); + wasm.__wbg_stakeregdelegcert_free(ptr); + } + /** + * @returns {Uint8Array} + */ + to_bytes() { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + wasm.stakeregdelegcert_to_bytes(retptr, this.ptr); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var v0 = getArrayU8FromWasm0(r0, r1).slice(); + wasm.__wbindgen_free(r0, r1 * 1); + return v0; + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @param {Uint8Array} bytes + * @returns {StakeRegDelegCert} + */ + static from_bytes(bytes) { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + const ptr0 = passArray8ToWasm0(bytes, wasm.__wbindgen_malloc); + const len0 = WASM_VECTOR_LEN; + wasm.stakeregdelegcert_from_bytes(retptr, ptr0, len0); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + if (r2) { + throw takeObject(r1); + } + return StakeRegDelegCert.__wrap(r0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @returns {string} + */ + to_json() { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + wasm.stakeregdelegcert_to_json(retptr, this.ptr); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + var r3 = getInt32Memory0()[retptr / 4 + 3]; + var ptr0 = r0; + var len0 = r1; + if (r3) { + ptr0 = 0; + len0 = 0; + throw takeObject(r2); + } + return getStringFromWasm0(ptr0, len0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + wasm.__wbindgen_free(ptr0, len0); + } + } + /** + * @returns {any} + */ + to_js_value() { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + wasm.stakeregdelegcert_to_js_value(retptr, this.ptr); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + if (r2) { + throw takeObject(r1); + } + return takeObject(r0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @param {string} json + * @returns {StakeRegDelegCert} + */ + static from_json(json) { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + const ptr0 = passStringToWasm0( + json, + wasm.__wbindgen_malloc, + wasm.__wbindgen_realloc, + ); + const len0 = WASM_VECTOR_LEN; + wasm.stakeregdelegcert_from_json(retptr, ptr0, len0); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + if (r2) { + throw takeObject(r1); + } + return StakeRegDelegCert.__wrap(r0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @returns {StakeCredential} + */ + stake_credential() { + const ret = wasm.stakeregdelegcert_stake_credential(this.ptr); + return StakeCredential.__wrap(ret); + } + /** + * @returns {Ed25519KeyHash} + */ + pool_keyhash() { + const ret = wasm.stakeregdelegcert_pool_keyhash(this.ptr); + return Ed25519KeyHash.__wrap(ret); + } + /** + * @returns {BigNum} + */ + coin() { + const ret = wasm.constrplutusdata_alternative(this.ptr); + return BigNum.__wrap(ret); + } + /** + * @param {StakeCredential} stake_credential + * @param {Ed25519KeyHash} pool_keyhash + * @param {BigNum} coin + * @returns {StakeRegDelegCert} + */ + static new(stake_credential, pool_keyhash, coin) { + _assertClass(stake_credential, StakeCredential); + _assertClass(pool_keyhash, Ed25519KeyHash); + _assertClass(coin, BigNum); + const ret = wasm.stakeregdelegcert_new( + stake_credential.ptr, + pool_keyhash.ptr, + coin.ptr, + ); + return StakeRegDelegCert.__wrap(ret); + } +} +module.exports.StakeRegDelegCert = StakeRegDelegCert; + +const StakeRegistrationFinalization = new FinalizationRegistry((ptr) => + wasm.__wbg_stakeregistration_free(ptr) +); +/** */ +class StakeRegistration { + static __wrap(ptr) { + const obj = Object.create(StakeRegistration.prototype); + obj.ptr = ptr; + StakeRegistrationFinalization.register(obj, obj.ptr, obj); + return obj; + } + + __destroy_into_raw() { + const ptr = this.ptr; + this.ptr = 0; + StakeRegistrationFinalization.unregister(this); + return ptr; + } + + free() { + const ptr = this.__destroy_into_raw(); + wasm.__wbg_stakeregistration_free(ptr); + } + /** + * @returns {Uint8Array} + */ + to_bytes() { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + wasm.stakeregistration_to_bytes(retptr, this.ptr); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var v0 = getArrayU8FromWasm0(r0, r1).slice(); + wasm.__wbindgen_free(r0, r1 * 1); + return v0; + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @param {Uint8Array} bytes + * @returns {StakeRegistration} + */ + static from_bytes(bytes) { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + const ptr0 = passArray8ToWasm0(bytes, wasm.__wbindgen_malloc); + const len0 = WASM_VECTOR_LEN; + wasm.stakeregistration_from_bytes(retptr, ptr0, len0); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + if (r2) { + throw takeObject(r1); + } + return StakeRegistration.__wrap(r0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @returns {string} + */ + to_json() { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + wasm.stakederegistration_to_json(retptr, this.ptr); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + var r3 = getInt32Memory0()[retptr / 4 + 3]; + var ptr0 = r0; + var len0 = r1; + if (r3) { + ptr0 = 0; + len0 = 0; + throw takeObject(r2); + } + return getStringFromWasm0(ptr0, len0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + wasm.__wbindgen_free(ptr0, len0); + } + } + /** + * @returns {any} + */ + to_js_value() { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + wasm.stakederegistration_to_js_value(retptr, this.ptr); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + if (r2) { + throw takeObject(r1); + } + return takeObject(r0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @param {string} json + * @returns {StakeRegistration} + */ + static from_json(json) { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + const ptr0 = passStringToWasm0( + json, + wasm.__wbindgen_malloc, + wasm.__wbindgen_realloc, + ); + const len0 = WASM_VECTOR_LEN; + wasm.stakeregistration_from_json(retptr, ptr0, len0); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + if (r2) { + throw takeObject(r1); + } + return StakeRegistration.__wrap(r0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @returns {StakeCredential} + */ + stake_credential() { + const ret = wasm.baseaddress_payment_cred(this.ptr); + return StakeCredential.__wrap(ret); + } + /** + * @param {StakeCredential} stake_credential + * @returns {StakeRegistration} + */ + static new(stake_credential) { + _assertClass(stake_credential, StakeCredential); + const ret = wasm.stakederegistration_new(stake_credential.ptr); + return StakeRegistration.__wrap(ret); + } +} +module.exports.StakeRegistration = StakeRegistration; + +const StakeVoteDelegCertFinalization = new FinalizationRegistry((ptr) => + wasm.__wbg_stakevotedelegcert_free(ptr) +); +/** */ +class StakeVoteDelegCert { + static __wrap(ptr) { + const obj = Object.create(StakeVoteDelegCert.prototype); + obj.ptr = ptr; + StakeVoteDelegCertFinalization.register(obj, obj.ptr, obj); + return obj; + } + + __destroy_into_raw() { + const ptr = this.ptr; + this.ptr = 0; + StakeVoteDelegCertFinalization.unregister(this); + return ptr; + } + + free() { + const ptr = this.__destroy_into_raw(); + wasm.__wbg_stakevotedelegcert_free(ptr); + } + /** + * @returns {Uint8Array} + */ + to_bytes() { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + wasm.stakevotedelegcert_to_bytes(retptr, this.ptr); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var v0 = getArrayU8FromWasm0(r0, r1).slice(); + wasm.__wbindgen_free(r0, r1 * 1); + return v0; + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @param {Uint8Array} bytes + * @returns {StakeVoteDelegCert} + */ + static from_bytes(bytes) { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + const ptr0 = passArray8ToWasm0(bytes, wasm.__wbindgen_malloc); + const len0 = WASM_VECTOR_LEN; + wasm.stakevotedelegcert_from_bytes(retptr, ptr0, len0); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + if (r2) { + throw takeObject(r1); + } + return StakeVoteDelegCert.__wrap(r0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @returns {string} + */ + to_json() { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + wasm.stakevotedelegcert_to_json(retptr, this.ptr); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + var r3 = getInt32Memory0()[retptr / 4 + 3]; + var ptr0 = r0; + var len0 = r1; + if (r3) { + ptr0 = 0; + len0 = 0; + throw takeObject(r2); + } + return getStringFromWasm0(ptr0, len0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + wasm.__wbindgen_free(ptr0, len0); + } + } + /** + * @returns {any} + */ + to_js_value() { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + wasm.stakevotedelegcert_to_js_value(retptr, this.ptr); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + if (r2) { + throw takeObject(r1); + } + return takeObject(r0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @param {string} json + * @returns {StakeVoteDelegCert} + */ + static from_json(json) { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + const ptr0 = passStringToWasm0( + json, + wasm.__wbindgen_malloc, + wasm.__wbindgen_realloc, + ); + const len0 = WASM_VECTOR_LEN; + wasm.stakevotedelegcert_from_json(retptr, ptr0, len0); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + if (r2) { + throw takeObject(r1); + } + return StakeVoteDelegCert.__wrap(r0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @returns {StakeCredential} + */ + stake_credential() { + const ret = wasm.baseaddress_payment_cred(this.ptr); + return StakeCredential.__wrap(ret); + } + /** + * @returns {Ed25519KeyHash} + */ + pool_keyhash() { + const ret = wasm.stakevotedelegcert_pool_keyhash(this.ptr); + return Ed25519KeyHash.__wrap(ret); + } + /** + * @returns {Drep} + */ + drep() { + const ret = wasm.stakevotedelegcert_drep(this.ptr); + return Drep.__wrap(ret); + } + /** + * @param {StakeCredential} stake_credential + * @param {Ed25519KeyHash} pool_keyhash + * @param {Drep} drep + * @returns {StakeVoteDelegCert} + */ + static new(stake_credential, pool_keyhash, drep) { + _assertClass(stake_credential, StakeCredential); + _assertClass(pool_keyhash, Ed25519KeyHash); + _assertClass(drep, Drep); + const ret = wasm.stakevotedelegcert_new( + stake_credential.ptr, + pool_keyhash.ptr, + drep.ptr, + ); + return StakeVoteDelegCert.__wrap(ret); + } +} +module.exports.StakeVoteDelegCert = StakeVoteDelegCert; + +const StakeVoteRegDelegCertFinalization = new FinalizationRegistry((ptr) => + wasm.__wbg_stakevoteregdelegcert_free(ptr) +); +/** */ +class StakeVoteRegDelegCert { + static __wrap(ptr) { + const obj = Object.create(StakeVoteRegDelegCert.prototype); + obj.ptr = ptr; + StakeVoteRegDelegCertFinalization.register(obj, obj.ptr, obj); + return obj; + } + + __destroy_into_raw() { + const ptr = this.ptr; + this.ptr = 0; + StakeVoteRegDelegCertFinalization.unregister(this); + return ptr; + } + + free() { + const ptr = this.__destroy_into_raw(); + wasm.__wbg_stakevoteregdelegcert_free(ptr); + } + /** + * @returns {Uint8Array} + */ + to_bytes() { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + wasm.stakevoteregdelegcert_to_bytes(retptr, this.ptr); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var v0 = getArrayU8FromWasm0(r0, r1).slice(); + wasm.__wbindgen_free(r0, r1 * 1); + return v0; + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @param {Uint8Array} bytes + * @returns {StakeVoteRegDelegCert} + */ + static from_bytes(bytes) { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + const ptr0 = passArray8ToWasm0(bytes, wasm.__wbindgen_malloc); + const len0 = WASM_VECTOR_LEN; + wasm.stakevoteregdelegcert_from_bytes(retptr, ptr0, len0); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + if (r2) { + throw takeObject(r1); + } + return StakeVoteRegDelegCert.__wrap(r0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @returns {string} + */ + to_json() { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + wasm.stakevoteregdelegcert_to_json(retptr, this.ptr); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + var r3 = getInt32Memory0()[retptr / 4 + 3]; + var ptr0 = r0; + var len0 = r1; + if (r3) { + ptr0 = 0; + len0 = 0; + throw takeObject(r2); + } + return getStringFromWasm0(ptr0, len0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + wasm.__wbindgen_free(ptr0, len0); + } + } + /** + * @returns {any} + */ + to_js_value() { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + wasm.stakevoteregdelegcert_to_js_value(retptr, this.ptr); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + if (r2) { + throw takeObject(r1); + } + return takeObject(r0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @param {string} json + * @returns {StakeVoteRegDelegCert} + */ + static from_json(json) { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + const ptr0 = passStringToWasm0( + json, + wasm.__wbindgen_malloc, + wasm.__wbindgen_realloc, + ); + const len0 = WASM_VECTOR_LEN; + wasm.stakevoteregdelegcert_from_json(retptr, ptr0, len0); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + if (r2) { + throw takeObject(r1); + } + return StakeVoteRegDelegCert.__wrap(r0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @returns {StakeCredential} + */ + stake_credential() { + const ret = wasm.stakevoteregdelegcert_stake_credential(this.ptr); + return StakeCredential.__wrap(ret); + } + /** + * @returns {Ed25519KeyHash} + */ + pool_keyhash() { + const ret = wasm.stakeregdelegcert_pool_keyhash(this.ptr); + return Ed25519KeyHash.__wrap(ret); + } + /** + * @returns {Drep} + */ + drep() { + const ret = wasm.stakevoteregdelegcert_drep(this.ptr); + return Drep.__wrap(ret); + } + /** + * @returns {BigNum} + */ + coin() { + const ret = wasm.constrplutusdata_alternative(this.ptr); + return BigNum.__wrap(ret); + } + /** + * @param {StakeCredential} stake_credential + * @param {Ed25519KeyHash} pool_keyhash + * @param {Drep} drep + * @param {BigNum} coin + * @returns {StakeVoteRegDelegCert} + */ + static new(stake_credential, pool_keyhash, drep, coin) { + _assertClass(stake_credential, StakeCredential); + _assertClass(pool_keyhash, Ed25519KeyHash); + _assertClass(drep, Drep); + _assertClass(coin, BigNum); + const ret = wasm.stakevoteregdelegcert_new( + stake_credential.ptr, + pool_keyhash.ptr, + drep.ptr, + coin.ptr, + ); + return StakeVoteRegDelegCert.__wrap(ret); + } +} +module.exports.StakeVoteRegDelegCert = StakeVoteRegDelegCert; + +const StringsFinalization = new FinalizationRegistry((ptr) => + wasm.__wbg_strings_free(ptr) +); +/** */ +class Strings { + static __wrap(ptr) { + const obj = Object.create(Strings.prototype); + obj.ptr = ptr; + StringsFinalization.register(obj, obj.ptr, obj); + return obj; + } + + __destroy_into_raw() { + const ptr = this.ptr; + this.ptr = 0; + StringsFinalization.unregister(this); + return ptr; + } + + free() { + const ptr = this.__destroy_into_raw(); + wasm.__wbg_strings_free(ptr); + } + /** + * @returns {Strings} + */ + static new() { + const ret = wasm.assetnames_new(); + return Strings.__wrap(ret); + } + /** + * @returns {number} + */ + len() { + const ret = wasm.assetnames_len(this.ptr); + return ret >>> 0; + } + /** + * @param {number} index + * @returns {string} + */ + get(index) { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + wasm.strings_get(retptr, this.ptr, index); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + return getStringFromWasm0(r0, r1); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + wasm.__wbindgen_free(r0, r1); + } + } + /** + * @param {string} elem + */ + add(elem) { + const ptr0 = passStringToWasm0( + elem, + wasm.__wbindgen_malloc, + wasm.__wbindgen_realloc, + ); + const len0 = WASM_VECTOR_LEN; + wasm.strings_add(this.ptr, ptr0, len0); + } +} +module.exports.Strings = Strings; + +const TimelockExpiryFinalization = new FinalizationRegistry((ptr) => + wasm.__wbg_timelockexpiry_free(ptr) +); +/** */ +class TimelockExpiry { + static __wrap(ptr) { + const obj = Object.create(TimelockExpiry.prototype); + obj.ptr = ptr; + TimelockExpiryFinalization.register(obj, obj.ptr, obj); + return obj; + } + + __destroy_into_raw() { + const ptr = this.ptr; + this.ptr = 0; + TimelockExpiryFinalization.unregister(this); + return ptr; + } + + free() { + const ptr = this.__destroy_into_raw(); + wasm.__wbg_timelockexpiry_free(ptr); + } + /** + * @returns {Uint8Array} + */ + to_bytes() { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + wasm.timelockexpiry_to_bytes(retptr, this.ptr); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var v0 = getArrayU8FromWasm0(r0, r1).slice(); + wasm.__wbindgen_free(r0, r1 * 1); + return v0; + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @param {Uint8Array} bytes + * @returns {TimelockExpiry} + */ + static from_bytes(bytes) { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + const ptr0 = passArray8ToWasm0(bytes, wasm.__wbindgen_malloc); + const len0 = WASM_VECTOR_LEN; + wasm.timelockexpiry_from_bytes(retptr, ptr0, len0); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + if (r2) { + throw takeObject(r1); + } + return TimelockExpiry.__wrap(r0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @returns {string} + */ + to_json() { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + wasm.timelockexpiry_to_json(retptr, this.ptr); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + var r3 = getInt32Memory0()[retptr / 4 + 3]; + var ptr0 = r0; + var len0 = r1; + if (r3) { + ptr0 = 0; + len0 = 0; + throw takeObject(r2); + } + return getStringFromWasm0(ptr0, len0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + wasm.__wbindgen_free(ptr0, len0); + } + } + /** + * @returns {any} + */ + to_js_value() { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + wasm.timelockexpiry_to_js_value(retptr, this.ptr); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + if (r2) { + throw takeObject(r1); + } + return takeObject(r0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @param {string} json + * @returns {TimelockExpiry} + */ + static from_json(json) { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + const ptr0 = passStringToWasm0( + json, + wasm.__wbindgen_malloc, + wasm.__wbindgen_realloc, + ); + const len0 = WASM_VECTOR_LEN; + wasm.timelockexpiry_from_json(retptr, ptr0, len0); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + if (r2) { + throw takeObject(r1); + } + return TimelockExpiry.__wrap(r0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @returns {BigNum} + */ + slot() { + const ret = wasm.linearfee_constant(this.ptr); + return BigNum.__wrap(ret); + } + /** + * @param {BigNum} slot + * @returns {TimelockExpiry} + */ + static new(slot) { + _assertClass(slot, BigNum); + const ret = wasm.constrplutusdata_alternative(slot.ptr); + return TimelockExpiry.__wrap(ret); + } +} +module.exports.TimelockExpiry = TimelockExpiry; + +const TimelockStartFinalization = new FinalizationRegistry((ptr) => + wasm.__wbg_timelockstart_free(ptr) +); +/** */ +class TimelockStart { + static __wrap(ptr) { + const obj = Object.create(TimelockStart.prototype); + obj.ptr = ptr; + TimelockStartFinalization.register(obj, obj.ptr, obj); + return obj; + } + + __destroy_into_raw() { + const ptr = this.ptr; + this.ptr = 0; + TimelockStartFinalization.unregister(this); + return ptr; + } + + free() { + const ptr = this.__destroy_into_raw(); + wasm.__wbg_timelockstart_free(ptr); + } + /** + * @returns {Uint8Array} + */ + to_bytes() { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + wasm.timelockstart_to_bytes(retptr, this.ptr); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var v0 = getArrayU8FromWasm0(r0, r1).slice(); + wasm.__wbindgen_free(r0, r1 * 1); + return v0; + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @param {Uint8Array} bytes + * @returns {TimelockStart} + */ + static from_bytes(bytes) { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + const ptr0 = passArray8ToWasm0(bytes, wasm.__wbindgen_malloc); + const len0 = WASM_VECTOR_LEN; + wasm.timelockstart_from_bytes(retptr, ptr0, len0); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + if (r2) { + throw takeObject(r1); + } + return TimelockStart.__wrap(r0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @returns {string} + */ + to_json() { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + wasm.timelockexpiry_to_json(retptr, this.ptr); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + var r3 = getInt32Memory0()[retptr / 4 + 3]; + var ptr0 = r0; + var len0 = r1; + if (r3) { + ptr0 = 0; + len0 = 0; + throw takeObject(r2); + } + return getStringFromWasm0(ptr0, len0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + wasm.__wbindgen_free(ptr0, len0); + } + } + /** + * @returns {any} + */ + to_js_value() { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + wasm.timelockexpiry_to_js_value(retptr, this.ptr); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + if (r2) { + throw takeObject(r1); + } + return takeObject(r0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @param {string} json + * @returns {TimelockStart} + */ + static from_json(json) { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + const ptr0 = passStringToWasm0( + json, + wasm.__wbindgen_malloc, + wasm.__wbindgen_realloc, + ); + const len0 = WASM_VECTOR_LEN; + wasm.timelockstart_from_json(retptr, ptr0, len0); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + if (r2) { + throw takeObject(r1); + } + return TimelockStart.__wrap(r0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @returns {BigNum} + */ + slot() { + const ret = wasm.linearfee_constant(this.ptr); + return BigNum.__wrap(ret); + } + /** + * @param {BigNum} slot + * @returns {TimelockStart} + */ + static new(slot) { + _assertClass(slot, BigNum); + const ret = wasm.constrplutusdata_alternative(slot.ptr); + return TimelockStart.__wrap(ret); + } +} +module.exports.TimelockStart = TimelockStart; + +const TransactionFinalization = new FinalizationRegistry((ptr) => + wasm.__wbg_transaction_free(ptr) +); +/** */ +class Transaction { + static __wrap(ptr) { + const obj = Object.create(Transaction.prototype); + obj.ptr = ptr; + TransactionFinalization.register(obj, obj.ptr, obj); + return obj; + } + + __destroy_into_raw() { + const ptr = this.ptr; + this.ptr = 0; + TransactionFinalization.unregister(this); + return ptr; + } + + free() { + const ptr = this.__destroy_into_raw(); + wasm.__wbg_transaction_free(ptr); + } + /** + * @returns {Uint8Array} + */ + to_bytes() { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + wasm.transaction_to_bytes(retptr, this.ptr); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var v0 = getArrayU8FromWasm0(r0, r1).slice(); + wasm.__wbindgen_free(r0, r1 * 1); + return v0; + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @param {Uint8Array} bytes + * @returns {Transaction} + */ + static from_bytes(bytes) { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + const ptr0 = passArray8ToWasm0(bytes, wasm.__wbindgen_malloc); + const len0 = WASM_VECTOR_LEN; + wasm.transaction_from_bytes(retptr, ptr0, len0); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + if (r2) { + throw takeObject(r1); + } + return Transaction.__wrap(r0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @returns {string} + */ + to_json() { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + wasm.transaction_to_json(retptr, this.ptr); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + var r3 = getInt32Memory0()[retptr / 4 + 3]; + var ptr0 = r0; + var len0 = r1; + if (r3) { + ptr0 = 0; + len0 = 0; + throw takeObject(r2); + } + return getStringFromWasm0(ptr0, len0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + wasm.__wbindgen_free(ptr0, len0); + } + } + /** + * @returns {any} + */ + to_js_value() { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + wasm.transaction_to_js_value(retptr, this.ptr); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + if (r2) { + throw takeObject(r1); + } + return takeObject(r0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @param {string} json + * @returns {Transaction} + */ + static from_json(json) { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + const ptr0 = passStringToWasm0( + json, + wasm.__wbindgen_malloc, + wasm.__wbindgen_realloc, + ); + const len0 = WASM_VECTOR_LEN; + wasm.transaction_from_json(retptr, ptr0, len0); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + if (r2) { + throw takeObject(r1); + } + return Transaction.__wrap(r0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @returns {TransactionBody} + */ + body() { + const ret = wasm.transaction_body(this.ptr); + return TransactionBody.__wrap(ret); + } + /** + * @returns {TransactionWitnessSet} + */ + witness_set() { + const ret = wasm.transaction_witness_set(this.ptr); + return TransactionWitnessSet.__wrap(ret); + } + /** + * @returns {boolean} + */ + is_valid() { + const ret = wasm.transaction_is_valid(this.ptr); + return ret !== 0; + } + /** + * @returns {AuxiliaryData | undefined} + */ + auxiliary_data() { + const ret = wasm.transaction_auxiliary_data(this.ptr); + return ret === 0 ? undefined : AuxiliaryData.__wrap(ret); + } + /** + * @param {boolean} valid + */ + set_is_valid(valid) { + wasm.transaction_set_is_valid(this.ptr, valid); + } + /** + * @param {TransactionBody} body + * @param {TransactionWitnessSet} witness_set + * @param {AuxiliaryData | undefined} auxiliary_data + * @returns {Transaction} + */ + static new(body, witness_set, auxiliary_data) { + _assertClass(body, TransactionBody); + _assertClass(witness_set, TransactionWitnessSet); + let ptr0 = 0; + if (!isLikeNone(auxiliary_data)) { + _assertClass(auxiliary_data, AuxiliaryData); + ptr0 = auxiliary_data.__destroy_into_raw(); + } + const ret = wasm.transaction_new(body.ptr, witness_set.ptr, ptr0); + return Transaction.__wrap(ret); + } +} +module.exports.Transaction = Transaction; + +const TransactionBodiesFinalization = new FinalizationRegistry((ptr) => + wasm.__wbg_transactionbodies_free(ptr) +); +/** */ +class TransactionBodies { + static __wrap(ptr) { + const obj = Object.create(TransactionBodies.prototype); + obj.ptr = ptr; + TransactionBodiesFinalization.register(obj, obj.ptr, obj); + return obj; + } + + __destroy_into_raw() { + const ptr = this.ptr; + this.ptr = 0; + TransactionBodiesFinalization.unregister(this); + return ptr; + } + + free() { + const ptr = this.__destroy_into_raw(); + wasm.__wbg_transactionbodies_free(ptr); + } + /** + * @returns {Uint8Array} + */ + to_bytes() { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + wasm.transactionbodies_to_bytes(retptr, this.ptr); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var v0 = getArrayU8FromWasm0(r0, r1).slice(); + wasm.__wbindgen_free(r0, r1 * 1); + return v0; + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @param {Uint8Array} bytes + * @returns {TransactionBodies} + */ + static from_bytes(bytes) { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + const ptr0 = passArray8ToWasm0(bytes, wasm.__wbindgen_malloc); + const len0 = WASM_VECTOR_LEN; + wasm.transactionbodies_from_bytes(retptr, ptr0, len0); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + if (r2) { + throw takeObject(r1); + } + return TransactionBodies.__wrap(r0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @returns {string} + */ + to_json() { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + wasm.transactionbodies_to_json(retptr, this.ptr); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + var r3 = getInt32Memory0()[retptr / 4 + 3]; + var ptr0 = r0; + var len0 = r1; + if (r3) { + ptr0 = 0; + len0 = 0; + throw takeObject(r2); + } + return getStringFromWasm0(ptr0, len0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + wasm.__wbindgen_free(ptr0, len0); + } + } + /** + * @returns {any} + */ + to_js_value() { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + wasm.transactionbodies_to_js_value(retptr, this.ptr); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + if (r2) { + throw takeObject(r1); + } + return takeObject(r0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @param {string} json + * @returns {TransactionBodies} + */ + static from_json(json) { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + const ptr0 = passStringToWasm0( + json, + wasm.__wbindgen_malloc, + wasm.__wbindgen_realloc, + ); + const len0 = WASM_VECTOR_LEN; + wasm.transactionbodies_from_json(retptr, ptr0, len0); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + if (r2) { + throw takeObject(r1); + } + return TransactionBodies.__wrap(r0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @returns {TransactionBodies} + */ + static new() { + const ret = wasm.certificates_new(); + return TransactionBodies.__wrap(ret); + } + /** + * @returns {number} + */ + len() { + const ret = wasm.assetnames_len(this.ptr); + return ret >>> 0; + } + /** + * @param {number} index + * @returns {TransactionBody} + */ + get(index) { + const ret = wasm.transactionbodies_get(this.ptr, index); + return TransactionBody.__wrap(ret); + } + /** + * @param {TransactionBody} elem + */ + add(elem) { + _assertClass(elem, TransactionBody); + wasm.transactionbodies_add(this.ptr, elem.ptr); + } +} +module.exports.TransactionBodies = TransactionBodies; + +const TransactionBodyFinalization = new FinalizationRegistry((ptr) => + wasm.__wbg_transactionbody_free(ptr) +); +/** */ +class TransactionBody { + static __wrap(ptr) { + const obj = Object.create(TransactionBody.prototype); + obj.ptr = ptr; + TransactionBodyFinalization.register(obj, obj.ptr, obj); + return obj; + } + + __destroy_into_raw() { + const ptr = this.ptr; + this.ptr = 0; + TransactionBodyFinalization.unregister(this); + return ptr; + } + + free() { + const ptr = this.__destroy_into_raw(); + wasm.__wbg_transactionbody_free(ptr); + } + /** + * @returns {Uint8Array} + */ + to_bytes() { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + wasm.transactionbody_to_bytes(retptr, this.ptr); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var v0 = getArrayU8FromWasm0(r0, r1).slice(); + wasm.__wbindgen_free(r0, r1 * 1); + return v0; + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @param {Uint8Array} bytes + * @returns {TransactionBody} + */ + static from_bytes(bytes) { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + const ptr0 = passArray8ToWasm0(bytes, wasm.__wbindgen_malloc); + const len0 = WASM_VECTOR_LEN; + wasm.transactionbody_from_bytes(retptr, ptr0, len0); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + if (r2) { + throw takeObject(r1); + } + return TransactionBody.__wrap(r0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @returns {string} + */ + to_json() { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + wasm.transactionbody_to_json(retptr, this.ptr); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + var r3 = getInt32Memory0()[retptr / 4 + 3]; + var ptr0 = r0; + var len0 = r1; + if (r3) { + ptr0 = 0; + len0 = 0; + throw takeObject(r2); + } + return getStringFromWasm0(ptr0, len0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + wasm.__wbindgen_free(ptr0, len0); + } + } + /** + * @returns {any} + */ + to_js_value() { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + wasm.transactionbody_to_js_value(retptr, this.ptr); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + if (r2) { + throw takeObject(r1); + } + return takeObject(r0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @param {string} json + * @returns {TransactionBody} + */ + static from_json(json) { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + const ptr0 = passStringToWasm0( + json, + wasm.__wbindgen_malloc, + wasm.__wbindgen_realloc, + ); + const len0 = WASM_VECTOR_LEN; + wasm.transactionbody_from_json(retptr, ptr0, len0); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + if (r2) { + throw takeObject(r1); + } + return TransactionBody.__wrap(r0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @returns {TransactionInputs} + */ + inputs() { + const ret = wasm.transactionbody_inputs(this.ptr); + return TransactionInputs.__wrap(ret); + } + /** + * @returns {TransactionOutputs} + */ + outputs() { + const ret = wasm.transactionbody_outputs(this.ptr); + return TransactionOutputs.__wrap(ret); + } + /** + * @returns {BigNum} + */ + fee() { + const ret = wasm.transactionbody_fee(this.ptr); + return BigNum.__wrap(ret); + } + /** + * @returns {BigNum | undefined} + */ + ttl() { + const ret = wasm.transactionbody_ttl(this.ptr); + return ret === 0 ? undefined : BigNum.__wrap(ret); + } + /** + * @param {Certificates} certs + */ + set_certs(certs) { + _assertClass(certs, Certificates); + wasm.transactionbody_set_certs(this.ptr, certs.ptr); + } + /** + * @returns {Certificates | undefined} + */ + certs() { + const ret = wasm.transactionbody_certs(this.ptr); + return ret === 0 ? undefined : Certificates.__wrap(ret); + } + /** + * @param {Withdrawals} withdrawals + */ + set_withdrawals(withdrawals) { + _assertClass(withdrawals, Withdrawals); + wasm.transactionbody_set_withdrawals(this.ptr, withdrawals.ptr); + } + /** + * @returns {Withdrawals | undefined} + */ + withdrawals() { + const ret = wasm.transactionbody_withdrawals(this.ptr); + return ret === 0 ? undefined : Withdrawals.__wrap(ret); + } + /** + * @param {Update} update + */ + set_update(update) { + _assertClass(update, Update); + wasm.transactionbody_set_update(this.ptr, update.ptr); + } + /** + * @returns {Update | undefined} + */ + update() { + const ret = wasm.transactionbody_update(this.ptr); + return ret === 0 ? undefined : Update.__wrap(ret); + } + /** + * @returns {VotingProcedures | undefined} + */ + voting_procedures() { + const ret = wasm.transactionbody_voting_procedures(this.ptr); + return ret === 0 ? undefined : VotingProcedures.__wrap(ret); + } + /** + * @returns {ProposalProcedures | undefined} + */ + proposal_procedures() { + const ret = wasm.transactionbody_proposal_procedures(this.ptr); + return ret === 0 ? undefined : ProposalProcedures.__wrap(ret); + } + /** + * @param {AuxiliaryDataHash} auxiliary_data_hash + */ + set_auxiliary_data_hash(auxiliary_data_hash) { + _assertClass(auxiliary_data_hash, AuxiliaryDataHash); + wasm.transactionbody_set_auxiliary_data_hash( + this.ptr, + auxiliary_data_hash.ptr, + ); + } + /** + * @returns {AuxiliaryDataHash | undefined} + */ + auxiliary_data_hash() { + const ret = wasm.transactionbody_auxiliary_data_hash(this.ptr); + return ret === 0 ? undefined : AuxiliaryDataHash.__wrap(ret); + } + /** + * @param {BigNum} validity_start_interval + */ + set_validity_start_interval(validity_start_interval) { + _assertClass(validity_start_interval, BigNum); + wasm.protocolparamupdate_set_minfee_b( + this.ptr, + validity_start_interval.ptr, + ); + } + /** + * @returns {BigNum | undefined} + */ + validity_start_interval() { + const ret = wasm.protocolparamupdate_minfee_b(this.ptr); + return ret === 0 ? undefined : BigNum.__wrap(ret); + } + /** + * @param {Mint} mint + */ + set_mint(mint) { + _assertClass(mint, Mint); + wasm.transactionbody_set_mint(this.ptr, mint.ptr); + } + /** + * @returns {Mint | undefined} + */ + mint() { + const ret = wasm.transactionbody_mint(this.ptr); + return ret === 0 ? undefined : Mint.__wrap(ret); + } + /** + * @param {ScriptDataHash} script_data_hash + */ + set_script_data_hash(script_data_hash) { + _assertClass(script_data_hash, ScriptDataHash); + wasm.transactionbody_set_script_data_hash(this.ptr, script_data_hash.ptr); + } + /** + * @returns {ScriptDataHash | undefined} + */ + script_data_hash() { + const ret = wasm.transactionbody_script_data_hash(this.ptr); + return ret === 0 ? undefined : ScriptDataHash.__wrap(ret); + } + /** + * @param {TransactionInputs} collateral + */ + set_collateral(collateral) { + _assertClass(collateral, TransactionInputs); + wasm.transactionbody_set_collateral(this.ptr, collateral.ptr); + } + /** + * @returns {TransactionInputs | undefined} + */ + collateral() { + const ret = wasm.transactionbody_collateral(this.ptr); + return ret === 0 ? undefined : TransactionInputs.__wrap(ret); + } + /** + * @param {Ed25519KeyHashes} required_signers + */ + set_required_signers(required_signers) { + _assertClass(required_signers, Ed25519KeyHashes); + wasm.transactionbody_set_required_signers(this.ptr, required_signers.ptr); + } + /** + * @returns {Ed25519KeyHashes | undefined} + */ + required_signers() { + const ret = wasm.transactionbody_required_signers(this.ptr); + return ret === 0 ? undefined : Ed25519KeyHashes.__wrap(ret); + } + /** + * @param {NetworkId} network_id + */ + set_network_id(network_id) { + _assertClass(network_id, NetworkId); + wasm.transactionbody_set_network_id(this.ptr, network_id.ptr); + } + /** + * @returns {NetworkId | undefined} + */ + network_id() { + const ret = wasm.transactionbody_network_id(this.ptr); + return ret === 0 ? undefined : NetworkId.__wrap(ret); + } + /** + * @param {TransactionOutput} collateral_return + */ + set_collateral_return(collateral_return) { + _assertClass(collateral_return, TransactionOutput); + wasm.transactionbody_set_collateral_return(this.ptr, collateral_return.ptr); + } + /** + * @returns {TransactionOutput | undefined} + */ + collateral_return() { + const ret = wasm.transactionbody_collateral_return(this.ptr); + return ret === 0 ? undefined : TransactionOutput.__wrap(ret); + } + /** + * @param {BigNum} total_collateral + */ + set_total_collateral(total_collateral) { + _assertClass(total_collateral, BigNum); + wasm.protocolparamupdate_set_key_deposit(this.ptr, total_collateral.ptr); + } + /** + * @returns {BigNum | undefined} + */ + total_collateral() { + const ret = wasm.protocolparamupdate_key_deposit(this.ptr); + return ret === 0 ? undefined : BigNum.__wrap(ret); + } + /** + * @param {TransactionInputs} reference_inputs + */ + set_reference_inputs(reference_inputs) { + _assertClass(reference_inputs, TransactionInputs); + wasm.transactionbody_set_reference_inputs(this.ptr, reference_inputs.ptr); + } + /** + * @returns {TransactionInputs | undefined} + */ + reference_inputs() { + const ret = wasm.transactionbody_reference_inputs(this.ptr); + return ret === 0 ? undefined : TransactionInputs.__wrap(ret); + } + /** + * @param {VotingProcedures} voting_procedures + */ + set_voting_procedures(voting_procedures) { + _assertClass(voting_procedures, VotingProcedures); + wasm.transactionbody_set_voting_procedures(this.ptr, voting_procedures.ptr); + } + /** + * @param {ProposalProcedures} proposal_procedures + */ + set_proposal_procedures(proposal_procedures) { + _assertClass(proposal_procedures, ProposalProcedures); + wasm.transactionbody_set_proposal_procedures( + this.ptr, + proposal_procedures.ptr, + ); + } + /** + * @param {TransactionInputs} inputs + * @param {TransactionOutputs} outputs + * @param {BigNum} fee + * @param {BigNum | undefined} ttl + * @returns {TransactionBody} + */ + static new(inputs, outputs, fee, ttl) { + _assertClass(inputs, TransactionInputs); + _assertClass(outputs, TransactionOutputs); + _assertClass(fee, BigNum); + let ptr0 = 0; + if (!isLikeNone(ttl)) { + _assertClass(ttl, BigNum); + ptr0 = ttl.__destroy_into_raw(); + } + const ret = wasm.transactionbody_new( + inputs.ptr, + outputs.ptr, + fee.ptr, + ptr0, + ); + return TransactionBody.__wrap(ret); + } + /** + * @returns {Uint8Array | undefined} + */ + raw() { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + wasm.transactionbody_raw(retptr, this.ptr); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + let v0; + if (r0 !== 0) { + v0 = getArrayU8FromWasm0(r0, r1).slice(); + wasm.__wbindgen_free(r0, r1 * 1); + } + return v0; + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } +} +module.exports.TransactionBody = TransactionBody; + +const TransactionBuilderFinalization = new FinalizationRegistry((ptr) => + wasm.__wbg_transactionbuilder_free(ptr) +); +/** */ +class TransactionBuilder { + static __wrap(ptr) { + const obj = Object.create(TransactionBuilder.prototype); + obj.ptr = ptr; + TransactionBuilderFinalization.register(obj, obj.ptr, obj); + return obj; + } + + __destroy_into_raw() { + const ptr = this.ptr; + this.ptr = 0; + TransactionBuilderFinalization.unregister(this); + return ptr; + } + + free() { + const ptr = this.__destroy_into_raw(); + wasm.__wbg_transactionbuilder_free(ptr); + } + /** + * This automatically selects and adds inputs from {inputs} consisting of just enough to cover + * the outputs that have already been added. + * This should be called after adding all certs/outputs/etc and will be an error otherwise. + * Adding a change output must be called after via TransactionBuilder::balance() + * inputs to cover the minimum fees. This does not, however, set the txbuilder's fee. + * + * change_address is required here in order to determine the min ada requirement precisely + * weights is a coma separated representation of a Uint32Arary + * @param {TransactionUnspentOutputs} inputs + * @param {Address} change_address + * @param {string} weights_str + */ + add_inputs_from_impl(inputs, change_address, weights_str) { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + _assertClass(inputs, TransactionUnspentOutputs); + _assertClass(change_address, Address); + const ptr0 = passStringToWasm0( + weights_str, + wasm.__wbindgen_malloc, + wasm.__wbindgen_realloc, + ); + const len0 = WASM_VECTOR_LEN; + wasm.transactionbuilder_add_inputs_from_impl( + retptr, + this.ptr, + inputs.ptr, + change_address.ptr, + ptr0, + len0, + ); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + if (r1) { + throw takeObject(r0); + } + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * This automatically selects and adds inputs from {inputs} consisting of just enough to cover + * the outputs that have already been added. + * This should be called after adding all certs/outputs/etc and will be an error otherwise. + * Adding a change output must be called after via TransactionBuilder::balance() + * inputs to cover the minimum fees. This does not, however, set the txbuilder's fee. + * + * change_address is required here in order to determine the min ada requirement precisely + * @param {TransactionUnspentOutputs} inputs + * @param {Address} change_address + * @param {Uint32Array} weights + */ + add_inputs_from(inputs, change_address, weights) { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + _assertClass(inputs, TransactionUnspentOutputs); + _assertClass(change_address, Address); + const ptr0 = passArray32ToWasm0(weights, wasm.__wbindgen_malloc); + const len0 = WASM_VECTOR_LEN; + wasm.transactionbuilder_add_inputs_from( + retptr, + this.ptr, + inputs.ptr, + change_address.ptr, + ptr0, + len0, + ); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + if (r1) { + throw takeObject(r0); + } + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @param {TransactionUnspentOutput} utxo + * @param {ScriptWitness | undefined} script_witness + */ + add_input(utxo, script_witness) { + _assertClass(utxo, TransactionUnspentOutput); + let ptr0 = 0; + if (!isLikeNone(script_witness)) { + _assertClass(script_witness, ScriptWitness); + ptr0 = script_witness.__destroy_into_raw(); + } + wasm.transactionbuilder_add_input(this.ptr, utxo.ptr, ptr0); + } + /** + * @param {TransactionUnspentOutput} utxo + */ + add_reference_input(utxo) { + _assertClass(utxo, TransactionUnspentOutput); + wasm.transactionbuilder_add_reference_input(this.ptr, utxo.ptr); + } + /** + * calculates how much the fee would increase if you added a given output + * @param {Address} address + * @param {TransactionInput} input + * @param {Value} amount + * @returns {BigNum} + */ + fee_for_input(address, input, amount) { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + _assertClass(address, Address); + _assertClass(input, TransactionInput); + _assertClass(amount, Value); + wasm.transactionbuilder_fee_for_input( + retptr, + this.ptr, + address.ptr, + input.ptr, + amount.ptr, + ); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + if (r2) { + throw takeObject(r1); + } + return BigNum.__wrap(r0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * Add explicit output via a TransactionOutput object + * @param {TransactionOutput} output + */ + add_output(output) { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + _assertClass(output, TransactionOutput); + wasm.transactionbuilder_add_output(retptr, this.ptr, output.ptr); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + if (r1) { + throw takeObject(r0); + } + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * Add plutus scripts via a PlutusScripts object + * @param {PlutusScript} plutus_script + */ + add_plutus_script(plutus_script) { + _assertClass(plutus_script, PlutusScript); + wasm.transactionbuilder_add_plutus_script(this.ptr, plutus_script.ptr); + } + /** + * Add plutus v2 scripts via a PlutusScripts object + * @param {PlutusScript} plutus_script + */ + add_plutus_v2_script(plutus_script) { + _assertClass(plutus_script, PlutusScript); + wasm.transactionbuilder_add_plutus_v2_script(this.ptr, plutus_script.ptr); + } + /** + * Add plutus data via a PlutusData object + * @param {PlutusData} plutus_data + */ + add_plutus_data(plutus_data) { + _assertClass(plutus_data, PlutusData); + wasm.transactionbuilder_add_plutus_data(this.ptr, plutus_data.ptr); + } + /** + * Add native scripts via a NativeScripts object + * @param {NativeScript} native_script + */ + add_native_script(native_script) { + _assertClass(native_script, NativeScript); + wasm.transactionbuilder_add_native_script(this.ptr, native_script.ptr); + } + /** + * Add certificate via a Certificates object + * @param {Certificate} certificate + * @param {ScriptWitness | undefined} script_witness + */ + add_certificate(certificate, script_witness) { + _assertClass(certificate, Certificate); + let ptr0 = 0; + if (!isLikeNone(script_witness)) { + _assertClass(script_witness, ScriptWitness); + ptr0 = script_witness.__destroy_into_raw(); + } + wasm.transactionbuilder_add_certificate(this.ptr, certificate.ptr, ptr0); + } + /** + * calculates how much the fee would increase if you added a given output + * @param {TransactionOutput} output + * @returns {BigNum} + */ + fee_for_output(output) { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + _assertClass(output, TransactionOutput); + wasm.transactionbuilder_fee_for_output(retptr, this.ptr, output.ptr); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + if (r2) { + throw takeObject(r1); + } + return BigNum.__wrap(r0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @param {BigNum} ttl + */ + set_ttl(ttl) { + _assertClass(ttl, BigNum); + wasm.protocolparamupdate_set_minfee_b(this.ptr, ttl.ptr); + } + /** + * @param {BigNum} validity_start_interval + */ + set_validity_start_interval(validity_start_interval) { + _assertClass(validity_start_interval, BigNum); + wasm.transactionbuilder_set_validity_start_interval( + this.ptr, + validity_start_interval.ptr, + ); + } + /** + * @param {RewardAddress} reward_address + * @param {BigNum} coin + * @param {ScriptWitness | undefined} script_witness + */ + add_withdrawal(reward_address, coin, script_witness) { + _assertClass(reward_address, RewardAddress); + _assertClass(coin, BigNum); + let ptr0 = 0; + if (!isLikeNone(script_witness)) { + _assertClass(script_witness, ScriptWitness); + ptr0 = script_witness.__destroy_into_raw(); + } + wasm.transactionbuilder_add_withdrawal( + this.ptr, + reward_address.ptr, + coin.ptr, + ptr0, + ); + } + /** + * @returns {AuxiliaryData | undefined} + */ + auxiliary_data() { + const ret = wasm.transactionbuilder_auxiliary_data(this.ptr); + return ret === 0 ? undefined : AuxiliaryData.__wrap(ret); + } + /** + * Set explicit auxiliary data via an AuxiliaryData object + * It might contain some metadata plus native or Plutus scripts + * @param {AuxiliaryData} auxiliary_data + */ + set_auxiliary_data(auxiliary_data) { + _assertClass(auxiliary_data, AuxiliaryData); + wasm.transactionbuilder_set_auxiliary_data(this.ptr, auxiliary_data.ptr); + } + /** + * Set metadata using a GeneralTransactionMetadata object + * It will be set to the existing or new auxiliary data in this builder + * @param {GeneralTransactionMetadata} metadata + */ + set_metadata(metadata) { + _assertClass(metadata, GeneralTransactionMetadata); + wasm.transactionbuilder_set_metadata(this.ptr, metadata.ptr); + } + /** + * Add a single metadatum using TransactionMetadatumLabel and TransactionMetadatum objects + * It will be securely added to existing or new metadata in this builder + * @param {BigNum} key + * @param {TransactionMetadatum} val + */ + add_metadatum(key, val) { + _assertClass(key, BigNum); + _assertClass(val, TransactionMetadatum); + wasm.transactionbuilder_add_metadatum(this.ptr, key.ptr, val.ptr); + } + /** + * Add a single JSON metadatum using a TransactionMetadatumLabel and a String + * It will be securely added to existing or new metadata in this builder + * @param {BigNum} key + * @param {string} val + */ + add_json_metadatum(key, val) { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + _assertClass(key, BigNum); + const ptr0 = passStringToWasm0( + val, + wasm.__wbindgen_malloc, + wasm.__wbindgen_realloc, + ); + const len0 = WASM_VECTOR_LEN; + wasm.transactionbuilder_add_json_metadatum( + retptr, + this.ptr, + key.ptr, + ptr0, + len0, + ); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + if (r1) { + throw takeObject(r0); + } + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * Add a single JSON metadatum using a TransactionMetadatumLabel, a String, and a MetadataJsonSchema object + * It will be securely added to existing or new metadata in this builder + * @param {BigNum} key + * @param {string} val + * @param {number} schema + */ + add_json_metadatum_with_schema(key, val, schema) { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + _assertClass(key, BigNum); + const ptr0 = passStringToWasm0( + val, + wasm.__wbindgen_malloc, + wasm.__wbindgen_realloc, + ); + const len0 = WASM_VECTOR_LEN; + wasm.transactionbuilder_add_json_metadatum_with_schema( + retptr, + this.ptr, + key.ptr, + ptr0, + len0, + schema, + ); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + if (r1) { + throw takeObject(r0); + } + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * Returns a copy of the current mint state in the builder + * @returns {Mint | undefined} + */ + mint() { + const ret = wasm.transactionbuilder_mint(this.ptr); + return ret === 0 ? undefined : Mint.__wrap(ret); + } + /** + * @returns {Certificates | undefined} + */ + certificates() { + const ret = wasm.transactionbuilder_certificates(this.ptr); + return ret === 0 ? undefined : Certificates.__wrap(ret); + } + /** + * @returns {Withdrawals | undefined} + */ + withdrawals() { + const ret = wasm.transactionbuilder_withdrawals(this.ptr); + return ret === 0 ? undefined : Withdrawals.__wrap(ret); + } + /** + * Returns a copy of the current witness native scripts in the builder + * @returns {NativeScripts | undefined} + */ + native_scripts() { + const ret = wasm.transactionbuilder_native_scripts(this.ptr); + return ret === 0 ? undefined : NativeScripts.__wrap(ret); + } + /** + * Add a mint entry to this builder using a PolicyID and MintAssets object + * It will be securely added to existing or new Mint in this builder + * It will securely add assets to an existing PolicyID + * But it will replace/overwrite any existing mint assets with the same PolicyID + * first redeemer applied to a PolicyID is taken for all further assets added to the same PolicyID + * @param {ScriptHash} policy_id + * @param {MintAssets} mint_assets + * @param {ScriptWitness | undefined} script_witness + */ + add_mint(policy_id, mint_assets, script_witness) { + _assertClass(policy_id, ScriptHash); + _assertClass(mint_assets, MintAssets); + let ptr0 = 0; + if (!isLikeNone(script_witness)) { + _assertClass(script_witness, ScriptWitness); + ptr0 = script_witness.__destroy_into_raw(); + } + wasm.transactionbuilder_add_mint( + this.ptr, + policy_id.ptr, + mint_assets.ptr, + ptr0, + ); + } + /** + * @param {TransactionBuilderConfig} cfg + * @returns {TransactionBuilder} + */ + static new(cfg) { + _assertClass(cfg, TransactionBuilderConfig); + const ret = wasm.transactionbuilder_new(cfg.ptr); + return TransactionBuilder.__wrap(ret); + } + /** + * @returns {ScriptDataHash | undefined} + */ + script_data_hash() { + const ret = wasm.transactionbuilder_script_data_hash(this.ptr); + return ret === 0 ? undefined : ScriptDataHash.__wrap(ret); + } + /** + * @param {TransactionUnspentOutput} utxo + */ + add_collateral(utxo) { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + _assertClass(utxo, TransactionUnspentOutput); + wasm.transactionbuilder_add_collateral(retptr, this.ptr, utxo.ptr); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + if (r1) { + throw takeObject(r0); + } + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @returns {TransactionInputs | undefined} + */ + get_collateral() { + const ret = wasm.transactionbuilder_get_collateral(this.ptr); + return ret === 0 ? undefined : TransactionInputs.__wrap(ret); + } + /** + * @param {Ed25519KeyHash} required_signer + */ + add_required_signer(required_signer) { + _assertClass(required_signer, Ed25519KeyHash); + wasm.transactionbuilder_add_required_signer(this.ptr, required_signer.ptr); + } + /** + * @returns {Ed25519KeyHashes | undefined} + */ + required_signers() { + const ret = wasm.transactionbuilder_required_signers(this.ptr); + return ret === 0 ? undefined : Ed25519KeyHashes.__wrap(ret); + } + /** + * @param {NetworkId} network_id + */ + set_network_id(network_id) { + _assertClass(network_id, NetworkId); + var ptr0 = network_id.__destroy_into_raw(); + wasm.transactionbuilder_set_network_id(this.ptr, ptr0); + } + /** + * @returns {NetworkId | undefined} + */ + network_id() { + const ret = wasm.transactionbuilder_network_id(this.ptr); + return ret === 0 ? undefined : NetworkId.__wrap(ret); + } + /** + * @returns {Redeemers | undefined} + */ + redeemers() { + const ret = wasm.transactionbuilder_redeemers(this.ptr); + return ret === 0 ? undefined : Redeemers.__wrap(ret); + } + /** + * does not include refunds or withdrawals + * @returns {Value} + */ + get_explicit_input() { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + wasm.transactionbuilder_get_explicit_input(retptr, this.ptr); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + if (r2) { + throw takeObject(r1); + } + return Value.__wrap(r0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * withdrawals and refunds + * @returns {Value} + */ + get_implicit_input() { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + wasm.transactionbuilder_get_implicit_input(retptr, this.ptr); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + if (r2) { + throw takeObject(r1); + } + return Value.__wrap(r0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * Return explicit input plus implicit input plus mint + * @returns {Value} + */ + get_total_input() { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + wasm.transactionbuilder_get_total_input(retptr, this.ptr); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + if (r2) { + throw takeObject(r1); + } + return Value.__wrap(r0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * Return explicit output plus implicit output plus burn (does not consider fee directly) + * @returns {Value} + */ + get_total_output() { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + wasm.transactionbuilder_get_total_output(retptr, this.ptr); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + if (r2) { + throw takeObject(r1); + } + return Value.__wrap(r0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * does not include fee + * @returns {Value} + */ + get_explicit_output() { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + wasm.transactionbuilder_get_explicit_output(retptr, this.ptr); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + if (r2) { + throw takeObject(r1); + } + return Value.__wrap(r0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @returns {BigNum} + */ + get_deposit() { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + wasm.transactionbuilder_get_deposit(retptr, this.ptr); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + if (r2) { + throw takeObject(r1); + } + return BigNum.__wrap(r0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @returns {BigNum | undefined} + */ + get_fee_if_set() { + const ret = wasm.protocolparamupdate_minfee_a(this.ptr); + return ret === 0 ? undefined : BigNum.__wrap(ret); + } + /** + * Warning: this function will mutate the /fee/ field + * Make sure to call this function last after setting all other tx-body properties + * Editing inputs, outputs, mint, etc. after change been calculated + * might cause a mismatch in calculated fee versus the required fee + * @param {Address} change_address + * @param {Datum | undefined} datum + */ + balance(change_address, datum) { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + _assertClass(change_address, Address); + let ptr0 = 0; + if (!isLikeNone(datum)) { + _assertClass(datum, Datum); + ptr0 = datum.__destroy_into_raw(); + } + wasm.transactionbuilder_balance( + retptr, + this.ptr, + change_address.ptr, + ptr0, + ); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + if (r1) { + throw takeObject(r0); + } + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * Returns the TransactionBody. + * @returns {Uint8Array} + */ + to_bytes() { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + wasm.transactionbuilder_to_bytes(retptr, this.ptr); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + var r3 = getInt32Memory0()[retptr / 4 + 3]; + if (r3) { + throw takeObject(r2); + } + var v0 = getArrayU8FromWasm0(r0, r1).slice(); + wasm.__wbindgen_free(r0, r1 * 1); + return v0; + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @returns {number} + */ + full_size() { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + wasm.transactionbuilder_full_size(retptr, this.ptr); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + if (r2) { + throw takeObject(r1); + } + return r0 >>> 0; + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @returns {Uint32Array} + */ + output_sizes() { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + wasm.transactionbuilder_output_sizes(retptr, this.ptr); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var v0 = getArrayU32FromWasm0(r0, r1).slice(); + wasm.__wbindgen_free(r0, r1 * 4); + return v0; + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @returns {TransactionOutputs} + */ + outputs() { + const ret = wasm.transactionbuilder_outputs(this.ptr); + return TransactionOutputs.__wrap(ret); + } + /** + * Returns full Transaction object with the body and the auxiliary data + * + * NOTE: witness_set will contain all mint_scripts if any been added or set + * + * takes fetched ex units into consideration + * + * add collateral utxos and collateral change receiver in case you redeem from plutus script utxos + * + * async call + * + * NOTE: is_valid set to true + * @param {TransactionUnspentOutputs | undefined} collateral_utxos + * @param {Address | undefined} collateral_change_address + * @param {boolean | undefined} native_uplc + * @returns {Promise} + */ + construct(collateral_utxos, collateral_change_address, native_uplc) { + const ptr = this.__destroy_into_raw(); + let ptr0 = 0; + if (!isLikeNone(collateral_utxos)) { + _assertClass(collateral_utxos, TransactionUnspentOutputs); + ptr0 = collateral_utxos.__destroy_into_raw(); + } + let ptr1 = 0; + if (!isLikeNone(collateral_change_address)) { + _assertClass(collateral_change_address, Address); + ptr1 = collateral_change_address.__destroy_into_raw(); + } + const ret = wasm.transactionbuilder_construct( + ptr, + ptr0, + ptr1, + isLikeNone(native_uplc) ? 0xFFFFFF : native_uplc ? 1 : 0, + ); + return takeObject(ret); + } + /** + * Returns full Transaction object with the body and the auxiliary data + * NOTE: witness_set will contain all mint_scripts if any been added or set + * NOTE: is_valid set to true + * @returns {Transaction} + */ + build_tx() { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + wasm.transactionbuilder_build_tx(retptr, this.ptr); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + if (r2) { + throw takeObject(r1); + } + return Transaction.__wrap(r0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * warning: sum of all parts of a transaction must equal 0. You cannot just set the fee to the min value and forget about it + * warning: min_fee may be slightly larger than the actual minimum fee (ex: a few lovelaces) + * this is done to simplify the library code, but can be fixed later + * @returns {BigNum} + */ + min_fee() { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + wasm.transactionbuilder_min_fee(retptr, this.ptr); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + if (r2) { + throw takeObject(r1); + } + return BigNum.__wrap(r0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } +} +module.exports.TransactionBuilder = TransactionBuilder; + +const TransactionBuilderConfigFinalization = new FinalizationRegistry((ptr) => + wasm.__wbg_transactionbuilderconfig_free(ptr) +); +/** */ +class TransactionBuilderConfig { + static __wrap(ptr) { + const obj = Object.create(TransactionBuilderConfig.prototype); + obj.ptr = ptr; + TransactionBuilderConfigFinalization.register(obj, obj.ptr, obj); + return obj; + } + + __destroy_into_raw() { + const ptr = this.ptr; + this.ptr = 0; + TransactionBuilderConfigFinalization.unregister(this); + return ptr; + } + + free() { + const ptr = this.__destroy_into_raw(); + wasm.__wbg_transactionbuilderconfig_free(ptr); + } +} +module.exports.TransactionBuilderConfig = TransactionBuilderConfig; + +const TransactionBuilderConfigBuilderFinalization = new FinalizationRegistry( + (ptr) => wasm.__wbg_transactionbuilderconfigbuilder_free(ptr) +); +/** */ +class TransactionBuilderConfigBuilder { + static __wrap(ptr) { + const obj = Object.create(TransactionBuilderConfigBuilder.prototype); + obj.ptr = ptr; + TransactionBuilderConfigBuilderFinalization.register(obj, obj.ptr, obj); + return obj; + } + + __destroy_into_raw() { + const ptr = this.ptr; + this.ptr = 0; + TransactionBuilderConfigBuilderFinalization.unregister(this); + return ptr; + } + + free() { + const ptr = this.__destroy_into_raw(); + wasm.__wbg_transactionbuilderconfigbuilder_free(ptr); + } + /** + * @returns {TransactionBuilderConfigBuilder} + */ + static new() { + const ret = wasm.transactionbuilderconfigbuilder_new(); + return TransactionBuilderConfigBuilder.__wrap(ret); + } + /** + * @param {LinearFee} fee_algo + * @returns {TransactionBuilderConfigBuilder} + */ + fee_algo(fee_algo) { + _assertClass(fee_algo, LinearFee); + const ret = wasm.transactionbuilderconfigbuilder_fee_algo( + this.ptr, + fee_algo.ptr, + ); + return TransactionBuilderConfigBuilder.__wrap(ret); + } + /** + * @param {BigNum} coins_per_utxo_byte + * @returns {TransactionBuilderConfigBuilder} + */ + coins_per_utxo_byte(coins_per_utxo_byte) { + _assertClass(coins_per_utxo_byte, BigNum); + const ret = wasm.transactionbuilderconfigbuilder_coins_per_utxo_byte( + this.ptr, + coins_per_utxo_byte.ptr, + ); + return TransactionBuilderConfigBuilder.__wrap(ret); + } + /** + * @param {BigNum} pool_deposit + * @returns {TransactionBuilderConfigBuilder} + */ + pool_deposit(pool_deposit) { + _assertClass(pool_deposit, BigNum); + const ret = wasm.transactionbuilderconfigbuilder_pool_deposit( + this.ptr, + pool_deposit.ptr, + ); + return TransactionBuilderConfigBuilder.__wrap(ret); + } + /** + * @param {BigNum} key_deposit + * @returns {TransactionBuilderConfigBuilder} + */ + key_deposit(key_deposit) { + _assertClass(key_deposit, BigNum); + const ret = wasm.transactionbuilderconfigbuilder_key_deposit( + this.ptr, + key_deposit.ptr, + ); + return TransactionBuilderConfigBuilder.__wrap(ret); + } + /** + * @param {number} max_value_size + * @returns {TransactionBuilderConfigBuilder} + */ + max_value_size(max_value_size) { + const ret = wasm.transactionbuilderconfigbuilder_max_value_size( + this.ptr, + max_value_size, + ); + return TransactionBuilderConfigBuilder.__wrap(ret); + } + /** + * @param {number} max_tx_size + * @returns {TransactionBuilderConfigBuilder} + */ + max_tx_size(max_tx_size) { + const ret = wasm.transactionbuilderconfigbuilder_max_tx_size( + this.ptr, + max_tx_size, + ); + return TransactionBuilderConfigBuilder.__wrap(ret); + } + /** + * @param {ExUnitPrices} ex_unit_prices + * @returns {TransactionBuilderConfigBuilder} + */ + ex_unit_prices(ex_unit_prices) { + _assertClass(ex_unit_prices, ExUnitPrices); + const ret = wasm.transactionbuilderconfigbuilder_ex_unit_prices( + this.ptr, + ex_unit_prices.ptr, + ); + return TransactionBuilderConfigBuilder.__wrap(ret); + } + /** + * @param {ExUnits} max_tx_ex_units + * @returns {TransactionBuilderConfigBuilder} + */ + max_tx_ex_units(max_tx_ex_units) { + _assertClass(max_tx_ex_units, ExUnits); + const ret = wasm.transactionbuilderconfigbuilder_max_tx_ex_units( + this.ptr, + max_tx_ex_units.ptr, + ); + return TransactionBuilderConfigBuilder.__wrap(ret); + } + /** + * @param {Costmdls} costmdls + * @returns {TransactionBuilderConfigBuilder} + */ + costmdls(costmdls) { + _assertClass(costmdls, Costmdls); + const ret = wasm.transactionbuilderconfigbuilder_costmdls( + this.ptr, + costmdls.ptr, + ); + return TransactionBuilderConfigBuilder.__wrap(ret); + } + /** + * @param {number} collateral_percentage + * @returns {TransactionBuilderConfigBuilder} + */ + collateral_percentage(collateral_percentage) { + const ret = wasm.transactionbuilderconfigbuilder_collateral_percentage( + this.ptr, + collateral_percentage, + ); + return TransactionBuilderConfigBuilder.__wrap(ret); + } + /** + * @param {number} max_collateral_inputs + * @returns {TransactionBuilderConfigBuilder} + */ + max_collateral_inputs(max_collateral_inputs) { + const ret = wasm.transactionbuilderconfigbuilder_max_collateral_inputs( + this.ptr, + max_collateral_inputs, + ); + return TransactionBuilderConfigBuilder.__wrap(ret); + } + /** + * @param {BigNum} zero_time + * @param {BigNum} zero_slot + * @param {number} slot_length + * @returns {TransactionBuilderConfigBuilder} + */ + slot_config(zero_time, zero_slot, slot_length) { + _assertClass(zero_time, BigNum); + _assertClass(zero_slot, BigNum); + const ret = wasm.transactionbuilderconfigbuilder_slot_config( + this.ptr, + zero_time.ptr, + zero_slot.ptr, + slot_length, + ); + return TransactionBuilderConfigBuilder.__wrap(ret); + } + /** + * @param {Blockfrost} blockfrost + * @returns {TransactionBuilderConfigBuilder} + */ + blockfrost(blockfrost) { + _assertClass(blockfrost, Blockfrost); + const ret = wasm.transactionbuilderconfigbuilder_blockfrost( + this.ptr, + blockfrost.ptr, + ); + return TransactionBuilderConfigBuilder.__wrap(ret); + } + /** + * @returns {TransactionBuilderConfig} + */ + build() { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + wasm.transactionbuilderconfigbuilder_build(retptr, this.ptr); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + if (r2) { + throw takeObject(r1); + } + return TransactionBuilderConfig.__wrap(r0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } +} +module.exports.TransactionBuilderConfigBuilder = + TransactionBuilderConfigBuilder; + +const TransactionHashFinalization = new FinalizationRegistry((ptr) => + wasm.__wbg_transactionhash_free(ptr) +); +/** */ +class TransactionHash { + static __wrap(ptr) { + const obj = Object.create(TransactionHash.prototype); + obj.ptr = ptr; + TransactionHashFinalization.register(obj, obj.ptr, obj); + return obj; + } + + __destroy_into_raw() { + const ptr = this.ptr; + this.ptr = 0; + TransactionHashFinalization.unregister(this); + return ptr; + } + + free() { + const ptr = this.__destroy_into_raw(); + wasm.__wbg_transactionhash_free(ptr); + } + /** + * @param {Uint8Array} bytes + * @returns {TransactionHash} + */ + static from_bytes(bytes) { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + const ptr0 = passArray8ToWasm0(bytes, wasm.__wbindgen_malloc); + const len0 = WASM_VECTOR_LEN; + wasm.transactionhash_from_bytes(retptr, ptr0, len0); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + if (r2) { + throw takeObject(r1); + } + return TransactionHash.__wrap(r0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @returns {Uint8Array} + */ + to_bytes() { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + wasm.auxiliarydatahash_to_bytes(retptr, this.ptr); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var v0 = getArrayU8FromWasm0(r0, r1).slice(); + wasm.__wbindgen_free(r0, r1 * 1); + return v0; + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @param {string} prefix + * @returns {string} + */ + to_bech32(prefix) { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + const ptr0 = passStringToWasm0( + prefix, + wasm.__wbindgen_malloc, + wasm.__wbindgen_realloc, + ); + const len0 = WASM_VECTOR_LEN; + wasm.auxiliarydatahash_to_bech32(retptr, this.ptr, ptr0, len0); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + var r3 = getInt32Memory0()[retptr / 4 + 3]; + var ptr1 = r0; + var len1 = r1; + if (r3) { + ptr1 = 0; + len1 = 0; + throw takeObject(r2); + } + return getStringFromWasm0(ptr1, len1); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + wasm.__wbindgen_free(ptr1, len1); + } + } + /** + * @param {string} bech_str + * @returns {TransactionHash} + */ + static from_bech32(bech_str) { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + const ptr0 = passStringToWasm0( + bech_str, + wasm.__wbindgen_malloc, + wasm.__wbindgen_realloc, + ); + const len0 = WASM_VECTOR_LEN; + wasm.transactionhash_from_bech32(retptr, ptr0, len0); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + if (r2) { + throw takeObject(r1); + } + return TransactionHash.__wrap(r0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @returns {string} + */ + to_hex() { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + wasm.auxiliarydatahash_to_hex(retptr, this.ptr); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + return getStringFromWasm0(r0, r1); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + wasm.__wbindgen_free(r0, r1); + } + } + /** + * @param {string} hex + * @returns {TransactionHash} + */ + static from_hex(hex) { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + const ptr0 = passStringToWasm0( + hex, + wasm.__wbindgen_malloc, + wasm.__wbindgen_realloc, + ); + const len0 = WASM_VECTOR_LEN; + wasm.transactionhash_from_hex(retptr, ptr0, len0); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + if (r2) { + throw takeObject(r1); + } + return TransactionHash.__wrap(r0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } +} +module.exports.TransactionHash = TransactionHash; + +const TransactionIndexesFinalization = new FinalizationRegistry((ptr) => + wasm.__wbg_transactionindexes_free(ptr) +); +/** */ +class TransactionIndexes { + static __wrap(ptr) { + const obj = Object.create(TransactionIndexes.prototype); + obj.ptr = ptr; + TransactionIndexesFinalization.register(obj, obj.ptr, obj); + return obj; + } + + __destroy_into_raw() { + const ptr = this.ptr; + this.ptr = 0; + TransactionIndexesFinalization.unregister(this); + return ptr; + } + + free() { + const ptr = this.__destroy_into_raw(); + wasm.__wbg_transactionindexes_free(ptr); + } + /** + * @returns {Uint8Array} + */ + to_bytes() { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + wasm.transactionindexes_to_bytes(retptr, this.ptr); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var v0 = getArrayU8FromWasm0(r0, r1).slice(); + wasm.__wbindgen_free(r0, r1 * 1); + return v0; + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @param {Uint8Array} bytes + * @returns {TransactionIndexes} + */ + static from_bytes(bytes) { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + const ptr0 = passArray8ToWasm0(bytes, wasm.__wbindgen_malloc); + const len0 = WASM_VECTOR_LEN; + wasm.transactionindexes_from_bytes(retptr, ptr0, len0); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + if (r2) { + throw takeObject(r1); + } + return TransactionIndexes.__wrap(r0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @returns {TransactionIndexes} + */ + static new() { + const ret = wasm.certificates_new(); + return TransactionIndexes.__wrap(ret); + } + /** + * @returns {number} + */ + len() { + const ret = wasm.assetnames_len(this.ptr); + return ret >>> 0; + } + /** + * @param {number} index + * @returns {BigNum} + */ + get(index) { + const ret = wasm.transactionindexes_get(this.ptr, index); + return BigNum.__wrap(ret); + } + /** + * @param {BigNum} elem + */ + add(elem) { + _assertClass(elem, BigNum); + wasm.transactionindexes_add(this.ptr, elem.ptr); + } +} +module.exports.TransactionIndexes = TransactionIndexes; + +const TransactionInputFinalization = new FinalizationRegistry((ptr) => + wasm.__wbg_transactioninput_free(ptr) +); +/** */ +class TransactionInput { + static __wrap(ptr) { + const obj = Object.create(TransactionInput.prototype); + obj.ptr = ptr; + TransactionInputFinalization.register(obj, obj.ptr, obj); + return obj; + } + + __destroy_into_raw() { + const ptr = this.ptr; + this.ptr = 0; + TransactionInputFinalization.unregister(this); + return ptr; + } + + free() { + const ptr = this.__destroy_into_raw(); + wasm.__wbg_transactioninput_free(ptr); + } + /** + * @returns {Uint8Array} + */ + to_bytes() { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + wasm.transactioninput_to_bytes(retptr, this.ptr); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var v0 = getArrayU8FromWasm0(r0, r1).slice(); + wasm.__wbindgen_free(r0, r1 * 1); + return v0; + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @param {Uint8Array} bytes + * @returns {TransactionInput} + */ + static from_bytes(bytes) { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + const ptr0 = passArray8ToWasm0(bytes, wasm.__wbindgen_malloc); + const len0 = WASM_VECTOR_LEN; + wasm.transactioninput_from_bytes(retptr, ptr0, len0); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + if (r2) { + throw takeObject(r1); + } + return TransactionInput.__wrap(r0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @returns {string} + */ + to_json() { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + wasm.transactioninput_to_json(retptr, this.ptr); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + var r3 = getInt32Memory0()[retptr / 4 + 3]; + var ptr0 = r0; + var len0 = r1; + if (r3) { + ptr0 = 0; + len0 = 0; + throw takeObject(r2); + } + return getStringFromWasm0(ptr0, len0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + wasm.__wbindgen_free(ptr0, len0); + } + } + /** + * @returns {any} + */ + to_js_value() { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + wasm.transactioninput_to_js_value(retptr, this.ptr); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + if (r2) { + throw takeObject(r1); + } + return takeObject(r0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @param {string} json + * @returns {TransactionInput} + */ + static from_json(json) { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + const ptr0 = passStringToWasm0( + json, + wasm.__wbindgen_malloc, + wasm.__wbindgen_realloc, + ); + const len0 = WASM_VECTOR_LEN; + wasm.transactioninput_from_json(retptr, ptr0, len0); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + if (r2) { + throw takeObject(r1); + } + return TransactionInput.__wrap(r0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @returns {TransactionHash} + */ + transaction_id() { + const ret = wasm.governanceactionid_transaction_id(this.ptr); + return TransactionHash.__wrap(ret); + } + /** + * @returns {BigNum} + */ + index() { + const ret = wasm.governanceactionid_governance_action_index(this.ptr); + return BigNum.__wrap(ret); + } + /** + * @param {TransactionHash} transaction_id + * @param {BigNum} index + * @returns {TransactionInput} + */ + static new(transaction_id, index) { + _assertClass(transaction_id, TransactionHash); + _assertClass(index, BigNum); + const ret = wasm.governanceactionid_new(transaction_id.ptr, index.ptr); + return TransactionInput.__wrap(ret); + } +} +module.exports.TransactionInput = TransactionInput; + +const TransactionInputsFinalization = new FinalizationRegistry((ptr) => + wasm.__wbg_transactioninputs_free(ptr) +); +/** */ +class TransactionInputs { + static __wrap(ptr) { + const obj = Object.create(TransactionInputs.prototype); + obj.ptr = ptr; + TransactionInputsFinalization.register(obj, obj.ptr, obj); + return obj; + } + + __destroy_into_raw() { + const ptr = this.ptr; + this.ptr = 0; + TransactionInputsFinalization.unregister(this); + return ptr; + } + + free() { + const ptr = this.__destroy_into_raw(); + wasm.__wbg_transactioninputs_free(ptr); + } + /** + * @returns {Uint8Array} + */ + to_bytes() { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + wasm.transactioninputs_to_bytes(retptr, this.ptr); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var v0 = getArrayU8FromWasm0(r0, r1).slice(); + wasm.__wbindgen_free(r0, r1 * 1); + return v0; + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @param {Uint8Array} bytes + * @returns {TransactionInputs} + */ + static from_bytes(bytes) { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + const ptr0 = passArray8ToWasm0(bytes, wasm.__wbindgen_malloc); + const len0 = WASM_VECTOR_LEN; + wasm.transactioninputs_from_bytes(retptr, ptr0, len0); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + if (r2) { + throw takeObject(r1); + } + return TransactionInputs.__wrap(r0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @returns {string} + */ + to_json() { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + wasm.transactioninputs_to_json(retptr, this.ptr); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + var r3 = getInt32Memory0()[retptr / 4 + 3]; + var ptr0 = r0; + var len0 = r1; + if (r3) { + ptr0 = 0; + len0 = 0; + throw takeObject(r2); + } + return getStringFromWasm0(ptr0, len0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + wasm.__wbindgen_free(ptr0, len0); + } + } + /** + * @returns {any} + */ + to_js_value() { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + wasm.transactioninputs_to_js_value(retptr, this.ptr); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + if (r2) { + throw takeObject(r1); + } + return takeObject(r0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @param {string} json + * @returns {TransactionInputs} + */ + static from_json(json) { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + const ptr0 = passStringToWasm0( + json, + wasm.__wbindgen_malloc, + wasm.__wbindgen_realloc, + ); + const len0 = WASM_VECTOR_LEN; + wasm.transactioninputs_from_json(retptr, ptr0, len0); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + if (r2) { + throw takeObject(r1); + } + return TransactionInputs.__wrap(r0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @returns {TransactionInputs} + */ + static new() { + const ret = wasm.certificates_new(); + return TransactionInputs.__wrap(ret); + } + /** + * @returns {number} + */ + len() { + const ret = wasm.assetnames_len(this.ptr); + return ret >>> 0; + } + /** + * @param {number} index + * @returns {TransactionInput} + */ + get(index) { + const ret = wasm.transactioninputs_get(this.ptr, index); + return TransactionInput.__wrap(ret); + } + /** + * @param {TransactionInput} elem + */ + add(elem) { + _assertClass(elem, TransactionInput); + wasm.transactioninputs_add(this.ptr, elem.ptr); + } + /** */ + sort() { + wasm.transactioninputs_sort(this.ptr); + } +} +module.exports.TransactionInputs = TransactionInputs; + +const TransactionMetadatumFinalization = new FinalizationRegistry((ptr) => + wasm.__wbg_transactionmetadatum_free(ptr) +); +/** */ +class TransactionMetadatum { + static __wrap(ptr) { + const obj = Object.create(TransactionMetadatum.prototype); + obj.ptr = ptr; + TransactionMetadatumFinalization.register(obj, obj.ptr, obj); + return obj; + } + + __destroy_into_raw() { + const ptr = this.ptr; + this.ptr = 0; + TransactionMetadatumFinalization.unregister(this); + return ptr; + } + + free() { + const ptr = this.__destroy_into_raw(); + wasm.__wbg_transactionmetadatum_free(ptr); + } + /** + * @returns {Uint8Array} + */ + to_bytes() { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + wasm.transactionmetadatum_to_bytes(retptr, this.ptr); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var v0 = getArrayU8FromWasm0(r0, r1).slice(); + wasm.__wbindgen_free(r0, r1 * 1); + return v0; + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @param {Uint8Array} bytes + * @returns {TransactionMetadatum} + */ + static from_bytes(bytes) { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + const ptr0 = passArray8ToWasm0(bytes, wasm.__wbindgen_malloc); + const len0 = WASM_VECTOR_LEN; + wasm.transactionmetadatum_from_bytes(retptr, ptr0, len0); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + if (r2) { + throw takeObject(r1); + } + return TransactionMetadatum.__wrap(r0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @param {MetadataMap} map + * @returns {TransactionMetadatum} + */ + static new_map(map) { + _assertClass(map, MetadataMap); + const ret = wasm.transactionmetadatum_new_map(map.ptr); + return TransactionMetadatum.__wrap(ret); + } + /** + * @param {MetadataList} list + * @returns {TransactionMetadatum} + */ + static new_list(list) { + _assertClass(list, MetadataList); + const ret = wasm.transactionmetadatum_new_list(list.ptr); + return TransactionMetadatum.__wrap(ret); + } + /** + * @param {Int} int + * @returns {TransactionMetadatum} + */ + static new_int(int) { + _assertClass(int, Int); + const ret = wasm.transactionmetadatum_new_int(int.ptr); + return TransactionMetadatum.__wrap(ret); + } + /** + * @param {Uint8Array} bytes + * @returns {TransactionMetadatum} + */ + static new_bytes(bytes) { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + const ptr0 = passArray8ToWasm0(bytes, wasm.__wbindgen_malloc); + const len0 = WASM_VECTOR_LEN; + wasm.transactionmetadatum_new_bytes(retptr, ptr0, len0); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + if (r2) { + throw takeObject(r1); + } + return TransactionMetadatum.__wrap(r0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @param {string} text + * @returns {TransactionMetadatum} + */ + static new_text(text) { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + const ptr0 = passStringToWasm0( + text, + wasm.__wbindgen_malloc, + wasm.__wbindgen_realloc, + ); + const len0 = WASM_VECTOR_LEN; + wasm.transactionmetadatum_new_text(retptr, ptr0, len0); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + if (r2) { + throw takeObject(r1); + } + return TransactionMetadatum.__wrap(r0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @returns {number} + */ + kind() { + const ret = wasm.transactionmetadatum_kind(this.ptr); + return ret >>> 0; + } + /** + * @returns {MetadataMap} + */ + as_map() { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + wasm.transactionmetadatum_as_map(retptr, this.ptr); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + if (r2) { + throw takeObject(r1); + } + return MetadataMap.__wrap(r0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @returns {MetadataList} + */ + as_list() { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + wasm.transactionmetadatum_as_list(retptr, this.ptr); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + if (r2) { + throw takeObject(r1); + } + return MetadataList.__wrap(r0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @returns {Int} + */ + as_int() { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + wasm.transactionmetadatum_as_int(retptr, this.ptr); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + if (r2) { + throw takeObject(r1); + } + return Int.__wrap(r0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @returns {Uint8Array} + */ + as_bytes() { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + wasm.transactionmetadatum_as_bytes(retptr, this.ptr); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + var r3 = getInt32Memory0()[retptr / 4 + 3]; + if (r3) { + throw takeObject(r2); + } + var v0 = getArrayU8FromWasm0(r0, r1).slice(); + wasm.__wbindgen_free(r0, r1 * 1); + return v0; + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @returns {string} + */ + as_text() { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + wasm.transactionmetadatum_as_text(retptr, this.ptr); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + var r3 = getInt32Memory0()[retptr / 4 + 3]; + var ptr0 = r0; + var len0 = r1; + if (r3) { + ptr0 = 0; + len0 = 0; + throw takeObject(r2); + } + return getStringFromWasm0(ptr0, len0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + wasm.__wbindgen_free(ptr0, len0); + } + } +} +module.exports.TransactionMetadatum = TransactionMetadatum; + +const TransactionMetadatumLabelsFinalization = new FinalizationRegistry((ptr) => + wasm.__wbg_transactionmetadatumlabels_free(ptr) +); +/** */ +class TransactionMetadatumLabels { + static __wrap(ptr) { + const obj = Object.create(TransactionMetadatumLabels.prototype); + obj.ptr = ptr; + TransactionMetadatumLabelsFinalization.register(obj, obj.ptr, obj); + return obj; + } + + __destroy_into_raw() { + const ptr = this.ptr; + this.ptr = 0; + TransactionMetadatumLabelsFinalization.unregister(this); + return ptr; + } + + free() { + const ptr = this.__destroy_into_raw(); + wasm.__wbg_transactionmetadatumlabels_free(ptr); + } + /** + * @returns {Uint8Array} + */ + to_bytes() { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + wasm.transactionmetadatumlabels_to_bytes(retptr, this.ptr); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var v0 = getArrayU8FromWasm0(r0, r1).slice(); + wasm.__wbindgen_free(r0, r1 * 1); + return v0; + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @param {Uint8Array} bytes + * @returns {TransactionMetadatumLabels} + */ + static from_bytes(bytes) { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + const ptr0 = passArray8ToWasm0(bytes, wasm.__wbindgen_malloc); + const len0 = WASM_VECTOR_LEN; + wasm.transactionmetadatumlabels_from_bytes(retptr, ptr0, len0); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + if (r2) { + throw takeObject(r1); + } + return TransactionMetadatumLabels.__wrap(r0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @returns {TransactionMetadatumLabels} + */ + static new() { + const ret = wasm.certificates_new(); + return TransactionMetadatumLabels.__wrap(ret); + } + /** + * @returns {number} + */ + len() { + const ret = wasm.assetnames_len(this.ptr); + return ret >>> 0; + } + /** + * @param {number} index + * @returns {BigNum} + */ + get(index) { + const ret = wasm.transactionmetadatumlabels_get(this.ptr, index); + return BigNum.__wrap(ret); + } + /** + * @param {BigNum} elem + */ + add(elem) { + _assertClass(elem, BigNum); + wasm.transactionindexes_add(this.ptr, elem.ptr); + } +} +module.exports.TransactionMetadatumLabels = TransactionMetadatumLabels; + +const TransactionOutputFinalization = new FinalizationRegistry((ptr) => + wasm.__wbg_transactionoutput_free(ptr) +); +/** */ +class TransactionOutput { + static __wrap(ptr) { + const obj = Object.create(TransactionOutput.prototype); + obj.ptr = ptr; + TransactionOutputFinalization.register(obj, obj.ptr, obj); + return obj; + } + + __destroy_into_raw() { + const ptr = this.ptr; + this.ptr = 0; + TransactionOutputFinalization.unregister(this); + return ptr; + } + + free() { + const ptr = this.__destroy_into_raw(); + wasm.__wbg_transactionoutput_free(ptr); + } + /** + * @returns {Uint8Array} + */ + to_bytes() { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + wasm.transactionoutput_to_bytes(retptr, this.ptr); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var v0 = getArrayU8FromWasm0(r0, r1).slice(); + wasm.__wbindgen_free(r0, r1 * 1); + return v0; + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @param {Uint8Array} bytes + * @returns {TransactionOutput} + */ + static from_bytes(bytes) { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + const ptr0 = passArray8ToWasm0(bytes, wasm.__wbindgen_malloc); + const len0 = WASM_VECTOR_LEN; + wasm.transactionoutput_from_bytes(retptr, ptr0, len0); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + if (r2) { + throw takeObject(r1); + } + return TransactionOutput.__wrap(r0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @returns {string} + */ + to_json() { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + wasm.transactionoutput_to_json(retptr, this.ptr); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + var r3 = getInt32Memory0()[retptr / 4 + 3]; + var ptr0 = r0; + var len0 = r1; + if (r3) { + ptr0 = 0; + len0 = 0; + throw takeObject(r2); + } + return getStringFromWasm0(ptr0, len0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + wasm.__wbindgen_free(ptr0, len0); + } + } + /** + * @returns {any} + */ + to_js_value() { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + wasm.transactionoutput_to_js_value(retptr, this.ptr); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + if (r2) { + throw takeObject(r1); + } + return takeObject(r0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @param {string} json + * @returns {TransactionOutput} + */ + static from_json(json) { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + const ptr0 = passStringToWasm0( + json, + wasm.__wbindgen_malloc, + wasm.__wbindgen_realloc, + ); + const len0 = WASM_VECTOR_LEN; + wasm.transactionoutput_from_json(retptr, ptr0, len0); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + if (r2) { + throw takeObject(r1); + } + return TransactionOutput.__wrap(r0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @returns {Address} + */ + address() { + const ret = wasm.transactionoutput_address(this.ptr); + return Address.__wrap(ret); + } + /** + * @returns {Value} + */ + amount() { + const ret = wasm.transactionoutput_amount(this.ptr); + return Value.__wrap(ret); + } + /** + * @returns {Datum | undefined} + */ + datum() { + const ret = wasm.transactionoutput_datum(this.ptr); + return ret === 0 ? undefined : Datum.__wrap(ret); + } + /** + * @returns {ScriptRef | undefined} + */ + script_ref() { + const ret = wasm.transactionoutput_script_ref(this.ptr); + return ret === 0 ? undefined : ScriptRef.__wrap(ret); + } + /** + * @param {Datum} datum + */ + set_datum(datum) { + _assertClass(datum, Datum); + wasm.transactionoutput_set_datum(this.ptr, datum.ptr); + } + /** + * @param {ScriptRef} script_ref + */ + set_script_ref(script_ref) { + _assertClass(script_ref, ScriptRef); + wasm.transactionoutput_set_script_ref(this.ptr, script_ref.ptr); + } + /** + * @param {Address} address + * @param {Value} amount + * @returns {TransactionOutput} + */ + static new(address, amount) { + _assertClass(address, Address); + _assertClass(amount, Value); + const ret = wasm.transactionoutput_new(address.ptr, amount.ptr); + return TransactionOutput.__wrap(ret); + } + /** + * @returns {number} + */ + format() { + const ret = wasm.transactionoutput_format(this.ptr); + return ret; + } + /** + * legacy support: serialize output as array array + * + * does not support inline datum and script_ref! + * @returns {Uint8Array} + */ + to_legacy_bytes() { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + wasm.transactionoutput_to_legacy_bytes(retptr, this.ptr); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var v0 = getArrayU8FromWasm0(r0, r1).slice(); + wasm.__wbindgen_free(r0, r1 * 1); + return v0; + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } +} +module.exports.TransactionOutput = TransactionOutput; + +const TransactionOutputAmountBuilderFinalization = new FinalizationRegistry( + (ptr) => wasm.__wbg_transactionoutputamountbuilder_free(ptr) +); +/** */ +class TransactionOutputAmountBuilder { + static __wrap(ptr) { + const obj = Object.create(TransactionOutputAmountBuilder.prototype); + obj.ptr = ptr; + TransactionOutputAmountBuilderFinalization.register(obj, obj.ptr, obj); + return obj; + } + + __destroy_into_raw() { + const ptr = this.ptr; + this.ptr = 0; + TransactionOutputAmountBuilderFinalization.unregister(this); + return ptr; + } + + free() { + const ptr = this.__destroy_into_raw(); + wasm.__wbg_transactionoutputamountbuilder_free(ptr); + } + /** + * @param {Value} amount + * @returns {TransactionOutputAmountBuilder} + */ + with_value(amount) { + _assertClass(amount, Value); + const ret = wasm.transactionoutputamountbuilder_with_value( + this.ptr, + amount.ptr, + ); + return TransactionOutputAmountBuilder.__wrap(ret); + } + /** + * @param {BigNum} coin + * @returns {TransactionOutputAmountBuilder} + */ + with_coin(coin) { + _assertClass(coin, BigNum); + const ret = wasm.transactionoutputamountbuilder_with_coin( + this.ptr, + coin.ptr, + ); + return TransactionOutputAmountBuilder.__wrap(ret); + } + /** + * @param {BigNum} coin + * @param {MultiAsset} multiasset + * @returns {TransactionOutputAmountBuilder} + */ + with_coin_and_asset(coin, multiasset) { + _assertClass(coin, BigNum); + _assertClass(multiasset, MultiAsset); + const ret = wasm.transactionoutputamountbuilder_with_coin_and_asset( + this.ptr, + coin.ptr, + multiasset.ptr, + ); + return TransactionOutputAmountBuilder.__wrap(ret); + } + /** + * @param {MultiAsset} multiasset + * @param {BigNum} coins_per_utxo_word + * @returns {TransactionOutputAmountBuilder} + */ + with_asset_and_min_required_coin(multiasset, coins_per_utxo_word) { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + _assertClass(multiasset, MultiAsset); + _assertClass(coins_per_utxo_word, BigNum); + wasm.transactionoutputamountbuilder_with_asset_and_min_required_coin( + retptr, + this.ptr, + multiasset.ptr, + coins_per_utxo_word.ptr, + ); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + if (r2) { + throw takeObject(r1); + } + return TransactionOutputAmountBuilder.__wrap(r0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @returns {TransactionOutput} + */ + build() { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + wasm.transactionoutputamountbuilder_build(retptr, this.ptr); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + if (r2) { + throw takeObject(r1); + } + return TransactionOutput.__wrap(r0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } +} +module.exports.TransactionOutputAmountBuilder = TransactionOutputAmountBuilder; + +const TransactionOutputBuilderFinalization = new FinalizationRegistry((ptr) => + wasm.__wbg_transactionoutputbuilder_free(ptr) +); +/** + * We introduce a builder-pattern format for creating transaction outputs + * This is because: + * 1. Some fields (i.e. data hash) are optional, and we can't easily expose Option<> in WASM + * 2. Some fields like amounts have many ways it could be set (some depending on other field values being known) + * 3. Easier to adapt as the output format gets more complicated in future Cardano releases + */ +class TransactionOutputBuilder { + static __wrap(ptr) { + const obj = Object.create(TransactionOutputBuilder.prototype); + obj.ptr = ptr; + TransactionOutputBuilderFinalization.register(obj, obj.ptr, obj); + return obj; + } + + __destroy_into_raw() { + const ptr = this.ptr; + this.ptr = 0; + TransactionOutputBuilderFinalization.unregister(this); + return ptr; + } + + free() { + const ptr = this.__destroy_into_raw(); + wasm.__wbg_transactionoutputbuilder_free(ptr); + } + /** + * @returns {TransactionOutputBuilder} + */ + static new() { + const ret = wasm.transactionoutputbuilder_new(); + return TransactionOutputBuilder.__wrap(ret); + } + /** + * @param {Address} address + * @returns {TransactionOutputBuilder} + */ + with_address(address) { + _assertClass(address, Address); + const ret = wasm.transactionoutputbuilder_with_address( + this.ptr, + address.ptr, + ); + return TransactionOutputBuilder.__wrap(ret); + } + /** + * @param {Datum} data_hash + * @returns {TransactionOutputBuilder} + */ + with_datum(data_hash) { + _assertClass(data_hash, Datum); + const ret = wasm.transactionoutputbuilder_with_datum( + this.ptr, + data_hash.ptr, + ); + return TransactionOutputBuilder.__wrap(ret); + } + /** + * @returns {TransactionOutputAmountBuilder} + */ + next() { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + wasm.transactionoutputbuilder_next(retptr, this.ptr); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + if (r2) { + throw takeObject(r1); + } + return TransactionOutputAmountBuilder.__wrap(r0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } +} +module.exports.TransactionOutputBuilder = TransactionOutputBuilder; + +const TransactionOutputsFinalization = new FinalizationRegistry((ptr) => + wasm.__wbg_transactionoutputs_free(ptr) +); +/** */ +class TransactionOutputs { + static __wrap(ptr) { + const obj = Object.create(TransactionOutputs.prototype); + obj.ptr = ptr; + TransactionOutputsFinalization.register(obj, obj.ptr, obj); + return obj; + } + + __destroy_into_raw() { + const ptr = this.ptr; + this.ptr = 0; + TransactionOutputsFinalization.unregister(this); + return ptr; + } + + free() { + const ptr = this.__destroy_into_raw(); + wasm.__wbg_transactionoutputs_free(ptr); + } + /** + * @returns {Uint8Array} + */ + to_bytes() { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + wasm.transactionoutputs_to_bytes(retptr, this.ptr); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var v0 = getArrayU8FromWasm0(r0, r1).slice(); + wasm.__wbindgen_free(r0, r1 * 1); + return v0; + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @param {Uint8Array} bytes + * @returns {TransactionOutputs} + */ + static from_bytes(bytes) { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + const ptr0 = passArray8ToWasm0(bytes, wasm.__wbindgen_malloc); + const len0 = WASM_VECTOR_LEN; + wasm.transactionoutputs_from_bytes(retptr, ptr0, len0); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + if (r2) { + throw takeObject(r1); + } + return TransactionOutputs.__wrap(r0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @returns {string} + */ + to_json() { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + wasm.transactionoutputs_to_json(retptr, this.ptr); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + var r3 = getInt32Memory0()[retptr / 4 + 3]; + var ptr0 = r0; + var len0 = r1; + if (r3) { + ptr0 = 0; + len0 = 0; + throw takeObject(r2); + } + return getStringFromWasm0(ptr0, len0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + wasm.__wbindgen_free(ptr0, len0); + } + } + /** + * @returns {any} + */ + to_js_value() { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + wasm.transactionoutputs_to_js_value(retptr, this.ptr); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + if (r2) { + throw takeObject(r1); + } + return takeObject(r0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @param {string} json + * @returns {TransactionOutputs} + */ + static from_json(json) { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + const ptr0 = passStringToWasm0( + json, + wasm.__wbindgen_malloc, + wasm.__wbindgen_realloc, + ); + const len0 = WASM_VECTOR_LEN; + wasm.transactionoutputs_from_json(retptr, ptr0, len0); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + if (r2) { + throw takeObject(r1); + } + return TransactionOutputs.__wrap(r0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @returns {TransactionOutputs} + */ + static new() { + const ret = wasm.certificates_new(); + return TransactionOutputs.__wrap(ret); + } + /** + * @returns {number} + */ + len() { + const ret = wasm.assetnames_len(this.ptr); + return ret >>> 0; + } + /** + * @param {number} index + * @returns {TransactionOutput} + */ + get(index) { + const ret = wasm.transactionoutputs_get(this.ptr, index); + return TransactionOutput.__wrap(ret); + } + /** + * @param {TransactionOutput} elem + */ + add(elem) { + _assertClass(elem, TransactionOutput); + wasm.transactionoutputs_add(this.ptr, elem.ptr); + } +} +module.exports.TransactionOutputs = TransactionOutputs; + +const TransactionUnspentOutputFinalization = new FinalizationRegistry((ptr) => + wasm.__wbg_transactionunspentoutput_free(ptr) +); +/** */ +class TransactionUnspentOutput { + static __wrap(ptr) { + const obj = Object.create(TransactionUnspentOutput.prototype); + obj.ptr = ptr; + TransactionUnspentOutputFinalization.register(obj, obj.ptr, obj); + return obj; + } + + __destroy_into_raw() { + const ptr = this.ptr; + this.ptr = 0; + TransactionUnspentOutputFinalization.unregister(this); + return ptr; + } + + free() { + const ptr = this.__destroy_into_raw(); + wasm.__wbg_transactionunspentoutput_free(ptr); + } + /** + * @returns {Uint8Array} + */ + to_bytes() { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + wasm.transactionunspentoutput_to_bytes(retptr, this.ptr); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var v0 = getArrayU8FromWasm0(r0, r1).slice(); + wasm.__wbindgen_free(r0, r1 * 1); + return v0; + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @param {Uint8Array} bytes + * @returns {TransactionUnspentOutput} + */ + static from_bytes(bytes) { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + const ptr0 = passArray8ToWasm0(bytes, wasm.__wbindgen_malloc); + const len0 = WASM_VECTOR_LEN; + wasm.transactionunspentoutput_from_bytes(retptr, ptr0, len0); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + if (r2) { + throw takeObject(r1); + } + return TransactionUnspentOutput.__wrap(r0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @param {TransactionInput} input + * @param {TransactionOutput} output + * @returns {TransactionUnspentOutput} + */ + static new(input, output) { + _assertClass(input, TransactionInput); + _assertClass(output, TransactionOutput); + const ret = wasm.transactionunspentoutput_new(input.ptr, output.ptr); + return TransactionUnspentOutput.__wrap(ret); + } + /** + * @returns {TransactionInput} + */ + input() { + const ret = wasm.transactionunspentoutput_input(this.ptr); + return TransactionInput.__wrap(ret); + } + /** + * @returns {TransactionOutput} + */ + output() { + const ret = wasm.transactionunspentoutput_output(this.ptr); + return TransactionOutput.__wrap(ret); + } + /** + * @returns {Uint8Array} + */ + to_legacy_bytes() { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + wasm.transactionunspentoutput_to_legacy_bytes(retptr, this.ptr); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var v0 = getArrayU8FromWasm0(r0, r1).slice(); + wasm.__wbindgen_free(r0, r1 * 1); + return v0; + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } +} +module.exports.TransactionUnspentOutput = TransactionUnspentOutput; + +const TransactionUnspentOutputsFinalization = new FinalizationRegistry((ptr) => + wasm.__wbg_transactionunspentoutputs_free(ptr) +); +/** */ +class TransactionUnspentOutputs { + static __wrap(ptr) { + const obj = Object.create(TransactionUnspentOutputs.prototype); + obj.ptr = ptr; + TransactionUnspentOutputsFinalization.register(obj, obj.ptr, obj); + return obj; + } + + __destroy_into_raw() { + const ptr = this.ptr; + this.ptr = 0; + TransactionUnspentOutputsFinalization.unregister(this); + return ptr; + } + + free() { + const ptr = this.__destroy_into_raw(); + wasm.__wbg_transactionunspentoutputs_free(ptr); + } + /** + * @returns {TransactionUnspentOutputs} + */ + static new() { + const ret = wasm.certificates_new(); + return TransactionUnspentOutputs.__wrap(ret); + } + /** + * @returns {number} + */ + len() { + const ret = wasm.assetnames_len(this.ptr); + return ret >>> 0; + } + /** + * @param {number} index + * @returns {TransactionUnspentOutput} + */ + get(index) { + const ret = wasm.transactionunspentoutputs_get(this.ptr, index); + return TransactionUnspentOutput.__wrap(ret); + } + /** + * @param {TransactionUnspentOutput} elem + */ + add(elem) { + _assertClass(elem, TransactionUnspentOutput); + wasm.transactionunspentoutputs_add(this.ptr, elem.ptr); + } +} +module.exports.TransactionUnspentOutputs = TransactionUnspentOutputs; + +const TransactionWitnessSetFinalization = new FinalizationRegistry((ptr) => + wasm.__wbg_transactionwitnessset_free(ptr) +); +/** */ +class TransactionWitnessSet { + static __wrap(ptr) { + const obj = Object.create(TransactionWitnessSet.prototype); + obj.ptr = ptr; + TransactionWitnessSetFinalization.register(obj, obj.ptr, obj); + return obj; + } + + __destroy_into_raw() { + const ptr = this.ptr; + this.ptr = 0; + TransactionWitnessSetFinalization.unregister(this); + return ptr; + } + + free() { + const ptr = this.__destroy_into_raw(); + wasm.__wbg_transactionwitnessset_free(ptr); + } + /** + * @returns {Uint8Array} + */ + to_bytes() { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + wasm.transactionwitnessset_to_bytes(retptr, this.ptr); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var v0 = getArrayU8FromWasm0(r0, r1).slice(); + wasm.__wbindgen_free(r0, r1 * 1); + return v0; + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @param {Uint8Array} bytes + * @returns {TransactionWitnessSet} + */ + static from_bytes(bytes) { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + const ptr0 = passArray8ToWasm0(bytes, wasm.__wbindgen_malloc); + const len0 = WASM_VECTOR_LEN; + wasm.transactionwitnessset_from_bytes(retptr, ptr0, len0); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + if (r2) { + throw takeObject(r1); + } + return TransactionWitnessSet.__wrap(r0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @returns {string} + */ + to_json() { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + wasm.transactionwitnessset_to_json(retptr, this.ptr); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + var r3 = getInt32Memory0()[retptr / 4 + 3]; + var ptr0 = r0; + var len0 = r1; + if (r3) { + ptr0 = 0; + len0 = 0; + throw takeObject(r2); + } + return getStringFromWasm0(ptr0, len0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + wasm.__wbindgen_free(ptr0, len0); + } + } + /** + * @returns {any} + */ + to_js_value() { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + wasm.transactionwitnessset_to_js_value(retptr, this.ptr); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + if (r2) { + throw takeObject(r1); + } + return takeObject(r0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @param {string} json + * @returns {TransactionWitnessSet} + */ + static from_json(json) { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + const ptr0 = passStringToWasm0( + json, + wasm.__wbindgen_malloc, + wasm.__wbindgen_realloc, + ); + const len0 = WASM_VECTOR_LEN; + wasm.transactionwitnessset_from_json(retptr, ptr0, len0); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + if (r2) { + throw takeObject(r1); + } + return TransactionWitnessSet.__wrap(r0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @param {Vkeywitnesses} vkeys + */ + set_vkeys(vkeys) { + _assertClass(vkeys, Vkeywitnesses); + wasm.transactionwitnessset_set_vkeys(this.ptr, vkeys.ptr); + } + /** + * @returns {Vkeywitnesses | undefined} + */ + vkeys() { + const ret = wasm.transactionwitnessset_vkeys(this.ptr); + return ret === 0 ? undefined : Vkeywitnesses.__wrap(ret); + } + /** + * @param {NativeScripts} native_scripts + */ + set_native_scripts(native_scripts) { + _assertClass(native_scripts, NativeScripts); + wasm.transactionwitnessset_set_native_scripts(this.ptr, native_scripts.ptr); + } + /** + * @returns {NativeScripts | undefined} + */ + native_scripts() { + const ret = wasm.transactionwitnessset_native_scripts(this.ptr); + return ret === 0 ? undefined : NativeScripts.__wrap(ret); + } + /** + * @param {BootstrapWitnesses} bootstraps + */ + set_bootstraps(bootstraps) { + _assertClass(bootstraps, BootstrapWitnesses); + wasm.transactionwitnessset_set_bootstraps(this.ptr, bootstraps.ptr); + } + /** + * @returns {BootstrapWitnesses | undefined} + */ + bootstraps() { + const ret = wasm.transactionwitnessset_bootstraps(this.ptr); + return ret === 0 ? undefined : BootstrapWitnesses.__wrap(ret); + } + /** + * @param {PlutusScripts} plutus_scripts + */ + set_plutus_scripts(plutus_scripts) { + _assertClass(plutus_scripts, PlutusScripts); + wasm.transactionwitnessset_set_plutus_scripts(this.ptr, plutus_scripts.ptr); + } + /** + * @returns {PlutusScripts | undefined} + */ + plutus_scripts() { + const ret = wasm.transactionwitnessset_plutus_scripts(this.ptr); + return ret === 0 ? undefined : PlutusScripts.__wrap(ret); + } + /** + * @param {PlutusList} plutus_data + */ + set_plutus_data(plutus_data) { + _assertClass(plutus_data, PlutusList); + wasm.transactionwitnessset_set_plutus_data(this.ptr, plutus_data.ptr); + } + /** + * @returns {PlutusList | undefined} + */ + plutus_data() { + const ret = wasm.transactionwitnessset_plutus_data(this.ptr); + return ret === 0 ? undefined : PlutusList.__wrap(ret); + } + /** + * @param {Redeemers} redeemers + */ + set_redeemers(redeemers) { + _assertClass(redeemers, Redeemers); + wasm.transactionwitnessset_set_redeemers(this.ptr, redeemers.ptr); + } + /** + * @param {PlutusScripts} plutus_scripts + */ + set_plutus_v2_scripts(plutus_scripts) { + _assertClass(plutus_scripts, PlutusScripts); + wasm.transactionwitnessset_set_plutus_v2_scripts( + this.ptr, + plutus_scripts.ptr, + ); + } + /** + * @param {PlutusScripts} plutus_scripts + */ + set_plutus_v3_scripts(plutus_scripts) { + _assertClass(plutus_scripts, PlutusScripts); + wasm.transactionwitnessset_set_plutus_v3_scripts( + this.ptr, + plutus_scripts.ptr, + ); + } + /** + * @returns {Redeemers | undefined} + */ + redeemers() { + const ret = wasm.transactionwitnessset_redeemers(this.ptr); + return ret === 0 ? undefined : Redeemers.__wrap(ret); + } + /** + * @returns {PlutusScripts | undefined} + */ + plutus_v2_scripts() { + const ret = wasm.transactionwitnessset_plutus_v2_scripts(this.ptr); + return ret === 0 ? undefined : PlutusScripts.__wrap(ret); + } + /** + * @returns {PlutusScripts | undefined} + */ + plutus_v3_scripts() { + const ret = wasm.transactionwitnessset_plutus_v3_scripts(this.ptr); + return ret === 0 ? undefined : PlutusScripts.__wrap(ret); + } + /** + * @returns {TransactionWitnessSet} + */ + static new() { + const ret = wasm.transactionwitnessset_new(); + return TransactionWitnessSet.__wrap(ret); + } +} +module.exports.TransactionWitnessSet = TransactionWitnessSet; + +const TransactionWitnessSetBuilderFinalization = new FinalizationRegistry( + (ptr) => wasm.__wbg_transactionwitnesssetbuilder_free(ptr) +); +/** + * Builder de-duplicates witnesses as they are added + */ +class TransactionWitnessSetBuilder { + static __wrap(ptr) { + const obj = Object.create(TransactionWitnessSetBuilder.prototype); + obj.ptr = ptr; + TransactionWitnessSetBuilderFinalization.register(obj, obj.ptr, obj); + return obj; + } + + __destroy_into_raw() { + const ptr = this.ptr; + this.ptr = 0; + TransactionWitnessSetBuilderFinalization.unregister(this); + return ptr; + } + + free() { + const ptr = this.__destroy_into_raw(); + wasm.__wbg_transactionwitnesssetbuilder_free(ptr); + } + /** + * @param {Vkeywitness} vkey + */ + add_vkey(vkey) { + _assertClass(vkey, Vkeywitness); + wasm.transactionwitnesssetbuilder_add_vkey(this.ptr, vkey.ptr); + } + /** + * @param {BootstrapWitness} bootstrap + */ + add_bootstrap(bootstrap) { + _assertClass(bootstrap, BootstrapWitness); + wasm.transactionwitnesssetbuilder_add_bootstrap(this.ptr, bootstrap.ptr); + } + /** + * @param {NativeScript} native_script + */ + add_native_script(native_script) { + _assertClass(native_script, NativeScript); + wasm.transactionwitnesssetbuilder_add_native_script( + this.ptr, + native_script.ptr, + ); + } + /** + * @param {PlutusScript} plutus_script + */ + add_plutus_script(plutus_script) { + _assertClass(plutus_script, PlutusScript); + wasm.transactionwitnesssetbuilder_add_plutus_script( + this.ptr, + plutus_script.ptr, + ); + } + /** + * @param {PlutusScript} plutus_script + */ + add_plutus_v2_script(plutus_script) { + _assertClass(plutus_script, PlutusScript); + wasm.transactionwitnesssetbuilder_add_plutus_v2_script( + this.ptr, + plutus_script.ptr, + ); + } + /** + * @param {PlutusData} plutus_datum + */ + add_plutus_datum(plutus_datum) { + _assertClass(plutus_datum, PlutusData); + wasm.transactionwitnesssetbuilder_add_plutus_datum( + this.ptr, + plutus_datum.ptr, + ); + } + /** + * @param {Redeemer} redeemer + */ + add_redeemer(redeemer) { + _assertClass(redeemer, Redeemer); + wasm.transactionwitnesssetbuilder_add_redeemer(this.ptr, redeemer.ptr); + } + /** + * @param {RequiredWitnessSet} required_wits + */ + add_required_wits(required_wits) { + _assertClass(required_wits, RequiredWitnessSet); + wasm.transactionwitnesssetbuilder_add_required_wits( + this.ptr, + required_wits.ptr, + ); + } + /** + * @returns {TransactionWitnessSetBuilder} + */ + static new() { + const ret = wasm.transactionwitnesssetbuilder_new(); + return TransactionWitnessSetBuilder.__wrap(ret); + } + /** + * @param {TransactionWitnessSet} wit_set + */ + add_existing(wit_set) { + _assertClass(wit_set, TransactionWitnessSet); + wasm.transactionwitnesssetbuilder_add_existing(this.ptr, wit_set.ptr); + } + /** + * @returns {TransactionWitnessSet} + */ + build() { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + wasm.transactionwitnesssetbuilder_build(retptr, this.ptr); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + if (r2) { + throw takeObject(r1); + } + return TransactionWitnessSet.__wrap(r0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } +} +module.exports.TransactionWitnessSetBuilder = TransactionWitnessSetBuilder; + +const TransactionWitnessSetsFinalization = new FinalizationRegistry((ptr) => + wasm.__wbg_transactionwitnesssets_free(ptr) +); +/** */ +class TransactionWitnessSets { + static __wrap(ptr) { + const obj = Object.create(TransactionWitnessSets.prototype); + obj.ptr = ptr; + TransactionWitnessSetsFinalization.register(obj, obj.ptr, obj); + return obj; + } + + __destroy_into_raw() { + const ptr = this.ptr; + this.ptr = 0; + TransactionWitnessSetsFinalization.unregister(this); + return ptr; + } + + free() { + const ptr = this.__destroy_into_raw(); + wasm.__wbg_transactionwitnesssets_free(ptr); + } + /** + * @returns {Uint8Array} + */ + to_bytes() { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + wasm.transactionwitnesssets_to_bytes(retptr, this.ptr); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var v0 = getArrayU8FromWasm0(r0, r1).slice(); + wasm.__wbindgen_free(r0, r1 * 1); + return v0; + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @param {Uint8Array} bytes + * @returns {TransactionWitnessSets} + */ + static from_bytes(bytes) { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + const ptr0 = passArray8ToWasm0(bytes, wasm.__wbindgen_malloc); + const len0 = WASM_VECTOR_LEN; + wasm.transactionwitnesssets_from_bytes(retptr, ptr0, len0); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + if (r2) { + throw takeObject(r1); + } + return TransactionWitnessSets.__wrap(r0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @returns {string} + */ + to_json() { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + wasm.transactionwitnesssets_to_json(retptr, this.ptr); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + var r3 = getInt32Memory0()[retptr / 4 + 3]; + var ptr0 = r0; + var len0 = r1; + if (r3) { + ptr0 = 0; + len0 = 0; + throw takeObject(r2); + } + return getStringFromWasm0(ptr0, len0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + wasm.__wbindgen_free(ptr0, len0); + } + } + /** + * @returns {any} + */ + to_js_value() { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + wasm.transactionwitnesssets_to_js_value(retptr, this.ptr); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + if (r2) { + throw takeObject(r1); + } + return takeObject(r0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @param {string} json + * @returns {TransactionWitnessSets} + */ + static from_json(json) { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + const ptr0 = passStringToWasm0( + json, + wasm.__wbindgen_malloc, + wasm.__wbindgen_realloc, + ); + const len0 = WASM_VECTOR_LEN; + wasm.transactionwitnesssets_from_json(retptr, ptr0, len0); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + if (r2) { + throw takeObject(r1); + } + return TransactionWitnessSets.__wrap(r0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @returns {TransactionWitnessSets} + */ + static new() { + const ret = wasm.assetnames_new(); + return TransactionWitnessSets.__wrap(ret); + } + /** + * @returns {number} + */ + len() { + const ret = wasm.assetnames_len(this.ptr); + return ret >>> 0; + } + /** + * @param {number} index + * @returns {TransactionWitnessSet} + */ + get(index) { + const ret = wasm.transactionwitnesssets_get(this.ptr, index); + return TransactionWitnessSet.__wrap(ret); + } + /** + * @param {TransactionWitnessSet} elem + */ + add(elem) { + _assertClass(elem, TransactionWitnessSet); + wasm.transactionwitnesssets_add(this.ptr, elem.ptr); + } +} +module.exports.TransactionWitnessSets = TransactionWitnessSets; + +const TreasuryWithdrawalsFinalization = new FinalizationRegistry((ptr) => + wasm.__wbg_treasurywithdrawals_free(ptr) +); +/** */ +class TreasuryWithdrawals { + static __wrap(ptr) { + const obj = Object.create(TreasuryWithdrawals.prototype); + obj.ptr = ptr; + TreasuryWithdrawalsFinalization.register(obj, obj.ptr, obj); + return obj; + } + + __destroy_into_raw() { + const ptr = this.ptr; + this.ptr = 0; + TreasuryWithdrawalsFinalization.unregister(this); + return ptr; + } + + free() { + const ptr = this.__destroy_into_raw(); + wasm.__wbg_treasurywithdrawals_free(ptr); + } + /** + * @returns {Uint8Array} + */ + to_bytes() { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + wasm.treasurywithdrawals_to_bytes(retptr, this.ptr); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var v0 = getArrayU8FromWasm0(r0, r1).slice(); + wasm.__wbindgen_free(r0, r1 * 1); + return v0; + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @param {Uint8Array} bytes + * @returns {TreasuryWithdrawals} + */ + static from_bytes(bytes) { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + const ptr0 = passArray8ToWasm0(bytes, wasm.__wbindgen_malloc); + const len0 = WASM_VECTOR_LEN; + wasm.treasurywithdrawals_from_bytes(retptr, ptr0, len0); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + if (r2) { + throw takeObject(r1); + } + return TreasuryWithdrawals.__wrap(r0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @returns {string} + */ + to_json() { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + wasm.treasurywithdrawals_to_json(retptr, this.ptr); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + var r3 = getInt32Memory0()[retptr / 4 + 3]; + var ptr0 = r0; + var len0 = r1; + if (r3) { + ptr0 = 0; + len0 = 0; + throw takeObject(r2); + } + return getStringFromWasm0(ptr0, len0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + wasm.__wbindgen_free(ptr0, len0); + } + } + /** + * @returns {any} + */ + to_js_value() { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + wasm.treasurywithdrawals_to_js_value(retptr, this.ptr); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + if (r2) { + throw takeObject(r1); + } + return takeObject(r0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @param {string} json + * @returns {TreasuryWithdrawals} + */ + static from_json(json) { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + const ptr0 = passStringToWasm0( + json, + wasm.__wbindgen_malloc, + wasm.__wbindgen_realloc, + ); + const len0 = WASM_VECTOR_LEN; + wasm.treasurywithdrawals_from_json(retptr, ptr0, len0); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + if (r2) { + throw takeObject(r1); + } + return TreasuryWithdrawals.__wrap(r0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @returns {TreasuryWithdrawals} + */ + static new() { + const ret = wasm.assets_new(); + return TreasuryWithdrawals.__wrap(ret); + } + /** + * @returns {number} + */ + len() { + const ret = wasm.assetnames_len(this.ptr); + return ret >>> 0; + } + /** + * @param {Ed25519KeyHash} key + * @param {BigNum} value + * @returns {BigNum | undefined} + */ + insert(key, value) { + _assertClass(key, Ed25519KeyHash); + _assertClass(value, BigNum); + const ret = wasm.treasurywithdrawals_insert(this.ptr, key.ptr, value.ptr); + return ret === 0 ? undefined : BigNum.__wrap(ret); + } + /** + * @param {Ed25519KeyHash} key + * @returns {BigNum | undefined} + */ + get(key) { + _assertClass(key, Ed25519KeyHash); + const ret = wasm.treasurywithdrawals_get(this.ptr, key.ptr); + return ret === 0 ? undefined : BigNum.__wrap(ret); + } + /** + * @returns {Ed25519KeyHashes} + */ + keys() { + const ret = wasm.treasurywithdrawals_keys(this.ptr); + return Ed25519KeyHashes.__wrap(ret); + } +} +module.exports.TreasuryWithdrawals = TreasuryWithdrawals; + +const TreasuryWithdrawalsActionFinalization = new FinalizationRegistry((ptr) => + wasm.__wbg_treasurywithdrawalsaction_free(ptr) +); +/** */ +class TreasuryWithdrawalsAction { + static __wrap(ptr) { + const obj = Object.create(TreasuryWithdrawalsAction.prototype); + obj.ptr = ptr; + TreasuryWithdrawalsActionFinalization.register(obj, obj.ptr, obj); + return obj; + } + + __destroy_into_raw() { + const ptr = this.ptr; + this.ptr = 0; + TreasuryWithdrawalsActionFinalization.unregister(this); + return ptr; + } + + free() { + const ptr = this.__destroy_into_raw(); + wasm.__wbg_treasurywithdrawalsaction_free(ptr); + } + /** + * @returns {Uint8Array} + */ + to_bytes() { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + wasm.treasurywithdrawalsaction_to_bytes(retptr, this.ptr); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var v0 = getArrayU8FromWasm0(r0, r1).slice(); + wasm.__wbindgen_free(r0, r1 * 1); + return v0; + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @param {Uint8Array} bytes + * @returns {TreasuryWithdrawalsAction} + */ + static from_bytes(bytes) { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + const ptr0 = passArray8ToWasm0(bytes, wasm.__wbindgen_malloc); + const len0 = WASM_VECTOR_LEN; + wasm.treasurywithdrawalsaction_from_bytes(retptr, ptr0, len0); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + if (r2) { + throw takeObject(r1); + } + return TreasuryWithdrawalsAction.__wrap(r0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @returns {string} + */ + to_json() { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + wasm.treasurywithdrawalsaction_to_json(retptr, this.ptr); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + var r3 = getInt32Memory0()[retptr / 4 + 3]; + var ptr0 = r0; + var len0 = r1; + if (r3) { + ptr0 = 0; + len0 = 0; + throw takeObject(r2); + } + return getStringFromWasm0(ptr0, len0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + wasm.__wbindgen_free(ptr0, len0); + } + } + /** + * @returns {any} + */ + to_js_value() { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + wasm.treasurywithdrawalsaction_to_js_value(retptr, this.ptr); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + if (r2) { + throw takeObject(r1); + } + return takeObject(r0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @param {string} json + * @returns {TreasuryWithdrawalsAction} + */ + static from_json(json) { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + const ptr0 = passStringToWasm0( + json, + wasm.__wbindgen_malloc, + wasm.__wbindgen_realloc, + ); + const len0 = WASM_VECTOR_LEN; + wasm.treasurywithdrawalsaction_from_json(retptr, ptr0, len0); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + if (r2) { + throw takeObject(r1); + } + return TreasuryWithdrawalsAction.__wrap(r0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @returns {TreasuryWithdrawals} + */ + withdrawals() { + const ret = wasm.treasurywithdrawalsaction_withdrawals(this.ptr); + return TreasuryWithdrawals.__wrap(ret); + } + /** + * @param {TreasuryWithdrawals} withdrawals + * @returns {TreasuryWithdrawalsAction} + */ + static new(withdrawals) { + _assertClass(withdrawals, TreasuryWithdrawals); + const ret = wasm.treasurywithdrawalsaction_new(withdrawals.ptr); + return TreasuryWithdrawalsAction.__wrap(ret); + } +} +module.exports.TreasuryWithdrawalsAction = TreasuryWithdrawalsAction; + +const UnitIntervalFinalization = new FinalizationRegistry((ptr) => + wasm.__wbg_unitinterval_free(ptr) +); +/** */ +class UnitInterval { + static __wrap(ptr) { + const obj = Object.create(UnitInterval.prototype); + obj.ptr = ptr; + UnitIntervalFinalization.register(obj, obj.ptr, obj); + return obj; + } + + __destroy_into_raw() { + const ptr = this.ptr; + this.ptr = 0; + UnitIntervalFinalization.unregister(this); + return ptr; + } + + free() { + const ptr = this.__destroy_into_raw(); + wasm.__wbg_unitinterval_free(ptr); + } + /** + * @returns {Uint8Array} + */ + to_bytes() { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + wasm.unitinterval_to_bytes(retptr, this.ptr); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var v0 = getArrayU8FromWasm0(r0, r1).slice(); + wasm.__wbindgen_free(r0, r1 * 1); + return v0; + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @param {Uint8Array} bytes + * @returns {UnitInterval} + */ + static from_bytes(bytes) { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + const ptr0 = passArray8ToWasm0(bytes, wasm.__wbindgen_malloc); + const len0 = WASM_VECTOR_LEN; + wasm.unitinterval_from_bytes(retptr, ptr0, len0); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + if (r2) { + throw takeObject(r1); + } + return UnitInterval.__wrap(r0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @returns {string} + */ + to_json() { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + wasm.unitinterval_to_json(retptr, this.ptr); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + var r3 = getInt32Memory0()[retptr / 4 + 3]; + var ptr0 = r0; + var len0 = r1; + if (r3) { + ptr0 = 0; + len0 = 0; + throw takeObject(r2); + } + return getStringFromWasm0(ptr0, len0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + wasm.__wbindgen_free(ptr0, len0); + } + } + /** + * @returns {any} + */ + to_js_value() { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + wasm.unitinterval_to_js_value(retptr, this.ptr); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + if (r2) { + throw takeObject(r1); + } + return takeObject(r0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @param {string} json + * @returns {UnitInterval} + */ + static from_json(json) { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + const ptr0 = passStringToWasm0( + json, + wasm.__wbindgen_malloc, + wasm.__wbindgen_realloc, + ); + const len0 = WASM_VECTOR_LEN; + wasm.unitinterval_from_json(retptr, ptr0, len0); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + if (r2) { + throw takeObject(r1); + } + return UnitInterval.__wrap(r0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @returns {BigNum} + */ + numerator() { + const ret = wasm.constrplutusdata_alternative(this.ptr); + return BigNum.__wrap(ret); + } + /** + * @returns {BigNum} + */ + denominator() { + const ret = wasm.exunits_steps(this.ptr); + return BigNum.__wrap(ret); + } + /** + * @param {BigNum} numerator + * @param {BigNum} denominator + * @returns {UnitInterval} + */ + static new(numerator, denominator) { + _assertClass(numerator, BigNum); + _assertClass(denominator, BigNum); + const ret = wasm.exunits_new(numerator.ptr, denominator.ptr); + return UnitInterval.__wrap(ret); + } + /** + * @param {number} float_number + * @returns {UnitInterval} + */ + static from_float(float_number) { + const ret = wasm.unitinterval_from_float(float_number); + return UnitInterval.__wrap(ret); + } +} +module.exports.UnitInterval = UnitInterval; + +const UnregCertFinalization = new FinalizationRegistry((ptr) => + wasm.__wbg_unregcert_free(ptr) +); +/** */ +class UnregCert { + static __wrap(ptr) { + const obj = Object.create(UnregCert.prototype); + obj.ptr = ptr; + UnregCertFinalization.register(obj, obj.ptr, obj); + return obj; + } + + __destroy_into_raw() { + const ptr = this.ptr; + this.ptr = 0; + UnregCertFinalization.unregister(this); + return ptr; + } + + free() { + const ptr = this.__destroy_into_raw(); + wasm.__wbg_unregcert_free(ptr); + } + /** + * @returns {Uint8Array} + */ + to_bytes() { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + wasm.unregcert_to_bytes(retptr, this.ptr); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var v0 = getArrayU8FromWasm0(r0, r1).slice(); + wasm.__wbindgen_free(r0, r1 * 1); + return v0; + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @param {Uint8Array} bytes + * @returns {UnregCert} + */ + static from_bytes(bytes) { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + const ptr0 = passArray8ToWasm0(bytes, wasm.__wbindgen_malloc); + const len0 = WASM_VECTOR_LEN; + wasm.unregcert_from_bytes(retptr, ptr0, len0); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + if (r2) { + throw takeObject(r1); + } + return UnregCert.__wrap(r0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @returns {string} + */ + to_json() { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + wasm.regcert_to_json(retptr, this.ptr); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + var r3 = getInt32Memory0()[retptr / 4 + 3]; + var ptr0 = r0; + var len0 = r1; + if (r3) { + ptr0 = 0; + len0 = 0; + throw takeObject(r2); + } + return getStringFromWasm0(ptr0, len0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + wasm.__wbindgen_free(ptr0, len0); + } + } + /** + * @returns {any} + */ + to_js_value() { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + wasm.regcert_to_js_value(retptr, this.ptr); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + if (r2) { + throw takeObject(r1); + } + return takeObject(r0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @param {string} json + * @returns {UnregCert} + */ + static from_json(json) { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + const ptr0 = passStringToWasm0( + json, + wasm.__wbindgen_malloc, + wasm.__wbindgen_realloc, + ); + const len0 = WASM_VECTOR_LEN; + wasm.unregcert_from_json(retptr, ptr0, len0); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + if (r2) { + throw takeObject(r1); + } + return UnregCert.__wrap(r0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @returns {StakeCredential} + */ + stake_credential() { + const ret = wasm.regcert_stake_credential(this.ptr); + return StakeCredential.__wrap(ret); + } + /** + * @returns {BigNum} + */ + coin() { + const ret = wasm.constrplutusdata_alternative(this.ptr); + return BigNum.__wrap(ret); + } + /** + * @param {StakeCredential} stake_credential + * @param {BigNum} coin + * @returns {UnregCert} + */ + static new(stake_credential, coin) { + _assertClass(stake_credential, StakeCredential); + _assertClass(coin, BigNum); + const ret = wasm.regcert_new(stake_credential.ptr, coin.ptr); + return UnregCert.__wrap(ret); + } +} +module.exports.UnregCert = UnregCert; + +const UnregCommitteeHotKeyCertFinalization = new FinalizationRegistry((ptr) => + wasm.__wbg_unregcommitteehotkeycert_free(ptr) +); +/** */ +class UnregCommitteeHotKeyCert { + static __wrap(ptr) { + const obj = Object.create(UnregCommitteeHotKeyCert.prototype); + obj.ptr = ptr; + UnregCommitteeHotKeyCertFinalization.register(obj, obj.ptr, obj); + return obj; + } + + __destroy_into_raw() { + const ptr = this.ptr; + this.ptr = 0; + UnregCommitteeHotKeyCertFinalization.unregister(this); + return ptr; + } + + free() { + const ptr = this.__destroy_into_raw(); + wasm.__wbg_unregcommitteehotkeycert_free(ptr); + } + /** + * @returns {Uint8Array} + */ + to_bytes() { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + wasm.unregcommitteehotkeycert_to_bytes(retptr, this.ptr); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var v0 = getArrayU8FromWasm0(r0, r1).slice(); + wasm.__wbindgen_free(r0, r1 * 1); + return v0; + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @param {Uint8Array} bytes + * @returns {UnregCommitteeHotKeyCert} + */ + static from_bytes(bytes) { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + const ptr0 = passArray8ToWasm0(bytes, wasm.__wbindgen_malloc); + const len0 = WASM_VECTOR_LEN; + wasm.unregcommitteehotkeycert_from_bytes(retptr, ptr0, len0); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + if (r2) { + throw takeObject(r1); + } + return UnregCommitteeHotKeyCert.__wrap(r0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @returns {string} + */ + to_json() { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + wasm.unregcommitteehotkeycert_to_json(retptr, this.ptr); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + var r3 = getInt32Memory0()[retptr / 4 + 3]; + var ptr0 = r0; + var len0 = r1; + if (r3) { + ptr0 = 0; + len0 = 0; + throw takeObject(r2); + } + return getStringFromWasm0(ptr0, len0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + wasm.__wbindgen_free(ptr0, len0); + } + } + /** + * @returns {any} + */ + to_js_value() { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + wasm.unregcommitteehotkeycert_to_js_value(retptr, this.ptr); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + if (r2) { + throw takeObject(r1); + } + return takeObject(r0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @param {string} json + * @returns {UnregCommitteeHotKeyCert} + */ + static from_json(json) { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + const ptr0 = passStringToWasm0( + json, + wasm.__wbindgen_malloc, + wasm.__wbindgen_realloc, + ); + const len0 = WASM_VECTOR_LEN; + wasm.unregcommitteehotkeycert_from_json(retptr, ptr0, len0); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + if (r2) { + throw takeObject(r1); + } + return UnregCommitteeHotKeyCert.__wrap(r0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @returns {Ed25519KeyHash} + */ + committee_cold_keyhash() { + const ret = wasm.regcommitteehotkeycert_committee_cold_keyhash(this.ptr); + return Ed25519KeyHash.__wrap(ret); + } + /** + * @param {Ed25519KeyHash} committee_cold_keyhash + * @returns {UnregCommitteeHotKeyCert} + */ + static new(committee_cold_keyhash) { + _assertClass(committee_cold_keyhash, Ed25519KeyHash); + const ret = wasm.scriptpubkey_new(committee_cold_keyhash.ptr); + return UnregCommitteeHotKeyCert.__wrap(ret); + } +} +module.exports.UnregCommitteeHotKeyCert = UnregCommitteeHotKeyCert; + +const UnregDrepCertFinalization = new FinalizationRegistry((ptr) => + wasm.__wbg_unregdrepcert_free(ptr) +); +/** */ +class UnregDrepCert { + static __wrap(ptr) { + const obj = Object.create(UnregDrepCert.prototype); + obj.ptr = ptr; + UnregDrepCertFinalization.register(obj, obj.ptr, obj); + return obj; + } + + __destroy_into_raw() { + const ptr = this.ptr; + this.ptr = 0; + UnregDrepCertFinalization.unregister(this); + return ptr; + } + + free() { + const ptr = this.__destroy_into_raw(); + wasm.__wbg_unregdrepcert_free(ptr); + } + /** + * @returns {Uint8Array} + */ + to_bytes() { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + wasm.unregdrepcert_to_bytes(retptr, this.ptr); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var v0 = getArrayU8FromWasm0(r0, r1).slice(); + wasm.__wbindgen_free(r0, r1 * 1); + return v0; + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @param {Uint8Array} bytes + * @returns {UnregDrepCert} + */ + static from_bytes(bytes) { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + const ptr0 = passArray8ToWasm0(bytes, wasm.__wbindgen_malloc); + const len0 = WASM_VECTOR_LEN; + wasm.unregdrepcert_from_bytes(retptr, ptr0, len0); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + if (r2) { + throw takeObject(r1); + } + return UnregDrepCert.__wrap(r0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @returns {string} + */ + to_json() { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + wasm.regdrepcert_to_json(retptr, this.ptr); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + var r3 = getInt32Memory0()[retptr / 4 + 3]; + var ptr0 = r0; + var len0 = r1; + if (r3) { + ptr0 = 0; + len0 = 0; + throw takeObject(r2); + } + return getStringFromWasm0(ptr0, len0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + wasm.__wbindgen_free(ptr0, len0); + } + } + /** + * @returns {any} + */ + to_js_value() { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + wasm.regdrepcert_to_js_value(retptr, this.ptr); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + if (r2) { + throw takeObject(r1); + } + return takeObject(r0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @param {string} json + * @returns {UnregDrepCert} + */ + static from_json(json) { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + const ptr0 = passStringToWasm0( + json, + wasm.__wbindgen_malloc, + wasm.__wbindgen_realloc, + ); + const len0 = WASM_VECTOR_LEN; + wasm.unregdrepcert_from_json(retptr, ptr0, len0); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + if (r2) { + throw takeObject(r1); + } + return UnregDrepCert.__wrap(r0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @returns {StakeCredential} + */ + voting_credential() { + const ret = wasm.regcert_stake_credential(this.ptr); + return StakeCredential.__wrap(ret); + } + /** + * @returns {BigNum} + */ + coin() { + const ret = wasm.constrplutusdata_alternative(this.ptr); + return BigNum.__wrap(ret); + } + /** + * @param {StakeCredential} voting_credential + * @param {BigNum} coin + * @returns {UnregDrepCert} + */ + static new(voting_credential, coin) { + _assertClass(voting_credential, StakeCredential); + _assertClass(coin, BigNum); + const ret = wasm.regcert_new(voting_credential.ptr, coin.ptr); + return UnregDrepCert.__wrap(ret); + } +} +module.exports.UnregDrepCert = UnregDrepCert; + +const UpdateFinalization = new FinalizationRegistry((ptr) => + wasm.__wbg_update_free(ptr) +); +/** */ +class Update { + static __wrap(ptr) { + const obj = Object.create(Update.prototype); + obj.ptr = ptr; + UpdateFinalization.register(obj, obj.ptr, obj); + return obj; + } + + __destroy_into_raw() { + const ptr = this.ptr; + this.ptr = 0; + UpdateFinalization.unregister(this); + return ptr; + } + + free() { + const ptr = this.__destroy_into_raw(); + wasm.__wbg_update_free(ptr); + } + /** + * @returns {Uint8Array} + */ + to_bytes() { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + wasm.update_to_bytes(retptr, this.ptr); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var v0 = getArrayU8FromWasm0(r0, r1).slice(); + wasm.__wbindgen_free(r0, r1 * 1); + return v0; + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @param {Uint8Array} bytes + * @returns {Update} + */ + static from_bytes(bytes) { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + const ptr0 = passArray8ToWasm0(bytes, wasm.__wbindgen_malloc); + const len0 = WASM_VECTOR_LEN; + wasm.update_from_bytes(retptr, ptr0, len0); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + if (r2) { + throw takeObject(r1); + } + return Update.__wrap(r0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @returns {string} + */ + to_json() { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + wasm.update_to_json(retptr, this.ptr); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + var r3 = getInt32Memory0()[retptr / 4 + 3]; + var ptr0 = r0; + var len0 = r1; + if (r3) { + ptr0 = 0; + len0 = 0; + throw takeObject(r2); + } + return getStringFromWasm0(ptr0, len0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + wasm.__wbindgen_free(ptr0, len0); + } + } + /** + * @returns {any} + */ + to_js_value() { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + wasm.update_to_js_value(retptr, this.ptr); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + if (r2) { + throw takeObject(r1); + } + return takeObject(r0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @param {string} json + * @returns {Update} + */ + static from_json(json) { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + const ptr0 = passStringToWasm0( + json, + wasm.__wbindgen_malloc, + wasm.__wbindgen_realloc, + ); + const len0 = WASM_VECTOR_LEN; + wasm.update_from_json(retptr, ptr0, len0); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + if (r2) { + throw takeObject(r1); + } + return Update.__wrap(r0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @returns {ProposedProtocolParameterUpdates} + */ + proposed_protocol_parameter_updates() { + const ret = wasm.update_proposed_protocol_parameter_updates(this.ptr); + return ProposedProtocolParameterUpdates.__wrap(ret); + } + /** + * @returns {number} + */ + epoch() { + const ret = wasm.update_epoch(this.ptr); + return ret >>> 0; + } + /** + * @param {ProposedProtocolParameterUpdates} proposed_protocol_parameter_updates + * @param {number} epoch + * @returns {Update} + */ + static new(proposed_protocol_parameter_updates, epoch) { + _assertClass( + proposed_protocol_parameter_updates, + ProposedProtocolParameterUpdates, + ); + const ret = wasm.update_new(proposed_protocol_parameter_updates.ptr, epoch); + return Update.__wrap(ret); + } +} +module.exports.Update = Update; + +const UrlFinalization = new FinalizationRegistry((ptr) => + wasm.__wbg_url_free(ptr) +); +/** */ +class Url { + static __wrap(ptr) { + const obj = Object.create(Url.prototype); + obj.ptr = ptr; + UrlFinalization.register(obj, obj.ptr, obj); + return obj; + } + + __destroy_into_raw() { + const ptr = this.ptr; + this.ptr = 0; + UrlFinalization.unregister(this); + return ptr; + } + + free() { + const ptr = this.__destroy_into_raw(); + wasm.__wbg_url_free(ptr); + } + /** + * @returns {Uint8Array} + */ + to_bytes() { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + wasm.url_to_bytes(retptr, this.ptr); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var v0 = getArrayU8FromWasm0(r0, r1).slice(); + wasm.__wbindgen_free(r0, r1 * 1); + return v0; + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @param {Uint8Array} bytes + * @returns {Url} + */ + static from_bytes(bytes) { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + const ptr0 = passArray8ToWasm0(bytes, wasm.__wbindgen_malloc); + const len0 = WASM_VECTOR_LEN; + wasm.url_from_bytes(retptr, ptr0, len0); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + if (r2) { + throw takeObject(r1); + } + return Url.__wrap(r0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @param {string} url + * @returns {Url} + */ + static new(url) { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + const ptr0 = passStringToWasm0( + url, + wasm.__wbindgen_malloc, + wasm.__wbindgen_realloc, + ); + const len0 = WASM_VECTOR_LEN; + wasm.url_new(retptr, ptr0, len0); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + if (r2) { + throw takeObject(r1); + } + return Url.__wrap(r0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @returns {string} + */ + url() { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + wasm.blockfrost_url(retptr, this.ptr); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + return getStringFromWasm0(r0, r1); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + wasm.__wbindgen_free(r0, r1); + } + } +} +module.exports.Url = Url; + +const VRFCertFinalization = new FinalizationRegistry((ptr) => + wasm.__wbg_vrfcert_free(ptr) +); +/** */ +class VRFCert { + static __wrap(ptr) { + const obj = Object.create(VRFCert.prototype); + obj.ptr = ptr; + VRFCertFinalization.register(obj, obj.ptr, obj); + return obj; + } + + __destroy_into_raw() { + const ptr = this.ptr; + this.ptr = 0; + VRFCertFinalization.unregister(this); + return ptr; + } + + free() { + const ptr = this.__destroy_into_raw(); + wasm.__wbg_vrfcert_free(ptr); + } + /** + * @returns {Uint8Array} + */ + to_bytes() { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + wasm.vrfcert_to_bytes(retptr, this.ptr); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var v0 = getArrayU8FromWasm0(r0, r1).slice(); + wasm.__wbindgen_free(r0, r1 * 1); + return v0; + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @param {Uint8Array} bytes + * @returns {VRFCert} + */ + static from_bytes(bytes) { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + const ptr0 = passArray8ToWasm0(bytes, wasm.__wbindgen_malloc); + const len0 = WASM_VECTOR_LEN; + wasm.vrfcert_from_bytes(retptr, ptr0, len0); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + if (r2) { + throw takeObject(r1); + } + return VRFCert.__wrap(r0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @returns {string} + */ + to_json() { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + wasm.vrfcert_to_json(retptr, this.ptr); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + var r3 = getInt32Memory0()[retptr / 4 + 3]; + var ptr0 = r0; + var len0 = r1; + if (r3) { + ptr0 = 0; + len0 = 0; + throw takeObject(r2); + } + return getStringFromWasm0(ptr0, len0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + wasm.__wbindgen_free(ptr0, len0); + } + } + /** + * @returns {any} + */ + to_js_value() { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + wasm.vrfcert_to_js_value(retptr, this.ptr); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + if (r2) { + throw takeObject(r1); + } + return takeObject(r0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @param {string} json + * @returns {VRFCert} + */ + static from_json(json) { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + const ptr0 = passStringToWasm0( + json, + wasm.__wbindgen_malloc, + wasm.__wbindgen_realloc, + ); + const len0 = WASM_VECTOR_LEN; + wasm.vrfcert_from_json(retptr, ptr0, len0); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + if (r2) { + throw takeObject(r1); + } + return VRFCert.__wrap(r0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @returns {Uint8Array} + */ + output() { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + wasm.assetname_name(retptr, this.ptr); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var v0 = getArrayU8FromWasm0(r0, r1).slice(); + wasm.__wbindgen_free(r0, r1 * 1); + return v0; + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @returns {Uint8Array} + */ + proof() { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + wasm.bootstrapwitness_attributes(retptr, this.ptr); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var v0 = getArrayU8FromWasm0(r0, r1).slice(); + wasm.__wbindgen_free(r0, r1 * 1); + return v0; + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @param {Uint8Array} output + * @param {Uint8Array} proof + * @returns {VRFCert} + */ + static new(output, proof) { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + const ptr0 = passArray8ToWasm0(output, wasm.__wbindgen_malloc); + const len0 = WASM_VECTOR_LEN; + const ptr1 = passArray8ToWasm0(proof, wasm.__wbindgen_malloc); + const len1 = WASM_VECTOR_LEN; + wasm.vrfcert_new(retptr, ptr0, len0, ptr1, len1); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + if (r2) { + throw takeObject(r1); + } + return VRFCert.__wrap(r0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } +} +module.exports.VRFCert = VRFCert; + +const VRFKeyHashFinalization = new FinalizationRegistry((ptr) => + wasm.__wbg_vrfkeyhash_free(ptr) +); +/** */ +class VRFKeyHash { + static __wrap(ptr) { + const obj = Object.create(VRFKeyHash.prototype); + obj.ptr = ptr; + VRFKeyHashFinalization.register(obj, obj.ptr, obj); + return obj; + } + + __destroy_into_raw() { + const ptr = this.ptr; + this.ptr = 0; + VRFKeyHashFinalization.unregister(this); + return ptr; + } + + free() { + const ptr = this.__destroy_into_raw(); + wasm.__wbg_vrfkeyhash_free(ptr); + } + /** + * @param {Uint8Array} bytes + * @returns {VRFKeyHash} + */ + static from_bytes(bytes) { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + const ptr0 = passArray8ToWasm0(bytes, wasm.__wbindgen_malloc); + const len0 = WASM_VECTOR_LEN; + wasm.vrfkeyhash_from_bytes(retptr, ptr0, len0); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + if (r2) { + throw takeObject(r1); + } + return VRFKeyHash.__wrap(r0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @returns {Uint8Array} + */ + to_bytes() { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + wasm.auxiliarydatahash_to_bytes(retptr, this.ptr); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var v0 = getArrayU8FromWasm0(r0, r1).slice(); + wasm.__wbindgen_free(r0, r1 * 1); + return v0; + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @param {string} prefix + * @returns {string} + */ + to_bech32(prefix) { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + const ptr0 = passStringToWasm0( + prefix, + wasm.__wbindgen_malloc, + wasm.__wbindgen_realloc, + ); + const len0 = WASM_VECTOR_LEN; + wasm.auxiliarydatahash_to_bech32(retptr, this.ptr, ptr0, len0); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + var r3 = getInt32Memory0()[retptr / 4 + 3]; + var ptr1 = r0; + var len1 = r1; + if (r3) { + ptr1 = 0; + len1 = 0; + throw takeObject(r2); + } + return getStringFromWasm0(ptr1, len1); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + wasm.__wbindgen_free(ptr1, len1); + } + } + /** + * @param {string} bech_str + * @returns {VRFKeyHash} + */ + static from_bech32(bech_str) { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + const ptr0 = passStringToWasm0( + bech_str, + wasm.__wbindgen_malloc, + wasm.__wbindgen_realloc, + ); + const len0 = WASM_VECTOR_LEN; + wasm.vrfkeyhash_from_bech32(retptr, ptr0, len0); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + if (r2) { + throw takeObject(r1); + } + return VRFKeyHash.__wrap(r0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @returns {string} + */ + to_hex() { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + wasm.auxiliarydatahash_to_hex(retptr, this.ptr); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + return getStringFromWasm0(r0, r1); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + wasm.__wbindgen_free(r0, r1); + } + } + /** + * @param {string} hex + * @returns {VRFKeyHash} + */ + static from_hex(hex) { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + const ptr0 = passStringToWasm0( + hex, + wasm.__wbindgen_malloc, + wasm.__wbindgen_realloc, + ); + const len0 = WASM_VECTOR_LEN; + wasm.vrfkeyhash_from_hex(retptr, ptr0, len0); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + if (r2) { + throw takeObject(r1); + } + return VRFKeyHash.__wrap(r0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } +} +module.exports.VRFKeyHash = VRFKeyHash; + +const VRFVKeyFinalization = new FinalizationRegistry((ptr) => + wasm.__wbg_vrfvkey_free(ptr) +); +/** */ +class VRFVKey { + static __wrap(ptr) { + const obj = Object.create(VRFVKey.prototype); + obj.ptr = ptr; + VRFVKeyFinalization.register(obj, obj.ptr, obj); + return obj; + } + + __destroy_into_raw() { + const ptr = this.ptr; + this.ptr = 0; + VRFVKeyFinalization.unregister(this); + return ptr; + } + + free() { + const ptr = this.__destroy_into_raw(); + wasm.__wbg_vrfvkey_free(ptr); + } + /** + * @returns {Uint8Array} + */ + to_bytes() { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + wasm.vrfvkey_to_bytes(retptr, this.ptr); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var v0 = getArrayU8FromWasm0(r0, r1).slice(); + wasm.__wbindgen_free(r0, r1 * 1); + return v0; + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @param {Uint8Array} bytes + * @returns {VRFVKey} + */ + static from_bytes(bytes) { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + const ptr0 = passArray8ToWasm0(bytes, wasm.__wbindgen_malloc); + const len0 = WASM_VECTOR_LEN; + wasm.plutusscript_from_bytes(retptr, ptr0, len0); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + if (r2) { + throw takeObject(r1); + } + return VRFVKey.__wrap(r0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @returns {VRFKeyHash} + */ + hash() { + const ret = wasm.vrfvkey_hash(this.ptr); + return VRFKeyHash.__wrap(ret); + } + /** + * @returns {Uint8Array} + */ + to_raw_key() { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + wasm.assetname_name(retptr, this.ptr); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var v0 = getArrayU8FromWasm0(r0, r1).slice(); + wasm.__wbindgen_free(r0, r1 * 1); + return v0; + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } +} +module.exports.VRFVKey = VRFVKey; + +const ValueFinalization = new FinalizationRegistry((ptr) => + wasm.__wbg_value_free(ptr) +); +/** */ +class Value { + static __wrap(ptr) { + const obj = Object.create(Value.prototype); + obj.ptr = ptr; + ValueFinalization.register(obj, obj.ptr, obj); + return obj; + } + + __destroy_into_raw() { + const ptr = this.ptr; + this.ptr = 0; + ValueFinalization.unregister(this); + return ptr; + } + + free() { + const ptr = this.__destroy_into_raw(); + wasm.__wbg_value_free(ptr); + } + /** + * @returns {Uint8Array} + */ + to_bytes() { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + wasm.value_to_bytes(retptr, this.ptr); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var v0 = getArrayU8FromWasm0(r0, r1).slice(); + wasm.__wbindgen_free(r0, r1 * 1); + return v0; + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @param {Uint8Array} bytes + * @returns {Value} + */ + static from_bytes(bytes) { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + const ptr0 = passArray8ToWasm0(bytes, wasm.__wbindgen_malloc); + const len0 = WASM_VECTOR_LEN; + wasm.value_from_bytes(retptr, ptr0, len0); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + if (r2) { + throw takeObject(r1); + } + return Value.__wrap(r0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @returns {string} + */ + to_json() { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + wasm.value_to_json(retptr, this.ptr); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + var r3 = getInt32Memory0()[retptr / 4 + 3]; + var ptr0 = r0; + var len0 = r1; + if (r3) { + ptr0 = 0; + len0 = 0; + throw takeObject(r2); + } + return getStringFromWasm0(ptr0, len0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + wasm.__wbindgen_free(ptr0, len0); + } + } + /** + * @returns {any} + */ + to_js_value() { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + wasm.value_to_js_value(retptr, this.ptr); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + if (r2) { + throw takeObject(r1); + } + return takeObject(r0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @param {string} json + * @returns {Value} + */ + static from_json(json) { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + const ptr0 = passStringToWasm0( + json, + wasm.__wbindgen_malloc, + wasm.__wbindgen_realloc, + ); + const len0 = WASM_VECTOR_LEN; + wasm.value_from_json(retptr, ptr0, len0); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + if (r2) { + throw takeObject(r1); + } + return Value.__wrap(r0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @param {BigNum} coin + * @returns {Value} + */ + static new(coin) { + _assertClass(coin, BigNum); + const ret = wasm.value_new(coin.ptr); + return Value.__wrap(ret); + } + /** + * @param {MultiAsset} multiasset + * @returns {Value} + */ + static new_from_assets(multiasset) { + _assertClass(multiasset, MultiAsset); + const ret = wasm.value_new_from_assets(multiasset.ptr); + return Value.__wrap(ret); + } + /** + * @returns {Value} + */ + static zero() { + const ret = wasm.value_zero(); + return Value.__wrap(ret); + } + /** + * @returns {boolean} + */ + is_zero() { + const ret = wasm.value_is_zero(this.ptr); + return ret !== 0; + } + /** + * @returns {BigNum} + */ + coin() { + const ret = wasm.value_coin(this.ptr); + return BigNum.__wrap(ret); + } + /** + * @param {BigNum} coin + */ + set_coin(coin) { + _assertClass(coin, BigNum); + wasm.value_set_coin(this.ptr, coin.ptr); + } + /** + * @returns {MultiAsset | undefined} + */ + multiasset() { + const ret = wasm.value_multiasset(this.ptr); + return ret === 0 ? undefined : MultiAsset.__wrap(ret); + } + /** + * @param {MultiAsset} multiasset + */ + set_multiasset(multiasset) { + _assertClass(multiasset, MultiAsset); + wasm.value_set_multiasset(this.ptr, multiasset.ptr); + } + /** + * @param {Value} rhs + * @returns {Value} + */ + checked_add(rhs) { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + _assertClass(rhs, Value); + wasm.value_checked_add(retptr, this.ptr, rhs.ptr); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + if (r2) { + throw takeObject(r1); + } + return Value.__wrap(r0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @param {Value} rhs_value + * @returns {Value} + */ + checked_sub(rhs_value) { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + _assertClass(rhs_value, Value); + wasm.value_checked_sub(retptr, this.ptr, rhs_value.ptr); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + if (r2) { + throw takeObject(r1); + } + return Value.__wrap(r0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @param {Value} rhs_value + * @returns {Value} + */ + clamped_sub(rhs_value) { + _assertClass(rhs_value, Value); + const ret = wasm.value_clamped_sub(this.ptr, rhs_value.ptr); + return Value.__wrap(ret); + } + /** + * note: values are only partially comparable + * @param {Value} rhs_value + * @returns {number | undefined} + */ + compare(rhs_value) { + _assertClass(rhs_value, Value); + const ret = wasm.value_compare(this.ptr, rhs_value.ptr); + return ret === 0xFFFFFF ? undefined : ret; + } +} +module.exports.Value = Value; + +const VkeyFinalization = new FinalizationRegistry((ptr) => + wasm.__wbg_vkey_free(ptr) +); +/** */ +class Vkey { + static __wrap(ptr) { + const obj = Object.create(Vkey.prototype); + obj.ptr = ptr; + VkeyFinalization.register(obj, obj.ptr, obj); + return obj; + } + + __destroy_into_raw() { + const ptr = this.ptr; + this.ptr = 0; + VkeyFinalization.unregister(this); + return ptr; + } + + free() { + const ptr = this.__destroy_into_raw(); + wasm.__wbg_vkey_free(ptr); + } + /** + * @returns {Uint8Array} + */ + to_bytes() { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + wasm.vkey_to_bytes(retptr, this.ptr); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var v0 = getArrayU8FromWasm0(r0, r1).slice(); + wasm.__wbindgen_free(r0, r1 * 1); + return v0; + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @param {Uint8Array} bytes + * @returns {Vkey} + */ + static from_bytes(bytes) { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + const ptr0 = passArray8ToWasm0(bytes, wasm.__wbindgen_malloc); + const len0 = WASM_VECTOR_LEN; + wasm.vkey_from_bytes(retptr, ptr0, len0); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + if (r2) { + throw takeObject(r1); + } + return Vkey.__wrap(r0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @param {PublicKey} pk + * @returns {Vkey} + */ + static new(pk) { + _assertClass(pk, PublicKey); + const ret = wasm.vkey_new(pk.ptr); + return Vkey.__wrap(ret); + } + /** + * @returns {PublicKey} + */ + public_key() { + const ret = wasm.vkey_public_key(this.ptr); + return PublicKey.__wrap(ret); + } +} +module.exports.Vkey = Vkey; + +const VkeysFinalization = new FinalizationRegistry((ptr) => + wasm.__wbg_vkeys_free(ptr) +); +/** */ +class Vkeys { + static __wrap(ptr) { + const obj = Object.create(Vkeys.prototype); + obj.ptr = ptr; + VkeysFinalization.register(obj, obj.ptr, obj); + return obj; + } + + __destroy_into_raw() { + const ptr = this.ptr; + this.ptr = 0; + VkeysFinalization.unregister(this); + return ptr; + } + + free() { + const ptr = this.__destroy_into_raw(); + wasm.__wbg_vkeys_free(ptr); + } + /** + * @returns {Vkeys} + */ + static new() { + const ret = wasm.ed25519keyhashes_new(); + return Vkeys.__wrap(ret); + } + /** + * @returns {number} + */ + len() { + const ret = wasm.assetnames_len(this.ptr); + return ret >>> 0; + } + /** + * @param {number} index + * @returns {Vkey} + */ + get(index) { + const ret = wasm.vkeys_get(this.ptr, index); + return Vkey.__wrap(ret); + } + /** + * @param {Vkey} elem + */ + add(elem) { + _assertClass(elem, Vkey); + wasm.vkeys_add(this.ptr, elem.ptr); + } +} +module.exports.Vkeys = Vkeys; + +const VkeywitnessFinalization = new FinalizationRegistry((ptr) => + wasm.__wbg_vkeywitness_free(ptr) +); +/** */ +class Vkeywitness { + static __wrap(ptr) { + const obj = Object.create(Vkeywitness.prototype); + obj.ptr = ptr; + VkeywitnessFinalization.register(obj, obj.ptr, obj); + return obj; + } + + __destroy_into_raw() { + const ptr = this.ptr; + this.ptr = 0; + VkeywitnessFinalization.unregister(this); + return ptr; + } + + free() { + const ptr = this.__destroy_into_raw(); + wasm.__wbg_vkeywitness_free(ptr); + } + /** + * @returns {Uint8Array} + */ + to_bytes() { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + wasm.vkeywitness_to_bytes(retptr, this.ptr); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var v0 = getArrayU8FromWasm0(r0, r1).slice(); + wasm.__wbindgen_free(r0, r1 * 1); + return v0; + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @param {Uint8Array} bytes + * @returns {Vkeywitness} + */ + static from_bytes(bytes) { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + const ptr0 = passArray8ToWasm0(bytes, wasm.__wbindgen_malloc); + const len0 = WASM_VECTOR_LEN; + wasm.vkeywitness_from_bytes(retptr, ptr0, len0); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + if (r2) { + throw takeObject(r1); + } + return Vkeywitness.__wrap(r0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @returns {string} + */ + to_json() { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + wasm.vkeywitness_to_json(retptr, this.ptr); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + var r3 = getInt32Memory0()[retptr / 4 + 3]; + var ptr0 = r0; + var len0 = r1; + if (r3) { + ptr0 = 0; + len0 = 0; + throw takeObject(r2); + } + return getStringFromWasm0(ptr0, len0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + wasm.__wbindgen_free(ptr0, len0); + } + } + /** + * @returns {any} + */ + to_js_value() { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + wasm.vkeywitness_to_js_value(retptr, this.ptr); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + if (r2) { + throw takeObject(r1); + } + return takeObject(r0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @param {string} json + * @returns {Vkeywitness} + */ + static from_json(json) { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + const ptr0 = passStringToWasm0( + json, + wasm.__wbindgen_malloc, + wasm.__wbindgen_realloc, + ); + const len0 = WASM_VECTOR_LEN; + wasm.vkeywitness_from_json(retptr, ptr0, len0); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + if (r2) { + throw takeObject(r1); + } + return Vkeywitness.__wrap(r0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @param {Vkey} vkey + * @param {Ed25519Signature} signature + * @returns {Vkeywitness} + */ + static new(vkey, signature) { + _assertClass(vkey, Vkey); + _assertClass(signature, Ed25519Signature); + const ret = wasm.vkeywitness_new(vkey.ptr, signature.ptr); + return Vkeywitness.__wrap(ret); + } + /** + * @returns {Vkey} + */ + vkey() { + const ret = wasm.vkeywitness_vkey(this.ptr); + return Vkey.__wrap(ret); + } + /** + * @returns {Ed25519Signature} + */ + signature() { + const ret = wasm.vkeywitness_signature(this.ptr); + return Ed25519Signature.__wrap(ret); + } +} +module.exports.Vkeywitness = Vkeywitness; + +const VkeywitnessesFinalization = new FinalizationRegistry((ptr) => + wasm.__wbg_vkeywitnesses_free(ptr) +); +/** */ +class Vkeywitnesses { + static __wrap(ptr) { + const obj = Object.create(Vkeywitnesses.prototype); + obj.ptr = ptr; + VkeywitnessesFinalization.register(obj, obj.ptr, obj); + return obj; + } + + __destroy_into_raw() { + const ptr = this.ptr; + this.ptr = 0; + VkeywitnessesFinalization.unregister(this); + return ptr; + } + + free() { + const ptr = this.__destroy_into_raw(); + wasm.__wbg_vkeywitnesses_free(ptr); + } + /** + * @returns {Vkeywitnesses} + */ + static new() { + const ret = wasm.ed25519keyhashes_new(); + return Vkeywitnesses.__wrap(ret); + } + /** + * @returns {number} + */ + len() { + const ret = wasm.assetnames_len(this.ptr); + return ret >>> 0; + } + /** + * @param {number} index + * @returns {Vkeywitness} + */ + get(index) { + const ret = wasm.vkeywitnesses_get(this.ptr, index); + return Vkeywitness.__wrap(ret); + } + /** + * @param {Vkeywitness} elem + */ + add(elem) { + _assertClass(elem, Vkeywitness); + wasm.vkeywitnesses_add(this.ptr, elem.ptr); + } +} +module.exports.Vkeywitnesses = Vkeywitnesses; + +const VoteFinalization = new FinalizationRegistry((ptr) => + wasm.__wbg_vote_free(ptr) +); +/** */ +class Vote { + static __wrap(ptr) { + const obj = Object.create(Vote.prototype); + obj.ptr = ptr; + VoteFinalization.register(obj, obj.ptr, obj); + return obj; + } + + __destroy_into_raw() { + const ptr = this.ptr; + this.ptr = 0; + VoteFinalization.unregister(this); + return ptr; + } + + free() { + const ptr = this.__destroy_into_raw(); + wasm.__wbg_vote_free(ptr); + } + /** + * @returns {Uint8Array} + */ + to_bytes() { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + wasm.vote_to_bytes(retptr, this.ptr); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var v0 = getArrayU8FromWasm0(r0, r1).slice(); + wasm.__wbindgen_free(r0, r1 * 1); + return v0; + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @param {Uint8Array} bytes + * @returns {Vote} + */ + static from_bytes(bytes) { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + const ptr0 = passArray8ToWasm0(bytes, wasm.__wbindgen_malloc); + const len0 = WASM_VECTOR_LEN; + wasm.vote_from_bytes(retptr, ptr0, len0); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + if (r2) { + throw takeObject(r1); + } + return Vote.__wrap(r0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @returns {string} + */ + to_json() { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + wasm.vote_to_json(retptr, this.ptr); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + var r3 = getInt32Memory0()[retptr / 4 + 3]; + var ptr0 = r0; + var len0 = r1; + if (r3) { + ptr0 = 0; + len0 = 0; + throw takeObject(r2); + } + return getStringFromWasm0(ptr0, len0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + wasm.__wbindgen_free(ptr0, len0); + } + } + /** + * @returns {any} + */ + to_js_value() { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + wasm.vote_to_js_value(retptr, this.ptr); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + if (r2) { + throw takeObject(r1); + } + return takeObject(r0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @param {string} json + * @returns {Vote} + */ + static from_json(json) { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + const ptr0 = passStringToWasm0( + json, + wasm.__wbindgen_malloc, + wasm.__wbindgen_realloc, + ); + const len0 = WASM_VECTOR_LEN; + wasm.vote_from_json(retptr, ptr0, len0); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + if (r2) { + throw takeObject(r1); + } + return Vote.__wrap(r0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @returns {Vote} + */ + static new_no() { + const ret = wasm.language_new_plutus_v1(); + return Vote.__wrap(ret); + } + /** + * @returns {Vote} + */ + static new_yes() { + const ret = wasm.language_new_plutus_v2(); + return Vote.__wrap(ret); + } + /** + * @returns {Vote} + */ + static new_abstain() { + const ret = wasm.language_new_plutus_v3(); + return Vote.__wrap(ret); + } + /** + * @returns {number} + */ + kind() { + const ret = wasm.vote_kind(this.ptr); + return ret >>> 0; + } +} +module.exports.Vote = Vote; + +const VoteDelegCertFinalization = new FinalizationRegistry((ptr) => + wasm.__wbg_votedelegcert_free(ptr) +); +/** */ +class VoteDelegCert { + static __wrap(ptr) { + const obj = Object.create(VoteDelegCert.prototype); + obj.ptr = ptr; + VoteDelegCertFinalization.register(obj, obj.ptr, obj); + return obj; + } + + __destroy_into_raw() { + const ptr = this.ptr; + this.ptr = 0; + VoteDelegCertFinalization.unregister(this); + return ptr; + } + + free() { + const ptr = this.__destroy_into_raw(); + wasm.__wbg_votedelegcert_free(ptr); + } + /** + * @returns {Uint8Array} + */ + to_bytes() { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + wasm.votedelegcert_to_bytes(retptr, this.ptr); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var v0 = getArrayU8FromWasm0(r0, r1).slice(); + wasm.__wbindgen_free(r0, r1 * 1); + return v0; + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @param {Uint8Array} bytes + * @returns {VoteDelegCert} + */ + static from_bytes(bytes) { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + const ptr0 = passArray8ToWasm0(bytes, wasm.__wbindgen_malloc); + const len0 = WASM_VECTOR_LEN; + wasm.votedelegcert_from_bytes(retptr, ptr0, len0); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + if (r2) { + throw takeObject(r1); + } + return VoteDelegCert.__wrap(r0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @returns {string} + */ + to_json() { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + wasm.votedelegcert_to_json(retptr, this.ptr); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + var r3 = getInt32Memory0()[retptr / 4 + 3]; + var ptr0 = r0; + var len0 = r1; + if (r3) { + ptr0 = 0; + len0 = 0; + throw takeObject(r2); + } + return getStringFromWasm0(ptr0, len0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + wasm.__wbindgen_free(ptr0, len0); + } + } + /** + * @returns {any} + */ + to_js_value() { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + wasm.votedelegcert_to_js_value(retptr, this.ptr); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + if (r2) { + throw takeObject(r1); + } + return takeObject(r0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @param {string} json + * @returns {VoteDelegCert} + */ + static from_json(json) { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + const ptr0 = passStringToWasm0( + json, + wasm.__wbindgen_malloc, + wasm.__wbindgen_realloc, + ); + const len0 = WASM_VECTOR_LEN; + wasm.votedelegcert_from_json(retptr, ptr0, len0); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + if (r2) { + throw takeObject(r1); + } + return VoteDelegCert.__wrap(r0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @returns {StakeCredential} + */ + stake_credential() { + const ret = wasm.baseaddress_payment_cred(this.ptr); + return StakeCredential.__wrap(ret); + } + /** + * @returns {Drep} + */ + drep() { + const ret = wasm.stakevotedelegcert_drep(this.ptr); + return Drep.__wrap(ret); + } + /** + * @param {StakeCredential} stake_credential + * @param {Drep} drep + * @returns {VoteDelegCert} + */ + static new(stake_credential, drep) { + _assertClass(stake_credential, StakeCredential); + _assertClass(drep, Drep); + const ret = wasm.votedelegcert_new(stake_credential.ptr, drep.ptr); + return VoteDelegCert.__wrap(ret); + } +} +module.exports.VoteDelegCert = VoteDelegCert; + +const VoteRegDelegCertFinalization = new FinalizationRegistry((ptr) => + wasm.__wbg_voteregdelegcert_free(ptr) +); +/** */ +class VoteRegDelegCert { + static __wrap(ptr) { + const obj = Object.create(VoteRegDelegCert.prototype); + obj.ptr = ptr; + VoteRegDelegCertFinalization.register(obj, obj.ptr, obj); + return obj; + } + + __destroy_into_raw() { + const ptr = this.ptr; + this.ptr = 0; + VoteRegDelegCertFinalization.unregister(this); + return ptr; + } + + free() { + const ptr = this.__destroy_into_raw(); + wasm.__wbg_voteregdelegcert_free(ptr); + } + /** + * @returns {Uint8Array} + */ + to_bytes() { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + wasm.voteregdelegcert_to_bytes(retptr, this.ptr); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var v0 = getArrayU8FromWasm0(r0, r1).slice(); + wasm.__wbindgen_free(r0, r1 * 1); + return v0; + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @param {Uint8Array} bytes + * @returns {VoteRegDelegCert} + */ + static from_bytes(bytes) { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + const ptr0 = passArray8ToWasm0(bytes, wasm.__wbindgen_malloc); + const len0 = WASM_VECTOR_LEN; + wasm.voteregdelegcert_from_bytes(retptr, ptr0, len0); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + if (r2) { + throw takeObject(r1); + } + return VoteRegDelegCert.__wrap(r0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @returns {string} + */ + to_json() { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + wasm.voteregdelegcert_to_json(retptr, this.ptr); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + var r3 = getInt32Memory0()[retptr / 4 + 3]; + var ptr0 = r0; + var len0 = r1; + if (r3) { + ptr0 = 0; + len0 = 0; + throw takeObject(r2); + } + return getStringFromWasm0(ptr0, len0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + wasm.__wbindgen_free(ptr0, len0); + } + } + /** + * @returns {any} + */ + to_js_value() { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + wasm.voteregdelegcert_to_js_value(retptr, this.ptr); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + if (r2) { + throw takeObject(r1); + } + return takeObject(r0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @param {string} json + * @returns {VoteRegDelegCert} + */ + static from_json(json) { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + const ptr0 = passStringToWasm0( + json, + wasm.__wbindgen_malloc, + wasm.__wbindgen_realloc, + ); + const len0 = WASM_VECTOR_LEN; + wasm.voteregdelegcert_from_json(retptr, ptr0, len0); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + if (r2) { + throw takeObject(r1); + } + return VoteRegDelegCert.__wrap(r0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @returns {StakeCredential} + */ + stake_credential() { + const ret = wasm.regcert_stake_credential(this.ptr); + return StakeCredential.__wrap(ret); + } + /** + * @returns {Drep} + */ + drep() { + const ret = wasm.voteregdelegcert_drep(this.ptr); + return Drep.__wrap(ret); + } + /** + * @returns {BigNum} + */ + coin() { + const ret = wasm.constrplutusdata_alternative(this.ptr); + return BigNum.__wrap(ret); + } + /** + * @param {StakeCredential} stake_credential + * @param {Drep} drep + * @param {BigNum} coin + * @returns {VoteRegDelegCert} + */ + static new(stake_credential, drep, coin) { + _assertClass(stake_credential, StakeCredential); + _assertClass(drep, Drep); + _assertClass(coin, BigNum); + const ret = wasm.voteregdelegcert_new( + stake_credential.ptr, + drep.ptr, + coin.ptr, + ); + return VoteRegDelegCert.__wrap(ret); + } +} +module.exports.VoteRegDelegCert = VoteRegDelegCert; + +const VoterFinalization = new FinalizationRegistry((ptr) => + wasm.__wbg_voter_free(ptr) +); +/** */ +class Voter { + static __wrap(ptr) { + const obj = Object.create(Voter.prototype); + obj.ptr = ptr; + VoterFinalization.register(obj, obj.ptr, obj); + return obj; + } + + __destroy_into_raw() { + const ptr = this.ptr; + this.ptr = 0; + VoterFinalization.unregister(this); + return ptr; + } + + free() { + const ptr = this.__destroy_into_raw(); + wasm.__wbg_voter_free(ptr); + } + /** + * @returns {Uint8Array} + */ + to_bytes() { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + wasm.voter_to_bytes(retptr, this.ptr); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var v0 = getArrayU8FromWasm0(r0, r1).slice(); + wasm.__wbindgen_free(r0, r1 * 1); + return v0; + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @param {Uint8Array} bytes + * @returns {Voter} + */ + static from_bytes(bytes) { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + const ptr0 = passArray8ToWasm0(bytes, wasm.__wbindgen_malloc); + const len0 = WASM_VECTOR_LEN; + wasm.voter_from_bytes(retptr, ptr0, len0); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + if (r2) { + throw takeObject(r1); + } + return Voter.__wrap(r0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @returns {string} + */ + to_json() { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + wasm.voter_to_json(retptr, this.ptr); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + var r3 = getInt32Memory0()[retptr / 4 + 3]; + var ptr0 = r0; + var len0 = r1; + if (r3) { + ptr0 = 0; + len0 = 0; + throw takeObject(r2); + } + return getStringFromWasm0(ptr0, len0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + wasm.__wbindgen_free(ptr0, len0); + } + } + /** + * @returns {any} + */ + to_js_value() { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + wasm.voter_to_js_value(retptr, this.ptr); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + if (r2) { + throw takeObject(r1); + } + return takeObject(r0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @param {string} json + * @returns {Voter} + */ + static from_json(json) { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + const ptr0 = passStringToWasm0( + json, + wasm.__wbindgen_malloc, + wasm.__wbindgen_realloc, + ); + const len0 = WASM_VECTOR_LEN; + wasm.voter_from_json(retptr, ptr0, len0); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + if (r2) { + throw takeObject(r1); + } + return Voter.__wrap(r0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @param {Ed25519KeyHash} keyhash + * @returns {Voter} + */ + static new_committee_hot_keyhash(keyhash) { + _assertClass(keyhash, Ed25519KeyHash); + const ret = wasm.drep_new_keyhash(keyhash.ptr); + return Voter.__wrap(ret); + } + /** + * @param {ScriptHash} scripthash + * @returns {Voter} + */ + static new_committee_hot_scripthash(scripthash) { + _assertClass(scripthash, ScriptHash); + const ret = wasm.drep_new_scripthash(scripthash.ptr); + return Voter.__wrap(ret); + } + /** + * @param {Ed25519KeyHash} keyhash + * @returns {Voter} + */ + static new_drep_keyhash(keyhash) { + _assertClass(keyhash, Ed25519KeyHash); + const ret = wasm.voter_new_drep_keyhash(keyhash.ptr); + return Voter.__wrap(ret); + } + /** + * @param {ScriptHash} scripthash + * @returns {Voter} + */ + static new_drep_scripthash(scripthash) { + _assertClass(scripthash, ScriptHash); + const ret = wasm.voter_new_drep_scripthash(scripthash.ptr); + return Voter.__wrap(ret); + } + /** + * @param {Ed25519KeyHash} keyhash + * @returns {Voter} + */ + static new_staking_pool_keyhash(keyhash) { + _assertClass(keyhash, Ed25519KeyHash); + const ret = wasm.voter_new_staking_pool_keyhash(keyhash.ptr); + return Voter.__wrap(ret); + } + /** + * @returns {number} + */ + kind() { + const ret = wasm.voter_kind(this.ptr); + return ret >>> 0; + } + /** + * @returns {Ed25519KeyHash | undefined} + */ + as_committee_hot_keyhash() { + const ret = wasm.voter_as_committee_hot_keyhash(this.ptr); + return ret === 0 ? undefined : Ed25519KeyHash.__wrap(ret); + } + /** + * @returns {ScriptHash | undefined} + */ + as_committee_hot_scripthash() { + const ret = wasm.voter_as_committee_hot_scripthash(this.ptr); + return ret === 0 ? undefined : ScriptHash.__wrap(ret); + } + /** + * @returns {Ed25519KeyHash | undefined} + */ + as_drep_keyhash() { + const ret = wasm.voter_as_drep_keyhash(this.ptr); + return ret === 0 ? undefined : Ed25519KeyHash.__wrap(ret); + } + /** + * @returns {ScriptHash | undefined} + */ + as_drep_scripthash() { + const ret = wasm.voter_as_drep_scripthash(this.ptr); + return ret === 0 ? undefined : ScriptHash.__wrap(ret); + } + /** + * @returns {Ed25519KeyHash | undefined} + */ + as_staking_pool_keyhash() { + const ret = wasm.voter_as_staking_pool_keyhash(this.ptr); + return ret === 0 ? undefined : Ed25519KeyHash.__wrap(ret); + } +} +module.exports.Voter = Voter; + +const VotingProcedureFinalization = new FinalizationRegistry((ptr) => + wasm.__wbg_votingprocedure_free(ptr) +); +/** */ +class VotingProcedure { + static __wrap(ptr) { + const obj = Object.create(VotingProcedure.prototype); + obj.ptr = ptr; + VotingProcedureFinalization.register(obj, obj.ptr, obj); + return obj; + } + + __destroy_into_raw() { + const ptr = this.ptr; + this.ptr = 0; + VotingProcedureFinalization.unregister(this); + return ptr; + } + + free() { + const ptr = this.__destroy_into_raw(); + wasm.__wbg_votingprocedure_free(ptr); + } + /** + * @returns {Uint8Array} + */ + to_bytes() { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + wasm.votingprocedure_to_bytes(retptr, this.ptr); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var v0 = getArrayU8FromWasm0(r0, r1).slice(); + wasm.__wbindgen_free(r0, r1 * 1); + return v0; + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @param {Uint8Array} bytes + * @returns {VotingProcedure} + */ + static from_bytes(bytes) { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + const ptr0 = passArray8ToWasm0(bytes, wasm.__wbindgen_malloc); + const len0 = WASM_VECTOR_LEN; + wasm.votingprocedure_from_bytes(retptr, ptr0, len0); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + if (r2) { + throw takeObject(r1); + } + return VotingProcedure.__wrap(r0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @returns {string} + */ + to_json() { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + wasm.votingprocedure_to_json(retptr, this.ptr); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + var r3 = getInt32Memory0()[retptr / 4 + 3]; + var ptr0 = r0; + var len0 = r1; + if (r3) { + ptr0 = 0; + len0 = 0; + throw takeObject(r2); + } + return getStringFromWasm0(ptr0, len0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + wasm.__wbindgen_free(ptr0, len0); + } + } + /** + * @returns {any} + */ + to_js_value() { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + wasm.votingprocedure_to_js_value(retptr, this.ptr); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + if (r2) { + throw takeObject(r1); + } + return takeObject(r0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @param {string} json + * @returns {VotingProcedure} + */ + static from_json(json) { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + const ptr0 = passStringToWasm0( + json, + wasm.__wbindgen_malloc, + wasm.__wbindgen_realloc, + ); + const len0 = WASM_VECTOR_LEN; + wasm.votingprocedure_from_json(retptr, ptr0, len0); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + if (r2) { + throw takeObject(r1); + } + return VotingProcedure.__wrap(r0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @returns {GovernanceActionId} + */ + governance_action_id() { + const ret = wasm.votingprocedure_governance_action_id(this.ptr); + return GovernanceActionId.__wrap(ret); + } + /** + * @returns {Voter} + */ + voter() { + const ret = wasm.votingprocedure_voter(this.ptr); + return Voter.__wrap(ret); + } + /** + * @returns {number} + */ + vote() { + const ret = wasm.votingprocedure_vote(this.ptr); + return ret >>> 0; + } + /** + * @returns {Anchor} + */ + anchor() { + const ret = wasm.votingprocedure_anchor(this.ptr); + return Anchor.__wrap(ret); + } + /** + * @param {GovernanceActionId} governance_action_id + * @param {Voter} voter + * @param {Vote} vote + * @param {Anchor} anchor + * @returns {VotingProcedure} + */ + static new(governance_action_id, voter, vote, anchor) { + _assertClass(governance_action_id, GovernanceActionId); + _assertClass(voter, Voter); + _assertClass(vote, Vote); + _assertClass(anchor, Anchor); + const ret = wasm.votingprocedure_new( + governance_action_id.ptr, + voter.ptr, + vote.ptr, + anchor.ptr, + ); + return VotingProcedure.__wrap(ret); + } +} +module.exports.VotingProcedure = VotingProcedure; + +const VotingProceduresFinalization = new FinalizationRegistry((ptr) => + wasm.__wbg_votingprocedures_free(ptr) +); +/** */ +class VotingProcedures { + static __wrap(ptr) { + const obj = Object.create(VotingProcedures.prototype); + obj.ptr = ptr; + VotingProceduresFinalization.register(obj, obj.ptr, obj); + return obj; + } + + __destroy_into_raw() { + const ptr = this.ptr; + this.ptr = 0; + VotingProceduresFinalization.unregister(this); + return ptr; + } + + free() { + const ptr = this.__destroy_into_raw(); + wasm.__wbg_votingprocedures_free(ptr); + } + /** + * @returns {Uint8Array} + */ + to_bytes() { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + wasm.votingprocedures_to_bytes(retptr, this.ptr); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var v0 = getArrayU8FromWasm0(r0, r1).slice(); + wasm.__wbindgen_free(r0, r1 * 1); + return v0; + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @param {Uint8Array} bytes + * @returns {VotingProcedures} + */ + static from_bytes(bytes) { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + const ptr0 = passArray8ToWasm0(bytes, wasm.__wbindgen_malloc); + const len0 = WASM_VECTOR_LEN; + wasm.votingprocedures_from_bytes(retptr, ptr0, len0); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + if (r2) { + throw takeObject(r1); + } + return VotingProcedures.__wrap(r0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @returns {VotingProcedures} + */ + static new() { + const ret = wasm.certificates_new(); + return VotingProcedures.__wrap(ret); + } + /** + * @returns {number} + */ + len() { + const ret = wasm.assetnames_len(this.ptr); + return ret >>> 0; + } + /** + * @param {number} index + * @returns {VotingProcedure} + */ + get(index) { + const ret = wasm.votingprocedures_get(this.ptr, index); + return VotingProcedure.__wrap(ret); + } + /** + * @param {VotingProcedure} elem + */ + add(elem) { + _assertClass(elem, VotingProcedure); + wasm.votingprocedures_add(this.ptr, elem.ptr); + } +} +module.exports.VotingProcedures = VotingProcedures; + +const WithdrawalsFinalization = new FinalizationRegistry((ptr) => + wasm.__wbg_withdrawals_free(ptr) +); +/** */ +class Withdrawals { + static __wrap(ptr) { + const obj = Object.create(Withdrawals.prototype); + obj.ptr = ptr; + WithdrawalsFinalization.register(obj, obj.ptr, obj); + return obj; + } + + __destroy_into_raw() { + const ptr = this.ptr; + this.ptr = 0; + WithdrawalsFinalization.unregister(this); + return ptr; + } + + free() { + const ptr = this.__destroy_into_raw(); + wasm.__wbg_withdrawals_free(ptr); + } + /** + * @returns {Uint8Array} + */ + to_bytes() { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + wasm.withdrawals_to_bytes(retptr, this.ptr); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var v0 = getArrayU8FromWasm0(r0, r1).slice(); + wasm.__wbindgen_free(r0, r1 * 1); + return v0; + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @param {Uint8Array} bytes + * @returns {Withdrawals} + */ + static from_bytes(bytes) { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + const ptr0 = passArray8ToWasm0(bytes, wasm.__wbindgen_malloc); + const len0 = WASM_VECTOR_LEN; + wasm.withdrawals_from_bytes(retptr, ptr0, len0); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + if (r2) { + throw takeObject(r1); + } + return Withdrawals.__wrap(r0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @returns {string} + */ + to_json() { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + wasm.withdrawals_to_json(retptr, this.ptr); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + var r3 = getInt32Memory0()[retptr / 4 + 3]; + var ptr0 = r0; + var len0 = r1; + if (r3) { + ptr0 = 0; + len0 = 0; + throw takeObject(r2); + } + return getStringFromWasm0(ptr0, len0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + wasm.__wbindgen_free(ptr0, len0); + } + } + /** + * @returns {any} + */ + to_js_value() { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + wasm.withdrawals_to_js_value(retptr, this.ptr); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + if (r2) { + throw takeObject(r1); + } + return takeObject(r0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @param {string} json + * @returns {Withdrawals} + */ + static from_json(json) { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + const ptr0 = passStringToWasm0( + json, + wasm.__wbindgen_malloc, + wasm.__wbindgen_realloc, + ); + const len0 = WASM_VECTOR_LEN; + wasm.withdrawals_from_json(retptr, ptr0, len0); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + if (r2) { + throw takeObject(r1); + } + return Withdrawals.__wrap(r0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } + /** + * @returns {Withdrawals} + */ + static new() { + const ret = wasm.assets_new(); + return Withdrawals.__wrap(ret); + } + /** + * @returns {number} + */ + len() { + const ret = wasm.assetnames_len(this.ptr); + return ret >>> 0; + } + /** + * @param {RewardAddress} key + * @param {BigNum} value + * @returns {BigNum | undefined} + */ + insert(key, value) { + _assertClass(key, RewardAddress); + _assertClass(value, BigNum); + const ret = wasm.withdrawals_insert(this.ptr, key.ptr, value.ptr); + return ret === 0 ? undefined : BigNum.__wrap(ret); + } + /** + * @param {RewardAddress} key + * @returns {BigNum | undefined} + */ + get(key) { + _assertClass(key, RewardAddress); + const ret = wasm.withdrawals_get(this.ptr, key.ptr); + return ret === 0 ? undefined : BigNum.__wrap(ret); + } + /** + * @returns {RewardAddresses} + */ + keys() { + const ret = wasm.withdrawals_keys(this.ptr); + return RewardAddresses.__wrap(ret); + } +} +module.exports.Withdrawals = Withdrawals; + +module.exports.__wbindgen_object_drop_ref = function (arg0) { + takeObject(arg0); +}; + +module.exports.__wbindgen_json_parse = function (arg0, arg1) { + const ret = JSON.parse(getStringFromWasm0(arg0, arg1)); + return addHeapObject(ret); +}; + +module.exports.__wbindgen_json_serialize = function (arg0, arg1) { + const obj = getObject(arg1); + const ret = JSON.stringify(obj === undefined ? null : obj); + const ptr0 = passStringToWasm0( + ret, + wasm.__wbindgen_malloc, + wasm.__wbindgen_realloc, + ); + const len0 = WASM_VECTOR_LEN; + getInt32Memory0()[arg0 / 4 + 1] = len0; + getInt32Memory0()[arg0 / 4 + 0] = ptr0; +}; + +module.exports.__wbindgen_string_new = function (arg0, arg1) { + const ret = getStringFromWasm0(arg0, arg1); + return addHeapObject(ret); +}; + +module.exports.__wbg_fetch_16f5dddfc5a913a4 = function (arg0, arg1) { + const ret = getObject(arg0).fetch(getObject(arg1)); + return addHeapObject(ret); +}; + +module.exports.__wbg_transaction_new = function (arg0) { + const ret = Transaction.__wrap(arg0); + return addHeapObject(ret); +}; + +module.exports.__wbindgen_string_get = function (arg0, arg1) { + const obj = getObject(arg1); + const ret = typeof obj === "string" ? obj : undefined; + var ptr0 = isLikeNone(ret) + ? 0 + : passStringToWasm0(ret, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc); + var len0 = WASM_VECTOR_LEN; + getInt32Memory0()[arg0 / 4 + 1] = len0; + getInt32Memory0()[arg0 / 4 + 0] = ptr0; +}; + +module.exports.__wbindgen_object_clone_ref = function (arg0) { + const ret = getObject(arg0); + return addHeapObject(ret); +}; + +module.exports.__wbg_set_a5d34c36a1a4ebd1 = function () { + return handleError(function (arg0, arg1, arg2, arg3, arg4) { + getObject(arg0).set( + getStringFromWasm0(arg1, arg2), + getStringFromWasm0(arg3, arg4), + ); + }, arguments); +}; + +module.exports.__wbg_headers_ab5251d2727ac41e = function (arg0) { + const ret = getObject(arg0).headers; + return addHeapObject(ret); +}; + +module.exports.__wbg_newwithstrandinit_c45f0dc6da26fd03 = function () { + return handleError(function (arg0, arg1, arg2) { + const ret = new Request(getStringFromWasm0(arg0, arg1), getObject(arg2)); + return addHeapObject(ret); + }, arguments); +}; + +module.exports.__wbg_instanceof_Response_fb3a4df648c1859b = function (arg0) { + let result; + try { + result = getObject(arg0) instanceof Response; + } catch { + result = false; + } + const ret = result; + return ret; +}; + +module.exports.__wbg_json_b9414eb18cb751d0 = function () { + return handleError(function (arg0) { + const ret = getObject(arg0).json(); + return addHeapObject(ret); + }, arguments); +}; + +module.exports.__wbindgen_cb_drop = function (arg0) { + const obj = takeObject(arg0).original; + if (obj.cnt-- == 1) { + obj.a = 0; + return true; + } + const ret = false; + return ret; +}; + +module.exports.__wbg_static_accessor_NODE_MODULE_06b864c18e8ae506 = + function () { + const ret = module; + return addHeapObject(ret); + }; + +module.exports.__wbg_process_5615a087a47ba544 = function (arg0) { + const ret = getObject(arg0).process; + return addHeapObject(ret); +}; + +module.exports.__wbindgen_is_object = function (arg0) { + const val = getObject(arg0); + const ret = typeof val === "object" && val !== null; + return ret; +}; + +module.exports.__wbg_versions_8404a8b21b9337ae = function (arg0) { + const ret = getObject(arg0).versions; + return addHeapObject(ret); +}; + +module.exports.__wbg_node_8b504e170b6380b9 = function (arg0) { + const ret = getObject(arg0).node; + return addHeapObject(ret); +}; + +module.exports.__wbindgen_is_string = function (arg0) { + const ret = typeof (getObject(arg0)) === "string"; + return ret; +}; + +module.exports.__wbg_require_0430b68b38d1a77e = function () { + return handleError(function (arg0, arg1, arg2) { + const ret = getObject(arg0).require(getStringFromWasm0(arg1, arg2)); + return addHeapObject(ret); + }, arguments); +}; + +module.exports.__wbg_crypto_ca5197b41df5e2bd = function (arg0) { + const ret = getObject(arg0).crypto; + return addHeapObject(ret); +}; + +module.exports.__wbg_msCrypto_1088c21440b2d7e4 = function (arg0) { + const ret = getObject(arg0).msCrypto; + return addHeapObject(ret); +}; + +module.exports.__wbg_randomFillSync_2f6909f8132a175d = function () { + return handleError(function (arg0, arg1, arg2) { + getObject(arg0).randomFillSync(getArrayU8FromWasm0(arg1, arg2)); + }, arguments); +}; + +module.exports.__wbg_getRandomValues_11a236fbf9914290 = function () { + return handleError(function (arg0, arg1) { + getObject(arg0).getRandomValues(getObject(arg1)); + }, arguments); +}; + +module.exports.__wbg_self_e7c1f827057f6584 = function () { + return handleError(function () { + const ret = self.self; + return addHeapObject(ret); + }, arguments); +}; + +module.exports.__wbg_window_a09ec664e14b1b81 = function () { + return handleError(function () { + const ret = globalThis.window; + return addHeapObject(ret); + }, arguments); +}; + +module.exports.__wbg_globalThis_87cbb8506fecf3a9 = function () { + return handleError(function () { + const ret = globalThis.globalThis; + return addHeapObject(ret); + }, arguments); +}; + +module.exports.__wbg_global_c85a9259e621f3db = function () { + return handleError(function () { + const ret = global.global; + return addHeapObject(ret); + }, arguments); +}; + +module.exports.__wbindgen_is_undefined = function (arg0) { + const ret = getObject(arg0) === undefined; + return ret; +}; + +module.exports.__wbg_newnoargs_2b8b6bd7753c76ba = function (arg0, arg1) { + const ret = new Function(getStringFromWasm0(arg0, arg1)); + return addHeapObject(ret); +}; + +module.exports.__wbg_call_95d1ea488d03e4e8 = function () { + return handleError(function (arg0, arg1) { + const ret = getObject(arg0).call(getObject(arg1)); + return addHeapObject(ret); + }, arguments); +}; + +module.exports.__wbg_new_f9876326328f45ed = function () { + const ret = new Object(); + return addHeapObject(ret); +}; + +module.exports.__wbg_call_9495de66fdbe016b = function () { + return handleError(function (arg0, arg1, arg2) { + const ret = getObject(arg0).call(getObject(arg1), getObject(arg2)); + return addHeapObject(ret); + }, arguments); +}; + +module.exports.__wbg_set_6aa458a4ebdb65cb = function () { + return handleError(function (arg0, arg1, arg2) { + const ret = Reflect.set(getObject(arg0), getObject(arg1), getObject(arg2)); + return ret; + }, arguments); +}; + +module.exports.__wbg_buffer_cf65c07de34b9a08 = function (arg0) { + const ret = getObject(arg0).buffer; + return addHeapObject(ret); +}; + +module.exports.__wbg_new_9d3a9ce4282a18a8 = function (arg0, arg1) { + try { + var state0 = { a: arg0, b: arg1 }; + var cb0 = (arg0, arg1) => { + const a = state0.a; + state0.a = 0; + try { + return __wbg_adapter_1681(a, state0.b, arg0, arg1); + } finally { + state0.a = a; + } + }; + const ret = new Promise(cb0); + return addHeapObject(ret); + } finally { + state0.a = state0.b = 0; + } +}; + +module.exports.__wbg_resolve_fd40f858d9db1a04 = function (arg0) { + const ret = Promise.resolve(getObject(arg0)); + return addHeapObject(ret); +}; + +module.exports.__wbg_then_ec5db6d509eb475f = function (arg0, arg1) { + const ret = getObject(arg0).then(getObject(arg1)); + return addHeapObject(ret); +}; + +module.exports.__wbg_then_f753623316e2873a = function (arg0, arg1, arg2) { + const ret = getObject(arg0).then(getObject(arg1), getObject(arg2)); + return addHeapObject(ret); +}; + +module.exports.__wbg_new_537b7341ce90bb31 = function (arg0) { + const ret = new Uint8Array(getObject(arg0)); + return addHeapObject(ret); +}; + +module.exports.__wbg_set_17499e8aa4003ebd = function (arg0, arg1, arg2) { + getObject(arg0).set(getObject(arg1), arg2 >>> 0); +}; + +module.exports.__wbg_length_27a2afe8ab42b09f = function (arg0) { + const ret = getObject(arg0).length; + return ret; +}; + +module.exports.__wbg_newwithlength_b56c882b57805732 = function (arg0) { + const ret = new Uint8Array(arg0 >>> 0); + return addHeapObject(ret); +}; + +module.exports.__wbg_subarray_7526649b91a252a6 = function (arg0, arg1, arg2) { + const ret = getObject(arg0).subarray(arg1 >>> 0, arg2 >>> 0); + return addHeapObject(ret); +}; + +module.exports.__wbg_new_d87f272aec784ec0 = function (arg0, arg1) { + const ret = new Function(getStringFromWasm0(arg0, arg1)); + return addHeapObject(ret); +}; + +module.exports.__wbg_call_eae29933372a39be = function (arg0, arg1) { + const ret = getObject(arg0).call(getObject(arg1)); + return addHeapObject(ret); +}; + +module.exports.__wbindgen_jsval_eq = function (arg0, arg1) { + const ret = getObject(arg0) === getObject(arg1); + return ret; +}; + +module.exports.__wbg_self_e0b3266d2d9eba1a = function (arg0) { + const ret = getObject(arg0).self; + return addHeapObject(ret); +}; + +module.exports.__wbg_require_0993fe224bf8e202 = function (arg0, arg1) { + const ret = require(getStringFromWasm0(arg0, arg1)); + return addHeapObject(ret); +}; + +module.exports.__wbg_crypto_e95a6e54c5c2e37f = function (arg0) { + const ret = getObject(arg0).crypto; + return addHeapObject(ret); +}; + +module.exports.__wbg_getRandomValues_dc67302a7bd1aec5 = function (arg0) { + const ret = getObject(arg0).getRandomValues; + return addHeapObject(ret); +}; + +module.exports.__wbg_randomFillSync_dd2297de5917c74e = function ( + arg0, + arg1, + arg2, +) { + getObject(arg0).randomFillSync(getArrayU8FromWasm0(arg1, arg2)); +}; + +module.exports.__wbg_getRandomValues_02639197c8166a96 = function ( + arg0, + arg1, + arg2, +) { + getObject(arg0).getRandomValues(getArrayU8FromWasm0(arg1, arg2)); +}; + +module.exports.__wbindgen_debug_string = function (arg0, arg1) { + const ret = debugString(getObject(arg1)); + const ptr0 = passStringToWasm0( + ret, + wasm.__wbindgen_malloc, + wasm.__wbindgen_realloc, + ); + const len0 = WASM_VECTOR_LEN; + getInt32Memory0()[arg0 / 4 + 1] = len0; + getInt32Memory0()[arg0 / 4 + 0] = ptr0; +}; + +module.exports.__wbindgen_throw = function (arg0, arg1) { + throw new Error(getStringFromWasm0(arg0, arg1)); +}; + +module.exports.__wbindgen_memory = function () { + const ret = wasm.memory; + return addHeapObject(ret); +}; + +module.exports.__wbindgen_closure_wrapper7021 = function (arg0, arg1, arg2) { + const ret = makeMutClosure(arg0, arg1, 186, __wbg_adapter_30); + return addHeapObject(ret); +}; + +const path = require("path").join( + __dirname, + "../cardano_multiplatform_lib_bg.wasm", +); +const bytes = require("fs").readFileSync(path); + +const wasmModule = new WebAssembly.Module(bytes); +const wasmInstance = new WebAssembly.Instance(wasmModule, imports); +wasm = wasmInstance.exports; +module.exports.__wasm = wasm; diff --git a/dist/src/src/lucid/lucid.ts b/dist/src/src/lucid/lucid.ts index 072c13fb..8f292f51 100644 --- a/dist/src/src/lucid/lucid.ts +++ b/dist/src/src/lucid/lucid.ts @@ -1,7 +1,6 @@ import { C } from "../core/mod.js"; import { coreToUtxo, - createCostModels, fromHex, fromUnit, paymentCredentialOf, @@ -26,6 +25,7 @@ import { RewardAddress, SignedMessage, Slot, + SlotConfig, Transaction, TxHash, Unit, @@ -41,6 +41,8 @@ import { Message } from "./message.js"; import { SLOT_CONFIG_NETWORK } from "../plutus/time.js"; import { Constr, Data } from "../plutus/data.js"; import { Emulator } from "../provider/emulator.js"; +import { Freeable, Freeables } from "../utils/freeable.js"; +import { getTransactionBuilderConfig } from "../utils/transaction_builder_config.js"; type LucidConstructorArgs = { provider?: Provider; @@ -49,8 +51,8 @@ type LucidConstructorArgs = { }; export class Lucid { - protocolParameters: ProtocolParameters; - txBuilderConfig!: C.TransactionBuilderConfig; + protocolParameters?: ProtocolParameters; + slotConfig!: SlotConfig; wallet!: Wallet; provider!: Provider; network: Network = "Mainnet"; @@ -77,67 +79,34 @@ export class Lucid { }; } } - if (provider && !protocolParameters) { - const protocolParams = await provider.getProtocolParameters(); - lucid.protocolParameters = protocolParams; - } - if (lucid.protocolParameters) { - const slotConfig = SLOT_CONFIG_NETWORK[lucid.network]; - lucid.txBuilderConfig = C.TransactionBuilderConfigBuilder.new() - .coins_per_utxo_byte( - C.BigNum.from_str( - lucid.protocolParameters.coinsPerUtxoByte.toString() - ) - ) - .fee_algo( - C.LinearFee.new( - C.BigNum.from_str(lucid.protocolParameters.minFeeA.toString()), - C.BigNum.from_str(lucid.protocolParameters.minFeeB.toString()) - ) - ) - .key_deposit( - C.BigNum.from_str(lucid.protocolParameters.keyDeposit.toString()) - ) - .pool_deposit( - C.BigNum.from_str(lucid.protocolParameters.poolDeposit.toString()) - ) - .max_tx_size(lucid.protocolParameters.maxTxSize) - .max_value_size(lucid.protocolParameters.maxValSize) - .collateral_percentage(lucid.protocolParameters.collateralPercentage) - .max_collateral_inputs(lucid.protocolParameters.maxCollateralInputs) - .max_tx_ex_units( - C.ExUnits.new( - C.BigNum.from_str(lucid.protocolParameters.maxTxExMem.toString()), - C.BigNum.from_str(lucid.protocolParameters.maxTxExSteps.toString()) - ) - ) - .ex_unit_prices( - C.ExUnitPrices.from_float( - lucid.protocolParameters.priceMem, - lucid.protocolParameters.priceStep - ) - ) - .slot_config( - C.BigNum.from_str(slotConfig.zeroTime.toString()), - C.BigNum.from_str(slotConfig.zeroSlot.toString()), - slotConfig.slotLength - ) - .blockfrost( - // We have Aiken now as native plutus core engine (primary), but we still support blockfrost (secondary) in case of bugs. - C.Blockfrost.new( - // deno-lint-ignore no-explicit-any - ((provider as any)?.url || "") + "/utils/txs/evaluate", - // deno-lint-ignore no-explicit-any - (provider as any)?.projectId || "" - ) - ) - .costmdls(createCostModels(lucid.protocolParameters.costModels)) - .build(); + if (provider && !lucid.protocolParameters) { + const protocolParameters = await provider.getProtocolParameters(); + lucid.protocolParameters = protocolParameters; } + lucid.slotConfig = SLOT_CONFIG_NETWORK[lucid.network]; + lucid.utils = new Utils(lucid); return lucid; } + getTransactionBuilderConfig(): C.TransactionBuilderConfig { + if (!this.protocolParameters) { + throw new Error( + "Protocol parameters or slot config not set. Set a provider or iniatilize with protocol parameters.", + ); + } + return getTransactionBuilderConfig( + this.protocolParameters, + this.slotConfig, + { + // deno-lint-ignore no-explicit-any + url: (this.provider as any)?.url, + // deno-lint-ignore no-explicit-any + projectId: (this.provider as any)?.projectId, + }, + ); + } + /** * Switch provider and/or network. * If provider or network unset, no overwriting happens. Provider or network from current instance are taken then. @@ -146,11 +115,17 @@ export class Lucid { if (this.network === "Custom") { throw new Error("Cannot switch when on custom network."); } - const lucid = await Lucid.new(provider, network); - this.txBuilderConfig = lucid.txBuilderConfig; + const lucid = await Lucid.new({ provider, network }); + this.protocolParameters = lucid.protocolParameters; + this.slotConfig = lucid.slotConfig; this.provider = provider || this.provider; + // Given that protoclParameters and provider are optional we should fetch protocol parameters if they are not set when switiching providers + if (!this.protocolParameters && provider) { + this.protocolParameters = await provider.getProtocolParameters(); + } this.network = network || this.network; this.wallet = lucid.wallet; + return this; } @@ -171,7 +146,7 @@ export class Lucid { verifyMessage( address: Address | RewardAddress, payload: Payload, - signedMessage: SignedMessage + signedMessage: SignedMessage, ): boolean { const { paymentCredential, @@ -194,7 +169,7 @@ export class Lucid { utxosAtWithUnit( addressOrCredential: Address | Credential, - unit: Unit + unit: Unit, ): Promise { return this.provider.getUtxosWithUnit(addressOrCredential, unit); } @@ -248,55 +223,72 @@ export class Lucid { */ selectWalletFromPrivateKey(privateKey: PrivateKey): Lucid { const priv = C.PrivateKey.from_bech32(privateKey); - const pubKeyHash = priv.to_public().hash(); + const publicKey = priv.to_public(); + priv.free(); + const pubKeyHash = publicKey.hash(); + publicKey.free(); this.wallet = { - // deno-lint-ignore require-await - address: async (): Promise
=> - C.EnterpriseAddress.new( + address: (): Promise
=> { + const bucket: Freeable[] = []; + const stakeCredential = C.StakeCredential.from_keyhash(pubKeyHash); + bucket.push(stakeCredential); + const enterpriseAddress = C.EnterpriseAddress.new( this.network === "Mainnet" ? 1 : 0, - C.StakeCredential.from_keyhash(pubKeyHash) - ) - .to_address() - .to_bech32(undefined), - // deno-lint-ignore require-await - rewardAddress: async (): Promise => null, + stakeCredential, + ); + bucket.push(enterpriseAddress); + const address = enterpriseAddress.to_address(); + bucket.push(address); + const bech32 = address.to_bech32(undefined); + Freeables.free(...bucket); + + return Promise.resolve(bech32); + }, + + rewardAddress: (): Promise => Promise.resolve(null), getCollateralCore: (): C.TransactionUnspentOutputs | undefined => { return undefined; }, getUtxos: async (): Promise => { return await this.utxosAt( - paymentCredentialOf(await this.wallet.address()) + paymentCredentialOf(await this.wallet.address()), ); }, getUtxosCore: async (): Promise => { const utxos = await this.utxosAt( - paymentCredentialOf(await this.wallet.address()) + paymentCredentialOf(await this.wallet.address()), ); const coreUtxos = C.TransactionUnspentOutputs.new(); utxos.forEach((utxo) => { - coreUtxos.add(utxoToCore(utxo)); + const coreUtxo = utxoToCore(utxo); + coreUtxos.add(coreUtxo); + coreUtxo.free(); }); return coreUtxos; }, - // deno-lint-ignore require-await - getDelegation: async (): Promise => { - return { poolId: null, rewards: 0n }; + getDelegation: (): Promise => { + return Promise.resolve({ poolId: null, rewards: 0n }); }, - // deno-lint-ignore require-await - signTx: async (tx: C.Transaction): Promise => { - const witness = C.make_vkey_witness( - C.hash_transaction(tx.body()), - priv - ); + signTx: (tx: C.Transaction): Promise => { + const bucket: Freeable[] = []; + const txBody = tx.body(); + bucket.push(txBody); + const hash = C.hash_transaction(txBody); + bucket.push(hash); + const witness = C.make_vkey_witness(hash, priv); + bucket.push(witness); const txWitnessSetBuilder = C.TransactionWitnessSetBuilder.new(); + bucket.push(txWitnessSetBuilder); txWitnessSetBuilder.add_vkey(witness); - return txWitnessSetBuilder.build(); + const witnessSet = txWitnessSetBuilder.build(); + + Freeables.free(...bucket); + return Promise.resolve(witnessSet); }, - // deno-lint-ignore require-await - signMessage: async ( + signMessage: ( address: Address | RewardAddress, - payload: Payload + payload: Payload, ): Promise => { const { paymentCredential, @@ -310,12 +302,13 @@ export class Lucid { throw new Error(`Cannot sign message for address: ${address}.`); } - return signData(hexAddress, payload, privateKey); + return Promise.resolve(signData(hexAddress, payload, privateKey)); }, submitTx: async (tx: Transaction): Promise => { return await this.provider.submitTx(tx); }, }; + return this; } @@ -329,20 +322,27 @@ export class Lucid { }; this.wallet = { - address: async (): Promise
=> - C.Address.from_bytes(fromHex(await getAddressHex())).to_bech32( - undefined - ), + address: async (): Promise
=> { + const addressHex = await getAddressHex(); + const address = C.Address.from_bytes(fromHex(addressHex)); + const bech32 = address.to_bech32(undefined); + address.free(); + return bech32; + }, + rewardAddress: async (): Promise => { const [rewardAddressHex] = await api.getRewardAddresses(); - const rewardAddress = rewardAddressHex - ? C.RewardAddress.from_address( - C.Address.from_bytes(fromHex(rewardAddressHex)) - )! - .to_address() - .to_bech32(undefined) - : null; - return rewardAddress; + if (rewardAddressHex) { + const address = C.Address.from_bytes(fromHex(rewardAddressHex)); + const rewardAddress = C.RewardAddress.from_address(address)!; + address.free(); + const addr = rewardAddress.to_address(); + rewardAddress.free(); + const bech32 = addr.to_bech32(undefined); + addr.free(); + return bech32; + } + return null; }, getCollateralCore: (): C.TransactionUnspentOutputs | undefined => { return undefined; @@ -350,16 +350,20 @@ export class Lucid { getUtxos: async (): Promise => { const utxos = ((await api.getUtxos()) || []).map((utxo) => { const parsedUtxo = C.TransactionUnspentOutput.from_bytes( - fromHex(utxo) + fromHex(utxo), ); - return coreToUtxo(parsedUtxo); + const finalUtxo = coreToUtxo(parsedUtxo); + parsedUtxo.free(); + return finalUtxo; }); return utxos; }, getUtxosCore: async (): Promise => { const utxos = C.TransactionUnspentOutputs.new(); ((await api.getUtxos()) || []).forEach((utxo) => { - utxos.add(C.TransactionUnspentOutput.from_bytes(fromHex(utxo))); + const coreUtxo = C.TransactionUnspentOutput.from_bytes(fromHex(utxo)); + utxos.add(coreUtxo); + coreUtxo.free(); }); return utxos; }, @@ -376,9 +380,11 @@ export class Lucid { }, signMessage: async ( address: Address | RewardAddress, - payload: Payload + payload: Payload, ): Promise => { - const hexAddress = toHex(C.Address.from_bech32(address).to_bytes()); + const cAddress = C.Address.from_bech32(address); + const hexAddress = toHex(cAddress.to_bytes()); + cAddress.free(); return await api.signData(hexAddress, payload); }, submitTx: async (tx: Transaction): Promise => { @@ -401,36 +407,29 @@ export class Lucid { }: ExternalWallet): Lucid { const addressDetails = this.utils.getAddressDetails(address); this.wallet = { - // deno-lint-ignore require-await - address: async (): Promise
=> address, - // deno-lint-ignore require-await - rewardAddress: async (): Promise => { - const rewardAddr = - !rewardAddress && addressDetails.stakeCredential - ? (() => { - if (addressDetails.stakeCredential.type === "Key") { - return C.RewardAddress.new( - this.network === "Mainnet" ? 1 : 0, - C.StakeCredential.from_keyhash( - C.Ed25519KeyHash.from_hex( - addressDetails.stakeCredential.hash - ) - ) - ) - .to_address() - .to_bech32(undefined); - } - return C.RewardAddress.new( - this.network === "Mainnet" ? 1 : 0, - C.StakeCredential.from_scripthash( - C.ScriptHash.from_hex(addressDetails.stakeCredential.hash) - ) - ) - .to_address() - .to_bech32(undefined); - })() - : rewardAddress; - return rewardAddr || null; + address: (): Promise
=> Promise.resolve(address), + rewardAddress: (): Promise => { + if (!rewardAddress && addressDetails.stakeCredential) { + if (addressDetails.stakeCredential.type === "Key") { + const keyHash = C.Ed25519KeyHash.from_hex( + addressDetails.stakeCredential.hash, + ); + const stakeCredential = C.StakeCredential.from_keyhash(keyHash); + keyHash.free(); + const rewardAddress = C.RewardAddress.new( + this.network === "Mainnet" ? 1 : 0, + stakeCredential, + ); + stakeCredential.free(); + const address = rewardAddress.to_address(); + rewardAddress.free(); + const bech32 = address.to_bech32(undefined); + address.free(); + return Promise.resolve(bech32); + } + } + + return Promise.resolve(rewardAddress ?? null); }, getCollateralCore: (): C.TransactionUnspentOutputs | undefined => { if (!collateral || !collateral.length) { @@ -449,7 +448,12 @@ export class Lucid { (utxos ? utxos : await this.utxosAt(paymentCredentialOf(address)) - ).forEach((utxo) => coreUtxos.add(utxoToCore(utxo))); + ).forEach((utxo) => { + const coreUtxo = utxoToCore(utxo); + coreUtxos.add(coreUtxo); + coreUtxo.free(); + }); + return coreUtxos; }, getDelegation: async (): Promise => { @@ -459,17 +463,14 @@ export class Lucid { ? await this.delegationAt(rewardAddr) : { poolId: null, rewards: 0n }; }, - // deno-lint-ignore require-await - signTx: async (): Promise => { - throw new Error("Not implemented"); - }, - // deno-lint-ignore require-await - signMessage: async (): Promise => { - throw new Error("Not implemented"); - }, - submitTx: async (tx: Transaction): Promise => { - return await this.provider.submitTx(tx); - }, + signTx: (): Promise => + Promise.reject("Not implemented"), + + signMessage: (): Promise => + Promise.reject("Not implemented"), + + submitTx: (tx: Transaction): Promise => + this.provider.submitTx(tx), }; return this; } @@ -484,8 +485,9 @@ export class Lucid { addressType?: "Base" | "Enterprise"; accountIndex?: number; password?: string; - } + }, ): Lucid { + const bucket: Freeable[] = []; const { address, rewardAddress, paymentKey, stakeKey } = walletFromSeed( seed, { @@ -493,16 +495,29 @@ export class Lucid { accountIndex: options?.accountIndex || 0, password: options?.password, network: this.network, - } + }, ); - const paymentKeyHash = C.PrivateKey.from_bech32(paymentKey) - .to_public() - .hash() - .to_hex(); - const stakeKeyHash = stakeKey - ? C.PrivateKey.from_bech32(stakeKey).to_public().hash().to_hex() - : ""; + const paymentPrivateKey = C.PrivateKey.from_bech32(paymentKey); + bucket.push(paymentPrivateKey); + const paymentPublicKey = paymentPrivateKey.to_public(); + bucket.push(paymentPublicKey); + const paymentPubKeyHash = paymentPublicKey.hash(); + bucket.push(paymentPubKeyHash); + const paymentKeyHash = paymentPubKeyHash.to_hex(); + + const getStakeKeyHash = (stakeKey: string) => { + const stakePrivateKey = C.PrivateKey.from_bech32(stakeKey); + bucket.push(stakePrivateKey); + const stakePublicKey = stakePrivateKey.to_public(); + bucket.push(stakePublicKey); + const stakePubKeyHash = stakePublicKey.hash(); + bucket.push(stakePubKeyHash); + const stakeKeyHash = stakePubKeyHash.to_hex(); + return stakeKeyHash; + }; + + const stakeKeyHash = stakeKey ? getStakeKeyHash(stakeKey) : ""; const privKeyHashMap = { [paymentKeyHash]: paymentKey, @@ -510,22 +525,21 @@ export class Lucid { }; this.wallet = { - // deno-lint-ignore require-await - address: async (): Promise
=> address, - // deno-lint-ignore require-await - rewardAddress: async (): Promise => - rewardAddress || null, + address: (): Promise
=> Promise.resolve(address), + rewardAddress: (): Promise => + Promise.resolve(rewardAddress || null), + getUtxos: (): Promise => + this.utxosAt(paymentCredentialOf(address)), getCollateralCore: (): C.TransactionUnspentOutputs | undefined => { return undefined; }, - // deno-lint-ignore require-await - getUtxos: async (): Promise => - this.utxosAt(paymentCredentialOf(address)), getUtxosCore: async (): Promise => { const coreUtxos = C.TransactionUnspentOutputs.new(); - (await this.utxosAt(paymentCredentialOf(address))).forEach((utxo) => - coreUtxos.add(utxoToCore(utxo)) - ); + (await this.utxosAt(paymentCredentialOf(address))).forEach((utxo) => { + const coreUtxo = utxoToCore(utxo); + coreUtxos.add(coreUtxo); + coreUtxo.free(); + }); return coreUtxos; }, getDelegation: async (): Promise => { @@ -543,23 +557,29 @@ export class Lucid { const usedKeyHashes = discoverOwnUsedTxKeyHashes( tx, ownKeyHashes, - utxos + utxos, ); const txWitnessSetBuilder = C.TransactionWitnessSetBuilder.new(); usedKeyHashes.forEach((keyHash) => { - const witness = C.make_vkey_witness( - C.hash_transaction(tx.body()), - C.PrivateKey.from_bech32(privKeyHashMap[keyHash]!) - ); + const txBody = tx.body(); + const hash = C.hash_transaction(txBody); + txBody.free(); + const privateKey = C.PrivateKey.from_bech32(privKeyHashMap[keyHash]!); + const witness = C.make_vkey_witness(hash, privateKey); + hash.free(); + privateKey.free(); txWitnessSetBuilder.add_vkey(witness); + witness.free(); }); - return txWitnessSetBuilder.build(); + + const txWitnessSet = txWitnessSetBuilder.build(); + txWitnessSetBuilder.free(); + return txWitnessSet; }, - // deno-lint-ignore require-await - signMessage: async ( + signMessage: ( address: Address | RewardAddress, - payload: Payload + payload: Payload, ): Promise => { const { paymentCredential, @@ -575,12 +595,14 @@ export class Lucid { throw new Error(`Cannot sign message for address: ${address}.`); } - return signData(hexAddress, payload, privateKey); + return Promise.resolve(signData(hexAddress, payload, privateKey)); }, submitTx: async (tx: Transaction): Promise => { return await this.provider.submitTx(tx); }, }; + + Freeables.free(...bucket); return this; } } diff --git a/dist/src/src/lucid/message.ts b/dist/src/src/lucid/message.ts index 1e070039..935e41e5 100644 --- a/dist/src/src/lucid/message.ts +++ b/dist/src/src/lucid/message.ts @@ -8,6 +8,7 @@ import { } from "../types/mod.js"; import { signData } from "../misc/sign_data.js"; import { C } from "../mod.js"; +import { FreeableBucket, Freeables } from "../utils/freeable.js"; export class Message { lucid: Lucid; @@ -17,7 +18,7 @@ export class Message { constructor( lucid: Lucid, address: Address | RewardAddress, - payload: Payload, + payload: Payload ) { this.lucid = lucid; this.address = address; @@ -31,18 +32,31 @@ export class Message { /** Sign message with a separate private key. */ signWithPrivateKey(privateKey: PrivateKey): SignedMessage { - const { paymentCredential, stakeCredential, address: { hex: hexAddress } } = - this.lucid.utils.getAddressDetails(this.address); - - const keyHash = paymentCredential?.hash || stakeCredential?.hash; - - const keyHashOriginal = C.PrivateKey.from_bech32(privateKey).to_public() - .hash().to_hex(); - - if (!keyHash || keyHash !== keyHashOriginal) { - throw new Error(`Cannot sign message for address: ${this.address}.`); + const bucket: FreeableBucket = []; + try { + const { + paymentCredential, + stakeCredential, + address: { hex: hexAddress }, + } = this.lucid.utils.getAddressDetails(this.address); + + const keyHash = paymentCredential?.hash || stakeCredential?.hash; + + const skey = C.PrivateKey.from_bech32(privateKey); + bucket.push(skey); + const vkey = skey.to_public(); + bucket.push(vkey); + const hash = vkey.hash(); + bucket.push(hash); + const keyHashOriginal = hash.to_hex(); + + if (!keyHash || keyHash !== keyHashOriginal) { + throw new Error(`Cannot sign message for address: ${this.address}.`); + } + + return signData(hexAddress, this.payload, privateKey); + } finally { + Freeables.free(...bucket); } - - return signData(hexAddress, this.payload, privateKey); } } diff --git a/dist/src/src/lucid/tx.ts b/dist/src/src/lucid/tx.ts index da52a942..ef35e060 100644 --- a/dist/src/src/lucid/tx.ts +++ b/dist/src/src/lucid/tx.ts @@ -1,5 +1,5 @@ import { C } from "../core/mod.js"; -import { Data } from "../mod.js"; +import { Data, PROTOCOL_PARAMETERS_DEFAULT } from "../mod.js"; import { Address, Assets, @@ -22,17 +22,24 @@ import { UTxO, WithdrawalValidator, } from "../types/mod.js"; +import { + addressFromWithNetworkCheck, + attachScript, + createPoolRegistration, + getDatumFromOutputData, + getScriptWitness, + getStakeCredential, +} from "../utils/cml.js"; +import { type FreeableBucket, Freeables } from "../utils/freeable.js"; import { assetsToValue, fromHex, - networkToId, toHex, - toScriptRef, utxoToCore, valueToAssets, chunk, + createOutput, } from "../utils/mod.js"; -import { applyDoubleCborEncoding } from "../utils/utils.js"; import { Lucid } from "./lucid.js"; import { defaultConfig } from "./tx_config.js"; import { TxComplete } from "./tx_complete.js"; @@ -46,22 +53,31 @@ export class Tx { constructor(lucid: Lucid) { this.lucid = lucid; - this.txBuilder = C.TransactionBuilder.new(this.lucid.txBuilderConfig); + this.txBuilder = C.TransactionBuilder.new( + lucid.getTransactionBuilderConfig(), + ); this.tasks = []; } /** Read data from utxos. These utxos are only referenced and not spent. */ readFrom(utxos: UTxO[]): Tx { this.tasks.push(async (that) => { - for (const utxo of utxos) { - if (utxo.datumHash) { - utxo.datum = Data.to(await that.lucid.datumOf(utxo)); - // Add datum to witness set, so it can be read from validators - const plutusData = C.PlutusData.from_bytes(fromHex(utxo.datum!)); - that.txBuilder.add_plutus_data(plutusData); + const bucket: FreeableBucket = []; + try { + for (const utxo of utxos) { + if (utxo.datumHash) { + utxo.datum = Data.to(await that.lucid.datumOf(utxo)); + // Add datum to witness set, so it can be read from validators + const plutusData = C.PlutusData.from_bytes(fromHex(utxo.datum!)); + bucket.push(plutusData); + that.txBuilder.add_plutus_data(plutusData); + } + const coreUtxo = utxoToCore(utxo); + bucket.push(coreUtxo); + that.txBuilder.add_reference_input(coreUtxo); } - const coreUtxo = utxoToCore(utxo); - that.txBuilder.add_reference_input(coreUtxo); + } finally { + Freeables.free(...bucket); } }); return this; @@ -81,24 +97,26 @@ export class Tx { */ collectFrom(utxos: UTxO[], redeemer?: Redeemer): Tx { this.tasks.push(async (that) => { - for (const utxo of utxos) { - if (utxo.datumHash && !utxo.datum) { - utxo.datum = Data.to(await that.lucid.datumOf(utxo)); - } - const coreUtxo = utxoToCore(utxo); - that.txBuilder.add_input( - coreUtxo, - (redeemer as undefined) && - C.ScriptWitness.new_plutus_witness( - C.PlutusWitness.new( - C.PlutusData.from_bytes(fromHex(redeemer!)), - utxo.datumHash && utxo.datum - ? C.PlutusData.from_bytes(fromHex(utxo.datum!)) - : undefined, - undefined + const bucket: FreeableBucket = []; + try { + for (const utxo of utxos) { + if (utxo.datumHash && !utxo.datum) { + utxo.datum = Data.to(await that.lucid.datumOf(utxo)); + } + const coreUtxo = utxoToCore(utxo); + bucket.push(coreUtxo); + // We don't free Options as the ownership is passed to the txBuilder + const scriptWitness = redeemer + ? getScriptWitness( + redeemer, + utxo.datumHash && utxo.datum ? utxo.datum : undefined, ) - ) - ); + : undefined; + + that.txBuilder.add_input(coreUtxo, scriptWitness); + } + } finally { + Freeables.free(...bucket); } }); return this; @@ -111,34 +129,32 @@ export class Tx { */ mintAssets(assets: Assets, redeemer?: Redeemer): Tx { this.tasks.push((that) => { - const units = Object.keys(assets); - const policyId = units[0].slice(0, 56); - const mintAssets = C.MintAssets.new(); - units.forEach((unit) => { - if (unit.slice(0, 56) !== policyId) { - throw new Error( - "Only one policy id allowed. You can chain multiple mintAssets functions together if you need to mint assets with different policy ids." - ); - } - mintAssets.insert( - C.AssetName.new(fromHex(unit.slice(56))), - C.Int.from_str(assets[unit].toString()) - ); - }); - const scriptHash = C.ScriptHash.from_bytes(fromHex(policyId)); - that.txBuilder.add_mint( - scriptHash, - mintAssets, - redeemer - ? C.ScriptWitness.new_plutus_witness( - C.PlutusWitness.new( - C.PlutusData.from_bytes(fromHex(redeemer!)), - undefined, - undefined - ) - ) - : undefined - ); + const bucket: FreeableBucket = []; + try { + const units = Object.keys(assets); + const policyId = units[0].slice(0, 56); + const mintAssets = C.MintAssets.new(); + bucket.push(mintAssets); + units.forEach((unit) => { + if (unit.slice(0, 56) !== policyId) { + throw new Error( + "Only one policy id allowed. You can chain multiple mintAssets functions together if you need to mint assets with different policy ids.", + ); + } + const assetName = C.AssetName.new(fromHex(unit.slice(56))); + const int = C.Int.from_str(assets[unit].toString()); + // Int is being passed by value so we don't need to free it + bucket.push(assetName); + mintAssets.insert(assetName, int); + }); + const scriptHash = C.ScriptHash.from_bytes(fromHex(policyId)); + // We don't free Options as the ownership is passed to the txBuilder + const scriptWitness = redeemer ? getScriptWitness(redeemer) : undefined; + bucket.push(scriptHash); + that.txBuilder.add_mint(scriptHash, mintAssets, scriptWitness); + } finally { + Freeables.free(...bucket); + } }); return this; } @@ -146,17 +162,16 @@ export class Tx { /** Pay to a public key or native script address. */ payToAddress(address: Address, assets: Assets): Tx { this.tasks.push((that) => { - let output = C.TransactionOutput.new( - addressFromWithNetworkCheck(address, that.lucid), - assetsToValue(assets) - ); + const addr = addressFromWithNetworkCheck(address, that.lucid); + const value = assetsToValue(assets); + + const output = C.TransactionOutput.new(addr, value); const minAda = that.lucid.utils.getMinAdaForOutput(output); assets.lovelace = assets.lovelace > minAda ? assets.lovelace : minAda; - output = C.TransactionOutput.new( - addressFromWithNetworkCheck(address, that.lucid), - assetsToValue(assets) - ); - that.txBuilder.add_output(output); + const valueWithMinAda = assetsToValue(assets); + const outputWithMinAda = C.TransactionOutput.new(addr, valueWithMinAda); + that.txBuilder.add_output(outputWithMinAda); + Freeables.free(output, addr, value, valueWithMinAda, outputWithMinAda); }); return this; } @@ -165,57 +180,51 @@ export class Tx { payToAddressWithData( address: Address, outputData: Datum | OutputData, - assets: Assets + assets: Assets, ): Tx { this.tasks.push((that) => { - if (typeof outputData === "string") { - outputData = { asHash: outputData }; - } - - if ( - [outputData.hash, outputData.asHash, outputData.inline].filter((b) => b) - .length > 1 - ) { - throw new Error( - "Not allowed to set hash, asHash and inline at the same time." - ); - } - const createOutput = (_assets: Assets, _outputData: OutputData) => { - const output = C.TransactionOutput.new( - addressFromWithNetworkCheck(address, that.lucid), - assetsToValue(_assets) - ); + const bucket: FreeableBucket = []; + try { + if (typeof outputData === "string") { + outputData = { asHash: outputData }; + } - if (_outputData.hash) { - output.set_datum( - C.Datum.new_data_hash(C.DataHash.from_hex(_outputData.hash)) - ); - } else if (_outputData.asHash) { - const plutusData = C.PlutusData.from_bytes( - fromHex(_outputData.asHash) - ); - output.set_datum( - C.Datum.new_data_hash(C.hash_plutus_data(plutusData)) - ); - that.txBuilder.add_plutus_data(plutusData); - } else if (_outputData.inline) { - const plutusData = C.PlutusData.from_bytes( - fromHex(_outputData.inline) + if ( + [outputData.hash, outputData.asHash, outputData.inline].filter( + (b) => b, + ).length > 1 + ) { + throw new Error( + "Not allowed to set hash, asHash and inline at the same time.", ); - output.set_datum(C.Datum.new_data(C.Data.new(plutusData))); } - const script = _outputData.scriptRef; - if (script) { - output.set_script_ref(toScriptRef(script)); - } - return output; - }; - let output = createOutput(assets, outputData); - const minAda = this.lucid.utils.getMinAdaForOutput(output); - assets.lovelace = assets.lovelace > minAda ? assets.lovelace : minAda; - output = createOutput(assets, outputData); - that.txBuilder.add_output(output); + const output = createOutput({ + bucket, + txBuilder: that.txBuilder, + lucid: that.lucid, + address, + outputData, + assets, + }); + const minAda = this.lucid.utils.getMinAdaForOutput(output); + const assetsWithMinAda = { ...assets }; + assetsWithMinAda.lovelace = + assets.lovelace > minAda ? assets.lovelace : minAda; + const outputWithMinAda = createOutput({ + bucket, + txBuilder: that.txBuilder, + lucid: that.lucid, + address, + outputData, + assets: assetsWithMinAda, + }); + bucket.push(output, outputWithMinAda); + + that.txBuilder.add_output(outputWithMinAda); + } finally { + Freeables.free(...bucket); + } }); return this; } @@ -224,7 +233,7 @@ export class Tx { payToContract( address: Address, outputData: Datum | OutputData, - assets: Assets + assets: Assets, ): Tx { if (typeof outputData === "string") { outputData = { asHash: outputData }; @@ -232,7 +241,7 @@ export class Tx { if (!(outputData.hash || outputData.asHash || outputData.inline)) { throw new Error( - "No datum set. Script output becomes unspendable without datum." + "No datum set. Script output becomes unspendable without datum.", ); } return this.payToAddressWithData(address, outputData, assets); @@ -242,7 +251,7 @@ export class Tx { delegateTo( rewardAddress: RewardAddress, poolId: PoolId, - redeemer?: Redeemer + redeemer?: Redeemer, ): Tx { this.tasks.push((that) => { const addressDetails = that.lucid.utils.getAddressDetails(rewardAddress); @@ -250,36 +259,18 @@ export class Tx { if (addressDetails.type !== "Reward" || !addressDetails.stakeCredential) { throw new Error("Not a reward address provided."); } - const credential = - addressDetails.stakeCredential.type === "Key" - ? C.StakeCredential.from_keyhash( - C.Ed25519KeyHash.from_bytes( - fromHex(addressDetails.stakeCredential.hash) - ) - ) - : C.StakeCredential.from_scripthash( - C.ScriptHash.from_bytes( - fromHex(addressDetails.stakeCredential.hash) - ) - ); - - that.txBuilder.add_certificate( - C.Certificate.new_stake_delegation( - C.StakeDelegation.new( - credential, - C.Ed25519KeyHash.from_bech32(poolId) - ) - ), - redeemer - ? C.ScriptWitness.new_plutus_witness( - C.PlutusWitness.new( - C.PlutusData.from_bytes(fromHex(redeemer!)), - undefined, - undefined - ) - ) - : undefined + const credential = getStakeCredential( + addressDetails.stakeCredential.hash, + addressDetails.stakeCredential.type, ); + + const keyHash = C.Ed25519KeyHash.from_bech32(poolId); + const delegation = C.StakeDelegation.new(credential, keyHash); + // We don't free Options as the ownership is passed to the txBuilder + const scriptWitness = redeemer ? getScriptWitness(redeemer) : undefined; + const certificate = C.Certificate.new_stake_delegation(delegation); + that.txBuilder.add_certificate(certificate, scriptWitness); + Freeables.free(keyHash, delegation, credential, certificate); }); return this; } @@ -292,25 +283,16 @@ export class Tx { if (addressDetails.type !== "Reward" || !addressDetails.stakeCredential) { throw new Error("Not a reward address provided."); } - const credential = - addressDetails.stakeCredential.type === "Key" - ? C.StakeCredential.from_keyhash( - C.Ed25519KeyHash.from_bytes( - fromHex(addressDetails.stakeCredential.hash) - ) - ) - : C.StakeCredential.from_scripthash( - C.ScriptHash.from_bytes( - fromHex(addressDetails.stakeCredential.hash) - ) - ); - - that.txBuilder.add_certificate( - C.Certificate.new_stake_registration( - C.StakeRegistration.new(credential) - ), - undefined + const credential = getStakeCredential( + addressDetails.stakeCredential.hash, + addressDetails.stakeCredential.type, ); + const stakeRegistration = C.StakeRegistration.new(credential); + const certificate = + C.Certificate.new_stake_registration(stakeRegistration); + + that.txBuilder.add_certificate(certificate, undefined); + Freeables.free(credential, stakeRegistration, certificate); }); return this; } @@ -323,33 +305,18 @@ export class Tx { if (addressDetails.type !== "Reward" || !addressDetails.stakeCredential) { throw new Error("Not a reward address provided."); } - const credential = - addressDetails.stakeCredential.type === "Key" - ? C.StakeCredential.from_keyhash( - C.Ed25519KeyHash.from_bytes( - fromHex(addressDetails.stakeCredential.hash) - ) - ) - : C.StakeCredential.from_scripthash( - C.ScriptHash.from_bytes( - fromHex(addressDetails.stakeCredential.hash) - ) - ); - - that.txBuilder.add_certificate( - C.Certificate.new_stake_deregistration( - C.StakeDeregistration.new(credential) - ), - redeemer - ? C.ScriptWitness.new_plutus_witness( - C.PlutusWitness.new( - C.PlutusData.from_bytes(fromHex(redeemer!)), - undefined, - undefined - ) - ) - : undefined + const credential = getStakeCredential( + addressDetails.stakeCredential.hash, + addressDetails.stakeCredential.type, ); + const stakeDeregistration = C.StakeDeregistration.new(credential); + const certificate = + C.Certificate.new_stake_deregistration(stakeDeregistration); + // We don't free Options as the ownership is passed to the txBuilder + const scriptWitness = redeemer ? getScriptWitness(redeemer) : undefined; + + that.txBuilder.add_certificate(certificate, scriptWitness); + Freeables.free(credential, stakeDeregistration, certificate); }); return this; } @@ -359,12 +326,13 @@ export class Tx { this.tasks.push(async (that) => { const poolRegistration = await createPoolRegistration( poolParams, - that.lucid + that.lucid, ); const certificate = C.Certificate.new_pool_registration(poolRegistration); that.txBuilder.add_certificate(certificate, undefined); + Freeables.free(certificate, poolRegistration); }); return this; } @@ -374,13 +342,14 @@ export class Tx { this.tasks.push(async (that) => { const poolRegistration = await createPoolRegistration( poolParams, - that.lucid + that.lucid, ); // This flag makes sure a pool deposit is not required poolRegistration.set_is_update(true); const certificate = C.Certificate.new_pool_registration(poolRegistration); + Freeables.free(poolRegistration, certificate); that.txBuilder.add_certificate(certificate, undefined); }); @@ -392,10 +361,11 @@ export class Tx { */ retirePool(poolId: PoolId, epoch: number): Tx { this.tasks.push((that) => { - const certificate = C.Certificate.new_pool_retirement( - C.PoolRetirement.new(C.Ed25519KeyHash.from_bech32(poolId), epoch) - ); + const keyHash = C.Ed25519KeyHash.from_bech32(poolId); + const poolRetirement = C.PoolRetirement.new(keyHash, epoch); + const certificate = C.Certificate.new_pool_retirement(poolRetirement); that.txBuilder.add_certificate(certificate, undefined); + Freeables.free(keyHash, poolRetirement, certificate); }); return this; } @@ -403,24 +373,15 @@ export class Tx { withdraw( rewardAddress: RewardAddress, amount: Lovelace, - redeemer?: Redeemer + redeemer?: Redeemer, ): Tx { this.tasks.push((that) => { - that.txBuilder.add_withdrawal( - C.RewardAddress.from_address( - addressFromWithNetworkCheck(rewardAddress, that.lucid) - )!, - C.BigNum.from_str(amount.toString()), - redeemer - ? C.ScriptWitness.new_plutus_witness( - C.PlutusWitness.new( - C.PlutusData.from_bytes(fromHex(redeemer!)), - undefined, - undefined - ) - ) - : undefined - ); + const addr = addressFromWithNetworkCheck(rewardAddress, that.lucid); + const rewardAddr = C.RewardAddress.from_address(addr)!; + const amountBigNum = C.BigNum.from_str(amount.toString()); + const scriptWitness = redeemer ? getScriptWitness(redeemer) : undefined; + that.txBuilder.add_withdrawal(rewardAddr, amountBigNum, scriptWitness); + Freeables.free(addr, rewardAddr, amountBigNum, scriptWitness); }); return this; } @@ -451,9 +412,9 @@ export class Tx { /** Add a payment or stake key hash as a required signer of the transaction. */ addSignerKey(keyHash: PaymentKeyHash | StakeKeyHash): Tx { this.tasks.push((that) => { - that.txBuilder.add_required_signer( - C.Ed25519KeyHash.from_bytes(fromHex(keyHash)) - ); + const key = C.Ed25519KeyHash.from_bytes(fromHex(keyHash)); + that.txBuilder.add_required_signer(key); + Freeables.free(key); }); return this; } @@ -461,9 +422,9 @@ export class Tx { validFrom(unixTime: UnixTime): Tx { this.tasks.push((that) => { const slot = that.lucid.utils.unixTimeToSlot(unixTime); - that.txBuilder.set_validity_start_interval( - C.BigNum.from_str(slot.toString()) - ); + const slotNum = C.BigNum.from_str(slot.toString()); + that.txBuilder.set_validity_start_interval(slotNum); + Freeables.free(slotNum); }); return this; } @@ -471,17 +432,18 @@ export class Tx { validTo(unixTime: UnixTime): Tx { this.tasks.push((that) => { const slot = that.lucid.utils.unixTimeToSlot(unixTime); - that.txBuilder.set_ttl(C.BigNum.from_str(slot.toString())); + const slotNum = C.BigNum.from_str(slot.toString()); + that.txBuilder.set_ttl(slotNum); + Freeables.free(slotNum); }); return this; } attachMetadata(label: Label, metadata: Json): Tx { this.tasks.push((that) => { - that.txBuilder.add_json_metadatum( - C.BigNum.from_str(label.toString()), - JSON.stringify(metadata) - ); + const labelNum = C.BigNum.from_str(label.toString()); + that.txBuilder.add_json_metadatum(labelNum, JSON.stringify(metadata)); + Freeables.free(labelNum); }); return this; } @@ -489,11 +451,13 @@ export class Tx { /** Converts strings to bytes if prefixed with **'0x'**. */ attachMetadataWithConversion(label: Label, metadata: Json): Tx { this.tasks.push((that) => { + const labelNum = C.BigNum.from_str(label.toString()); that.txBuilder.add_json_metadatum_with_schema( - C.BigNum.from_str(label.toString()), + labelNum, JSON.stringify(metadata), - C.MetadataJsonSchema.BasicConversions + C.MetadataJsonSchema.BasicConversions, ); + Freeables.free(labelNum); }); return this; } @@ -501,9 +465,11 @@ export class Tx { /** Explicitely set the network id in the transaction body. */ addNetworkId(id: number): Tx { this.tasks.push((that) => { - that.txBuilder.set_network_id( - C.NetworkId.from_bytes(fromHex(id.toString(16).padStart(2, "0"))) + const networkId = C.NetworkId.from_bytes( + fromHex(id.toString(16).padStart(2, "0")), ); + that.txBuilder.set_network_id(networkId); + Freeables.free(networkId); }); return this; } @@ -554,93 +520,86 @@ export class Tx { return this; } + free() { + this.txBuilder.free(); + } + + /** Completes the transaction. This might fail, you should free the txBuilder when you are done with it. */ async complete(options?: { change?: { address?: Address; outputData?: OutputData }; coinSelection?: boolean; nativeUplc?: boolean; }): Promise { + const bucket: FreeableBucket = []; const { enableChangeSplitting } = this.configuration; - if ( - [ - options?.change?.outputData?.hash, - options?.change?.outputData?.asHash, - options?.change?.outputData?.inline, - ].filter((b) => b).length > 1 - ) { - throw new Error( - "Not allowed to set hash, asHash and inline at the same time." - ); - } + try { + if ( + [ + options?.change?.outputData?.hash, + options?.change?.outputData?.asHash, + options?.change?.outputData?.inline, + ].filter((b) => b).length > 1 + ) { + throw new Error( + "Not allowed to set hash, asHash and inline at the same time.", + ); + } - let task = this.tasks.shift(); - while (task) { - await task(this); - task = this.tasks.shift(); - } + let task = this.tasks.shift(); + while (task) { + await task(this); + task = this.tasks.shift(); + } - const utxos = await this.lucid.wallet.getUtxosCore(); - const collateral = await this.lucid.wallet.getCollateralCore(); + // We don't free `utxos` as it is passed as an Option to the txBuilder and the ownership is passed when passing an Option + const utxos = await this.lucid.wallet.getUtxosCore(); - const changeAddress: C.Address = addressFromWithNetworkCheck( - options?.change?.address || (await this.lucid.wallet.address()), - this.lucid - ); + const collateral = this.lucid.wallet.getCollateralCore(); - if (options?.coinSelection || options?.coinSelection === undefined) { - this.txBuilder.add_inputs_from( - utxos, - changeAddress, - Uint32Array.from([ - 200, // weight ideal > 100 inputs - 1000, // weight ideal < 100 inputs - 1500, // weight assets if plutus - 800, // weight assets if not plutus - 800, // weight distance if not plutus - 5000, // weight utxos - ]) + // We don't free `changeAddress` as it is passed as an Option to the txBuilder and the ownership is passed when passing an Option + const changeAddress: C.Address = addressFromWithNetworkCheck( + options?.change?.address || (await this.lucid.wallet.address()), + this.lucid, ); - } - if (enableChangeSplitting) { - await this.splitChange(); - } + if (options?.coinSelection || options?.coinSelection === undefined) { + this.txBuilder.add_inputs_from_impl( + utxos, + changeAddress, + // Uint32Array.from([ + // 200, // weight ideal > 100 inputs + // 1000, // weight ideal < 100 inputs + // 1500, // weight assets if plutus + // 800, // weight assets if not plutus + // 800, // weight distance if not plutus + // 5000, // weight utxos + // ]), + "200,1000,1500,800,800,5000", + ); + } - this.txBuilder.balance( - changeAddress, - (() => { - if (options?.change?.outputData?.hash) { - return C.Datum.new_data_hash( - C.DataHash.from_hex(options.change.outputData.hash) - ); - } else if (options?.change?.outputData?.asHash) { - this.txBuilder.add_plutus_data( - C.PlutusData.from_bytes(fromHex(options.change.outputData.asHash)) - ); - return C.Datum.new_data_hash( - C.hash_plutus_data( - C.PlutusData.from_bytes(fromHex(options.change.outputData.asHash)) - ) - ); - } else if (options?.change?.outputData?.inline) { - return C.Datum.new_data( - C.Data.new( - C.PlutusData.from_bytes(fromHex(options.change.outputData.inline)) - ) - ); - } else { - return undefined; - } - })() - ); + const { datum, plutusData } = getDatumFromOutputData( + options?.change?.outputData, + ); + if (plutusData) { + this.txBuilder.add_plutus_data(plutusData); + } + bucket.push(datum, plutusData); + if (enableChangeSplitting) { + await this.splitChange(); + } + this.txBuilder.balance(changeAddress, datum); - return new TxComplete( - this.lucid, - await this.txBuilder.construct( + const tx = await this.txBuilder.construct( collateral || utxos, changeAddress, - options?.nativeUplc === undefined ? true : options?.nativeUplc - ) - ); + options?.nativeUplc === undefined ? true : options?.nativeUplc, + ); + + return new TxComplete(this.lucid, tx); + } finally { + Freeables.free(...bucket); + } } /** Return the current transaction body in Hex encoded Cbor. */ @@ -670,16 +629,20 @@ export class Tx { * This is the advanced UTxO management algorithm used by Eternl */ private async splitChange() { - const { coinsPerUtxoByte } = await this.lucid.protocolParameters; + const bucket: FreeableBucket = []; + const { coinsPerUtxoByte } = + this.lucid.protocolParameters || PROTOCOL_PARAMETERS_DEFAULT; const { changeNativeAssetChunkSize, changeMinUtxo } = this.configuration; - const change = this.txBuilder - .get_explicit_input() - .checked_sub(this.txBuilder.get_explicit_output()); + const txInputs = this.txBuilder.get_explicit_input(); + const txOutputs = this.txBuilder.get_explicit_output(); + bucket.push(txInputs, txOutputs); + const change = txInputs.checked_sub(txOutputs); let changeAda = change.coin(); let changeAssets = valueToAssets(change); + bucket.push(changeAda); const changeAssetsArray = Object.keys(changeAssets) .filter((v) => v !== "lovelace") // Sort canonically so we group policy IDs together @@ -687,42 +650,59 @@ export class Tx { changeAssets = changeAssetsArray.reduce( (res, key) => Object.assign(res, { [key]: changeAssets[key] }), - {} + {}, ); const numOutputsWithNativeAssets = Math.ceil( - changeAssetsArray.length / changeNativeAssetChunkSize + changeAssetsArray.length / changeNativeAssetChunkSize, ); let longestAddress = C.Address.from_bech32( - await this.lucid.wallet.address() + await this.lucid.wallet.address(), ); + bucket.push(longestAddress); const outputs = this.txBuilder.outputs(); + bucket.push(outputs); for (let i = 0; i < outputs.len(); i++) { const output = outputs.get(i); + bucket.push(output); + const outputAddress = output.address(); if ( !longestAddress || - output.address().to_bech32(undefined).length > + outputAddress.to_bech32(undefined).length > longestAddress.to_bech32(undefined).length ) { longestAddress = output.address(); } } - const minAdaPerOutput = C.min_ada_required( - C.TransactionOutput.new(longestAddress, assetsToValue(changeAssets)), - C.BigNum.from_str(coinsPerUtxoByte.toString()) + const txOutputValue = assetsToValue(changeAssets); + const transactionOutput = C.TransactionOutput.new( + longestAddress, + txOutputValue, + ); + const coinUtxoByte = C.BigNum.from_str(coinsPerUtxoByte.toString()); + const minAdaPerOutput = C.min_ada_required(transactionOutput, coinUtxoByte); + bucket.push( + txOutputValue, + transactionOutput, + coinUtxoByte, + minAdaPerOutput, ); // Do we have enough ADA in the change to split and still // statisfy minADA requirements? - const shouldSplitChange = - minAdaPerOutput - .checked_mul(C.BigNum.from_str(numOutputsWithNativeAssets.toString())) - .compare(changeAda) < 0; + const numOutputsWithAssets = C.BigNum.from_str( + numOutputsWithNativeAssets.toString(), + ); + const changeAmount = minAdaPerOutput.checked_mul(numOutputsWithAssets); + bucket.push(numOutputsWithAssets, changeAmount); + const shouldSplitChange = changeAmount.compare(changeAda) < 0; - if (change.multiasset() && shouldSplitChange) { + const changeMultiAsset = change.multiasset(); + bucket.push(changeMultiAsset); + if (changeMultiAsset && shouldSplitChange) { const assetChunks = chunk(changeAssetsArray, 20); const totalChunks = assetChunks.length; @@ -734,169 +714,52 @@ export class Tx { const val = assetsToValue( piece.reduce( (res, key) => Object.assign(res, { [key]: changeAssets[key] }), - {} - ) - ); - const minAda = C.min_ada_required( - C.TransactionOutput.new( - C.Address.from_bech32(await this.lucid.wallet.address()), - val + {}, ), - C.BigNum.from_str(coinsPerUtxoByte.toString()) ); + bucket.push(val); + const changeAddress = C.Address.from_bech32( + await this.lucid.wallet.address(), + ); + const minAdaTxOutput = C.TransactionOutput.new(changeAddress, val); - const coin = minAda; - - val.set_coin(coin); - changeAda = changeAda.checked_sub(coin); + const coinUtxoByte = C.BigNum.from_str(coinsPerUtxoByte.toString()); + const minAda = C.min_ada_required(minAdaTxOutput, coinUtxoByte); - this.txBuilder.add_output( - C.TransactionOutput.new( - C.Address.from_bech32(await this.lucid.wallet.address()), - val - ) - ); + val.set_coin(minAda); + changeAda = changeAda.checked_sub(minAda); + const txOutputWithMinAda = C.TransactionOutput.new(changeAddress, val); + bucket.push(changeAda, minAdaTxOutput); + this.txBuilder.add_output(txOutputWithMinAda); } } + const two = C.BigNum.from_str("2"); + const changeMinUtxoBigNum = C.BigNum.from_str(changeMinUtxo); + let split = changeAda.checked_div(two); + bucket.push(two, changeMinUtxoBigNum, split); while ( // If the half is more than the minimum, we can split it - changeAda - .checked_div(C.BigNum.from_str("2")) - .compare(C.BigNum.from_str(changeMinUtxo)) >= 0 + split.compare(changeMinUtxoBigNum) >= 0 ) { - const half = changeAda.checked_div(C.BigNum.from_str("2")); + const half = changeAda.checked_div(two); changeAda = changeAda.checked_sub(half); - this.txBuilder.add_output( - C.TransactionOutput.new( - C.Address.from_bech32(await this.lucid.wallet.address()), - C.Value.new(half) - ) - ); - } - } -} - -function attachScript( - tx: Tx, - { - type, - script, - }: - | SpendingValidator - | MintingPolicy - | CertificateValidator - | WithdrawalValidator -) { - if (type === "Native") { - return tx.txBuilder.add_native_script( - C.NativeScript.from_bytes(fromHex(script)) - ); - } else if (type === "PlutusV1") { - return tx.txBuilder.add_plutus_script( - C.PlutusScript.from_bytes(fromHex(applyDoubleCborEncoding(script))) - ); - } else if (type === "PlutusV2") { - return tx.txBuilder.add_plutus_v2_script( - C.PlutusScript.from_bytes(fromHex(applyDoubleCborEncoding(script))) - ); - } - throw new Error("No variant matched."); -} + split = changeAda.checked_div(two); -async function createPoolRegistration( - poolParams: PoolParams, - lucid: Lucid -): Promise { - const poolOwners = C.Ed25519KeyHashes.new(); - poolParams.owners.forEach((owner) => { - const { stakeCredential } = lucid.utils.getAddressDetails(owner); - if (stakeCredential?.type === "Key") { - poolOwners.add(C.Ed25519KeyHash.from_hex(stakeCredential.hash)); - } else throw new Error("Only key hashes allowed for pool owners."); - }); - - const metadata = poolParams.metadataUrl - ? await fetch(poolParams.metadataUrl).then((res) => res.arrayBuffer()) - : null; - - const metadataHash = metadata - ? C.PoolMetadataHash.from_bytes(C.hash_blake2b256(new Uint8Array(metadata))) - : null; - - const relays = C.Relays.new(); - poolParams.relays.forEach((relay) => { - switch (relay.type) { - case "SingleHostIp": { - const ipV4 = relay.ipV4 - ? C.Ipv4.new( - new Uint8Array(relay.ipV4.split(".").map((b) => parseInt(b))) - ) - : undefined; - const ipV6 = relay.ipV6 - ? C.Ipv6.new(fromHex(relay.ipV6.replaceAll(":", ""))) - : undefined; - relays.add( - C.Relay.new_single_host_addr( - C.SingleHostAddr.new(relay.port, ipV4, ipV6) - ) - ); - break; - } - case "SingleHostDomainName": { - relays.add( - C.Relay.new_single_host_name( - C.SingleHostName.new( - relay.port, - C.DNSRecordAorAAAA.new(relay.domainName!) - ) - ) - ); - break; - } - case "MultiHost": { - relays.add( - C.Relay.new_multi_host_name( - C.MultiHostName.new(C.DNSRecordSRV.new(relay.domainName!)) - ) - ); - break; - } + const changeAddress = C.Address.from_bech32( + await this.lucid.wallet.address(), + ); + const halfValue = C.Value.new(half); + const changeOutput = C.TransactionOutput.new(changeAddress, halfValue); + bucket.push( + half, + changeAda, + split, + changeAddress, + halfValue, + changeOutput, + ); + this.txBuilder.add_output(changeOutput); } - }); - - return C.PoolRegistration.new( - C.PoolParams.new( - C.Ed25519KeyHash.from_bech32(poolParams.poolId), - C.VRFKeyHash.from_hex(poolParams.vrfKeyHash), - C.BigNum.from_str(poolParams.pledge.toString()), - C.BigNum.from_str(poolParams.cost.toString()), - C.UnitInterval.from_float(poolParams.margin), - C.RewardAddress.from_address( - addressFromWithNetworkCheck(poolParams.rewardAddress, lucid) - )!, - poolOwners, - relays, - metadataHash - ? C.PoolMetadata.new(C.Url.new(poolParams.metadataUrl!), metadataHash) - : undefined - ) - ); -} - -function addressFromWithNetworkCheck( - address: Address | RewardAddress, - lucid: Lucid -): C.Address { - const { type, networkId } = lucid.utils.getAddressDetails(address); - - const actualNetworkId = networkToId(lucid.network); - if (networkId !== actualNetworkId) { - throw new Error( - `Invalid address: Expected address with network id ${actualNetworkId}, but got ${networkId}`, - ); } - return type === "Byron" - ? C.ByronAddress.from_base58(address).to_address() - : C.Address.from_bech32(address); } diff --git a/dist/src/src/lucid/tx_complete.ts b/dist/src/src/lucid/tx_complete.ts index 444dff6f..08cb51eb 100644 --- a/dist/src/src/lucid/tx_complete.ts +++ b/dist/src/src/lucid/tx_complete.ts @@ -8,6 +8,7 @@ import { import { Lucid } from "./lucid.js"; import { TxSigned } from "./tx_signed.js"; import { fromHex, toHex } from "../utils/mod.js"; +import { FreeableBucket, Freeables } from "../utils/freeable.js"; export class TxComplete { txComplete: C.Transaction; @@ -18,39 +19,64 @@ export class TxComplete { exUnits: { cpu: number; mem: number } | null = null; constructor(lucid: Lucid, tx: C.Transaction) { + const bucket: FreeableBucket = []; this.lucid = lucid; this.txComplete = tx; this.witnessSetBuilder = C.TransactionWitnessSetBuilder.new(); this.tasks = []; - this.fee = parseInt(tx.body().fee().to_str()); - const redeemers = tx.witness_set().redeemers(); + const body = tx.body(); + bucket.push(body); + const fee = body.fee(); + bucket.push(fee); + const witnessSet = tx.witness_set(); + bucket.push(witnessSet); + + this.fee = parseInt(fee.to_str()); + const redeemers = witnessSet.redeemers(); + bucket.push(redeemers); if (redeemers) { const exUnits = { cpu: 0, mem: 0 }; for (let i = 0; i < redeemers.len(); i++) { const redeemer = redeemers.get(i); - exUnits.cpu += parseInt(redeemer.ex_units().steps().to_str()); - exUnits.mem += parseInt(redeemer.ex_units().mem().to_str()); + bucket.push(redeemer); + const cExUnits = redeemer.ex_units(); + bucket.push(cExUnits); + const steps = cExUnits.steps(); + bucket.push(steps); + const mem = cExUnits.mem(); + bucket.push(mem); + + exUnits.cpu += parseInt(steps.to_str()); + exUnits.mem += parseInt(mem.to_str()); } this.exUnits = exUnits; } + + Freeables.free(...bucket); } sign(): TxComplete { this.tasks.push(async () => { const witnesses = await this.lucid.wallet.signTx(this.txComplete); this.witnessSetBuilder.add_existing(witnesses); + witnesses.free(); }); return this; } /** Add an extra signature from a private key. */ signWithPrivateKey(privateKey: PrivateKey): TxComplete { + const bucket: FreeableBucket = []; const priv = C.PrivateKey.from_bech32(privateKey); - const witness = C.make_vkey_witness( - C.hash_transaction(this.txComplete.body()), - priv, - ); + bucket.push(priv); + const body = this.txComplete.body(); + bucket.push(body); + const hash = C.hash_transaction(body); + bucket.push(hash); + const witness = C.make_vkey_witness(hash, priv); + bucket.push(witness); this.witnessSetBuilder.add_vkey(witness); + Freeables.free(...bucket); return this; } @@ -58,7 +84,9 @@ export class TxComplete { async partialSign(): Promise { const witnesses = await this.lucid.wallet.signTx(this.txComplete); this.witnessSetBuilder.add_existing(witnesses); - return toHex(witnesses.to_bytes()); + const bytes = witnesses.to_bytes(); + witnesses.free(); + return toHex(bytes); } /** @@ -66,24 +94,36 @@ export class TxComplete { * Add an extra signature from a private key. */ partialSignWithPrivateKey(privateKey: PrivateKey): TransactionWitnesses { + const bucket: FreeableBucket = []; const priv = C.PrivateKey.from_bech32(privateKey); - const witness = C.make_vkey_witness( - C.hash_transaction(this.txComplete.body()), - priv, - ); + bucket.push(priv); + const body = this.txComplete.body(); + bucket.push(body); + const hash = C.hash_transaction(body); + bucket.push(hash); + const witness = C.make_vkey_witness(hash, priv); + bucket.push(witness); + this.witnessSetBuilder.add_vkey(witness); const witnesses = C.TransactionWitnessSetBuilder.new(); + bucket.push(witnesses); witnesses.add_vkey(witness); - return toHex(witnesses.build().to_bytes()); + const witnessSet = witnesses.build(); + bucket.push(witnessSet); + const bytes = witnessSet.to_bytes(); + + Freeables.free(...bucket); + return toHex(bytes); } /** Sign the transaction with the given witnesses. */ assemble(witnesses: TransactionWitnesses[]): TxComplete { witnesses.forEach((witness) => { const witnessParsed = C.TransactionWitnessSet.from_bytes( - fromHex(witness), + fromHex(witness) ); this.witnessSetBuilder.add_existing(witnessParsed); + witnessParsed.free(); }); return this; } @@ -93,12 +133,19 @@ export class TxComplete { await task(); } - this.witnessSetBuilder.add_existing(this.txComplete.witness_set()); - const signedTx = C.Transaction.new( - this.txComplete.body(), - this.witnessSetBuilder.build(), - this.txComplete.auxiliary_data(), - ); + const bucket: FreeableBucket = []; + const txCompleteWitnessSet = this.txComplete.witness_set(); + bucket.push(txCompleteWitnessSet); + this.witnessSetBuilder.add_existing(txCompleteWitnessSet); + const body = this.txComplete.body(); + bucket.push(body); + const witnessSet = this.witnessSetBuilder.build(); + bucket.push(witnessSet); + const auxiliaryData = this.txComplete.auxiliary_data(); + bucket.push(auxiliaryData); + const signedTx = C.Transaction.new(body, witnessSet, auxiliaryData); + + Freeables.free(...bucket); return new TxSigned(this.lucid, signedTx); } @@ -109,6 +156,16 @@ export class TxComplete { /** Return the transaction hash. */ toHash(): TxHash { - return C.hash_transaction(this.txComplete.body()).to_hex(); + const body = this.txComplete.body(); + const hash = C.hash_transaction(body); + const txHash = hash.to_hex(); + Freeables.free(body, hash); + return txHash; + } + + /** Since this object has WASM fields, we must use the free method to free the fields */ + free() { + this.txComplete.free(); + this.witnessSetBuilder.free(); } } diff --git a/dist/src/src/lucid/tx_signed.ts b/dist/src/src/lucid/tx_signed.ts index db34530d..6332551c 100644 --- a/dist/src/src/lucid/tx_signed.ts +++ b/dist/src/src/lucid/tx_signed.ts @@ -13,7 +13,7 @@ export class TxSigned { async submit(): Promise { return await (this.lucid.wallet || this.lucid.provider).submitTx( - toHex(this.txSigned.to_bytes()), + toHex(this.txSigned.to_bytes()) ); } @@ -24,6 +24,14 @@ export class TxSigned { /** Return the transaction hash. */ toHash(): TxHash { - return C.hash_transaction(this.txSigned.body()).to_hex(); + const hash = C.hash_transaction(this.txSigned.body()); + const txHash = hash.to_hex(); + hash.free(); + return txHash; + } + + /** Since this object has WASM fields, we must use the free method to free the fields */ + free() { + this.txSigned.free(); } } diff --git a/dist/src/src/plutus/data.ts b/dist/src/src/plutus/data.ts index 67dd44bc..55124383 100644 --- a/dist/src/src/plutus/data.ts +++ b/dist/src/src/plutus/data.ts @@ -10,6 +10,7 @@ import { import { C } from "../core/mod.js"; import { Datum, Exact, Json, Redeemer } from "../types/mod.js"; import { fromHex, fromText, toHex } from "../utils/utils.js"; +import { FreeableBucket, Freeables } from "../utils/freeable.js"; export class Constr { index: number; @@ -38,14 +39,12 @@ export type Data = export const Data = { // Types // Note: Recursive types are not supported (yet) - Integer: function ( - options?: { - minimum?: number; - maximum?: number; - exclusiveMinimum?: number; - exclusiveMaximum?: number; - }, - ) { + Integer: function (options?: { + minimum?: number; + maximum?: number; + exclusiveMinimum?: number; + exclusiveMaximum?: number; + }) { const integer = Type.Unsafe({ dataType: "integer" }); if (options) { Object.entries(options).forEach(([key, value]) => { @@ -54,9 +53,11 @@ export const Data = { } return integer; }, - Bytes: function ( - options?: { minLength?: number; maxLength?: number; enum?: string[] }, - ) { + Bytes: function (options?: { + minLength?: number; + maxLength?: number; + enum?: string[]; + }) { const bytes = Type.Unsafe({ dataType: "bytes" }); if (options) { Object.entries(options).forEach(([key, value]) => { @@ -88,7 +89,7 @@ export const Data = { }, Array: function ( items: T, - options?: { minItems?: number; maxItems?: number; uniqueItems?: boolean }, + options?: { minItems?: number; maxItems?: number; uniqueItems?: boolean } ) { const array = Type.Array(items); replaceProperties(array, { dataType: "list", items }); @@ -102,7 +103,7 @@ export const Data = { Map: function ( keys: T, values: U, - options?: { minItems?: number; maxItems?: number }, + options?: { minItems?: number; maxItems?: number } ) { const map = Type.Unsafe, Data.Static>>({ dataType: "map", @@ -122,55 +123,55 @@ export const Data = { */ Object: function ( properties: T, - options?: { hasConstr?: boolean }, + options?: { hasConstr?: boolean } ) { const object = Type.Object(properties); replaceProperties(object, { - anyOf: [{ - dataType: "constructor", - index: 0, // Will be replaced when using Data.Enum - fields: Object.entries(properties).map(([title, p]) => ({ - ...p, - title, - })), - }], + anyOf: [ + { + dataType: "constructor", + index: 0, // Will be replaced when using Data.Enum + fields: Object.entries(properties).map(([title, p]) => ({ + ...p, + title, + })), + }, + ], }); - object.anyOf[0].hasConstr = typeof options?.hasConstr === "undefined" || - options.hasConstr; + object.anyOf[0].hasConstr = + typeof options?.hasConstr === "undefined" || options.hasConstr; return object; }, Enum: function (items: T[]) { const union = Type.Union(items); - replaceProperties( - union, - { - anyOf: items.map((item, index) => - item.anyOf[0].fields.length === 0 - ? ({ + replaceProperties(union, { + anyOf: items.map((item, index) => + item.anyOf[0].fields.length === 0 + ? { ...item.anyOf[0], index, - }) - : ({ + } + : { dataType: "constructor", title: (() => { const title = item.anyOf[0].fields[0].title; if ( (title as string).charAt(0) !== - (title as string).charAt(0).toUpperCase() + (title as string).charAt(0).toUpperCase() ) { throw new Error( - `Enum '${title}' needs to start with an uppercase letter.`, + `Enum '${title}' needs to start with an uppercase letter.` ); } return item.anyOf[0].fields[0].title; })(), index, - fields: item.anyOf[0].fields[0].items || + fields: + item.anyOf[0].fields[0].items || item.anyOf[0].fields[0].anyOf[0].fields, - }) - ), - }, - ); + } + ), + }); return union; }, /** @@ -179,7 +180,7 @@ export const Data = { */ Tuple: function ( items: [...T], - options?: { hasConstr?: boolean }, + options?: { hasConstr?: boolean } ) { const tuple = Type.Tuple(items); replaceProperties(tuple, { @@ -198,17 +199,19 @@ export const Data = { (title as string).charAt(0) !== (title as string).charAt(0).toUpperCase() ) { throw new Error( - `Enum '${title}' needs to start with an uppercase letter.`, + `Enum '${title}' needs to start with an uppercase letter.` ); } const literal = Type.Literal(title); replaceProperties(literal, { - anyOf: [{ - dataType: "constructor", - title, - index: 0, // Will be replaced in Data.Enum - fields: [], - }], + anyOf: [ + { + dataType: "constructor", + title, + index: 0, // Will be replaced in Data.Enum + fields: [], + }, + ], }); return literal; }, @@ -220,9 +223,7 @@ export const Data = { description: "An optional value.", dataType: "constructor", index: 0, - fields: [ - item, - ], + fields: [item], }, { title: "None", @@ -264,36 +265,51 @@ export const Data = { */ function to(data: Exact, type?: T): Datum | Redeemer { function serialize(data: Data): C.PlutusData { + const bucket: FreeableBucket = []; try { - if ( - typeof data === "bigint" - ) { - return C.PlutusData.new_integer(C.BigInt.from_str(data.toString())); + if (typeof data === "bigint") { + const integer = C.BigInt.from_str(data.toString()); + bucket.push(integer); + return C.PlutusData.new_integer(integer); } else if (typeof data === "string") { return C.PlutusData.new_bytes(fromHex(data)); } else if (data instanceof Constr) { const { index, fields } = data; const plutusList = C.PlutusList.new(); - - fields.forEach((field) => plutusList.add(serialize(field))); - - return C.PlutusData.new_constr_plutus_data( - C.ConstrPlutusData.new( - C.BigNum.from_str(index.toString()), - plutusList, - ), + bucket.push(plutusList); + fields.forEach((field) => { + const serializedField = serialize(field); + plutusList.add(serializedField); + bucket.push(serializedField); + }); + + const constrIndex = C.BigNum.from_str(index.toString()); + bucket.push(constrIndex); + const cosntrPlutusData = C.ConstrPlutusData.new( + constrIndex, + plutusList ); + bucket.push(cosntrPlutusData); + return C.PlutusData.new_constr_plutus_data(cosntrPlutusData); } else if (data instanceof Array) { const plutusList = C.PlutusList.new(); - - data.forEach((arg) => plutusList.add(serialize(arg))); + bucket.push(plutusList); + data.forEach((arg) => { + const serializedArg = serialize(arg); + plutusList.add(serializedArg); + bucket.push(serializedArg); + }); return C.PlutusData.new_list(plutusList); } else if (data instanceof Map) { const plutusMap = C.PlutusMap.new(); - + bucket.push(plutusMap); for (const [key, value] of data.entries()) { - plutusMap.insert(serialize(key), serialize(value)); + const serializedKey = serialize(key); + bucket.push(serializedKey); + const serializedValue = serialize(value); + bucket.push(serializedValue); + plutusMap.insert(serializedKey, serializedValue); } return C.PlutusData.new_map(plutusMap); @@ -301,10 +317,15 @@ function to(data: Exact, type?: T): Datum | Redeemer { throw new Error("Unsupported type"); } catch (error) { throw new Error("Could not serialize the data: " + error); + } finally { + Freeables.free(...bucket); } } - const d = type ? castTo(data, type) : data as Data; - return toHex(serialize(d).to_bytes()) as Datum | Redeemer; + const d = type ? castTo(data, type) : (data as Data); + const serializedD = serialize(d); + const result = toHex(serializedD.to_bytes()) as Datum | Redeemer; + serializedD.free(); + return result; } /** @@ -313,39 +334,63 @@ function to(data: Exact, type?: T): Datum | Redeemer { */ function from(raw: Datum | Redeemer, type?: T): T { function deserialize(data: C.PlutusData): Data { - if (data.kind() === 0) { - const constr = data.as_constr_plutus_data()!; - const l = constr.data(); - const desL = []; - for (let i = 0; i < l.len(); i++) { - desL.push(deserialize(l.get(i))); - } - return new Constr(parseInt(constr.alternative().to_str()), desL); - } else if (data.kind() === 1) { - const m = data.as_map()!; - const desM: Map = new Map(); - const keys = m.keys(); - for (let i = 0; i < keys.len(); i++) { - desM.set(deserialize(keys.get(i)), deserialize(m.get(keys.get(i))!)); - } - return desM; - } else if (data.kind() === 2) { - const l = data.as_list()!; - const desL = []; - for (let i = 0; i < l.len(); i++) { - desL.push(deserialize(l.get(i))); + const bucket: FreeableBucket = []; + try { + if (data.kind() === 0) { + const constr = data.as_constr_plutus_data()!; + bucket.push(constr); + const l = constr.data(); + bucket.push(l); + const desL = []; + for (let i = 0; i < l.len(); i++) { + const des = l.get(i); + bucket.push(des); + desL.push(deserialize(des)); + } + const alternativeConstr = constr.alternative(); + bucket.push(alternativeConstr); + return new Constr(parseInt(alternativeConstr.to_str()), desL); + } else if (data.kind() === 1) { + const m = data.as_map()!; + bucket.push(m); + const desM: Map = new Map(); + const keys = m.keys(); + bucket.push(keys); + for (let i = 0; i < keys.len(); i++) { + const key = keys.get(i); + bucket.push(key); + const value = m.get(key)!; + bucket.push(value); + desM.set(deserialize(key), deserialize(value)); + } + return desM; + } else if (data.kind() === 2) { + const l = data.as_list()!; + bucket.push(l); + const desL = []; + for (let i = 0; i < l.len(); i++) { + const elem = l.get(i); + bucket.push(elem); + desL.push(deserialize(elem)); + } + return desL; + } else if (data.kind() === 3) { + const i = data.as_integer()!; + bucket.push(i); + return BigInt(i.to_str()); + } else if (data.kind() === 4) { + return toHex(data.as_bytes()!); } - return desL; - } else if (data.kind() === 3) { - return BigInt(data.as_integer()!.to_str()); - } else if (data.kind() === 4) { - return toHex(data.as_bytes()!); + throw new Error("Unsupported type"); + } finally { + Freeables.free(...bucket); } - throw new Error("Unsupported type"); } - const data = deserialize(C.PlutusData.from_bytes(fromHex(raw))); + const plutusData = C.PlutusData.from_bytes(fromHex(raw)); + const data = deserialize(plutusData); + plutusData.free(); - return type ? castFrom(data, type) : data as T; + return type ? castFrom(data, type) : (data as T); } /** @@ -386,15 +431,14 @@ function toJson(plutusData: Data): Json { !isNaN(parseInt(data)) && data.slice(-1) === "n") ) { - const bigint = typeof data === "string" - ? BigInt(data.slice(0, -1)) - : data; + const bigint = + typeof data === "string" ? BigInt(data.slice(0, -1)) : data; return parseInt(bigint.toString()); } if (typeof data === "string") { try { return new TextDecoder(undefined, { fatal: true }).decode( - fromHex(data), + fromHex(data) ); } catch (_) { return "0x" + toHex(fromHex(data)); @@ -410,7 +454,7 @@ function toJson(plutusData: Data): Json { typeof convertedKey !== "number" ) { throw new Error( - "Unsupported type (Note: Only bytes or integers can be keys of a JSON object)", + "Unsupported type (Note: Only bytes or integers can be keys of a JSON object)" ); } tempJson[convertedKey] = fromData(value); @@ -418,7 +462,7 @@ function toJson(plutusData: Data): Json { return tempJson; } throw new Error( - "Unsupported type (Note: Constructor cannot be converted to JSON)", + "Unsupported type (Note: Constructor cannot be converted to JSON)" ); } return fromData(plutusData); @@ -447,59 +491,52 @@ function castFrom(data: Data, type: T): T { case "constructor": { if (isVoid(shape)) { if ( - !(data instanceof Constr) || data.index !== 0 || + !(data instanceof Constr) || + data.index !== 0 || data.fields.length !== 0 ) { throw new Error("Could not type cast to void."); } return undefined as T; } else if ( - data instanceof Constr && data.index === shape.index && + data instanceof Constr && + data.index === shape.index && (shape.hasConstr || shape.hasConstr === undefined) ) { const fields: Record = {}; if (shape.fields.length !== data.fields.length) { throw new Error( - "Could not type cast to object. Fields do not match.", + "Could not type cast to object. Fields do not match." ); } - shape.fields.forEach( - (field: Json, fieldIndex: number) => { - const title = field.title || "wrapper"; - if ((/[A-Z]/.test(title[0]))) { - throw new Error( - "Could not type cast to object. Object properties need to start with a lowercase letter.", - ); - } - fields[title] = castFrom( - data.fields[fieldIndex], - field, + shape.fields.forEach((field: Json, fieldIndex: number) => { + const title = field.title || "wrapper"; + if (/[A-Z]/.test(title[0])) { + throw new Error( + "Could not type cast to object. Object properties need to start with a lowercase letter." ); - }, - ); + } + fields[title] = castFrom(data.fields[fieldIndex], field); + }); return fields as T; } else if ( - data instanceof Array && !shape.hasConstr && + data instanceof Array && + !shape.hasConstr && shape.hasConstr !== undefined ) { const fields: Record = {}; if (shape.fields.length !== data.length) { throw new Error("Could not ype cast to object. Fields do not match."); } - shape.fields.forEach( - (field: Json, fieldIndex: number) => { - const title = field.title || "wrapper"; - if ((/[A-Z]/.test(title[0]))) { - throw new Error( - "Could not type cast to object. Object properties need to start with a lowercase letter.", - ); - } - fields[title] = castFrom( - data[fieldIndex], - field, + shape.fields.forEach((field: Json, fieldIndex: number) => { + const title = field.title || "wrapper"; + if (/[A-Z]/.test(title[0])) { + throw new Error( + "Could not type cast to object. Object properties need to start with a lowercase letter." ); - }, - ); + } + fields[title] = castFrom(data[fieldIndex], field); + }); return fields as T; } throw new Error("Could not type cast to object."); @@ -514,8 +551,8 @@ function castFrom(data: Data, type: T): T { throw new Error("Could not type cast to enum."); } - const enumShape = shape.anyOf.find((entry: Json) => - entry.index === data.index + const enumShape = shape.anyOf.find( + (entry: Json) => entry.index === data.index ); if (!enumShape || enumShape.fields.length !== data.fields.length) { throw new Error("Could not type cast to enum."); @@ -534,17 +571,13 @@ function castFrom(data: Data, type: T): T { } else if (isNullable(shape)) { switch (data.index) { case 0: { - if ( - data.fields.length !== 1 - ) { + if (data.fields.length !== 1) { throw new Error("Could not type cast to nullable object."); } return castFrom(data.fields[0], shape.anyOf[0].fields[0]); } case 1: { - if ( - data.fields.length !== 0 - ) { + if (data.fields.length !== 0) { throw new Error("Could not type cast to nullable object."); } return null as T; @@ -555,16 +588,14 @@ function castFrom(data: Data, type: T): T { switch (enumShape.dataType) { case "constructor": { if (enumShape.fields.length === 0) { - if ( - /[A-Z]/.test(enumShape.title[0]) - ) { + if (/[A-Z]/.test(enumShape.title[0])) { return enumShape.title as T; } throw new Error("Could not type cast to enum."); } else { - if (!(/[A-Z]/.test(enumShape.title))) { + if (!/[A-Z]/.test(enumShape.title)) { throw new Error( - "Could not type cast to enum. Enums need to start with an uppercase letter.", + "Could not type cast to enum. Enums need to start with an uppercase letter." ); } @@ -574,14 +605,15 @@ function castFrom(data: Data, type: T): T { // check if named args const args = enumShape.fields[0].title - ? Object.fromEntries(enumShape.fields.map(( - field: Json, - index: number, - ) => [field.title, castFrom(data.fields[index], field)])) - : enumShape.fields.map(( - field: Json, - index: number, - ) => castFrom(data.fields[index], field)); + ? Object.fromEntries( + enumShape.fields.map((field: Json, index: number) => [ + field.title, + castFrom(data.fields[index], field), + ]) + ) + : enumShape.fields.map((field: Json, index: number) => + castFrom(data.fields[index], field) + ); return { [enumShape.title]: args, @@ -594,11 +626,7 @@ function castFrom(data: Data, type: T): T { case "list": { if (shape.items instanceof Array) { // tuple - if ( - data instanceof Constr && - data.index === 0 && - shape.hasConstr - ) { + if (data instanceof Constr && data.index === 0 && shape.hasConstr) { return data.fields.map((field, index) => castFrom(field, shape.items[index]) ) as T; @@ -625,10 +653,7 @@ function castFrom(data: Data, type: T): T { } mapConstraints(data, shape); const map = new Map(); - for ( - const [key, value] of (data) - .entries() - ) { + for (const [key, value] of data.entries()) { map.set(castFrom(key, shape.keys), castFrom(value, shape.values)); } return map as T; @@ -667,7 +692,8 @@ function castTo(struct: Exact, type: T): Data { } return new Constr(0, []); } else if ( - typeof struct !== "object" || struct === null || + typeof struct !== "object" || + struct === null || shape.fields.length !== Object.keys(struct).length ) { throw new Error("Could not type cast to constructor."); @@ -675,10 +701,10 @@ function castTo(struct: Exact, type: T): Data { const fields = shape.fields.map((field: Json) => castTo( (struct as Record)[field.title || "wrapper"], - field, + field ) ); - return (shape.hasConstr || shape.hasConstr === undefined) + return shape.hasConstr || shape.hasConstr === undefined ? new Constr(shape.index, fields) : fields; } @@ -690,9 +716,7 @@ function castTo(struct: Exact, type: T): Data { if (isBoolean(shape)) { if (typeof struct !== "boolean") { - throw new Error( - "Could not type cast to boolean.", - ); + throw new Error("Could not type cast to boolean."); } return new Constr(struct ? 1 : 0, []); } else if (isNullable(shape)) { @@ -702,24 +726,21 @@ function castTo(struct: Exact, type: T): Data { if (fields.length !== 1) { throw new Error("Could not type cast to nullable object."); } - return new Constr(0, [ - castTo(struct, fields[0]), - ]); + return new Constr(0, [castTo(struct, fields[0])]); } } switch (typeof struct) { case "string": { - if (!(/[A-Z]/.test(struct[0]))) { + if (!/[A-Z]/.test(struct[0])) { throw new Error( - "Could not type cast to enum. Enum needs to start with an uppercase letter.", + "Could not type cast to enum. Enum needs to start with an uppercase letter." ); } - const enumIndex = (shape as TEnum).anyOf.findIndex(( - s: TLiteral, - ) => - s.dataType === "constructor" && - s.fields.length === 0 && - s.title === struct + const enumIndex = (shape as TEnum).anyOf.findIndex( + (s: TLiteral) => + s.dataType === "constructor" && + s.fields.length === 0 && + s.title === struct ); if (enumIndex === -1) throw new Error("Could not type cast to enum."); return new Constr(enumIndex, []); @@ -728,14 +749,13 @@ function castTo(struct: Exact, type: T): Data { if (struct === null) throw new Error("Could not type cast to enum."); const structTitle = Object.keys(struct)[0]; - if (!(/[A-Z]/.test(structTitle))) { + if (!/[A-Z]/.test(structTitle)) { throw new Error( - "Could not type cast to enum. Enum needs to start with an uppercase letter.", + "Could not type cast to enum. Enum needs to start with an uppercase letter." ); } - const enumEntry = shape.anyOf.find((s: Json) => - s.dataType === "constructor" && - s.title === structTitle + const enumEntry = shape.anyOf.find( + (s: Json) => s.dataType === "constructor" && s.title === structTitle ); if (!enumEntry) throw new Error("Could not type cast to enum."); @@ -747,16 +767,14 @@ function castTo(struct: Exact, type: T): Data { // check if named args args instanceof Array ? args.map((item, index) => - castTo(item, enumEntry.fields[index]) - ) - : enumEntry.fields.map( - (entry: Json) => { - const [_, item]: [string, Json] = Object.entries(args).find(( - [title], - ) => title === entry.title)!; + castTo(item, enumEntry.fields[index]) + ) + : enumEntry.fields.map((entry: Json) => { + const [_, item]: [string, Json] = Object.entries(args).find( + ([title]) => title === entry.title + )!; return castTo(item, entry); - }, - ), + }) ); } } @@ -786,10 +804,7 @@ function castTo(struct: Exact, type: T): Data { mapConstraints(struct, shape); const map = new Map(); - for ( - const [key, value] of (struct) - .entries() - ) { + for (const [key, value] of struct.entries()) { map.set(castTo(key, shape.keys), castTo(value, shape.values)); } return map; @@ -804,79 +819,72 @@ function castTo(struct: Exact, type: T): Data { function integerConstraints(integer: bigint, shape: TSchema) { if (shape.minimum && integer < BigInt(shape.minimum)) { throw new Error( - `Integer ${integer} is below the minimum ${shape.minimum}.`, + `Integer ${integer} is below the minimum ${shape.minimum}.` ); } if (shape.maximum && integer > BigInt(shape.maximum)) { throw new Error( - `Integer ${integer} is above the maxiumum ${shape.maximum}.`, + `Integer ${integer} is above the maxiumum ${shape.maximum}.` ); } if (shape.exclusiveMinimum && integer <= BigInt(shape.exclusiveMinimum)) { throw new Error( - `Integer ${integer} is below the exclusive minimum ${shape.exclusiveMinimum}.`, + `Integer ${integer} is below the exclusive minimum ${shape.exclusiveMinimum}.` ); } if (shape.exclusiveMaximum && integer >= BigInt(shape.exclusiveMaximum)) { throw new Error( - `Integer ${integer} is above the exclusive maximum ${shape.exclusiveMaximum}.`, + `Integer ${integer} is above the exclusive maximum ${shape.exclusiveMaximum}.` ); } } function bytesConstraints(bytes: string, shape: TSchema) { - if ( - shape.enum && !shape.enum.some((keyword: string) => keyword === bytes) - ) throw new Error(`None of the keywords match with '${bytes}'.`); + if (shape.enum && !shape.enum.some((keyword: string) => keyword === bytes)) { + throw new Error(`None of the keywords match with '${bytes}'.`); + } if (shape.minLength && bytes.length / 2 < shape.minLength) { throw new Error( - `Bytes need to have a length of at least ${shape.minLength} bytes.`, + `Bytes need to have a length of at least ${shape.minLength} bytes.` ); } if (shape.maxLength && bytes.length / 2 > shape.maxLength) { throw new Error( - `Bytes can have a length of at most ${shape.minLength} bytes.`, + `Bytes can have a length of at most ${shape.minLength} bytes.` ); } } function listConstraints(list: Array, shape: TSchema) { if (shape.minItems && list.length < shape.minItems) { - throw new Error( - `Array needs to contain at least ${shape.minItems} items.`, - ); + throw new Error(`Array needs to contain at least ${shape.minItems} items.`); } if (shape.maxItems && list.length > shape.maxItems) { - throw new Error( - `Array can contain at most ${shape.maxItems} items.`, - ); + throw new Error(`Array can contain at most ${shape.maxItems} items.`); } - if (shape.uniqueItems && (new Set(list)).size !== list.length) { + if (shape.uniqueItems && new Set(list).size !== list.length) { // Note this only works for primitive types like string and bigint. - throw new Error( - "Array constains duplicates.", - ); + throw new Error("Array constains duplicates."); } } function mapConstraints(map: Map, shape: TSchema) { if (shape.minItems && map.size < shape.minItems) { - throw new Error( - `Map needs to contain at least ${shape.minItems} items.`, - ); + throw new Error(`Map needs to contain at least ${shape.minItems} items.`); } if (shape.maxItems && map.size > shape.maxItems) { - throw new Error( - `Map can contain at most ${shape.maxItems} items.`, - ); + throw new Error(`Map can contain at most ${shape.maxItems} items.`); } } function isBoolean(shape: TSchema): boolean { - return shape.anyOf && shape.anyOf[0]?.title === "False" && - shape.anyOf[1]?.title === "True"; + return ( + shape.anyOf && + shape.anyOf[0]?.title === "False" && + shape.anyOf[1]?.title === "True" + ); } function isVoid(shape: TSchema): boolean { @@ -884,8 +892,11 @@ function isVoid(shape: TSchema): boolean { } function isNullable(shape: TSchema): boolean { - return shape.anyOf && shape.anyOf[0]?.title === "Some" && - shape.anyOf[1]?.title === "None"; + return ( + shape.anyOf && + shape.anyOf[0]?.title === "Some" && + shape.anyOf[1]?.title === "None" + ); } function replaceProperties(object: Json, properties: Json) { diff --git a/dist/src/src/provider/blockfrost.ts b/dist/src/src/provider/blockfrost.ts index 6b5da2f4..cddf66c5 100644 --- a/dist/src/src/provider/blockfrost.ts +++ b/dist/src/src/provider/blockfrost.ts @@ -16,6 +16,7 @@ import { UTxO, } from "../types/mod.js"; import packageJson from "../../package.js"; +import { FreeableBucket, Freeables } from "../utils/freeable.js"; export class Blockfrost implements Provider { url: string; @@ -52,13 +53,13 @@ export class Blockfrost implements Provider { async getUtxos(addressOrCredential: Address | Credential): Promise { const queryPredicate = (() => { if (typeof addressOrCredential === "string") return addressOrCredential; - const credentialBech32 = addressOrCredential.type === "Key" - ? C.Ed25519KeyHash.from_hex(addressOrCredential.hash).to_bech32( - "addr_vkh", - ) - : C.ScriptHash.from_hex(addressOrCredential.hash).to_bech32( - "addr_vkh", - ); // should be 'script' (CIP-0005) + const hash = + addressOrCredential.type === "Key" + ? C.Ed25519KeyHash.from_hex(addressOrCredential.hash) + : C.ScriptHash.from_hex(addressOrCredential.hash); + + const credentialBech32 = hash.to_bech32("addr_vkh"); // should be 'script' according to CIP-0005, but to maintain bakcwards compatabiltiy I am not changing this + hash.free(); return credentialBech32; })(); let result: BlockfrostUtxoResult = []; @@ -67,7 +68,7 @@ export class Blockfrost implements Provider { const pageResult: BlockfrostUtxoResult | BlockfrostUtxoError = await fetch( `${this.url}/addresses/${queryPredicate}/utxos?page=${page}`, - { headers: { project_id: this.projectId, lucid } }, + { headers: { project_id: this.projectId, lucid } } ).then((res) => res.json()); if ((pageResult as BlockfrostUtxoError).error) { if ((pageResult as BlockfrostUtxoError).status_code === 404) { @@ -86,17 +87,17 @@ export class Blockfrost implements Provider { async getUtxosWithUnit( addressOrCredential: Address | Credential, - unit: Unit, + unit: Unit ): Promise { const queryPredicate = (() => { if (typeof addressOrCredential === "string") return addressOrCredential; - const credentialBech32 = addressOrCredential.type === "Key" - ? C.Ed25519KeyHash.from_hex(addressOrCredential.hash).to_bech32( - "addr_vkh", - ) - : C.ScriptHash.from_hex(addressOrCredential.hash).to_bech32( - "addr_vkh", - ); // should be 'script' (CIP-0005) + const hash = + addressOrCredential.type === "Key" + ? C.Ed25519KeyHash.from_hex(addressOrCredential.hash) + : C.ScriptHash.from_hex(addressOrCredential.hash); + + const credentialBech32 = hash.to_bech32("addr_vkh"); // should be 'script' according to CIP-0005, but to maintain bakcwards compatabiltiy I am not changing this + hash.free(); return credentialBech32; })(); let result: BlockfrostUtxoResult = []; @@ -105,7 +106,7 @@ export class Blockfrost implements Provider { const pageResult: BlockfrostUtxoResult | BlockfrostUtxoError = await fetch( `${this.url}/addresses/${queryPredicate}/utxos/${unit}?page=${page}`, - { headers: { project_id: this.projectId, lucid } }, + { headers: { project_id: this.projectId, lucid } } ).then((res) => res.json()); if ((pageResult as BlockfrostUtxoError).error) { if ((pageResult as BlockfrostUtxoError).status_code === 404) { @@ -125,7 +126,7 @@ export class Blockfrost implements Provider { async getUtxoByUnit(unit: Unit): Promise { const addresses = await fetch( `${this.url}/assets/${unit}/addresses?count=2`, - { headers: { project_id: this.projectId, lucid } }, + { headers: { project_id: this.projectId, lucid } } ).then((res) => res.json()); if (!addresses || addresses.error) { @@ -149,36 +150,42 @@ export class Blockfrost implements Provider { async getUtxosByOutRef(outRefs: OutRef[]): Promise { // TODO: Make sure old already spent UTxOs are not retrievable. const queryHashes = [...new Set(outRefs.map((outRef) => outRef.txHash))]; - const utxos = await Promise.all(queryHashes.map(async (txHash) => { - const result = await fetch( - `${this.url}/txs/${txHash}/utxos`, - { headers: { project_id: this.projectId, lucid } }, - ).then((res) => res.json()); - if (!result || result.error) { - return []; - } - const utxosResult: BlockfrostUtxoResult = result.outputs.map(( - // deno-lint-ignore no-explicit-any - r: any, - ) => ({ - ...r, - tx_hash: txHash, - })); - return this.blockfrostUtxosToUtxos(utxosResult); - })); - - return utxos.reduce((acc, utxos) => acc.concat(utxos), []).filter((utxo) => - outRefs.some((outRef) => - utxo.txHash === outRef.txHash && utxo.outputIndex === outRef.outputIndex - ) + const utxos = await Promise.all( + queryHashes.map(async (txHash) => { + const result = await fetch(`${this.url}/txs/${txHash}/utxos`, { + headers: { project_id: this.projectId, lucid }, + }).then((res) => res.json()); + if (!result || result.error) { + return []; + } + const utxosResult: BlockfrostUtxoResult = result.outputs.map( + ( + // deno-lint-ignore no-explicit-any + r: any + ) => ({ + ...r, + tx_hash: txHash, + }) + ); + return this.blockfrostUtxosToUtxos(utxosResult); + }) ); + + return utxos + .reduce((acc, utxos) => acc.concat(utxos), []) + .filter((utxo) => + outRefs.some( + (outRef) => + utxo.txHash === outRef.txHash && + utxo.outputIndex === outRef.outputIndex + ) + ); } async getDelegation(rewardAddress: RewardAddress): Promise { - const result = await fetch( - `${this.url}/accounts/${rewardAddress}`, - { headers: { project_id: this.projectId, lucid } }, - ).then((res) => res.json()); + const result = await fetch(`${this.url}/accounts/${rewardAddress}`, { + headers: { project_id: this.projectId, lucid }, + }).then((res) => res.json()); if (!result || result.error) { return { poolId: null, rewards: 0n }; } @@ -189,12 +196,9 @@ export class Blockfrost implements Provider { } async getDatum(datumHash: DatumHash): Promise { - const datum = await fetch( - `${this.url}/scripts/datum/${datumHash}/cbor`, - { - headers: { project_id: this.projectId, lucid }, - }, - ) + const datum = await fetch(`${this.url}/scripts/datum/${datumHash}/cbor`, { + headers: { project_id: this.projectId, lucid }, + }) .then((res) => res.json()) .then((res) => res.cbor); if (!datum || datum.error) { @@ -236,43 +240,41 @@ export class Blockfrost implements Provider { } private async blockfrostUtxosToUtxos( - result: BlockfrostUtxoResult, + result: BlockfrostUtxoResult ): Promise { return (await Promise.all( result.map(async (r) => ({ txHash: r.tx_hash, outputIndex: r.output_index, assets: Object.fromEntries( - r.amount.map(({ unit, quantity }) => [unit, BigInt(quantity)]), + r.amount.map(({ unit, quantity }) => [unit, BigInt(quantity)]) ), address: r.address, datumHash: (!r.inline_datum && r.data_hash) || undefined, datum: r.inline_datum || undefined, scriptRef: r.reference_script_hash - ? (await (async () => { - const { - type, - } = await fetch( - `${this.url}/scripts/${r.reference_script_hash}`, - { - headers: { project_id: this.projectId, lucid }, - }, - ).then((res) => res.json()); - // TODO: support native scripts - if (type === "Native" || type === "native") { - throw new Error("Native script ref not implemented!"); - } - const { cbor: script } = await fetch( - `${this.url}/scripts/${r.reference_script_hash}/cbor`, - { headers: { project_id: this.projectId, lucid } }, - ).then((res) => res.json()); - return { - type: type === "plutusV1" ? "PlutusV1" : "PlutusV2", - script: applyDoubleCborEncoding(script), - }; - })()) + ? await (async () => { + const { type } = await fetch( + `${this.url}/scripts/${r.reference_script_hash}`, + { + headers: { project_id: this.projectId, lucid }, + } + ).then((res) => res.json()); + // TODO: support native scripts + if (type === "Native" || type === "native") { + throw new Error("Native script ref not implemented!"); + } + const { cbor: script } = await fetch( + `${this.url}/scripts/${r.reference_script_hash}/cbor`, + { headers: { project_id: this.projectId, lucid } } + ).then((res) => res.json()); + return { + type: type === "plutusV1" ? "PlutusV1" : "PlutusV2", + script: applyDoubleCborEncoding(script), + }; + })() : undefined, - })), + })) )) as UTxO[]; } } @@ -283,38 +285,61 @@ export class Blockfrost implements Provider { */ export function datumJsonToCbor(json: DatumJson): Datum { const convert = (json: DatumJson): C.PlutusData => { - if (!isNaN(json.int!)) { - return C.PlutusData.new_integer(C.BigInt.from_str(json.int!.toString())); - } else if (json.bytes || !isNaN(Number(json.bytes))) { - return C.PlutusData.new_bytes(fromHex(json.bytes!)); - } else if (json.map) { - const m = C.PlutusMap.new(); - json.map.forEach(({ k, v }: { k: unknown; v: unknown }) => { - m.insert(convert(k as DatumJson), convert(v as DatumJson)); - }); - return C.PlutusData.new_map(m); - } else if (json.list) { - const l = C.PlutusList.new(); - json.list.forEach((v: DatumJson) => { - l.add(convert(v)); - }); - return C.PlutusData.new_list(l); - } else if (!isNaN(json.constructor! as unknown as number)) { - const l = C.PlutusList.new(); - json.fields!.forEach((v: DatumJson) => { - l.add(convert(v)); - }); - return C.PlutusData.new_constr_plutus_data( - C.ConstrPlutusData.new( - C.BigNum.from_str(json.constructor!.toString()), - l, - ), - ); + const bucket: FreeableBucket = []; + try { + if (!isNaN(json.int!)) { + const int = C.BigInt.from_str(json.int!.toString()); + bucket.push(int); + return C.PlutusData.new_integer(int); + } else if (json.bytes || !isNaN(Number(json.bytes))) { + return C.PlutusData.new_bytes(fromHex(json.bytes!)); + } else if (json.map) { + const m = C.PlutusMap.new(); + bucket.push(m); + json.map.forEach(({ k, v }: { k: unknown; v: unknown }) => { + const key = convert(k as DatumJson); + bucket.push(key); + const value = convert(v as DatumJson); + bucket.push(value); + + m.insert(key, value); + }); + return C.PlutusData.new_map(m); + } else if (json.list) { + const l = C.PlutusList.new(); + bucket.push(l); + json.list.forEach((v: DatumJson) => { + const value = convert(v); + bucket.push(value); + l.add(value); + }); + return C.PlutusData.new_list(l); + } else if (!isNaN(json.constructor! as unknown as number)) { + const l = C.PlutusList.new(); + bucket.push(l); + json.fields!.forEach((v: DatumJson) => { + const value = convert(v); + bucket.push(value); + l.add(value); + }); + const constructorIndex = C.BigNum.from_str( + json.constructor!.toString() + ); + bucket.push(constructorIndex); + const plutusData = C.ConstrPlutusData.new(constructorIndex, l); + bucket.push(plutusData); + return C.PlutusData.new_constr_plutus_data(plutusData); + } + throw new Error("Unsupported type"); + } finally { + Freeables.free(...bucket); } - throw new Error("Unsupported type"); }; - return toHex(convert(json).to_bytes()); + const convertedJson = convert(json); + const cbor = convertedJson.to_bytes(); + convertedJson.free(); + return toHex(cbor); } type DatumJson = { diff --git a/dist/src/src/provider/emulator.ts b/dist/src/src/provider/emulator.ts index 2a503557..2238b32b 100644 --- a/dist/src/src/provider/emulator.ts +++ b/dist/src/src/provider/emulator.ts @@ -7,6 +7,7 @@ import { DatumHash, Delegation, Lovelace, + OutputData, OutRef, PoolId, ProtocolParameters, @@ -19,6 +20,7 @@ import { UnixTime, UTxO, } from "../types/types.js"; +import { FreeableBucket } from "../utils/freeable.js"; import { PROTOCOL_PARAMETERS_DEFAULT } from "../utils/mod.js"; import { coreToUtxo, @@ -48,21 +50,42 @@ export class Emulator implements Provider { datumTable: Record = {}; constructor( - accounts: { address: Address; assets: Assets }[], - protocolParameters: ProtocolParameters = PROTOCOL_PARAMETERS_DEFAULT, + accounts: { + address: Address; + assets: Assets; + outputData?: OutputData; + }[], + protocolParameters: ProtocolParameters = PROTOCOL_PARAMETERS_DEFAULT ) { const GENESIS_HASH = "00".repeat(32); this.blockHeight = 0; this.slot = 0; this.time = Date.now(); this.ledger = {}; - accounts.forEach(({ address, assets }, index) => { + accounts.forEach(({ address, assets, outputData }, index) => { + if ( + [outputData?.hash, outputData?.asHash, outputData?.inline].filter( + (b) => b + ).length > 1 + ) { + throw new Error( + "Not allowed to set hash, asHash and inline at the same time." + ); + } + this.ledger[GENESIS_HASH + index] = { utxo: { txHash: GENESIS_HASH, outputIndex: index, address, assets, + datumHash: outputData?.asHash + ? C.hash_plutus_data( + C.PlutusData.from_bytes(fromHex(outputData.asHash)) + ).to_hex() + : outputData?.hash, + datum: outputData?.inline, + scriptRef: outputData?.scriptRef, }, spent: false, }; @@ -114,16 +137,12 @@ export class Emulator implements Provider { if (typeof addressOrCredential === "string") { return addressOrCredential === utxo.address ? utxo : []; } else { - const { paymentCredential } = getAddressDetails( - utxo.address, - ); + const { paymentCredential } = getAddressDetails(utxo.address); return paymentCredential?.hash === addressOrCredential.hash ? utxo : []; } }); - return Promise.resolve( - utxos, - ); + return Promise.resolve(utxos); } getProtocolParameters(): Promise { @@ -136,7 +155,7 @@ export class Emulator implements Provider { getUtxosWithUnit( addressOrCredential: Address | Credential, - unit: Unit, + unit: Unit ): Promise { const utxos: UTxO[] = Object.values(this.ledger).flatMap(({ utxo }) => { if (typeof addressOrCredential === "string") { @@ -144,26 +163,22 @@ export class Emulator implements Provider { ? utxo : []; } else { - const { paymentCredential } = getAddressDetails( - utxo.address, - ); + const { paymentCredential } = getAddressDetails(utxo.address); return paymentCredential?.hash === addressOrCredential.hash && - utxo.assets[unit] > 0n + utxo.assets[unit] > 0n ? utxo : []; } }); - return Promise.resolve( - utxos, - ); + return Promise.resolve(utxos); } getUtxosByOutRef(outRefs: OutRef[]): Promise { return Promise.resolve( - outRefs.flatMap((outRef) => - this.ledger[outRef.txHash + outRef.outputIndex]?.utxo || [] - ), + outRefs.flatMap( + (outRef) => this.ledger[outRef.txHash + outRef.outputIndex]?.utxo || [] + ) ); } @@ -199,17 +214,16 @@ export class Emulator implements Provider { * Stake keys need to be registered and delegated like on a real chain in order to receive rewards. */ distributeRewards(rewards: Lovelace) { - for ( - const [rewardAddress, { registeredStake, delegation }] of Object.entries( - this.chain, - ) - ) { + for (const [ + rewardAddress, + { registeredStake, delegation }, + ] of Object.entries(this.chain)) { if (registeredStake && delegation.poolId) { this.chain[rewardAddress] = { registeredStake, delegation: { poolId: delegation.poolId, - rewards: delegation.rewards += rewards, + rewards: (delegation.rewards += rewards), }, }; } @@ -235,31 +249,42 @@ export class Emulator implements Provider { - Validity interval */ + const bucket: FreeableBucket = []; const desTx = C.Transaction.from_bytes(fromHex(tx)); + bucket.push(desTx); const body = desTx.body(); + bucket.push(body); const witnesses = desTx.witness_set(); + bucket.push(witnesses); const datums = witnesses.plutus_data(); + bucket.push(datums); - const txHash = C.hash_transaction(body).to_hex(); + const transactionHash = C.hash_transaction(body); + bucket.push(transactionHash); + const txHash = transactionHash.to_hex(); // Validity interval // Lower bound is inclusive? // Upper bound is inclusive? - const lowerBound = body.validity_start_interval() - ? parseInt(body.validity_start_interval()!.to_str()) + const validityStartInterval = body.validity_start_interval(); + bucket.push(validityStartInterval); + const lowerBound = validityStartInterval + ? parseInt(validityStartInterval.to_str()) : null; - const upperBound = body.ttl() ? parseInt(body.ttl()!.to_str()) : null; + const ttl = body.ttl(); + bucket.push(ttl); + const upperBound = ttl ? parseInt(ttl.to_str()) : null; if (Number.isInteger(lowerBound) && this.slot < lowerBound!) { throw new Error( - `Lower bound (${lowerBound}) not in slot range (${this.slot}).`, + `Lower bound (${lowerBound}) not in slot range (${this.slot}).` ); } if (Number.isInteger(upperBound) && this.slot > upperBound!) { throw new Error( - `Upper bound (${upperBound}) not in slot range (${this.slot}).`, + `Upper bound (${upperBound}) not in slot range (${this.slot}).` ); } @@ -268,7 +293,10 @@ export class Emulator implements Provider { const table: Record = {}; for (let i = 0; i < (datums?.len() || 0); i++) { const datum = datums!.get(i); - const datumHash = C.hash_plutus_data(datum).to_hex(); + bucket.push(datum); + const plutusDataHash = C.hash_plutus_data(datum); + bucket.push(plutusDataHash); + const datumHash = plutusDataHash.to_hex(); table[datumHash] = toHex(datum.to_bytes()); } return table; @@ -279,15 +307,21 @@ export class Emulator implements Provider { // Witness keys const keyHashes = (() => { const keyHashes = []; - for (let i = 0; i < (witnesses.vkeys()?.len() || 0); i++) { - const witness = witnesses.vkeys()!.get(i); - const publicKey = witness.vkey().public_key(); - const keyHash = publicKey.hash().to_hex(); + const vkeys = witnesses.vkeys(); + bucket.push(vkeys); + for (let i = 0; i < (vkeys?.len() || 0); i++) { + const witness = vkeys!.get(i); + bucket.push(witness); + const vkey = witness.vkey(); + bucket.push(vkey); + const publicKey = vkey.public_key(); + bucket.push(publicKey); + const hash = publicKey.hash(); + bucket.push(hash); + const keyHash = hash.to_hex(); if (!publicKey.verify(fromHex(txHash), witness.signature())) { - throw new Error( - `Invalid vkey witness. Key hash: ${keyHash}`, - ); + throw new Error(`Invalid vkey witness. Key hash: ${keyHash}`); } keyHashes.push(keyHash); } @@ -296,35 +330,43 @@ export class Emulator implements Provider { // We only need this to verify native scripts. The check happens in the CML. const edKeyHashes = C.Ed25519KeyHashes.new(); - keyHashes.forEach((keyHash) => - edKeyHashes.add(C.Ed25519KeyHash.from_hex(keyHash)) - ); + bucket.push(edKeyHashes); + keyHashes.forEach((keyHash) => { + const ed25519KeyHash = C.Ed25519KeyHash.from_hex(keyHash); + bucket.push(ed25519KeyHash); + edKeyHashes.add(ed25519KeyHash); + }); const nativeHashes = (() => { const scriptHashes = []; - - for (let i = 0; i < (witnesses.native_scripts()?.len() || 0); i++) { - const witness = witnesses.native_scripts()!.get(i); - const scriptHash = witness.hash(C.ScriptHashNamespace.NativeScript) - .to_hex(); - - if ( - !witness.verify( - Number.isInteger(lowerBound) - ? C.BigNum.from_str(lowerBound!.toString()) - : undefined, - Number.isInteger(upperBound) - ? C.BigNum.from_str(upperBound!.toString()) - : undefined, - edKeyHashes, - ) - ) { + const nativeScripts = witnesses.native_scripts(); + bucket.push(nativeScripts); + for (let i = 0; i < (nativeScripts?.len() || 0); i++) { + const witness = nativeScripts!.get(i); + bucket.push(witness); + const hash = witness.hash(C.ScriptHashNamespace.NativeScript); + bucket.push(hash); + const scriptHash = hash.to_hex(); + + const lBound = Number.isInteger(lowerBound) + ? C.BigNum.from_str(lowerBound!.toString()) + : undefined; + bucket.push(lBound); + const uBound = Number.isInteger(upperBound) + ? C.BigNum.from_str(upperBound!.toString()) + : undefined; + bucket.push(uBound); + if (!witness.verify(lBound, uBound, edKeyHashes)) { throw new Error( - `Invalid native script witness. Script hash: ${scriptHash}`, + `Invalid native script witness. Script hash: ${scriptHash}` ); } - for (let i = 0; i < witness.get_required_signers().len(); i++) { - const keyHash = witness.get_required_signers().get(i).to_hex(); + const requiredSigners = witness.get_required_signers(); + bucket.push(requiredSigners); + for (let i = 0; i < requiredSigners.len(); i++) { + const hash = requiredSigners.get(i); + bucket.push(hash); + const keyHash = hash.to_hex(); consumedHashes.add(keyHash); } scriptHashes.push(scriptHash); @@ -337,17 +379,26 @@ export class Emulator implements Provider { const plutusHashes = (() => { const scriptHashes = []; - for (let i = 0; i < (witnesses.plutus_scripts()?.len() || 0); i++) { - const script = witnesses.plutus_scripts()!.get(i); - const scriptHash = script.hash(C.ScriptHashNamespace.PlutusV1) - .to_hex(); + const plutusScripts = witnesses.plutus_scripts(); + bucket.push(plutusScripts); + for (let i = 0; i < (plutusScripts?.len() || 0); i++) { + const script = plutusScripts!.get(i); + bucket.push(script); + const hash = script.hash(C.ScriptHashNamespace.PlutusV1); + bucket.push(hash); + const scriptHash = hash.to_hex(); scriptHashes.push(scriptHash); } - for (let i = 0; i < (witnesses.plutus_v2_scripts()?.len() || 0); i++) { - const script = witnesses.plutus_v2_scripts()!.get(i); - const scriptHash = script.hash(C.ScriptHashNamespace.PlutusV2) - .to_hex(); + + const plutusV2Scripts = witnesses.plutus_v2_scripts(); + bucket.push(plutusV2Scripts); + for (let i = 0; i < (plutusV2Scripts?.len() || 0); i++) { + const script = plutusV2Scripts!.get(i); + bucket.push(script); + const hash = script.hash(C.ScriptHashNamespace.PlutusV2); + bucket.push(hash); + const scriptHash = hash.to_hex(); scriptHashes.push(scriptHash); } @@ -355,6 +406,7 @@ export class Emulator implements Provider { })(); const inputs = body.inputs(); + bucket.push(inputs); inputs.sort(); type ResolvedInput = { @@ -367,8 +419,13 @@ export class Emulator implements Provider { // Check existence of inputs and look for script refs. for (let i = 0; i < inputs.len(); i++) { const input = inputs.get(i); + bucket.push(input); + const transactionId = input.transaction_id(); + bucket.push(transactionId); + const transactionIndex = input.index(); + bucket.push(transactionIndex); - const outRef = input.transaction_id().to_hex() + input.index().to_str(); + const outRef = transactionId.to_hex() + transactionIndex.to_str(); const entryLedger = this.ledger[outRef]; @@ -378,12 +435,10 @@ export class Emulator implements Provider { if (!entry || entry.spent) { throw new Error( - `Could not spend UTxO: ${ - JSON.stringify({ - txHash: entry?.utxo.txHash, - outputIndex: entry?.utxo.outputIndex, - }) - }\nIt does not exist or was already spent.`, + `Could not spend UTxO: ${JSON.stringify({ + txHash: entry?.utxo.txHash, + outputIndex: entry?.utxo.outputIndex, + })}\nIt does not exist or was already spent.` ); } @@ -392,23 +447,27 @@ export class Emulator implements Provider { switch (scriptRef.type) { case "Native": { const script = C.NativeScript.from_bytes(fromHex(scriptRef.script)); - nativeHashesOptional[ - script.hash(C.ScriptHashNamespace.NativeScript).to_hex() - ] = script; + bucket.push(script); + const hash = script.hash(C.ScriptHashNamespace.NativeScript); + bucket.push(hash); + + nativeHashesOptional[hash.to_hex()] = script; break; } case "PlutusV1": { const script = C.PlutusScript.from_bytes(fromHex(scriptRef.script)); - plutusHashesOptional.push( - script.hash(C.ScriptHashNamespace.PlutusV1).to_hex(), - ); + bucket.push(script); + const hash = script.hash(C.ScriptHashNamespace.PlutusV1); + bucket.push(hash); + plutusHashesOptional.push(hash.to_hex()); break; } case "PlutusV2": { const script = C.PlutusScript.from_bytes(fromHex(scriptRef.script)); - plutusHashesOptional.push( - script.hash(C.ScriptHashNamespace.PlutusV2).to_hex(), - ); + bucket.push(script); + const hash = script.hash(C.ScriptHashNamespace.PlutusV2); + bucket.push(hash); + plutusHashesOptional.push(hash.to_hex()); break; } } @@ -420,21 +479,27 @@ export class Emulator implements Provider { } // Check existence of reference inputs and look for script refs. - for (let i = 0; i < (body.reference_inputs()?.len() || 0); i++) { - const input = body.reference_inputs()!.get(i); + const referenceInputs = body.reference_inputs(); + bucket.push(referenceInputs); + for (let i = 0; i < (referenceInputs?.len() || 0); i++) { + const input = referenceInputs!.get(i); + bucket.push(input); + + const inputId = input.transaction_id(); + bucket.push(inputId); + const inputIndex = input.index(); + bucket.push(inputIndex); - const outRef = input.transaction_id().to_hex() + input.index().to_str(); + const outRef = inputId.to_hex() + inputIndex.to_str(); const entry = this.ledger[outRef] || this.mempool[outRef]; if (!entry || entry.spent) { throw new Error( - `Could not read UTxO: ${ - JSON.stringify({ - txHash: entry?.utxo.txHash, - outputIndex: entry?.utxo.outputIndex, - }) - }\nIt does not exist or was already spent.`, + `Could not read UTxO: ${JSON.stringify({ + txHash: entry?.utxo.txHash, + outputIndex: entry?.utxo.outputIndex, + })}\nIt does not exist or was already spent.` ); } @@ -443,23 +508,27 @@ export class Emulator implements Provider { switch (scriptRef.type) { case "Native": { const script = C.NativeScript.from_bytes(fromHex(scriptRef.script)); - nativeHashesOptional[ - script.hash(C.ScriptHashNamespace.NativeScript).to_hex() - ] = script; + bucket.push(script); + const hash = script.hash(C.ScriptHashNamespace.NativeScript); + bucket.push(hash); + + nativeHashesOptional[hash.to_hex()] = script; break; } case "PlutusV1": { const script = C.PlutusScript.from_bytes(fromHex(scriptRef.script)); - plutusHashesOptional.push( - script.hash(C.ScriptHashNamespace.PlutusV1).to_hex(), - ); + bucket.push(script); + const hash = script.hash(C.ScriptHashNamespace.PlutusV1); + bucket.push(hash); + plutusHashesOptional.push(hash.to_hex()); break; } case "PlutusV2": { const script = C.PlutusScript.from_bytes(fromHex(scriptRef.script)); - plutusHashesOptional.push( - script.hash(C.ScriptHashNamespace.PlutusV2).to_hex(), - ); + bucket.push(script); + const hash = script.hash(C.ScriptHashNamespace.PlutusV2); + bucket.push(hash); + plutusHashesOptional.push(hash.to_hex()); break; } } @@ -478,11 +547,19 @@ export class Emulator implements Provider { 3: "Reward", }; const collected = []; - for (let i = 0; i < (witnesses.redeemers()?.len() || 0); i++) { - const redeemer = witnesses.redeemers()!.get(i); + const redeemers = witnesses.redeemers(); + bucket.push(redeemers); + for (let i = 0; i < (redeemers?.len() || 0); i++) { + const redeemer = redeemers!.get(i); + bucket.push(redeemer); + const tag = redeemer.tag(); + bucket.push(tag); + + const redeemerIndex = redeemer.index(); + bucket.push(redeemerIndex); collected.push({ - tag: tagMap[redeemer.tag().kind()], - index: parseInt(redeemer.index().to_str()), + tag: tagMap[tag.kind()], + index: parseInt(redeemerIndex.to_str()), }); } return collected; @@ -491,13 +568,13 @@ export class Emulator implements Provider { function checkAndConsumeHash( credential: Credential, tag: Tag | null, - index: number | null, + index: number | null ) { switch (credential.type) { case "Key": { if (!keyHashes.includes(credential.hash)) { throw new Error( - `Missing vkey witness. Key hash: ${credential.hash}`, + `Missing vkey witness. Key hash: ${credential.hash}` ); } consumedHashes.add(credential.hash); @@ -508,19 +585,24 @@ export class Emulator implements Provider { consumedHashes.add(credential.hash); break; } else if (nativeHashesOptional[credential.hash]) { + const lBound = Number.isInteger(lowerBound) + ? C.BigNum.from_str(lowerBound!.toString()) + : undefined; + bucket.push(lBound); + const uBound = Number.isInteger(upperBound) + ? C.BigNum.from_str(upperBound!.toString()) + : undefined; + bucket.push(uBound); + if ( !nativeHashesOptional[credential.hash].verify( - Number.isInteger(lowerBound) - ? C.BigNum.from_str(lowerBound!.toString()) - : undefined, - Number.isInteger(upperBound) - ? C.BigNum.from_str(upperBound!.toString()) - : undefined, - edKeyHashes, + lBound, + uBound, + edKeyHashes ) ) { throw new Error( - `Invalid native script witness. Script hash: ${credential.hash}`, + `Invalid native script witness. Script hash: ${credential.hash}` ); } break; @@ -529,8 +611,8 @@ export class Emulator implements Provider { plutusHashesOptional.includes(credential.hash) ) { if ( - redeemers.find((redeemer) => - redeemer.tag === tag && redeemer.index === index + redeemers.find( + (redeemer) => redeemer.tag === tag && redeemer.index === index ) ) { consumedHashes.add(credential.hash); @@ -538,29 +620,34 @@ export class Emulator implements Provider { } } throw new Error( - `Missing script witness. Script hash: ${credential.hash}`, + `Missing script witness. Script hash: ${credential.hash}` ); } } } // Check collateral inputs + const collateral = body.collateral(); + bucket.push(collateral); + for (let i = 0; i < (collateral?.len() || 0); i++) { + const input = collateral!.get(i); + bucket.push(input); - for (let i = 0; i < (body.collateral()?.len() || 0); i++) { - const input = body.collateral()!.get(i); + const transactionId = input.transaction_id(); + bucket.push(transactionId); + const transactionIndex = input.index(); + bucket.push(transactionIndex); - const outRef = input.transaction_id().to_hex() + input.index().to_str(); + const outRef = transactionId.to_hex() + transactionIndex.to_str(); const entry = this.ledger[outRef] || this.mempool[outRef]; if (!entry || entry.spent) { throw new Error( - `Could not read UTxO: ${ - JSON.stringify({ - txHash: entry?.utxo.txHash, - outputIndex: entry?.utxo.outputIndex, - }) - }\nIt does not exist or was already spent.`, + `Could not read UTxO: ${JSON.stringify({ + txHash: entry?.utxo.txHash, + outputIndex: entry?.utxo.outputIndex, + })}\nIt does not exist or was already spent.` ); } @@ -572,17 +659,24 @@ export class Emulator implements Provider { } // Check required signers - - for (let i = 0; i < (body.required_signers()?.len() || 0); i++) { - const signer = body.required_signers()!.get(i); + const requiredSigners = body.required_signers(); + bucket.push(requiredSigners); + for (let i = 0; i < (requiredSigners?.len() || 0); i++) { + const signer = requiredSigners!.get(i); + bucket.push(signer); checkAndConsumeHash({ type: "Key", hash: signer.to_hex() }, null, null); } // Check mint witnesses - - for (let index = 0; index < (body.mint()?.keys().len() || 0); index++) { - const policyId = body.mint()!.keys().get(index).to_hex(); - checkAndConsumeHash({ type: "Script", hash: policyId }, "Mint", index); + const mint = body.mint(); + bucket.push(mint); + const mintKeys = mint?.keys(); + bucket.push(mintKeys); + for (let index = 0; index < (mintKeys?.len() || 0); index++) { + const policy = mintKeys!.get(index); + bucket.push(policy); + const hash = policy.to_hex(); + checkAndConsumeHash({ type: "Script", hash }, "Mint", index); } // Check withdrawal witnesses @@ -592,23 +686,22 @@ export class Emulator implements Provider { withdrawal: Lovelace; }[] = []; - for ( - let index = 0; - index < (body.withdrawals()?.keys().len() || 0); - index++ - ) { - const rawAddress = body.withdrawals()!.keys().get(index); - const withdrawal: Lovelace = BigInt( - body.withdrawals()!.get(rawAddress)!.to_str(), - ); - const rewardAddress = rawAddress.to_address().to_bech32(undefined); - const { stakeCredential } = getAddressDetails( - rewardAddress, - ); + const withdrawals = body.withdrawals(); + const withdrawalKeys = withdrawals?.keys(); + for (let index = 0; index < (withdrawalKeys?.len() || 0); index++) { + const rawAddress = withdrawalKeys!.get(index); + bucket.push(rawAddress); + const cWithdrawal = withdrawals!.get(rawAddress); + bucket.push(cWithdrawal); + const withdrawal: Lovelace = BigInt(cWithdrawal!.to_str()); + const cAddress = rawAddress.to_address(); + bucket.push(cAddress); + const rewardAddress = cAddress.to_bech32(undefined); + const { stakeCredential } = getAddressDetails(rewardAddress); checkAndConsumeHash(stakeCredential!, "Reward", index); if (this.chain[rewardAddress]?.delegation.rewards !== withdrawal) { throw new Error( - "Withdrawal amount doesn't match actual reward balance.", + "Withdrawal amount doesn't match actual reward balance." ); } withdrawalRequests.push({ rewardAddress, withdrawal }); @@ -622,7 +715,9 @@ export class Emulator implements Provider { poolId?: PoolId; }[] = []; - for (let index = 0; index < (body.certs()?.len() || 0); index++) { + const certs = body.certs(); + bucket.push(certs); + for (let index = 0; index < (certs?.len() || 0); index++) { /* Checking only: 1. Stake registration @@ -631,17 +726,27 @@ export class Emulator implements Provider { All other certificate types are not checked and considered valid. */ - const cert = body.certs()!.get(index); + const cert = certs!.get(index); + bucket.push(cert); switch (cert.kind()) { case 0: { const registration = cert.as_stake_registration()!; - const rewardAddress = C.RewardAddress.new( - C.NetworkInfo.testnet().network_id(), - registration.stake_credential(), - ).to_address().to_bech32(undefined); + bucket.push(registration); + const networkInfo = C.NetworkInfo.testnet(); + bucket.push(networkInfo); + const stakeCredential = registration.stake_credential(); + bucket.push(stakeCredential); + const cRewardAddress = C.RewardAddress.new( + networkInfo.network_id(), + stakeCredential + ); + bucket.push(cRewardAddress); + const address = cRewardAddress.to_address(); + bucket.push(address); + const rewardAddress = address.to_bech32(undefined); if (this.chain[rewardAddress]?.registeredStake) { throw new Error( - `Stake key is already registered. Reward address: ${rewardAddress}`, + `Stake key is already registered. Reward address: ${rewardAddress}` ); } certRequests.push({ type: "Registration", rewardAddress }); @@ -649,17 +754,26 @@ export class Emulator implements Provider { } case 1: { const deregistration = cert.as_stake_deregistration()!; - const rewardAddress = C.RewardAddress.new( - C.NetworkInfo.testnet().network_id(), - deregistration.stake_credential(), - ).to_address().to_bech32(undefined); + bucket.push(deregistration); + const networkInfo = C.NetworkInfo.testnet(); + bucket.push(networkInfo); + const cStakeCredential = deregistration.stake_credential(); + bucket.push(cStakeCredential); + const cRewardAddress = C.RewardAddress.new( + networkInfo.network_id(), + cStakeCredential + ); + bucket.push(cRewardAddress); + const address = cRewardAddress.to_address(); + bucket.push(address); + const rewardAddress = address.to_bech32(undefined); const { stakeCredential } = getAddressDetails(rewardAddress); checkAndConsumeHash(stakeCredential!, "Cert", index); if (!this.chain[rewardAddress]?.registeredStake) { throw new Error( - `Stake key is already deregistered. Reward address: ${rewardAddress}`, + `Stake key is already deregistered. Reward address: ${rewardAddress}` ); } certRequests.push({ type: "Deregistration", rewardAddress }); @@ -667,24 +781,36 @@ export class Emulator implements Provider { } case 2: { const delegation = cert.as_stake_delegation()!; - const rewardAddress = C.RewardAddress.new( - C.NetworkInfo.testnet().network_id(), - delegation.stake_credential(), - ).to_address().to_bech32(undefined); - const poolId = delegation.pool_keyhash().to_bech32("pool"); + bucket.push(delegation); + const networkInfo = C.NetworkInfo.testnet(); + bucket.push(networkInfo); + const cStakeCredential = delegation.stake_credential(); + bucket.push(cStakeCredential); + const cRewardAddress = C.RewardAddress.new( + networkInfo.network_id(), + cStakeCredential + ); + bucket.push(cRewardAddress); + const address = cRewardAddress.to_address(); + bucket.push(address); + const rewardAddress = address.to_bech32(undefined); + const poolKeyHash = delegation.pool_keyhash(); + bucket.push(poolKeyHash); + const poolId = poolKeyHash.to_bech32("pool"); const { stakeCredential } = getAddressDetails(rewardAddress); checkAndConsumeHash(stakeCredential!, "Cert", index); if ( !this.chain[rewardAddress]?.registeredStake && - !certRequests.find((request) => - request.type === "Registration" && - request.rewardAddress === rewardAddress + !certRequests.find( + (request) => + request.type === "Registration" && + request.rewardAddress === rewardAddress ) ) { throw new Error( - `Stake key is not registered. Reward address: ${rewardAddress}`, + `Stake key is not registered. Reward address: ${rewardAddress}` ); } certRequests.push({ type: "Delegation", rewardAddress, poolId }); @@ -702,60 +828,65 @@ export class Emulator implements Provider { // Create outputs and consume datum hashes const outputs = (() => { + const outputs = body.outputs(); + bucket.push(outputs); const collected = []; - for (let i = 0; i < body.outputs().len(); i++) { - const output = body.outputs().get(i); + for (let i = 0; i < outputs.len(); i++) { + const output = outputs.get(i); + bucket.push(output); + const transactionHash = C.TransactionHash.from_hex(txHash); + bucket.push(transactionHash); + const index = C.BigNum.from_str(i.toString()); + bucket.push(index); + const transactionInput = C.TransactionInput.new(transactionHash, index); + bucket.push(transactionInput); const unspentOutput = C.TransactionUnspentOutput.new( - C.TransactionInput.new( - C.TransactionHash.from_hex(txHash), - C.BigNum.from_str(i.toString()), - ), - output, + transactionInput, + output ); + bucket.push(unspentOutput); const utxo = coreToUtxo(unspentOutput); if (utxo.datumHash) consumedHashes.add(utxo.datumHash); - collected.push( - { - utxo, - spent: false, - }, - ); + collected.push({ + utxo, + spent: false, + }); } return collected; })(); // Check consumed witnesses - const [extraKeyHash] = keyHashes.filter((keyHash) => - !consumedHashes.has(keyHash) + const [extraKeyHash] = keyHashes.filter( + (keyHash) => !consumedHashes.has(keyHash) ); if (extraKeyHash) { throw new Error(`Extraneous vkey witness. Key hash: ${extraKeyHash}`); } - const [extraNativeHash] = nativeHashes.filter((scriptHash) => - !consumedHashes.has(scriptHash) + const [extraNativeHash] = nativeHashes.filter( + (scriptHash) => !consumedHashes.has(scriptHash) ); if (extraNativeHash) { throw new Error( - `Extraneous native script. Script hash: ${extraNativeHash}`, + `Extraneous native script. Script hash: ${extraNativeHash}` ); } - const [extraPlutusHash] = plutusHashes.filter((scriptHash) => - !consumedHashes.has(scriptHash) + const [extraPlutusHash] = plutusHashes.filter( + (scriptHash) => !consumedHashes.has(scriptHash) ); if (extraPlutusHash) { throw new Error( - `Extraneous plutus script. Script hash: ${extraPlutusHash}`, + `Extraneous plutus script. Script hash: ${extraPlutusHash}` ); } - const [extraDatumHash] = Object.keys(datumTable).filter((datumHash) => - !consumedHashes.has(datumHash) + const [extraDatumHash] = Object.keys(datumTable).filter( + (datumHash) => !consumedHashes.has(datumHash) ); if (extraDatumHash) { throw new Error(`Extraneous plutus data. Datum hash: ${extraDatumHash}`); @@ -863,21 +994,15 @@ export class Emulator implements Provider { "color:white", "color:yellow", "color:white", - "color:yellow", + "color:yellow" ); console.log("\n"); for (const [address, assets] of Object.entries(balances)) { - console.log( - `Address: %c${address}`, - "color:blue", - "\n", - ); + console.log(`Address: %c${address}`, "color:blue", "\n"); for (const [unit, quantity] of Object.entries(assets)) { const barLength = Math.max( - Math.floor( - 60 * (Number(quantity) / Number(totalBalances[unit])), - ), - 1, + Math.floor(60 * (Number(quantity) / Number(totalBalances[unit]))), + 1 ); console.log( `%c${"\u2586".repeat(barLength) + " ".repeat(60 - barLength)}`, @@ -885,12 +1010,10 @@ export class Emulator implements Provider { "", `${unit}:`, quantity, - "", + "" ); } - console.log( - `\n${"\u2581".repeat(60)}\n`, - ); + console.log(`\n${"\u2581".repeat(60)}\n`); } } } diff --git a/dist/src/src/provider/kupmios.ts b/dist/src/src/provider/kupmios.ts index ec0ee7da..7b86431e 100644 --- a/dist/src/src/provider/kupmios.ts +++ b/dist/src/src/provider/kupmios.ts @@ -36,22 +36,23 @@ export class Kupmios implements Provider { }); return new Promise((res, rej) => { - client.addEventListener("message", (msg: MessageEvent) => { - try { - const { result } = JSON.parse(msg.data); + client.addEventListener( + "message", + (msg: MessageEvent) => { + try { + const { result } = JSON.parse(msg.data); - // deno-lint-ignore no-explicit-any - const costModels: any = {}; - Object.keys(result.costModels).forEach((v) => { - const version = v.split(":")[1].toUpperCase(); - const plutusVersion = "Plutus" + version; - costModels[plutusVersion] = result.costModels[v]; - }); - const [memNum, memDenom] = result.prices.memory.split("/"); - const [stepsNum, stepsDenom] = result.prices.steps.split("/"); + // deno-lint-ignore no-explicit-any + const costModels: any = {}; + Object.keys(result.costModels).forEach((v) => { + const version = v.split(":")[1].toUpperCase(); + const plutusVersion = "Plutus" + version; + costModels[plutusVersion] = result.costModels[v]; + }); + const [memNum, memDenom] = result.prices.memory.split("/"); + const [stepsNum, stepsDenom] = result.prices.steps.split("/"); - res( - { + res({ minFeeA: parseInt(result.minFeeCoefficient), minFeeB: parseInt(result.minFeeConstant), maxTxSize: parseInt(result.maxTxSize), @@ -62,19 +63,20 @@ export class Kupmios implements Provider { priceStep: parseInt(stepsNum) / parseInt(stepsDenom), maxTxExMem: BigInt(result.maxExecutionUnitsPerTransaction.memory), maxTxExSteps: BigInt( - result.maxExecutionUnitsPerTransaction.steps, + result.maxExecutionUnitsPerTransaction.steps ), coinsPerUtxoByte: BigInt(result.coinsPerUtxoByte), collateralPercentage: parseInt(result.collateralPercentage), maxCollateralInputs: parseInt(result.maxCollateralInputs), costModels, - }, - ); - client.close(); - } catch (e) { - rej(e); - } - }, { once: true }); + }); + client.close(); + } catch (e) { + rej(e); + } + }, + { once: true } + ); }); } @@ -86,15 +88,14 @@ export class Kupmios implements Provider { const result = await fetch( `${this.kupoUrl}/matches/${queryPredicate}${ isAddress ? "" : "/*" - }?unspent`, - ) - .then((res) => res.json()); + }?unspent` + ).then((res) => res.json()); return this.kupmiosUtxosToUtxos(result); } async getUtxosWithUnit( addressOrCredential: Address | Credential, - unit: Unit, + unit: Unit ): Promise { const isAddress = typeof addressOrCredential === "string"; const queryPredicate = isAddress @@ -106,9 +107,8 @@ export class Kupmios implements Provider { isAddress ? "" : "/*" }?unspent&policy_id=${policyId}${ assetName ? `&asset_name=${assetName}` : "" - }`, - ) - .then((res) => res.json()); + }` + ).then((res) => res.json()); return this.kupmiosUtxosToUtxos(result); } @@ -117,9 +117,8 @@ export class Kupmios implements Provider { const result = await fetch( `${this.kupoUrl}/matches/${policyId}.${ assetName ? `${assetName}` : "*" - }?unspent`, - ) - .then((res) => res.json()); + }?unspent` + ).then((res) => res.json()); const utxos = await this.kupmiosUtxosToUtxos(result); @@ -133,51 +132,59 @@ export class Kupmios implements Provider { async getUtxosByOutRef(outRefs: Array): Promise { const queryHashes = [...new Set(outRefs.map((outRef) => outRef.txHash))]; - const utxos = await Promise.all(queryHashes.map(async (txHash) => { - const result = await fetch( - `${this.kupoUrl}/matches/*@${txHash}?unspent`, - ).then((res) => res.json()); - return this.kupmiosUtxosToUtxos(result); - })); - - return utxos.reduce((acc, utxos) => acc.concat(utxos), []).filter((utxo) => - outRefs.some((outRef) => - utxo.txHash === outRef.txHash && utxo.outputIndex === outRef.outputIndex - ) + const utxos = await Promise.all( + queryHashes.map(async (txHash) => { + const result = await fetch( + `${this.kupoUrl}/matches/*@${txHash}?unspent` + ).then((res) => res.json()); + return this.kupmiosUtxosToUtxos(result); + }) ); + + return utxos + .reduce((acc, utxos) => acc.concat(utxos), []) + .filter((utxo) => + outRefs.some( + (outRef) => + utxo.txHash === outRef.txHash && + utxo.outputIndex === outRef.outputIndex + ) + ); } async getDelegation(rewardAddress: RewardAddress): Promise { const client = await this.ogmiosWsp("Query", { - query: { "delegationsAndRewards": [rewardAddress] }, + query: { delegationsAndRewards: [rewardAddress] }, }); return new Promise((res, rej) => { - client.addEventListener("message", (msg: MessageEvent) => { - try { - const { result } = JSON.parse(msg.data); - const delegation = (result ? Object.values(result)[0] : {}) as { - delegate: string; - rewards: number; - }; - res( - { + client.addEventListener( + "message", + (msg: MessageEvent) => { + try { + const { result } = JSON.parse(msg.data); + const delegation = (result ? Object.values(result)[0] : {}) as { + delegate: string; + rewards: number; + }; + res({ poolId: delegation?.delegate || null, rewards: BigInt(delegation?.rewards || 0), - }, - ); - client.close(); - } catch (e) { - rej(e); - } - }, { once: true }); + }); + client.close(); + } catch (e) { + rej(e); + } + }, + { once: true } + ); }); } async getDatum(datumHash: DatumHash): Promise { - const result = await fetch( - `${this.kupoUrl}/datums/${datumHash}`, - ).then((res) => res.json()); + const result = await fetch(`${this.kupoUrl}/datums/${datumHash}`).then( + (res) => res.json() + ); if (!result || !result.datum) { throw new Error(`No datum found for datum hash: ${datumHash}`); } @@ -188,7 +195,7 @@ export class Kupmios implements Provider { return new Promise((res) => { const confirmation = setInterval(async () => { const isConfirmed = await fetch( - `${this.kupoUrl}/matches/*@${txHash}?unspent`, + `${this.kupoUrl}/matches/*@${txHash}?unspent` ).then((res) => res.json()); if (isConfirmed && isConfirmed.length > 0) { clearInterval(confirmation); @@ -205,80 +212,94 @@ export class Kupmios implements Provider { }); return new Promise((res, rej) => { - client.addEventListener("message", (msg: MessageEvent) => { - try { - const { result } = JSON.parse(msg.data); + client.addEventListener( + "message", + (msg: MessageEvent) => { + try { + const { result } = JSON.parse(msg.data); - if (result.SubmitSuccess) res(result.SubmitSuccess.txId); - else rej(result.SubmitFail); - client.close(); - } catch (e) { - rej(e); - } - }, { once: true }); + if (result.SubmitSuccess) res(result.SubmitSuccess.txId); + else rej(result.SubmitFail); + client.close(); + } catch (e) { + rej(e); + } + }, + { once: true } + ); }); } private kupmiosUtxosToUtxos(utxos: unknown): Promise { - // deno-lint-ignore no-explicit-any - return Promise.all((utxos as any).map(async (utxo: any) => { - return ({ - txHash: utxo.transaction_id, - outputIndex: parseInt(utxo.output_index), - address: utxo.address, - assets: (() => { - const a: Assets = { lovelace: BigInt(utxo.value.coins) }; - Object.keys(utxo.value.assets).forEach((unit) => { - a[unit.replace(".", "")] = BigInt(utxo.value.assets[unit]); - }); - return a; - })(), - datumHash: utxo?.datum_type === "hash" ? utxo.datum_hash : null, - datum: utxo?.datum_type === "inline" - ? await this.getDatum(utxo.datum_hash) - : null, - scriptRef: utxo.script_hash && - (await (async () => { - const { - script, - language, - } = await fetch( - `${this.kupoUrl}/scripts/${utxo.script_hash}`, - ).then((res) => res.json()); + return Promise.all( + // deno-lint-ignore no-explicit-any + (utxos as any).map(async (utxo: any) => { + return { + txHash: utxo.transaction_id, + outputIndex: parseInt(utxo.output_index), + address: utxo.address, + assets: (() => { + const a: Assets = { lovelace: BigInt(utxo.value.coins) }; + Object.keys(utxo.value.assets).forEach((unit) => { + a[unit.replace(".", "")] = BigInt(utxo.value.assets[unit]); + }); + return a; + })(), + datumHash: utxo?.datum_type === "hash" ? utxo.datum_hash : null, + datum: + utxo?.datum_type === "inline" + ? await this.getDatum(utxo.datum_hash) + : null, + scriptRef: + utxo.script_hash && + (await (async () => { + const { script, language } = await fetch( + `${this.kupoUrl}/scripts/${utxo.script_hash}` + ).then((res) => res.json()); - if (language === "native") { - return { type: "Native", script }; - } else if (language === "plutus:v1") { - return { - type: "PlutusV1", - script: toHex(C.PlutusScript.new(fromHex(script)).to_bytes()), - }; - } else if (language === "plutus:v2") { - return { - type: "PlutusV2", - script: toHex(C.PlutusScript.new(fromHex(script)).to_bytes()), - }; - } - })()), - }) as UTxO; - })); + if (language === "native") { + return { type: "Native", script }; + } else if (language === "plutus:v1") { + const plutusScript = C.PlutusScript.new(fromHex(script)); + const scriptBytes = plutusScript.to_bytes(); + plutusScript.free(); + return { + type: "PlutusV1", + script: toHex(scriptBytes), + }; + } else if (language === "plutus:v2") { + const plutusScript = C.PlutusScript.new(fromHex(script)); + const scriptBytes = plutusScript.to_bytes(); + plutusScript.free(); + + return { + type: "PlutusV2", + script: toHex(scriptBytes), + }; + } + })()), + } as UTxO; + }) + ); } private async ogmiosWsp( methodname: string, - args: unknown, + args: unknown ): Promise { const client = new WebSocket(this.ogmiosUrl); await new Promise((res) => { client.addEventListener("open", () => res(1), { once: true }); }); - client.send(JSON.stringify({ - type: "jsonwsp/request", - version: "1.0", - servicename: "ogmios", - methodname, - args, - })); + client.send( + JSON.stringify({ + type: "jsonwsp/request", + version: "1.0", + servicename: "ogmios", + methodname, + args, + }) + ); return client; } } diff --git a/dist/src/src/provider/maestro.ts b/dist/src/src/provider/maestro.ts index 3e809a9b..0fd0aea1 100644 --- a/dist/src/src/provider/maestro.ts +++ b/dist/src/src/provider/maestro.ts @@ -19,22 +19,21 @@ import { } from "../types/mod.js"; import packageJson from "../../package.js"; -export type MaestroSupportedNetworks = "Mainnet" | "Preprod" | "Preview" +export type MaestroSupportedNetworks = "Mainnet" | "Preprod" | "Preview"; export interface MaestroConfig { - network: MaestroSupportedNetworks, - apiKey: string, - turboSubmit?: boolean // Read about paid turbo transaction submission feature at https://docs-v1.gomaestro.org/docs/Dapp%20Platform/Turbo%20Transaction. + network: MaestroSupportedNetworks; + apiKey: string; + turboSubmit?: boolean; // Read about paid turbo transaction submission feature at https://docs-v1.gomaestro.org/docs/Dapp%20Platform/Turbo%20Transaction. } export class Maestro implements Provider { - url: string; apiKey: string; turboSubmit: boolean; constructor({ network, apiKey, turboSubmit = false }: MaestroConfig) { - this.url = `https://${network}.gomaestro-api.org/v1` + this.url = `https://${network}.gomaestro-api.org/v1`; this.apiKey = apiKey; this.turboSubmit = turboSubmit; } @@ -47,21 +46,26 @@ export class Maestro implements Provider { // Decimal numbers in Maestro are given as ratio of two numbers represented by string of format "firstNumber/secondNumber". const decimalFromRationalString = (str: string): number => { const forwardSlashIndex = str.indexOf("/"); - return parseInt(str.slice(0, forwardSlashIndex)) / parseInt(str.slice(forwardSlashIndex + 1)); - } + return ( + parseInt(str.slice(0, forwardSlashIndex)) / + parseInt(str.slice(forwardSlashIndex + 1)) + ); + }; // To rename keys in an object by the given key-map. // deno-lint-ignore no-explicit-any const renameKeysAndSort = (obj: any, newKeys: any) => { - const entries = Object.keys(obj).sort().map((key) => { - const newKey = newKeys[key] || key; - return { - [newKey]: Object.fromEntries( - Object.entries(obj[key]).sort(([k, _v], [k2, _v2]) => - k.localeCompare(k2) + const entries = Object.keys(obj) + .sort() + .map((key) => { + const newKey = newKeys[key] || key; + return { + [newKey]: Object.fromEntries( + Object.entries(obj[key]).sort(([k, _v], [k2, _v2]) => + k.localeCompare(k2) + ) ), - ), - }; - }); + }; + }); return Object.assign({}, ...entries); }; return { @@ -85,62 +89,76 @@ export class Maestro implements Provider { }; } - async getUtxos(addressOrCredential: Address | Credential): Promise { + private async getUtxosInternal( + addressOrCredential: Address | Credential, + unit?: Unit + ): Promise { const queryPredicate = (() => { - if (typeof addressOrCredential === "string") return "/addresses/" + addressOrCredential; - let credentialBech32Query = "/addresses/cred/" - credentialBech32Query += addressOrCredential.type === "Key" - ? C.Ed25519KeyHash.from_hex(addressOrCredential.hash).to_bech32( - "addr_vkh", - ) - : C.ScriptHash.from_hex(addressOrCredential.hash).to_bech32( - "addr_shared_vkh", - ); + if (typeof addressOrCredential === "string") { + return "/addresses/" + addressOrCredential; + } + const hash = + addressOrCredential.type == "Key" + ? C.Ed25519KeyHash.from_hex(addressOrCredential.hash) + : C.ScriptHash.from_hex(addressOrCredential.hash); + let credentialBech32Query = "/addresses/cred/"; + credentialBech32Query += + addressOrCredential.type === "Key" + ? hash.to_bech32("addr_vkh") + : hash.to_bech32("addr_shared_vkh"); + + hash.free(); + return credentialBech32Query; })(); - let result: MaestroUtxos = []; - let nextCursor = null; - while (true) { - const appendCursorString = nextCursor === null ? "" : `&cursor=${nextCursor}` - const response = await fetch( - `${this.url}${queryPredicate}/utxos?count=100${appendCursorString}`, - { headers: this.commonHeaders() }, - ); - const pageResult = await response.json(); - if (!response.ok) { - throw new Error("Could not fetch UTxOs from Maestro. Received status code: " + response.status); - } - nextCursor = pageResult.next_cursor; - result = result.concat(pageResult.data as MaestroUtxos); - if (nextCursor == null) break; - } + const qparams = new URLSearchParams({ + count: "100", + ...(unit && { asset: unit }), + }); + const result: MaestroUtxos = await this.getAllPagesData( + async (qry: string) => + await fetch(qry, { headers: this.commonHeaders() }), + `${this.url}${queryPredicate}/utxos`, + qparams, + "Location: getUtxosInternal. Error: Could not fetch UTxOs from Maestro" + ); return result.map(this.maestroUtxoToUtxo); } - async getUtxosWithUnit( + getUtxos(addressOrCredential: Address | Credential): Promise { + return this.getUtxosInternal(addressOrCredential); + } + + getUtxosWithUnit( addressOrCredential: Address | Credential, - unit: Unit, + unit: Unit ): Promise { - const utxos = await this.getUtxos(addressOrCredential); - return utxos.filter((utxo) => utxo.assets[unit]); + return this.getUtxosInternal(addressOrCredential, unit); } async getUtxoByUnit(unit: Unit): Promise { const timestampedAddressesResponse = await fetch( `${this.url}/assets/${unit}/addresses?count=2`, - { headers: this.commonHeaders() }, + { headers: this.commonHeaders() } ); - const timestampedAddresses = await timestampedAddressesResponse.json() + const timestampedAddresses = await timestampedAddressesResponse.json(); if (!timestampedAddressesResponse.ok) { - if (timestampedAddresses.message) throw new Error(timestampedAddresses.message) - throw new Error("Couldn't perform query. Received status code: " + timestampedAddressesResponse.status) + if (timestampedAddresses.message) { + throw new Error(timestampedAddresses.message); + } + throw new Error( + "Location: getUtxoByUnit. Error: Couldn't perform query. Received status code: " + + timestampedAddressesResponse.status + ); } const addressesWithAmount = timestampedAddresses.data; if (addressesWithAmount.length === 0) { - throw new Error("Unit not found."); + throw new Error("Location: getUtxoByUnit. Error: Unit not found."); } if (addressesWithAmount.length > 1) { - throw new Error("Unit needs to be an NFT or only held by one address."); + throw new Error( + "Location: getUtxoByUnit. Error: Unit needs to be an NFT or only held by one address." + ); } const address = addressesWithAmount[0].address; @@ -148,30 +166,40 @@ export class Maestro implements Provider { const utxos = await this.getUtxosWithUnit(address, unit); if (utxos.length > 1) { - throw new Error("Unit needs to be an NFT or only held by one address."); + throw new Error( + "Location: getUtxoByUnit. Error: Unit needs to be an NFT or only held by one address." + ); } return utxos[0]; } async getUtxosByOutRef(outRefs: OutRef[]): Promise { - const response = await fetch(`${this.url}/transactions/outputs`, { - method: "POST", - headers: { - 'Content-Type': 'application/json', - ...this.commonHeaders() - }, - body: JSON.stringify(outRefs.map(({ txHash, outputIndex }) => `${txHash}#${outputIndex}`)), - }); - if (!response.ok) return []; - const utxos = (await response.json()).data; - return utxos.map(this.maestroUtxoToUtxo) + const qry = `${this.url}/transactions/outputs`; + const body = JSON.stringify( + outRefs.map(({ txHash, outputIndex }) => `${txHash}#${outputIndex}`) + ); + const utxos = await this.getAllPagesData( + async (qry: string) => + await fetch(qry, { + method: "POST", + headers: { + "Content-Type": "application/json", + ...this.commonHeaders(), + }, + body: body, + }), + qry, + new URLSearchParams({}), + "Location: getUtxosByOutRef. Error: Could not fetch UTxOs by references from Maestro" + ); + return utxos.map(this.maestroUtxoToUtxo); } async getDelegation(rewardAddress: RewardAddress): Promise { const timestampedResultResponse = await fetch( `${this.url}/accounts/${rewardAddress}`, - { headers: this.commonHeaders() }, + { headers: this.commonHeaders() } ); if (!timestampedResultResponse.ok) { return { poolId: null, rewards: 0n }; @@ -189,13 +217,17 @@ export class Maestro implements Provider { `${this.url}/datum/${datumHash}`, { headers: this.commonHeaders(), - }, + } ); if (!timestampedResultResponse.ok) { - if (timestampedResultResponse.status === 404) + if (timestampedResultResponse.status === 404) { throw new Error(`No datum found for datum hash: ${datumHash}`); - else - throw new Error("Couldn't successfully perform query. Received status code: " + timestampedResultResponse.status); + } else { + throw new Error( + "Location: getDatum. Error: Couldn't successfully perform query. Received status code: " + + timestampedResultResponse.status + ); + } } const timestampedResult = await timestampedResultResponse.json(); return timestampedResult.data.bytes; @@ -208,10 +240,10 @@ export class Maestro implements Provider { `${this.url}/transactions/${txHash}/cbor`, { headers: this.commonHeaders(), - }, + } ); if (isConfirmedResponse.ok) { - await isConfirmedResponse.json() + await isConfirmedResponse.json(); clearInterval(confirmation); await new Promise((res) => setTimeout(() => res(1), 1000)); return res(true); @@ -222,12 +254,12 @@ export class Maestro implements Provider { async submitTx(tx: Transaction): Promise { let queryUrl = `${this.url}/txmanager`; - queryUrl += this.turboSubmit ? '/turbosubmit' : '' + queryUrl += this.turboSubmit ? "/turbosubmit" : ""; const response = await fetch(queryUrl, { method: "POST", headers: { "Content-Type": "application/cbor", - "Accept": "text/plain", + Accept: "text/plain", ...this.commonHeaders(), }, body: fromHex(tx), @@ -235,7 +267,12 @@ export class Maestro implements Provider { const result = await response.text(); if (!response.ok) { if (response.status === 400) throw new Error(result); - else throw new Error("Could not submit transaction. Received status code: " + response.status); + else { + throw new Error( + "Could not submit transaction. Received status code: " + + response.status + ); + } } return result; } @@ -257,19 +294,49 @@ export class Maestro implements Provider { })(), address: result.address, datumHash: result.datum - ? result.datum.type == "inline" ? undefined : result.datum.hash + ? result.datum.type == "inline" + ? undefined + : result.datum.hash : undefined, datum: result.datum?.bytes, scriptRef: result.reference_script - ? result.reference_script.type == "native" ? undefined : { - type: result.reference_script.type == "plutusv1" - ? "PlutusV1" - : "PlutusV2", - script: applyDoubleCborEncoding(result.reference_script.bytes!), - } + ? result.reference_script.type == "native" + ? undefined + : { + type: + result.reference_script.type == "plutusv1" + ? "PlutusV1" + : "PlutusV2", + script: applyDoubleCborEncoding(result.reference_script.bytes!), + } : undefined, }; } + private async getAllPagesData( + getResponse: (qry: string) => Promise, + qry: string, + paramsGiven: URLSearchParams, + errorMsg: string + ): Promise> { + let nextCursor = null; + let result: Array = []; + while (true) { + if (nextCursor !== null) { + paramsGiven.set("cursor", nextCursor); + } + const response = await getResponse(`${qry}?` + paramsGiven); + const pageResult = await response.json(); + if (!response.ok) { + throw new Error( + `${errorMsg}. Received status code: ${response.status}` + ); + } + nextCursor = pageResult.next_cursor; + result = result.concat(pageResult.data as Array); + if (nextCursor == null) break; + } + return result; + } } type MaestroDatumOptionType = "hash" | "inline"; diff --git a/dist/src/src/utils/cml.ts b/dist/src/src/utils/cml.ts new file mode 100644 index 00000000..9c600b47 --- /dev/null +++ b/dist/src/src/utils/cml.ts @@ -0,0 +1,298 @@ +import { TransactionBuilder } from "../core/libs/cardano_multiplatform_lib/nodejs/cardano_multiplatform_lib.generated.js"; +import { + Address, + Assets, + C, + CertificateValidator, + Datum, + Lucid, + MintingPolicy, + OutputData, + PoolParams, + Redeemer, + RewardAddress, + SpendingValidator, + Tx, + WithdrawalValidator, + applyDoubleCborEncoding, + assetsToValue, + fromHex, + networkToId, + toScriptRef, +} from "../mod.js"; +import { FreeableBucket, Freeables } from "./freeable.js"; + +export function getScriptWitness( + redeemer: Redeemer, + datum?: Datum, +): C.ScriptWitness { + const bucket: FreeableBucket = []; + try { + const plutusRedeemer = C.PlutusData.from_bytes(fromHex(redeemer!)); + const plutusData = datum + ? C.PlutusData.from_bytes(fromHex(datum)) + : undefined; + const plutusWitness = C.PlutusWitness.new( + plutusRedeemer, + plutusData, + undefined, + ); + // We shouldn't free plutusData as it is an Option + bucket.push(plutusRedeemer, plutusWitness); + return C.ScriptWitness.new_plutus_witness(plutusWitness); + } finally { + Freeables.free(...bucket); + } +} + +export function getStakeCredential(hash: string, type: "Key" | "Script") { + if (type === "Key") { + const keyHash = C.Ed25519KeyHash.from_bytes(fromHex(hash)); + const credential = C.StakeCredential.from_keyhash(keyHash); + Freeables.free(keyHash); + return credential; + } + const scriptHash = C.ScriptHash.from_bytes(fromHex(hash)); + const credential = C.StakeCredential.from_scripthash(scriptHash); + Freeables.free(scriptHash); + return credential; +} + +export async function createPoolRegistration( + poolParams: PoolParams, + lucid: Lucid, +): Promise { + const bucket: FreeableBucket = []; + try { + const poolOwners = C.Ed25519KeyHashes.new(); + bucket.push(poolOwners); + poolParams.owners.forEach((owner) => { + const { stakeCredential } = lucid.utils.getAddressDetails(owner); + if (stakeCredential?.type === "Key") { + const keyHash = C.Ed25519KeyHash.from_hex(stakeCredential.hash); + poolOwners.add(keyHash); + bucket.push(keyHash); + } else throw new Error("Only key hashes allowed for pool owners."); + }); + + const metadata = poolParams.metadataUrl + ? await fetch(poolParams.metadataUrl).then((res) => res.arrayBuffer()) + : null; + + const metadataHash = metadata + ? C.PoolMetadataHash.from_bytes( + C.hash_blake2b256(new Uint8Array(metadata)), + ) + : null; + + const relays = C.Relays.new(); + bucket.push(metadataHash, relays); + poolParams.relays.forEach((relay) => { + switch (relay.type) { + case "SingleHostIp": { + const ipV4 = relay.ipV4 + ? C.Ipv4.new( + new Uint8Array(relay.ipV4.split(".").map((b) => parseInt(b))), + ) + : undefined; + const ipV6 = relay.ipV6 + ? C.Ipv6.new(fromHex(relay.ipV6.replaceAll(":", ""))) + : undefined; + const host = C.SingleHostAddr.new(relay.port, ipV4, ipV6); + const newRelay = C.Relay.new_single_host_addr(host); + //We shouldn't free ipV4 and ipV6 as they are optionals + bucket.push(host, newRelay); + relays.add(newRelay); + break; + } + case "SingleHostDomainName": { + const record = C.DNSRecordAorAAAA.new(relay.domainName!); + const host = C.SingleHostName.new(relay.port, record); + const newRelay = C.Relay.new_single_host_name(host); + bucket.push(record, host, newRelay); + relays.add(newRelay); + break; + } + case "MultiHost": { + const record = C.DNSRecordSRV.new(relay.domainName!); + const host = C.MultiHostName.new(record); + const newRelay = C.Relay.new_multi_host_name(host); + bucket.push(record, host, newRelay); + relays.add(newRelay); + break; + } + } + }); + + const operator = C.Ed25519KeyHash.from_bech32(poolParams.poolId); + const vrfKeyHash = C.VRFKeyHash.from_hex(poolParams.vrfKeyHash); + const pledge = C.BigNum.from_str(poolParams.pledge.toString()); + const cost = C.BigNum.from_str(poolParams.cost.toString()); + + const margin = C.UnitInterval.from_float(poolParams.margin); + const addr = addressFromWithNetworkCheck(poolParams.rewardAddress, lucid); + const rewardAddress = C.RewardAddress.from_address(addr); + const url = C.Url.new(poolParams.metadataUrl!); + const poolMetadata = metadataHash + ? C.PoolMetadata.new(url, metadataHash) + : undefined; + bucket.push( + operator, + vrfKeyHash, + pledge, + cost, + margin, + addr, + rewardAddress, + url, + poolMetadata, + ); + + const params = C.PoolParams.new( + operator, + vrfKeyHash, + pledge, + cost, + margin, + rewardAddress!, + poolOwners, + relays, + poolMetadata, + ); + + const poolRegistration = C.PoolRegistration.new(params); + return poolRegistration; + } finally { + Freeables.free(...bucket); + } +} + +export function attachScript( + tx: Tx, + { + type, + script, + }: + | SpendingValidator + | MintingPolicy + | CertificateValidator + | WithdrawalValidator, +) { + if (type === "Native") { + const nativeScript = C.NativeScript.from_bytes(fromHex(script)); + tx.txBuilder.add_native_script(nativeScript); + Freeables.free(nativeScript); + return; + } else if (type === "PlutusV1") { + const plutusScript = C.PlutusScript.from_bytes( + fromHex(applyDoubleCborEncoding(script)), + ); + tx.txBuilder.add_plutus_script(plutusScript); + Freeables.free(plutusScript); + return; + } else if (type === "PlutusV2") { + const plutusScript = C.PlutusScript.from_bytes( + fromHex(applyDoubleCborEncoding(script)), + ); + tx.txBuilder.add_plutus_v2_script(plutusScript); + Freeables.free(plutusScript); + return; + } + throw new Error("No variant matched."); +} + +export function addressFromWithNetworkCheck( + address: Address | RewardAddress, + lucid: Lucid, +): C.Address { + const { type, networkId } = lucid.utils.getAddressDetails(address); + + const actualNetworkId = networkToId(lucid.network); + if (networkId !== actualNetworkId) { + throw new Error( + `Invalid address: Expected address with network id ${actualNetworkId}, but got ${networkId}`, + ); + } + if (type === "Byron") { + const byron = C.ByronAddress.from_base58(address); + const addr = byron.to_address(); + byron.free(); + return addr; + } + return C.Address.from_bech32(address); +} + +export function getDatumFromOutputData(outputData?: OutputData): { + datum?: C.Datum | undefined; + plutusData?: C.PlutusData; +} { + if (outputData?.hash) { + const hash = C.DataHash.from_hex(outputData.hash); + const datum = C.Datum.new_data_hash(hash); + hash.free(); + return { datum }; + } else if (outputData?.asHash) { + const plutusData = C.PlutusData.from_bytes(fromHex(outputData.asHash)); + const dataHash = C.hash_plutus_data(plutusData); + const datum = C.Datum.new_data_hash(dataHash); + dataHash.free(); + return { plutusData, datum }; + } else if (outputData?.inline) { + const plutusData = C.PlutusData.from_bytes(fromHex(outputData.inline)); + const data = C.Data.new(plutusData); + const datum = C.Datum.new_data(data); + Freeables.free(plutusData, data); + return { datum }; + } else { + return {}; + } +} + +export function createOutput({ + bucket, + address, + assets, + outputData, + lucid, + txBuilder, +}: { + bucket: FreeableBucket; + address: Address; + assets: Assets; + outputData: OutputData; + lucid: Lucid; + txBuilder: TransactionBuilder; +}) { + const addr = addressFromWithNetworkCheck(address, lucid); + const value = assetsToValue(assets); + const output = C.TransactionOutput.new(addr, value); + bucket.push(output, addr, value); + + if (outputData.hash) { + const dataHash = C.DataHash.from_hex(outputData.hash); + const datum = C.Datum.new_data_hash(dataHash); + bucket.push(dataHash, datum); + output.set_datum(datum); + } else if (outputData.asHash) { + const plutusData = C.PlutusData.from_bytes(fromHex(outputData.asHash)); + const dataHash = C.hash_plutus_data(plutusData); + const datum = C.Datum.new_data_hash(dataHash); + bucket.push(plutusData, dataHash, datum); + output.set_datum(datum); + txBuilder.add_plutus_data(plutusData); + } else if (outputData.inline) { + const plutusData = C.PlutusData.from_bytes(fromHex(outputData.inline)); + const data = C.Data.new(plutusData); + const datum = C.Datum.new_data(data); + bucket.push(plutusData, data, datum); + output.set_datum(datum); + } + + const script = outputData.scriptRef; + if (script) { + const scriptRef = toScriptRef(script); + bucket.push(scriptRef); + output.set_script_ref(toScriptRef(script)); + } + return output; +} diff --git a/dist/src/src/utils/cost_model.ts b/dist/src/src/utils/cost_model.ts index 124fea55..03d08f72 100644 --- a/dist/src/src/utils/cost_model.ts +++ b/dist/src/src/utils/cost_model.ts @@ -1,25 +1,45 @@ import { C } from "../core/mod.js"; import { CostModels } from "../mod.js"; import { ProtocolParameters } from "../types/types.js"; +import { Freeable, Freeables } from "./freeable.js"; export function createCostModels(costModels: CostModels): C.Costmdls { - const costmdls = C.Costmdls.new(); + const bucket: Freeable[] = []; + try { + const costmdls = C.Costmdls.new(); - // add plutus v1 - const costmdlV1 = C.CostModel.new(); - Object.values(costModels.PlutusV1).forEach((cost, index) => { - costmdlV1.set(index, C.Int.new(C.BigNum.from_str(cost.toString()))); - }); - costmdls.insert(C.Language.new_plutus_v1(), costmdlV1); + // add plutus v1 + const costmdlV1 = C.CostModel.new(); + bucket.push(costmdlV1); + Object.values(costModels.PlutusV1).forEach((cost, index) => { + const bigNumVal = C.BigNum.from_str(cost.toString()); + bucket.push(bigNumVal); + const intVal = C.Int.new(bigNumVal); + bucket.push(intVal); + costmdlV1.set(index, intVal); + }); + const plutusV1 = C.Language.new_plutus_v1(); + bucket.push(plutusV1); + costmdls.insert(plutusV1, costmdlV1); - // add plutus v2 - const costmdlV2 = C.CostModel.new_plutus_v2(); - Object.values(costModels.PlutusV2 || []).forEach((cost, index) => { - costmdlV2.set(index, C.Int.new(C.BigNum.from_str(cost.toString()))); - }); - costmdls.insert(C.Language.new_plutus_v2(), costmdlV2); + // add plutus v2 + const costmdlV2 = C.CostModel.new_plutus_v2(); + bucket.push(costmdlV2); + Object.values(costModels.PlutusV2 || []).forEach((cost, index) => { + const bigNumVal = C.BigNum.from_str(cost.toString()); + bucket.push(bigNumVal); + const intVal = C.Int.new(bigNumVal); + bucket.push(intVal); + costmdlV2.set(index, intVal); + }); + const plutusV2 = C.Language.new_plutus_v2(); + bucket.push(plutusV2); + costmdls.insert(plutusV2, costmdlV2); - return costmdls; + return costmdls; + } finally { + Freeables.free(...bucket); + } } export const PROTOCOL_PARAMETERS_DEFAULT: ProtocolParameters = { diff --git a/dist/src/src/utils/freeable.ts b/dist/src/src/utils/freeable.ts new file mode 100644 index 00000000..99b2d215 --- /dev/null +++ b/dist/src/src/utils/freeable.ts @@ -0,0 +1,33 @@ +/** + * These types and classes are used to help with freeing memory. + * Objects passed from the WASM to JS (Objects from Rust libraries, for example) are not freed automatically, or at least inconsistently. + * This can lead to memory leaks. + * In order to free these objects, we need to call the `free()` method on them. These types make it easier. + */ + +/** This interface represents WASM objects that can and need to be freed. */ +export interface Freeable { + free(): void; +} + +export type FreeableBucket = Array; + +/** This class makes it easier to free large sets of memory. It can be used like this: + * ```ts + * const bucket: FreeableBucket = []; + * try { + * const rustObject = C.some_rust_object(); + * bucket.push(rustObject); + * ... + * } finally { + * Freeables.free(...bucket); + * } + * ``` + */ +export abstract class Freeables { + static free(...bucket: FreeableBucket) { + bucket.forEach((freeable) => { + freeable?.free(); + }); + } +} diff --git a/dist/src/src/utils/mod.ts b/dist/src/src/utils/mod.ts index 8e127d1d..04fe4189 100644 --- a/dist/src/src/utils/mod.ts +++ b/dist/src/src/utils/mod.ts @@ -1,3 +1,5 @@ export * from "./cost_model.js"; export * from "./utils.js"; export * from "./merkle_tree.js"; +export * from "./cml.js"; +export * from "./freeable.js"; diff --git a/dist/src/src/utils/transaction_builder_config.ts b/dist/src/src/utils/transaction_builder_config.ts new file mode 100644 index 00000000..ca857b0a --- /dev/null +++ b/dist/src/src/utils/transaction_builder_config.ts @@ -0,0 +1,108 @@ +import { C, SlotConfig } from "../mod.js"; +import { ProtocolParameters } from "../types/mod.js"; +import { createCostModels } from "./cost_model.js"; +import { Freeable, Freeables } from "./freeable.js"; + +export function getTransactionBuilderConfig( + protocolParameters: ProtocolParameters, + slotConfig: SlotConfig, + blockfrostConfig: { + url?: string; + projectId?: string; + }, +) { + const bucket: Freeable[] = []; + let builderA = C.TransactionBuilderConfigBuilder.new(); + + const coinsPerUtxoByte = C.BigNum.from_str( + protocolParameters.coinsPerUtxoByte.toString(), + ); + bucket.push(coinsPerUtxoByte); + let builderB = builderA.coins_per_utxo_byte(coinsPerUtxoByte); + builderA.free(); + + const minFeeA = C.BigNum.from_str(protocolParameters.minFeeA.toString()); + bucket.push(minFeeA); + const minFeeB = C.BigNum.from_str(protocolParameters.minFeeB.toString()); + bucket.push(minFeeB); + const linearFee = C.LinearFee.new(minFeeA, minFeeB); + bucket.push(linearFee); + builderA = builderB.fee_algo(linearFee); + builderB.free(); + + const keyDeposit = C.BigNum.from_str( + protocolParameters.keyDeposit.toString(), + ); + bucket.push(keyDeposit); + builderB = builderA.key_deposit(keyDeposit); + builderA.free(); + + const poolDeposit = C.BigNum.from_str( + protocolParameters.poolDeposit.toString(), + ); + bucket.push(poolDeposit); + builderA = builderB.pool_deposit(poolDeposit); + builderB.free(); + + builderB = builderA.max_tx_size(protocolParameters.maxTxSize); + builderA.free(); + + builderA = builderB.max_value_size(protocolParameters.maxValSize); + builderB.free(); + + builderB = builderA.collateral_percentage( + protocolParameters.collateralPercentage, + ); + builderA.free(); + + builderA = builderB.max_collateral_inputs( + protocolParameters.maxCollateralInputs, + ); + builderB.free(); + + const maxTxExMem = C.BigNum.from_str( + protocolParameters.maxTxExMem.toString(), + ); + bucket.push(maxTxExMem); + const maxTxExSteps = C.BigNum.from_str( + protocolParameters.maxTxExSteps.toString(), + ); + bucket.push(maxTxExSteps); + const exUnits = C.ExUnits.new(maxTxExMem, maxTxExSteps); + bucket.push(exUnits); + builderB = builderA.max_tx_ex_units(exUnits); + builderA.free(); + + const exUnitPrices = C.ExUnitPrices.from_float( + protocolParameters.priceMem, + protocolParameters.priceStep, + ); + bucket.push(exUnitPrices); + builderA = builderB.ex_unit_prices(exUnitPrices); + builderB.free(); + + const zeroTime = C.BigNum.from_str(slotConfig.zeroTime.toString()); + bucket.push(zeroTime); + const zeroSlot = C.BigNum.from_str(slotConfig.zeroSlot.toString()); + bucket.push(zeroSlot); + builderB = builderA.slot_config(zeroTime, zeroSlot, slotConfig.slotLength); + builderA.free(); + + const blockfrost = C.Blockfrost.new( + blockfrostConfig?.url ?? "" + "utils/tx/evaulate", + blockfrostConfig?.projectId ?? "", + ); + bucket.push(blockfrost); + builderA = builderB.blockfrost(blockfrost); + builderB.free(); + + const costModels = createCostModels(protocolParameters.costModels); + bucket.push(costModels); + builderB = builderA.costmdls(costModels); + + const config = builderB.build(); + builderB.free(); + Freeables.free(...bucket); + + return config; +} diff --git a/dist/src/src/utils/utils.ts b/dist/src/src/utils/utils.ts index 366e603f..183133a1 100644 --- a/dist/src/src/utils/utils.ts +++ b/dist/src/src/utils/utils.ts @@ -40,6 +40,7 @@ import { unixTimeToEnclosingSlot, } from "../plutus/time.js"; import { Data } from "../plutus/data.js"; +import { FreeableBucket, Freeables } from "./freeable.js"; export class Utils { private lucid: Lucid; @@ -49,120 +50,215 @@ export class Utils { validatorToAddress( validator: SpendingValidator, - stakeCredential?: Credential + stakeCredential?: Credential, ): Address { - const validatorHash = this.validatorToScriptHash(validator); - if (stakeCredential) { - return C.BaseAddress.new( - networkToId(this.lucid.network), - C.StakeCredential.from_scripthash(C.ScriptHash.from_hex(validatorHash)), - stakeCredential.type === "Key" - ? C.StakeCredential.from_keyhash( - C.Ed25519KeyHash.from_hex(stakeCredential.hash) - ) - : C.StakeCredential.from_scripthash( - C.ScriptHash.from_hex(stakeCredential.hash) - ) - ) - .to_address() - .to_bech32(undefined); - } else { - return C.EnterpriseAddress.new( - networkToId(this.lucid.network), - C.StakeCredential.from_scripthash(C.ScriptHash.from_hex(validatorHash)) - ) - .to_address() - .to_bech32(undefined); + const bucket: FreeableBucket = []; + const networkId = networkToId(this.lucid.network); + try { + const validatorHash = this.validatorToScriptHash(validator); + if (stakeCredential) { + const validatorScriptHash = C.ScriptHash.from_hex(validatorHash); + bucket.push(validatorScriptHash); + const paymentPart = + C.StakeCredential.from_scripthash(validatorScriptHash); + bucket.push(paymentPart); + let stakePart: C.StakeCredential; + if (stakeCredential.type === "Key") { + const keyHash = C.Ed25519KeyHash.from_hex(stakeCredential.hash); + stakePart = C.StakeCredential.from_keyhash(keyHash); + keyHash.free(); + } else { + const scriptHash = C.ScriptHash.from_hex(stakeCredential.hash); + stakePart = C.StakeCredential.from_scripthash(scriptHash); + scriptHash.free(); + } + bucket.push(stakePart); + const baseAddress = C.BaseAddress.new( + networkId, + paymentPart, + stakePart, + ); + bucket.push(baseAddress); + const address = baseAddress.to_address(); + bucket.push(address); + + return address.to_bech32(undefined); + } else { + const validatorScriptHash = C.ScriptHash.from_hex(validatorHash); + bucket.push(validatorScriptHash); + + const paymentPart = + C.StakeCredential.from_scripthash(validatorScriptHash); + bucket.push(paymentPart); + const enterpriseAddress = C.EnterpriseAddress.new( + networkId, + paymentPart, + ); + bucket.push(enterpriseAddress); + const address = enterpriseAddress.to_address(); + bucket.push(address); + + return address.to_bech32(undefined); + } + } finally { + Freeables.free(...bucket); } } credentialToAddress( paymentCredential: Credential, - stakeCredential?: Credential + stakeCredential?: Credential, ): Address { - if (stakeCredential) { - return C.BaseAddress.new( - networkToId(this.lucid.network), - paymentCredential.type === "Key" - ? C.StakeCredential.from_keyhash( - C.Ed25519KeyHash.from_hex(paymentCredential.hash) - ) - : C.StakeCredential.from_scripthash( - C.ScriptHash.from_hex(paymentCredential.hash) - ), - stakeCredential.type === "Key" - ? C.StakeCredential.from_keyhash( - C.Ed25519KeyHash.from_hex(stakeCredential.hash) - ) - : C.StakeCredential.from_scripthash( - C.ScriptHash.from_hex(stakeCredential.hash) - ) - ) - .to_address() - .to_bech32(undefined); - } else { - return C.EnterpriseAddress.new( - networkToId(this.lucid.network), - paymentCredential.type === "Key" - ? C.StakeCredential.from_keyhash( - C.Ed25519KeyHash.from_hex(paymentCredential.hash) - ) - : C.StakeCredential.from_scripthash( - C.ScriptHash.from_hex(paymentCredential.hash) - ) - ) - .to_address() - .to_bech32(undefined); + const networkId = networkToId(this.lucid.network); + const bucket: FreeableBucket = []; + try { + if (stakeCredential) { + let paymentPart: C.StakeCredential; + let stakePart: C.StakeCredential; + if (paymentCredential.type === "Key") { + const keyHash = C.Ed25519KeyHash.from_hex(paymentCredential.hash); + bucket.push(keyHash); + paymentPart = C.StakeCredential.from_keyhash(keyHash); + } else { + const scriptHash = C.ScriptHash.from_hex(paymentCredential.hash); + bucket.push(scriptHash); + paymentPart = C.StakeCredential.from_scripthash(scriptHash); + } + bucket.push(paymentPart); + if (stakeCredential.type === "Key") { + const keyHash = C.Ed25519KeyHash.from_hex(stakeCredential.hash); + bucket.push(keyHash); + stakePart = C.StakeCredential.from_keyhash(keyHash); + } else { + const scriptHash = C.ScriptHash.from_hex(stakeCredential.hash); + bucket.push(scriptHash); + stakePart = C.StakeCredential.from_scripthash(scriptHash); + } + bucket.push(stakePart); + + const baseAddress = C.BaseAddress.new( + networkId, + paymentPart, + stakePart, + ); + bucket.push(baseAddress); + const address = baseAddress.to_address(); + bucket.push(address); + + return address.to_bech32(undefined); + } else { + let paymentPart: C.StakeCredential; + if (paymentCredential.type === "Key") { + const keyHash = C.Ed25519KeyHash.from_hex(paymentCredential.hash); + bucket.push(keyHash); + paymentPart = C.StakeCredential.from_keyhash(keyHash); + } else { + const scriptHash = C.ScriptHash.from_hex(paymentCredential.hash); + bucket.push(scriptHash); + paymentPart = C.StakeCredential.from_scripthash(scriptHash); + } + bucket.push(paymentPart); + + const enterpriseAddress = C.EnterpriseAddress.new( + networkId, + paymentPart, + ); + bucket.push(enterpriseAddress); + const address = enterpriseAddress.to_address(); + bucket.push(address); + + return address.to_bech32(undefined); + } + } finally { + Freeables.free(...bucket); } } validatorToRewardAddress( - validator: CertificateValidator | WithdrawalValidator + validator: CertificateValidator | WithdrawalValidator, ): RewardAddress { + const bucket: FreeableBucket = []; const validatorHash = this.validatorToScriptHash(validator); - return C.RewardAddress.new( + const scriptHash = C.ScriptHash.from_hex(validatorHash); + bucket.push(scriptHash); + const stakePart = C.StakeCredential.from_scripthash(scriptHash); + bucket.push(stakePart); + const rewardAddress = C.RewardAddress.new( networkToId(this.lucid.network), - C.StakeCredential.from_scripthash(C.ScriptHash.from_hex(validatorHash)) - ) - .to_address() - .to_bech32(undefined); + stakePart, + ); + bucket.push(rewardAddress); + const address = rewardAddress.to_address(); + bucket.push(address); + const bech32 = address.to_bech32(undefined); + + Freeables.free(...bucket); + return bech32; } credentialToRewardAddress(stakeCredential: Credential): RewardAddress { - return C.RewardAddress.new( + const bucket: FreeableBucket = []; + let stakePart: C.StakeCredential; + if (stakeCredential.type === "Key") { + const keyHash = C.Ed25519KeyHash.from_hex(stakeCredential.hash); + bucket.push(keyHash); + stakePart = C.StakeCredential.from_keyhash(keyHash); + } else { + const scriptHash = C.ScriptHash.from_hex(stakeCredential.hash); + bucket.push(scriptHash); + stakePart = C.StakeCredential.from_scripthash(scriptHash); + } + bucket.push(stakePart); + + const rewardAddress = C.RewardAddress.new( networkToId(this.lucid.network), - stakeCredential.type === "Key" - ? C.StakeCredential.from_keyhash( - C.Ed25519KeyHash.from_hex(stakeCredential.hash) - ) - : C.StakeCredential.from_scripthash( - C.ScriptHash.from_hex(stakeCredential.hash) - ) - ) - .to_address() - .to_bech32(undefined); + stakePart, + ); + bucket.push(rewardAddress); + const address = rewardAddress.to_address(); + bucket.push(address); + const bech32 = address.to_bech32(undefined); + Freeables.free(...bucket); + + return bech32; } validatorToScriptHash(validator: Validator): ScriptHash { - switch (validator.type) { - case "Native": - return C.NativeScript.from_bytes(fromHex(validator.script)) - .hash(C.ScriptHashNamespace.NativeScript) - .to_hex(); - case "PlutusV1": - return C.PlutusScript.from_bytes( - fromHex(applyDoubleCborEncoding(validator.script)) - ) - .hash(C.ScriptHashNamespace.PlutusV1) - .to_hex(); - case "PlutusV2": - return C.PlutusScript.from_bytes( - fromHex(applyDoubleCborEncoding(validator.script)) - ) - .hash(C.ScriptHashNamespace.PlutusV2) - .to_hex(); - default: - throw new Error("No variant matched"); + const bucket: FreeableBucket = []; + try { + switch (validator.type) { + case "Native": { + const nativeScript = C.NativeScript.from_bytes( + fromHex(validator.script), + ); + bucket.push(nativeScript); + const hash = nativeScript.hash(C.ScriptHashNamespace.NativeScript); + bucket.push(hash); + return hash.to_hex(); + } + case "PlutusV1": { + const plutusScript = C.PlutusScript.from_bytes( + fromHex(applyDoubleCborEncoding(validator.script)), + ); + bucket.push(plutusScript); + const hash = plutusScript.hash(C.ScriptHashNamespace.PlutusV1); + bucket.push(hash); + return hash.to_hex(); + } + case "PlutusV2": { + const plutusScript = C.PlutusScript.from_bytes( + fromHex(applyDoubleCborEncoding(validator.script)), + ); + bucket.push(plutusScript); + const hash = plutusScript.hash(C.ScriptHashNamespace.PlutusV2); + bucket.push(hash); + return hash.to_hex(); + } + default: + throw new Error("No variant matched"); + } + } finally { + Freeables.free(...bucket); } } @@ -171,7 +267,12 @@ export class Utils { } datumToHash(datum: Datum): DatumHash { - return C.hash_plutus_data(C.PlutusData.from_bytes(fromHex(datum))).to_hex(); + const plutusData = C.PlutusData.from_bytes(fromHex(datum)); + const hash = C.hash_plutus_data(plutusData); + plutusData.free(); + const datumHash = hash.to_hex(); + hash.free(); + return datumHash; } scriptHashToCredential(scriptHash: ScriptHash): Credential { @@ -199,7 +300,7 @@ export class Utils { unixTimeToSlot(unixTime: UnixTime): Slot { return unixTimeToEnclosingSlot( unixTime, - SLOT_CONFIG_NETWORK[this.lucid.network] + SLOT_CONFIG_NETWORK[this.lucid.network], ); } @@ -232,8 +333,8 @@ export class Utils { const minAda = C.min_ada_required( output, C.BigNum.from_str( - this.lucid.protocolParameters.coinsPerUtxoByte.toString() - ) + this.lucid.protocolParameters.coinsPerUtxoByte.toString(), + ), ); return BigInt(minAda.to_str()).valueOf(); } @@ -253,169 +354,238 @@ function addressFromHexOrBech32(address: string): C.Address { /** Address can be in Bech32 or Hex. */ export function getAddressDetails(address: string): AddressDetails { - // Base Address + const bucket: FreeableBucket = []; + // wrapped in an outer try to ensure that memory is freed try { - const parsedAddress = C.BaseAddress.from_address( - addressFromHexOrBech32(address) - )!; - const paymentCredential: Credential = - parsedAddress.payment_cred().kind() === 0 - ? { - type: "Key", - hash: toHex(parsedAddress.payment_cred().to_keyhash()!.to_bytes()), - } - : { - type: "Script", - hash: toHex( - parsedAddress.payment_cred().to_scripthash()!.to_bytes() - ), - }; - const stakeCredential: Credential = - parsedAddress.stake_cred().kind() === 0 - ? { - type: "Key", - hash: toHex(parsedAddress.stake_cred().to_keyhash()!.to_bytes()), - } - : { - type: "Script", - hash: toHex(parsedAddress.stake_cred().to_scripthash()!.to_bytes()), - }; - return { - type: "Base", - networkId: parsedAddress.to_address().network_id(), - address: { - bech32: parsedAddress.to_address().to_bech32(undefined), - hex: toHex(parsedAddress.to_address().to_bytes()), - }, - paymentCredential, - stakeCredential, - }; - } catch (_e) { - /* pass */ - } + // Base Address + try { + const parsedAddress = addressFromHexOrBech32(address); + bucket.push(parsedAddress); + const baseAddress = C.BaseAddress.from_address(parsedAddress)!; + bucket.push(baseAddress); - // Enterprise Address - try { - const parsedAddress = C.EnterpriseAddress.from_address( - addressFromHexOrBech32(address) - )!; - const paymentCredential: Credential = - parsedAddress.payment_cred().kind() === 0 - ? { - type: "Key", - hash: toHex(parsedAddress.payment_cred().to_keyhash()!.to_bytes()), - } - : { - type: "Script", - hash: toHex( - parsedAddress.payment_cred().to_scripthash()!.to_bytes() - ), - }; - return { - type: "Enterprise", - networkId: parsedAddress.to_address().network_id(), - address: { - bech32: parsedAddress.to_address().to_bech32(undefined), - hex: toHex(parsedAddress.to_address().to_bytes()), - }, - paymentCredential, - }; - } catch (_e) { - /* pass */ - } + let paymentCredential: Credential; + const paymentCred = baseAddress.payment_cred(); + bucket.push(paymentCred); + if (paymentCred.kind() === 0) { + const keyHash = paymentCred.to_keyhash()!; + bucket.push(keyHash); + paymentCredential = { + type: "Key", + hash: toHex(keyHash.to_bytes()), + }; + } else { + const scriptHash = paymentCred.to_scripthash()!; + bucket.push(scriptHash); + paymentCredential = { + type: "Script", + hash: toHex(scriptHash.to_bytes()), + }; + } - // Pointer Address - try { - const parsedAddress = C.PointerAddress.from_address( - addressFromHexOrBech32(address) - )!; - const paymentCredential: Credential = - parsedAddress.payment_cred().kind() === 0 - ? { - type: "Key", - hash: toHex(parsedAddress.payment_cred().to_keyhash()!.to_bytes()), - } - : { - type: "Script", - hash: toHex( - parsedAddress.payment_cred().to_scripthash()!.to_bytes() - ), - }; - return { - type: "Pointer", - networkId: parsedAddress.to_address().network_id(), - address: { - bech32: parsedAddress.to_address().to_bech32(undefined), - hex: toHex(parsedAddress.to_address().to_bytes()), - }, - paymentCredential, - }; - } catch (_e) { - /* pass */ - } + let stakeCredential: Credential; + const stakeCred = baseAddress.stake_cred(); + bucket.push(stakeCred); + if (stakeCred.kind() === 0) { + const keyHash = stakeCred.to_keyhash()!; + bucket.push(keyHash); + stakeCredential = { + type: "Key", + hash: toHex(keyHash.to_bytes()), + }; + } else { + const scriptHash = stakeCred.to_scripthash()!; + bucket.push(scriptHash); + stakeCredential = { + type: "Script", + hash: toHex(scriptHash.to_bytes()), + }; + } - // Reward Address - try { - const parsedAddress = C.RewardAddress.from_address( - addressFromHexOrBech32(address) - )!; - const stakeCredential: Credential = - parsedAddress.payment_cred().kind() === 0 - ? { - type: "Key", - hash: toHex(parsedAddress.payment_cred().to_keyhash()!.to_bytes()), - } - : { - type: "Script", - hash: toHex( - parsedAddress.payment_cred().to_scripthash()!.to_bytes() - ), - }; - return { - type: "Reward", - networkId: parsedAddress.to_address().network_id(), - address: { - bech32: parsedAddress.to_address().to_bech32(undefined), - hex: toHex(parsedAddress.to_address().to_bytes()), - }, - stakeCredential, - }; - } catch (_e) { - /* pass */ - } + const cAddress = baseAddress.to_address(); + bucket.push(cAddress); - // Limited support for Byron addresses - try { - const parsedAddress = ((address: string): C.ByronAddress => { - try { - return C.ByronAddress.from_bytes(fromHex(address)); - } catch (_e) { + return { + type: "Base", + networkId: cAddress.network_id(), + address: { + bech32: cAddress.to_bech32(undefined), + hex: toHex(cAddress.to_bytes()), + }, + paymentCredential, + stakeCredential, + }; + } catch (_e) { + /* pass */ + } + + // Enterprise Address + try { + const parsedAddress = addressFromHexOrBech32(address); + bucket.push(parsedAddress); + const enterpriseAddress = + C.EnterpriseAddress.from_address(parsedAddress)!; + bucket.push(enterpriseAddress); + + let paymentCredential: Credential; + const paymentCred = enterpriseAddress.payment_cred(); + bucket.push(paymentCred); + if (paymentCred.kind() === 0) { + const keyHash = paymentCred.to_keyhash()!; + bucket.push(keyHash); + paymentCredential = { + type: "Key", + hash: toHex(keyHash.to_bytes()), + }; + } else { + const scriptHash = paymentCred.to_scripthash()!; + bucket.push(scriptHash); + paymentCredential = { + type: "Script", + hash: toHex(scriptHash.to_bytes()), + }; + } + + const cAddress = enterpriseAddress.to_address(); + bucket.push(cAddress); + return { + type: "Enterprise", + networkId: cAddress.network_id(), + address: { + bech32: cAddress.to_bech32(undefined), + hex: toHex(cAddress.to_bytes()), + }, + paymentCredential, + }; + } catch (_e) { + /* pass */ + } + + // Pointer Address + try { + const parsedAddress = addressFromHexOrBech32(address); + bucket.push(parsedAddress); + const pointerAddress = C.PointerAddress.from_address(parsedAddress)!; + bucket.push(pointerAddress); + + let paymentCredential: Credential; + const paymentCred = pointerAddress.payment_cred(); + bucket.push(paymentCred); + if (paymentCred.kind() === 0) { + const keyHash = paymentCred.to_keyhash()!; + bucket.push(keyHash); + paymentCredential = { + type: "Key", + hash: toHex(keyHash.to_bytes()), + }; + } else { + const scriptHash = paymentCred.to_scripthash()!; + bucket.push(scriptHash); + paymentCredential = { + type: "Script", + hash: toHex(scriptHash.to_bytes()), + }; + } + + const cAddress = pointerAddress.to_address(); + bucket.push(cAddress); + + return { + type: "Pointer", + networkId: cAddress.network_id(), + address: { + bech32: cAddress.to_bech32(undefined), + hex: toHex(cAddress.to_bytes()), + }, + paymentCredential, + }; + } catch (_e) { + /* pass */ + } + + // Reward Address + try { + const parsedAddress = addressFromHexOrBech32(address); + bucket.push(parsedAddress); + const rewardAddress = C.RewardAddress.from_address(parsedAddress)!; + bucket.push(rewardAddress); + + let stakeCredential: Credential; + const paymentCred = rewardAddress.payment_cred(); + bucket.push(paymentCred); + if (paymentCred.kind() === 0) { + const keyHash = paymentCred.to_keyhash()!; + bucket.push(keyHash); + stakeCredential = { + type: "Key", + hash: toHex(keyHash.to_bytes()), + }; + } else { + const scriptHash = paymentCred.to_scripthash()!; + bucket.push(scriptHash); + stakeCredential = { + type: "Script", + hash: toHex(scriptHash.to_bytes()), + }; + } + + const cAddress = rewardAddress.to_address(); + bucket.push(cAddress); + + return { + type: "Reward", + networkId: cAddress.network_id(), + address: { + bech32: cAddress.to_bech32(undefined), + hex: toHex(cAddress.to_bytes()), + }, + stakeCredential, + }; + } catch (_e) { + /* pass */ + } + + // Limited support for Byron addresses + try { + const parsedAddress = ((address: string): C.ByronAddress => { try { - return C.ByronAddress.from_base58(address); + return C.ByronAddress.from_bytes(fromHex(address)); } catch (_e) { - throw new Error("Could not deserialize address."); + try { + return C.ByronAddress.from_base58(address); + } catch (_e) { + throw new Error("Could not deserialize address."); + } } - } - })(address); + })(address); + bucket.push(parsedAddress); - return { - type: "Byron", - networkId: parsedAddress.network_id(), - address: { - bech32: "", - hex: toHex(parsedAddress.to_address().to_bytes()), - }, - }; - } catch (_e) { /* pass */ } + const cAddress = parsedAddress.to_address(); + bucket.push(cAddress); + + return { + type: "Byron", + networkId: parsedAddress.network_id(), + address: { + bech32: "", + hex: toHex(cAddress.to_bytes()), + }, + }; + } catch (_e) { + /* pass */ + } - throw new Error("No address type matched for: " + address); + throw new Error("No address type matched for: " + address); + } finally { + Freeables.free(...bucket); + } } export function paymentCredentialOf(address: Address): Credential { const { paymentCredential } = getAddressDetails(address); if (!paymentCredential) { throw new Error( - "The specified address does not contain a payment credential." + "The specified address does not contain a payment credential.", ); } return paymentCredential; @@ -425,14 +595,17 @@ export function stakeCredentialOf(rewardAddress: RewardAddress): Credential { const { stakeCredential } = getAddressDetails(rewardAddress); if (!stakeCredential) { throw new Error( - "The specified address does not contain a stake credential." + "The specified address does not contain a stake credential.", ); } return stakeCredential; } export function generatePrivateKey(): PrivateKey { - return C.PrivateKey.generate_ed25519().to_bech32(); + const ed25519 = C.PrivateKey.generate_ed25519(); + const bech32 = ed25519.to_bech32(); + ed25519.free(); + return bech32; } export function generateSeedPhrase(): string { @@ -440,156 +613,257 @@ export function generateSeedPhrase(): string { } export function valueToAssets(value: C.Value): Assets { + const bucket: FreeableBucket = []; const assets: Assets = {}; - assets["lovelace"] = BigInt(value.coin().to_str()); + const lovelace = value.coin(); + bucket.push(lovelace); + assets["lovelace"] = BigInt(lovelace.to_str()); const ma = value.multiasset(); + bucket.push(ma); if (ma) { const multiAssets = ma.keys(); + bucket.push(multiAssets); for (let j = 0; j < multiAssets.len(); j++) { const policy = multiAssets.get(j); + bucket.push(policy); const policyAssets = ma.get(policy)!; + bucket.push(policyAssets); const assetNames = policyAssets.keys(); + bucket.push(assetNames); for (let k = 0; k < assetNames.len(); k++) { const policyAsset = assetNames.get(k); + bucket.push(policyAsset); const quantity = policyAssets.get(policyAsset)!; + bucket.push(quantity); const unit = toHex(policy.to_bytes()) + toHex(policyAsset.name()); assets[unit] = BigInt(quantity.to_str()); } } } + Freeables.free(...bucket); return assets; } export function assetsToValue(assets: Assets): C.Value { + const bucket: FreeableBucket = []; const multiAsset = C.MultiAsset.new(); + bucket.push(multiAsset); const lovelace = assets["lovelace"]; const units = Object.keys(assets); const policies = Array.from( new Set( units .filter((unit) => unit !== "lovelace") - .map((unit) => unit.slice(0, 56)) - ) + .map((unit) => unit.slice(0, 56)), + ), ); policies.forEach((policy) => { const policyUnits = units.filter((unit) => unit.slice(0, 56) === policy); const assetsValue = C.Assets.new(); policyUnits.forEach((unit) => { - assetsValue.insert( - C.AssetName.new(fromHex(unit.slice(56))), - C.BigNum.from_str(assets[unit].toString()) - ); + const assetName = C.AssetName.new(fromHex(unit.slice(56))); + bucket.push(assetName); + const quantity = C.BigNum.from_str(assets[unit].toString()); + bucket.push(quantity); + + assetsValue.insert(assetName, quantity); }); - multiAsset.insert(C.ScriptHash.from_bytes(fromHex(policy)), assetsValue); + const policyId = C.ScriptHash.from_bytes(fromHex(policy)); + bucket.push(policyId); + multiAsset.insert(policyId, assetsValue); }); - const value = C.Value.new( - C.BigNum.from_str(lovelace ? lovelace.toString() : "0") - ); + const coin = C.BigNum.from_str(lovelace ? lovelace.toString() : "0"); + bucket.push(coin); + + const value = C.Value.new(coin); if (units.length > 1 || !lovelace) value.set_multiasset(multiAsset); + + Freeables.free(...bucket); return value; } export function fromScriptRef(scriptRef: C.ScriptRef): Script { - const kind = scriptRef.get().kind(); - switch (kind) { - case 0: - return { - type: "Native", - script: toHex(scriptRef.get().as_native()!.to_bytes()), - }; - case 1: - return { - type: "PlutusV1", - script: toHex(scriptRef.get().as_plutus_v1()!.to_bytes()), - }; - case 2: - return { - type: "PlutusV2", - script: toHex(scriptRef.get().as_plutus_v2()!.to_bytes()), - }; - default: - throw new Error("No variant matched."); + const bucket: FreeableBucket = []; + try { + const script = scriptRef.get(); + bucket.push(script); + const kind = script.kind(); + switch (kind) { + case 0: { + const native = script.as_native()!; + bucket.push(native); + return { + type: "Native", + script: toHex(native.to_bytes()), + }; + } + case 1: { + const plutusV1 = script.as_plutus_v1()!; + bucket.push(plutusV1); + return { + type: "PlutusV1", + script: toHex(plutusV1.to_bytes()), + }; + } + case 2: { + const plutusV2 = script.as_plutus_v2()!; + bucket.push(plutusV2); + return { + type: "PlutusV2", + script: toHex(plutusV2.to_bytes()), + }; + } + default: + throw new Error("No variant matched."); + } + } finally { + Freeables.free(...bucket); } } export function toScriptRef(script: Script): C.ScriptRef { - switch (script.type) { - case "Native": - return C.ScriptRef.new( - C.Script.new_native(C.NativeScript.from_bytes(fromHex(script.script))) - ); - case "PlutusV1": - return C.ScriptRef.new( - C.Script.new_plutus_v1( - C.PlutusScript.from_bytes( - fromHex(applyDoubleCborEncoding(script.script)) - ) - ) - ); - case "PlutusV2": - return C.ScriptRef.new( - C.Script.new_plutus_v2( - C.PlutusScript.from_bytes( - fromHex(applyDoubleCborEncoding(script.script)) - ) - ) - ); - default: - throw new Error("No variant matched."); + const bucket: FreeableBucket = []; + try { + switch (script.type) { + case "Native": { + const nativeScript = C.NativeScript.from_bytes(fromHex(script.script)); + bucket.push(nativeScript); + const cScript = C.Script.new_native(nativeScript); + bucket.push(cScript); + return C.ScriptRef.new(cScript); + } + case "PlutusV1": { + const plutusScript = C.PlutusScript.from_bytes( + fromHex(applyDoubleCborEncoding(script.script)), + ); + bucket.push(plutusScript); + const cScript = C.Script.new_plutus_v1(plutusScript); + bucket.push(cScript); + return C.ScriptRef.new(cScript); + } + case "PlutusV2": { + const plutusScript = C.PlutusScript.from_bytes( + fromHex(applyDoubleCborEncoding(script.script)), + ); + bucket.push(plutusScript); + const cScript = C.Script.new_plutus_v2(plutusScript); + bucket.push(cScript); + return C.ScriptRef.new(cScript); + } + default: + throw new Error("No variant matched."); + } + } finally { + Freeables.free(...bucket); } } export function utxoToCore(utxo: UTxO): C.TransactionUnspentOutput { + const bucket: FreeableBucket = []; const address: C.Address = (() => { try { + console.log("success"); return C.Address.from_bech32(utxo.address); } catch (_e) { - return C.ByronAddress.from_base58(utxo.address).to_address(); + const byronAddress = C.ByronAddress.from_base58(utxo.address); + bucket.push(byronAddress); + return byronAddress.to_address(); } })(); - const output = C.TransactionOutput.new(address, assetsToValue(utxo.assets)); + bucket.push(address); + const value = assetsToValue(utxo.assets); + bucket.push(value); + const output = C.TransactionOutput.new(address, value); + bucket.push(output); if (utxo.datumHash) { - output.set_datum( - C.Datum.new_data_hash(C.DataHash.from_bytes(fromHex(utxo.datumHash))) - ); + const dataHash = C.DataHash.from_bytes(fromHex(utxo.datumHash)); + bucket.push(dataHash); + const datum = C.Datum.new_data_hash(dataHash); + bucket.push(datum); + output.set_datum(datum); } // inline datum if (!utxo.datumHash && utxo.datum) { - output.set_datum( - C.Datum.new_data(C.Data.new(C.PlutusData.from_bytes(fromHex(utxo.datum)))) - ); + const plutusData = C.PlutusData.from_bytes(fromHex(utxo.datum)); + bucket.push(plutusData); + const data = C.Data.new(plutusData); + bucket.push(data); + const datum = C.Datum.new_data(data); + bucket.push(datum); + output.set_datum(datum); } if (utxo.scriptRef) { - output.set_script_ref(toScriptRef(utxo.scriptRef)); + const scriptRef = toScriptRef(utxo.scriptRef); + bucket.push(scriptRef); + output.set_script_ref(scriptRef); } - return C.TransactionUnspentOutput.new( - C.TransactionInput.new( - C.TransactionHash.from_bytes(fromHex(utxo.txHash)), - C.BigNum.from_str(utxo.outputIndex.toString()) - ), - output - ); + const hash = C.TransactionHash.from_bytes(fromHex(utxo.txHash)); + bucket.push(hash); + const index = C.BigNum.from_str(utxo.outputIndex.toString()); + bucket.push(index); + const input = C.TransactionInput.new(hash, index); + bucket.push(input); + const coreUtxo = C.TransactionUnspentOutput.new(input, output); + + Freeables.free(...bucket); + return coreUtxo; } export function coreToUtxo(coreUtxo: C.TransactionUnspentOutput): UTxO { - const datum = coreUtxo.output()?.datum()?.as_data()?.get(); - const datumHash = coreUtxo.output()?.datum()?.as_data_hash()?.to_hex(); + const bucket: FreeableBucket = []; + const input = coreUtxo.input(); + bucket.push(input); + const output = coreUtxo.output(); + bucket.push(output); - return { - txHash: toHex(coreUtxo.input().transaction_id().to_bytes()), - outputIndex: parseInt(coreUtxo.input().index().to_str()), - assets: valueToAssets(coreUtxo.output().amount()), - address: coreUtxo.output().address().as_byron() - ? coreUtxo.output().address().as_byron()?.to_base58()! - : coreUtxo.output().address().to_bech32(undefined), - datumHash: datum ? C.hash_plutus_data(datum).to_hex() : datumHash, - datum: datum && toHex(datum.to_bytes()), - scriptRef: - coreUtxo.output()?.script_ref() && - fromScriptRef(coreUtxo.output().script_ref()!), + const txId = input.transaction_id(); + bucket.push(txId); + const txHash = toHex(txId.to_bytes()); + + const index = input.index(); + bucket.push(index); + const outputIndex = parseInt(index.to_str()); + + const amount = output.amount(); + bucket.push(amount); + const assets = valueToAssets(amount); + + const cAddress = output.address(); + bucket.push(cAddress); + const byronAddress = cAddress.as_byron(); + bucket.push(byronAddress); + const address = byronAddress + ? byronAddress.to_base58() + : cAddress.to_bech32(undefined); + + const cDatum = output.datum(); + bucket.push(cDatum); + const dataHash = cDatum?.as_data_hash(); + bucket.push(dataHash); + const datumHash = dataHash?.to_hex(); + + const cDatumData = cDatum?.as_data(); + bucket.push(cDatumData); + const plutusData = cDatumData?.get(); + bucket.push(plutusData); + const datum = plutusData && toHex(plutusData.to_bytes()); + const cScriptRef = output.script_ref(); + bucket.push(cScriptRef); + const scriptRef = cScriptRef && fromScriptRef(cScriptRef); + const utxo = { + txHash, + outputIndex, + assets, + address, + datumHash, + datum, + scriptRef, }; + + Freeables.free(...bucket); + return utxo; } export function networkToId(network: Network): number { @@ -626,7 +900,12 @@ export function fromText(text: string): string { } export function toPublicKey(privateKey: PrivateKey): PublicKey { - return C.PrivateKey.from_bech32(privateKey).to_public().to_bech32(); + const sKey = C.PrivateKey.from_bech32(privateKey); + const vKey = sKey.to_public(); + const bech32 = vKey.to_bech32(); + Freeables.free(sKey, vKey); + + return bech32; } /** Padded number in Hex. */ @@ -637,7 +916,7 @@ function checksum(num: string): string { export function toLabel(num: number): string { if (num < 0 || num > 65535) { throw new Error( - `Label ${num} out of range: min label 1 - max label 65535.` + `Label ${num} out of range: min label 1 - max label 65535.`, ); } const numHex = num.toString(16).padStart(4, "0"); @@ -660,7 +939,7 @@ export function fromLabel(label: string): number | null { export function toUnit( policyId: PolicyId, name?: string | null, - label?: number | null + label?: number | null, ): Unit { const hexLabel = Number.isInteger(label) ? toLabel(label!) : ""; const n = name ? name : ""; @@ -698,31 +977,36 @@ export function fromUnit(unit: Unit): { * It follows this Json format: https://github.com/input-output-hk/cardano-node/blob/master/doc/reference/simple-scripts.md */ export function nativeScriptFromJson(nativeScript: NativeScript): Script { + const cNativeScript = C.encode_json_str_to_native_script( + JSON.stringify(nativeScript), + "", + C.ScriptSchema.Node, + ); + const script = toHex(cNativeScript.to_bytes()); + cNativeScript.free(); + return { type: "Native", - script: toHex( - C.encode_json_str_to_native_script( - JSON.stringify(nativeScript), - "", - C.ScriptSchema.Node - ).to_bytes() - ), + script, }; } export function applyParamsToScript( plutusScript: string, params: Exact<[...T]>, - type?: T + type?: T, ): string { const p = (type ? Data.castTo(params, type) : params) as Data[]; - return toHex( - C.apply_params_to_plutus_script( - C.PlutusList.from_bytes(fromHex(Data.to(p))), - - C.PlutusScript.from_bytes(fromHex(applyDoubleCborEncoding(plutusScript))) - ).to_bytes() + // cPlutusScript ownership is passed to rust, so don't free + const cPlutusScript = C.PlutusScript.from_bytes( + fromHex(applyDoubleCborEncoding(plutusScript)), ); + const cParams = C.PlutusList.from_bytes(fromHex(Data.to(p))); + const cScript = C.apply_params_to_plutus_script(cParams, cPlutusScript); + const script = toHex(cScript.to_bytes()); + Freeables.free(cParams, cScript); + + return script; } export const chunk = (array: T[], size: number) => { @@ -742,11 +1026,14 @@ export const chunk = (array: T[], size: number) => { export function applyDoubleCborEncoding(script: string): string { try { C.PlutusScript.from_bytes( - C.PlutusScript.from_bytes(fromHex(script)).bytes() + C.PlutusScript.from_bytes(fromHex(script)).bytes(), ); return script; } catch (_e) { - return toHex(C.PlutusScript.new(fromHex(script)).to_bytes()); + const plutusScript = C.PlutusScript.new(fromHex(script)); + const bytes = plutusScript.to_bytes(); + plutusScript.free(); + return toHex(bytes); } } diff --git a/dist/types/src/core/libs/cardano_multiplatform_lib/cardano_multiplatform_lib.generated.d.ts b/dist/types/src/core/libs/cardano_multiplatform_lib/cardano_multiplatform_lib.generated.d.ts index e2a2e2cf..2144870f 100644 --- a/dist/types/src/core/libs/cardano_multiplatform_lib/cardano_multiplatform_lib.generated.d.ts +++ b/dist/types/src/core/libs/cardano_multiplatform_lib/cardano_multiplatform_lib.generated.d.ts @@ -7281,6 +7281,20 @@ export class TransactionBuilder { __destroy_into_raw(): number | undefined; ptr: number | undefined; free(): void; + /** + * This automatically selects and adds inputs from {inputs} consisting of just enough to cover + * the outputs that have already been added. + * This should be called after adding all certs/outputs/etc and will be an error otherwise. + * Adding a change output must be called after via TransactionBuilder::balance() + * inputs to cover the minimum fees. This does not, however, set the txbuilder's fee. + * + * change_address is required here in order to determine the min ada requirement precisely + * weights is a coma separated representation of a Uint32Arary + * @param {TransactionUnspentOutputs} inputs + * @param {Address} change_address + * @param {string} weights_str + */ + add_inputs_from_impl(inputs: TransactionUnspentOutputs, change_address: Address, weights_str: string): void; /** * This automatically selects and adds inputs from {inputs} consisting of just enough to cover * the outputs that have already been added. diff --git a/dist/types/src/core/libs/cardano_multiplatform_lib/nodejs/cardano_multiplatform_lib.generated.d.ts b/dist/types/src/core/libs/cardano_multiplatform_lib/nodejs/cardano_multiplatform_lib.generated.d.ts new file mode 100644 index 00000000..91117690 --- /dev/null +++ b/dist/types/src/core/libs/cardano_multiplatform_lib/nodejs/cardano_multiplatform_lib.generated.d.ts @@ -0,0 +1,8795 @@ +export function encrypt_with_password(password: string, salt: string, nonce: string, data: string): string; +export function decrypt_with_password(password: string, data: string): string; +export function min_fee(tx: Transaction, linear_fee: LinearFee, ex_unit_prices: ExUnitPrices): BigNum; +export function encode_arbitrary_bytes_as_metadatum(bytes: Uint8Array): TransactionMetadatum; +export function decode_arbitrary_bytes_from_metadatum(metadata: TransactionMetadatum): Uint8Array; +export function encode_json_str_to_metadatum(json: string, schema: number): TransactionMetadatum; +export function decode_metadatum_to_json_str(metadatum: TransactionMetadatum, schema: number): string; +export function encode_json_str_to_plutus_datum(json: string, schema: number): PlutusData; +export function decode_plutus_datum_to_json_str(datum: PlutusData, schema: number): string; +export function make_daedalus_bootstrap_witness(tx_body_hash: TransactionHash, addr: ByronAddress, key: LegacyDaedalusPrivateKey): BootstrapWitness; +export function make_icarus_bootstrap_witness(tx_body_hash: TransactionHash, addr: ByronAddress, key: Bip32PrivateKey): BootstrapWitness; +export function make_vkey_witness(tx_body_hash: TransactionHash, sk: PrivateKey): Vkeywitness; +export function hash_auxiliary_data(auxiliary_data: AuxiliaryData): AuxiliaryDataHash; +export function hash_transaction(tx_body: TransactionBody): TransactionHash; +export function hash_plutus_data(plutus_data: PlutusData): DataHash; +export function hash_blake2b256(data: Uint8Array): Uint8Array; +export function hash_blake2b224(data: Uint8Array): Uint8Array; +export function hash_script_data(redeemers: Redeemers, cost_models: Costmdls, datums: PlutusList | undefined): ScriptDataHash; +export function get_implicit_input(txbody: TransactionBody, pool_deposit: BigNum, key_deposit: BigNum): Value; +export function get_deposit(txbody: TransactionBody, pool_deposit: BigNum, key_deposit: BigNum): BigNum; +export function min_ada_required(output: TransactionOutput, coins_per_utxo_byte: BigNum): BigNum; +export function encode_json_str_to_native_script(json: string, self_xpub: string, schema: number): NativeScript; +export function apply_params_to_plutus_script(params: PlutusList, plutus_script: PlutusScript): PlutusScript; +export const StakeCredKind: Readonly<{ + Key: 0; + "0": "Key"; + Script: 1; + "1": "Script"; +}>; +export const GovernanceActionKind: Readonly<{ + ParameterChangeAction: 0; + "0": "ParameterChangeAction"; + HardForkInitiationAction: 1; + "1": "HardForkInitiationAction"; + TreasuryWithdrawalsAction: 2; + "2": "TreasuryWithdrawalsAction"; + NoConfidence: 3; + "3": "NoConfidence"; + NewCommittee: 4; + "4": "NewCommittee"; + NewConstitution: 5; + "5": "NewConstitution"; + InfoAction: 6; + "6": "InfoAction"; +}>; +export const VoterKind: Readonly<{ + CommitteeHotKeyHash: 0; + "0": "CommitteeHotKeyHash"; + CommitteeHotScriptHash: 1; + "1": "CommitteeHotScriptHash"; + DrepKeyHash: 2; + "2": "DrepKeyHash"; + DrepScriptHash: 3; + "3": "DrepScriptHash"; + StakingPoolKeyHash: 4; + "4": "StakingPoolKeyHash"; +}>; +export const VoteKind: Readonly<{ + No: 0; + "0": "No"; + Yes: 1; + "1": "Yes"; + Abstain: 2; + "2": "Abstain"; +}>; +export const DrepKind: Readonly<{ + KeyHash: 0; + "0": "KeyHash"; + ScriptHash: 1; + "1": "ScriptHash"; + Abstain: 2; + "2": "Abstain"; + NoConfidence: 3; + "3": "NoConfidence"; +}>; +export const TransactionMetadatumKind: Readonly<{ + MetadataMap: 0; + "0": "MetadataMap"; + MetadataList: 1; + "1": "MetadataList"; + Int: 2; + "2": "Int"; + Bytes: 3; + "3": "Bytes"; + Text: 4; + "4": "Text"; +}>; +export const MetadataJsonSchema: Readonly<{ + NoConversions: 0; + "0": "NoConversions"; + BasicConversions: 1; + "1": "BasicConversions"; + DetailedSchema: 2; + "2": "DetailedSchema"; +}>; +export const LanguageKind: Readonly<{ + PlutusV1: 0; + "0": "PlutusV1"; + PlutusV2: 1; + "1": "PlutusV2"; + PlutusV3: 2; + "2": "PlutusV3"; +}>; +export const PlutusDataKind: Readonly<{ + ConstrPlutusData: 0; + "0": "ConstrPlutusData"; + Map: 1; + "1": "Map"; + List: 2; + "2": "List"; + Integer: 3; + "3": "Integer"; + Bytes: 4; + "4": "Bytes"; +}>; +export const RedeemerTagKind: Readonly<{ + Spend: 0; + "0": "Spend"; + Mint: 1; + "1": "Mint"; + Cert: 2; + "2": "Cert"; + Reward: 3; + "3": "Reward"; + Drep: 4; + "4": "Drep"; +}>; +export const PlutusDatumSchema: Readonly<{ + /** + * ScriptDataJsonNoSchema in cardano-node. + * + * This is the format used by --script-data-value in cardano-cli + * This tries to accept most JSON but does not support the full spectrum of Plutus datums. + * From JSON: + * * null/true/false/floats NOT supported + * * strings starting with 0x are treated as hex bytes. All other strings are encoded as their utf8 bytes. + * To JSON: + * * ConstrPlutusData not supported in ANY FORM (neither keys nor values) + * * Lists not supported in keys + * * Maps not supported in keys + */ + BasicConversions: 0; + "0": "BasicConversions"; + /** + * ScriptDataJsonDetailedSchema in cardano-node. + * + * This is the format used by --script-data-file in cardano-cli + * This covers almost all (only minor exceptions) Plutus datums, but the JSON must conform to a strict schema. + * The schema specifies that ALL keys and ALL values must be contained in a JSON map with 2 cases: + * 1. For ConstrPlutusData there must be two fields "constructor" contianing a number and "fields" containing its fields + * e.g. { "constructor": 2, "fields": [{"int": 2}, {"list": [{"bytes": "CAFEF00D"}]}]} + * 2. For all other cases there must be only one field named "int", "bytes", "list" or "map" + * Integer's value is a JSON number e.g. {"int": 100} + * Bytes' value is a hex string representing the bytes WITHOUT any prefix e.g. {"bytes": "CAFEF00D"} + * Lists' value is a JSON list of its elements encoded via the same schema e.g. {"list": [{"bytes": "CAFEF00D"}]} + * Maps' value is a JSON list of objects, one for each key-value pair in the map, with keys "k" and "v" + * respectively with their values being the plutus datum encoded via this same schema + * e.g. {"map": [ + * {"k": {"int": 2}, "v": {"int": 5}}, + * {"k": {"map": [{"k": {"list": [{"int": 1}]}, "v": {"bytes": "FF03"}}]}, "v": {"list": []}} + * ]} + * From JSON: + * * null/true/false/floats NOT supported + * * the JSON must conform to a very specific schema + * To JSON: + * * all Plutus datums should be fully supported outside of the integer range limitations outlined above. + */ + DetailedSchema: 1; + "1": "DetailedSchema"; +}>; +export const ScriptKind: Readonly<{ + NativeScript: 0; + "0": "NativeScript"; + PlutusScriptV1: 1; + "1": "PlutusScriptV1"; + PlutusScriptV2: 2; + "2": "PlutusScriptV2"; + PlutusScriptV3: 3; + "3": "PlutusScriptV3"; +}>; +export const DatumKind: Readonly<{ + Hash: 0; + "0": "Hash"; + Data: 1; + "1": "Data"; +}>; +export const ScriptHashNamespace: Readonly<{ + NativeScript: 0; + "0": "NativeScript"; + PlutusV1: 1; + "1": "PlutusV1"; + PlutusV2: 2; + "2": "PlutusV2"; +}>; +export const ScriptSchema: Readonly<{ + Wallet: 0; + "0": "Wallet"; + Node: 1; + "1": "Node"; +}>; +export const ScriptWitnessKind: Readonly<{ + NativeWitness: 0; + "0": "NativeWitness"; + PlutusWitness: 1; + "1": "PlutusWitness"; +}>; +export const CertificateKind: Readonly<{ + StakeRegistration: 0; + "0": "StakeRegistration"; + StakeDeregistration: 1; + "1": "StakeDeregistration"; + StakeDelegation: 2; + "2": "StakeDelegation"; + PoolRegistration: 3; + "3": "PoolRegistration"; + PoolRetirement: 4; + "4": "PoolRetirement"; + GenesisKeyDelegation: 5; + "5": "GenesisKeyDelegation"; + MoveInstantaneousRewardsCert: 6; + "6": "MoveInstantaneousRewardsCert"; + RegCert: 7; + "7": "RegCert"; + UnregCert: 8; + "8": "UnregCert"; + VoteDelegCert: 9; + "9": "VoteDelegCert"; + StakeVoteDelegCert: 10; + "10": "StakeVoteDelegCert"; + StakeRegDelegCert: 11; + "11": "StakeRegDelegCert"; + VoteRegDelegCert: 12; + "12": "VoteRegDelegCert"; + StakeVoteRegDelegCert: 13; + "13": "StakeVoteRegDelegCert"; + RegCommitteeHotKeyCert: 14; + "14": "RegCommitteeHotKeyCert"; + UnregCommitteeHotKeyCert: 15; + "15": "UnregCommitteeHotKeyCert"; + RegDrepCert: 16; + "16": "RegDrepCert"; + UnregDrepCert: 17; + "17": "UnregDrepCert"; +}>; +export const MIRPot: Readonly<{ + Reserves: 0; + "0": "Reserves"; + Treasury: 1; + "1": "Treasury"; +}>; +export const MIRKind: Readonly<{ + ToOtherPot: 0; + "0": "ToOtherPot"; + ToStakeCredentials: 1; + "1": "ToStakeCredentials"; +}>; +export const RelayKind: Readonly<{ + SingleHostAddr: 0; + "0": "SingleHostAddr"; + SingleHostName: 1; + "1": "SingleHostName"; + MultiHostName: 2; + "2": "MultiHostName"; +}>; +export const NativeScriptKind: Readonly<{ + ScriptPubkey: 0; + "0": "ScriptPubkey"; + ScriptAll: 1; + "1": "ScriptAll"; + ScriptAny: 2; + "2": "ScriptAny"; + ScriptNOfK: 3; + "3": "ScriptNOfK"; + TimelockStart: 4; + "4": "TimelockStart"; + TimelockExpiry: 5; + "5": "TimelockExpiry"; +}>; +export const NetworkIdKind: Readonly<{ + Testnet: 0; + "0": "Testnet"; + Mainnet: 1; + "1": "Mainnet"; +}>; +export function __wbindgen_object_drop_ref(arg0: any): void; +export function __wbindgen_json_parse(arg0: any, arg1: any): number; +export function __wbindgen_json_serialize(arg0: any, arg1: any): void; +export function __wbindgen_string_new(arg0: any, arg1: any): number; +export function __wbg_fetch_16f5dddfc5a913a4(arg0: any, arg1: any): number; +export function __wbg_transaction_new(arg0: any): number; +export function __wbindgen_string_get(arg0: any, arg1: any): void; +export function __wbindgen_object_clone_ref(arg0: any): number; +export function __wbg_set_a5d34c36a1a4ebd1(...args: any[]): any; +export function __wbg_headers_ab5251d2727ac41e(arg0: any): number; +export function __wbg_newwithstrandinit_c45f0dc6da26fd03(...args: any[]): any; +export function __wbg_instanceof_Response_fb3a4df648c1859b(arg0: any): boolean; +export function __wbg_json_b9414eb18cb751d0(...args: any[]): any; +export function __wbindgen_cb_drop(arg0: any): boolean; +export function __wbg_static_accessor_NODE_MODULE_06b864c18e8ae506(): number; +export function __wbg_process_5615a087a47ba544(arg0: any): number; +export function __wbindgen_is_object(arg0: any): boolean; +export function __wbg_versions_8404a8b21b9337ae(arg0: any): number; +export function __wbg_node_8b504e170b6380b9(arg0: any): number; +export function __wbindgen_is_string(arg0: any): boolean; +export function __wbg_require_0430b68b38d1a77e(...args: any[]): any; +export function __wbg_crypto_ca5197b41df5e2bd(arg0: any): number; +export function __wbg_msCrypto_1088c21440b2d7e4(arg0: any): number; +export function __wbg_randomFillSync_2f6909f8132a175d(...args: any[]): any; +export function __wbg_getRandomValues_11a236fbf9914290(...args: any[]): any; +export function __wbg_self_e7c1f827057f6584(...args: any[]): any; +export function __wbg_window_a09ec664e14b1b81(...args: any[]): any; +export function __wbg_globalThis_87cbb8506fecf3a9(...args: any[]): any; +export function __wbg_global_c85a9259e621f3db(...args: any[]): any; +export function __wbindgen_is_undefined(arg0: any): boolean; +export function __wbg_newnoargs_2b8b6bd7753c76ba(arg0: any, arg1: any): number; +export function __wbg_call_95d1ea488d03e4e8(...args: any[]): any; +export function __wbg_new_f9876326328f45ed(): number; +export function __wbg_call_9495de66fdbe016b(...args: any[]): any; +export function __wbg_set_6aa458a4ebdb65cb(...args: any[]): any; +export function __wbg_buffer_cf65c07de34b9a08(arg0: any): number; +export function __wbg_new_9d3a9ce4282a18a8(arg0: any, arg1: any): number; +export function __wbg_resolve_fd40f858d9db1a04(arg0: any): number; +export function __wbg_then_ec5db6d509eb475f(arg0: any, arg1: any): number; +export function __wbg_then_f753623316e2873a(arg0: any, arg1: any, arg2: any): number; +export function __wbg_new_537b7341ce90bb31(arg0: any): number; +export function __wbg_set_17499e8aa4003ebd(arg0: any, arg1: any, arg2: any): void; +export function __wbg_length_27a2afe8ab42b09f(arg0: any): any; +export function __wbg_newwithlength_b56c882b57805732(arg0: any): number; +export function __wbg_subarray_7526649b91a252a6(arg0: any, arg1: any, arg2: any): number; +export function __wbg_new_d87f272aec784ec0(arg0: any, arg1: any): number; +export function __wbg_call_eae29933372a39be(arg0: any, arg1: any): number; +export function __wbindgen_jsval_eq(arg0: any, arg1: any): boolean; +export function __wbg_self_e0b3266d2d9eba1a(arg0: any): number; +export function __wbg_require_0993fe224bf8e202(arg0: any, arg1: any): number; +export function __wbg_crypto_e95a6e54c5c2e37f(arg0: any): number; +export function __wbg_getRandomValues_dc67302a7bd1aec5(arg0: any): number; +export function __wbg_randomFillSync_dd2297de5917c74e(arg0: any, arg1: any, arg2: any): void; +export function __wbg_getRandomValues_02639197c8166a96(arg0: any, arg1: any, arg2: any): void; +export function __wbindgen_debug_string(arg0: any, arg1: any): void; +export function __wbindgen_throw(arg0: any, arg1: any): never; +export function __wbindgen_memory(): number; +export function __wbindgen_closure_wrapper7021(arg0: any, arg1: any, arg2: any): number; +/** */ +export class Transaction { + static __wrap(ptr: any): any; + /** + * @param {Uint8Array} bytes + * @returns {Transaction} + */ + static from_bytes(bytes: Uint8Array): Transaction; + /** + * @param {string} json + * @returns {Transaction} + */ + static from_json(json: string): Transaction; + /** + * @param {TransactionBody} body + * @param {TransactionWitnessSet} witness_set + * @param {AuxiliaryData | undefined} auxiliary_data + * @returns {Transaction} + */ + static new(body: TransactionBody, witness_set: TransactionWitnessSet, auxiliary_data: AuxiliaryData | undefined): Transaction; + __destroy_into_raw(): number | undefined; + ptr: number | undefined; + free(): void; + /** + * @returns {Uint8Array} + */ + to_bytes(): Uint8Array; + /** + * @returns {string} + */ + to_json(): string; + /** + * @returns {any} + */ + to_js_value(): any; + /** + * @returns {TransactionBody} + */ + body(): TransactionBody; + /** + * @returns {TransactionWitnessSet} + */ + witness_set(): TransactionWitnessSet; + /** + * @returns {boolean} + */ + is_valid(): boolean; + /** + * @returns {AuxiliaryData | undefined} + */ + auxiliary_data(): AuxiliaryData | undefined; + /** + * @param {boolean} valid + */ + set_is_valid(valid: boolean): void; +} +/** */ +export class LinearFee { + static __wrap(ptr: any): any; + /** + * @param {BigNum} coefficient + * @param {BigNum} constant + * @returns {LinearFee} + */ + static new(coefficient: BigNum, constant: BigNum): LinearFee; + __destroy_into_raw(): number | undefined; + ptr: number | undefined; + free(): void; + /** + * @returns {BigNum} + */ + constant(): BigNum; + /** + * @returns {BigNum} + */ + coefficient(): BigNum; +} +/** */ +export class ExUnitPrices { + static __wrap(ptr: any): any; + /** + * @param {Uint8Array} bytes + * @returns {ExUnitPrices} + */ + static from_bytes(bytes: Uint8Array): ExUnitPrices; + /** + * @param {UnitInterval} mem_price + * @param {UnitInterval} step_price + * @returns {ExUnitPrices} + */ + static new(mem_price: UnitInterval, step_price: UnitInterval): ExUnitPrices; + /** + * @param {number} mem_price + * @param {number} step_price + * @returns {ExUnitPrices} + */ + static from_float(mem_price: number, step_price: number): ExUnitPrices; + __destroy_into_raw(): number | undefined; + ptr: number | undefined; + free(): void; + /** + * @returns {Uint8Array} + */ + to_bytes(): Uint8Array; + /** + * @returns {UnitInterval} + */ + mem_price(): UnitInterval; + /** + * @returns {UnitInterval} + */ + step_price(): UnitInterval; +} +/** */ +export class BigNum { + static __wrap(ptr: any): any; + /** + * @param {Uint8Array} bytes + * @returns {BigNum} + */ + static from_bytes(bytes: Uint8Array): BigNum; + /** + * @param {string} string + * @returns {BigNum} + */ + static from_str(string: string): BigNum; + /** + * @returns {BigNum} + */ + static zero(): BigNum; + __destroy_into_raw(): number | undefined; + ptr: number | undefined; + free(): void; + /** + * @returns {Uint8Array} + */ + to_bytes(): Uint8Array; + /** + * @returns {string} + */ + to_str(): string; + /** + * @returns {boolean} + */ + is_zero(): boolean; + /** + * @param {BigNum} other + * @returns {BigNum} + */ + checked_mul(other: BigNum): BigNum; + /** + * @param {BigNum} other + * @returns {BigNum} + */ + checked_add(other: BigNum): BigNum; + /** + * @param {BigNum} other + * @returns {BigNum} + */ + checked_sub(other: BigNum): BigNum; + /** + * @param {BigNum} other + * @returns {BigNum} + */ + checked_div(other: BigNum): BigNum; + /** + * @param {BigNum} other + * @returns {BigNum} + */ + checked_div_ceil(other: BigNum): BigNum; + /** + * returns 0 if it would otherwise underflow + * @param {BigNum} other + * @returns {BigNum} + */ + clamped_sub(other: BigNum): BigNum; + /** + * @param {BigNum} rhs_value + * @returns {number} + */ + compare(rhs_value: BigNum): number; +} +/** */ +export class TransactionMetadatum { + static __wrap(ptr: any): any; + /** + * @param {Uint8Array} bytes + * @returns {TransactionMetadatum} + */ + static from_bytes(bytes: Uint8Array): TransactionMetadatum; + /** + * @param {MetadataMap} map + * @returns {TransactionMetadatum} + */ + static new_map(map: MetadataMap): TransactionMetadatum; + /** + * @param {MetadataList} list + * @returns {TransactionMetadatum} + */ + static new_list(list: MetadataList): TransactionMetadatum; + /** + * @param {Int} int + * @returns {TransactionMetadatum} + */ + static new_int(int: Int): TransactionMetadatum; + /** + * @param {Uint8Array} bytes + * @returns {TransactionMetadatum} + */ + static new_bytes(bytes: Uint8Array): TransactionMetadatum; + /** + * @param {string} text + * @returns {TransactionMetadatum} + */ + static new_text(text: string): TransactionMetadatum; + __destroy_into_raw(): number | undefined; + ptr: number | undefined; + free(): void; + /** + * @returns {Uint8Array} + */ + to_bytes(): Uint8Array; + /** + * @returns {number} + */ + kind(): number; + /** + * @returns {MetadataMap} + */ + as_map(): MetadataMap; + /** + * @returns {MetadataList} + */ + as_list(): MetadataList; + /** + * @returns {Int} + */ + as_int(): Int; + /** + * @returns {Uint8Array} + */ + as_bytes(): Uint8Array; + /** + * @returns {string} + */ + as_text(): string; +} +/** */ +export class PlutusData { + static __wrap(ptr: any): any; + /** + * @param {Uint8Array} bytes + * @returns {PlutusData} + */ + static from_bytes(bytes: Uint8Array): PlutusData; + /** + * @param {ConstrPlutusData} constr_plutus_data + * @returns {PlutusData} + */ + static new_constr_plutus_data(constr_plutus_data: ConstrPlutusData): PlutusData; + /** + * @param {PlutusMap} map + * @returns {PlutusData} + */ + static new_map(map: PlutusMap): PlutusData; + /** + * @param {PlutusList} list + * @returns {PlutusData} + */ + static new_list(list: PlutusList): PlutusData; + /** + * @param {BigInt} integer + * @returns {PlutusData} + */ + static new_integer(integer: BigInt): PlutusData; + /** + * @param {Uint8Array} bytes + * @returns {PlutusData} + */ + static new_bytes(bytes: Uint8Array): PlutusData; + __destroy_into_raw(): number | undefined; + ptr: number | undefined; + free(): void; + /** + * @returns {Uint8Array} + */ + to_bytes(): Uint8Array; + /** + * @returns {number} + */ + kind(): number; + /** + * @returns {ConstrPlutusData | undefined} + */ + as_constr_plutus_data(): ConstrPlutusData | undefined; + /** + * @returns {PlutusMap | undefined} + */ + as_map(): PlutusMap | undefined; + /** + * @returns {PlutusList | undefined} + */ + as_list(): PlutusList | undefined; + /** + * @returns {BigInt | undefined} + */ + as_integer(): BigInt | undefined; + /** + * @returns {Uint8Array | undefined} + */ + as_bytes(): Uint8Array | undefined; +} +/** */ +export class TransactionHash { + static __wrap(ptr: any): any; + /** + * @param {Uint8Array} bytes + * @returns {TransactionHash} + */ + static from_bytes(bytes: Uint8Array): TransactionHash; + /** + * @param {string} bech_str + * @returns {TransactionHash} + */ + static from_bech32(bech_str: string): TransactionHash; + /** + * @param {string} hex + * @returns {TransactionHash} + */ + static from_hex(hex: string): TransactionHash; + __destroy_into_raw(): number | undefined; + ptr: number | undefined; + free(): void; + /** + * @returns {Uint8Array} + */ + to_bytes(): Uint8Array; + /** + * @param {string} prefix + * @returns {string} + */ + to_bech32(prefix: string): string; + /** + * @returns {string} + */ + to_hex(): string; +} +/** */ +export class ByronAddress { + static __wrap(ptr: any): any; + /** + * @param {Uint8Array} bytes + * @returns {ByronAddress} + */ + static from_bytes(bytes: Uint8Array): ByronAddress; + /** + * @param {string} s + * @returns {ByronAddress} + */ + static from_base58(s: string): ByronAddress; + /** + * @param {Bip32PublicKey} key + * @param {number} protocol_magic + * @returns {ByronAddress} + */ + static icarus_from_key(key: Bip32PublicKey, protocol_magic: number): ByronAddress; + /** + * @param {string} s + * @returns {boolean} + */ + static is_valid(s: string): boolean; + /** + * @param {Address} addr + * @returns {ByronAddress | undefined} + */ + static from_address(addr: Address): ByronAddress | undefined; + __destroy_into_raw(): number | undefined; + ptr: number | undefined; + free(): void; + /** + * @returns {string} + */ + to_base58(): string; + /** + * @returns {Uint8Array} + */ + to_bytes(): Uint8Array; + /** + * returns the byron protocol magic embedded in the address, or mainnet id if none is present + * note: for bech32 addresses, you need to use network_id instead + * @returns {number} + */ + byron_protocol_magic(): number; + /** + * @returns {Uint8Array} + */ + attributes(): Uint8Array; + /** + * @returns {number} + */ + network_id(): number; + /** + * @returns {Address} + */ + to_address(): Address; +} +/** */ +export class LegacyDaedalusPrivateKey { + static __wrap(ptr: any): any; + /** + * @param {Uint8Array} bytes + * @returns {LegacyDaedalusPrivateKey} + */ + static from_bytes(bytes: Uint8Array): LegacyDaedalusPrivateKey; + __destroy_into_raw(): number | undefined; + ptr: number | undefined; + free(): void; + /** + * @returns {Uint8Array} + */ + as_bytes(): Uint8Array; + /** + * @returns {Uint8Array} + */ + chaincode(): Uint8Array; +} +/** */ +export class BootstrapWitness { + static __wrap(ptr: any): any; + /** + * @param {Uint8Array} bytes + * @returns {BootstrapWitness} + */ + static from_bytes(bytes: Uint8Array): BootstrapWitness; + /** + * @param {string} json + * @returns {BootstrapWitness} + */ + static from_json(json: string): BootstrapWitness; + /** + * @param {Vkey} vkey + * @param {Ed25519Signature} signature + * @param {Uint8Array} chain_code + * @param {Uint8Array} attributes + * @returns {BootstrapWitness} + */ + static new(vkey: Vkey, signature: Ed25519Signature, chain_code: Uint8Array, attributes: Uint8Array): BootstrapWitness; + __destroy_into_raw(): number | undefined; + ptr: number | undefined; + free(): void; + /** + * @returns {Uint8Array} + */ + to_bytes(): Uint8Array; + /** + * @returns {string} + */ + to_json(): string; + /** + * @returns {any} + */ + to_js_value(): any; + /** + * @returns {Vkey} + */ + vkey(): Vkey; + /** + * @returns {Ed25519Signature} + */ + signature(): Ed25519Signature; + /** + * @returns {Uint8Array} + */ + chain_code(): Uint8Array; + /** + * @returns {Uint8Array} + */ + attributes(): Uint8Array; +} +/** */ +export class Bip32PrivateKey { + static __wrap(ptr: any): any; + /** + * 128-byte xprv a key format in Cardano that some software still uses or requires + * the traditional 96-byte xprv is simply encoded as + * prv | chaincode + * however, because some software may not know how to compute a public key from a private key, + * the 128-byte inlines the public key in the following format + * prv | pub | chaincode + * so be careful if you see the term "xprv" as it could refer to either one + * our library does not require the pub (instead we compute the pub key when needed) + * @param {Uint8Array} bytes + * @returns {Bip32PrivateKey} + */ + static from_128_xprv(bytes: Uint8Array): Bip32PrivateKey; + /** + * @returns {Bip32PrivateKey} + */ + static generate_ed25519_bip32(): Bip32PrivateKey; + /** + * @param {Uint8Array} bytes + * @returns {Bip32PrivateKey} + */ + static from_bytes(bytes: Uint8Array): Bip32PrivateKey; + /** + * @param {string} bech32_str + * @returns {Bip32PrivateKey} + */ + static from_bech32(bech32_str: string): Bip32PrivateKey; + /** + * @param {Uint8Array} entropy + * @param {Uint8Array} password + * @returns {Bip32PrivateKey} + */ + static from_bip39_entropy(entropy: Uint8Array, password: Uint8Array): Bip32PrivateKey; + __destroy_into_raw(): number | undefined; + ptr: number | undefined; + free(): void; + /** + * derive this private key with the given index. + * + * # Security considerations + * + * * hard derivation index cannot be soft derived with the public key + * + * # Hard derivation vs Soft derivation + * + * If you pass an index below 0x80000000 then it is a soft derivation. + * The advantage of soft derivation is that it is possible to derive the + * public key too. I.e. derivation the private key with a soft derivation + * index and then retrieving the associated public key is equivalent to + * deriving the public key associated to the parent private key. + * + * Hard derivation index does not allow public key derivation. + * + * This is why deriving the private key should not fail while deriving + * the public key may fail (if the derivation index is invalid). + * @param {number} index + * @returns {Bip32PrivateKey} + */ + derive(index: number): Bip32PrivateKey; + /** + * see from_128_xprv + * @returns {Uint8Array} + */ + to_128_xprv(): Uint8Array; + /** + * @returns {PrivateKey} + */ + to_raw_key(): PrivateKey; + /** + * @returns {Bip32PublicKey} + */ + to_public(): Bip32PublicKey; + /** + * @returns {Uint8Array} + */ + as_bytes(): Uint8Array; + /** + * @returns {string} + */ + to_bech32(): string; + /** + * @returns {Uint8Array} + */ + chaincode(): Uint8Array; +} +/** */ +export class PrivateKey { + static __wrap(ptr: any): any; + /** + * @returns {PrivateKey} + */ + static generate_ed25519(): PrivateKey; + /** + * @returns {PrivateKey} + */ + static generate_ed25519extended(): PrivateKey; + /** + * Get private key from its bech32 representation + * ```javascript + * PrivateKey.from_bech32('ed25519_sk1ahfetf02qwwg4dkq7mgp4a25lx5vh9920cr5wnxmpzz9906qvm8qwvlts0'); + * ``` + * For an extended 25519 key + * ```javascript + * PrivateKey.from_bech32('ed25519e_sk1gqwl4szuwwh6d0yk3nsqcc6xxc3fpvjlevgwvt60df59v8zd8f8prazt8ln3lmz096ux3xvhhvm3ca9wj2yctdh3pnw0szrma07rt5gl748fp'); + * ``` + * @param {string} bech32_str + * @returns {PrivateKey} + */ + static from_bech32(bech32_str: string): PrivateKey; + /** + * @param {Uint8Array} bytes + * @returns {PrivateKey} + */ + static from_extended_bytes(bytes: Uint8Array): PrivateKey; + /** + * @param {Uint8Array} bytes + * @returns {PrivateKey} + */ + static from_normal_bytes(bytes: Uint8Array): PrivateKey; + /** + * @param {Uint8Array} bytes + * @returns {PrivateKey} + */ + static from_bytes(bytes: Uint8Array): PrivateKey; + __destroy_into_raw(): number | undefined; + ptr: number | undefined; + free(): void; + /** + * @returns {PublicKey} + */ + to_public(): PublicKey; + /** + * @returns {string} + */ + to_bech32(): string; + /** + * @returns {Uint8Array} + */ + as_bytes(): Uint8Array; + /** + * @param {Uint8Array} message + * @returns {Ed25519Signature} + */ + sign(message: Uint8Array): Ed25519Signature; + /** + * @returns {Uint8Array} + */ + to_bytes(): Uint8Array; +} +/** */ +export class Vkeywitness { + static __wrap(ptr: any): any; + /** + * @param {Uint8Array} bytes + * @returns {Vkeywitness} + */ + static from_bytes(bytes: Uint8Array): Vkeywitness; + /** + * @param {string} json + * @returns {Vkeywitness} + */ + static from_json(json: string): Vkeywitness; + /** + * @param {Vkey} vkey + * @param {Ed25519Signature} signature + * @returns {Vkeywitness} + */ + static new(vkey: Vkey, signature: Ed25519Signature): Vkeywitness; + __destroy_into_raw(): number | undefined; + ptr: number | undefined; + free(): void; + /** + * @returns {Uint8Array} + */ + to_bytes(): Uint8Array; + /** + * @returns {string} + */ + to_json(): string; + /** + * @returns {any} + */ + to_js_value(): any; + /** + * @returns {Vkey} + */ + vkey(): Vkey; + /** + * @returns {Ed25519Signature} + */ + signature(): Ed25519Signature; +} +/** */ +export class AuxiliaryData { + static __wrap(ptr: any): any; + /** + * @param {Uint8Array} bytes + * @returns {AuxiliaryData} + */ + static from_bytes(bytes: Uint8Array): AuxiliaryData; + /** + * @param {string} json + * @returns {AuxiliaryData} + */ + static from_json(json: string): AuxiliaryData; + /** + * @returns {AuxiliaryData} + */ + static new(): AuxiliaryData; + __destroy_into_raw(): number | undefined; + ptr: number | undefined; + free(): void; + /** + * @returns {Uint8Array} + */ + to_bytes(): Uint8Array; + /** + * @returns {string} + */ + to_json(): string; + /** + * @returns {any} + */ + to_js_value(): any; + /** + * @returns {GeneralTransactionMetadata | undefined} + */ + metadata(): GeneralTransactionMetadata | undefined; + /** + * @param {GeneralTransactionMetadata} metadata + */ + set_metadata(metadata: GeneralTransactionMetadata): void; + /** + * @returns {NativeScripts | undefined} + */ + native_scripts(): NativeScripts | undefined; + /** + * @param {NativeScripts} native_scripts + */ + set_native_scripts(native_scripts: NativeScripts): void; + /** + * @returns {PlutusScripts | undefined} + */ + plutus_scripts(): PlutusScripts | undefined; + /** + * @returns {PlutusScripts | undefined} + */ + plutus_v2_scripts(): PlutusScripts | undefined; + /** + * @returns {PlutusScripts | undefined} + */ + plutus_v3_scripts(): PlutusScripts | undefined; + /** + * @param {PlutusScripts} plutus_scripts + */ + set_plutus_scripts(plutus_scripts: PlutusScripts): void; + /** + * @param {PlutusScripts} plutus_scripts + */ + set_plutus_v2_scripts(plutus_scripts: PlutusScripts): void; + /** + * @param {PlutusScripts} plutus_scripts + */ + set_plutus_v3_scripts(plutus_scripts: PlutusScripts): void; +} +/** */ +export class AuxiliaryDataHash { + static __wrap(ptr: any): any; + /** + * @param {Uint8Array} bytes + * @returns {AuxiliaryDataHash} + */ + static from_bytes(bytes: Uint8Array): AuxiliaryDataHash; + /** + * @param {string} bech_str + * @returns {AuxiliaryDataHash} + */ + static from_bech32(bech_str: string): AuxiliaryDataHash; + /** + * @param {string} hex + * @returns {AuxiliaryDataHash} + */ + static from_hex(hex: string): AuxiliaryDataHash; + __destroy_into_raw(): number | undefined; + ptr: number | undefined; + free(): void; + /** + * @returns {Uint8Array} + */ + to_bytes(): Uint8Array; + /** + * @param {string} prefix + * @returns {string} + */ + to_bech32(prefix: string): string; + /** + * @returns {string} + */ + to_hex(): string; +} +/** */ +export class TransactionBody { + static __wrap(ptr: any): any; + /** + * @param {Uint8Array} bytes + * @returns {TransactionBody} + */ + static from_bytes(bytes: Uint8Array): TransactionBody; + /** + * @param {string} json + * @returns {TransactionBody} + */ + static from_json(json: string): TransactionBody; + /** + * @param {TransactionInputs} inputs + * @param {TransactionOutputs} outputs + * @param {BigNum} fee + * @param {BigNum | undefined} ttl + * @returns {TransactionBody} + */ + static new(inputs: TransactionInputs, outputs: TransactionOutputs, fee: BigNum, ttl: BigNum | undefined): TransactionBody; + __destroy_into_raw(): number | undefined; + ptr: number | undefined; + free(): void; + /** + * @returns {Uint8Array} + */ + to_bytes(): Uint8Array; + /** + * @returns {string} + */ + to_json(): string; + /** + * @returns {any} + */ + to_js_value(): any; + /** + * @returns {TransactionInputs} + */ + inputs(): TransactionInputs; + /** + * @returns {TransactionOutputs} + */ + outputs(): TransactionOutputs; + /** + * @returns {BigNum} + */ + fee(): BigNum; + /** + * @returns {BigNum | undefined} + */ + ttl(): BigNum | undefined; + /** + * @param {Certificates} certs + */ + set_certs(certs: Certificates): void; + /** + * @returns {Certificates | undefined} + */ + certs(): Certificates | undefined; + /** + * @param {Withdrawals} withdrawals + */ + set_withdrawals(withdrawals: Withdrawals): void; + /** + * @returns {Withdrawals | undefined} + */ + withdrawals(): Withdrawals | undefined; + /** + * @param {Update} update + */ + set_update(update: Update): void; + /** + * @returns {Update | undefined} + */ + update(): Update | undefined; + /** + * @returns {VotingProcedures | undefined} + */ + voting_procedures(): VotingProcedures | undefined; + /** + * @returns {ProposalProcedures | undefined} + */ + proposal_procedures(): ProposalProcedures | undefined; + /** + * @param {AuxiliaryDataHash} auxiliary_data_hash + */ + set_auxiliary_data_hash(auxiliary_data_hash: AuxiliaryDataHash): void; + /** + * @returns {AuxiliaryDataHash | undefined} + */ + auxiliary_data_hash(): AuxiliaryDataHash | undefined; + /** + * @param {BigNum} validity_start_interval + */ + set_validity_start_interval(validity_start_interval: BigNum): void; + /** + * @returns {BigNum | undefined} + */ + validity_start_interval(): BigNum | undefined; + /** + * @param {Mint} mint + */ + set_mint(mint: Mint): void; + /** + * @returns {Mint | undefined} + */ + mint(): Mint | undefined; + /** + * @param {ScriptDataHash} script_data_hash + */ + set_script_data_hash(script_data_hash: ScriptDataHash): void; + /** + * @returns {ScriptDataHash | undefined} + */ + script_data_hash(): ScriptDataHash | undefined; + /** + * @param {TransactionInputs} collateral + */ + set_collateral(collateral: TransactionInputs): void; + /** + * @returns {TransactionInputs | undefined} + */ + collateral(): TransactionInputs | undefined; + /** + * @param {Ed25519KeyHashes} required_signers + */ + set_required_signers(required_signers: Ed25519KeyHashes): void; + /** + * @returns {Ed25519KeyHashes | undefined} + */ + required_signers(): Ed25519KeyHashes | undefined; + /** + * @param {NetworkId} network_id + */ + set_network_id(network_id: NetworkId): void; + /** + * @returns {NetworkId | undefined} + */ + network_id(): NetworkId | undefined; + /** + * @param {TransactionOutput} collateral_return + */ + set_collateral_return(collateral_return: TransactionOutput): void; + /** + * @returns {TransactionOutput | undefined} + */ + collateral_return(): TransactionOutput | undefined; + /** + * @param {BigNum} total_collateral + */ + set_total_collateral(total_collateral: BigNum): void; + /** + * @returns {BigNum | undefined} + */ + total_collateral(): BigNum | undefined; + /** + * @param {TransactionInputs} reference_inputs + */ + set_reference_inputs(reference_inputs: TransactionInputs): void; + /** + * @returns {TransactionInputs | undefined} + */ + reference_inputs(): TransactionInputs | undefined; + /** + * @param {VotingProcedures} voting_procedures + */ + set_voting_procedures(voting_procedures: VotingProcedures): void; + /** + * @param {ProposalProcedures} proposal_procedures + */ + set_proposal_procedures(proposal_procedures: ProposalProcedures): void; + /** + * @returns {Uint8Array | undefined} + */ + raw(): Uint8Array | undefined; +} +/** */ +export class DataHash { + static __wrap(ptr: any): any; + /** + * @param {Uint8Array} bytes + * @returns {DataHash} + */ + static from_bytes(bytes: Uint8Array): DataHash; + /** + * @param {string} bech_str + * @returns {DataHash} + */ + static from_bech32(bech_str: string): DataHash; + /** + * @param {string} hex + * @returns {DataHash} + */ + static from_hex(hex: string): DataHash; + __destroy_into_raw(): number | undefined; + ptr: number | undefined; + free(): void; + /** + * @returns {Uint8Array} + */ + to_bytes(): Uint8Array; + /** + * @param {string} prefix + * @returns {string} + */ + to_bech32(prefix: string): string; + /** + * @returns {string} + */ + to_hex(): string; +} +/** */ +export class Redeemers { + static __wrap(ptr: any): any; + /** + * @param {Uint8Array} bytes + * @returns {Redeemers} + */ + static from_bytes(bytes: Uint8Array): Redeemers; + /** + * @returns {Redeemers} + */ + static new(): Redeemers; + __destroy_into_raw(): number | undefined; + ptr: number | undefined; + free(): void; + /** + * @returns {Uint8Array} + */ + to_bytes(): Uint8Array; + /** + * @returns {number} + */ + len(): number; + /** + * @param {number} index + * @returns {Redeemer} + */ + get(index: number): Redeemer; + /** + * @param {Redeemer} elem + */ + add(elem: Redeemer): void; +} +/** */ +export class Costmdls { + static __wrap(ptr: any): any; + /** + * @param {Uint8Array} bytes + * @returns {Costmdls} + */ + static from_bytes(bytes: Uint8Array): Costmdls; + /** + * @returns {Costmdls} + */ + static new(): Costmdls; + __destroy_into_raw(): number | undefined; + ptr: number | undefined; + free(): void; + /** + * @returns {Uint8Array} + */ + to_bytes(): Uint8Array; + /** + * @returns {number} + */ + len(): number; + /** + * @param {Language} key + * @param {CostModel} value + * @returns {CostModel | undefined} + */ + insert(key: Language, value: CostModel): CostModel | undefined; + /** + * @param {Language} key + * @returns {CostModel | undefined} + */ + get(key: Language): CostModel | undefined; + /** + * @returns {Languages} + */ + keys(): Languages; +} +/** */ +export class PlutusList { + static __wrap(ptr: any): any; + /** + * @param {Uint8Array} bytes + * @returns {PlutusList} + */ + static from_bytes(bytes: Uint8Array): PlutusList; + /** + * @returns {PlutusList} + */ + static new(): PlutusList; + __destroy_into_raw(): number | undefined; + ptr: number | undefined; + free(): void; + /** + * @returns {Uint8Array} + */ + to_bytes(): Uint8Array; + /** + * @returns {number} + */ + len(): number; + /** + * @param {number} index + * @returns {PlutusData} + */ + get(index: number): PlutusData; + /** + * @param {PlutusData} elem + */ + add(elem: PlutusData): void; +} +/** */ +export class ScriptDataHash { + static __wrap(ptr: any): any; + /** + * @param {Uint8Array} bytes + * @returns {ScriptDataHash} + */ + static from_bytes(bytes: Uint8Array): ScriptDataHash; + /** + * @param {string} bech_str + * @returns {ScriptDataHash} + */ + static from_bech32(bech_str: string): ScriptDataHash; + /** + * @param {string} hex + * @returns {ScriptDataHash} + */ + static from_hex(hex: string): ScriptDataHash; + __destroy_into_raw(): number | undefined; + ptr: number | undefined; + free(): void; + /** + * @returns {Uint8Array} + */ + to_bytes(): Uint8Array; + /** + * @param {string} prefix + * @returns {string} + */ + to_bech32(prefix: string): string; + /** + * @returns {string} + */ + to_hex(): string; +} +/** */ +export class Value { + static __wrap(ptr: any): any; + /** + * @param {Uint8Array} bytes + * @returns {Value} + */ + static from_bytes(bytes: Uint8Array): Value; + /** + * @param {string} json + * @returns {Value} + */ + static from_json(json: string): Value; + /** + * @param {BigNum} coin + * @returns {Value} + */ + static new(coin: BigNum): Value; + /** + * @param {MultiAsset} multiasset + * @returns {Value} + */ + static new_from_assets(multiasset: MultiAsset): Value; + /** + * @returns {Value} + */ + static zero(): Value; + __destroy_into_raw(): number | undefined; + ptr: number | undefined; + free(): void; + /** + * @returns {Uint8Array} + */ + to_bytes(): Uint8Array; + /** + * @returns {string} + */ + to_json(): string; + /** + * @returns {any} + */ + to_js_value(): any; + /** + * @returns {boolean} + */ + is_zero(): boolean; + /** + * @returns {BigNum} + */ + coin(): BigNum; + /** + * @param {BigNum} coin + */ + set_coin(coin: BigNum): void; + /** + * @returns {MultiAsset | undefined} + */ + multiasset(): MultiAsset | undefined; + /** + * @param {MultiAsset} multiasset + */ + set_multiasset(multiasset: MultiAsset): void; + /** + * @param {Value} rhs + * @returns {Value} + */ + checked_add(rhs: Value): Value; + /** + * @param {Value} rhs_value + * @returns {Value} + */ + checked_sub(rhs_value: Value): Value; + /** + * @param {Value} rhs_value + * @returns {Value} + */ + clamped_sub(rhs_value: Value): Value; + /** + * note: values are only partially comparable + * @param {Value} rhs_value + * @returns {number | undefined} + */ + compare(rhs_value: Value): number | undefined; +} +/** */ +export class TransactionOutput { + static __wrap(ptr: any): any; + /** + * @param {Uint8Array} bytes + * @returns {TransactionOutput} + */ + static from_bytes(bytes: Uint8Array): TransactionOutput; + /** + * @param {string} json + * @returns {TransactionOutput} + */ + static from_json(json: string): TransactionOutput; + /** + * @param {Address} address + * @param {Value} amount + * @returns {TransactionOutput} + */ + static new(address: Address, amount: Value): TransactionOutput; + __destroy_into_raw(): number | undefined; + ptr: number | undefined; + free(): void; + /** + * @returns {Uint8Array} + */ + to_bytes(): Uint8Array; + /** + * @returns {string} + */ + to_json(): string; + /** + * @returns {any} + */ + to_js_value(): any; + /** + * @returns {Address} + */ + address(): Address; + /** + * @returns {Value} + */ + amount(): Value; + /** + * @returns {Datum | undefined} + */ + datum(): Datum | undefined; + /** + * @returns {ScriptRef | undefined} + */ + script_ref(): ScriptRef | undefined; + /** + * @param {Datum} datum + */ + set_datum(datum: Datum): void; + /** + * @param {ScriptRef} script_ref + */ + set_script_ref(script_ref: ScriptRef): void; + /** + * @returns {number} + */ + format(): number; + /** + * legacy support: serialize output as array array + * + * does not support inline datum and script_ref! + * @returns {Uint8Array} + */ + to_legacy_bytes(): Uint8Array; +} +/** */ +export class NativeScript { + static __wrap(ptr: any): any; + /** + * @param {Uint8Array} bytes + * @returns {NativeScript} + */ + static from_bytes(bytes: Uint8Array): NativeScript; + /** + * @param {string} json + * @returns {NativeScript} + */ + static from_json(json: string): NativeScript; + /** + * @param {ScriptPubkey} script_pubkey + * @returns {NativeScript} + */ + static new_script_pubkey(script_pubkey: ScriptPubkey): NativeScript; + /** + * @param {ScriptAll} script_all + * @returns {NativeScript} + */ + static new_script_all(script_all: ScriptAll): NativeScript; + /** + * @param {ScriptAny} script_any + * @returns {NativeScript} + */ + static new_script_any(script_any: ScriptAny): NativeScript; + /** + * @param {ScriptNOfK} script_n_of_k + * @returns {NativeScript} + */ + static new_script_n_of_k(script_n_of_k: ScriptNOfK): NativeScript; + /** + * @param {TimelockStart} timelock_start + * @returns {NativeScript} + */ + static new_timelock_start(timelock_start: TimelockStart): NativeScript; + /** + * @param {TimelockExpiry} timelock_expiry + * @returns {NativeScript} + */ + static new_timelock_expiry(timelock_expiry: TimelockExpiry): NativeScript; + __destroy_into_raw(): number | undefined; + ptr: number | undefined; + free(): void; + /** + * @returns {Uint8Array} + */ + to_bytes(): Uint8Array; + /** + * @returns {string} + */ + to_json(): string; + /** + * @returns {any} + */ + to_js_value(): any; + /** + * @param {number} namespace + * @returns {ScriptHash} + */ + hash(namespace: number): ScriptHash; + /** + * @returns {number} + */ + kind(): number; + /** + * @returns {ScriptPubkey | undefined} + */ + as_script_pubkey(): ScriptPubkey | undefined; + /** + * @returns {ScriptAll | undefined} + */ + as_script_all(): ScriptAll | undefined; + /** + * @returns {ScriptAny | undefined} + */ + as_script_any(): ScriptAny | undefined; + /** + * @returns {ScriptNOfK | undefined} + */ + as_script_n_of_k(): ScriptNOfK | undefined; + /** + * @returns {TimelockStart | undefined} + */ + as_timelock_start(): TimelockStart | undefined; + /** + * @returns {TimelockExpiry | undefined} + */ + as_timelock_expiry(): TimelockExpiry | undefined; + /** + * Returns an array of unique Ed25519KeyHashes + * contained within this script recursively on any depth level. + * The order of the keys in the result is not determined in any way. + * @returns {Ed25519KeyHashes} + */ + get_required_signers(): Ed25519KeyHashes; + /** + * @param {BigNum | undefined} lower_bound + * @param {BigNum | undefined} upper_bound + * @param {Ed25519KeyHashes} key_hashes + * @returns {boolean} + */ + verify(lower_bound: BigNum | undefined, upper_bound: BigNum | undefined, key_hashes: Ed25519KeyHashes): boolean; +} +/** */ +export class PlutusScript { + static __wrap(ptr: any): any; + /** + * @param {Uint8Array} bytes + * @returns {PlutusScript} + */ + static from_bytes(bytes: Uint8Array): PlutusScript; + /** + * * Creates a new Plutus script from the RAW bytes of the compiled script. + * * This does NOT include any CBOR encoding around these bytes (e.g. from "cborBytes" in cardano-cli) + * * If you creating this from those you should use PlutusScript::from_bytes() instead. + * + * @param {Uint8Array} bytes + * @returns {PlutusScript} + */ + static new(bytes: Uint8Array): PlutusScript; + __destroy_into_raw(): number | undefined; + ptr: number | undefined; + free(): void; + /** + * @returns {Uint8Array} + */ + to_bytes(): Uint8Array; + /** + * @param {number} namespace + * @returns {ScriptHash} + */ + hash(namespace: number): ScriptHash; + /** + * * The raw bytes of this compiled Plutus script. + * * If you need "cborBytes" for cardano-cli use PlutusScript::to_bytes() instead. + * + * @returns {Uint8Array} + */ + bytes(): Uint8Array; +} +/** */ +export class Address { + static __wrap(ptr: any): any; + /** + * @param {Uint8Array} data + * @returns {Address} + */ + static from_bytes(data: Uint8Array): Address; + /** + * @param {string} json + * @returns {Address} + */ + static from_json(json: string): Address; + /** + * @param {string} bech_str + * @returns {Address} + */ + static from_bech32(bech_str: string): Address; + __destroy_into_raw(): number | undefined; + ptr: number | undefined; + free(): void; + /** + * @returns {string} + */ + to_json(): string; + /** + * @returns {any} + */ + to_js_value(): any; + /** + * @returns {Uint8Array} + */ + to_bytes(): Uint8Array; + /** + * @param {string | undefined} prefix + * @returns {string} + */ + to_bech32(prefix: string | undefined): string; + /** + * @returns {number} + */ + network_id(): number; + /** + * @returns {ByronAddress | undefined} + */ + as_byron(): ByronAddress | undefined; + /** + * @returns {RewardAddress | undefined} + */ + as_reward(): RewardAddress | undefined; + /** + * @returns {PointerAddress | undefined} + */ + as_pointer(): PointerAddress | undefined; + /** + * @returns {EnterpriseAddress | undefined} + */ + as_enterprise(): EnterpriseAddress | undefined; + /** + * @returns {BaseAddress | undefined} + */ + as_base(): BaseAddress | undefined; +} +/** */ +export class Anchor { + static __wrap(ptr: any): any; + /** + * @param {Uint8Array} bytes + * @returns {Anchor} + */ + static from_bytes(bytes: Uint8Array): Anchor; + /** + * @param {string} json + * @returns {Anchor} + */ + static from_json(json: string): Anchor; + /** + * @param {Url} anchor_url + * @param {DataHash} anchor_data_hash + * @returns {Anchor} + */ + static new(anchor_url: Url, anchor_data_hash: DataHash): Anchor; + __destroy_into_raw(): number | undefined; + ptr: number | undefined; + free(): void; + /** + * @returns {Uint8Array} + */ + to_bytes(): Uint8Array; + /** + * @returns {string} + */ + to_json(): string; + /** + * @returns {any} + */ + to_js_value(): any; + /** + * @returns {Url} + */ + anchor_url(): Url; + /** + * @returns {DataHash} + */ + anchor_data_hash(): DataHash; +} +/** */ +export class AssetName { + static __wrap(ptr: any): any; + /** + * @param {Uint8Array} bytes + * @returns {AssetName} + */ + static from_bytes(bytes: Uint8Array): AssetName; + /** + * @param {string} json + * @returns {AssetName} + */ + static from_json(json: string): AssetName; + /** + * @param {Uint8Array} name + * @returns {AssetName} + */ + static new(name: Uint8Array): AssetName; + __destroy_into_raw(): number | undefined; + ptr: number | undefined; + free(): void; + /** + * @returns {Uint8Array} + */ + to_bytes(): Uint8Array; + /** + * @returns {string} + */ + to_json(): string; + /** + * @returns {any} + */ + to_js_value(): any; + /** + * @returns {Uint8Array} + */ + name(): Uint8Array; +} +/** */ +export class AssetNames { + static __wrap(ptr: any): any; + /** + * @param {Uint8Array} bytes + * @returns {AssetNames} + */ + static from_bytes(bytes: Uint8Array): AssetNames; + /** + * @param {string} json + * @returns {AssetNames} + */ + static from_json(json: string): AssetNames; + /** + * @returns {AssetNames} + */ + static new(): AssetNames; + __destroy_into_raw(): number | undefined; + ptr: number | undefined; + free(): void; + /** + * @returns {Uint8Array} + */ + to_bytes(): Uint8Array; + /** + * @returns {string} + */ + to_json(): string; + /** + * @returns {any} + */ + to_js_value(): any; + /** + * @returns {number} + */ + len(): number; + /** + * @param {number} index + * @returns {AssetName} + */ + get(index: number): AssetName; + /** + * @param {AssetName} elem + */ + add(elem: AssetName): void; +} +/** */ +export class Assets { + static __wrap(ptr: any): any; + /** + * @param {Uint8Array} bytes + * @returns {Assets} + */ + static from_bytes(bytes: Uint8Array): Assets; + /** + * @param {string} json + * @returns {Assets} + */ + static from_json(json: string): Assets; + /** + * @returns {Assets} + */ + static new(): Assets; + __destroy_into_raw(): number | undefined; + ptr: number | undefined; + free(): void; + /** + * @returns {Uint8Array} + */ + to_bytes(): Uint8Array; + /** + * @returns {string} + */ + to_json(): string; + /** + * @returns {any} + */ + to_js_value(): any; + /** + * @returns {number} + */ + len(): number; + /** + * @param {AssetName} key + * @param {BigNum} value + * @returns {BigNum | undefined} + */ + insert(key: AssetName, value: BigNum): BigNum | undefined; + /** + * @param {AssetName} key + * @returns {BigNum | undefined} + */ + get(key: AssetName): BigNum | undefined; + /** + * @returns {AssetNames} + */ + keys(): AssetNames; +} +/** */ +export class AuxiliaryDataSet { + static __wrap(ptr: any): any; + /** + * @returns {AuxiliaryDataSet} + */ + static new(): AuxiliaryDataSet; + __destroy_into_raw(): number | undefined; + ptr: number | undefined; + free(): void; + /** + * @returns {number} + */ + len(): number; + /** + * @param {BigNum} tx_index + * @param {AuxiliaryData} data + * @returns {AuxiliaryData | undefined} + */ + insert(tx_index: BigNum, data: AuxiliaryData): AuxiliaryData | undefined; + /** + * @param {BigNum} tx_index + * @returns {AuxiliaryData | undefined} + */ + get(tx_index: BigNum): AuxiliaryData | undefined; + /** + * @returns {TransactionIndexes} + */ + indices(): TransactionIndexes; +} +/** */ +export class BaseAddress { + static __wrap(ptr: any): any; + /** + * @param {number} network + * @param {StakeCredential} payment + * @param {StakeCredential} stake + * @returns {BaseAddress} + */ + static new(network: number, payment: StakeCredential, stake: StakeCredential): BaseAddress; + /** + * @param {Address} addr + * @returns {BaseAddress | undefined} + */ + static from_address(addr: Address): BaseAddress | undefined; + __destroy_into_raw(): number | undefined; + ptr: number | undefined; + free(): void; + /** + * @returns {StakeCredential} + */ + payment_cred(): StakeCredential; + /** + * @returns {StakeCredential} + */ + stake_cred(): StakeCredential; + /** + * @returns {Address} + */ + to_address(): Address; +} +/** */ +export class BigInt { + static __wrap(ptr: any): any; + /** + * @param {Uint8Array} bytes + * @returns {BigInt} + */ + static from_bytes(bytes: Uint8Array): BigInt; + /** + * @param {string} text + * @returns {BigInt} + */ + static from_str(text: string): BigInt; + __destroy_into_raw(): number | undefined; + ptr: number | undefined; + free(): void; + /** + * @returns {Uint8Array} + */ + to_bytes(): Uint8Array; + /** + * @returns {BigNum | undefined} + */ + as_u64(): BigNum | undefined; + /** + * @returns {Int | undefined} + */ + as_int(): Int | undefined; + /** + * @returns {string} + */ + to_str(): string; +} +/** */ +export class Bip32PublicKey { + static __wrap(ptr: any): any; + /** + * @param {Uint8Array} bytes + * @returns {Bip32PublicKey} + */ + static from_bytes(bytes: Uint8Array): Bip32PublicKey; + /** + * @param {string} bech32_str + * @returns {Bip32PublicKey} + */ + static from_bech32(bech32_str: string): Bip32PublicKey; + __destroy_into_raw(): number | undefined; + ptr: number | undefined; + free(): void; + /** + * derive this public key with the given index. + * + * # Errors + * + * If the index is not a soft derivation index (< 0x80000000) then + * calling this method will fail. + * + * # Security considerations + * + * * hard derivation index cannot be soft derived with the public key + * + * # Hard derivation vs Soft derivation + * + * If you pass an index below 0x80000000 then it is a soft derivation. + * The advantage of soft derivation is that it is possible to derive the + * public key too. I.e. derivation the private key with a soft derivation + * index and then retrieving the associated public key is equivalent to + * deriving the public key associated to the parent private key. + * + * Hard derivation index does not allow public key derivation. + * + * This is why deriving the private key should not fail while deriving + * the public key may fail (if the derivation index is invalid). + * @param {number} index + * @returns {Bip32PublicKey} + */ + derive(index: number): Bip32PublicKey; + /** + * @returns {PublicKey} + */ + to_raw_key(): PublicKey; + /** + * @returns {Uint8Array} + */ + as_bytes(): Uint8Array; + /** + * @returns {string} + */ + to_bech32(): string; + /** + * @returns {Uint8Array} + */ + chaincode(): Uint8Array; +} +/** */ +export class Block { + static __wrap(ptr: any): any; + /** + * @param {Uint8Array} bytes + * @returns {Block} + */ + static from_bytes(bytes: Uint8Array): Block; + /** + * @param {string} json + * @returns {Block} + */ + static from_json(json: string): Block; + /** + * @param {Header} header + * @param {TransactionBodies} transaction_bodies + * @param {TransactionWitnessSets} transaction_witness_sets + * @param {AuxiliaryDataSet} auxiliary_data_set + * @param {TransactionIndexes} invalid_transactions + * @returns {Block} + */ + static new(header: Header, transaction_bodies: TransactionBodies, transaction_witness_sets: TransactionWitnessSets, auxiliary_data_set: AuxiliaryDataSet, invalid_transactions: TransactionIndexes): Block; + __destroy_into_raw(): number | undefined; + ptr: number | undefined; + free(): void; + /** + * @returns {Uint8Array} + */ + to_bytes(): Uint8Array; + /** + * @returns {string} + */ + to_json(): string; + /** + * @returns {any} + */ + to_js_value(): any; + /** + * @returns {Header} + */ + header(): Header; + /** + * @returns {TransactionBodies} + */ + transaction_bodies(): TransactionBodies; + /** + * @returns {TransactionWitnessSets} + */ + transaction_witness_sets(): TransactionWitnessSets; + /** + * @returns {AuxiliaryDataSet} + */ + auxiliary_data_set(): AuxiliaryDataSet; + /** + * @returns {TransactionIndexes} + */ + invalid_transactions(): TransactionIndexes; +} +/** */ +export class BlockHash { + static __wrap(ptr: any): any; + /** + * @param {Uint8Array} bytes + * @returns {BlockHash} + */ + static from_bytes(bytes: Uint8Array): BlockHash; + /** + * @param {string} bech_str + * @returns {BlockHash} + */ + static from_bech32(bech_str: string): BlockHash; + /** + * @param {string} hex + * @returns {BlockHash} + */ + static from_hex(hex: string): BlockHash; + __destroy_into_raw(): number | undefined; + ptr: number | undefined; + free(): void; + /** + * @returns {Uint8Array} + */ + to_bytes(): Uint8Array; + /** + * @param {string} prefix + * @returns {string} + */ + to_bech32(prefix: string): string; + /** + * @returns {string} + */ + to_hex(): string; +} +/** */ +export class Blockfrost { + static __wrap(ptr: any): any; + /** + * @param {string} url + * @param {string} project_id + * @returns {Blockfrost} + */ + static new(url: string, project_id: string): Blockfrost; + __destroy_into_raw(): number | undefined; + ptr: number | undefined; + free(): void; + /** + * @returns {string} + */ + url(): string; + /** + * @returns {string} + */ + project_id(): string; +} +/** */ +export class BootstrapWitnesses { + static __wrap(ptr: any): any; + /** + * @returns {BootstrapWitnesses} + */ + static new(): BootstrapWitnesses; + __destroy_into_raw(): number | undefined; + ptr: number | undefined; + free(): void; + /** + * @returns {number} + */ + len(): number; + /** + * @param {number} index + * @returns {BootstrapWitness} + */ + get(index: number): BootstrapWitness; + /** + * @param {BootstrapWitness} elem + */ + add(elem: BootstrapWitness): void; +} +/** */ +export class Certificate { + static __wrap(ptr: any): any; + /** + * @param {Uint8Array} bytes + * @returns {Certificate} + */ + static from_bytes(bytes: Uint8Array): Certificate; + /** + * @param {string} json + * @returns {Certificate} + */ + static from_json(json: string): Certificate; + /** + * @param {StakeRegistration} stake_registration + * @returns {Certificate} + */ + static new_stake_registration(stake_registration: StakeRegistration): Certificate; + /** + * @param {StakeDeregistration} stake_deregistration + * @returns {Certificate} + */ + static new_stake_deregistration(stake_deregistration: StakeDeregistration): Certificate; + /** + * @param {StakeDelegation} stake_delegation + * @returns {Certificate} + */ + static new_stake_delegation(stake_delegation: StakeDelegation): Certificate; + /** + * @param {PoolRegistration} pool_registration + * @returns {Certificate} + */ + static new_pool_registration(pool_registration: PoolRegistration): Certificate; + /** + * @param {PoolRetirement} pool_retirement + * @returns {Certificate} + */ + static new_pool_retirement(pool_retirement: PoolRetirement): Certificate; + /** + * @param {GenesisKeyDelegation} genesis_key_delegation + * @returns {Certificate} + */ + static new_genesis_key_delegation(genesis_key_delegation: GenesisKeyDelegation): Certificate; + /** + * @param {MoveInstantaneousRewardsCert} move_instantaneous_rewards_cert + * @returns {Certificate} + */ + static new_move_instantaneous_rewards_cert(move_instantaneous_rewards_cert: MoveInstantaneousRewardsCert): Certificate; + __destroy_into_raw(): number | undefined; + ptr: number | undefined; + free(): void; + /** + * @returns {Uint8Array} + */ + to_bytes(): Uint8Array; + /** + * @returns {string} + */ + to_json(): string; + /** + * @returns {any} + */ + to_js_value(): any; + /** + * @returns {number} + */ + kind(): number; + /** + * @returns {StakeRegistration | undefined} + */ + as_stake_registration(): StakeRegistration | undefined; + /** + * @returns {StakeDeregistration | undefined} + */ + as_stake_deregistration(): StakeDeregistration | undefined; + /** + * @returns {StakeDelegation | undefined} + */ + as_stake_delegation(): StakeDelegation | undefined; + /** + * @returns {PoolRegistration | undefined} + */ + as_pool_registration(): PoolRegistration | undefined; + /** + * @returns {PoolRetirement | undefined} + */ + as_pool_retirement(): PoolRetirement | undefined; + /** + * @returns {GenesisKeyDelegation | undefined} + */ + as_genesis_key_delegation(): GenesisKeyDelegation | undefined; + /** + * @returns {MoveInstantaneousRewardsCert | undefined} + */ + as_move_instantaneous_rewards_cert(): MoveInstantaneousRewardsCert | undefined; + /** + * @returns {RegCert | undefined} + */ + as_reg_cert(): RegCert | undefined; + /** + * @returns {UnregCert | undefined} + */ + as_unreg_cert(): UnregCert | undefined; + /** + * @returns {VoteDelegCert | undefined} + */ + as_vote_deleg_cert(): VoteDelegCert | undefined; + /** + * @returns {StakeVoteDelegCert | undefined} + */ + as_stake_vote_deleg_cert(): StakeVoteDelegCert | undefined; + /** + * @returns {StakeRegDelegCert | undefined} + */ + as_stake_reg_deleg_cert(): StakeRegDelegCert | undefined; + /** + * @returns {VoteRegDelegCert | undefined} + */ + as_vote_reg_deleg_cert(): VoteRegDelegCert | undefined; + /** + * @returns {StakeVoteRegDelegCert | undefined} + */ + as_stake_vote_reg_deleg_cert(): StakeVoteRegDelegCert | undefined; + /** + * @returns {RegCommitteeHotKeyCert | undefined} + */ + as_reg_committee_hot_key_cert(): RegCommitteeHotKeyCert | undefined; + /** + * @returns {UnregCommitteeHotKeyCert | undefined} + */ + as_unreg_committee_hot_key_cert(): UnregCommitteeHotKeyCert | undefined; + /** + * @returns {RegDrepCert | undefined} + */ + as_reg_drep_cert(): RegDrepCert | undefined; + /** + * @returns {UnregDrepCert | undefined} + */ + as_unreg_drep_cert(): UnregDrepCert | undefined; +} +/** */ +export class Certificates { + static __wrap(ptr: any): any; + /** + * @param {Uint8Array} bytes + * @returns {Certificates} + */ + static from_bytes(bytes: Uint8Array): Certificates; + /** + * @param {string} json + * @returns {Certificates} + */ + static from_json(json: string): Certificates; + /** + * @returns {Certificates} + */ + static new(): Certificates; + __destroy_into_raw(): number | undefined; + ptr: number | undefined; + free(): void; + /** + * @returns {Uint8Array} + */ + to_bytes(): Uint8Array; + /** + * @returns {string} + */ + to_json(): string; + /** + * @returns {any} + */ + to_js_value(): any; + /** + * @returns {number} + */ + len(): number; + /** + * @param {number} index + * @returns {Certificate} + */ + get(index: number): Certificate; + /** + * @param {Certificate} elem + */ + add(elem: Certificate): void; +} +/** */ +export class ConstrPlutusData { + static __wrap(ptr: any): any; + /** + * @param {Uint8Array} bytes + * @returns {ConstrPlutusData} + */ + static from_bytes(bytes: Uint8Array): ConstrPlutusData; + /** + * @param {BigNum} alternative + * @param {PlutusList} data + * @returns {ConstrPlutusData} + */ + static new(alternative: BigNum, data: PlutusList): ConstrPlutusData; + __destroy_into_raw(): number | undefined; + ptr: number | undefined; + free(): void; + /** + * @returns {Uint8Array} + */ + to_bytes(): Uint8Array; + /** + * @returns {BigNum} + */ + alternative(): BigNum; + /** + * @returns {PlutusList} + */ + data(): PlutusList; +} +/** */ +export class CostModel { + static __wrap(ptr: any): any; + /** + * @param {Uint8Array} bytes + * @returns {CostModel} + */ + static from_bytes(bytes: Uint8Array): CostModel; + /** + * @returns {CostModel} + */ + static new(): CostModel; + /** + * @returns {CostModel} + */ + static new_plutus_v2(): CostModel; + /** + * @returns {CostModel} + */ + static new_plutus_v3(): CostModel; + __destroy_into_raw(): number | undefined; + ptr: number | undefined; + free(): void; + /** + * @returns {Uint8Array} + */ + to_bytes(): Uint8Array; + /** + * @param {number} operation + * @param {Int} cost + * @returns {Int} + */ + set(operation: number, cost: Int): Int; + /** + * @param {number} operation + * @returns {Int} + */ + get(operation: number): Int; + /** + * @returns {number} + */ + len(): number; +} +/** */ +export class DNSRecordAorAAAA { + static __wrap(ptr: any): any; + /** + * @param {Uint8Array} bytes + * @returns {DNSRecordAorAAAA} + */ + static from_bytes(bytes: Uint8Array): DNSRecordAorAAAA; + /** + * @param {string} dns_name + * @returns {DNSRecordAorAAAA} + */ + static new(dns_name: string): DNSRecordAorAAAA; + __destroy_into_raw(): number | undefined; + ptr: number | undefined; + free(): void; + /** + * @returns {Uint8Array} + */ + to_bytes(): Uint8Array; + /** + * @returns {string} + */ + record(): string; +} +/** */ +export class DNSRecordSRV { + static __wrap(ptr: any): any; + /** + * @param {Uint8Array} bytes + * @returns {DNSRecordSRV} + */ + static from_bytes(bytes: Uint8Array): DNSRecordSRV; + /** + * @param {string} dns_name + * @returns {DNSRecordSRV} + */ + static new(dns_name: string): DNSRecordSRV; + __destroy_into_raw(): number | undefined; + ptr: number | undefined; + free(): void; + /** + * @returns {Uint8Array} + */ + to_bytes(): Uint8Array; + /** + * @returns {string} + */ + record(): string; +} +/** */ +export class Data { + static __wrap(ptr: any): any; + /** + * @param {Uint8Array} bytes + * @returns {Data} + */ + static from_bytes(bytes: Uint8Array): Data; + /** + * @param {string} json + * @returns {Data} + */ + static from_json(json: string): Data; + /** + * @param {PlutusData} plutus_data + * @returns {Data} + */ + static new(plutus_data: PlutusData): Data; + __destroy_into_raw(): number | undefined; + ptr: number | undefined; + free(): void; + /** + * @returns {Uint8Array} + */ + to_bytes(): Uint8Array; + /** + * @returns {string} + */ + to_json(): string; + /** + * @returns {any} + */ + to_js_value(): any; + /** + * @returns {PlutusData} + */ + get(): PlutusData; +} +/** */ +export class Datum { + static __wrap(ptr: any): any; + /** + * @param {Uint8Array} bytes + * @returns {Datum} + */ + static from_bytes(bytes: Uint8Array): Datum; + /** + * @param {string} json + * @returns {Datum} + */ + static from_json(json: string): Datum; + /** + * @param {DataHash} data_hash + * @returns {Datum} + */ + static new_data_hash(data_hash: DataHash): Datum; + /** + * @param {Data} data + * @returns {Datum} + */ + static new_data(data: Data): Datum; + __destroy_into_raw(): number | undefined; + ptr: number | undefined; + free(): void; + /** + * @returns {Uint8Array} + */ + to_bytes(): Uint8Array; + /** + * @returns {string} + */ + to_json(): string; + /** + * @returns {any} + */ + to_js_value(): any; + /** + * @returns {number} + */ + kind(): number; + /** + * @returns {DataHash | undefined} + */ + as_data_hash(): DataHash | undefined; + /** + * @returns {Data | undefined} + */ + as_data(): Data | undefined; +} +/** */ +export class Drep { + static __wrap(ptr: any): any; + /** + * @param {Uint8Array} bytes + * @returns {Drep} + */ + static from_bytes(bytes: Uint8Array): Drep; + /** + * @param {string} json + * @returns {Drep} + */ + static from_json(json: string): Drep; + /** + * @param {Ed25519KeyHash} keyhash + * @returns {Drep} + */ + static new_keyhash(keyhash: Ed25519KeyHash): Drep; + /** + * @param {ScriptHash} scripthash + * @returns {Drep} + */ + static new_scripthash(scripthash: ScriptHash): Drep; + /** + * @returns {Drep} + */ + static new_abstain(): Drep; + /** + * @returns {Drep} + */ + static new_no_confidence(): Drep; + __destroy_into_raw(): number | undefined; + ptr: number | undefined; + free(): void; + /** + * @returns {Uint8Array} + */ + to_bytes(): Uint8Array; + /** + * @returns {string} + */ + to_json(): string; + /** + * @returns {any} + */ + to_js_value(): any; + /** + * @returns {number} + */ + kind(): number; + /** + * @returns {Ed25519KeyHash | undefined} + */ + as_keyhash(): Ed25519KeyHash | undefined; + /** + * @returns {ScriptHash | undefined} + */ + as_scripthash(): ScriptHash | undefined; +} +/** */ +export class DrepVotingThresholds { + static __wrap(ptr: any): any; + /** + * @param {Uint8Array} bytes + * @returns {DrepVotingThresholds} + */ + static from_bytes(bytes: Uint8Array): DrepVotingThresholds; + /** + * @param {string} json + * @returns {DrepVotingThresholds} + */ + static from_json(json: string): DrepVotingThresholds; + /** + * @param {UnitInterval} motion_no_confidence + * @param {UnitInterval} committee_normal + * @param {UnitInterval} committee_no_confidence + * @param {UnitInterval} update_constitution + * @param {UnitInterval} hard_fork_initiation + * @param {UnitInterval} pp_network_group + * @param {UnitInterval} pp_economic_group + * @param {UnitInterval} pp_technical_group + * @param {UnitInterval} pp_governance_group + * @param {UnitInterval} treasury_withdrawal + * @returns {DrepVotingThresholds} + */ + static new(motion_no_confidence: UnitInterval, committee_normal: UnitInterval, committee_no_confidence: UnitInterval, update_constitution: UnitInterval, hard_fork_initiation: UnitInterval, pp_network_group: UnitInterval, pp_economic_group: UnitInterval, pp_technical_group: UnitInterval, pp_governance_group: UnitInterval, treasury_withdrawal: UnitInterval): DrepVotingThresholds; + __destroy_into_raw(): number | undefined; + ptr: number | undefined; + free(): void; + /** + * @returns {Uint8Array} + */ + to_bytes(): Uint8Array; + /** + * @returns {string} + */ + to_json(): string; + /** + * @returns {any} + */ + to_js_value(): any; + /** + * @returns {UnitInterval} + */ + motion_no_confidence(): UnitInterval; + /** + * @returns {UnitInterval} + */ + committee_normal(): UnitInterval; + /** + * @returns {UnitInterval} + */ + committee_no_confidence(): UnitInterval; + /** + * @returns {UnitInterval} + */ + update_constitution(): UnitInterval; + /** + * @returns {UnitInterval} + */ + hard_fork_initiation(): UnitInterval; + /** + * @returns {UnitInterval} + */ + pp_network_group(): UnitInterval; + /** + * @returns {UnitInterval} + */ + pp_economic_group(): UnitInterval; + /** + * @returns {UnitInterval} + */ + pp_technical_group(): UnitInterval; + /** + * @returns {UnitInterval} + */ + pp_governance_group(): UnitInterval; + /** + * @returns {UnitInterval} + */ + treasury_withdrawal(): UnitInterval; +} +/** */ +export class Ed25519KeyHash { + static __wrap(ptr: any): any; + /** + * @param {Uint8Array} bytes + * @returns {Ed25519KeyHash} + */ + static from_bytes(bytes: Uint8Array): Ed25519KeyHash; + /** + * @param {string} bech_str + * @returns {Ed25519KeyHash} + */ + static from_bech32(bech_str: string): Ed25519KeyHash; + /** + * @param {string} hex + * @returns {Ed25519KeyHash} + */ + static from_hex(hex: string): Ed25519KeyHash; + __destroy_into_raw(): number | undefined; + ptr: number | undefined; + free(): void; + /** + * @returns {Uint8Array} + */ + to_bytes(): Uint8Array; + /** + * @param {string} prefix + * @returns {string} + */ + to_bech32(prefix: string): string; + /** + * @returns {string} + */ + to_hex(): string; +} +/** */ +export class Ed25519KeyHashes { + static __wrap(ptr: any): any; + /** + * @param {Uint8Array} bytes + * @returns {Ed25519KeyHashes} + */ + static from_bytes(bytes: Uint8Array): Ed25519KeyHashes; + /** + * @param {string} json + * @returns {Ed25519KeyHashes} + */ + static from_json(json: string): Ed25519KeyHashes; + /** + * @returns {Ed25519KeyHashes} + */ + static new(): Ed25519KeyHashes; + __destroy_into_raw(): number | undefined; + ptr: number | undefined; + free(): void; + /** + * @returns {Uint8Array} + */ + to_bytes(): Uint8Array; + /** + * @returns {string} + */ + to_json(): string; + /** + * @returns {any} + */ + to_js_value(): any; + /** + * @returns {number} + */ + len(): number; + /** + * @param {number} index + * @returns {Ed25519KeyHash} + */ + get(index: number): Ed25519KeyHash; + /** + * @param {Ed25519KeyHash} elem + */ + add(elem: Ed25519KeyHash): void; +} +/** */ +export class Ed25519Signature { + static __wrap(ptr: any): any; + /** + * @param {string} bech32_str + * @returns {Ed25519Signature} + */ + static from_bech32(bech32_str: string): Ed25519Signature; + /** + * @param {string} input + * @returns {Ed25519Signature} + */ + static from_hex(input: string): Ed25519Signature; + /** + * @param {Uint8Array} bytes + * @returns {Ed25519Signature} + */ + static from_bytes(bytes: Uint8Array): Ed25519Signature; + __destroy_into_raw(): number | undefined; + ptr: number | undefined; + free(): void; + /** + * @returns {Uint8Array} + */ + to_bytes(): Uint8Array; + /** + * @returns {string} + */ + to_bech32(): string; + /** + * @returns {string} + */ + to_hex(): string; +} +/** */ +export class EnterpriseAddress { + static __wrap(ptr: any): any; + /** + * @param {number} network + * @param {StakeCredential} payment + * @returns {EnterpriseAddress} + */ + static new(network: number, payment: StakeCredential): EnterpriseAddress; + /** + * @param {Address} addr + * @returns {EnterpriseAddress | undefined} + */ + static from_address(addr: Address): EnterpriseAddress | undefined; + __destroy_into_raw(): number | undefined; + ptr: number | undefined; + free(): void; + /** + * @returns {StakeCredential} + */ + payment_cred(): StakeCredential; + /** + * @returns {Address} + */ + to_address(): Address; +} +/** */ +export class ExUnits { + static __wrap(ptr: any): any; + /** + * @param {Uint8Array} bytes + * @returns {ExUnits} + */ + static from_bytes(bytes: Uint8Array): ExUnits; + /** + * @param {BigNum} mem + * @param {BigNum} steps + * @returns {ExUnits} + */ + static new(mem: BigNum, steps: BigNum): ExUnits; + __destroy_into_raw(): number | undefined; + ptr: number | undefined; + free(): void; + /** + * @returns {Uint8Array} + */ + to_bytes(): Uint8Array; + /** + * @returns {BigNum} + */ + mem(): BigNum; + /** + * @returns {BigNum} + */ + steps(): BigNum; +} +/** */ +export class GeneralTransactionMetadata { + static __wrap(ptr: any): any; + /** + * @param {Uint8Array} bytes + * @returns {GeneralTransactionMetadata} + */ + static from_bytes(bytes: Uint8Array): GeneralTransactionMetadata; + /** + * @param {string} json + * @returns {GeneralTransactionMetadata} + */ + static from_json(json: string): GeneralTransactionMetadata; + /** + * @returns {GeneralTransactionMetadata} + */ + static new(): GeneralTransactionMetadata; + __destroy_into_raw(): number | undefined; + ptr: number | undefined; + free(): void; + /** + * @returns {Uint8Array} + */ + to_bytes(): Uint8Array; + /** + * @returns {string} + */ + to_json(): string; + /** + * @returns {any} + */ + to_js_value(): any; + /** + * @returns {number} + */ + len(): number; + /** + * @param {BigNum} key + * @param {TransactionMetadatum} value + * @returns {TransactionMetadatum | undefined} + */ + insert(key: BigNum, value: TransactionMetadatum): TransactionMetadatum | undefined; + /** + * @param {BigNum} key + * @returns {TransactionMetadatum | undefined} + */ + get(key: BigNum): TransactionMetadatum | undefined; + /** + * @returns {TransactionMetadatumLabels} + */ + keys(): TransactionMetadatumLabels; +} +/** */ +export class GenesisDelegateHash { + static __wrap(ptr: any): any; + /** + * @param {Uint8Array} bytes + * @returns {GenesisDelegateHash} + */ + static from_bytes(bytes: Uint8Array): GenesisDelegateHash; + /** + * @param {string} bech_str + * @returns {GenesisDelegateHash} + */ + static from_bech32(bech_str: string): GenesisDelegateHash; + /** + * @param {string} hex + * @returns {GenesisDelegateHash} + */ + static from_hex(hex: string): GenesisDelegateHash; + __destroy_into_raw(): number | undefined; + ptr: number | undefined; + free(): void; + /** + * @returns {Uint8Array} + */ + to_bytes(): Uint8Array; + /** + * @param {string} prefix + * @returns {string} + */ + to_bech32(prefix: string): string; + /** + * @returns {string} + */ + to_hex(): string; +} +/** */ +export class GenesisHash { + static __wrap(ptr: any): any; + /** + * @param {Uint8Array} bytes + * @returns {GenesisHash} + */ + static from_bytes(bytes: Uint8Array): GenesisHash; + /** + * @param {string} bech_str + * @returns {GenesisHash} + */ + static from_bech32(bech_str: string): GenesisHash; + /** + * @param {string} hex + * @returns {GenesisHash} + */ + static from_hex(hex: string): GenesisHash; + __destroy_into_raw(): number | undefined; + ptr: number | undefined; + free(): void; + /** + * @returns {Uint8Array} + */ + to_bytes(): Uint8Array; + /** + * @param {string} prefix + * @returns {string} + */ + to_bech32(prefix: string): string; + /** + * @returns {string} + */ + to_hex(): string; +} +/** */ +export class GenesisHashes { + static __wrap(ptr: any): any; + /** + * @param {Uint8Array} bytes + * @returns {GenesisHashes} + */ + static from_bytes(bytes: Uint8Array): GenesisHashes; + /** + * @param {string} json + * @returns {GenesisHashes} + */ + static from_json(json: string): GenesisHashes; + /** + * @returns {GenesisHashes} + */ + static new(): GenesisHashes; + __destroy_into_raw(): number | undefined; + ptr: number | undefined; + free(): void; + /** + * @returns {Uint8Array} + */ + to_bytes(): Uint8Array; + /** + * @returns {string} + */ + to_json(): string; + /** + * @returns {any} + */ + to_js_value(): any; + /** + * @returns {number} + */ + len(): number; + /** + * @param {number} index + * @returns {GenesisHash} + */ + get(index: number): GenesisHash; + /** + * @param {GenesisHash} elem + */ + add(elem: GenesisHash): void; +} +/** */ +export class GenesisKeyDelegation { + static __wrap(ptr: any): any; + /** + * @param {Uint8Array} bytes + * @returns {GenesisKeyDelegation} + */ + static from_bytes(bytes: Uint8Array): GenesisKeyDelegation; + /** + * @param {string} json + * @returns {GenesisKeyDelegation} + */ + static from_json(json: string): GenesisKeyDelegation; + /** + * @param {GenesisHash} genesishash + * @param {GenesisDelegateHash} genesis_delegate_hash + * @param {VRFKeyHash} vrf_keyhash + * @returns {GenesisKeyDelegation} + */ + static new(genesishash: GenesisHash, genesis_delegate_hash: GenesisDelegateHash, vrf_keyhash: VRFKeyHash): GenesisKeyDelegation; + __destroy_into_raw(): number | undefined; + ptr: number | undefined; + free(): void; + /** + * @returns {Uint8Array} + */ + to_bytes(): Uint8Array; + /** + * @returns {string} + */ + to_json(): string; + /** + * @returns {any} + */ + to_js_value(): any; + /** + * @returns {GenesisHash} + */ + genesishash(): GenesisHash; + /** + * @returns {GenesisDelegateHash} + */ + genesis_delegate_hash(): GenesisDelegateHash; + /** + * @returns {VRFKeyHash} + */ + vrf_keyhash(): VRFKeyHash; +} +/** */ +export class GovernanceAction { + static __wrap(ptr: any): any; + /** + * @param {Uint8Array} bytes + * @returns {GovernanceAction} + */ + static from_bytes(bytes: Uint8Array): GovernanceAction; + /** + * @param {string} json + * @returns {GovernanceAction} + */ + static from_json(json: string): GovernanceAction; + /** + * @param {ParameterChangeAction} parameter_change_action + * @returns {GovernanceAction} + */ + static new_parameter_change_action(parameter_change_action: ParameterChangeAction): GovernanceAction; + /** + * @param {HardForkInitiationAction} hard_fork_initiation_action + * @returns {GovernanceAction} + */ + static new_hard_fork_initiation_action(hard_fork_initiation_action: HardForkInitiationAction): GovernanceAction; + /** + * @param {TreasuryWithdrawalsAction} treasury_withdrawals_action + * @returns {GovernanceAction} + */ + static new_treasury_withdrawals_action(treasury_withdrawals_action: TreasuryWithdrawalsAction): GovernanceAction; + /** + * @returns {GovernanceAction} + */ + static new_no_confidence(): GovernanceAction; + /** + * @param {NewCommittee} new_committe + * @returns {GovernanceAction} + */ + static new_new_committee(new_committe: NewCommittee): GovernanceAction; + /** + * @param {NewConstitution} new_constitution + * @returns {GovernanceAction} + */ + static new_new_constitution(new_constitution: NewConstitution): GovernanceAction; + /** + * @returns {GovernanceAction} + */ + static new_info_action(): GovernanceAction; + __destroy_into_raw(): number | undefined; + ptr: number | undefined; + free(): void; + /** + * @returns {Uint8Array} + */ + to_bytes(): Uint8Array; + /** + * @returns {string} + */ + to_json(): string; + /** + * @returns {any} + */ + to_js_value(): any; + /** + * @returns {number} + */ + kind(): number; + /** + * @returns {ParameterChangeAction | undefined} + */ + as_parameter_change_action(): ParameterChangeAction | undefined; + /** + * @returns {HardForkInitiationAction | undefined} + */ + as_hard_fork_initiation_action(): HardForkInitiationAction | undefined; + /** + * @returns {TreasuryWithdrawalsAction | undefined} + */ + as_treasury_withdrawals_action(): TreasuryWithdrawalsAction | undefined; + /** + * @returns {NewCommittee | undefined} + */ + as_new_committee(): NewCommittee | undefined; + /** + * @returns {NewConstitution | undefined} + */ + as_new_constitution(): NewConstitution | undefined; +} +/** */ +export class GovernanceActionId { + static __wrap(ptr: any): any; + /** + * @param {Uint8Array} bytes + * @returns {GovernanceActionId} + */ + static from_bytes(bytes: Uint8Array): GovernanceActionId; + /** + * @param {string} json + * @returns {GovernanceActionId} + */ + static from_json(json: string): GovernanceActionId; + /** + * @param {TransactionHash} transaction_id + * @param {BigNum} governance_action_index + * @returns {GovernanceActionId} + */ + static new(transaction_id: TransactionHash, governance_action_index: BigNum): GovernanceActionId; + __destroy_into_raw(): number | undefined; + ptr: number | undefined; + free(): void; + /** + * @returns {Uint8Array} + */ + to_bytes(): Uint8Array; + /** + * @returns {string} + */ + to_json(): string; + /** + * @returns {any} + */ + to_js_value(): any; + /** + * @returns {TransactionHash} + */ + transaction_id(): TransactionHash; + /** + * @returns {BigNum} + */ + governance_action_index(): BigNum; +} +/** */ +export class HardForkInitiationAction { + static __wrap(ptr: any): any; + /** + * @param {Uint8Array} bytes + * @returns {HardForkInitiationAction} + */ + static from_bytes(bytes: Uint8Array): HardForkInitiationAction; + /** + * @param {string} json + * @returns {HardForkInitiationAction} + */ + static from_json(json: string): HardForkInitiationAction; + /** + * @param {ProtocolVersion} protocol_version + * @returns {HardForkInitiationAction} + */ + static new(protocol_version: ProtocolVersion): HardForkInitiationAction; + __destroy_into_raw(): number | undefined; + ptr: number | undefined; + free(): void; + /** + * @returns {Uint8Array} + */ + to_bytes(): Uint8Array; + /** + * @returns {string} + */ + to_json(): string; + /** + * @returns {any} + */ + to_js_value(): any; + /** + * @returns {ProtocolVersion} + */ + protocol_version(): ProtocolVersion; +} +/** */ +export class Header { + static __wrap(ptr: any): any; + /** + * @param {Uint8Array} bytes + * @returns {Header} + */ + static from_bytes(bytes: Uint8Array): Header; + /** + * @param {string} json + * @returns {Header} + */ + static from_json(json: string): Header; + /** + * @param {HeaderBody} header_body + * @param {KESSignature} body_signature + * @returns {Header} + */ + static new(header_body: HeaderBody, body_signature: KESSignature): Header; + __destroy_into_raw(): number | undefined; + ptr: number | undefined; + free(): void; + /** + * @returns {Uint8Array} + */ + to_bytes(): Uint8Array; + /** + * @returns {string} + */ + to_json(): string; + /** + * @returns {any} + */ + to_js_value(): any; + /** + * @returns {HeaderBody} + */ + header_body(): HeaderBody; + /** + * @returns {KESSignature} + */ + body_signature(): KESSignature; +} +/** */ +export class HeaderBody { + static __wrap(ptr: any): any; + /** + * @param {Uint8Array} bytes + * @returns {HeaderBody} + */ + static from_bytes(bytes: Uint8Array): HeaderBody; + /** + * @param {string} json + * @returns {HeaderBody} + */ + static from_json(json: string): HeaderBody; + /** + * @param {number} block_number + * @param {BigNum} slot + * @param {BlockHash | undefined} prev_hash + * @param {Vkey} issuer_vkey + * @param {VRFVKey} vrf_vkey + * @param {VRFCert} nonce_vrf + * @param {VRFCert} leader_vrf + * @param {number} block_body_size + * @param {BlockHash} block_body_hash + * @param {OperationalCert} operational_cert + * @param {ProtocolVersion} protocol_version + * @returns {HeaderBody} + */ + static new(block_number: number, slot: BigNum, prev_hash: BlockHash | undefined, issuer_vkey: Vkey, vrf_vkey: VRFVKey, nonce_vrf: VRFCert, leader_vrf: VRFCert, block_body_size: number, block_body_hash: BlockHash, operational_cert: OperationalCert, protocol_version: ProtocolVersion): HeaderBody; + __destroy_into_raw(): number | undefined; + ptr: number | undefined; + free(): void; + /** + * @returns {Uint8Array} + */ + to_bytes(): Uint8Array; + /** + * @returns {string} + */ + to_json(): string; + /** + * @returns {any} + */ + to_js_value(): any; + /** + * @returns {number} + */ + block_number(): number; + /** + * @returns {BigNum} + */ + slot(): BigNum; + /** + * @returns {BlockHash | undefined} + */ + prev_hash(): BlockHash | undefined; + /** + * @returns {Vkey} + */ + issuer_vkey(): Vkey; + /** + * @returns {VRFVKey} + */ + vrf_vkey(): VRFVKey; + /** + * @returns {VRFCert} + */ + nonce_vrf(): VRFCert; + /** + * @returns {VRFCert} + */ + leader_vrf(): VRFCert; + /** + * @returns {number} + */ + block_body_size(): number; + /** + * @returns {BlockHash} + */ + block_body_hash(): BlockHash; + /** + * @returns {OperationalCert} + */ + operational_cert(): OperationalCert; + /** + * @returns {ProtocolVersion} + */ + protocol_version(): ProtocolVersion; +} +/** */ +export class Int { + static __wrap(ptr: any): any; + /** + * @param {Uint8Array} bytes + * @returns {Int} + */ + static from_bytes(bytes: Uint8Array): Int; + /** + * @param {BigNum} x + * @returns {Int} + */ + static new(x: BigNum): Int; + /** + * @param {BigNum} x + * @returns {Int} + */ + static new_negative(x: BigNum): Int; + /** + * @param {number} x + * @returns {Int} + */ + static new_i32(x: number): Int; + /** + * @param {string} string + * @returns {Int} + */ + static from_str(string: string): Int; + __destroy_into_raw(): number | undefined; + ptr: number | undefined; + free(): void; + /** + * @returns {Uint8Array} + */ + to_bytes(): Uint8Array; + /** + * @returns {boolean} + */ + is_positive(): boolean; + /** + * BigNum can only contain unsigned u64 values + * + * This function will return the BigNum representation + * only in case the underlying i128 value is positive. + * + * Otherwise nothing will be returned (undefined). + * @returns {BigNum | undefined} + */ + as_positive(): BigNum | undefined; + /** + * BigNum can only contain unsigned u64 values + * + * This function will return the *absolute* BigNum representation + * only in case the underlying i128 value is negative. + * + * Otherwise nothing will be returned (undefined). + * @returns {BigNum | undefined} + */ + as_negative(): BigNum | undefined; + /** + * !!! DEPRECATED !!! + * Returns an i32 value in case the underlying original i128 value is within the limits. + * Otherwise will just return an empty value (undefined). + * @returns {number | undefined} + */ + as_i32(): number | undefined; + /** + * Returns the underlying value converted to i32 if possible (within limits) + * Otherwise will just return an empty value (undefined). + * @returns {number | undefined} + */ + as_i32_or_nothing(): number | undefined; + /** + * Returns the underlying value converted to i32 if possible (within limits) + * JsError in case of out of boundary overflow + * @returns {number} + */ + as_i32_or_fail(): number; + /** + * Returns string representation of the underlying i128 value directly. + * Might contain the minus sign (-) in case of negative value. + * @returns {string} + */ + to_str(): string; +} +/** */ +export class Ipv4 { + static __wrap(ptr: any): any; + /** + * @param {Uint8Array} bytes + * @returns {Ipv4} + */ + static from_bytes(bytes: Uint8Array): Ipv4; + /** + * @param {string} json + * @returns {Ipv4} + */ + static from_json(json: string): Ipv4; + /** + * @param {Uint8Array} data + * @returns {Ipv4} + */ + static new(data: Uint8Array): Ipv4; + __destroy_into_raw(): number | undefined; + ptr: number | undefined; + free(): void; + /** + * @returns {Uint8Array} + */ + to_bytes(): Uint8Array; + /** + * @returns {string} + */ + to_json(): string; + /** + * @returns {any} + */ + to_js_value(): any; + /** + * @returns {Uint8Array} + */ + ip(): Uint8Array; +} +/** */ +export class Ipv6 { + static __wrap(ptr: any): any; + /** + * @param {Uint8Array} bytes + * @returns {Ipv6} + */ + static from_bytes(bytes: Uint8Array): Ipv6; + /** + * @param {string} json + * @returns {Ipv6} + */ + static from_json(json: string): Ipv6; + /** + * @param {Uint8Array} data + * @returns {Ipv6} + */ + static new(data: Uint8Array): Ipv6; + __destroy_into_raw(): number | undefined; + ptr: number | undefined; + free(): void; + /** + * @returns {Uint8Array} + */ + to_bytes(): Uint8Array; + /** + * @returns {string} + */ + to_json(): string; + /** + * @returns {any} + */ + to_js_value(): any; + /** + * @returns {Uint8Array} + */ + ip(): Uint8Array; +} +/** */ +export class KESSignature { + static __wrap(ptr: any): any; + /** + * @param {Uint8Array} bytes + * @returns {KESSignature} + */ + static from_bytes(bytes: Uint8Array): KESSignature; + __destroy_into_raw(): number | undefined; + ptr: number | undefined; + free(): void; + /** + * @returns {Uint8Array} + */ + to_bytes(): Uint8Array; +} +/** */ +export class KESVKey { + static __wrap(ptr: any): any; + /** + * @param {Uint8Array} bytes + * @returns {KESVKey} + */ + static from_bytes(bytes: Uint8Array): KESVKey; + /** + * @param {string} bech_str + * @returns {KESVKey} + */ + static from_bech32(bech_str: string): KESVKey; + /** + * @param {string} hex + * @returns {KESVKey} + */ + static from_hex(hex: string): KESVKey; + __destroy_into_raw(): number | undefined; + ptr: number | undefined; + free(): void; + /** + * @returns {Uint8Array} + */ + to_bytes(): Uint8Array; + /** + * @param {string} prefix + * @returns {string} + */ + to_bech32(prefix: string): string; + /** + * @returns {string} + */ + to_hex(): string; +} +/** */ +export class Language { + static __wrap(ptr: any): any; + /** + * @param {Uint8Array} bytes + * @returns {Language} + */ + static from_bytes(bytes: Uint8Array): Language; + /** + * @returns {Language} + */ + static new_plutus_v1(): Language; + /** + * @returns {Language} + */ + static new_plutus_v2(): Language; + /** + * @returns {Language} + */ + static new_plutus_v3(): Language; + __destroy_into_raw(): number | undefined; + ptr: number | undefined; + free(): void; + /** + * @returns {Uint8Array} + */ + to_bytes(): Uint8Array; + /** + * @returns {number} + */ + kind(): number; +} +/** */ +export class Languages { + static __wrap(ptr: any): any; + /** + * @returns {Languages} + */ + static new(): Languages; + __destroy_into_raw(): number | undefined; + ptr: number | undefined; + free(): void; + /** + * @returns {number} + */ + len(): number; + /** + * @param {number} index + * @returns {Language} + */ + get(index: number): Language; + /** + * @param {Language} elem + */ + add(elem: Language): void; +} +/** */ +export class MIRToStakeCredentials { + static __wrap(ptr: any): any; + /** + * @param {Uint8Array} bytes + * @returns {MIRToStakeCredentials} + */ + static from_bytes(bytes: Uint8Array): MIRToStakeCredentials; + /** + * @param {string} json + * @returns {MIRToStakeCredentials} + */ + static from_json(json: string): MIRToStakeCredentials; + /** + * @returns {MIRToStakeCredentials} + */ + static new(): MIRToStakeCredentials; + __destroy_into_raw(): number | undefined; + ptr: number | undefined; + free(): void; + /** + * @returns {Uint8Array} + */ + to_bytes(): Uint8Array; + /** + * @returns {string} + */ + to_json(): string; + /** + * @returns {any} + */ + to_js_value(): any; + /** + * @returns {number} + */ + len(): number; + /** + * @param {StakeCredential} cred + * @param {Int} delta + * @returns {Int | undefined} + */ + insert(cred: StakeCredential, delta: Int): Int | undefined; + /** + * @param {StakeCredential} cred + * @returns {Int | undefined} + */ + get(cred: StakeCredential): Int | undefined; + /** + * @returns {StakeCredentials} + */ + keys(): StakeCredentials; +} +/** */ +export class MetadataList { + static __wrap(ptr: any): any; + /** + * @param {Uint8Array} bytes + * @returns {MetadataList} + */ + static from_bytes(bytes: Uint8Array): MetadataList; + /** + * @returns {MetadataList} + */ + static new(): MetadataList; + __destroy_into_raw(): number | undefined; + ptr: number | undefined; + free(): void; + /** + * @returns {Uint8Array} + */ + to_bytes(): Uint8Array; + /** + * @returns {number} + */ + len(): number; + /** + * @param {number} index + * @returns {TransactionMetadatum} + */ + get(index: number): TransactionMetadatum; + /** + * @param {TransactionMetadatum} elem + */ + add(elem: TransactionMetadatum): void; +} +/** */ +export class MetadataMap { + static __wrap(ptr: any): any; + /** + * @param {Uint8Array} bytes + * @returns {MetadataMap} + */ + static from_bytes(bytes: Uint8Array): MetadataMap; + /** + * @returns {MetadataMap} + */ + static new(): MetadataMap; + __destroy_into_raw(): number | undefined; + ptr: number | undefined; + free(): void; + /** + * @returns {Uint8Array} + */ + to_bytes(): Uint8Array; + /** + * @returns {number} + */ + len(): number; + /** + * @param {TransactionMetadatum} key + * @param {TransactionMetadatum} value + * @returns {TransactionMetadatum | undefined} + */ + insert(key: TransactionMetadatum, value: TransactionMetadatum): TransactionMetadatum | undefined; + /** + * @param {string} key + * @param {TransactionMetadatum} value + * @returns {TransactionMetadatum | undefined} + */ + insert_str(key: string, value: TransactionMetadatum): TransactionMetadatum | undefined; + /** + * @param {number} key + * @param {TransactionMetadatum} value + * @returns {TransactionMetadatum | undefined} + */ + insert_i32(key: number, value: TransactionMetadatum): TransactionMetadatum | undefined; + /** + * @param {TransactionMetadatum} key + * @returns {TransactionMetadatum} + */ + get(key: TransactionMetadatum): TransactionMetadatum; + /** + * @param {string} key + * @returns {TransactionMetadatum} + */ + get_str(key: string): TransactionMetadatum; + /** + * @param {number} key + * @returns {TransactionMetadatum} + */ + get_i32(key: number): TransactionMetadatum; + /** + * @param {TransactionMetadatum} key + * @returns {boolean} + */ + has(key: TransactionMetadatum): boolean; + /** + * @returns {MetadataList} + */ + keys(): MetadataList; +} +/** */ +export class Mint { + static __wrap(ptr: any): any; + /** + * @param {Uint8Array} bytes + * @returns {Mint} + */ + static from_bytes(bytes: Uint8Array): Mint; + /** + * @param {string} json + * @returns {Mint} + */ + static from_json(json: string): Mint; + /** + * @returns {Mint} + */ + static new(): Mint; + /** + * @param {ScriptHash} key + * @param {MintAssets} value + * @returns {Mint} + */ + static new_from_entry(key: ScriptHash, value: MintAssets): Mint; + __destroy_into_raw(): number | undefined; + ptr: number | undefined; + free(): void; + /** + * @returns {Uint8Array} + */ + to_bytes(): Uint8Array; + /** + * @returns {string} + */ + to_json(): string; + /** + * @returns {any} + */ + to_js_value(): any; + /** + * @returns {number} + */ + len(): number; + /** + * @param {ScriptHash} key + * @param {MintAssets} value + * @returns {MintAssets | undefined} + */ + insert(key: ScriptHash, value: MintAssets): MintAssets | undefined; + /** + * @param {ScriptHash} key + * @returns {MintAssets | undefined} + */ + get(key: ScriptHash): MintAssets | undefined; + /** + * @returns {ScriptHashes} + */ + keys(): ScriptHashes; + /** + * Returns the multiasset where only positive (minting) entries are present + * @returns {MultiAsset} + */ + as_positive_multiasset(): MultiAsset; + /** + * Returns the multiasset where only negative (burning) entries are present + * @returns {MultiAsset} + */ + as_negative_multiasset(): MultiAsset; +} +/** */ +export class MintAssets { + static __wrap(ptr: any): any; + /** + * @returns {MintAssets} + */ + static new(): MintAssets; + /** + * @param {AssetName} key + * @param {Int} value + * @returns {MintAssets} + */ + static new_from_entry(key: AssetName, value: Int): MintAssets; + __destroy_into_raw(): number | undefined; + ptr: number | undefined; + free(): void; + /** + * @returns {number} + */ + len(): number; + /** + * @param {AssetName} key + * @param {Int} value + * @returns {Int | undefined} + */ + insert(key: AssetName, value: Int): Int | undefined; + /** + * @param {AssetName} key + * @returns {Int | undefined} + */ + get(key: AssetName): Int | undefined; + /** + * @returns {AssetNames} + */ + keys(): AssetNames; +} +/** */ +export class MoveInstantaneousReward { + static __wrap(ptr: any): any; + /** + * @param {Uint8Array} bytes + * @returns {MoveInstantaneousReward} + */ + static from_bytes(bytes: Uint8Array): MoveInstantaneousReward; + /** + * @param {string} json + * @returns {MoveInstantaneousReward} + */ + static from_json(json: string): MoveInstantaneousReward; + /** + * @param {number} pot + * @param {BigNum} amount + * @returns {MoveInstantaneousReward} + */ + static new_to_other_pot(pot: number, amount: BigNum): MoveInstantaneousReward; + /** + * @param {number} pot + * @param {MIRToStakeCredentials} amounts + * @returns {MoveInstantaneousReward} + */ + static new_to_stake_creds(pot: number, amounts: MIRToStakeCredentials): MoveInstantaneousReward; + __destroy_into_raw(): number | undefined; + ptr: number | undefined; + free(): void; + /** + * @returns {Uint8Array} + */ + to_bytes(): Uint8Array; + /** + * @returns {string} + */ + to_json(): string; + /** + * @returns {any} + */ + to_js_value(): any; + /** + * @returns {number} + */ + pot(): number; + /** + * @returns {number} + */ + kind(): number; + /** + * @returns {BigNum | undefined} + */ + as_to_other_pot(): BigNum | undefined; + /** + * @returns {MIRToStakeCredentials | undefined} + */ + as_to_stake_creds(): MIRToStakeCredentials | undefined; +} +/** */ +export class MoveInstantaneousRewardsCert { + static __wrap(ptr: any): any; + /** + * @param {Uint8Array} bytes + * @returns {MoveInstantaneousRewardsCert} + */ + static from_bytes(bytes: Uint8Array): MoveInstantaneousRewardsCert; + /** + * @param {string} json + * @returns {MoveInstantaneousRewardsCert} + */ + static from_json(json: string): MoveInstantaneousRewardsCert; + /** + * @param {MoveInstantaneousReward} move_instantaneous_reward + * @returns {MoveInstantaneousRewardsCert} + */ + static new(move_instantaneous_reward: MoveInstantaneousReward): MoveInstantaneousRewardsCert; + __destroy_into_raw(): number | undefined; + ptr: number | undefined; + free(): void; + /** + * @returns {Uint8Array} + */ + to_bytes(): Uint8Array; + /** + * @returns {string} + */ + to_json(): string; + /** + * @returns {any} + */ + to_js_value(): any; + /** + * @returns {MoveInstantaneousReward} + */ + move_instantaneous_reward(): MoveInstantaneousReward; +} +/** */ +export class MultiAsset { + static __wrap(ptr: any): any; + /** + * @param {Uint8Array} bytes + * @returns {MultiAsset} + */ + static from_bytes(bytes: Uint8Array): MultiAsset; + /** + * @param {string} json + * @returns {MultiAsset} + */ + static from_json(json: string): MultiAsset; + /** + * @returns {MultiAsset} + */ + static new(): MultiAsset; + __destroy_into_raw(): number | undefined; + ptr: number | undefined; + free(): void; + /** + * @returns {Uint8Array} + */ + to_bytes(): Uint8Array; + /** + * @returns {string} + */ + to_json(): string; + /** + * @returns {any} + */ + to_js_value(): any; + /** + * the number of unique policy IDs in the multiasset + * @returns {number} + */ + len(): number; + /** + * set (and replace if it exists) all assets with policy {policy_id} to a copy of {assets} + * @param {ScriptHash} policy_id + * @param {Assets} assets + * @returns {Assets | undefined} + */ + insert(policy_id: ScriptHash, assets: Assets): Assets | undefined; + /** + * all assets under {policy_id}, if any exist, or else None (undefined in JS) + * @param {ScriptHash} policy_id + * @returns {Assets | undefined} + */ + get(policy_id: ScriptHash): Assets | undefined; + /** + * sets the asset {asset_name} to {value} under policy {policy_id} + * returns the previous amount if it was set, or else None (undefined in JS) + * @param {ScriptHash} policy_id + * @param {AssetName} asset_name + * @param {BigNum} value + * @returns {BigNum | undefined} + */ + set_asset(policy_id: ScriptHash, asset_name: AssetName, value: BigNum): BigNum | undefined; + /** + * returns the amount of asset {asset_name} under policy {policy_id} + * If such an asset does not exist, 0 is returned. + * @param {ScriptHash} policy_id + * @param {AssetName} asset_name + * @returns {BigNum} + */ + get_asset(policy_id: ScriptHash, asset_name: AssetName): BigNum; + /** + * returns all policy IDs used by assets in this multiasset + * @returns {ScriptHashes} + */ + keys(): ScriptHashes; + /** + * removes an asset from the list if the result is 0 or less + * does not modify this object, instead the result is returned + * @param {MultiAsset} rhs_ma + * @returns {MultiAsset} + */ + sub(rhs_ma: MultiAsset): MultiAsset; +} +/** */ +export class MultiHostName { + static __wrap(ptr: any): any; + /** + * @param {Uint8Array} bytes + * @returns {MultiHostName} + */ + static from_bytes(bytes: Uint8Array): MultiHostName; + /** + * @param {string} json + * @returns {MultiHostName} + */ + static from_json(json: string): MultiHostName; + /** + * @param {DNSRecordSRV} dns_name + * @returns {MultiHostName} + */ + static new(dns_name: DNSRecordSRV): MultiHostName; + __destroy_into_raw(): number | undefined; + ptr: number | undefined; + free(): void; + /** + * @returns {Uint8Array} + */ + to_bytes(): Uint8Array; + /** + * @returns {string} + */ + to_json(): string; + /** + * @returns {any} + */ + to_js_value(): any; + /** + * @returns {DNSRecordSRV} + */ + dns_name(): DNSRecordSRV; +} +/** */ +export class NativeScripts { + static __wrap(ptr: any): any; + /** + * @returns {NativeScripts} + */ + static new(): NativeScripts; + __destroy_into_raw(): number | undefined; + ptr: number | undefined; + free(): void; + /** + * @returns {number} + */ + len(): number; + /** + * @param {number} index + * @returns {NativeScript} + */ + get(index: number): NativeScript; + /** + * @param {NativeScript} elem + */ + add(elem: NativeScript): void; +} +/** */ +export class NetworkId { + static __wrap(ptr: any): any; + /** + * @param {Uint8Array} bytes + * @returns {NetworkId} + */ + static from_bytes(bytes: Uint8Array): NetworkId; + /** + * @param {string} json + * @returns {NetworkId} + */ + static from_json(json: string): NetworkId; + /** + * @returns {NetworkId} + */ + static testnet(): NetworkId; + /** + * @returns {NetworkId} + */ + static mainnet(): NetworkId; + __destroy_into_raw(): number | undefined; + ptr: number | undefined; + free(): void; + /** + * @returns {Uint8Array} + */ + to_bytes(): Uint8Array; + /** + * @returns {string} + */ + to_json(): string; + /** + * @returns {any} + */ + to_js_value(): any; + /** + * @returns {number} + */ + kind(): number; +} +/** */ +export class NetworkInfo { + static __wrap(ptr: any): any; + /** + * @param {number} network_id + * @param {number} protocol_magic + * @returns {NetworkInfo} + */ + static new(network_id: number, protocol_magic: number): NetworkInfo; + /** + * @returns {NetworkInfo} + */ + static testnet(): NetworkInfo; + /** + * @returns {NetworkInfo} + */ + static mainnet(): NetworkInfo; + __destroy_into_raw(): number | undefined; + ptr: number | undefined; + free(): void; + /** + * @returns {number} + */ + network_id(): number; + /** + * @returns {number} + */ + protocol_magic(): number; +} +/** */ +export class NewCommittee { + static __wrap(ptr: any): any; + /** + * @param {Uint8Array} bytes + * @returns {NewCommittee} + */ + static from_bytes(bytes: Uint8Array): NewCommittee; + /** + * @param {string} json + * @returns {NewCommittee} + */ + static from_json(json: string): NewCommittee; + /** + * @param {Ed25519KeyHashes} committee + * @param {UnitInterval} rational + * @returns {NewCommittee} + */ + static new(committee: Ed25519KeyHashes, rational: UnitInterval): NewCommittee; + __destroy_into_raw(): number | undefined; + ptr: number | undefined; + free(): void; + /** + * @returns {Uint8Array} + */ + to_bytes(): Uint8Array; + /** + * @returns {string} + */ + to_json(): string; + /** + * @returns {any} + */ + to_js_value(): any; + /** + * @returns {Ed25519KeyHashes} + */ + committee(): Ed25519KeyHashes; + /** + * @returns {UnitInterval} + */ + rational(): UnitInterval; +} +/** */ +export class NewConstitution { + static __wrap(ptr: any): any; + /** + * @param {Uint8Array} bytes + * @returns {NewConstitution} + */ + static from_bytes(bytes: Uint8Array): NewConstitution; + /** + * @param {string} json + * @returns {NewConstitution} + */ + static from_json(json: string): NewConstitution; + /** + * @param {DataHash} hash + * @returns {NewConstitution} + */ + static new(hash: DataHash): NewConstitution; + __destroy_into_raw(): number | undefined; + ptr: number | undefined; + free(): void; + /** + * @returns {Uint8Array} + */ + to_bytes(): Uint8Array; + /** + * @returns {string} + */ + to_json(): string; + /** + * @returns {any} + */ + to_js_value(): any; + /** + * @returns {DataHash} + */ + hash(): DataHash; +} +/** */ +export class Nonce { + static __wrap(ptr: any): any; + /** + * @param {Uint8Array} bytes + * @returns {Nonce} + */ + static from_bytes(bytes: Uint8Array): Nonce; + /** + * @returns {Nonce} + */ + static new_identity(): Nonce; + /** + * @param {Uint8Array} hash + * @returns {Nonce} + */ + static new_from_hash(hash: Uint8Array): Nonce; + __destroy_into_raw(): number | undefined; + ptr: number | undefined; + free(): void; + /** + * @returns {Uint8Array} + */ + to_bytes(): Uint8Array; + /** + * @returns {Uint8Array | undefined} + */ + get_hash(): Uint8Array | undefined; +} +/** */ +export class OperationalCert { + static __wrap(ptr: any): any; + /** + * @param {Uint8Array} bytes + * @returns {OperationalCert} + */ + static from_bytes(bytes: Uint8Array): OperationalCert; + /** + * @param {string} json + * @returns {OperationalCert} + */ + static from_json(json: string): OperationalCert; + /** + * @param {KESVKey} hot_vkey + * @param {number} sequence_number + * @param {number} kes_period + * @param {Ed25519Signature} sigma + * @returns {OperationalCert} + */ + static new(hot_vkey: KESVKey, sequence_number: number, kes_period: number, sigma: Ed25519Signature): OperationalCert; + __destroy_into_raw(): number | undefined; + ptr: number | undefined; + free(): void; + /** + * @returns {Uint8Array} + */ + to_bytes(): Uint8Array; + /** + * @returns {string} + */ + to_json(): string; + /** + * @returns {any} + */ + to_js_value(): any; + /** + * @returns {KESVKey} + */ + hot_vkey(): KESVKey; + /** + * @returns {number} + */ + sequence_number(): number; + /** + * @returns {number} + */ + kes_period(): number; + /** + * @returns {Ed25519Signature} + */ + sigma(): Ed25519Signature; +} +/** */ +export class ParameterChangeAction { + static __wrap(ptr: any): any; + /** + * @param {Uint8Array} bytes + * @returns {ParameterChangeAction} + */ + static from_bytes(bytes: Uint8Array): ParameterChangeAction; + /** + * @param {string} json + * @returns {ParameterChangeAction} + */ + static from_json(json: string): ParameterChangeAction; + /** + * @param {ProtocolParamUpdate} protocol_param_update + * @returns {ParameterChangeAction} + */ + static new(protocol_param_update: ProtocolParamUpdate): ParameterChangeAction; + __destroy_into_raw(): number | undefined; + ptr: number | undefined; + free(): void; + /** + * @returns {Uint8Array} + */ + to_bytes(): Uint8Array; + /** + * @returns {string} + */ + to_json(): string; + /** + * @returns {any} + */ + to_js_value(): any; + /** + * @returns {ProtocolParamUpdate} + */ + protocol_param_update(): ProtocolParamUpdate; +} +/** */ +export class PlutusMap { + static __wrap(ptr: any): any; + /** + * @param {Uint8Array} bytes + * @returns {PlutusMap} + */ + static from_bytes(bytes: Uint8Array): PlutusMap; + /** + * @returns {PlutusMap} + */ + static new(): PlutusMap; + __destroy_into_raw(): number | undefined; + ptr: number | undefined; + free(): void; + /** + * @returns {Uint8Array} + */ + to_bytes(): Uint8Array; + /** + * @returns {number} + */ + len(): number; + /** + * @param {PlutusData} key + * @param {PlutusData} value + * @returns {PlutusData | undefined} + */ + insert(key: PlutusData, value: PlutusData): PlutusData | undefined; + /** + * @param {PlutusData} key + * @returns {PlutusData | undefined} + */ + get(key: PlutusData): PlutusData | undefined; + /** + * @returns {PlutusList} + */ + keys(): PlutusList; +} +/** */ +export class PlutusScripts { + static __wrap(ptr: any): any; + /** + * @param {Uint8Array} bytes + * @returns {PlutusScripts} + */ + static from_bytes(bytes: Uint8Array): PlutusScripts; + /** + * @returns {PlutusScripts} + */ + static new(): PlutusScripts; + __destroy_into_raw(): number | undefined; + ptr: number | undefined; + free(): void; + /** + * @returns {Uint8Array} + */ + to_bytes(): Uint8Array; + /** + * @returns {number} + */ + len(): number; + /** + * @param {number} index + * @returns {PlutusScript} + */ + get(index: number): PlutusScript; + /** + * @param {PlutusScript} elem + */ + add(elem: PlutusScript): void; +} +/** */ +export class PlutusWitness { + static __wrap(ptr: any): any; + /** + * Plutus V1 witness or witness where no script is attached and so version doesn't matter + * @param {PlutusData} redeemer + * @param {PlutusData | undefined} plutus_data + * @param {PlutusScript | undefined} script + * @returns {PlutusWitness} + */ + static new(redeemer: PlutusData, plutus_data: PlutusData | undefined, script: PlutusScript | undefined): PlutusWitness; + /** + * @param {PlutusData} redeemer + * @param {PlutusData | undefined} plutus_data + * @param {PlutusScript | undefined} script + * @returns {PlutusWitness} + */ + static new_plutus_v2(redeemer: PlutusData, plutus_data: PlutusData | undefined, script: PlutusScript | undefined): PlutusWitness; + __destroy_into_raw(): number | undefined; + ptr: number | undefined; + free(): void; + /** + * @returns {PlutusData | undefined} + */ + plutus_data(): PlutusData | undefined; + /** + * @returns {PlutusData} + */ + redeemer(): PlutusData; + /** + * @returns {PlutusScript | undefined} + */ + script(): PlutusScript | undefined; + /** + * @returns {number} + */ + version(): number; +} +/** */ +export class Pointer { + static __wrap(ptr: any): any; + /** + * @param {BigNum} slot + * @param {BigNum} tx_index + * @param {BigNum} cert_index + * @returns {Pointer} + */ + static new(slot: BigNum, tx_index: BigNum, cert_index: BigNum): Pointer; + __destroy_into_raw(): number | undefined; + ptr: number | undefined; + free(): void; + /** + * @returns {BigNum} + */ + slot(): BigNum; + /** + * @returns {BigNum} + */ + tx_index(): BigNum; + /** + * @returns {BigNum} + */ + cert_index(): BigNum; +} +/** */ +export class PointerAddress { + static __wrap(ptr: any): any; + /** + * @param {number} network + * @param {StakeCredential} payment + * @param {Pointer} stake + * @returns {PointerAddress} + */ + static new(network: number, payment: StakeCredential, stake: Pointer): PointerAddress; + /** + * @param {Address} addr + * @returns {PointerAddress | undefined} + */ + static from_address(addr: Address): PointerAddress | undefined; + __destroy_into_raw(): number | undefined; + ptr: number | undefined; + free(): void; + /** + * @returns {StakeCredential} + */ + payment_cred(): StakeCredential; + /** + * @returns {Pointer} + */ + stake_pointer(): Pointer; + /** + * @returns {Address} + */ + to_address(): Address; +} +/** */ +export class PoolMetadata { + static __wrap(ptr: any): any; + /** + * @param {Uint8Array} bytes + * @returns {PoolMetadata} + */ + static from_bytes(bytes: Uint8Array): PoolMetadata; + /** + * @param {string} json + * @returns {PoolMetadata} + */ + static from_json(json: string): PoolMetadata; + /** + * @param {Url} url + * @param {PoolMetadataHash} pool_metadata_hash + * @returns {PoolMetadata} + */ + static new(url: Url, pool_metadata_hash: PoolMetadataHash): PoolMetadata; + __destroy_into_raw(): number | undefined; + ptr: number | undefined; + free(): void; + /** + * @returns {Uint8Array} + */ + to_bytes(): Uint8Array; + /** + * @returns {string} + */ + to_json(): string; + /** + * @returns {any} + */ + to_js_value(): any; + /** + * @returns {Url} + */ + url(): Url; + /** + * @returns {PoolMetadataHash} + */ + pool_metadata_hash(): PoolMetadataHash; +} +/** */ +export class PoolMetadataHash { + static __wrap(ptr: any): any; + /** + * @param {Uint8Array} bytes + * @returns {PoolMetadataHash} + */ + static from_bytes(bytes: Uint8Array): PoolMetadataHash; + /** + * @param {string} bech_str + * @returns {PoolMetadataHash} + */ + static from_bech32(bech_str: string): PoolMetadataHash; + /** + * @param {string} hex + * @returns {PoolMetadataHash} + */ + static from_hex(hex: string): PoolMetadataHash; + __destroy_into_raw(): number | undefined; + ptr: number | undefined; + free(): void; + /** + * @returns {Uint8Array} + */ + to_bytes(): Uint8Array; + /** + * @param {string} prefix + * @returns {string} + */ + to_bech32(prefix: string): string; + /** + * @returns {string} + */ + to_hex(): string; +} +/** */ +export class PoolParams { + static __wrap(ptr: any): any; + /** + * @param {Uint8Array} bytes + * @returns {PoolParams} + */ + static from_bytes(bytes: Uint8Array): PoolParams; + /** + * @param {string} json + * @returns {PoolParams} + */ + static from_json(json: string): PoolParams; + /** + * @param {Ed25519KeyHash} operator + * @param {VRFKeyHash} vrf_keyhash + * @param {BigNum} pledge + * @param {BigNum} cost + * @param {UnitInterval} margin + * @param {RewardAddress} reward_account + * @param {Ed25519KeyHashes} pool_owners + * @param {Relays} relays + * @param {PoolMetadata | undefined} pool_metadata + * @returns {PoolParams} + */ + static new(operator: Ed25519KeyHash, vrf_keyhash: VRFKeyHash, pledge: BigNum, cost: BigNum, margin: UnitInterval, reward_account: RewardAddress, pool_owners: Ed25519KeyHashes, relays: Relays, pool_metadata: PoolMetadata | undefined): PoolParams; + __destroy_into_raw(): number | undefined; + ptr: number | undefined; + free(): void; + /** + * @returns {Uint8Array} + */ + to_bytes(): Uint8Array; + /** + * @returns {string} + */ + to_json(): string; + /** + * @returns {any} + */ + to_js_value(): any; + /** + * @returns {Ed25519KeyHash} + */ + operator(): Ed25519KeyHash; + /** + * @returns {VRFKeyHash} + */ + vrf_keyhash(): VRFKeyHash; + /** + * @returns {BigNum} + */ + pledge(): BigNum; + /** + * @returns {BigNum} + */ + cost(): BigNum; + /** + * @returns {UnitInterval} + */ + margin(): UnitInterval; + /** + * @returns {RewardAddress} + */ + reward_account(): RewardAddress; + /** + * @returns {Ed25519KeyHashes} + */ + pool_owners(): Ed25519KeyHashes; + /** + * @returns {Relays} + */ + relays(): Relays; + /** + * @returns {PoolMetadata | undefined} + */ + pool_metadata(): PoolMetadata | undefined; +} +/** */ +export class PoolRegistration { + static __wrap(ptr: any): any; + /** + * @param {Uint8Array} bytes + * @returns {PoolRegistration} + */ + static from_bytes(bytes: Uint8Array): PoolRegistration; + /** + * @param {string} json + * @returns {PoolRegistration} + */ + static from_json(json: string): PoolRegistration; + /** + * @param {PoolParams} pool_params + * @returns {PoolRegistration} + */ + static new(pool_params: PoolParams): PoolRegistration; + __destroy_into_raw(): number | undefined; + ptr: number | undefined; + free(): void; + /** + * @returns {Uint8Array} + */ + to_bytes(): Uint8Array; + /** + * @returns {string} + */ + to_json(): string; + /** + * @returns {any} + */ + to_js_value(): any; + /** + * @returns {PoolParams} + */ + pool_params(): PoolParams; + /** + * @param {boolean} update + */ + set_is_update(update: boolean): void; +} +/** */ +export class PoolRetirement { + static __wrap(ptr: any): any; + /** + * @param {Uint8Array} bytes + * @returns {PoolRetirement} + */ + static from_bytes(bytes: Uint8Array): PoolRetirement; + /** + * @param {string} json + * @returns {PoolRetirement} + */ + static from_json(json: string): PoolRetirement; + /** + * @param {Ed25519KeyHash} pool_keyhash + * @param {number} epoch + * @returns {PoolRetirement} + */ + static new(pool_keyhash: Ed25519KeyHash, epoch: number): PoolRetirement; + __destroy_into_raw(): number | undefined; + ptr: number | undefined; + free(): void; + /** + * @returns {Uint8Array} + */ + to_bytes(): Uint8Array; + /** + * @returns {string} + */ + to_json(): string; + /** + * @returns {any} + */ + to_js_value(): any; + /** + * @returns {Ed25519KeyHash} + */ + pool_keyhash(): Ed25519KeyHash; + /** + * @returns {number} + */ + epoch(): number; +} +/** */ +export class PoolVotingThresholds { + static __wrap(ptr: any): any; + /** + * @param {Uint8Array} bytes + * @returns {PoolVotingThresholds} + */ + static from_bytes(bytes: Uint8Array): PoolVotingThresholds; + /** + * @param {string} json + * @returns {PoolVotingThresholds} + */ + static from_json(json: string): PoolVotingThresholds; + /** + * @param {UnitInterval} motion_no_confidence + * @param {UnitInterval} committee_normal + * @param {UnitInterval} committee_no_confidence + * @param {UnitInterval} hard_fork_initiation + * @returns {PoolVotingThresholds} + */ + static new(motion_no_confidence: UnitInterval, committee_normal: UnitInterval, committee_no_confidence: UnitInterval, hard_fork_initiation: UnitInterval): PoolVotingThresholds; + __destroy_into_raw(): number | undefined; + ptr: number | undefined; + free(): void; + /** + * @returns {Uint8Array} + */ + to_bytes(): Uint8Array; + /** + * @returns {string} + */ + to_json(): string; + /** + * @returns {any} + */ + to_js_value(): any; + /** + * @returns {UnitInterval} + */ + motion_no_confidence(): UnitInterval; + /** + * @returns {UnitInterval} + */ + committee_normal(): UnitInterval; + /** + * @returns {UnitInterval} + */ + committee_no_confidence(): UnitInterval; + /** + * @returns {UnitInterval} + */ + hard_fork_initiation(): UnitInterval; +} +/** */ +export class ProposalProcedure { + static __wrap(ptr: any): any; + /** + * @param {Uint8Array} bytes + * @returns {ProposalProcedure} + */ + static from_bytes(bytes: Uint8Array): ProposalProcedure; + /** + * @param {string} json + * @returns {ProposalProcedure} + */ + static from_json(json: string): ProposalProcedure; + /** + * @param {BigNum} deposit + * @param {ScriptHash} hash + * @param {GovernanceAction} governance_action + * @param {Anchor} anchor + * @returns {ProposalProcedure} + */ + static new(deposit: BigNum, hash: ScriptHash, governance_action: GovernanceAction, anchor: Anchor): ProposalProcedure; + __destroy_into_raw(): number | undefined; + ptr: number | undefined; + free(): void; + /** + * @returns {Uint8Array} + */ + to_bytes(): Uint8Array; + /** + * @returns {string} + */ + to_json(): string; + /** + * @returns {any} + */ + to_js_value(): any; + /** + * @returns {BigNum} + */ + deposit(): BigNum; + /** + * @returns {ScriptHash} + */ + hash(): ScriptHash; + /** + * @returns {GovernanceAction} + */ + governance_action(): GovernanceAction; + /** + * @returns {Anchor} + */ + anchor(): Anchor; +} +/** */ +export class ProposalProcedures { + static __wrap(ptr: any): any; + /** + * @param {Uint8Array} bytes + * @returns {ProposalProcedures} + */ + static from_bytes(bytes: Uint8Array): ProposalProcedures; + /** + * @returns {ProposalProcedures} + */ + static new(): ProposalProcedures; + __destroy_into_raw(): number | undefined; + ptr: number | undefined; + free(): void; + /** + * @returns {Uint8Array} + */ + to_bytes(): Uint8Array; + /** + * @returns {number} + */ + len(): number; + /** + * @param {number} index + * @returns {ProposalProcedure} + */ + get(index: number): ProposalProcedure; + /** + * @param {ProposalProcedure} elem + */ + add(elem: ProposalProcedure): void; +} +/** */ +export class ProposedProtocolParameterUpdates { + static __wrap(ptr: any): any; + /** + * @param {Uint8Array} bytes + * @returns {ProposedProtocolParameterUpdates} + */ + static from_bytes(bytes: Uint8Array): ProposedProtocolParameterUpdates; + /** + * @param {string} json + * @returns {ProposedProtocolParameterUpdates} + */ + static from_json(json: string): ProposedProtocolParameterUpdates; + /** + * @returns {ProposedProtocolParameterUpdates} + */ + static new(): ProposedProtocolParameterUpdates; + __destroy_into_raw(): number | undefined; + ptr: number | undefined; + free(): void; + /** + * @returns {Uint8Array} + */ + to_bytes(): Uint8Array; + /** + * @returns {string} + */ + to_json(): string; + /** + * @returns {any} + */ + to_js_value(): any; + /** + * @returns {number} + */ + len(): number; + /** + * @param {GenesisHash} key + * @param {ProtocolParamUpdate} value + * @returns {ProtocolParamUpdate | undefined} + */ + insert(key: GenesisHash, value: ProtocolParamUpdate): ProtocolParamUpdate | undefined; + /** + * @param {GenesisHash} key + * @returns {ProtocolParamUpdate | undefined} + */ + get(key: GenesisHash): ProtocolParamUpdate | undefined; + /** + * @returns {GenesisHashes} + */ + keys(): GenesisHashes; +} +/** */ +export class ProtocolParamUpdate { + static __wrap(ptr: any): any; + /** + * @param {Uint8Array} bytes + * @returns {ProtocolParamUpdate} + */ + static from_bytes(bytes: Uint8Array): ProtocolParamUpdate; + /** + * @param {string} json + * @returns {ProtocolParamUpdate} + */ + static from_json(json: string): ProtocolParamUpdate; + /** + * @returns {ProtocolParamUpdate} + */ + static new(): ProtocolParamUpdate; + __destroy_into_raw(): number | undefined; + ptr: number | undefined; + free(): void; + /** + * @returns {Uint8Array} + */ + to_bytes(): Uint8Array; + /** + * @returns {string} + */ + to_json(): string; + /** + * @returns {any} + */ + to_js_value(): any; + /** + * @param {BigNum} minfee_a + */ + set_minfee_a(minfee_a: BigNum): void; + /** + * @returns {BigNum | undefined} + */ + minfee_a(): BigNum | undefined; + /** + * @param {BigNum} minfee_b + */ + set_minfee_b(minfee_b: BigNum): void; + /** + * @returns {BigNum | undefined} + */ + minfee_b(): BigNum | undefined; + /** + * @param {number} max_block_body_size + */ + set_max_block_body_size(max_block_body_size: number): void; + /** + * @returns {number | undefined} + */ + max_block_body_size(): number | undefined; + /** + * @param {number} max_tx_size + */ + set_max_tx_size(max_tx_size: number): void; + /** + * @returns {number | undefined} + */ + max_tx_size(): number | undefined; + /** + * @param {number} max_block_header_size + */ + set_max_block_header_size(max_block_header_size: number): void; + /** + * @returns {number | undefined} + */ + max_block_header_size(): number | undefined; + /** + * @param {BigNum} key_deposit + */ + set_key_deposit(key_deposit: BigNum): void; + /** + * @returns {BigNum | undefined} + */ + key_deposit(): BigNum | undefined; + /** + * @param {BigNum} pool_deposit + */ + set_pool_deposit(pool_deposit: BigNum): void; + /** + * @returns {BigNum | undefined} + */ + pool_deposit(): BigNum | undefined; + /** + * @param {number} max_epoch + */ + set_max_epoch(max_epoch: number): void; + /** + * @returns {number | undefined} + */ + max_epoch(): number | undefined; + /** + * @param {number} n_opt + */ + set_n_opt(n_opt: number): void; + /** + * @returns {number | undefined} + */ + n_opt(): number | undefined; + /** + * @param {UnitInterval} pool_pledge_influence + */ + set_pool_pledge_influence(pool_pledge_influence: UnitInterval): void; + /** + * @returns {UnitInterval | undefined} + */ + pool_pledge_influence(): UnitInterval | undefined; + /** + * @param {UnitInterval} expansion_rate + */ + set_expansion_rate(expansion_rate: UnitInterval): void; + /** + * @returns {UnitInterval | undefined} + */ + expansion_rate(): UnitInterval | undefined; + /** + * @param {UnitInterval} treasury_growth_rate + */ + set_treasury_growth_rate(treasury_growth_rate: UnitInterval): void; + /** + * @returns {UnitInterval | undefined} + */ + treasury_growth_rate(): UnitInterval | undefined; + /** + * @param {UnitInterval} d + */ + set_d(d: UnitInterval): void; + /** + * @returns {UnitInterval | undefined} + */ + d(): UnitInterval | undefined; + /** + * @param {Nonce} extra_entropy + */ + set_extra_entropy(extra_entropy: Nonce): void; + /** + * @returns {Nonce | undefined} + */ + extra_entropy(): Nonce | undefined; + /** + * @param {ProtocolVersion} protocol_version + */ + set_protocol_version(protocol_version: ProtocolVersion): void; + /** + * @returns {ProtocolVersion | undefined} + */ + protocol_version(): ProtocolVersion | undefined; + /** + * @param {BigNum} min_pool_cost + */ + set_min_pool_cost(min_pool_cost: BigNum): void; + /** + * @returns {BigNum | undefined} + */ + min_pool_cost(): BigNum | undefined; + /** + * @param {BigNum} ada_per_utxo_byte + */ + set_ada_per_utxo_byte(ada_per_utxo_byte: BigNum): void; + /** + * @returns {BigNum | undefined} + */ + ada_per_utxo_byte(): BigNum | undefined; + /** + * @param {Costmdls} cost_models + */ + set_cost_models(cost_models: Costmdls): void; + /** + * @returns {Costmdls | undefined} + */ + cost_models(): Costmdls | undefined; + /** + * @param {ExUnitPrices} execution_costs + */ + set_execution_costs(execution_costs: ExUnitPrices): void; + /** + * @returns {ExUnitPrices | undefined} + */ + execution_costs(): ExUnitPrices | undefined; + /** + * @param {ExUnits} max_tx_ex_units + */ + set_max_tx_ex_units(max_tx_ex_units: ExUnits): void; + /** + * @returns {ExUnits | undefined} + */ + max_tx_ex_units(): ExUnits | undefined; + /** + * @param {ExUnits} max_block_ex_units + */ + set_max_block_ex_units(max_block_ex_units: ExUnits): void; + /** + * @returns {ExUnits | undefined} + */ + max_block_ex_units(): ExUnits | undefined; + /** + * @param {number} max_value_size + */ + set_max_value_size(max_value_size: number): void; + /** + * @returns {number | undefined} + */ + max_value_size(): number | undefined; + /** + * @param {number} collateral_percentage + */ + set_collateral_percentage(collateral_percentage: number): void; + /** + * @returns {number | undefined} + */ + collateral_percentage(): number | undefined; + /** + * @param {number} max_collateral_inputs + */ + set_max_collateral_inputs(max_collateral_inputs: number): void; + /** + * @returns {number | undefined} + */ + max_collateral_inputs(): number | undefined; + /** + * @param {PoolVotingThresholds} pool_voting_thresholds + */ + set_pool_voting_thresholds(pool_voting_thresholds: PoolVotingThresholds): void; + /** + * @returns {PoolVotingThresholds | undefined} + */ + pool_voting_thresholds(): PoolVotingThresholds | undefined; + /** + * @param {DrepVotingThresholds} drep_voting_thresholds + */ + set_drep_voting_thresholds(drep_voting_thresholds: DrepVotingThresholds): void; + /** + * @returns {DrepVotingThresholds | undefined} + */ + drep_voting_thresholds(): DrepVotingThresholds | undefined; + /** + * @param {BigNum} min_committee_size + */ + set_min_committee_size(min_committee_size: BigNum): void; + /** + * @returns {BigNum | undefined} + */ + min_committee_size(): BigNum | undefined; + /** + * @param {BigNum} committee_term_limit + */ + set_committee_term_limit(committee_term_limit: BigNum): void; + /** + * @returns {BigNum | undefined} + */ + committee_term_limit(): BigNum | undefined; + /** + * @param {BigNum} governance_action_expiration + */ + set_governance_action_expiration(governance_action_expiration: BigNum): void; + /** + * @returns {BigNum | undefined} + */ + governance_action_expiration(): BigNum | undefined; + /** + * @param {BigNum} governance_action_deposit + */ + set_governance_action_deposit(governance_action_deposit: BigNum): void; + /** + * @returns {BigNum | undefined} + */ + governance_action_deposit(): BigNum | undefined; + /** + * @param {BigNum} drep_deposit + */ + set_drep_deposit(drep_deposit: BigNum): void; + /** + * @returns {BigNum | undefined} + */ + drep_deposit(): BigNum | undefined; + /** + * @param {number} drep_inactivity_period + */ + set_drep_inactivity_period(drep_inactivity_period: number): void; + /** + * @returns {number | undefined} + */ + drep_inactivity_period(): number | undefined; +} +/** */ +export class ProtocolVersion { + static __wrap(ptr: any): any; + /** + * @param {Uint8Array} bytes + * @returns {ProtocolVersion} + */ + static from_bytes(bytes: Uint8Array): ProtocolVersion; + /** + * @param {string} json + * @returns {ProtocolVersion} + */ + static from_json(json: string): ProtocolVersion; + /** + * @param {number} major + * @param {number} minor + * @returns {ProtocolVersion} + */ + static new(major: number, minor: number): ProtocolVersion; + __destroy_into_raw(): number | undefined; + ptr: number | undefined; + free(): void; + /** + * @returns {Uint8Array} + */ + to_bytes(): Uint8Array; + /** + * @returns {string} + */ + to_json(): string; + /** + * @returns {any} + */ + to_js_value(): any; + /** + * @returns {number} + */ + major(): number; + /** + * @returns {number} + */ + minor(): number; +} +/** + * ED25519 key used as public key + */ +export class PublicKey { + static __wrap(ptr: any): any; + /** + * Get public key from its bech32 representation + * Example: + * ```javascript + * const pkey = PublicKey.from_bech32('ed25519_pk1dgaagyh470y66p899txcl3r0jaeaxu6yd7z2dxyk55qcycdml8gszkxze2'); + * ``` + * @param {string} bech32_str + * @returns {PublicKey} + */ + static from_bech32(bech32_str: string): PublicKey; + /** + * @param {Uint8Array} bytes + * @returns {PublicKey} + */ + static from_bytes(bytes: Uint8Array): PublicKey; + __destroy_into_raw(): number | undefined; + ptr: number | undefined; + free(): void; + /** + * @returns {string} + */ + to_bech32(): string; + /** + * @returns {Uint8Array} + */ + as_bytes(): Uint8Array; + /** + * @param {Uint8Array} data + * @param {Ed25519Signature} signature + * @returns {boolean} + */ + verify(data: Uint8Array, signature: Ed25519Signature): boolean; + /** + * @returns {Ed25519KeyHash} + */ + hash(): Ed25519KeyHash; +} +/** */ +export class PublicKeys { + static __wrap(ptr: any): any; + __destroy_into_raw(): number | undefined; + ptr: number | undefined; + free(): void; + /** + * @returns {number} + */ + size(): number; + /** + * @param {number} index + * @returns {PublicKey} + */ + get(index: number): PublicKey; + /** + * @param {PublicKey} key + */ + add(key: PublicKey): void; +} +/** */ +export class Redeemer { + static __wrap(ptr: any): any; + /** + * @param {Uint8Array} bytes + * @returns {Redeemer} + */ + static from_bytes(bytes: Uint8Array): Redeemer; + /** + * @param {RedeemerTag} tag + * @param {BigNum} index + * @param {PlutusData} data + * @param {ExUnits} ex_units + * @returns {Redeemer} + */ + static new(tag: RedeemerTag, index: BigNum, data: PlutusData, ex_units: ExUnits): Redeemer; + __destroy_into_raw(): number | undefined; + ptr: number | undefined; + free(): void; + /** + * @returns {Uint8Array} + */ + to_bytes(): Uint8Array; + /** + * @returns {RedeemerTag} + */ + tag(): RedeemerTag; + /** + * @returns {BigNum} + */ + index(): BigNum; + /** + * @returns {PlutusData} + */ + data(): PlutusData; + /** + * @returns {ExUnits} + */ + ex_units(): ExUnits; +} +/** */ +export class RedeemerTag { + static __wrap(ptr: any): any; + /** + * @param {Uint8Array} bytes + * @returns {RedeemerTag} + */ + static from_bytes(bytes: Uint8Array): RedeemerTag; + /** + * @returns {RedeemerTag} + */ + static new_spend(): RedeemerTag; + /** + * @returns {RedeemerTag} + */ + static new_mint(): RedeemerTag; + /** + * @returns {RedeemerTag} + */ + static new_cert(): RedeemerTag; + /** + * @returns {RedeemerTag} + */ + static new_reward(): RedeemerTag; + /** + * @returns {RedeemerTag} + */ + static new_drep(): RedeemerTag; + __destroy_into_raw(): number | undefined; + ptr: number | undefined; + free(): void; + /** + * @returns {Uint8Array} + */ + to_bytes(): Uint8Array; + /** + * @returns {number} + */ + kind(): number; +} +/** */ +export class RedeemerWitnessKey { + static __wrap(ptr: any): any; + /** + * @param {RedeemerTag} tag + * @param {BigNum} index + * @returns {RedeemerWitnessKey} + */ + static new(tag: RedeemerTag, index: BigNum): RedeemerWitnessKey; + __destroy_into_raw(): number | undefined; + ptr: number | undefined; + free(): void; + /** + * @returns {RedeemerTag} + */ + tag(): RedeemerTag; + /** + * @returns {BigNum} + */ + index(): BigNum; +} +/** */ +export class RegCert { + static __wrap(ptr: any): any; + /** + * @param {Uint8Array} bytes + * @returns {RegCert} + */ + static from_bytes(bytes: Uint8Array): RegCert; + /** + * @param {string} json + * @returns {RegCert} + */ + static from_json(json: string): RegCert; + /** + * @param {StakeCredential} stake_credential + * @param {BigNum} coin + * @returns {RegCert} + */ + static new(stake_credential: StakeCredential, coin: BigNum): RegCert; + __destroy_into_raw(): number | undefined; + ptr: number | undefined; + free(): void; + /** + * @returns {Uint8Array} + */ + to_bytes(): Uint8Array; + /** + * @returns {string} + */ + to_json(): string; + /** + * @returns {any} + */ + to_js_value(): any; + /** + * @returns {StakeCredential} + */ + stake_credential(): StakeCredential; + /** + * @returns {BigNum} + */ + coin(): BigNum; +} +/** */ +export class RegCommitteeHotKeyCert { + static __wrap(ptr: any): any; + /** + * @param {Uint8Array} bytes + * @returns {RegCommitteeHotKeyCert} + */ + static from_bytes(bytes: Uint8Array): RegCommitteeHotKeyCert; + /** + * @param {string} json + * @returns {RegCommitteeHotKeyCert} + */ + static from_json(json: string): RegCommitteeHotKeyCert; + /** + * @param {Ed25519KeyHash} committee_cold_keyhash + * @param {Ed25519KeyHash} committee_hot_keyhash + * @returns {RegCommitteeHotKeyCert} + */ + static new(committee_cold_keyhash: Ed25519KeyHash, committee_hot_keyhash: Ed25519KeyHash): RegCommitteeHotKeyCert; + __destroy_into_raw(): number | undefined; + ptr: number | undefined; + free(): void; + /** + * @returns {Uint8Array} + */ + to_bytes(): Uint8Array; + /** + * @returns {string} + */ + to_json(): string; + /** + * @returns {any} + */ + to_js_value(): any; + /** + * @returns {Ed25519KeyHash} + */ + committee_cold_keyhash(): Ed25519KeyHash; + /** + * @returns {Ed25519KeyHash} + */ + committee_hot_keyhash(): Ed25519KeyHash; +} +/** */ +export class RegDrepCert { + static __wrap(ptr: any): any; + /** + * @param {Uint8Array} bytes + * @returns {RegDrepCert} + */ + static from_bytes(bytes: Uint8Array): RegDrepCert; + /** + * @param {string} json + * @returns {RegDrepCert} + */ + static from_json(json: string): RegDrepCert; + /** + * @param {StakeCredential} voting_credential + * @param {BigNum} coin + * @returns {RegDrepCert} + */ + static new(voting_credential: StakeCredential, coin: BigNum): RegDrepCert; + __destroy_into_raw(): number | undefined; + ptr: number | undefined; + free(): void; + /** + * @returns {Uint8Array} + */ + to_bytes(): Uint8Array; + /** + * @returns {string} + */ + to_json(): string; + /** + * @returns {any} + */ + to_js_value(): any; + /** + * @returns {StakeCredential} + */ + voting_credential(): StakeCredential; + /** + * @returns {BigNum} + */ + coin(): BigNum; +} +/** */ +export class Relay { + static __wrap(ptr: any): any; + /** + * @param {Uint8Array} bytes + * @returns {Relay} + */ + static from_bytes(bytes: Uint8Array): Relay; + /** + * @param {string} json + * @returns {Relay} + */ + static from_json(json: string): Relay; + /** + * @param {SingleHostAddr} single_host_addr + * @returns {Relay} + */ + static new_single_host_addr(single_host_addr: SingleHostAddr): Relay; + /** + * @param {SingleHostName} single_host_name + * @returns {Relay} + */ + static new_single_host_name(single_host_name: SingleHostName): Relay; + /** + * @param {MultiHostName} multi_host_name + * @returns {Relay} + */ + static new_multi_host_name(multi_host_name: MultiHostName): Relay; + __destroy_into_raw(): number | undefined; + ptr: number | undefined; + free(): void; + /** + * @returns {Uint8Array} + */ + to_bytes(): Uint8Array; + /** + * @returns {string} + */ + to_json(): string; + /** + * @returns {any} + */ + to_js_value(): any; + /** + * @returns {number} + */ + kind(): number; + /** + * @returns {SingleHostAddr | undefined} + */ + as_single_host_addr(): SingleHostAddr | undefined; + /** + * @returns {SingleHostName | undefined} + */ + as_single_host_name(): SingleHostName | undefined; + /** + * @returns {MultiHostName | undefined} + */ + as_multi_host_name(): MultiHostName | undefined; +} +/** */ +export class Relays { + static __wrap(ptr: any): any; + /** + * @param {Uint8Array} bytes + * @returns {Relays} + */ + static from_bytes(bytes: Uint8Array): Relays; + /** + * @param {string} json + * @returns {Relays} + */ + static from_json(json: string): Relays; + /** + * @returns {Relays} + */ + static new(): Relays; + __destroy_into_raw(): number | undefined; + ptr: number | undefined; + free(): void; + /** + * @returns {Uint8Array} + */ + to_bytes(): Uint8Array; + /** + * @returns {string} + */ + to_json(): string; + /** + * @returns {any} + */ + to_js_value(): any; + /** + * @returns {number} + */ + len(): number; + /** + * @param {number} index + * @returns {Relay} + */ + get(index: number): Relay; + /** + * @param {Relay} elem + */ + add(elem: Relay): void; +} +/** */ +export class RequiredWitnessSet { + static __wrap(ptr: any): any; + /** + * @returns {RequiredWitnessSet} + */ + static new(): RequiredWitnessSet; + __destroy_into_raw(): number | undefined; + ptr: number | undefined; + free(): void; + /** + * @param {Vkeywitness} vkey + */ + add_vkey(vkey: Vkeywitness): void; + /** + * @param {Vkey} vkey + */ + add_vkey_key(vkey: Vkey): void; + /** + * @param {Ed25519KeyHash} hash + */ + add_vkey_key_hash(hash: Ed25519KeyHash): void; + /** + * @param {BootstrapWitness} bootstrap + */ + add_bootstrap(bootstrap: BootstrapWitness): void; + /** + * @param {Vkey} bootstrap + */ + add_bootstrap_key(bootstrap: Vkey): void; + /** + * @param {Ed25519KeyHash} hash + */ + add_bootstrap_key_hash(hash: Ed25519KeyHash): void; + /** + * @param {NativeScript} native_script + */ + add_native_script(native_script: NativeScript): void; + /** + * @param {ScriptHash} native_script + */ + add_native_script_hash(native_script: ScriptHash): void; + /** + * @param {PlutusScript} plutus_script + */ + add_plutus_script(plutus_script: PlutusScript): void; + /** + * @param {PlutusScript} plutus_script + */ + add_plutus_v2_script(plutus_script: PlutusScript): void; + /** + * @param {ScriptHash} plutus_script + */ + add_plutus_hash(plutus_script: ScriptHash): void; + /** + * @param {PlutusData} plutus_datum + */ + add_plutus_datum(plutus_datum: PlutusData): void; + /** + * @param {DataHash} plutus_datum + */ + add_plutus_datum_hash(plutus_datum: DataHash): void; + /** + * @param {Redeemer} redeemer + */ + add_redeemer(redeemer: Redeemer): void; + /** + * @param {RedeemerWitnessKey} redeemer + */ + add_redeemer_tag(redeemer: RedeemerWitnessKey): void; + /** + * @param {RequiredWitnessSet} requirements + */ + add_all(requirements: RequiredWitnessSet): void; +} +/** */ +export class RewardAddress { + static __wrap(ptr: any): any; + /** + * @param {number} network + * @param {StakeCredential} payment + * @returns {RewardAddress} + */ + static new(network: number, payment: StakeCredential): RewardAddress; + /** + * @param {Address} addr + * @returns {RewardAddress | undefined} + */ + static from_address(addr: Address): RewardAddress | undefined; + __destroy_into_raw(): number | undefined; + ptr: number | undefined; + free(): void; + /** + * @returns {StakeCredential} + */ + payment_cred(): StakeCredential; + /** + * @returns {Address} + */ + to_address(): Address; +} +/** */ +export class RewardAddresses { + static __wrap(ptr: any): any; + /** + * @param {Uint8Array} bytes + * @returns {RewardAddresses} + */ + static from_bytes(bytes: Uint8Array): RewardAddresses; + /** + * @param {string} json + * @returns {RewardAddresses} + */ + static from_json(json: string): RewardAddresses; + /** + * @returns {RewardAddresses} + */ + static new(): RewardAddresses; + __destroy_into_raw(): number | undefined; + ptr: number | undefined; + free(): void; + /** + * @returns {Uint8Array} + */ + to_bytes(): Uint8Array; + /** + * @returns {string} + */ + to_json(): string; + /** + * @returns {any} + */ + to_js_value(): any; + /** + * @returns {number} + */ + len(): number; + /** + * @param {number} index + * @returns {RewardAddress} + */ + get(index: number): RewardAddress; + /** + * @param {RewardAddress} elem + */ + add(elem: RewardAddress): void; +} +/** */ +export class Script { + static __wrap(ptr: any): any; + /** + * @param {Uint8Array} bytes + * @returns {Script} + */ + static from_bytes(bytes: Uint8Array): Script; + /** + * @param {string} json + * @returns {Script} + */ + static from_json(json: string): Script; + /** + * @param {NativeScript} native_script + * @returns {Script} + */ + static new_native(native_script: NativeScript): Script; + /** + * @param {PlutusScript} plutus_script + * @returns {Script} + */ + static new_plutus_v1(plutus_script: PlutusScript): Script; + /** + * @param {PlutusScript} plutus_script + * @returns {Script} + */ + static new_plutus_v2(plutus_script: PlutusScript): Script; + /** + * @param {PlutusScript} plutus_script + * @returns {Script} + */ + static new_plutus_v3(plutus_script: PlutusScript): Script; + __destroy_into_raw(): number | undefined; + ptr: number | undefined; + free(): void; + /** + * @returns {Uint8Array} + */ + to_bytes(): Uint8Array; + /** + * @returns {string} + */ + to_json(): string; + /** + * @returns {any} + */ + to_js_value(): any; + /** + * @returns {number} + */ + kind(): number; + /** + * @returns {NativeScript | undefined} + */ + as_native(): NativeScript | undefined; + /** + * @returns {PlutusScript | undefined} + */ + as_plutus_v1(): PlutusScript | undefined; + /** + * @returns {PlutusScript | undefined} + */ + as_plutus_v2(): PlutusScript | undefined; + /** + * @returns {PlutusScript | undefined} + */ + as_plutus_v3(): PlutusScript | undefined; +} +/** */ +export class ScriptAll { + static __wrap(ptr: any): any; + /** + * @param {Uint8Array} bytes + * @returns {ScriptAll} + */ + static from_bytes(bytes: Uint8Array): ScriptAll; + /** + * @param {string} json + * @returns {ScriptAll} + */ + static from_json(json: string): ScriptAll; + /** + * @param {NativeScripts} native_scripts + * @returns {ScriptAll} + */ + static new(native_scripts: NativeScripts): ScriptAll; + __destroy_into_raw(): number | undefined; + ptr: number | undefined; + free(): void; + /** + * @returns {Uint8Array} + */ + to_bytes(): Uint8Array; + /** + * @returns {string} + */ + to_json(): string; + /** + * @returns {any} + */ + to_js_value(): any; + /** + * @returns {NativeScripts} + */ + native_scripts(): NativeScripts; +} +/** */ +export class ScriptAny { + static __wrap(ptr: any): any; + /** + * @param {Uint8Array} bytes + * @returns {ScriptAny} + */ + static from_bytes(bytes: Uint8Array): ScriptAny; + /** + * @param {string} json + * @returns {ScriptAny} + */ + static from_json(json: string): ScriptAny; + /** + * @param {NativeScripts} native_scripts + * @returns {ScriptAny} + */ + static new(native_scripts: NativeScripts): ScriptAny; + __destroy_into_raw(): number | undefined; + ptr: number | undefined; + free(): void; + /** + * @returns {Uint8Array} + */ + to_bytes(): Uint8Array; + /** + * @returns {string} + */ + to_json(): string; + /** + * @returns {any} + */ + to_js_value(): any; + /** + * @returns {NativeScripts} + */ + native_scripts(): NativeScripts; +} +/** */ +export class ScriptHash { + static __wrap(ptr: any): any; + /** + * @param {Uint8Array} bytes + * @returns {ScriptHash} + */ + static from_bytes(bytes: Uint8Array): ScriptHash; + /** + * @param {string} bech_str + * @returns {ScriptHash} + */ + static from_bech32(bech_str: string): ScriptHash; + /** + * @param {string} hex + * @returns {ScriptHash} + */ + static from_hex(hex: string): ScriptHash; + __destroy_into_raw(): number | undefined; + ptr: number | undefined; + free(): void; + /** + * @returns {Uint8Array} + */ + to_bytes(): Uint8Array; + /** + * @param {string} prefix + * @returns {string} + */ + to_bech32(prefix: string): string; + /** + * @returns {string} + */ + to_hex(): string; +} +/** */ +export class ScriptHashes { + static __wrap(ptr: any): any; + /** + * @param {Uint8Array} bytes + * @returns {ScriptHashes} + */ + static from_bytes(bytes: Uint8Array): ScriptHashes; + /** + * @param {string} json + * @returns {ScriptHashes} + */ + static from_json(json: string): ScriptHashes; + /** + * @returns {ScriptHashes} + */ + static new(): ScriptHashes; + __destroy_into_raw(): number | undefined; + ptr: number | undefined; + free(): void; + /** + * @returns {Uint8Array} + */ + to_bytes(): Uint8Array; + /** + * @returns {string} + */ + to_json(): string; + /** + * @returns {any} + */ + to_js_value(): any; + /** + * @returns {number} + */ + len(): number; + /** + * @param {number} index + * @returns {ScriptHash} + */ + get(index: number): ScriptHash; + /** + * @param {ScriptHash} elem + */ + add(elem: ScriptHash): void; +} +/** */ +export class ScriptNOfK { + static __wrap(ptr: any): any; + /** + * @param {Uint8Array} bytes + * @returns {ScriptNOfK} + */ + static from_bytes(bytes: Uint8Array): ScriptNOfK; + /** + * @param {string} json + * @returns {ScriptNOfK} + */ + static from_json(json: string): ScriptNOfK; + /** + * @param {number} n + * @param {NativeScripts} native_scripts + * @returns {ScriptNOfK} + */ + static new(n: number, native_scripts: NativeScripts): ScriptNOfK; + __destroy_into_raw(): number | undefined; + ptr: number | undefined; + free(): void; + /** + * @returns {Uint8Array} + */ + to_bytes(): Uint8Array; + /** + * @returns {string} + */ + to_json(): string; + /** + * @returns {any} + */ + to_js_value(): any; + /** + * @returns {number} + */ + n(): number; + /** + * @returns {NativeScripts} + */ + native_scripts(): NativeScripts; +} +/** */ +export class ScriptPubkey { + static __wrap(ptr: any): any; + /** + * @param {Uint8Array} bytes + * @returns {ScriptPubkey} + */ + static from_bytes(bytes: Uint8Array): ScriptPubkey; + /** + * @param {string} json + * @returns {ScriptPubkey} + */ + static from_json(json: string): ScriptPubkey; + /** + * @param {Ed25519KeyHash} addr_keyhash + * @returns {ScriptPubkey} + */ + static new(addr_keyhash: Ed25519KeyHash): ScriptPubkey; + __destroy_into_raw(): number | undefined; + ptr: number | undefined; + free(): void; + /** + * @returns {Uint8Array} + */ + to_bytes(): Uint8Array; + /** + * @returns {string} + */ + to_json(): string; + /** + * @returns {any} + */ + to_js_value(): any; + /** + * @returns {Ed25519KeyHash} + */ + addr_keyhash(): Ed25519KeyHash; +} +/** */ +export class ScriptRef { + static __wrap(ptr: any): any; + /** + * @param {Uint8Array} bytes + * @returns {ScriptRef} + */ + static from_bytes(bytes: Uint8Array): ScriptRef; + /** + * @param {string} json + * @returns {ScriptRef} + */ + static from_json(json: string): ScriptRef; + /** + * @param {Script} script + * @returns {ScriptRef} + */ + static new(script: Script): ScriptRef; + __destroy_into_raw(): number | undefined; + ptr: number | undefined; + free(): void; + /** + * @returns {Uint8Array} + */ + to_bytes(): Uint8Array; + /** + * @returns {string} + */ + to_json(): string; + /** + * @returns {any} + */ + to_js_value(): any; + /** + * @returns {Script} + */ + get(): Script; +} +/** */ +export class ScriptWitness { + static __wrap(ptr: any): any; + /** + * @param {string} json + * @returns {ScriptWitness} + */ + static from_json(json: string): ScriptWitness; + /** + * @param {NativeScript} native_script + * @returns {ScriptWitness} + */ + static new_native_witness(native_script: NativeScript): ScriptWitness; + /** + * @param {PlutusWitness} plutus_witness + * @returns {ScriptWitness} + */ + static new_plutus_witness(plutus_witness: PlutusWitness): ScriptWitness; + __destroy_into_raw(): number | undefined; + ptr: number | undefined; + free(): void; + /** + * @returns {string} + */ + to_json(): string; + /** + * @returns {any} + */ + to_js_value(): any; + /** + * @returns {number} + */ + kind(): number; + /** + * @returns {NativeScript | undefined} + */ + as_native_witness(): NativeScript | undefined; + /** + * @returns {PlutusWitness | undefined} + */ + as_plutus_witness(): PlutusWitness | undefined; +} +/** */ +export class SingleHostAddr { + static __wrap(ptr: any): any; + /** + * @param {Uint8Array} bytes + * @returns {SingleHostAddr} + */ + static from_bytes(bytes: Uint8Array): SingleHostAddr; + /** + * @param {string} json + * @returns {SingleHostAddr} + */ + static from_json(json: string): SingleHostAddr; + /** + * @param {number | undefined} port + * @param {Ipv4 | undefined} ipv4 + * @param {Ipv6 | undefined} ipv6 + * @returns {SingleHostAddr} + */ + static new(port: number | undefined, ipv4: Ipv4 | undefined, ipv6: Ipv6 | undefined): SingleHostAddr; + __destroy_into_raw(): number | undefined; + ptr: number | undefined; + free(): void; + /** + * @returns {Uint8Array} + */ + to_bytes(): Uint8Array; + /** + * @returns {string} + */ + to_json(): string; + /** + * @returns {any} + */ + to_js_value(): any; + /** + * @returns {number | undefined} + */ + port(): number | undefined; + /** + * @returns {Ipv4 | undefined} + */ + ipv4(): Ipv4 | undefined; + /** + * @returns {Ipv6 | undefined} + */ + ipv6(): Ipv6 | undefined; +} +/** */ +export class SingleHostName { + static __wrap(ptr: any): any; + /** + * @param {Uint8Array} bytes + * @returns {SingleHostName} + */ + static from_bytes(bytes: Uint8Array): SingleHostName; + /** + * @param {string} json + * @returns {SingleHostName} + */ + static from_json(json: string): SingleHostName; + /** + * @param {number | undefined} port + * @param {DNSRecordAorAAAA} dns_name + * @returns {SingleHostName} + */ + static new(port: number | undefined, dns_name: DNSRecordAorAAAA): SingleHostName; + __destroy_into_raw(): number | undefined; + ptr: number | undefined; + free(): void; + /** + * @returns {Uint8Array} + */ + to_bytes(): Uint8Array; + /** + * @returns {string} + */ + to_json(): string; + /** + * @returns {any} + */ + to_js_value(): any; + /** + * @returns {number | undefined} + */ + port(): number | undefined; + /** + * @returns {DNSRecordAorAAAA} + */ + dns_name(): DNSRecordAorAAAA; +} +/** */ +export class StakeCredential { + static __wrap(ptr: any): any; + /** + * @param {Ed25519KeyHash} hash + * @returns {StakeCredential} + */ + static from_keyhash(hash: Ed25519KeyHash): StakeCredential; + /** + * @param {ScriptHash} hash + * @returns {StakeCredential} + */ + static from_scripthash(hash: ScriptHash): StakeCredential; + /** + * @param {Uint8Array} bytes + * @returns {StakeCredential} + */ + static from_bytes(bytes: Uint8Array): StakeCredential; + /** + * @param {string} json + * @returns {StakeCredential} + */ + static from_json(json: string): StakeCredential; + __destroy_into_raw(): number | undefined; + ptr: number | undefined; + free(): void; + /** + * @returns {Ed25519KeyHash | undefined} + */ + to_keyhash(): Ed25519KeyHash | undefined; + /** + * @returns {ScriptHash | undefined} + */ + to_scripthash(): ScriptHash | undefined; + /** + * @returns {number} + */ + kind(): number; + /** + * @returns {Uint8Array} + */ + to_bytes(): Uint8Array; + /** + * @returns {string} + */ + to_json(): string; + /** + * @returns {any} + */ + to_js_value(): any; +} +/** */ +export class StakeCredentials { + static __wrap(ptr: any): any; + /** + * @param {Uint8Array} bytes + * @returns {StakeCredentials} + */ + static from_bytes(bytes: Uint8Array): StakeCredentials; + /** + * @param {string} json + * @returns {StakeCredentials} + */ + static from_json(json: string): StakeCredentials; + /** + * @returns {StakeCredentials} + */ + static new(): StakeCredentials; + __destroy_into_raw(): number | undefined; + ptr: number | undefined; + free(): void; + /** + * @returns {Uint8Array} + */ + to_bytes(): Uint8Array; + /** + * @returns {string} + */ + to_json(): string; + /** + * @returns {any} + */ + to_js_value(): any; + /** + * @returns {number} + */ + len(): number; + /** + * @param {number} index + * @returns {StakeCredential} + */ + get(index: number): StakeCredential; + /** + * @param {StakeCredential} elem + */ + add(elem: StakeCredential): void; +} +/** */ +export class StakeDelegation { + static __wrap(ptr: any): any; + /** + * @param {Uint8Array} bytes + * @returns {StakeDelegation} + */ + static from_bytes(bytes: Uint8Array): StakeDelegation; + /** + * @param {string} json + * @returns {StakeDelegation} + */ + static from_json(json: string): StakeDelegation; + /** + * @param {StakeCredential} stake_credential + * @param {Ed25519KeyHash} pool_keyhash + * @returns {StakeDelegation} + */ + static new(stake_credential: StakeCredential, pool_keyhash: Ed25519KeyHash): StakeDelegation; + __destroy_into_raw(): number | undefined; + ptr: number | undefined; + free(): void; + /** + * @returns {Uint8Array} + */ + to_bytes(): Uint8Array; + /** + * @returns {string} + */ + to_json(): string; + /** + * @returns {any} + */ + to_js_value(): any; + /** + * @returns {StakeCredential} + */ + stake_credential(): StakeCredential; + /** + * @returns {Ed25519KeyHash} + */ + pool_keyhash(): Ed25519KeyHash; +} +/** */ +export class StakeDeregistration { + static __wrap(ptr: any): any; + /** + * @param {Uint8Array} bytes + * @returns {StakeDeregistration} + */ + static from_bytes(bytes: Uint8Array): StakeDeregistration; + /** + * @param {string} json + * @returns {StakeDeregistration} + */ + static from_json(json: string): StakeDeregistration; + /** + * @param {StakeCredential} stake_credential + * @returns {StakeDeregistration} + */ + static new(stake_credential: StakeCredential): StakeDeregistration; + __destroy_into_raw(): number | undefined; + ptr: number | undefined; + free(): void; + /** + * @returns {Uint8Array} + */ + to_bytes(): Uint8Array; + /** + * @returns {string} + */ + to_json(): string; + /** + * @returns {any} + */ + to_js_value(): any; + /** + * @returns {StakeCredential} + */ + stake_credential(): StakeCredential; +} +/** */ +export class StakeRegDelegCert { + static __wrap(ptr: any): any; + /** + * @param {Uint8Array} bytes + * @returns {StakeRegDelegCert} + */ + static from_bytes(bytes: Uint8Array): StakeRegDelegCert; + /** + * @param {string} json + * @returns {StakeRegDelegCert} + */ + static from_json(json: string): StakeRegDelegCert; + /** + * @param {StakeCredential} stake_credential + * @param {Ed25519KeyHash} pool_keyhash + * @param {BigNum} coin + * @returns {StakeRegDelegCert} + */ + static new(stake_credential: StakeCredential, pool_keyhash: Ed25519KeyHash, coin: BigNum): StakeRegDelegCert; + __destroy_into_raw(): number | undefined; + ptr: number | undefined; + free(): void; + /** + * @returns {Uint8Array} + */ + to_bytes(): Uint8Array; + /** + * @returns {string} + */ + to_json(): string; + /** + * @returns {any} + */ + to_js_value(): any; + /** + * @returns {StakeCredential} + */ + stake_credential(): StakeCredential; + /** + * @returns {Ed25519KeyHash} + */ + pool_keyhash(): Ed25519KeyHash; + /** + * @returns {BigNum} + */ + coin(): BigNum; +} +/** */ +export class StakeRegistration { + static __wrap(ptr: any): any; + /** + * @param {Uint8Array} bytes + * @returns {StakeRegistration} + */ + static from_bytes(bytes: Uint8Array): StakeRegistration; + /** + * @param {string} json + * @returns {StakeRegistration} + */ + static from_json(json: string): StakeRegistration; + /** + * @param {StakeCredential} stake_credential + * @returns {StakeRegistration} + */ + static new(stake_credential: StakeCredential): StakeRegistration; + __destroy_into_raw(): number | undefined; + ptr: number | undefined; + free(): void; + /** + * @returns {Uint8Array} + */ + to_bytes(): Uint8Array; + /** + * @returns {string} + */ + to_json(): string; + /** + * @returns {any} + */ + to_js_value(): any; + /** + * @returns {StakeCredential} + */ + stake_credential(): StakeCredential; +} +/** */ +export class StakeVoteDelegCert { + static __wrap(ptr: any): any; + /** + * @param {Uint8Array} bytes + * @returns {StakeVoteDelegCert} + */ + static from_bytes(bytes: Uint8Array): StakeVoteDelegCert; + /** + * @param {string} json + * @returns {StakeVoteDelegCert} + */ + static from_json(json: string): StakeVoteDelegCert; + /** + * @param {StakeCredential} stake_credential + * @param {Ed25519KeyHash} pool_keyhash + * @param {Drep} drep + * @returns {StakeVoteDelegCert} + */ + static new(stake_credential: StakeCredential, pool_keyhash: Ed25519KeyHash, drep: Drep): StakeVoteDelegCert; + __destroy_into_raw(): number | undefined; + ptr: number | undefined; + free(): void; + /** + * @returns {Uint8Array} + */ + to_bytes(): Uint8Array; + /** + * @returns {string} + */ + to_json(): string; + /** + * @returns {any} + */ + to_js_value(): any; + /** + * @returns {StakeCredential} + */ + stake_credential(): StakeCredential; + /** + * @returns {Ed25519KeyHash} + */ + pool_keyhash(): Ed25519KeyHash; + /** + * @returns {Drep} + */ + drep(): Drep; +} +/** */ +export class StakeVoteRegDelegCert { + static __wrap(ptr: any): any; + /** + * @param {Uint8Array} bytes + * @returns {StakeVoteRegDelegCert} + */ + static from_bytes(bytes: Uint8Array): StakeVoteRegDelegCert; + /** + * @param {string} json + * @returns {StakeVoteRegDelegCert} + */ + static from_json(json: string): StakeVoteRegDelegCert; + /** + * @param {StakeCredential} stake_credential + * @param {Ed25519KeyHash} pool_keyhash + * @param {Drep} drep + * @param {BigNum} coin + * @returns {StakeVoteRegDelegCert} + */ + static new(stake_credential: StakeCredential, pool_keyhash: Ed25519KeyHash, drep: Drep, coin: BigNum): StakeVoteRegDelegCert; + __destroy_into_raw(): number | undefined; + ptr: number | undefined; + free(): void; + /** + * @returns {Uint8Array} + */ + to_bytes(): Uint8Array; + /** + * @returns {string} + */ + to_json(): string; + /** + * @returns {any} + */ + to_js_value(): any; + /** + * @returns {StakeCredential} + */ + stake_credential(): StakeCredential; + /** + * @returns {Ed25519KeyHash} + */ + pool_keyhash(): Ed25519KeyHash; + /** + * @returns {Drep} + */ + drep(): Drep; + /** + * @returns {BigNum} + */ + coin(): BigNum; +} +/** */ +export class Strings { + static __wrap(ptr: any): any; + /** + * @returns {Strings} + */ + static new(): Strings; + __destroy_into_raw(): number | undefined; + ptr: number | undefined; + free(): void; + /** + * @returns {number} + */ + len(): number; + /** + * @param {number} index + * @returns {string} + */ + get(index: number): string; + /** + * @param {string} elem + */ + add(elem: string): void; +} +/** */ +export class TimelockExpiry { + static __wrap(ptr: any): any; + /** + * @param {Uint8Array} bytes + * @returns {TimelockExpiry} + */ + static from_bytes(bytes: Uint8Array): TimelockExpiry; + /** + * @param {string} json + * @returns {TimelockExpiry} + */ + static from_json(json: string): TimelockExpiry; + /** + * @param {BigNum} slot + * @returns {TimelockExpiry} + */ + static new(slot: BigNum): TimelockExpiry; + __destroy_into_raw(): number | undefined; + ptr: number | undefined; + free(): void; + /** + * @returns {Uint8Array} + */ + to_bytes(): Uint8Array; + /** + * @returns {string} + */ + to_json(): string; + /** + * @returns {any} + */ + to_js_value(): any; + /** + * @returns {BigNum} + */ + slot(): BigNum; +} +/** */ +export class TimelockStart { + static __wrap(ptr: any): any; + /** + * @param {Uint8Array} bytes + * @returns {TimelockStart} + */ + static from_bytes(bytes: Uint8Array): TimelockStart; + /** + * @param {string} json + * @returns {TimelockStart} + */ + static from_json(json: string): TimelockStart; + /** + * @param {BigNum} slot + * @returns {TimelockStart} + */ + static new(slot: BigNum): TimelockStart; + __destroy_into_raw(): number | undefined; + ptr: number | undefined; + free(): void; + /** + * @returns {Uint8Array} + */ + to_bytes(): Uint8Array; + /** + * @returns {string} + */ + to_json(): string; + /** + * @returns {any} + */ + to_js_value(): any; + /** + * @returns {BigNum} + */ + slot(): BigNum; +} +/** */ +export class TransactionBodies { + static __wrap(ptr: any): any; + /** + * @param {Uint8Array} bytes + * @returns {TransactionBodies} + */ + static from_bytes(bytes: Uint8Array): TransactionBodies; + /** + * @param {string} json + * @returns {TransactionBodies} + */ + static from_json(json: string): TransactionBodies; + /** + * @returns {TransactionBodies} + */ + static new(): TransactionBodies; + __destroy_into_raw(): number | undefined; + ptr: number | undefined; + free(): void; + /** + * @returns {Uint8Array} + */ + to_bytes(): Uint8Array; + /** + * @returns {string} + */ + to_json(): string; + /** + * @returns {any} + */ + to_js_value(): any; + /** + * @returns {number} + */ + len(): number; + /** + * @param {number} index + * @returns {TransactionBody} + */ + get(index: number): TransactionBody; + /** + * @param {TransactionBody} elem + */ + add(elem: TransactionBody): void; +} +/** */ +export class TransactionBuilder { + static __wrap(ptr: any): any; + /** + * @param {TransactionBuilderConfig} cfg + * @returns {TransactionBuilder} + */ + static new(cfg: TransactionBuilderConfig): TransactionBuilder; + __destroy_into_raw(): number | undefined; + ptr: number | undefined; + free(): void; + /** + * This automatically selects and adds inputs from {inputs} consisting of just enough to cover + * the outputs that have already been added. + * This should be called after adding all certs/outputs/etc and will be an error otherwise. + * Adding a change output must be called after via TransactionBuilder::balance() + * inputs to cover the minimum fees. This does not, however, set the txbuilder's fee. + * + * change_address is required here in order to determine the min ada requirement precisely + * weights is a coma separated representation of a Uint32Arary + * @param {TransactionUnspentOutputs} inputs + * @param {Address} change_address + * @param {string} weights_str + */ + add_inputs_from_impl(inputs: TransactionUnspentOutputs, change_address: Address, weights_str: string): void; + /** + * This automatically selects and adds inputs from {inputs} consisting of just enough to cover + * the outputs that have already been added. + * This should be called after adding all certs/outputs/etc and will be an error otherwise. + * Adding a change output must be called after via TransactionBuilder::balance() + * inputs to cover the minimum fees. This does not, however, set the txbuilder's fee. + * + * change_address is required here in order to determine the min ada requirement precisely + * @param {TransactionUnspentOutputs} inputs + * @param {Address} change_address + * @param {Uint32Array} weights + */ + add_inputs_from(inputs: TransactionUnspentOutputs, change_address: Address, weights: Uint32Array): void; + /** + * @param {TransactionUnspentOutput} utxo + * @param {ScriptWitness | undefined} script_witness + */ + add_input(utxo: TransactionUnspentOutput, script_witness: ScriptWitness | undefined): void; + /** + * @param {TransactionUnspentOutput} utxo + */ + add_reference_input(utxo: TransactionUnspentOutput): void; + /** + * calculates how much the fee would increase if you added a given output + * @param {Address} address + * @param {TransactionInput} input + * @param {Value} amount + * @returns {BigNum} + */ + fee_for_input(address: Address, input: TransactionInput, amount: Value): BigNum; + /** + * Add explicit output via a TransactionOutput object + * @param {TransactionOutput} output + */ + add_output(output: TransactionOutput): void; + /** + * Add plutus scripts via a PlutusScripts object + * @param {PlutusScript} plutus_script + */ + add_plutus_script(plutus_script: PlutusScript): void; + /** + * Add plutus v2 scripts via a PlutusScripts object + * @param {PlutusScript} plutus_script + */ + add_plutus_v2_script(plutus_script: PlutusScript): void; + /** + * Add plutus data via a PlutusData object + * @param {PlutusData} plutus_data + */ + add_plutus_data(plutus_data: PlutusData): void; + /** + * Add native scripts via a NativeScripts object + * @param {NativeScript} native_script + */ + add_native_script(native_script: NativeScript): void; + /** + * Add certificate via a Certificates object + * @param {Certificate} certificate + * @param {ScriptWitness | undefined} script_witness + */ + add_certificate(certificate: Certificate, script_witness: ScriptWitness | undefined): void; + /** + * calculates how much the fee would increase if you added a given output + * @param {TransactionOutput} output + * @returns {BigNum} + */ + fee_for_output(output: TransactionOutput): BigNum; + /** + * @param {BigNum} ttl + */ + set_ttl(ttl: BigNum): void; + /** + * @param {BigNum} validity_start_interval + */ + set_validity_start_interval(validity_start_interval: BigNum): void; + /** + * @param {RewardAddress} reward_address + * @param {BigNum} coin + * @param {ScriptWitness | undefined} script_witness + */ + add_withdrawal(reward_address: RewardAddress, coin: BigNum, script_witness: ScriptWitness | undefined): void; + /** + * @returns {AuxiliaryData | undefined} + */ + auxiliary_data(): AuxiliaryData | undefined; + /** + * Set explicit auxiliary data via an AuxiliaryData object + * It might contain some metadata plus native or Plutus scripts + * @param {AuxiliaryData} auxiliary_data + */ + set_auxiliary_data(auxiliary_data: AuxiliaryData): void; + /** + * Set metadata using a GeneralTransactionMetadata object + * It will be set to the existing or new auxiliary data in this builder + * @param {GeneralTransactionMetadata} metadata + */ + set_metadata(metadata: GeneralTransactionMetadata): void; + /** + * Add a single metadatum using TransactionMetadatumLabel and TransactionMetadatum objects + * It will be securely added to existing or new metadata in this builder + * @param {BigNum} key + * @param {TransactionMetadatum} val + */ + add_metadatum(key: BigNum, val: TransactionMetadatum): void; + /** + * Add a single JSON metadatum using a TransactionMetadatumLabel and a String + * It will be securely added to existing or new metadata in this builder + * @param {BigNum} key + * @param {string} val + */ + add_json_metadatum(key: BigNum, val: string): void; + /** + * Add a single JSON metadatum using a TransactionMetadatumLabel, a String, and a MetadataJsonSchema object + * It will be securely added to existing or new metadata in this builder + * @param {BigNum} key + * @param {string} val + * @param {number} schema + */ + add_json_metadatum_with_schema(key: BigNum, val: string, schema: number): void; + /** + * Returns a copy of the current mint state in the builder + * @returns {Mint | undefined} + */ + mint(): Mint | undefined; + /** + * @returns {Certificates | undefined} + */ + certificates(): Certificates | undefined; + /** + * @returns {Withdrawals | undefined} + */ + withdrawals(): Withdrawals | undefined; + /** + * Returns a copy of the current witness native scripts in the builder + * @returns {NativeScripts | undefined} + */ + native_scripts(): NativeScripts | undefined; + /** + * Add a mint entry to this builder using a PolicyID and MintAssets object + * It will be securely added to existing or new Mint in this builder + * It will securely add assets to an existing PolicyID + * But it will replace/overwrite any existing mint assets with the same PolicyID + * first redeemer applied to a PolicyID is taken for all further assets added to the same PolicyID + * @param {ScriptHash} policy_id + * @param {MintAssets} mint_assets + * @param {ScriptWitness | undefined} script_witness + */ + add_mint(policy_id: ScriptHash, mint_assets: MintAssets, script_witness: ScriptWitness | undefined): void; + /** + * @returns {ScriptDataHash | undefined} + */ + script_data_hash(): ScriptDataHash | undefined; + /** + * @param {TransactionUnspentOutput} utxo + */ + add_collateral(utxo: TransactionUnspentOutput): void; + /** + * @returns {TransactionInputs | undefined} + */ + get_collateral(): TransactionInputs | undefined; + /** + * @param {Ed25519KeyHash} required_signer + */ + add_required_signer(required_signer: Ed25519KeyHash): void; + /** + * @returns {Ed25519KeyHashes | undefined} + */ + required_signers(): Ed25519KeyHashes | undefined; + /** + * @param {NetworkId} network_id + */ + set_network_id(network_id: NetworkId): void; + /** + * @returns {NetworkId | undefined} + */ + network_id(): NetworkId | undefined; + /** + * @returns {Redeemers | undefined} + */ + redeemers(): Redeemers | undefined; + /** + * does not include refunds or withdrawals + * @returns {Value} + */ + get_explicit_input(): Value; + /** + * withdrawals and refunds + * @returns {Value} + */ + get_implicit_input(): Value; + /** + * Return explicit input plus implicit input plus mint + * @returns {Value} + */ + get_total_input(): Value; + /** + * Return explicit output plus implicit output plus burn (does not consider fee directly) + * @returns {Value} + */ + get_total_output(): Value; + /** + * does not include fee + * @returns {Value} + */ + get_explicit_output(): Value; + /** + * @returns {BigNum} + */ + get_deposit(): BigNum; + /** + * @returns {BigNum | undefined} + */ + get_fee_if_set(): BigNum | undefined; + /** + * Warning: this function will mutate the /fee/ field + * Make sure to call this function last after setting all other tx-body properties + * Editing inputs, outputs, mint, etc. after change been calculated + * might cause a mismatch in calculated fee versus the required fee + * @param {Address} change_address + * @param {Datum | undefined} datum + */ + balance(change_address: Address, datum: Datum | undefined): void; + /** + * Returns the TransactionBody. + * @returns {Uint8Array} + */ + to_bytes(): Uint8Array; + /** + * @returns {number} + */ + full_size(): number; + /** + * @returns {Uint32Array} + */ + output_sizes(): Uint32Array; + /** + * @returns {TransactionOutputs} + */ + outputs(): TransactionOutputs; + /** + * Returns full Transaction object with the body and the auxiliary data + * + * NOTE: witness_set will contain all mint_scripts if any been added or set + * + * takes fetched ex units into consideration + * + * add collateral utxos and collateral change receiver in case you redeem from plutus script utxos + * + * async call + * + * NOTE: is_valid set to true + * @param {TransactionUnspentOutputs | undefined} collateral_utxos + * @param {Address | undefined} collateral_change_address + * @param {boolean | undefined} native_uplc + * @returns {Promise} + */ + construct(collateral_utxos: TransactionUnspentOutputs | undefined, collateral_change_address: Address | undefined, native_uplc: boolean | undefined): Promise; + /** + * Returns full Transaction object with the body and the auxiliary data + * NOTE: witness_set will contain all mint_scripts if any been added or set + * NOTE: is_valid set to true + * @returns {Transaction} + */ + build_tx(): Transaction; + /** + * warning: sum of all parts of a transaction must equal 0. You cannot just set the fee to the min value and forget about it + * warning: min_fee may be slightly larger than the actual minimum fee (ex: a few lovelaces) + * this is done to simplify the library code, but can be fixed later + * @returns {BigNum} + */ + min_fee(): BigNum; +} +/** */ +export class TransactionBuilderConfig { + static __wrap(ptr: any): any; + __destroy_into_raw(): number | undefined; + ptr: number | undefined; + free(): void; +} +/** */ +export class TransactionBuilderConfigBuilder { + static __wrap(ptr: any): any; + /** + * @returns {TransactionBuilderConfigBuilder} + */ + static new(): TransactionBuilderConfigBuilder; + __destroy_into_raw(): number | undefined; + ptr: number | undefined; + free(): void; + /** + * @param {LinearFee} fee_algo + * @returns {TransactionBuilderConfigBuilder} + */ + fee_algo(fee_algo: LinearFee): TransactionBuilderConfigBuilder; + /** + * @param {BigNum} coins_per_utxo_byte + * @returns {TransactionBuilderConfigBuilder} + */ + coins_per_utxo_byte(coins_per_utxo_byte: BigNum): TransactionBuilderConfigBuilder; + /** + * @param {BigNum} pool_deposit + * @returns {TransactionBuilderConfigBuilder} + */ + pool_deposit(pool_deposit: BigNum): TransactionBuilderConfigBuilder; + /** + * @param {BigNum} key_deposit + * @returns {TransactionBuilderConfigBuilder} + */ + key_deposit(key_deposit: BigNum): TransactionBuilderConfigBuilder; + /** + * @param {number} max_value_size + * @returns {TransactionBuilderConfigBuilder} + */ + max_value_size(max_value_size: number): TransactionBuilderConfigBuilder; + /** + * @param {number} max_tx_size + * @returns {TransactionBuilderConfigBuilder} + */ + max_tx_size(max_tx_size: number): TransactionBuilderConfigBuilder; + /** + * @param {ExUnitPrices} ex_unit_prices + * @returns {TransactionBuilderConfigBuilder} + */ + ex_unit_prices(ex_unit_prices: ExUnitPrices): TransactionBuilderConfigBuilder; + /** + * @param {ExUnits} max_tx_ex_units + * @returns {TransactionBuilderConfigBuilder} + */ + max_tx_ex_units(max_tx_ex_units: ExUnits): TransactionBuilderConfigBuilder; + /** + * @param {Costmdls} costmdls + * @returns {TransactionBuilderConfigBuilder} + */ + costmdls(costmdls: Costmdls): TransactionBuilderConfigBuilder; + /** + * @param {number} collateral_percentage + * @returns {TransactionBuilderConfigBuilder} + */ + collateral_percentage(collateral_percentage: number): TransactionBuilderConfigBuilder; + /** + * @param {number} max_collateral_inputs + * @returns {TransactionBuilderConfigBuilder} + */ + max_collateral_inputs(max_collateral_inputs: number): TransactionBuilderConfigBuilder; + /** + * @param {BigNum} zero_time + * @param {BigNum} zero_slot + * @param {number} slot_length + * @returns {TransactionBuilderConfigBuilder} + */ + slot_config(zero_time: BigNum, zero_slot: BigNum, slot_length: number): TransactionBuilderConfigBuilder; + /** + * @param {Blockfrost} blockfrost + * @returns {TransactionBuilderConfigBuilder} + */ + blockfrost(blockfrost: Blockfrost): TransactionBuilderConfigBuilder; + /** + * @returns {TransactionBuilderConfig} + */ + build(): TransactionBuilderConfig; +} +/** */ +export class TransactionIndexes { + static __wrap(ptr: any): any; + /** + * @param {Uint8Array} bytes + * @returns {TransactionIndexes} + */ + static from_bytes(bytes: Uint8Array): TransactionIndexes; + /** + * @returns {TransactionIndexes} + */ + static new(): TransactionIndexes; + __destroy_into_raw(): number | undefined; + ptr: number | undefined; + free(): void; + /** + * @returns {Uint8Array} + */ + to_bytes(): Uint8Array; + /** + * @returns {number} + */ + len(): number; + /** + * @param {number} index + * @returns {BigNum} + */ + get(index: number): BigNum; + /** + * @param {BigNum} elem + */ + add(elem: BigNum): void; +} +/** */ +export class TransactionInput { + static __wrap(ptr: any): any; + /** + * @param {Uint8Array} bytes + * @returns {TransactionInput} + */ + static from_bytes(bytes: Uint8Array): TransactionInput; + /** + * @param {string} json + * @returns {TransactionInput} + */ + static from_json(json: string): TransactionInput; + /** + * @param {TransactionHash} transaction_id + * @param {BigNum} index + * @returns {TransactionInput} + */ + static new(transaction_id: TransactionHash, index: BigNum): TransactionInput; + __destroy_into_raw(): number | undefined; + ptr: number | undefined; + free(): void; + /** + * @returns {Uint8Array} + */ + to_bytes(): Uint8Array; + /** + * @returns {string} + */ + to_json(): string; + /** + * @returns {any} + */ + to_js_value(): any; + /** + * @returns {TransactionHash} + */ + transaction_id(): TransactionHash; + /** + * @returns {BigNum} + */ + index(): BigNum; +} +/** */ +export class TransactionInputs { + static __wrap(ptr: any): any; + /** + * @param {Uint8Array} bytes + * @returns {TransactionInputs} + */ + static from_bytes(bytes: Uint8Array): TransactionInputs; + /** + * @param {string} json + * @returns {TransactionInputs} + */ + static from_json(json: string): TransactionInputs; + /** + * @returns {TransactionInputs} + */ + static new(): TransactionInputs; + __destroy_into_raw(): number | undefined; + ptr: number | undefined; + free(): void; + /** + * @returns {Uint8Array} + */ + to_bytes(): Uint8Array; + /** + * @returns {string} + */ + to_json(): string; + /** + * @returns {any} + */ + to_js_value(): any; + /** + * @returns {number} + */ + len(): number; + /** + * @param {number} index + * @returns {TransactionInput} + */ + get(index: number): TransactionInput; + /** + * @param {TransactionInput} elem + */ + add(elem: TransactionInput): void; + /** */ + sort(): void; +} +/** */ +export class TransactionMetadatumLabels { + static __wrap(ptr: any): any; + /** + * @param {Uint8Array} bytes + * @returns {TransactionMetadatumLabels} + */ + static from_bytes(bytes: Uint8Array): TransactionMetadatumLabels; + /** + * @returns {TransactionMetadatumLabels} + */ + static new(): TransactionMetadatumLabels; + __destroy_into_raw(): number | undefined; + ptr: number | undefined; + free(): void; + /** + * @returns {Uint8Array} + */ + to_bytes(): Uint8Array; + /** + * @returns {number} + */ + len(): number; + /** + * @param {number} index + * @returns {BigNum} + */ + get(index: number): BigNum; + /** + * @param {BigNum} elem + */ + add(elem: BigNum): void; +} +/** */ +export class TransactionOutputAmountBuilder { + static __wrap(ptr: any): any; + __destroy_into_raw(): number | undefined; + ptr: number | undefined; + free(): void; + /** + * @param {Value} amount + * @returns {TransactionOutputAmountBuilder} + */ + with_value(amount: Value): TransactionOutputAmountBuilder; + /** + * @param {BigNum} coin + * @returns {TransactionOutputAmountBuilder} + */ + with_coin(coin: BigNum): TransactionOutputAmountBuilder; + /** + * @param {BigNum} coin + * @param {MultiAsset} multiasset + * @returns {TransactionOutputAmountBuilder} + */ + with_coin_and_asset(coin: BigNum, multiasset: MultiAsset): TransactionOutputAmountBuilder; + /** + * @param {MultiAsset} multiasset + * @param {BigNum} coins_per_utxo_word + * @returns {TransactionOutputAmountBuilder} + */ + with_asset_and_min_required_coin(multiasset: MultiAsset, coins_per_utxo_word: BigNum): TransactionOutputAmountBuilder; + /** + * @returns {TransactionOutput} + */ + build(): TransactionOutput; +} +/** + * We introduce a builder-pattern format for creating transaction outputs + * This is because: + * 1. Some fields (i.e. data hash) are optional, and we can't easily expose Option<> in WASM + * 2. Some fields like amounts have many ways it could be set (some depending on other field values being known) + * 3. Easier to adapt as the output format gets more complicated in future Cardano releases + */ +export class TransactionOutputBuilder { + static __wrap(ptr: any): any; + /** + * @returns {TransactionOutputBuilder} + */ + static new(): TransactionOutputBuilder; + __destroy_into_raw(): number | undefined; + ptr: number | undefined; + free(): void; + /** + * @param {Address} address + * @returns {TransactionOutputBuilder} + */ + with_address(address: Address): TransactionOutputBuilder; + /** + * @param {Datum} data_hash + * @returns {TransactionOutputBuilder} + */ + with_datum(data_hash: Datum): TransactionOutputBuilder; + /** + * @returns {TransactionOutputAmountBuilder} + */ + next(): TransactionOutputAmountBuilder; +} +/** */ +export class TransactionOutputs { + static __wrap(ptr: any): any; + /** + * @param {Uint8Array} bytes + * @returns {TransactionOutputs} + */ + static from_bytes(bytes: Uint8Array): TransactionOutputs; + /** + * @param {string} json + * @returns {TransactionOutputs} + */ + static from_json(json: string): TransactionOutputs; + /** + * @returns {TransactionOutputs} + */ + static new(): TransactionOutputs; + __destroy_into_raw(): number | undefined; + ptr: number | undefined; + free(): void; + /** + * @returns {Uint8Array} + */ + to_bytes(): Uint8Array; + /** + * @returns {string} + */ + to_json(): string; + /** + * @returns {any} + */ + to_js_value(): any; + /** + * @returns {number} + */ + len(): number; + /** + * @param {number} index + * @returns {TransactionOutput} + */ + get(index: number): TransactionOutput; + /** + * @param {TransactionOutput} elem + */ + add(elem: TransactionOutput): void; +} +/** */ +export class TransactionUnspentOutput { + static __wrap(ptr: any): any; + /** + * @param {Uint8Array} bytes + * @returns {TransactionUnspentOutput} + */ + static from_bytes(bytes: Uint8Array): TransactionUnspentOutput; + /** + * @param {TransactionInput} input + * @param {TransactionOutput} output + * @returns {TransactionUnspentOutput} + */ + static new(input: TransactionInput, output: TransactionOutput): TransactionUnspentOutput; + __destroy_into_raw(): number | undefined; + ptr: number | undefined; + free(): void; + /** + * @returns {Uint8Array} + */ + to_bytes(): Uint8Array; + /** + * @returns {TransactionInput} + */ + input(): TransactionInput; + /** + * @returns {TransactionOutput} + */ + output(): TransactionOutput; + /** + * @returns {Uint8Array} + */ + to_legacy_bytes(): Uint8Array; +} +/** */ +export class TransactionUnspentOutputs { + static __wrap(ptr: any): any; + /** + * @returns {TransactionUnspentOutputs} + */ + static new(): TransactionUnspentOutputs; + __destroy_into_raw(): number | undefined; + ptr: number | undefined; + free(): void; + /** + * @returns {number} + */ + len(): number; + /** + * @param {number} index + * @returns {TransactionUnspentOutput} + */ + get(index: number): TransactionUnspentOutput; + /** + * @param {TransactionUnspentOutput} elem + */ + add(elem: TransactionUnspentOutput): void; +} +/** */ +export class TransactionWitnessSet { + static __wrap(ptr: any): any; + /** + * @param {Uint8Array} bytes + * @returns {TransactionWitnessSet} + */ + static from_bytes(bytes: Uint8Array): TransactionWitnessSet; + /** + * @param {string} json + * @returns {TransactionWitnessSet} + */ + static from_json(json: string): TransactionWitnessSet; + /** + * @returns {TransactionWitnessSet} + */ + static new(): TransactionWitnessSet; + __destroy_into_raw(): number | undefined; + ptr: number | undefined; + free(): void; + /** + * @returns {Uint8Array} + */ + to_bytes(): Uint8Array; + /** + * @returns {string} + */ + to_json(): string; + /** + * @returns {any} + */ + to_js_value(): any; + /** + * @param {Vkeywitnesses} vkeys + */ + set_vkeys(vkeys: Vkeywitnesses): void; + /** + * @returns {Vkeywitnesses | undefined} + */ + vkeys(): Vkeywitnesses | undefined; + /** + * @param {NativeScripts} native_scripts + */ + set_native_scripts(native_scripts: NativeScripts): void; + /** + * @returns {NativeScripts | undefined} + */ + native_scripts(): NativeScripts | undefined; + /** + * @param {BootstrapWitnesses} bootstraps + */ + set_bootstraps(bootstraps: BootstrapWitnesses): void; + /** + * @returns {BootstrapWitnesses | undefined} + */ + bootstraps(): BootstrapWitnesses | undefined; + /** + * @param {PlutusScripts} plutus_scripts + */ + set_plutus_scripts(plutus_scripts: PlutusScripts): void; + /** + * @returns {PlutusScripts | undefined} + */ + plutus_scripts(): PlutusScripts | undefined; + /** + * @param {PlutusList} plutus_data + */ + set_plutus_data(plutus_data: PlutusList): void; + /** + * @returns {PlutusList | undefined} + */ + plutus_data(): PlutusList | undefined; + /** + * @param {Redeemers} redeemers + */ + set_redeemers(redeemers: Redeemers): void; + /** + * @param {PlutusScripts} plutus_scripts + */ + set_plutus_v2_scripts(plutus_scripts: PlutusScripts): void; + /** + * @param {PlutusScripts} plutus_scripts + */ + set_plutus_v3_scripts(plutus_scripts: PlutusScripts): void; + /** + * @returns {Redeemers | undefined} + */ + redeemers(): Redeemers | undefined; + /** + * @returns {PlutusScripts | undefined} + */ + plutus_v2_scripts(): PlutusScripts | undefined; + /** + * @returns {PlutusScripts | undefined} + */ + plutus_v3_scripts(): PlutusScripts | undefined; +} +/** + * Builder de-duplicates witnesses as they are added + */ +export class TransactionWitnessSetBuilder { + static __wrap(ptr: any): any; + /** + * @returns {TransactionWitnessSetBuilder} + */ + static new(): TransactionWitnessSetBuilder; + __destroy_into_raw(): number | undefined; + ptr: number | undefined; + free(): void; + /** + * @param {Vkeywitness} vkey + */ + add_vkey(vkey: Vkeywitness): void; + /** + * @param {BootstrapWitness} bootstrap + */ + add_bootstrap(bootstrap: BootstrapWitness): void; + /** + * @param {NativeScript} native_script + */ + add_native_script(native_script: NativeScript): void; + /** + * @param {PlutusScript} plutus_script + */ + add_plutus_script(plutus_script: PlutusScript): void; + /** + * @param {PlutusScript} plutus_script + */ + add_plutus_v2_script(plutus_script: PlutusScript): void; + /** + * @param {PlutusData} plutus_datum + */ + add_plutus_datum(plutus_datum: PlutusData): void; + /** + * @param {Redeemer} redeemer + */ + add_redeemer(redeemer: Redeemer): void; + /** + * @param {RequiredWitnessSet} required_wits + */ + add_required_wits(required_wits: RequiredWitnessSet): void; + /** + * @param {TransactionWitnessSet} wit_set + */ + add_existing(wit_set: TransactionWitnessSet): void; + /** + * @returns {TransactionWitnessSet} + */ + build(): TransactionWitnessSet; +} +/** */ +export class TransactionWitnessSets { + static __wrap(ptr: any): any; + /** + * @param {Uint8Array} bytes + * @returns {TransactionWitnessSets} + */ + static from_bytes(bytes: Uint8Array): TransactionWitnessSets; + /** + * @param {string} json + * @returns {TransactionWitnessSets} + */ + static from_json(json: string): TransactionWitnessSets; + /** + * @returns {TransactionWitnessSets} + */ + static new(): TransactionWitnessSets; + __destroy_into_raw(): number | undefined; + ptr: number | undefined; + free(): void; + /** + * @returns {Uint8Array} + */ + to_bytes(): Uint8Array; + /** + * @returns {string} + */ + to_json(): string; + /** + * @returns {any} + */ + to_js_value(): any; + /** + * @returns {number} + */ + len(): number; + /** + * @param {number} index + * @returns {TransactionWitnessSet} + */ + get(index: number): TransactionWitnessSet; + /** + * @param {TransactionWitnessSet} elem + */ + add(elem: TransactionWitnessSet): void; +} +/** */ +export class TreasuryWithdrawals { + static __wrap(ptr: any): any; + /** + * @param {Uint8Array} bytes + * @returns {TreasuryWithdrawals} + */ + static from_bytes(bytes: Uint8Array): TreasuryWithdrawals; + /** + * @param {string} json + * @returns {TreasuryWithdrawals} + */ + static from_json(json: string): TreasuryWithdrawals; + /** + * @returns {TreasuryWithdrawals} + */ + static new(): TreasuryWithdrawals; + __destroy_into_raw(): number | undefined; + ptr: number | undefined; + free(): void; + /** + * @returns {Uint8Array} + */ + to_bytes(): Uint8Array; + /** + * @returns {string} + */ + to_json(): string; + /** + * @returns {any} + */ + to_js_value(): any; + /** + * @returns {number} + */ + len(): number; + /** + * @param {Ed25519KeyHash} key + * @param {BigNum} value + * @returns {BigNum | undefined} + */ + insert(key: Ed25519KeyHash, value: BigNum): BigNum | undefined; + /** + * @param {Ed25519KeyHash} key + * @returns {BigNum | undefined} + */ + get(key: Ed25519KeyHash): BigNum | undefined; + /** + * @returns {Ed25519KeyHashes} + */ + keys(): Ed25519KeyHashes; +} +/** */ +export class TreasuryWithdrawalsAction { + static __wrap(ptr: any): any; + /** + * @param {Uint8Array} bytes + * @returns {TreasuryWithdrawalsAction} + */ + static from_bytes(bytes: Uint8Array): TreasuryWithdrawalsAction; + /** + * @param {string} json + * @returns {TreasuryWithdrawalsAction} + */ + static from_json(json: string): TreasuryWithdrawalsAction; + /** + * @param {TreasuryWithdrawals} withdrawals + * @returns {TreasuryWithdrawalsAction} + */ + static new(withdrawals: TreasuryWithdrawals): TreasuryWithdrawalsAction; + __destroy_into_raw(): number | undefined; + ptr: number | undefined; + free(): void; + /** + * @returns {Uint8Array} + */ + to_bytes(): Uint8Array; + /** + * @returns {string} + */ + to_json(): string; + /** + * @returns {any} + */ + to_js_value(): any; + /** + * @returns {TreasuryWithdrawals} + */ + withdrawals(): TreasuryWithdrawals; +} +/** */ +export class UnitInterval { + static __wrap(ptr: any): any; + /** + * @param {Uint8Array} bytes + * @returns {UnitInterval} + */ + static from_bytes(bytes: Uint8Array): UnitInterval; + /** + * @param {string} json + * @returns {UnitInterval} + */ + static from_json(json: string): UnitInterval; + /** + * @param {BigNum} numerator + * @param {BigNum} denominator + * @returns {UnitInterval} + */ + static new(numerator: BigNum, denominator: BigNum): UnitInterval; + /** + * @param {number} float_number + * @returns {UnitInterval} + */ + static from_float(float_number: number): UnitInterval; + __destroy_into_raw(): number | undefined; + ptr: number | undefined; + free(): void; + /** + * @returns {Uint8Array} + */ + to_bytes(): Uint8Array; + /** + * @returns {string} + */ + to_json(): string; + /** + * @returns {any} + */ + to_js_value(): any; + /** + * @returns {BigNum} + */ + numerator(): BigNum; + /** + * @returns {BigNum} + */ + denominator(): BigNum; +} +/** */ +export class UnregCert { + static __wrap(ptr: any): any; + /** + * @param {Uint8Array} bytes + * @returns {UnregCert} + */ + static from_bytes(bytes: Uint8Array): UnregCert; + /** + * @param {string} json + * @returns {UnregCert} + */ + static from_json(json: string): UnregCert; + /** + * @param {StakeCredential} stake_credential + * @param {BigNum} coin + * @returns {UnregCert} + */ + static new(stake_credential: StakeCredential, coin: BigNum): UnregCert; + __destroy_into_raw(): number | undefined; + ptr: number | undefined; + free(): void; + /** + * @returns {Uint8Array} + */ + to_bytes(): Uint8Array; + /** + * @returns {string} + */ + to_json(): string; + /** + * @returns {any} + */ + to_js_value(): any; + /** + * @returns {StakeCredential} + */ + stake_credential(): StakeCredential; + /** + * @returns {BigNum} + */ + coin(): BigNum; +} +/** */ +export class UnregCommitteeHotKeyCert { + static __wrap(ptr: any): any; + /** + * @param {Uint8Array} bytes + * @returns {UnregCommitteeHotKeyCert} + */ + static from_bytes(bytes: Uint8Array): UnregCommitteeHotKeyCert; + /** + * @param {string} json + * @returns {UnregCommitteeHotKeyCert} + */ + static from_json(json: string): UnregCommitteeHotKeyCert; + /** + * @param {Ed25519KeyHash} committee_cold_keyhash + * @returns {UnregCommitteeHotKeyCert} + */ + static new(committee_cold_keyhash: Ed25519KeyHash): UnregCommitteeHotKeyCert; + __destroy_into_raw(): number | undefined; + ptr: number | undefined; + free(): void; + /** + * @returns {Uint8Array} + */ + to_bytes(): Uint8Array; + /** + * @returns {string} + */ + to_json(): string; + /** + * @returns {any} + */ + to_js_value(): any; + /** + * @returns {Ed25519KeyHash} + */ + committee_cold_keyhash(): Ed25519KeyHash; +} +/** */ +export class UnregDrepCert { + static __wrap(ptr: any): any; + /** + * @param {Uint8Array} bytes + * @returns {UnregDrepCert} + */ + static from_bytes(bytes: Uint8Array): UnregDrepCert; + /** + * @param {string} json + * @returns {UnregDrepCert} + */ + static from_json(json: string): UnregDrepCert; + /** + * @param {StakeCredential} voting_credential + * @param {BigNum} coin + * @returns {UnregDrepCert} + */ + static new(voting_credential: StakeCredential, coin: BigNum): UnregDrepCert; + __destroy_into_raw(): number | undefined; + ptr: number | undefined; + free(): void; + /** + * @returns {Uint8Array} + */ + to_bytes(): Uint8Array; + /** + * @returns {string} + */ + to_json(): string; + /** + * @returns {any} + */ + to_js_value(): any; + /** + * @returns {StakeCredential} + */ + voting_credential(): StakeCredential; + /** + * @returns {BigNum} + */ + coin(): BigNum; +} +/** */ +export class Update { + static __wrap(ptr: any): any; + /** + * @param {Uint8Array} bytes + * @returns {Update} + */ + static from_bytes(bytes: Uint8Array): Update; + /** + * @param {string} json + * @returns {Update} + */ + static from_json(json: string): Update; + /** + * @param {ProposedProtocolParameterUpdates} proposed_protocol_parameter_updates + * @param {number} epoch + * @returns {Update} + */ + static new(proposed_protocol_parameter_updates: ProposedProtocolParameterUpdates, epoch: number): Update; + __destroy_into_raw(): number | undefined; + ptr: number | undefined; + free(): void; + /** + * @returns {Uint8Array} + */ + to_bytes(): Uint8Array; + /** + * @returns {string} + */ + to_json(): string; + /** + * @returns {any} + */ + to_js_value(): any; + /** + * @returns {ProposedProtocolParameterUpdates} + */ + proposed_protocol_parameter_updates(): ProposedProtocolParameterUpdates; + /** + * @returns {number} + */ + epoch(): number; +} +/** */ +export class Url { + static __wrap(ptr: any): any; + /** + * @param {Uint8Array} bytes + * @returns {Url} + */ + static from_bytes(bytes: Uint8Array): Url; + /** + * @param {string} url + * @returns {Url} + */ + static new(url: string): Url; + __destroy_into_raw(): number | undefined; + ptr: number | undefined; + free(): void; + /** + * @returns {Uint8Array} + */ + to_bytes(): Uint8Array; + /** + * @returns {string} + */ + url(): string; +} +/** */ +export class VRFCert { + static __wrap(ptr: any): any; + /** + * @param {Uint8Array} bytes + * @returns {VRFCert} + */ + static from_bytes(bytes: Uint8Array): VRFCert; + /** + * @param {string} json + * @returns {VRFCert} + */ + static from_json(json: string): VRFCert; + /** + * @param {Uint8Array} output + * @param {Uint8Array} proof + * @returns {VRFCert} + */ + static new(output: Uint8Array, proof: Uint8Array): VRFCert; + __destroy_into_raw(): number | undefined; + ptr: number | undefined; + free(): void; + /** + * @returns {Uint8Array} + */ + to_bytes(): Uint8Array; + /** + * @returns {string} + */ + to_json(): string; + /** + * @returns {any} + */ + to_js_value(): any; + /** + * @returns {Uint8Array} + */ + output(): Uint8Array; + /** + * @returns {Uint8Array} + */ + proof(): Uint8Array; +} +/** */ +export class VRFKeyHash { + static __wrap(ptr: any): any; + /** + * @param {Uint8Array} bytes + * @returns {VRFKeyHash} + */ + static from_bytes(bytes: Uint8Array): VRFKeyHash; + /** + * @param {string} bech_str + * @returns {VRFKeyHash} + */ + static from_bech32(bech_str: string): VRFKeyHash; + /** + * @param {string} hex + * @returns {VRFKeyHash} + */ + static from_hex(hex: string): VRFKeyHash; + __destroy_into_raw(): number | undefined; + ptr: number | undefined; + free(): void; + /** + * @returns {Uint8Array} + */ + to_bytes(): Uint8Array; + /** + * @param {string} prefix + * @returns {string} + */ + to_bech32(prefix: string): string; + /** + * @returns {string} + */ + to_hex(): string; +} +/** */ +export class VRFVKey { + static __wrap(ptr: any): any; + /** + * @param {Uint8Array} bytes + * @returns {VRFVKey} + */ + static from_bytes(bytes: Uint8Array): VRFVKey; + __destroy_into_raw(): number | undefined; + ptr: number | undefined; + free(): void; + /** + * @returns {Uint8Array} + */ + to_bytes(): Uint8Array; + /** + * @returns {VRFKeyHash} + */ + hash(): VRFKeyHash; + /** + * @returns {Uint8Array} + */ + to_raw_key(): Uint8Array; +} +/** */ +export class Vkey { + static __wrap(ptr: any): any; + /** + * @param {Uint8Array} bytes + * @returns {Vkey} + */ + static from_bytes(bytes: Uint8Array): Vkey; + /** + * @param {PublicKey} pk + * @returns {Vkey} + */ + static new(pk: PublicKey): Vkey; + __destroy_into_raw(): number | undefined; + ptr: number | undefined; + free(): void; + /** + * @returns {Uint8Array} + */ + to_bytes(): Uint8Array; + /** + * @returns {PublicKey} + */ + public_key(): PublicKey; +} +/** */ +export class Vkeys { + static __wrap(ptr: any): any; + /** + * @returns {Vkeys} + */ + static new(): Vkeys; + __destroy_into_raw(): number | undefined; + ptr: number | undefined; + free(): void; + /** + * @returns {number} + */ + len(): number; + /** + * @param {number} index + * @returns {Vkey} + */ + get(index: number): Vkey; + /** + * @param {Vkey} elem + */ + add(elem: Vkey): void; +} +/** */ +export class Vkeywitnesses { + static __wrap(ptr: any): any; + /** + * @returns {Vkeywitnesses} + */ + static new(): Vkeywitnesses; + __destroy_into_raw(): number | undefined; + ptr: number | undefined; + free(): void; + /** + * @returns {number} + */ + len(): number; + /** + * @param {number} index + * @returns {Vkeywitness} + */ + get(index: number): Vkeywitness; + /** + * @param {Vkeywitness} elem + */ + add(elem: Vkeywitness): void; +} +/** */ +export class Vote { + static __wrap(ptr: any): any; + /** + * @param {Uint8Array} bytes + * @returns {Vote} + */ + static from_bytes(bytes: Uint8Array): Vote; + /** + * @param {string} json + * @returns {Vote} + */ + static from_json(json: string): Vote; + /** + * @returns {Vote} + */ + static new_no(): Vote; + /** + * @returns {Vote} + */ + static new_yes(): Vote; + /** + * @returns {Vote} + */ + static new_abstain(): Vote; + __destroy_into_raw(): number | undefined; + ptr: number | undefined; + free(): void; + /** + * @returns {Uint8Array} + */ + to_bytes(): Uint8Array; + /** + * @returns {string} + */ + to_json(): string; + /** + * @returns {any} + */ + to_js_value(): any; + /** + * @returns {number} + */ + kind(): number; +} +/** */ +export class VoteDelegCert { + static __wrap(ptr: any): any; + /** + * @param {Uint8Array} bytes + * @returns {VoteDelegCert} + */ + static from_bytes(bytes: Uint8Array): VoteDelegCert; + /** + * @param {string} json + * @returns {VoteDelegCert} + */ + static from_json(json: string): VoteDelegCert; + /** + * @param {StakeCredential} stake_credential + * @param {Drep} drep + * @returns {VoteDelegCert} + */ + static new(stake_credential: StakeCredential, drep: Drep): VoteDelegCert; + __destroy_into_raw(): number | undefined; + ptr: number | undefined; + free(): void; + /** + * @returns {Uint8Array} + */ + to_bytes(): Uint8Array; + /** + * @returns {string} + */ + to_json(): string; + /** + * @returns {any} + */ + to_js_value(): any; + /** + * @returns {StakeCredential} + */ + stake_credential(): StakeCredential; + /** + * @returns {Drep} + */ + drep(): Drep; +} +/** */ +export class VoteRegDelegCert { + static __wrap(ptr: any): any; + /** + * @param {Uint8Array} bytes + * @returns {VoteRegDelegCert} + */ + static from_bytes(bytes: Uint8Array): VoteRegDelegCert; + /** + * @param {string} json + * @returns {VoteRegDelegCert} + */ + static from_json(json: string): VoteRegDelegCert; + /** + * @param {StakeCredential} stake_credential + * @param {Drep} drep + * @param {BigNum} coin + * @returns {VoteRegDelegCert} + */ + static new(stake_credential: StakeCredential, drep: Drep, coin: BigNum): VoteRegDelegCert; + __destroy_into_raw(): number | undefined; + ptr: number | undefined; + free(): void; + /** + * @returns {Uint8Array} + */ + to_bytes(): Uint8Array; + /** + * @returns {string} + */ + to_json(): string; + /** + * @returns {any} + */ + to_js_value(): any; + /** + * @returns {StakeCredential} + */ + stake_credential(): StakeCredential; + /** + * @returns {Drep} + */ + drep(): Drep; + /** + * @returns {BigNum} + */ + coin(): BigNum; +} +/** */ +export class Voter { + static __wrap(ptr: any): any; + /** + * @param {Uint8Array} bytes + * @returns {Voter} + */ + static from_bytes(bytes: Uint8Array): Voter; + /** + * @param {string} json + * @returns {Voter} + */ + static from_json(json: string): Voter; + /** + * @param {Ed25519KeyHash} keyhash + * @returns {Voter} + */ + static new_committee_hot_keyhash(keyhash: Ed25519KeyHash): Voter; + /** + * @param {ScriptHash} scripthash + * @returns {Voter} + */ + static new_committee_hot_scripthash(scripthash: ScriptHash): Voter; + /** + * @param {Ed25519KeyHash} keyhash + * @returns {Voter} + */ + static new_drep_keyhash(keyhash: Ed25519KeyHash): Voter; + /** + * @param {ScriptHash} scripthash + * @returns {Voter} + */ + static new_drep_scripthash(scripthash: ScriptHash): Voter; + /** + * @param {Ed25519KeyHash} keyhash + * @returns {Voter} + */ + static new_staking_pool_keyhash(keyhash: Ed25519KeyHash): Voter; + __destroy_into_raw(): number | undefined; + ptr: number | undefined; + free(): void; + /** + * @returns {Uint8Array} + */ + to_bytes(): Uint8Array; + /** + * @returns {string} + */ + to_json(): string; + /** + * @returns {any} + */ + to_js_value(): any; + /** + * @returns {number} + */ + kind(): number; + /** + * @returns {Ed25519KeyHash | undefined} + */ + as_committee_hot_keyhash(): Ed25519KeyHash | undefined; + /** + * @returns {ScriptHash | undefined} + */ + as_committee_hot_scripthash(): ScriptHash | undefined; + /** + * @returns {Ed25519KeyHash | undefined} + */ + as_drep_keyhash(): Ed25519KeyHash | undefined; + /** + * @returns {ScriptHash | undefined} + */ + as_drep_scripthash(): ScriptHash | undefined; + /** + * @returns {Ed25519KeyHash | undefined} + */ + as_staking_pool_keyhash(): Ed25519KeyHash | undefined; +} +/** */ +export class VotingProcedure { + static __wrap(ptr: any): any; + /** + * @param {Uint8Array} bytes + * @returns {VotingProcedure} + */ + static from_bytes(bytes: Uint8Array): VotingProcedure; + /** + * @param {string} json + * @returns {VotingProcedure} + */ + static from_json(json: string): VotingProcedure; + /** + * @param {GovernanceActionId} governance_action_id + * @param {Voter} voter + * @param {Vote} vote + * @param {Anchor} anchor + * @returns {VotingProcedure} + */ + static new(governance_action_id: GovernanceActionId, voter: Voter, vote: Vote, anchor: Anchor): VotingProcedure; + __destroy_into_raw(): number | undefined; + ptr: number | undefined; + free(): void; + /** + * @returns {Uint8Array} + */ + to_bytes(): Uint8Array; + /** + * @returns {string} + */ + to_json(): string; + /** + * @returns {any} + */ + to_js_value(): any; + /** + * @returns {GovernanceActionId} + */ + governance_action_id(): GovernanceActionId; + /** + * @returns {Voter} + */ + voter(): Voter; + /** + * @returns {number} + */ + vote(): number; + /** + * @returns {Anchor} + */ + anchor(): Anchor; +} +/** */ +export class VotingProcedures { + static __wrap(ptr: any): any; + /** + * @param {Uint8Array} bytes + * @returns {VotingProcedures} + */ + static from_bytes(bytes: Uint8Array): VotingProcedures; + /** + * @returns {VotingProcedures} + */ + static new(): VotingProcedures; + __destroy_into_raw(): number | undefined; + ptr: number | undefined; + free(): void; + /** + * @returns {Uint8Array} + */ + to_bytes(): Uint8Array; + /** + * @returns {number} + */ + len(): number; + /** + * @param {number} index + * @returns {VotingProcedure} + */ + get(index: number): VotingProcedure; + /** + * @param {VotingProcedure} elem + */ + add(elem: VotingProcedure): void; +} +/** */ +export class Withdrawals { + static __wrap(ptr: any): any; + /** + * @param {Uint8Array} bytes + * @returns {Withdrawals} + */ + static from_bytes(bytes: Uint8Array): Withdrawals; + /** + * @param {string} json + * @returns {Withdrawals} + */ + static from_json(json: string): Withdrawals; + /** + * @returns {Withdrawals} + */ + static new(): Withdrawals; + __destroy_into_raw(): number | undefined; + ptr: number | undefined; + free(): void; + /** + * @returns {Uint8Array} + */ + to_bytes(): Uint8Array; + /** + * @returns {string} + */ + to_json(): string; + /** + * @returns {any} + */ + to_js_value(): any; + /** + * @returns {number} + */ + len(): number; + /** + * @param {RewardAddress} key + * @param {BigNum} value + * @returns {BigNum | undefined} + */ + insert(key: RewardAddress, value: BigNum): BigNum | undefined; + /** + * @param {RewardAddress} key + * @returns {BigNum | undefined} + */ + get(key: RewardAddress): BigNum | undefined; + /** + * @returns {RewardAddresses} + */ + keys(): RewardAddresses; +} +declare let wasm: any; +export { wasm as __wasm }; diff --git a/dist/types/src/lucid/lucid.d.ts b/dist/types/src/lucid/lucid.d.ts index 658b7cb9..e07ccb29 100644 --- a/dist/types/src/lucid/lucid.d.ts +++ b/dist/types/src/lucid/lucid.d.ts @@ -1,6 +1,6 @@ import { C } from "../core/mod.js"; import { Utils } from "../utils/mod.js"; -import { Address, Credential, Delegation, ExternalWallet, Json, Network, OutRef, Payload, PrivateKey, ProtocolParameters, Provider, RewardAddress, SignedMessage, Slot, Transaction, TxHash, Unit, UTxO, Wallet, WalletApi } from "../types/mod.js"; +import { Address, Credential, Delegation, ExternalWallet, Json, Network, OutRef, Payload, PrivateKey, ProtocolParameters, Provider, RewardAddress, SignedMessage, Slot, SlotConfig, Transaction, TxHash, Unit, UTxO, Wallet, WalletApi } from "../types/mod.js"; import { Tx } from "./tx.js"; import { TxComplete } from "./tx_complete.js"; import { Message } from "./message.js"; @@ -11,13 +11,14 @@ declare type LucidConstructorArgs = { protocolParameters?: ProtocolParameters; }; export declare class Lucid { - protocolParameters: ProtocolParameters; - txBuilderConfig: C.TransactionBuilderConfig; + protocolParameters?: ProtocolParameters; + slotConfig: SlotConfig; wallet: Wallet; provider: Provider; network: Network; utils: Utils; static new({ provider, network, protocolParameters, }: LucidConstructorArgs): Promise; + getTransactionBuilderConfig(): C.TransactionBuilderConfig; /** * Switch provider and/or network. * If provider or network unset, no overwriting happens. Provider or network from current instance are taken then. diff --git a/dist/types/src/lucid/tx.d.ts b/dist/types/src/lucid/tx.d.ts index 45178a6c..b04bf0e0 100644 --- a/dist/types/src/lucid/tx.d.ts +++ b/dist/types/src/lucid/tx.d.ts @@ -73,6 +73,8 @@ export declare class Tx { apply(callback: (thisTx: Tx) => unknown): Tx; /** Compose transactions. */ compose(tx: Tx | null): Tx; + free(): void; + /** Completes the transaction. This might fail, you should free the txBuilder when you are done with it. */ complete(options?: { change?: { address?: Address; diff --git a/dist/types/src/lucid/tx_complete.d.ts b/dist/types/src/lucid/tx_complete.d.ts index 3b455dc2..8904cd11 100644 --- a/dist/types/src/lucid/tx_complete.d.ts +++ b/dist/types/src/lucid/tx_complete.d.ts @@ -30,4 +30,6 @@ export declare class TxComplete { toString(): Transaction; /** Return the transaction hash. */ toHash(): TxHash; + /** Since this object has WASM fields, we must use the free method to free the fields */ + free(): void; } diff --git a/dist/types/src/lucid/tx_signed.d.ts b/dist/types/src/lucid/tx_signed.d.ts index 39b14e34..c8e4b7f2 100644 --- a/dist/types/src/lucid/tx_signed.d.ts +++ b/dist/types/src/lucid/tx_signed.d.ts @@ -10,4 +10,6 @@ export declare class TxSigned { toString(): Transaction; /** Return the transaction hash. */ toHash(): TxHash; + /** Since this object has WASM fields, we must use the free method to free the fields */ + free(): void; } diff --git a/dist/types/src/provider/emulator.d.ts b/dist/types/src/provider/emulator.d.ts index d71a95b1..84d87e80 100644 --- a/dist/types/src/provider/emulator.d.ts +++ b/dist/types/src/provider/emulator.d.ts @@ -1,4 +1,4 @@ -import { Address, Assets, Credential, Datum, DatumHash, Delegation, Lovelace, OutRef, ProtocolParameters, Provider, RewardAddress, Transaction, TxHash, Unit, UnixTime, UTxO } from "../types/types.js"; +import { Address, Assets, Credential, Datum, DatumHash, Delegation, Lovelace, OutputData, OutRef, ProtocolParameters, Provider, RewardAddress, Transaction, TxHash, Unit, UnixTime, UTxO } from "../types/types.js"; /** Concatentation of txHash + outputIndex */ declare type FlatOutRef = string; export declare class Emulator implements Provider { @@ -26,6 +26,7 @@ export declare class Emulator implements Provider { constructor(accounts: { address: Address; assets: Assets; + outputData?: OutputData; }[], protocolParameters?: ProtocolParameters); now(): UnixTime; awaitSlot(length?: number): void; diff --git a/dist/types/src/provider/maestro.d.ts b/dist/types/src/provider/maestro.d.ts index 8dc8e19a..419dfca5 100644 --- a/dist/types/src/provider/maestro.d.ts +++ b/dist/types/src/provider/maestro.d.ts @@ -11,6 +11,7 @@ export declare class Maestro implements Provider { turboSubmit: boolean; constructor({ network, apiKey, turboSubmit }: MaestroConfig); getProtocolParameters(): Promise; + private getUtxosInternal; getUtxos(addressOrCredential: Address | Credential): Promise; getUtxosWithUnit(addressOrCredential: Address | Credential, unit: Unit): Promise; getUtxoByUnit(unit: Unit): Promise; @@ -21,4 +22,5 @@ export declare class Maestro implements Provider { submitTx(tx: Transaction): Promise; private commonHeaders; private maestroUtxoToUtxo; + private getAllPagesData; } diff --git a/dist/types/src/utils/cml.d.ts b/dist/types/src/utils/cml.d.ts new file mode 100644 index 00000000..2b4e5eea --- /dev/null +++ b/dist/types/src/utils/cml.d.ts @@ -0,0 +1,20 @@ +import { TransactionBuilder } from "../core/libs/cardano_multiplatform_lib/nodejs/cardano_multiplatform_lib.generated.js"; +import { Address, Assets, C, CertificateValidator, Datum, Lucid, MintingPolicy, OutputData, PoolParams, Redeemer, RewardAddress, SpendingValidator, Tx, WithdrawalValidator } from "../mod.js"; +import { FreeableBucket } from "./freeable.js"; +export declare function getScriptWitness(redeemer: Redeemer, datum?: Datum): C.ScriptWitness; +export declare function getStakeCredential(hash: string, type: "Key" | "Script"): C.StakeCredential; +export declare function createPoolRegistration(poolParams: PoolParams, lucid: Lucid): Promise; +export declare function attachScript(tx: Tx, { type, script, }: SpendingValidator | MintingPolicy | CertificateValidator | WithdrawalValidator): void; +export declare function addressFromWithNetworkCheck(address: Address | RewardAddress, lucid: Lucid): C.Address; +export declare function getDatumFromOutputData(outputData?: OutputData): { + datum?: C.Datum | undefined; + plutusData?: C.PlutusData; +}; +export declare function createOutput({ bucket, address, assets, outputData, lucid, txBuilder, }: { + bucket: FreeableBucket; + address: Address; + assets: Assets; + outputData: OutputData; + lucid: Lucid; + txBuilder: TransactionBuilder; +}): C.TransactionOutput; diff --git a/dist/types/src/utils/freeable.d.ts b/dist/types/src/utils/freeable.d.ts new file mode 100644 index 00000000..961f3cc8 --- /dev/null +++ b/dist/types/src/utils/freeable.d.ts @@ -0,0 +1,26 @@ +/** + * These types and classes are used to help with freeing memory. + * Objects passed from the WASM to JS (Objects from Rust libraries, for example) are not freed automatically, or at least inconsistently. + * This can lead to memory leaks. + * In order to free these objects, we need to call the `free()` method on them. These types make it easier. + */ +/** This interface represents WASM objects that can and need to be freed. */ +export interface Freeable { + free(): void; +} +export declare type FreeableBucket = Array; +/** This class makes it easier to free large sets of memory. It can be used like this: + * ```ts + * const bucket: FreeableBucket = []; + * try { + * const rustObject = C.some_rust_object(); + * bucket.push(rustObject); + * ... + * } finally { + * Freeables.free(...bucket); + * } + * ``` + */ +export declare abstract class Freeables { + static free(...bucket: FreeableBucket): void; +} diff --git a/dist/types/src/utils/mod.d.ts b/dist/types/src/utils/mod.d.ts index 8e127d1d..04fe4189 100644 --- a/dist/types/src/utils/mod.d.ts +++ b/dist/types/src/utils/mod.d.ts @@ -1,3 +1,5 @@ export * from "./cost_model.js"; export * from "./utils.js"; export * from "./merkle_tree.js"; +export * from "./cml.js"; +export * from "./freeable.js"; diff --git a/dist/types/src/utils/transaction_builder_config.d.ts b/dist/types/src/utils/transaction_builder_config.d.ts new file mode 100644 index 00000000..9ad0a9dd --- /dev/null +++ b/dist/types/src/utils/transaction_builder_config.d.ts @@ -0,0 +1,6 @@ +import { C, SlotConfig } from "../mod.js"; +import { ProtocolParameters } from "../types/mod.js"; +export declare function getTransactionBuilderConfig(protocolParameters: ProtocolParameters, slotConfig: SlotConfig, blockfrostConfig: { + url?: string; + projectId?: string; +}): C.TransactionBuilderConfig; diff --git a/dist/web/mod.js b/dist/web/mod.js index ee24f70a..edb47f0c 100644 --- a/dist/web/mod.js +++ b/dist/web/mod.js @@ -1,14 +1,14 @@ -Object.hasOwn||Object.defineProperty(Object,"hasOwn",{value:function(a,e){if(a==null)throw new TypeError("Cannot convert undefined or null to object");return Object.prototype.hasOwnProperty.call(Object(a),e)},configurable:!0,enumerable:!1,writable:!0});import*as o from"../esm/src/core/libs/cardano_multiplatform_lib/cardano_multiplatform_lib.generated.js";import*as T from"../esm/src/core/libs/cardano_message_signing/cardano_message_signing.generated.js";var ge={name:"@jpg-store/lucid-cardano",version:"0.10.12",license:"MIT",description:"This is a fork of the original Lucid repo compiled into CommonJS. For more information check https://github.com/spacebudz/lucid",repository:"https://github.com/jpg-store/lucid",module:"./dist/esm/mod.js",main:"./dist/esm/mod.js",types:"./dist/types/mod.d.ts",engines:{node:">=14"},dependencies:{"node-fetch":"^3.2.3","@peculiar/webcrypto":"^1.4.0",ws:"^8.10.0"},type:"module",exports:{".":{import:"./dist/esm/mod.js",types:"./dist/types/mod.d.ts"}}};async function Ze(a,e){try{await a.instantiate({url:new URL(e,`https://deno.land/x/lucid@${ge.version}/src/core/libs/`)})}catch{}}await Promise.all([Ze(o,"cardano_multiplatform_lib/cardano_multiplatform_lib_bg.wasm"),Ze(T,"cardano_message_signing/cardano_message_signing_bg.wasm")]);function Qe(a){let e=o.Costmdls.new(),t=o.CostModel.new();Object.values(a.PlutusV1).forEach((s,n)=>{t.set(n,o.Int.new(o.BigNum.from_str(s.toString())))}),e.insert(o.Language.new_plutus_v1(),t);let r=o.CostModel.new_plutus_v2();return Object.values(a.PlutusV2||[]).forEach((s,n)=>{r.set(n,o.Int.new(o.BigNum.from_str(s.toString())))}),e.insert(o.Language.new_plutus_v2(),r),e}var et={minFeeA:44,minFeeB:155381,maxTxSize:16384,maxValSize:5e3,keyDeposit:2000000n,poolDeposit:500000000n,priceMem:.0577,priceStep:721e-7,maxTxExMem:14000000n,maxTxExSteps:10000000000n,coinsPerUtxoByte:4310n,collateralPercentage:150,maxCollateralInputs:3,costModels:{PlutusV1:{"addInteger-cpu-arguments-intercept":205665,"addInteger-cpu-arguments-slope":812,"addInteger-memory-arguments-intercept":1,"addInteger-memory-arguments-slope":1,"appendByteString-cpu-arguments-intercept":1e3,"appendByteString-cpu-arguments-slope":571,"appendByteString-memory-arguments-intercept":0,"appendByteString-memory-arguments-slope":1,"appendString-cpu-arguments-intercept":1e3,"appendString-cpu-arguments-slope":24177,"appendString-memory-arguments-intercept":4,"appendString-memory-arguments-slope":1,"bData-cpu-arguments":1e3,"bData-memory-arguments":32,"blake2b_256-cpu-arguments-intercept":117366,"blake2b_256-cpu-arguments-slope":10475,"blake2b_256-memory-arguments":4,"cekApplyCost-exBudgetCPU":23e3,"cekApplyCost-exBudgetMemory":100,"cekBuiltinCost-exBudgetCPU":23e3,"cekBuiltinCost-exBudgetMemory":100,"cekConstCost-exBudgetCPU":23e3,"cekConstCost-exBudgetMemory":100,"cekDelayCost-exBudgetCPU":23e3,"cekDelayCost-exBudgetMemory":100,"cekForceCost-exBudgetCPU":23e3,"cekForceCost-exBudgetMemory":100,"cekLamCost-exBudgetCPU":23e3,"cekLamCost-exBudgetMemory":100,"cekStartupCost-exBudgetCPU":100,"cekStartupCost-exBudgetMemory":100,"cekVarCost-exBudgetCPU":23e3,"cekVarCost-exBudgetMemory":100,"chooseData-cpu-arguments":19537,"chooseData-memory-arguments":32,"chooseList-cpu-arguments":175354,"chooseList-memory-arguments":32,"chooseUnit-cpu-arguments":46417,"chooseUnit-memory-arguments":4,"consByteString-cpu-arguments-intercept":221973,"consByteString-cpu-arguments-slope":511,"consByteString-memory-arguments-intercept":0,"consByteString-memory-arguments-slope":1,"constrData-cpu-arguments":89141,"constrData-memory-arguments":32,"decodeUtf8-cpu-arguments-intercept":497525,"decodeUtf8-cpu-arguments-slope":14068,"decodeUtf8-memory-arguments-intercept":4,"decodeUtf8-memory-arguments-slope":2,"divideInteger-cpu-arguments-constant":196500,"divideInteger-cpu-arguments-model-arguments-intercept":453240,"divideInteger-cpu-arguments-model-arguments-slope":220,"divideInteger-memory-arguments-intercept":0,"divideInteger-memory-arguments-minimum":1,"divideInteger-memory-arguments-slope":1,"encodeUtf8-cpu-arguments-intercept":1e3,"encodeUtf8-cpu-arguments-slope":28662,"encodeUtf8-memory-arguments-intercept":4,"encodeUtf8-memory-arguments-slope":2,"equalsByteString-cpu-arguments-constant":245e3,"equalsByteString-cpu-arguments-intercept":216773,"equalsByteString-cpu-arguments-slope":62,"equalsByteString-memory-arguments":1,"equalsData-cpu-arguments-intercept":1060367,"equalsData-cpu-arguments-slope":12586,"equalsData-memory-arguments":1,"equalsInteger-cpu-arguments-intercept":208512,"equalsInteger-cpu-arguments-slope":421,"equalsInteger-memory-arguments":1,"equalsString-cpu-arguments-constant":187e3,"equalsString-cpu-arguments-intercept":1e3,"equalsString-cpu-arguments-slope":52998,"equalsString-memory-arguments":1,"fstPair-cpu-arguments":80436,"fstPair-memory-arguments":32,"headList-cpu-arguments":43249,"headList-memory-arguments":32,"iData-cpu-arguments":1e3,"iData-memory-arguments":32,"ifThenElse-cpu-arguments":80556,"ifThenElse-memory-arguments":1,"indexByteString-cpu-arguments":57667,"indexByteString-memory-arguments":4,"lengthOfByteString-cpu-arguments":1e3,"lengthOfByteString-memory-arguments":10,"lessThanByteString-cpu-arguments-intercept":197145,"lessThanByteString-cpu-arguments-slope":156,"lessThanByteString-memory-arguments":1,"lessThanEqualsByteString-cpu-arguments-intercept":197145,"lessThanEqualsByteString-cpu-arguments-slope":156,"lessThanEqualsByteString-memory-arguments":1,"lessThanEqualsInteger-cpu-arguments-intercept":204924,"lessThanEqualsInteger-cpu-arguments-slope":473,"lessThanEqualsInteger-memory-arguments":1,"lessThanInteger-cpu-arguments-intercept":208896,"lessThanInteger-cpu-arguments-slope":511,"lessThanInteger-memory-arguments":1,"listData-cpu-arguments":52467,"listData-memory-arguments":32,"mapData-cpu-arguments":64832,"mapData-memory-arguments":32,"mkCons-cpu-arguments":65493,"mkCons-memory-arguments":32,"mkNilData-cpu-arguments":22558,"mkNilData-memory-arguments":32,"mkNilPairData-cpu-arguments":16563,"mkNilPairData-memory-arguments":32,"mkPairData-cpu-arguments":76511,"mkPairData-memory-arguments":32,"modInteger-cpu-arguments-constant":196500,"modInteger-cpu-arguments-model-arguments-intercept":453240,"modInteger-cpu-arguments-model-arguments-slope":220,"modInteger-memory-arguments-intercept":0,"modInteger-memory-arguments-minimum":1,"modInteger-memory-arguments-slope":1,"multiplyInteger-cpu-arguments-intercept":69522,"multiplyInteger-cpu-arguments-slope":11687,"multiplyInteger-memory-arguments-intercept":0,"multiplyInteger-memory-arguments-slope":1,"nullList-cpu-arguments":60091,"nullList-memory-arguments":32,"quotientInteger-cpu-arguments-constant":196500,"quotientInteger-cpu-arguments-model-arguments-intercept":453240,"quotientInteger-cpu-arguments-model-arguments-slope":220,"quotientInteger-memory-arguments-intercept":0,"quotientInteger-memory-arguments-minimum":1,"quotientInteger-memory-arguments-slope":1,"remainderInteger-cpu-arguments-constant":196500,"remainderInteger-cpu-arguments-model-arguments-intercept":453240,"remainderInteger-cpu-arguments-model-arguments-slope":220,"remainderInteger-memory-arguments-intercept":0,"remainderInteger-memory-arguments-minimum":1,"remainderInteger-memory-arguments-slope":1,"sha2_256-cpu-arguments-intercept":806990,"sha2_256-cpu-arguments-slope":30482,"sha2_256-memory-arguments":4,"sha3_256-cpu-arguments-intercept":1927926,"sha3_256-cpu-arguments-slope":82523,"sha3_256-memory-arguments":4,"sliceByteString-cpu-arguments-intercept":265318,"sliceByteString-cpu-arguments-slope":0,"sliceByteString-memory-arguments-intercept":4,"sliceByteString-memory-arguments-slope":0,"sndPair-cpu-arguments":85931,"sndPair-memory-arguments":32,"subtractInteger-cpu-arguments-intercept":205665,"subtractInteger-cpu-arguments-slope":812,"subtractInteger-memory-arguments-intercept":1,"subtractInteger-memory-arguments-slope":1,"tailList-cpu-arguments":41182,"tailList-memory-arguments":32,"trace-cpu-arguments":212342,"trace-memory-arguments":32,"unBData-cpu-arguments":31220,"unBData-memory-arguments":32,"unConstrData-cpu-arguments":32696,"unConstrData-memory-arguments":32,"unIData-cpu-arguments":43357,"unIData-memory-arguments":32,"unListData-cpu-arguments":32247,"unListData-memory-arguments":32,"unMapData-cpu-arguments":38314,"unMapData-memory-arguments":32,"verifyEd25519Signature-cpu-arguments-intercept":9462713,"verifyEd25519Signature-cpu-arguments-slope":1021,"verifyEd25519Signature-memory-arguments":10},PlutusV2:{"addInteger-cpu-arguments-intercept":205665,"addInteger-cpu-arguments-slope":812,"addInteger-memory-arguments-intercept":1,"addInteger-memory-arguments-slope":1,"appendByteString-cpu-arguments-intercept":1e3,"appendByteString-cpu-arguments-slope":571,"appendByteString-memory-arguments-intercept":0,"appendByteString-memory-arguments-slope":1,"appendString-cpu-arguments-intercept":1e3,"appendString-cpu-arguments-slope":24177,"appendString-memory-arguments-intercept":4,"appendString-memory-arguments-slope":1,"bData-cpu-arguments":1e3,"bData-memory-arguments":32,"blake2b_256-cpu-arguments-intercept":117366,"blake2b_256-cpu-arguments-slope":10475,"blake2b_256-memory-arguments":4,"cekApplyCost-exBudgetCPU":23e3,"cekApplyCost-exBudgetMemory":100,"cekBuiltinCost-exBudgetCPU":23e3,"cekBuiltinCost-exBudgetMemory":100,"cekConstCost-exBudgetCPU":23e3,"cekConstCost-exBudgetMemory":100,"cekDelayCost-exBudgetCPU":23e3,"cekDelayCost-exBudgetMemory":100,"cekForceCost-exBudgetCPU":23e3,"cekForceCost-exBudgetMemory":100,"cekLamCost-exBudgetCPU":23e3,"cekLamCost-exBudgetMemory":100,"cekStartupCost-exBudgetCPU":100,"cekStartupCost-exBudgetMemory":100,"cekVarCost-exBudgetCPU":23e3,"cekVarCost-exBudgetMemory":100,"chooseData-cpu-arguments":19537,"chooseData-memory-arguments":32,"chooseList-cpu-arguments":175354,"chooseList-memory-arguments":32,"chooseUnit-cpu-arguments":46417,"chooseUnit-memory-arguments":4,"consByteString-cpu-arguments-intercept":221973,"consByteString-cpu-arguments-slope":511,"consByteString-memory-arguments-intercept":0,"consByteString-memory-arguments-slope":1,"constrData-cpu-arguments":89141,"constrData-memory-arguments":32,"decodeUtf8-cpu-arguments-intercept":497525,"decodeUtf8-cpu-arguments-slope":14068,"decodeUtf8-memory-arguments-intercept":4,"decodeUtf8-memory-arguments-slope":2,"divideInteger-cpu-arguments-constant":196500,"divideInteger-cpu-arguments-model-arguments-intercept":453240,"divideInteger-cpu-arguments-model-arguments-slope":220,"divideInteger-memory-arguments-intercept":0,"divideInteger-memory-arguments-minimum":1,"divideInteger-memory-arguments-slope":1,"encodeUtf8-cpu-arguments-intercept":1e3,"encodeUtf8-cpu-arguments-slope":28662,"encodeUtf8-memory-arguments-intercept":4,"encodeUtf8-memory-arguments-slope":2,"equalsByteString-cpu-arguments-constant":245e3,"equalsByteString-cpu-arguments-intercept":216773,"equalsByteString-cpu-arguments-slope":62,"equalsByteString-memory-arguments":1,"equalsData-cpu-arguments-intercept":1060367,"equalsData-cpu-arguments-slope":12586,"equalsData-memory-arguments":1,"equalsInteger-cpu-arguments-intercept":208512,"equalsInteger-cpu-arguments-slope":421,"equalsInteger-memory-arguments":1,"equalsString-cpu-arguments-constant":187e3,"equalsString-cpu-arguments-intercept":1e3,"equalsString-cpu-arguments-slope":52998,"equalsString-memory-arguments":1,"fstPair-cpu-arguments":80436,"fstPair-memory-arguments":32,"headList-cpu-arguments":43249,"headList-memory-arguments":32,"iData-cpu-arguments":1e3,"iData-memory-arguments":32,"ifThenElse-cpu-arguments":80556,"ifThenElse-memory-arguments":1,"indexByteString-cpu-arguments":57667,"indexByteString-memory-arguments":4,"lengthOfByteString-cpu-arguments":1e3,"lengthOfByteString-memory-arguments":10,"lessThanByteString-cpu-arguments-intercept":197145,"lessThanByteString-cpu-arguments-slope":156,"lessThanByteString-memory-arguments":1,"lessThanEqualsByteString-cpu-arguments-intercept":197145,"lessThanEqualsByteString-cpu-arguments-slope":156,"lessThanEqualsByteString-memory-arguments":1,"lessThanEqualsInteger-cpu-arguments-intercept":204924,"lessThanEqualsInteger-cpu-arguments-slope":473,"lessThanEqualsInteger-memory-arguments":1,"lessThanInteger-cpu-arguments-intercept":208896,"lessThanInteger-cpu-arguments-slope":511,"lessThanInteger-memory-arguments":1,"listData-cpu-arguments":52467,"listData-memory-arguments":32,"mapData-cpu-arguments":64832,"mapData-memory-arguments":32,"mkCons-cpu-arguments":65493,"mkCons-memory-arguments":32,"mkNilData-cpu-arguments":22558,"mkNilData-memory-arguments":32,"mkNilPairData-cpu-arguments":16563,"mkNilPairData-memory-arguments":32,"mkPairData-cpu-arguments":76511,"mkPairData-memory-arguments":32,"modInteger-cpu-arguments-constant":196500,"modInteger-cpu-arguments-model-arguments-intercept":453240,"modInteger-cpu-arguments-model-arguments-slope":220,"modInteger-memory-arguments-intercept":0,"modInteger-memory-arguments-minimum":1,"modInteger-memory-arguments-slope":1,"multiplyInteger-cpu-arguments-intercept":69522,"multiplyInteger-cpu-arguments-slope":11687,"multiplyInteger-memory-arguments-intercept":0,"multiplyInteger-memory-arguments-slope":1,"nullList-cpu-arguments":60091,"nullList-memory-arguments":32,"quotientInteger-cpu-arguments-constant":196500,"quotientInteger-cpu-arguments-model-arguments-intercept":453240,"quotientInteger-cpu-arguments-model-arguments-slope":220,"quotientInteger-memory-arguments-intercept":0,"quotientInteger-memory-arguments-minimum":1,"quotientInteger-memory-arguments-slope":1,"remainderInteger-cpu-arguments-constant":196500,"remainderInteger-cpu-arguments-model-arguments-intercept":453240,"remainderInteger-cpu-arguments-model-arguments-slope":220,"remainderInteger-memory-arguments-intercept":0,"remainderInteger-memory-arguments-minimum":1,"remainderInteger-memory-arguments-slope":1,"serialiseData-cpu-arguments-intercept":1159724,"serialiseData-cpu-arguments-slope":392670,"serialiseData-memory-arguments-intercept":0,"serialiseData-memory-arguments-slope":2,"sha2_256-cpu-arguments-intercept":806990,"sha2_256-cpu-arguments-slope":30482,"sha2_256-memory-arguments":4,"sha3_256-cpu-arguments-intercept":1927926,"sha3_256-cpu-arguments-slope":82523,"sha3_256-memory-arguments":4,"sliceByteString-cpu-arguments-intercept":265318,"sliceByteString-cpu-arguments-slope":0,"sliceByteString-memory-arguments-intercept":4,"sliceByteString-memory-arguments-slope":0,"sndPair-cpu-arguments":85931,"sndPair-memory-arguments":32,"subtractInteger-cpu-arguments-intercept":205665,"subtractInteger-cpu-arguments-slope":812,"subtractInteger-memory-arguments-intercept":1,"subtractInteger-memory-arguments-slope":1,"tailList-cpu-arguments":41182,"tailList-memory-arguments":32,"trace-cpu-arguments":212342,"trace-memory-arguments":32,"unBData-cpu-arguments":31220,"unBData-memory-arguments":32,"unConstrData-cpu-arguments":32696,"unConstrData-memory-arguments":32,"unIData-cpu-arguments":43357,"unIData-memory-arguments":32,"unListData-cpu-arguments":32247,"unListData-memory-arguments":32,"unMapData-cpu-arguments":38314,"unMapData-memory-arguments":32,"verifyEcdsaSecp256k1Signature-cpu-arguments":35892428,"verifyEcdsaSecp256k1Signature-memory-arguments":10,"verifyEd25519Signature-cpu-arguments-intercept":57996947,"verifyEd25519Signature-cpu-arguments-slope":18975,"verifyEd25519Signature-memory-arguments":10,"verifySchnorrSecp256k1Signature-cpu-arguments-intercept":38887044,"verifySchnorrSecp256k1Signature-cpu-arguments-slope":32947,"verifySchnorrSecp256k1Signature-memory-arguments":10}}};var tt=new TextEncoder().encode("0123456789abcdef");function Dt(a){return new Error("encoding/hex: invalid byte: "+new TextDecoder().decode(new Uint8Array([a])))}function Mt(){return new Error("encoding/hex: odd length hex string")}function qe(a){if(48<=a&&a<=57)return a-48;if(97<=a&&a<=102)return a-97+10;if(65<=a&&a<=70)return a-65+10;throw Dt(a)}function Rt(a){return a*2}function $t(a){let e=new Uint8Array(Rt(a.length));for(let t=0;t>4],e[t*2+1]=tt[r&15]}return e}function rt(a){return new TextDecoder().decode($t(a))}function Ke(a){let e=new Uint8Array(qt(a.length));for(let t=0;t>>1}function st(a){return Ke(new TextEncoder().encode(a))}var v=function(a,e,t,r,s){if(r==="m")throw new TypeError("Private method is not writable");if(r==="a"&&!s)throw new TypeError("Private accessor was defined without a setter");if(typeof e=="function"?a!==e||!s:!e.has(a))throw new TypeError("Cannot write private member to an object whose class did not declare it");return r==="a"?s.call(a,t):s?s.value=t:e.set(a,t),t},g=function(a,e,t,r){if(t==="a"&&!r)throw new TypeError("Private accessor was defined without a getter");if(typeof e=="function"?a!==e||!r:!e.has(a))throw new TypeError("Cannot read private member from an object whose class did not declare it");return t==="m"?r:t==="a"?r.call(a):r?r.value:e.get(a)},se,ce,L,ye,ve,V,F,J,X,G,Y,Z,Q,le,xe,ne,Be,ae,Kt,Lt,zt,Wt,x="0123456789abcdef".split(""),Vt=[-2147483648,8388608,32768,128],K=[24,16,8,0],Ee=[1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298],U=[],we=class{constructor(e=!1,t=!1){se.set(this,void 0),ce.set(this,void 0),L.set(this,void 0),ye.set(this,void 0),ve.set(this,void 0),V.set(this,void 0),F.set(this,void 0),J.set(this,void 0),X.set(this,void 0),G.set(this,void 0),Y.set(this,void 0),Z.set(this,void 0),Q.set(this,void 0),le.set(this,void 0),xe.set(this,void 0),ne.set(this,void 0),Be.set(this,0),ae.set(this,void 0),this.init(e,t)}init(e,t){t?(U[0]=U[16]=U[1]=U[2]=U[3]=U[4]=U[5]=U[6]=U[7]=U[8]=U[9]=U[10]=U[11]=U[12]=U[13]=U[14]=U[15]=0,v(this,ce,U,"f")):v(this,ce,[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],"f"),e?(v(this,V,3238371032,"f"),v(this,F,914150663,"f"),v(this,J,812702999,"f"),v(this,X,4144912697,"f"),v(this,G,4290775857,"f"),v(this,Y,1750603025,"f"),v(this,Z,1694076839,"f"),v(this,Q,3204075428,"f")):(v(this,V,1779033703,"f"),v(this,F,3144134277,"f"),v(this,J,1013904242,"f"),v(this,X,2773480762,"f"),v(this,G,1359893119,"f"),v(this,Y,2600822924,"f"),v(this,Z,528734635,"f"),v(this,Q,1541459225,"f")),v(this,se,v(this,ae,v(this,L,v(this,xe,0,"f"),"f"),"f"),"f"),v(this,ye,v(this,le,!1,"f"),"f"),v(this,ve,!0,"f"),v(this,ne,e,"f")}update(e){if(g(this,ye,"f"))return this;let t;e instanceof ArrayBuffer?t=new Uint8Array(e):t=e;let r=0,s=t.length,n=g(this,ce,"f");for(;r>2]|=t[r]<>2]|=u<>2]|=(192|u>>6)<>2]|=(128|u&63)<=57344?(n[i>>2]|=(224|u>>12)<>2]|=(128|u>>6&63)<>2]|=(128|u&63)<>2]|=(240|u>>18)<>2]|=(128|u>>12&63)<>2]|=(128|u>>6&63)<>2]|=(128|u&63)<=64?(v(this,se,n[16],"f"),v(this,ae,i-64,"f"),this.hash(),v(this,le,!0,"f")):v(this,ae,i,"f")}return g(this,L,"f")>4294967295&&(v(this,xe,g(this,xe,"f")+(g(this,L,"f")/4294967296<<0),"f"),v(this,L,g(this,L,"f")%4294967296,"f")),this}finalize(){if(g(this,ye,"f"))return;v(this,ye,!0,"f");let e=g(this,ce,"f"),t=g(this,Be,"f");e[16]=g(this,se,"f"),e[t>>2]|=Vt[t&3],v(this,se,e[16],"f"),t>=56&&(g(this,le,"f")||this.hash(),e[0]=g(this,se,"f"),e[16]=e[1]=e[2]=e[3]=e[4]=e[5]=e[6]=e[7]=e[8]=e[9]=e[10]=e[11]=e[12]=e[13]=e[14]=e[15]=0),e[14]=g(this,xe,"f")<<3|g(this,L,"f")>>>29,e[15]=g(this,L,"f")<<3,this.hash()}hash(){let e=g(this,V,"f"),t=g(this,F,"f"),r=g(this,J,"f"),s=g(this,X,"f"),n=g(this,G,"f"),i=g(this,Y,"f"),u=g(this,Z,"f"),c=g(this,Q,"f"),m=g(this,ce,"f"),p,C,E,h,_,I,w,A,O,R;for(let B=16;B<64;++B)h=m[B-15],p=(h>>>7|h<<25)^(h>>>18|h<<14)^h>>>3,h=m[B-2],C=(h>>>17|h<<15)^(h>>>19|h<<13)^h>>>10,m[B]=m[B-16]+p+m[B-7]+C<<0;R=t&r;for(let B=0;B<64;B+=4)g(this,ve,"f")?(g(this,ne,"f")?(w=300032,h=m[0]-1413257819,c=h-150054599<<0,s=h+24177077<<0):(w=704751109,h=m[0]-210244248,c=h-1521486534<<0,s=h+143694565<<0),v(this,ve,!1,"f")):(p=(e>>>2|e<<30)^(e>>>13|e<<19)^(e>>>22|e<<10),C=(n>>>6|n<<26)^(n>>>11|n<<21)^(n>>>25|n<<7),w=e&t,E=w^e&r^R,I=n&i^~n&u,h=c+C+I+Ee[B]+m[B],_=p+E,c=s+h<<0,s=h+_<<0),p=(s>>>2|s<<30)^(s>>>13|s<<19)^(s>>>22|s<<10),C=(c>>>6|c<<26)^(c>>>11|c<<21)^(c>>>25|c<<7),A=s&e,E=A^s&t^w,I=c&n^~c&i,h=u+C+I+Ee[B+1]+m[B+1],_=p+E,u=r+h<<0,r=h+_<<0,p=(r>>>2|r<<30)^(r>>>13|r<<19)^(r>>>22|r<<10),C=(u>>>6|u<<26)^(u>>>11|u<<21)^(u>>>25|u<<7),O=r&s,E=O^r&e^A,I=u&c^~u&n,h=i+C+I+Ee[B+2]+m[B+2],_=p+E,i=t+h<<0,t=h+_<<0,p=(t>>>2|t<<30)^(t>>>13|t<<19)^(t>>>22|t<<10),C=(i>>>6|i<<26)^(i>>>11|i<<21)^(i>>>25|i<<7),R=t&r,E=R^t&s^O,I=i&u^~i&c,h=n+C+I+Ee[B+3]+m[B+3],_=p+E,n=e+h<<0,e=h+_<<0;v(this,V,g(this,V,"f")+e<<0,"f"),v(this,F,g(this,F,"f")+t<<0,"f"),v(this,J,g(this,J,"f")+r<<0,"f"),v(this,X,g(this,X,"f")+s<<0,"f"),v(this,G,g(this,G,"f")+n<<0,"f"),v(this,Y,g(this,Y,"f")+i<<0,"f"),v(this,Z,g(this,Z,"f")+u<<0,"f"),v(this,Q,g(this,Q,"f")+c<<0,"f")}hex(){this.finalize();let e=g(this,V,"f"),t=g(this,F,"f"),r=g(this,J,"f"),s=g(this,X,"f"),n=g(this,G,"f"),i=g(this,Y,"f"),u=g(this,Z,"f"),c=g(this,Q,"f"),m=x[e>>28&15]+x[e>>24&15]+x[e>>20&15]+x[e>>16&15]+x[e>>12&15]+x[e>>8&15]+x[e>>4&15]+x[e&15]+x[t>>28&15]+x[t>>24&15]+x[t>>20&15]+x[t>>16&15]+x[t>>12&15]+x[t>>8&15]+x[t>>4&15]+x[t&15]+x[r>>28&15]+x[r>>24&15]+x[r>>20&15]+x[r>>16&15]+x[r>>12&15]+x[r>>8&15]+x[r>>4&15]+x[r&15]+x[s>>28&15]+x[s>>24&15]+x[s>>20&15]+x[s>>16&15]+x[s>>12&15]+x[s>>8&15]+x[s>>4&15]+x[s&15]+x[n>>28&15]+x[n>>24&15]+x[n>>20&15]+x[n>>16&15]+x[n>>12&15]+x[n>>8&15]+x[n>>4&15]+x[n&15]+x[i>>28&15]+x[i>>24&15]+x[i>>20&15]+x[i>>16&15]+x[i>>12&15]+x[i>>8&15]+x[i>>4&15]+x[i&15]+x[u>>28&15]+x[u>>24&15]+x[u>>20&15]+x[u>>16&15]+x[u>>12&15]+x[u>>8&15]+x[u>>4&15]+x[u&15];return g(this,ne,"f")||(m+=x[c>>28&15]+x[c>>24&15]+x[c>>20&15]+x[c>>16&15]+x[c>>12&15]+x[c>>8&15]+x[c>>4&15]+x[c&15]),m}toString(){return this.hex()}digest(){this.finalize();let e=g(this,V,"f"),t=g(this,F,"f"),r=g(this,J,"f"),s=g(this,X,"f"),n=g(this,G,"f"),i=g(this,Y,"f"),u=g(this,Z,"f"),c=g(this,Q,"f"),m=[e>>24&255,e>>16&255,e>>8&255,e&255,t>>24&255,t>>16&255,t>>8&255,t&255,r>>24&255,r>>16&255,r>>8&255,r&255,s>>24&255,s>>16&255,s>>8&255,s&255,n>>24&255,n>>16&255,n>>8&255,n&255,i>>24&255,i>>16&255,i>>8&255,i&255,u>>24&255,u>>16&255,u>>8&255,u&255];return g(this,ne,"f")||m.push(c>>24&255,c>>16&255,c>>8&255,c&255),m}array(){return this.digest()}arrayBuffer(){this.finalize();let e=new ArrayBuffer(g(this,ne,"f")?28:32),t=new DataView(e);return t.setUint32(0,g(this,V,"f")),t.setUint32(4,g(this,F,"f")),t.setUint32(8,g(this,J,"f")),t.setUint32(12,g(this,X,"f")),t.setUint32(16,g(this,G,"f")),t.setUint32(20,g(this,Y,"f")),t.setUint32(24,g(this,Z,"f")),g(this,ne,"f")||t.setUint32(28,g(this,Q,"f")),e}};se=new WeakMap,ce=new WeakMap,L=new WeakMap,ye=new WeakMap,ve=new WeakMap,V=new WeakMap,F=new WeakMap,J=new WeakMap,X=new WeakMap,G=new WeakMap,Y=new WeakMap,Z=new WeakMap,Q=new WeakMap,le=new WeakMap,xe=new WeakMap,ne=new WeakMap,Be=new WeakMap,ae=new WeakMap;Kt=new WeakMap,Lt=new WeakMap,zt=new WeakMap,Wt=new WeakMap;var nt="Invalid mnemonic",de="Invalid entropy",Ft="Invalid mnemonic checksum",at=`A wordlist is required but a default could not be found. -Please pass a 2048 word array explicitly.`;function ot(a,e){if(e=e||ht,!e)throw new Error(at);let t=Gt(a).split(" ");if(t.length%3!==0)throw new Error(nt);let r=t.map(p=>{let C=e.indexOf(p);if(C===-1)throw new Error(nt);return ct(C.toString(2),"0",11)}).join(""),s=Math.floor(r.length/33)*32,n=r.slice(0,s),i=r.slice(s),u=n.match(/(.{1,8})/g).map(dt);if(u.length<16)throw new Error(de);if(u.length>32)throw new Error(de);if(u.length%4!==0)throw new Error(de);let c=new Uint8Array(u);if(ut(c)!==i)throw new Error(Ft);return y(c)}function Jt(a){let r=new Uint8Array(a);if(a>4294967295)throw new RangeError("requested too many random bytes");if(a>0)if(a>65536)for(let s=0;s32)throw new TypeError(de);if(a.length%4!==0)throw new TypeError(de);let t=lt(Array.from(a)),r=ut(a),i=(t+r).match(/(.{1,11})/g).map(u=>{let c=dt(u);return e[c]});return e[0]==="\u3042\u3044\u3053\u304F\u3057\u3093"?i.join("\u3000"):i.join(" ")}function ut(a){let t=a.length*8/32,r=new we().update(a).digest();return lt(Array.from(r)).slice(0,t)}function ct(a,e,t){for(;a.lengthct(e.toString(2),"0",8)).join("")}function Gt(a){return(a||"").normalize("NFKD")}function dt(a){return parseInt(a,2)}var ht=["abandon","ability","able","about","above","absent","absorb","abstract","absurd","abuse","access","accident","account","accuse","achieve","acid","acoustic","acquire","across","act","action","actor","actress","actual","adapt","add","addict","address","adjust","admit","adult","advance","advice","aerobic","affair","afford","afraid","again","age","agent","agree","ahead","aim","air","airport","aisle","alarm","album","alcohol","alert","alien","all","alley","allow","almost","alone","alpha","already","also","alter","always","amateur","amazing","among","amount","amused","analyst","anchor","ancient","anger","angle","angry","animal","ankle","announce","annual","another","answer","antenna","antique","anxiety","any","apart","apology","appear","apple","approve","april","arch","arctic","area","arena","argue","arm","armed","armor","army","around","arrange","arrest","arrive","arrow","art","artefact","artist","artwork","ask","aspect","assault","asset","assist","assume","asthma","athlete","atom","attack","attend","attitude","attract","auction","audit","august","aunt","author","auto","autumn","average","avocado","avoid","awake","aware","away","awesome","awful","awkward","axis","baby","bachelor","bacon","badge","bag","balance","balcony","ball","bamboo","banana","banner","bar","barely","bargain","barrel","base","basic","basket","battle","beach","bean","beauty","because","become","beef","before","begin","behave","behind","believe","below","belt","bench","benefit","best","betray","better","between","beyond","bicycle","bid","bike","bind","biology","bird","birth","bitter","black","blade","blame","blanket","blast","bleak","bless","blind","blood","blossom","blouse","blue","blur","blush","board","boat","body","boil","bomb","bone","bonus","book","boost","border","boring","borrow","boss","bottom","bounce","box","boy","bracket","brain","brand","brass","brave","bread","breeze","brick","bridge","brief","bright","bring","brisk","broccoli","broken","bronze","broom","brother","brown","brush","bubble","buddy","budget","buffalo","build","bulb","bulk","bullet","bundle","bunker","burden","burger","burst","bus","business","busy","butter","buyer","buzz","cabbage","cabin","cable","cactus","cage","cake","call","calm","camera","camp","can","canal","cancel","candy","cannon","canoe","canvas","canyon","capable","capital","captain","car","carbon","card","cargo","carpet","carry","cart","case","cash","casino","castle","casual","cat","catalog","catch","category","cattle","caught","cause","caution","cave","ceiling","celery","cement","census","century","cereal","certain","chair","chalk","champion","change","chaos","chapter","charge","chase","chat","cheap","check","cheese","chef","cherry","chest","chicken","chief","child","chimney","choice","choose","chronic","chuckle","chunk","churn","cigar","cinnamon","circle","citizen","city","civil","claim","clap","clarify","claw","clay","clean","clerk","clever","click","client","cliff","climb","clinic","clip","clock","clog","close","cloth","cloud","clown","club","clump","cluster","clutch","coach","coast","coconut","code","coffee","coil","coin","collect","color","column","combine","come","comfort","comic","common","company","concert","conduct","confirm","congress","connect","consider","control","convince","cook","cool","copper","copy","coral","core","corn","correct","cost","cotton","couch","country","couple","course","cousin","cover","coyote","crack","cradle","craft","cram","crane","crash","crater","crawl","crazy","cream","credit","creek","crew","cricket","crime","crisp","critic","crop","cross","crouch","crowd","crucial","cruel","cruise","crumble","crunch","crush","cry","crystal","cube","culture","cup","cupboard","curious","current","curtain","curve","cushion","custom","cute","cycle","dad","damage","damp","dance","danger","daring","dash","daughter","dawn","day","deal","debate","debris","decade","december","decide","decline","decorate","decrease","deer","defense","define","defy","degree","delay","deliver","demand","demise","denial","dentist","deny","depart","depend","deposit","depth","deputy","derive","describe","desert","design","desk","despair","destroy","detail","detect","develop","device","devote","diagram","dial","diamond","diary","dice","diesel","diet","differ","digital","dignity","dilemma","dinner","dinosaur","direct","dirt","disagree","discover","disease","dish","dismiss","disorder","display","distance","divert","divide","divorce","dizzy","doctor","document","dog","doll","dolphin","domain","donate","donkey","donor","door","dose","double","dove","draft","dragon","drama","drastic","draw","dream","dress","drift","drill","drink","drip","drive","drop","drum","dry","duck","dumb","dune","during","dust","dutch","duty","dwarf","dynamic","eager","eagle","early","earn","earth","easily","east","easy","echo","ecology","economy","edge","edit","educate","effort","egg","eight","either","elbow","elder","electric","elegant","element","elephant","elevator","elite","else","embark","embody","embrace","emerge","emotion","employ","empower","empty","enable","enact","end","endless","endorse","enemy","energy","enforce","engage","engine","enhance","enjoy","enlist","enough","enrich","enroll","ensure","enter","entire","entry","envelope","episode","equal","equip","era","erase","erode","erosion","error","erupt","escape","essay","essence","estate","eternal","ethics","evidence","evil","evoke","evolve","exact","example","excess","exchange","excite","exclude","excuse","execute","exercise","exhaust","exhibit","exile","exist","exit","exotic","expand","expect","expire","explain","expose","express","extend","extra","eye","eyebrow","fabric","face","faculty","fade","faint","faith","fall","false","fame","family","famous","fan","fancy","fantasy","farm","fashion","fat","fatal","father","fatigue","fault","favorite","feature","february","federal","fee","feed","feel","female","fence","festival","fetch","fever","few","fiber","fiction","field","figure","file","film","filter","final","find","fine","finger","finish","fire","firm","first","fiscal","fish","fit","fitness","fix","flag","flame","flash","flat","flavor","flee","flight","flip","float","flock","floor","flower","fluid","flush","fly","foam","focus","fog","foil","fold","follow","food","foot","force","forest","forget","fork","fortune","forum","forward","fossil","foster","found","fox","fragile","frame","frequent","fresh","friend","fringe","frog","front","frost","frown","frozen","fruit","fuel","fun","funny","furnace","fury","future","gadget","gain","galaxy","gallery","game","gap","garage","garbage","garden","garlic","garment","gas","gasp","gate","gather","gauge","gaze","general","genius","genre","gentle","genuine","gesture","ghost","giant","gift","giggle","ginger","giraffe","girl","give","glad","glance","glare","glass","glide","glimpse","globe","gloom","glory","glove","glow","glue","goat","goddess","gold","good","goose","gorilla","gospel","gossip","govern","gown","grab","grace","grain","grant","grape","grass","gravity","great","green","grid","grief","grit","grocery","group","grow","grunt","guard","guess","guide","guilt","guitar","gun","gym","habit","hair","half","hammer","hamster","hand","happy","harbor","hard","harsh","harvest","hat","have","hawk","hazard","head","health","heart","heavy","hedgehog","height","hello","helmet","help","hen","hero","hidden","high","hill","hint","hip","hire","history","hobby","hockey","hold","hole","holiday","hollow","home","honey","hood","hope","horn","horror","horse","hospital","host","hotel","hour","hover","hub","huge","human","humble","humor","hundred","hungry","hunt","hurdle","hurry","hurt","husband","hybrid","ice","icon","idea","identify","idle","ignore","ill","illegal","illness","image","imitate","immense","immune","impact","impose","improve","impulse","inch","include","income","increase","index","indicate","indoor","industry","infant","inflict","inform","inhale","inherit","initial","inject","injury","inmate","inner","innocent","input","inquiry","insane","insect","inside","inspire","install","intact","interest","into","invest","invite","involve","iron","island","isolate","issue","item","ivory","jacket","jaguar","jar","jazz","jealous","jeans","jelly","jewel","job","join","joke","journey","joy","judge","juice","jump","jungle","junior","junk","just","kangaroo","keen","keep","ketchup","key","kick","kid","kidney","kind","kingdom","kiss","kit","kitchen","kite","kitten","kiwi","knee","knife","knock","know","lab","label","labor","ladder","lady","lake","lamp","language","laptop","large","later","latin","laugh","laundry","lava","law","lawn","lawsuit","layer","lazy","leader","leaf","learn","leave","lecture","left","leg","legal","legend","leisure","lemon","lend","length","lens","leopard","lesson","letter","level","liar","liberty","library","license","life","lift","light","like","limb","limit","link","lion","liquid","list","little","live","lizard","load","loan","lobster","local","lock","logic","lonely","long","loop","lottery","loud","lounge","love","loyal","lucky","luggage","lumber","lunar","lunch","luxury","lyrics","machine","mad","magic","magnet","maid","mail","main","major","make","mammal","man","manage","mandate","mango","mansion","manual","maple","marble","march","margin","marine","market","marriage","mask","mass","master","match","material","math","matrix","matter","maximum","maze","meadow","mean","measure","meat","mechanic","medal","media","melody","melt","member","memory","mention","menu","mercy","merge","merit","merry","mesh","message","metal","method","middle","midnight","milk","million","mimic","mind","minimum","minor","minute","miracle","mirror","misery","miss","mistake","mix","mixed","mixture","mobile","model","modify","mom","moment","monitor","monkey","monster","month","moon","moral","more","morning","mosquito","mother","motion","motor","mountain","mouse","move","movie","much","muffin","mule","multiply","muscle","museum","mushroom","music","must","mutual","myself","mystery","myth","naive","name","napkin","narrow","nasty","nation","nature","near","neck","need","negative","neglect","neither","nephew","nerve","nest","net","network","neutral","never","news","next","nice","night","noble","noise","nominee","noodle","normal","north","nose","notable","note","nothing","notice","novel","now","nuclear","number","nurse","nut","oak","obey","object","oblige","obscure","observe","obtain","obvious","occur","ocean","october","odor","off","offer","office","often","oil","okay","old","olive","olympic","omit","once","one","onion","online","only","open","opera","opinion","oppose","option","orange","orbit","orchard","order","ordinary","organ","orient","original","orphan","ostrich","other","outdoor","outer","output","outside","oval","oven","over","own","owner","oxygen","oyster","ozone","pact","paddle","page","pair","palace","palm","panda","panel","panic","panther","paper","parade","parent","park","parrot","party","pass","patch","path","patient","patrol","pattern","pause","pave","payment","peace","peanut","pear","peasant","pelican","pen","penalty","pencil","people","pepper","perfect","permit","person","pet","phone","photo","phrase","physical","piano","picnic","picture","piece","pig","pigeon","pill","pilot","pink","pioneer","pipe","pistol","pitch","pizza","place","planet","plastic","plate","play","please","pledge","pluck","plug","plunge","poem","poet","point","polar","pole","police","pond","pony","pool","popular","portion","position","possible","post","potato","pottery","poverty","powder","power","practice","praise","predict","prefer","prepare","present","pretty","prevent","price","pride","primary","print","priority","prison","private","prize","problem","process","produce","profit","program","project","promote","proof","property","prosper","protect","proud","provide","public","pudding","pull","pulp","pulse","pumpkin","punch","pupil","puppy","purchase","purity","purpose","purse","push","put","puzzle","pyramid","quality","quantum","quarter","question","quick","quit","quiz","quote","rabbit","raccoon","race","rack","radar","radio","rail","rain","raise","rally","ramp","ranch","random","range","rapid","rare","rate","rather","raven","raw","razor","ready","real","reason","rebel","rebuild","recall","receive","recipe","record","recycle","reduce","reflect","reform","refuse","region","regret","regular","reject","relax","release","relief","rely","remain","remember","remind","remove","render","renew","rent","reopen","repair","repeat","replace","report","require","rescue","resemble","resist","resource","response","result","retire","retreat","return","reunion","reveal","review","reward","rhythm","rib","ribbon","rice","rich","ride","ridge","rifle","right","rigid","ring","riot","ripple","risk","ritual","rival","river","road","roast","robot","robust","rocket","romance","roof","rookie","room","rose","rotate","rough","round","route","royal","rubber","rude","rug","rule","run","runway","rural","sad","saddle","sadness","safe","sail","salad","salmon","salon","salt","salute","same","sample","sand","satisfy","satoshi","sauce","sausage","save","say","scale","scan","scare","scatter","scene","scheme","school","science","scissors","scorpion","scout","scrap","screen","script","scrub","sea","search","season","seat","second","secret","section","security","seed","seek","segment","select","sell","seminar","senior","sense","sentence","series","service","session","settle","setup","seven","shadow","shaft","shallow","share","shed","shell","sheriff","shield","shift","shine","ship","shiver","shock","shoe","shoot","shop","short","shoulder","shove","shrimp","shrug","shuffle","shy","sibling","sick","side","siege","sight","sign","silent","silk","silly","silver","similar","simple","since","sing","siren","sister","situate","six","size","skate","sketch","ski","skill","skin","skirt","skull","slab","slam","sleep","slender","slice","slide","slight","slim","slogan","slot","slow","slush","small","smart","smile","smoke","smooth","snack","snake","snap","sniff","snow","soap","soccer","social","sock","soda","soft","solar","soldier","solid","solution","solve","someone","song","soon","sorry","sort","soul","sound","soup","source","south","space","spare","spatial","spawn","speak","special","speed","spell","spend","sphere","spice","spider","spike","spin","spirit","split","spoil","sponsor","spoon","sport","spot","spray","spread","spring","spy","square","squeeze","squirrel","stable","stadium","staff","stage","stairs","stamp","stand","start","state","stay","steak","steel","stem","step","stereo","stick","still","sting","stock","stomach","stone","stool","story","stove","strategy","street","strike","strong","struggle","student","stuff","stumble","style","subject","submit","subway","success","such","sudden","suffer","sugar","suggest","suit","summer","sun","sunny","sunset","super","supply","supreme","sure","surface","surge","surprise","surround","survey","suspect","sustain","swallow","swamp","swap","swarm","swear","sweet","swift","swim","swing","switch","sword","symbol","symptom","syrup","system","table","tackle","tag","tail","talent","talk","tank","tape","target","task","taste","tattoo","taxi","teach","team","tell","ten","tenant","tennis","tent","term","test","text","thank","that","theme","then","theory","there","they","thing","this","thought","three","thrive","throw","thumb","thunder","ticket","tide","tiger","tilt","timber","time","tiny","tip","tired","tissue","title","toast","tobacco","today","toddler","toe","together","toilet","token","tomato","tomorrow","tone","tongue","tonight","tool","tooth","top","topic","topple","torch","tornado","tortoise","toss","total","tourist","toward","tower","town","toy","track","trade","traffic","tragic","train","transfer","trap","trash","travel","tray","treat","tree","trend","trial","tribe","trick","trigger","trim","trip","trophy","trouble","truck","true","truly","trumpet","trust","truth","try","tube","tuition","tumble","tuna","tunnel","turkey","turn","turtle","twelve","twenty","twice","twin","twist","two","type","typical","ugly","umbrella","unable","unaware","uncle","uncover","under","undo","unfair","unfold","unhappy","uniform","unique","unit","universe","unknown","unlock","until","unusual","unveil","update","upgrade","uphold","upon","upper","upset","urban","urge","usage","use","used","useful","useless","usual","utility","vacant","vacuum","vague","valid","valley","valve","van","vanish","vapor","various","vast","vault","vehicle","velvet","vendor","venture","venue","verb","verify","version","very","vessel","veteran","viable","vibrant","vicious","victory","video","view","village","vintage","violin","virtual","virus","visa","visit","visual","vital","vivid","vocal","voice","void","volcano","volume","vote","voyage","wage","wagon","wait","walk","wall","walnut","want","warfare","warm","warrior","wash","wasp","waste","water","wave","way","wealth","weapon","wear","weasel","weather","web","wedding","weekend","weird","welcome","west","wet","whale","what","wheat","wheel","when","where","whip","whisper","wide","width","wife","wild","will","win","window","wine","wing","wink","winner","winter","wire","wisdom","wise","wish","witness","wolf","woman","wonder","wood","wool","word","work","world","worry","worth","wrap","wreck","wrestle","wrist","write","wrong","yard","year","yellow","you","young","youth","zebra","zero","zone","zoo"];var Le=[0,7,14,9,28,27,18,21,56,63,54,49,36,35,42,45,112,119,126,121,108,107,98,101,72,79,70,65,84,83,90,93,224,231,238,233,252,251,242,245,216,223,214,209,196,195,202,205,144,151,158,153,140,139,130,133,168,175,166,161,180,179,186,189,199,192,201,206,219,220,213,210,255,248,241,246,227,228,237,234,183,176,185,190,171,172,165,162,143,136,129,134,147,148,157,154,39,32,41,46,59,60,53,50,31,24,17,22,3,4,13,10,87,80,89,94,75,76,69,66,111,104,97,102,115,116,125,122,137,142,135,128,149,146,155,156,177,182,191,184,173,170,163,164,249,254,247,240,229,226,235,236,193,198,207,200,221,218,211,212,105,110,103,96,117,114,123,124,81,86,95,88,77,74,67,68,25,30,23,16,5,2,11,12,33,38,47,40,61,58,51,52,78,73,64,71,82,85,92,91,118,113,120,127,106,109,100,99,62,57,48,55,34,37,44,43,6,1,8,15,26,29,20,19,174,169,160,167,178,181,188,187,150,145,152,159,138,141,132,131,222,217,208,215,194,197,204,203,230,225,232,239,250,253,244,243];typeof Int32Array<"u"&&(Le=new Int32Array(Le));function mt(a,e=0){let t=~~e;for(let r=0;risNaN(n)).map(n=>e[n]).map(n=>typeof n=="string"?{[S]:"Literal",type:"string",const:n}:{[S]:"Literal",type:"number",const:n});return this.Create({...t,[S]:"Union",[he]:"Enum",anyOf:s})}Function(e,t,r={}){if(e[S]==="Tuple"){let s=e.items===void 0?[]:e.items;return this.Create({...r,[S]:"Function",type:"object",instanceOf:"Function",parameters:s,returns:t})}else{if(globalThis.Array.isArray(e))return this.Create({...r,[S]:"Function",type:"object",instanceOf:"Function",parameters:e,returns:t});throw new Error("TypeBuilder.Function: Invalid parameters")}}InstanceType(e,t={}){return{...t,...this.Clone(e.returns)}}Integer(e={}){return this.Create({...e,[S]:"Integer",type:"integer"})}Intersect(e,t={}){let r=u=>u[H]&&u[H]==="Optional"||u[H]==="ReadonlyOptional",[s,n]=[new Set,new Set];for(let u of e)for(let[c,m]of Object.entries(u.properties))r(m)&&n.add(c);for(let u of e)for(let c of Object.keys(u.properties))n.has(c)||s.add(c);let i={};for(let u of e)for(let[c,m]of Object.entries(u.properties))i[c]=i[c]===void 0?m:{[S]:"Union",anyOf:[i[c],{...m}]};return s.size>0?this.Create({...t,[S]:"Object",type:"object",properties:i,required:[...s]}):this.Create({...t,[S]:"Object",type:"object",properties:i})}KeyOf(e,t={}){let r=Object.keys(e.properties).map(s=>this.Create({...t,[S]:"Literal",type:"string",const:s}));return this.Create({...t,[S]:"Union",[he]:"KeyOf",anyOf:r})}Literal(e,t={}){return this.Create({...t,[S]:"Literal",const:e,type:typeof e})}Never(e={}){return this.Create({...e,[S]:"Never",allOf:[{type:"boolean",const:!1},{type:"boolean",const:!0}]})}Null(e={}){return this.Create({...e,[S]:"Null",type:"null"})}Number(e={}){return this.Create({...e,[S]:"Number",type:"number"})}Object(e,t={}){let r=Object.keys(e),s=r.filter(i=>{let c=e[i][H];return c&&(c==="Optional"||c==="ReadonlyOptional")}),n=r.filter(i=>!s.includes(i));return n.length>0?this.Create({...t,[S]:"Object",type:"object",properties:e,required:n}):this.Create({...t,[S]:"Object",type:"object",properties:e})}Omit(e,t,r={}){let s=t[S]==="Union"?t.anyOf.map(i=>i.const):t,n={...this.Clone(e),...r,[he]:"Omit"};n.required&&(n.required=n.required.filter(i=>!s.includes(i)),n.required.length===0&&delete n.required);for(let i of Object.keys(n.properties))s.includes(i)&&delete n.properties[i];return this.Create(n)}Parameters(e,t={}){return N.Tuple(e.parameters,{...t})}Partial(e,t={}){let r={...this.Clone(e),...t,[he]:"Partial"};delete r.required;for(let s of Object.keys(r.properties)){let n=r.properties[s];switch(n[H]){case"ReadonlyOptional":n[H]="ReadonlyOptional";break;case"Readonly":n[H]="ReadonlyOptional";break;case"Optional":n[H]="Optional";break;default:n[H]="Optional";break}}return this.Create(r)}Pick(e,t,r={}){let s=t[S]==="Union"?t.anyOf.map(i=>i.const):t,n={...this.Clone(e),...r,[he]:"Pick"};n.required&&(n.required=n.required.filter(i=>s.includes(i)),n.required.length===0&&delete n.required);for(let i of Object.keys(n.properties))s.includes(i)||delete n.properties[i];return this.Create(n)}Promise(e,t={}){return this.Create({...t,[S]:"Promise",type:"object",instanceOf:"Promise",item:e})}Record(e,t,r={}){if(e[S]==="Union")return this.Object(e.anyOf.reduce((n,i)=>({...n,[i.const]:t}),{}),{...r,[he]:"Record"});let s=["Integer","Number"].includes(e[S])?"^(0|[1-9][0-9]*)$":e[S]==="String"&&e.pattern?e.pattern:"^.*$";return this.Create({...r,[S]:"Record",type:"object",patternProperties:{[s]:t},additionalProperties:!1})}Recursive(e,t={}){t.$id===void 0&&(t.$id=`T${Yt++}`);let r=e({[S]:"Self",$ref:`${t.$id}`});return r.$id=t.$id,this.Create({...t,...r})}Ref(e,t={}){if(e.$id===void 0)throw Error("TypeBuilder.Ref: Referenced schema must specify an $id");return this.Create({...t,[S]:"Ref",$ref:e.$id})}RegEx(e,t={}){return this.Create({...t,[S]:"String",type:"string",pattern:e.source})}Required(e,t={}){let r={...this.Clone(e),...t,[he]:"Required"};r.required=Object.keys(r.properties);for(let s of Object.keys(r.properties)){let n=r.properties[s];switch(n[H]){case"ReadonlyOptional":n[H]="Readonly";break;case"Readonly":n[H]="Readonly";break;case"Optional":delete n[H];break;default:delete n[H];break}}return this.Create(r)}ReturnType(e,t={}){return{...t,...this.Clone(e.returns)}}Strict(e){return JSON.parse(JSON.stringify(e))}String(e={}){return this.Create({...e,[S]:"String",type:"string"})}Tuple(e,t={}){let s=e.length,n=e.length,i=e.length>0?{...t,[S]:"Tuple",type:"array",items:e,additionalItems:!1,minItems:s,maxItems:n}:{...t,[S]:"Tuple",type:"array",minItems:s,maxItems:n};return this.Create(i)}Undefined(e={}){return this.Create({...e,[S]:"Undefined",type:"null",typeOf:"Undefined"})}Union(e,t={}){return e.length===0?N.Never({...t}):this.Create({...t,[S]:"Union",anyOf:e})}Uint8Array(e={}){return this.Create({...e,[S]:"Uint8Array",type:"object",instanceOf:"Uint8Array"})}Unknown(e={}){return this.Create({...e,[S]:"Unknown"})}Unsafe(e={}){return this.Create({...e,[S]:e[S]||"Unsafe"})}Void(e={}){return this.Create({...e,[S]:"Void",type:"null",typeOf:"Void"})}Create(e){return e}Clone(e){let t=s=>typeof s=="object"&&s!==null&&!Array.isArray(s),r=s=>typeof s=="object"&&s!==null&&Array.isArray(s);return t(e)?Object.keys(e).reduce((s,n)=>({...s,[n]:this.Clone(e[n])}),Object.getOwnPropertySymbols(e).reduce((s,n)=>({...s,[n]:this.Clone(e[n])}),{})):r(e)?e.map(s=>this.Clone(s)):e}},N=new ze;var j=class{constructor(e,t){Object.defineProperty(this,"index",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"fields",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.index=e,this.fields=t}},ee={Integer:function(a){let e=N.Unsafe({dataType:"integer"});return a&&Object.entries(a).forEach(([t,r])=>{e[t]=r}),e},Bytes:function(a){let e=N.Unsafe({dataType:"bytes"});return a&&Object.entries(a).forEach(([t,r])=>{e[t]=r}),e},Boolean:function(){return N.Unsafe({anyOf:[{title:"False",dataType:"constructor",index:0,fields:[]},{title:"True",dataType:"constructor",index:1,fields:[]}]})},Any:function(){return N.Unsafe({description:"Any Data."})},Array:function(a,e){let t=N.Array(a);return Se(t,{dataType:"list",items:a}),e&&Object.entries(e).forEach(([r,s])=>{t[r]=s}),t},Map:function(a,e,t){let r=N.Unsafe({dataType:"map",keys:a,values:e});return t&&Object.entries(t).forEach(([s,n])=>{r[s]=n}),r},Object:function(a,e){let t=N.Object(a);return Se(t,{anyOf:[{dataType:"constructor",index:0,fields:Object.entries(a).map(([r,s])=>({...s,title:r}))}]}),t.anyOf[0].hasConstr=typeof e?.hasConstr>"u"||e.hasConstr,t},Enum:function(a){let e=N.Union(a);return Se(e,{anyOf:a.map((t,r)=>t.anyOf[0].fields.length===0?{...t.anyOf[0],index:r}:{dataType:"constructor",title:(()=>{let s=t.anyOf[0].fields[0].title;if(s.charAt(0)!==s.charAt(0).toUpperCase())throw new Error(`Enum '${s}' needs to start with an uppercase letter.`);return t.anyOf[0].fields[0].title})(),index:r,fields:t.anyOf[0].fields[0].items||t.anyOf[0].fields[0].anyOf[0].fields})}),e},Tuple:function(a,e){let t=N.Tuple(a);return Se(t,{dataType:"list",items:a}),e&&Object.entries(e).forEach(([r,s])=>{t[r]=s}),t},Literal:function(a){if(a.charAt(0)!==a.charAt(0).toUpperCase())throw new Error(`Enum '${a}' needs to start with an uppercase letter.`);let e=N.Literal(a);return Se(e,{anyOf:[{dataType:"constructor",title:a,index:0,fields:[]}]}),e},Nullable:function(a){return N.Unsafe({anyOf:[{title:"Some",description:"An optional value.",dataType:"constructor",index:0,fields:[a]},{title:"None",description:"Nothing.",dataType:"constructor",index:1,fields:[]}]})},to:Zt,from:Qt,fromJson:er,toJson:tr,void:function(){return"d87980"},castFrom:M,castTo:z};function Zt(a,e){function t(s){try{if(typeof s=="bigint")return o.PlutusData.new_integer(o.BigInt.from_str(s.toString()));if(typeof s=="string")return o.PlutusData.new_bytes(d(s));if(s instanceof j){let{index:n,fields:i}=s,u=o.PlutusList.new();return i.forEach(c=>u.add(t(c))),o.PlutusData.new_constr_plutus_data(o.ConstrPlutusData.new(o.BigNum.from_str(n.toString()),u))}else if(s instanceof Array){let n=o.PlutusList.new();return s.forEach(i=>n.add(t(i))),o.PlutusData.new_list(n)}else if(s instanceof Map){let n=o.PlutusMap.new();for(let[i,u]of s.entries())n.insert(t(i),t(u));return o.PlutusData.new_map(n)}throw new Error("Unsupported type")}catch(n){throw new Error("Could not serialize the data: "+n)}}let r=e?z(a,e):a;return y(t(r).to_bytes())}function Qt(a,e){function t(s){if(s.kind()===0){let n=s.as_constr_plutus_data(),i=n.data(),u=[];for(let c=0;ce(r));if(t instanceof Object){let r=new Map;return Object.entries(t).forEach(([s,n])=>{r.set(e(s),e(n))}),r}throw new Error("Unsupported type")}return e(a)}function tr(a){function e(t){if(typeof t=="bigint"||typeof t=="number"||typeof t=="string"&&!isNaN(parseInt(t))&&t.slice(-1)==="n"){let r=typeof t=="string"?BigInt(t.slice(0,-1)):t;return parseInt(r.toString())}if(typeof t=="string")try{return new TextDecoder(void 0,{fatal:!0}).decode(d(t))}catch{return"0x"+y(d(t))}if(t instanceof Array)return t.map(r=>e(r));if(t instanceof Map){let r={};return t.forEach((s,n)=>{let i=e(n);if(typeof i!="string"&&typeof i!="number")throw new Error("Unsupported type (Note: Only bytes or integers can be keys of a JSON object)");r[i]=e(s)}),r}throw new Error("Unsupported type (Note: Constructor cannot be converted to JSON)")}return e(a)}function M(a,e){let t=e;if(!t)throw new Error("Could not type cast data.");switch((t.anyOf?"enum":"")||t.dataType){case"integer":{if(typeof a!="bigint")throw new Error("Could not type cast to integer.");return gt(a,t),a}case"bytes":{if(typeof a!="string")throw new Error("Could not type cast to bytes.");return yt(a,t),a}case"constructor":{if(_t(t)){if(!(a instanceof j)||a.index!==0||a.fields.length!==0)throw new Error("Could not type cast to void.");return}else if(a instanceof j&&a.index===t.index&&(t.hasConstr||t.hasConstr===void 0)){let s={};if(t.fields.length!==a.fields.length)throw new Error("Could not type cast to object. Fields do not match.");return t.fields.forEach((n,i)=>{let u=n.title||"wrapper";if(/[A-Z]/.test(u[0]))throw new Error("Could not type cast to object. Object properties need to start with a lowercase letter.");s[u]=M(a.fields[i],n)}),s}else if(a instanceof Array&&!t.hasConstr&&t.hasConstr!==void 0){let s={};if(t.fields.length!==a.length)throw new Error("Could not ype cast to object. Fields do not match.");return t.fields.forEach((n,i)=>{let u=n.title||"wrapper";if(/[A-Z]/.test(u[0]))throw new Error("Could not type cast to object. Object properties need to start with a lowercase letter.");s[u]=M(a[i],n)}),s}throw new Error("Could not type cast to object.")}case"enum":{if(t.anyOf.length===1)return M(a,t.anyOf[0]);if(!(a instanceof j))throw new Error("Could not type cast to enum.");let s=t.anyOf.find(n=>n.index===a.index);if(!s||s.fields.length!==a.fields.length)throw new Error("Could not type cast to enum.");if(bt(t)){if(a.fields.length!==0)throw new Error("Could not type cast to boolean.");switch(a.index){case 0:return!1;case 1:return!0}throw new Error("Could not type cast to boolean.")}else if(kt(t)){switch(a.index){case 0:{if(a.fields.length!==1)throw new Error("Could not type cast to nullable object.");return M(a.fields[0],t.anyOf[0].fields[0])}case 1:{if(a.fields.length!==0)throw new Error("Could not type cast to nullable object.");return null}}throw new Error("Could not type cast to nullable object.")}switch(s.dataType){case"constructor":if(s.fields.length===0){if(/[A-Z]/.test(s.title[0]))return s.title;throw new Error("Could not type cast to enum.")}else{if(!/[A-Z]/.test(s.title))throw new Error("Could not type cast to enum. Enums need to start with an uppercase letter.");if(s.fields.length!==a.fields.length)throw new Error("Could not type cast to enum.");let n=s.fields[0].title?Object.fromEntries(s.fields.map((i,u)=>[i.title,M(a.fields[u],i)])):s.fields.map((i,u)=>M(a.fields[u],i));return{[s.title]:n}}}throw new Error("Could not type cast to enum.")}case"list":if(t.items instanceof Array){if(a instanceof j&&a.index===0&&t.hasConstr)return a.fields.map((s,n)=>M(s,t.items[n]));if(a instanceof Array&&!t.hasConstr)return a.map((s,n)=>M(s,t.items[n]));throw new Error("Could not type cast to tuple.")}else{if(!(a instanceof Array))throw new Error("Could not type cast to array.");return xt(a,t),a.map(s=>M(s,t.items))}case"map":{if(!(a instanceof Map))throw new Error("Could not type cast to map.");wt(a,t);let s=new Map;for(let[n,i]of a.entries())s.set(M(n,t.keys),M(i,t.values));return s}case void 0:return a}throw new Error("Could not type cast data.")}function z(a,e){let t=e;if(!t)throw new Error("Could not type cast struct.");switch((t.anyOf?"enum":"")||t.dataType){case"integer":{if(typeof a!="bigint")throw new Error("Could not type cast to integer.");return gt(a,t),a}case"bytes":{if(typeof a!="string")throw new Error("Could not type cast to bytes.");return yt(a,t),a}case"constructor":{if(_t(t)){if(a!==void 0)throw new Error("Could not type cast to void.");return new j(0,[])}else if(typeof a!="object"||a===null||t.fields.length!==Object.keys(a).length)throw new Error("Could not type cast to constructor.");let s=t.fields.map(n=>z(a[n.title||"wrapper"],n));return t.hasConstr||t.hasConstr===void 0?new j(t.index,s):s}case"enum":{if(t.anyOf.length===1)return z(a,t.anyOf[0]);if(bt(t)){if(typeof a!="boolean")throw new Error("Could not type cast to boolean.");return new j(a?1:0,[])}else if(kt(t)){if(a===null)return new j(1,[]);{let s=t.anyOf[0].fields;if(s.length!==1)throw new Error("Could not type cast to nullable object.");return new j(0,[z(a,s[0])])}}switch(typeof a){case"string":{if(!/[A-Z]/.test(a[0]))throw new Error("Could not type cast to enum. Enum needs to start with an uppercase letter.");let s=t.anyOf.findIndex(n=>n.dataType==="constructor"&&n.fields.length===0&&n.title===a);if(s===-1)throw new Error("Could not type cast to enum.");return new j(s,[])}case"object":{if(a===null)throw new Error("Could not type cast to enum.");let s=Object.keys(a)[0];if(!/[A-Z]/.test(s))throw new Error("Could not type cast to enum. Enum needs to start with an uppercase letter.");let n=t.anyOf.find(u=>u.dataType==="constructor"&&u.title===s);if(!n)throw new Error("Could not type cast to enum.");let i=a[s];return new j(n.index,i instanceof Array?i.map((u,c)=>z(u,n.fields[c])):n.fields.map(u=>{let[c,m]=Object.entries(i).find(([p])=>p===u.title);return z(m,u)}))}}throw new Error("Could not type cast to enum.")}case"list":{if(!(a instanceof Array))throw new Error("Could not type cast to array/tuple.");if(t.items instanceof Array){let s=a.map((n,i)=>z(n,t.items[i]));return t.hasConstr?new j(0,s):s}else return xt(a,t),a.map(s=>z(s,t.items))}case"map":{if(!(a instanceof Map))throw new Error("Could not type cast to map.");wt(a,t);let s=new Map;for(let[n,i]of a.entries())s.set(z(n,t.keys),z(i,t.values));return s}case void 0:return a}throw new Error("Could not type cast struct.")}function gt(a,e){if(e.minimum&&aBigInt(e.maximum))throw new Error(`Integer ${a} is above the maxiumum ${e.maximum}.`);if(e.exclusiveMinimum&&a<=BigInt(e.exclusiveMinimum))throw new Error(`Integer ${a} is below the exclusive minimum ${e.exclusiveMinimum}.`);if(e.exclusiveMaximum&&a>=BigInt(e.exclusiveMaximum))throw new Error(`Integer ${a} is above the exclusive maximum ${e.exclusiveMaximum}.`)}function yt(a,e){if(e.enum&&!e.enum.some(t=>t===a))throw new Error(`None of the keywords match with '${a}'.`);if(e.minLength&&a.length/2e.maxLength)throw new Error(`Bytes can have a length of at most ${e.minLength} bytes.`)}function xt(a,e){if(e.minItems&&a.lengthe.maxItems)throw new Error(`Array can contain at most ${e.maxItems} items.`);if(e.uniqueItems&&new Set(a).size!==a.length)throw new Error("Array constains duplicates.")}function wt(a,e){if(e.minItems&&a.sizee.maxItems)throw new Error(`Map can contain at most ${e.maxItems} items.`)}function bt(a){return a.anyOf&&a.anyOf[0]?.title==="False"&&a.anyOf[1]?.title==="True"}function _t(a){return a.index===0&&a.fields.length===0}function kt(a){return a.anyOf&&a.anyOf[0]?.title==="Some"&&a.anyOf[1]?.title==="None"}function Se(a,e){Object.keys(a).forEach(t=>{delete a[t]}),Object.assign(a,e)}var Pe=class{constructor(e){Object.defineProperty(this,"lucid",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.lucid=e}validatorToAddress(e,t){let r=this.validatorToScriptHash(e);return t?o.BaseAddress.new(oe(this.lucid.network),o.StakeCredential.from_scripthash(o.ScriptHash.from_hex(r)),t.type==="Key"?o.StakeCredential.from_keyhash(o.Ed25519KeyHash.from_hex(t.hash)):o.StakeCredential.from_scripthash(o.ScriptHash.from_hex(t.hash))).to_address().to_bech32(void 0):o.EnterpriseAddress.new(oe(this.lucid.network),o.StakeCredential.from_scripthash(o.ScriptHash.from_hex(r))).to_address().to_bech32(void 0)}credentialToAddress(e,t){return t?o.BaseAddress.new(oe(this.lucid.network),e.type==="Key"?o.StakeCredential.from_keyhash(o.Ed25519KeyHash.from_hex(e.hash)):o.StakeCredential.from_scripthash(o.ScriptHash.from_hex(e.hash)),t.type==="Key"?o.StakeCredential.from_keyhash(o.Ed25519KeyHash.from_hex(t.hash)):o.StakeCredential.from_scripthash(o.ScriptHash.from_hex(t.hash))).to_address().to_bech32(void 0):o.EnterpriseAddress.new(oe(this.lucid.network),e.type==="Key"?o.StakeCredential.from_keyhash(o.Ed25519KeyHash.from_hex(e.hash)):o.StakeCredential.from_scripthash(o.ScriptHash.from_hex(e.hash))).to_address().to_bech32(void 0)}validatorToRewardAddress(e){let t=this.validatorToScriptHash(e);return o.RewardAddress.new(oe(this.lucid.network),o.StakeCredential.from_scripthash(o.ScriptHash.from_hex(t))).to_address().to_bech32(void 0)}credentialToRewardAddress(e){return o.RewardAddress.new(oe(this.lucid.network),e.type==="Key"?o.StakeCredential.from_keyhash(o.Ed25519KeyHash.from_hex(e.hash)):o.StakeCredential.from_scripthash(o.ScriptHash.from_hex(e.hash))).to_address().to_bech32(void 0)}validatorToScriptHash(e){switch(e.type){case"Native":return o.NativeScript.from_bytes(d(e.script)).hash(o.ScriptHashNamespace.NativeScript).to_hex();case"PlutusV1":return o.PlutusScript.from_bytes(d(q(e.script))).hash(o.ScriptHashNamespace.PlutusV1).to_hex();case"PlutusV2":return o.PlutusScript.from_bytes(d(q(e.script))).hash(o.ScriptHashNamespace.PlutusV2).to_hex();default:throw new Error("No variant matched")}}mintingPolicyToId(e){return this.validatorToScriptHash(e)}datumToHash(e){return o.hash_plutus_data(o.PlutusData.from_bytes(d(e))).to_hex()}scriptHashToCredential(e){return{type:"Script",hash:e}}keyHashToCredential(e){return{type:"Key",hash:e}}generatePrivateKey(){return sr()}generateSeedPhrase(){return nr()}unixTimeToSlot(e){return ft(e,be[this.lucid.network])}slotToUnixTime(e){return pt(e,be[this.lucid.network])}getAddressDetails(e){return D(e)}nativeScriptFromJson(e){return ur(e)}paymentCredentialOf(e){return ie(e)}stakeCredentialOf(e){return rr(e)}getMinAdaForOutput(e){let t=o.min_ada_required(e,o.BigNum.from_str(this.lucid.protocolParameters.coinsPerUtxoByte.toString()));return BigInt(t.to_str()).valueOf()}};function Te(a){try{return o.Address.from_bytes(d(a))}catch{try{return o.Address.from_bech32(a)}catch{throw new Error("Could not deserialize address.")}}}function D(a){try{let e=o.BaseAddress.from_address(Te(a)),t=e.payment_cred().kind()===0?{type:"Key",hash:y(e.payment_cred().to_keyhash().to_bytes())}:{type:"Script",hash:y(e.payment_cred().to_scripthash().to_bytes())},r=e.stake_cred().kind()===0?{type:"Key",hash:y(e.stake_cred().to_keyhash().to_bytes())}:{type:"Script",hash:y(e.stake_cred().to_scripthash().to_bytes())};return{type:"Base",networkId:e.to_address().network_id(),address:{bech32:e.to_address().to_bech32(void 0),hex:y(e.to_address().to_bytes())},paymentCredential:t,stakeCredential:r}}catch{}try{let e=o.EnterpriseAddress.from_address(Te(a)),t=e.payment_cred().kind()===0?{type:"Key",hash:y(e.payment_cred().to_keyhash().to_bytes())}:{type:"Script",hash:y(e.payment_cred().to_scripthash().to_bytes())};return{type:"Enterprise",networkId:e.to_address().network_id(),address:{bech32:e.to_address().to_bech32(void 0),hex:y(e.to_address().to_bytes())},paymentCredential:t}}catch{}try{let e=o.PointerAddress.from_address(Te(a)),t=e.payment_cred().kind()===0?{type:"Key",hash:y(e.payment_cred().to_keyhash().to_bytes())}:{type:"Script",hash:y(e.payment_cred().to_scripthash().to_bytes())};return{type:"Pointer",networkId:e.to_address().network_id(),address:{bech32:e.to_address().to_bech32(void 0),hex:y(e.to_address().to_bytes())},paymentCredential:t}}catch{}try{let e=o.RewardAddress.from_address(Te(a)),t=e.payment_cred().kind()===0?{type:"Key",hash:y(e.payment_cred().to_keyhash().to_bytes())}:{type:"Script",hash:y(e.payment_cred().to_scripthash().to_bytes())};return{type:"Reward",networkId:e.to_address().network_id(),address:{bech32:e.to_address().to_bech32(void 0),hex:y(e.to_address().to_bytes())},stakeCredential:t}}catch{}try{let e=(t=>{try{return o.ByronAddress.from_bytes(d(t))}catch{try{return o.ByronAddress.from_base58(t)}catch{throw new Error("Could not deserialize address.")}}})(a);return{type:"Byron",networkId:e.network_id(),address:{bech32:"",hex:y(e.to_address().to_bytes())}}}catch{}throw new Error("No address type matched for: "+a)}function ie(a){let{paymentCredential:e}=D(a);if(!e)throw new Error("The specified address does not contain a payment credential.");return e}function rr(a){let{stakeCredential:e}=D(a);if(!e)throw new Error("The specified address does not contain a stake credential.");return e}function sr(){return o.PrivateKey.generate_ed25519().to_bech32()}function nr(){return it(256)}function We(a){let e={};e.lovelace=BigInt(a.coin().to_str());let t=a.multiasset();if(t){let r=t.keys();for(let s=0;si!=="lovelace").map(i=>i.slice(0,56)))).forEach(i=>{let u=r.filter(m=>m.slice(0,56)===i),c=o.Assets.new();u.forEach(m=>{c.insert(o.AssetName.new(d(m.slice(56))),o.BigNum.from_str(a[m].toString()))}),e.insert(o.ScriptHash.from_bytes(d(i)),c)});let n=o.Value.new(o.BigNum.from_str(t?t.toString():"0"));return(r.length>1||!t)&&n.set_multiasset(e),n}function ar(a){switch(a.get().kind()){case 0:return{type:"Native",script:y(a.get().as_native().to_bytes())};case 1:return{type:"PlutusV1",script:y(a.get().as_plutus_v1().to_bytes())};case 2:return{type:"PlutusV2",script:y(a.get().as_plutus_v2().to_bytes())};default:throw new Error("No variant matched.")}}function Ve(a){switch(a.type){case"Native":return o.ScriptRef.new(o.Script.new_native(o.NativeScript.from_bytes(d(a.script))));case"PlutusV1":return o.ScriptRef.new(o.Script.new_plutus_v1(o.PlutusScript.from_bytes(d(q(a.script)))));case"PlutusV2":return o.ScriptRef.new(o.Script.new_plutus_v2(o.PlutusScript.from_bytes(d(q(a.script)))));default:throw new Error("No variant matched.")}}function ue(a){let e=(()=>{try{return o.Address.from_bech32(a.address)}catch{return o.ByronAddress.from_base58(a.address).to_address()}})(),t=o.TransactionOutput.new(e,me(a.assets));return a.datumHash&&t.set_datum(o.Datum.new_data_hash(o.DataHash.from_bytes(d(a.datumHash)))),!a.datumHash&&a.datum&&t.set_datum(o.Datum.new_data(o.Data.new(o.PlutusData.from_bytes(d(a.datum))))),a.scriptRef&&t.set_script_ref(Ve(a.scriptRef)),o.TransactionUnspentOutput.new(o.TransactionInput.new(o.TransactionHash.from_bytes(d(a.txHash)),o.BigNum.from_str(a.outputIndex.toString())),t)}function Oe(a){let e=a.output()?.datum()?.as_data()?.get(),t=a.output()?.datum()?.as_data_hash()?.to_hex();return{txHash:y(a.input().transaction_id().to_bytes()),outputIndex:parseInt(a.input().index().to_str()),assets:We(a.output().amount()),address:a.output().address().as_byron()?a.output().address().as_byron()?.to_base58():a.output().address().to_bech32(void 0),datumHash:e?o.hash_plutus_data(e).to_hex():t,datum:e&&y(e.to_bytes()),scriptRef:a.output()?.script_ref()&&ar(a.output().script_ref())}}function oe(a){switch(a){case"Preview":return 0;case"Preprod":return 0;case"Custom":return 0;case"Mainnet":return 1;default:throw new Error("Network not found")}}function d(a){return st(a)}function y(a){return rt(a)}function Dr(a){return new TextDecoder().decode(Ke(new TextEncoder().encode(a)))}function vt(a){return y(new TextEncoder().encode(a))}function Mr(a){return o.PrivateKey.from_bech32(a).to_public().to_bech32()}function St(a){return mt(d(a)).toString(16).padStart(2,"0")}function or(a){if(a<0||a>65535)throw new Error(`Label ${a} out of range: min label 1 - max label 65535.`);let e=a.toString(16).padStart(4,"0");return"0"+e+St(e)+"0"}function ir(a){if(a.length!==8||!(a[0]==="0"&&a[7]==="0"))return null;let e=a.slice(1,5),t=parseInt(e,16);return a.slice(5,7)===St(e)?t:null}function Ct(a,e,t){let r=Number.isInteger(t)?or(t):"",s=e||"";if((s+r).length>64)throw new Error("Asset name size exceeds 32 bytes.");if(a.length!==56)throw new Error(`Policy id invalid: ${a}.`);return a+r+s}function Ce(a){let e=a.slice(0,56),t=a.slice(56)||null,r=ir(a.slice(56,64)),s=(()=>(Number.isInteger(r)?a.slice(64):a.slice(56))||null)();return{policyId:e,assetName:t,name:s,label:r}}function ur(a){return{type:"Native",script:y(o.encode_json_str_to_native_script(JSON.stringify(a),"",o.ScriptSchema.Node).to_bytes())}}function Rr(a,e,t){let r=t?ee.castTo(e,t):e;return y(o.apply_params_to_plutus_script(o.PlutusList.from_bytes(d(ee.to(r))),o.PlutusScript.from_bytes(d(q(a)))).to_bytes())}var It=(a,e)=>{let t=[],r=a.length,s=0;for(;s{for(let r in t)Object.hasOwn(t,r)&&(e[r]=(e[r]||0n)+t[r]);return e},{})}function cr(a,e){if(a.length!==e.length)return!1;for(let t=0;tUe(t)))}static fromHashes(e){return new this(e)}static buildRecursively(e){if(e.length<=0)return null;if(e.length===1)return{node:e[0],left:null,right:null};let t=Math.floor(e.length/2),[r,s]=[e.slice(0,t),e.slice(t)],n=this.buildRecursively(r),i=this.buildRecursively(s);return n===null||i===null?null:{node:Fe(n.node,i.node),left:n,right:i}}rootHash(){if(this.root===null)throw new Error("Merkle tree root hash not found.");return this.root.node}getProof(e){let t=Ue(e),r=[],s=n=>{if(n&&Ae(n.node,t))return!0;if(n?.right&&s(n.left))return r.push({right:n.right.node}),!0;if(n?.left&&s(n.right))return r.push({left:n.left.node}),!0};return s(this.root),r}size(){let e=t=>t===null?0:1+e(t.left)+e(t.right);return e(this.root)}static verify(e,t,r){let s=Ue(e),n=(i,u)=>{if(u.length<=0)return Ae(t,i);let[c,m]=[u[0],u.slice(1)];return c.left?n(Fe(c.left,i),m):c.right?n(Fe(i,c.right),m):!1};return n(s,r)}toString(){let e=t=>t===null?null:{node:y(t.node),left:e(t.left),right:e(t.right)};return JSON.stringify(e(this.root),null,2)}};function Ue(a){return new Uint8Array(new we().update(a).arrayBuffer())}function Fe(a,e){return Ue(Et(a,e))}var Bt={enableChangeSplitting:!0,changeCollateral:"5000000",changeMinUtxo:"100000000",changeNativeAssetChunkSize:20};var je=class{constructor(e,t){Object.defineProperty(this,"txSigned",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"lucid",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.lucid=e,this.txSigned=t}async submit(){return await(this.lucid.wallet||this.lucid.provider).submitTx(y(this.txSigned.to_bytes()))}toString(){return y(this.txSigned.to_bytes())}toHash(){return o.hash_transaction(this.txSigned.body()).to_hex()}};var _e=class{constructor(e,t){Object.defineProperty(this,"txComplete",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"witnessSetBuilder",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"tasks",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"lucid",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"fee",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"exUnits",{enumerable:!0,configurable:!0,writable:!0,value:null}),this.lucid=e,this.txComplete=t,this.witnessSetBuilder=o.TransactionWitnessSetBuilder.new(),this.tasks=[],this.fee=parseInt(t.body().fee().to_str());let r=t.witness_set().redeemers();if(r){let s={cpu:0,mem:0};for(let n=0;n{let e=await this.lucid.wallet.signTx(this.txComplete);this.witnessSetBuilder.add_existing(e)}),this}signWithPrivateKey(e){let t=o.PrivateKey.from_bech32(e),r=o.make_vkey_witness(o.hash_transaction(this.txComplete.body()),t);return this.witnessSetBuilder.add_vkey(r),this}async partialSign(){let e=await this.lucid.wallet.signTx(this.txComplete);return this.witnessSetBuilder.add_existing(e),y(e.to_bytes())}partialSignWithPrivateKey(e){let t=o.PrivateKey.from_bech32(e),r=o.make_vkey_witness(o.hash_transaction(this.txComplete.body()),t);this.witnessSetBuilder.add_vkey(r);let s=o.TransactionWitnessSetBuilder.new();return s.add_vkey(r),y(s.build().to_bytes())}assemble(e){return e.forEach(t=>{let r=o.TransactionWitnessSet.from_bytes(d(t));this.witnessSetBuilder.add_existing(r)}),this}async complete(){for(let t of this.tasks)await t();this.witnessSetBuilder.add_existing(this.txComplete.witness_set());let e=o.Transaction.new(this.txComplete.body(),this.witnessSetBuilder.build(),this.txComplete.auxiliary_data());return new je(this.lucid,e)}toString(){return y(this.txComplete.to_bytes())}toHash(){return o.hash_transaction(this.txComplete.body()).to_hex()}};var De=class{constructor(e){Object.defineProperty(this,"txBuilder",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"tasks",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"lucid",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"configuration",{enumerable:!0,configurable:!0,writable:!0,value:Bt}),this.lucid=e,this.txBuilder=o.TransactionBuilder.new(this.lucid.txBuilderConfig),this.tasks=[]}readFrom(e){return this.tasks.push(async t=>{for(let r of e){if(r.datumHash){r.datum=ee.to(await t.lucid.datumOf(r));let n=o.PlutusData.from_bytes(d(r.datum));t.txBuilder.add_plutus_data(n)}let s=ue(r);t.txBuilder.add_reference_input(s)}}),this}config(e){return this.configuration={...this.configuration,...e},this}collectFrom(e,t){return this.tasks.push(async r=>{for(let s of e){s.datumHash&&!s.datum&&(s.datum=ee.to(await r.lucid.datumOf(s)));let n=ue(s);r.txBuilder.add_input(n,t&&o.ScriptWitness.new_plutus_witness(o.PlutusWitness.new(o.PlutusData.from_bytes(d(t)),s.datumHash&&s.datum?o.PlutusData.from_bytes(d(s.datum)):void 0,void 0)))}}),this}mintAssets(e,t){return this.tasks.push(r=>{let s=Object.keys(e),n=s[0].slice(0,56),i=o.MintAssets.new();s.forEach(c=>{if(c.slice(0,56)!==n)throw new Error("Only one policy id allowed. You can chain multiple mintAssets functions together if you need to mint assets with different policy ids.");i.insert(o.AssetName.new(d(c.slice(56))),o.Int.from_str(e[c].toString()))});let u=o.ScriptHash.from_bytes(d(n));r.txBuilder.add_mint(u,i,t?o.ScriptWitness.new_plutus_witness(o.PlutusWitness.new(o.PlutusData.from_bytes(d(t)),void 0,void 0)):void 0)}),this}payToAddress(e,t){return this.tasks.push(r=>{let s=o.TransactionOutput.new(ke(e,r.lucid),me(t)),n=r.lucid.utils.getMinAdaForOutput(s);t.lovelace=t.lovelace>n?t.lovelace:n,s=o.TransactionOutput.new(ke(e,r.lucid),me(t)),r.txBuilder.add_output(s)}),this}payToAddressWithData(e,t,r){return this.tasks.push(s=>{if(typeof t=="string"&&(t={asHash:t}),[t.hash,t.asHash,t.inline].filter(c=>c).length>1)throw new Error("Not allowed to set hash, asHash and inline at the same time.");let n=(c,m)=>{let p=o.TransactionOutput.new(ke(e,s.lucid),me(c));if(m.hash)p.set_datum(o.Datum.new_data_hash(o.DataHash.from_hex(m.hash)));else if(m.asHash){let E=o.PlutusData.from_bytes(d(m.asHash));p.set_datum(o.Datum.new_data_hash(o.hash_plutus_data(E))),s.txBuilder.add_plutus_data(E)}else if(m.inline){let E=o.PlutusData.from_bytes(d(m.inline));p.set_datum(o.Datum.new_data(o.Data.new(E)))}let C=m.scriptRef;return C&&p.set_script_ref(Ve(C)),p},i=n(r,t),u=this.lucid.utils.getMinAdaForOutput(i);r.lovelace=r.lovelace>u?r.lovelace:u,i=n(r,t),s.txBuilder.add_output(i)}),this}payToContract(e,t,r){if(typeof t=="string"&&(t={asHash:t}),!(t.hash||t.asHash||t.inline))throw new Error("No datum set. Script output becomes unspendable without datum.");return this.payToAddressWithData(e,t,r)}delegateTo(e,t,r){return this.tasks.push(s=>{let n=s.lucid.utils.getAddressDetails(e);if(n.type!=="Reward"||!n.stakeCredential)throw new Error("Not a reward address provided.");let i=n.stakeCredential.type==="Key"?o.StakeCredential.from_keyhash(o.Ed25519KeyHash.from_bytes(d(n.stakeCredential.hash))):o.StakeCredential.from_scripthash(o.ScriptHash.from_bytes(d(n.stakeCredential.hash)));s.txBuilder.add_certificate(o.Certificate.new_stake_delegation(o.StakeDelegation.new(i,o.Ed25519KeyHash.from_bech32(t))),r?o.ScriptWitness.new_plutus_witness(o.PlutusWitness.new(o.PlutusData.from_bytes(d(r)),void 0,void 0)):void 0)}),this}registerStake(e){return this.tasks.push(t=>{let r=t.lucid.utils.getAddressDetails(e);if(r.type!=="Reward"||!r.stakeCredential)throw new Error("Not a reward address provided.");let s=r.stakeCredential.type==="Key"?o.StakeCredential.from_keyhash(o.Ed25519KeyHash.from_bytes(d(r.stakeCredential.hash))):o.StakeCredential.from_scripthash(o.ScriptHash.from_bytes(d(r.stakeCredential.hash)));t.txBuilder.add_certificate(o.Certificate.new_stake_registration(o.StakeRegistration.new(s)),void 0)}),this}deregisterStake(e,t){return this.tasks.push(r=>{let s=r.lucid.utils.getAddressDetails(e);if(s.type!=="Reward"||!s.stakeCredential)throw new Error("Not a reward address provided.");let n=s.stakeCredential.type==="Key"?o.StakeCredential.from_keyhash(o.Ed25519KeyHash.from_bytes(d(s.stakeCredential.hash))):o.StakeCredential.from_scripthash(o.ScriptHash.from_bytes(d(s.stakeCredential.hash)));r.txBuilder.add_certificate(o.Certificate.new_stake_deregistration(o.StakeDeregistration.new(n)),t?o.ScriptWitness.new_plutus_witness(o.PlutusWitness.new(o.PlutusData.from_bytes(d(t)),void 0,void 0)):void 0)}),this}registerPool(e){return this.tasks.push(async t=>{let r=await Tt(e,t.lucid),s=o.Certificate.new_pool_registration(r);t.txBuilder.add_certificate(s,void 0)}),this}updatePool(e){return this.tasks.push(async t=>{let r=await Tt(e,t.lucid);r.set_is_update(!0);let s=o.Certificate.new_pool_registration(r);t.txBuilder.add_certificate(s,void 0)}),this}retirePool(e,t){return this.tasks.push(r=>{let s=o.Certificate.new_pool_retirement(o.PoolRetirement.new(o.Ed25519KeyHash.from_bech32(e),t));r.txBuilder.add_certificate(s,void 0)}),this}withdraw(e,t,r){return this.tasks.push(s=>{s.txBuilder.add_withdrawal(o.RewardAddress.from_address(ke(e,s.lucid)),o.BigNum.from_str(t.toString()),r?o.ScriptWitness.new_plutus_witness(o.PlutusWitness.new(o.PlutusData.from_bytes(d(r)),void 0,void 0)):void 0)}),this}addSigner(e){let t=this.lucid.utils.getAddressDetails(e);if(!t.paymentCredential&&!t.stakeCredential)throw new Error("Not a valid address.");let r=t.type==="Reward"?t.stakeCredential:t.paymentCredential;if(r.type==="Script")throw new Error("Only key hashes are allowed as signers.");return this.addSignerKey(r.hash)}addSignerKey(e){return this.tasks.push(t=>{t.txBuilder.add_required_signer(o.Ed25519KeyHash.from_bytes(d(e)))}),this}validFrom(e){return this.tasks.push(t=>{let r=t.lucid.utils.unixTimeToSlot(e);t.txBuilder.set_validity_start_interval(o.BigNum.from_str(r.toString()))}),this}validTo(e){return this.tasks.push(t=>{let r=t.lucid.utils.unixTimeToSlot(e);t.txBuilder.set_ttl(o.BigNum.from_str(r.toString()))}),this}attachMetadata(e,t){return this.tasks.push(r=>{r.txBuilder.add_json_metadatum(o.BigNum.from_str(e.toString()),JSON.stringify(t))}),this}attachMetadataWithConversion(e,t){return this.tasks.push(r=>{r.txBuilder.add_json_metadatum_with_schema(o.BigNum.from_str(e.toString()),JSON.stringify(t),o.MetadataJsonSchema.BasicConversions)}),this}addNetworkId(e){return this.tasks.push(t=>{t.txBuilder.set_network_id(o.NetworkId.from_bytes(d(e.toString(16).padStart(2,"0"))))}),this}attachSpendingValidator(e){return this.tasks.push(t=>{Ne(t,e)}),this}attachMintingPolicy(e){return this.tasks.push(t=>{Ne(t,e)}),this}attachCertificateValidator(e){return this.tasks.push(t=>{Ne(t,e)}),this}attachWithdrawalValidator(e){return this.tasks.push(t=>{Ne(t,e)}),this}applyIf(e,t){return e&&this.tasks.push(r=>t(r)),this}apply(e){return this.tasks.push(t=>e(t)),this}compose(e){return e&&(this.tasks=this.tasks.concat(e.tasks)),this}async complete(e){let{enableChangeSplitting:t}=this.configuration;if([e?.change?.outputData?.hash,e?.change?.outputData?.asHash,e?.change?.outputData?.inline].filter(u=>u).length>1)throw new Error("Not allowed to set hash, asHash and inline at the same time.");let r=this.tasks.shift();for(;r;)await r(this),r=this.tasks.shift();let s=await this.lucid.wallet.getUtxosCore(),n=await this.lucid.wallet.getCollateralCore(),i=ke(e?.change?.address||await this.lucid.wallet.address(),this.lucid);return(e?.coinSelection||e?.coinSelection===void 0)&&this.txBuilder.add_inputs_from(s,i,Uint32Array.from([200,1e3,1500,800,800,5e3])),t&&await this.splitChange(),this.txBuilder.balance(i,(()=>e?.change?.outputData?.hash?o.Datum.new_data_hash(o.DataHash.from_hex(e.change.outputData.hash)):e?.change?.outputData?.asHash?(this.txBuilder.add_plutus_data(o.PlutusData.from_bytes(d(e.change.outputData.asHash))),o.Datum.new_data_hash(o.hash_plutus_data(o.PlutusData.from_bytes(d(e.change.outputData.asHash))))):e?.change?.outputData?.inline?o.Datum.new_data(o.Data.new(o.PlutusData.from_bytes(d(e.change.outputData.inline)))):void 0)()),new _e(this.lucid,await this.txBuilder.construct(n||s,i,e?.nativeUplc===void 0?!0:e?.nativeUplc))}async toString(){let e=this.tasks.shift();for(;e;)await e(this),e=this.tasks.shift();return y(this.txBuilder.to_bytes())}async splitChange(){let{coinsPerUtxoByte:e}=await this.lucid.protocolParameters,{changeNativeAssetChunkSize:t,changeMinUtxo:r}=this.configuration,s=this.txBuilder.get_explicit_input().checked_sub(this.txBuilder.get_explicit_output()),n=s.coin(),i=We(s),u=Object.keys(i).filter(h=>h!=="lovelace").sort((h,_)=>h.localeCompare(_));i=u.reduce((h,_)=>Object.assign(h,{[_]:i[_]}),{});let c=Math.ceil(u.length/t),m=o.Address.from_bech32(await this.lucid.wallet.address()),p=this.txBuilder.outputs();for(let h=0;hm.to_bech32(void 0).length)&&(m=_.address())}let E=o.min_ada_required(o.TransactionOutput.new(m,me(i)),o.BigNum.from_str(e.toString())).checked_mul(o.BigNum.from_str(c.toString())).compare(n)<0;if(s.multiasset()&&E){let h=It(u,20),_=h.length;for(let[I,w]of h.entries()){if(I===_-1)continue;let O=me(w.reduce((pe,te)=>Object.assign(pe,{[te]:i[te]}),{})),B=o.min_ada_required(o.TransactionOutput.new(o.Address.from_bech32(await this.lucid.wallet.address()),O),o.BigNum.from_str(e.toString()));O.set_coin(B),n=n.checked_sub(B),this.txBuilder.add_output(o.TransactionOutput.new(o.Address.from_bech32(await this.lucid.wallet.address()),O))}}for(;n.checked_div(o.BigNum.from_str("2")).compare(o.BigNum.from_str(r))>=0;){let h=n.checked_div(o.BigNum.from_str("2"));n=n.checked_sub(h),this.txBuilder.add_output(o.TransactionOutput.new(o.Address.from_bech32(await this.lucid.wallet.address()),o.Value.new(h)))}}};function Ne(a,{type:e,script:t}){if(e==="Native")return a.txBuilder.add_native_script(o.NativeScript.from_bytes(d(t)));if(e==="PlutusV1")return a.txBuilder.add_plutus_script(o.PlutusScript.from_bytes(d(q(t))));if(e==="PlutusV2")return a.txBuilder.add_plutus_v2_script(o.PlutusScript.from_bytes(d(q(t))));throw new Error("No variant matched.")}async function Tt(a,e){let t=o.Ed25519KeyHashes.new();a.owners.forEach(i=>{let{stakeCredential:u}=e.utils.getAddressDetails(i);if(u?.type==="Key")t.add(o.Ed25519KeyHash.from_hex(u.hash));else throw new Error("Only key hashes allowed for pool owners.")});let r=a.metadataUrl?await fetch(a.metadataUrl).then(i=>i.arrayBuffer()):null,s=r?o.PoolMetadataHash.from_bytes(o.hash_blake2b256(new Uint8Array(r))):null,n=o.Relays.new();return a.relays.forEach(i=>{switch(i.type){case"SingleHostIp":{let u=i.ipV4?o.Ipv4.new(new Uint8Array(i.ipV4.split(".").map(m=>parseInt(m)))):void 0,c=i.ipV6?o.Ipv6.new(d(i.ipV6.replaceAll(":",""))):void 0;n.add(o.Relay.new_single_host_addr(o.SingleHostAddr.new(i.port,u,c)));break}case"SingleHostDomainName":{n.add(o.Relay.new_single_host_name(o.SingleHostName.new(i.port,o.DNSRecordAorAAAA.new(i.domainName))));break}case"MultiHost":{n.add(o.Relay.new_multi_host_name(o.MultiHostName.new(o.DNSRecordSRV.new(i.domainName))));break}}}),o.PoolRegistration.new(o.PoolParams.new(o.Ed25519KeyHash.from_bech32(a.poolId),o.VRFKeyHash.from_hex(a.vrfKeyHash),o.BigNum.from_str(a.pledge.toString()),o.BigNum.from_str(a.cost.toString()),o.UnitInterval.from_float(a.margin),o.RewardAddress.from_address(ke(a.rewardAddress,e)),t,n,s?o.PoolMetadata.new(o.Url.new(a.metadataUrl),s):void 0))}function ke(a,e){let{type:t,networkId:r}=e.utils.getAddressDetails(a),s=oe(e.network);if(r!==s)throw new Error(`Invalid address: Expected address with network id ${s}, but got ${r}`);return t==="Byron"?o.ByronAddress.from_base58(a).to_address():o.Address.from_bech32(a)}function Pt(a,e={addressType:"Base",accountIndex:0,network:"Mainnet"}){function t(h){if(typeof h!="number")throw new Error("Type number required here!");return 2147483648+h}let r=ot(a),n=o.Bip32PrivateKey.from_bip39_entropy(d(r),e.password?new TextEncoder().encode(e.password):new Uint8Array).derive(t(1852)).derive(t(1815)).derive(t(e.accountIndex)),i=n.derive(0).derive(0).to_raw_key(),u=n.derive(2).derive(0).to_raw_key(),c=i.to_public().hash(),m=u.to_public().hash(),p=e.network==="Mainnet"?1:0,C=e.addressType==="Base"?o.BaseAddress.new(p,o.StakeCredential.from_keyhash(c),o.StakeCredential.from_keyhash(m)).to_address().to_bech32(void 0):o.EnterpriseAddress.new(p,o.StakeCredential.from_keyhash(c)).to_address().to_bech32(void 0),E=e.addressType==="Base"?o.RewardAddress.new(p,o.StakeCredential.from_keyhash(m)).to_address().to_bech32(void 0):null;return{address:C,rewardAddress:E,paymentKey:i.to_bech32(),stakeKey:e.addressType==="Base"?u.to_bech32():null}}function Ot(a,e,t){let r=[],s=a.body().inputs();for(let h=0;hO.txHash===I&&O.outputIndex===w);if(A){let{paymentCredential:O}=D(A.address);r.push(O?.hash)}}let n=a.body();function i(h){let _=h.certs();if(_)for(let I=0;I<_.len();I++){let w=_.get(I);if(w.kind()===0)w.as_stake_registration()?.stake_credential()?.kind();else if(w.kind()===1){let A=w.as_stake_deregistration()?.stake_credential();if(A?.kind()===0){let O=y(A.to_keyhash().to_bytes());r.push(O)}}else if(w.kind()===2){let A=w.as_stake_delegation()?.stake_credential();if(A?.kind()===0){let O=y(A.to_keyhash().to_bytes());r.push(O)}}else if(w.kind()===3){let A=w.as_pool_registration()?.pool_params(),O=A?.pool_owners();if(!O)break;for(let B=0;BO.txHash===I&&O.outputIndex===w);if(A){let{paymentCredential:O}=D(A.address);r.push(O?.hash)}}return r.filter(h=>e.includes(h))}function Ie(a,e,t){let r=T.HeaderMap.new();r.set_algorithm_id(T.Label.from_algorithm_id(T.AlgorithmId.EdDSA)),r.set_header(T.Label.new_text("address"),T.CBORValue.new_bytes(d(a)));let s=T.ProtectedHeaderMap.new(r),n=T.HeaderMap.new(),i=T.Headers.new(s,n),u=T.COSESign1Builder.new(i,d(e),!1),c=u.make_data_to_sign().to_bytes(),m=o.PrivateKey.from_bech32(t),p=m.sign(c).to_bytes(),C=u.build(p),E=T.COSEKey.new(T.Label.from_key_type(T.KeyType.OKP));return E.set_algorithm_id(T.Label.from_algorithm_id(T.AlgorithmId.EdDSA)),E.set_header(T.Label.new_int(T.Int.new_negative(T.BigNum.from_str("1"))),T.CBORValue.new_int(T.Int.new_i32(6))),E.set_header(T.Label.new_int(T.Int.new_negative(T.BigNum.from_str("2"))),T.CBORValue.new_bytes(m.to_public().as_bytes())),{signature:y(C.to_bytes()),key:y(E.to_bytes())}}function At(a,e,t,r){let s=T.COSESign1.from_bytes(d(r.signature)),n=T.COSEKey.from_bytes(d(r.key)),i=s.headers().protected().deserialized_headers(),u=(()=>{try{return y(i.header(T.Label.new_text("address"))?.as_bytes())}catch{throw new Error("No address found in signature.")}})(),c=(()=>{try{let w=i.algorithm_id()?.as_int();return w?.is_positive()?parseInt(w.as_positive()?.to_str()):parseInt(w?.as_negative()?.to_str())}catch{throw new Error("Failed to retrieve Algorithm Id.")}})(),m=(()=>{try{let w=n.algorithm_id()?.as_int();return w?.is_positive()?parseInt(w.as_positive()?.to_str()):parseInt(w?.as_negative()?.to_str())}catch{throw new Error("Failed to retrieve Algorithm Id.")}})(),p=(()=>{try{let w=n.header(T.Label.new_int(T.Int.new_negative(T.BigNum.from_str("1"))))?.as_int();return w?.is_positive()?parseInt(w.as_positive()?.to_str()):parseInt(w?.as_negative()?.to_str())}catch{throw new Error("Failed to retrieve Curve.")}})(),C=(()=>{try{let w=n.key_type().as_int();return w?.is_positive()?parseInt(w.as_positive()?.to_str()):parseInt(w?.as_negative()?.to_str())}catch{throw new Error("Failed to retrieve Key Type.")}})(),E=(()=>{try{return o.PublicKey.from_bytes(n.header(T.Label.new_int(T.Int.new_negative(T.BigNum.from_str("2"))))?.as_bytes())}catch{throw new Error("No public key found.")}})(),h=(()=>{try{return y(s.payload())}catch{throw new Error("No payload found.")}})(),_=o.Ed25519Signature.from_bytes(s.signature()),I=s.signed_data(void 0,void 0).to_bytes();return u!==a||e!==E.hash().to_hex()||c!==m&&c!==T.AlgorithmId.EdDSA||p!==6||C!==1||h!==t?!1:E.verify(I,_)}var Me=class{constructor(e,t,r){Object.defineProperty(this,"lucid",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"address",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"payload",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.lucid=e,this.address=t,this.payload=r}sign(){return this.lucid.wallet.signMessage(this.address,this.payload)}signWithPrivateKey(e){let{paymentCredential:t,stakeCredential:r,address:{hex:s}}=this.lucid.utils.getAddressDetails(this.address),n=t?.hash||r?.hash,i=o.PrivateKey.from_bech32(e).to_public().hash().to_hex();if(!n||n!==i)throw new Error(`Cannot sign message for address: ${this.address}.`);return Ie(s,this.payload,e)}};var Re=class{constructor(e,t=et){Object.defineProperty(this,"ledger",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"mempool",{enumerable:!0,configurable:!0,writable:!0,value:{}}),Object.defineProperty(this,"chain",{enumerable:!0,configurable:!0,writable:!0,value:{}}),Object.defineProperty(this,"blockHeight",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"slot",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"time",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"protocolParameters",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"datumTable",{enumerable:!0,configurable:!0,writable:!0,value:{}});let r="00".repeat(32);this.blockHeight=0,this.slot=0,this.time=Date.now(),this.ledger={},e.forEach(({address:s,assets:n},i)=>{this.ledger[r+i]={utxo:{txHash:r,outputIndex:i,address:s,assets:n},spent:!1}}),this.protocolParameters=t}now(){return this.time}awaitSlot(e=1){this.slot+=e,this.time+=e*1e3;let t=this.blockHeight;if(this.blockHeight=Math.floor(this.slot/20),this.blockHeight>t){for(let[r,{utxo:s,spent:n}]of Object.entries(this.mempool))this.ledger[r]={utxo:s,spent:n};for(let[r,{spent:s}]of Object.entries(this.ledger))s&&delete this.ledger[r];this.mempool={}}}awaitBlock(e=1){this.blockHeight+=e,this.slot+=e*20,this.time+=e*20*1e3;for(let[t,{utxo:r,spent:s}]of Object.entries(this.mempool))this.ledger[t]={utxo:r,spent:s};for(let[t,{spent:r}]of Object.entries(this.ledger))r&&delete this.ledger[t];this.mempool={}}getUtxos(e){let t=Object.values(this.ledger).flatMap(({utxo:r})=>{if(typeof e=="string")return e===r.address?r:[];{let{paymentCredential:s}=D(r.address);return s?.hash===e.hash?r:[]}});return Promise.resolve(t)}getProtocolParameters(){return Promise.resolve(this.protocolParameters)}getDatum(e){return Promise.resolve(this.datumTable[e])}getUtxosWithUnit(e,t){let r=Object.values(this.ledger).flatMap(({utxo:s})=>{if(typeof e=="string")return e===s.address&&s.assets[t]>0n?s:[];{let{paymentCredential:n}=D(s.address);return n?.hash===e.hash&&s.assets[t]>0n?s:[]}});return Promise.resolve(r)}getUtxosByOutRef(e){return Promise.resolve(e.flatMap(t=>this.ledger[t.txHash+t.outputIndex]?.utxo||[]))}getUtxoByUnit(e){let t=Object.values(this.ledger).flatMap(({utxo:r})=>r.assets[e]>0n?r:[]);if(t.length>1)throw new Error("Unit needs to be an NFT or only held by one address.");return Promise.resolve(t[0])}getDelegation(e){return Promise.resolve({poolId:this.chain[e]?.delegation?.poolId||null,rewards:this.chain[e]?.delegation?.rewards||0n})}awaitTx(e){return this.mempool[e+0]&&this.awaitBlock(),Promise.resolve(!0)}distributeRewards(e){for(let[t,{registeredStake:r,delegation:s}]of Object.entries(this.chain))r&&s.poolId&&(this.chain[t]={registeredStake:r,delegation:{poolId:s.poolId,rewards:s.rewards+=e}});this.awaitBlock()}submitTx(e){let t=o.Transaction.from_bytes(d(e)),r=t.body(),s=t.witness_set(),n=s.plutus_data(),i=o.hash_transaction(r).to_hex(),u=r.validity_start_interval()?parseInt(r.validity_start_interval().to_str()):null,c=r.ttl()?parseInt(r.ttl().to_str()):null;if(Number.isInteger(u)&&this.slotc)throw new Error(`Upper bound (${c}) not in slot range (${this.slot}).`);let m=(()=>{let l={};for(let f=0;f<(n?.len()||0);f++){let k=n.get(f),b=o.hash_plutus_data(k).to_hex();l[b]=y(k.to_bytes())}return l})(),p=new Set,C=(()=>{let l=[];for(let f=0;f<(s.vkeys()?.len()||0);f++){let k=s.vkeys().get(f),b=k.vkey().public_key(),P=b.hash().to_hex();if(!b.verify(d(i),k.signature()))throw new Error(`Invalid vkey witness. Key hash: ${P}`);l.push(P)}return l})(),E=o.Ed25519KeyHashes.new();C.forEach(l=>E.add(o.Ed25519KeyHash.from_hex(l)));let h=(()=>{let l=[];for(let f=0;f<(s.native_scripts()?.len()||0);f++){let k=s.native_scripts().get(f),b=k.hash(o.ScriptHashNamespace.NativeScript).to_hex();if(!k.verify(Number.isInteger(u)?o.BigNum.from_str(u.toString()):void 0,Number.isInteger(c)?o.BigNum.from_str(c.toString()):void 0,E))throw new Error(`Invalid native script witness. Script hash: ${b}`);for(let P=0;P{let l=[];for(let f=0;f<(s.plutus_scripts()?.len()||0);f++){let b=s.plutus_scripts().get(f).hash(o.ScriptHashNamespace.PlutusV1).to_hex();l.push(b)}for(let f=0;f<(s.plutus_v2_scripts()?.len()||0);f++){let b=s.plutus_v2_scripts().get(f).hash(o.ScriptHashNamespace.PlutusV2).to_hex();l.push(b)}return l})(),A=r.inputs();A.sort();let O=[];for(let l=0;l{let l={0:"Spend",1:"Mint",2:"Cert",3:"Reward"},f=[];for(let k=0;k<(s.redeemers()?.len()||0);k++){let b=s.redeemers().get(k);f.push({tag:l[b.tag().kind()],index:parseInt(b.index().to_str())})}return f})();function B(l,f,k){switch(l.type){case"Key":{if(!C.includes(l.hash))throw new Error(`Missing vkey witness. Key hash: ${l.hash}`);p.add(l.hash);break}case"Script":{if(h.includes(l.hash)){p.add(l.hash);break}else if(_[l.hash]){if(!_[l.hash].verify(Number.isInteger(u)?o.BigNum.from_str(u.toString()):void 0,Number.isInteger(c)?o.BigNum.from_str(c.toString()):void 0,E))throw new Error(`Invalid native script witness. Script hash: ${l.hash}`);break}else if((w.includes(l.hash)||I.includes(l.hash))&&R.find(b=>b.tag===f&&b.index===k)){p.add(l.hash);break}throw new Error(`Missing script witness. Script hash: ${l.hash}`)}}}for(let l=0;l<(r.collateral()?.len()||0);l++){let f=r.collateral().get(l),k=f.transaction_id().to_hex()+f.index().to_str(),b=this.ledger[k]||this.mempool[k];if(!b||b.spent)throw new Error(`Could not read UTxO: ${JSON.stringify({txHash:b?.utxo.txHash,outputIndex:b?.utxo.outputIndex})} -It does not exist or was already spent.`);let{paymentCredential:P}=D(b.utxo.address);if(P?.type==="Script")throw new Error("Collateral inputs can only contain vkeys.");B(P,null,null)}for(let l=0;l<(r.required_signers()?.len()||0);l++){let f=r.required_signers().get(l);B({type:"Key",hash:f.to_hex()},null,null)}for(let l=0;l<(r.mint()?.keys().len()||0);l++){let f=r.mint().keys().get(l).to_hex();B({type:"Script",hash:f},"Mint",l)}let pe=[];for(let l=0;l<(r.withdrawals()?.keys().len()||0);l++){let f=r.withdrawals().keys().get(l),k=BigInt(r.withdrawals().get(f).to_str()),b=f.to_address().to_bech32(void 0),{stakeCredential:P}=D(b);if(B(P,"Reward",l),this.chain[b]?.delegation.rewards!==k)throw new Error("Withdrawal amount doesn't match actual reward balance.");pe.push({rewardAddress:b,withdrawal:k})}let te=[];for(let l=0;l<(r.certs()?.len()||0);l++){let f=r.certs().get(l);switch(f.kind()){case 0:{let k=f.as_stake_registration(),b=o.RewardAddress.new(o.NetworkInfo.testnet().network_id(),k.stake_credential()).to_address().to_bech32(void 0);if(this.chain[b]?.registeredStake)throw new Error(`Stake key is already registered. Reward address: ${b}`);te.push({type:"Registration",rewardAddress:b});break}case 1:{let k=f.as_stake_deregistration(),b=o.RewardAddress.new(o.NetworkInfo.testnet().network_id(),k.stake_credential()).to_address().to_bech32(void 0),{stakeCredential:P}=D(b);if(B(P,"Cert",l),!this.chain[b]?.registeredStake)throw new Error(`Stake key is already deregistered. Reward address: ${b}`);te.push({type:"Deregistration",rewardAddress:b});break}case 2:{let k=f.as_stake_delegation(),b=o.RewardAddress.new(o.NetworkInfo.testnet().network_id(),k.stake_credential()).to_address().to_bech32(void 0),P=k.pool_keyhash().to_bech32("pool"),{stakeCredential:$}=D(b);if(B($,"Cert",l),!this.chain[b]?.registeredStake&&!te.find(re=>re.type==="Registration"&&re.rewardAddress===b))throw new Error(`Stake key is not registered. Reward address: ${b}`);te.push({type:"Delegation",rewardAddress:b,poolId:P});break}}}O.forEach(({entry:{utxo:l}},f)=>{let{paymentCredential:k}=D(l.address);B(k,"Spend",f)});let Nt=(()=>{let l=[];for(let f=0;f!p.has(l));if(Je)throw new Error(`Extraneous vkey witness. Key hash: ${Je}`);let[Xe]=h.filter(l=>!p.has(l));if(Xe)throw new Error(`Extraneous native script. Script hash: ${Xe}`);let[Ge]=w.filter(l=>!p.has(l));if(Ge)throw new Error(`Extraneous plutus script. Script hash: ${Ge}`);let[Ye]=Object.keys(m).filter(l=>!p.has(l));if(Ye)throw new Error(`Extraneous plutus data. Datum hash: ${Ye}`);O.forEach(({entry:l,type:f})=>{let k=l.utxo.txHash+l.utxo.outputIndex;l.spent=!0,f==="Ledger"?this.ledger[k]=l:f==="Mempool"&&(this.mempool[k]=l)}),pe.forEach(({rewardAddress:l,withdrawal:f})=>{this.chain[l].delegation.rewards-=f}),te.forEach(({type:l,rewardAddress:f,poolId:k})=>{switch(l){case"Registration":{this.chain[f]?this.chain[f].registeredStake=!0:this.chain[f]={registeredStake:!0,delegation:{poolId:null,rewards:0n}};break}case"Deregistration":{this.chain[f].registeredStake=!1,this.chain[f].delegation.poolId=null;break}case"Delegation":this.chain[f].delegation.poolId=k}}),Nt.forEach(({utxo:l,spent:f})=>{this.mempool[l.txHash+l.outputIndex]={utxo:l,spent:f}});for(let[l,f]of Object.entries(m))this.datumTable[l]=f;return Promise.resolve(i)}log(){function e(s){let n=s==="lovelace"?"1":s,i=0;for(let p=0;p=14"},dependencies:{"node-fetch":"^3.2.3","@peculiar/webcrypto":"^1.4.0",ws:"^8.10.0"},type:"module",exports:{".":{import:"./dist/esm/mod.js",types:"./dist/types/mod.d.ts"}}};async function _t(a,e){try{await a.instantiate({url:new URL(e,`https://deno.land/x/lucid@${Be.version}/src/core/libs/`)})}catch{}}await Promise.all([_t(i,"cardano_multiplatform_lib/cardano_multiplatform_lib_bg.wasm"),_t(D,"cardano_message_signing/cardano_message_signing_bg.wasm")]);var _=class{static free(...e){e.forEach(t=>{t?.free()})}};function kt(a){let e=[];try{let t=i.Costmdls.new(),s=i.CostModel.new();e.push(s),Object.values(a.PlutusV1).forEach((c,u)=>{let l=i.BigNum.from_str(c.toString());e.push(l);let d=i.Int.new(l);e.push(d),s.set(u,d)});let r=i.Language.new_plutus_v1();e.push(r),t.insert(r,s);let n=i.CostModel.new_plutus_v2();e.push(n),Object.values(a.PlutusV2||[]).forEach((c,u)=>{let l=i.BigNum.from_str(c.toString());e.push(l);let d=i.Int.new(l);e.push(d),n.set(u,d)});let o=i.Language.new_plutus_v2();return e.push(o),t.insert(o,n),t}finally{_.free(...e)}}var Je={minFeeA:44,minFeeB:155381,maxTxSize:16384,maxValSize:5e3,keyDeposit:2000000n,poolDeposit:500000000n,priceMem:.0577,priceStep:721e-7,maxTxExMem:14000000n,maxTxExSteps:10000000000n,coinsPerUtxoByte:4310n,collateralPercentage:150,maxCollateralInputs:3,costModels:{PlutusV1:{"addInteger-cpu-arguments-intercept":205665,"addInteger-cpu-arguments-slope":812,"addInteger-memory-arguments-intercept":1,"addInteger-memory-arguments-slope":1,"appendByteString-cpu-arguments-intercept":1e3,"appendByteString-cpu-arguments-slope":571,"appendByteString-memory-arguments-intercept":0,"appendByteString-memory-arguments-slope":1,"appendString-cpu-arguments-intercept":1e3,"appendString-cpu-arguments-slope":24177,"appendString-memory-arguments-intercept":4,"appendString-memory-arguments-slope":1,"bData-cpu-arguments":1e3,"bData-memory-arguments":32,"blake2b_256-cpu-arguments-intercept":117366,"blake2b_256-cpu-arguments-slope":10475,"blake2b_256-memory-arguments":4,"cekApplyCost-exBudgetCPU":23e3,"cekApplyCost-exBudgetMemory":100,"cekBuiltinCost-exBudgetCPU":23e3,"cekBuiltinCost-exBudgetMemory":100,"cekConstCost-exBudgetCPU":23e3,"cekConstCost-exBudgetMemory":100,"cekDelayCost-exBudgetCPU":23e3,"cekDelayCost-exBudgetMemory":100,"cekForceCost-exBudgetCPU":23e3,"cekForceCost-exBudgetMemory":100,"cekLamCost-exBudgetCPU":23e3,"cekLamCost-exBudgetMemory":100,"cekStartupCost-exBudgetCPU":100,"cekStartupCost-exBudgetMemory":100,"cekVarCost-exBudgetCPU":23e3,"cekVarCost-exBudgetMemory":100,"chooseData-cpu-arguments":19537,"chooseData-memory-arguments":32,"chooseList-cpu-arguments":175354,"chooseList-memory-arguments":32,"chooseUnit-cpu-arguments":46417,"chooseUnit-memory-arguments":4,"consByteString-cpu-arguments-intercept":221973,"consByteString-cpu-arguments-slope":511,"consByteString-memory-arguments-intercept":0,"consByteString-memory-arguments-slope":1,"constrData-cpu-arguments":89141,"constrData-memory-arguments":32,"decodeUtf8-cpu-arguments-intercept":497525,"decodeUtf8-cpu-arguments-slope":14068,"decodeUtf8-memory-arguments-intercept":4,"decodeUtf8-memory-arguments-slope":2,"divideInteger-cpu-arguments-constant":196500,"divideInteger-cpu-arguments-model-arguments-intercept":453240,"divideInteger-cpu-arguments-model-arguments-slope":220,"divideInteger-memory-arguments-intercept":0,"divideInteger-memory-arguments-minimum":1,"divideInteger-memory-arguments-slope":1,"encodeUtf8-cpu-arguments-intercept":1e3,"encodeUtf8-cpu-arguments-slope":28662,"encodeUtf8-memory-arguments-intercept":4,"encodeUtf8-memory-arguments-slope":2,"equalsByteString-cpu-arguments-constant":245e3,"equalsByteString-cpu-arguments-intercept":216773,"equalsByteString-cpu-arguments-slope":62,"equalsByteString-memory-arguments":1,"equalsData-cpu-arguments-intercept":1060367,"equalsData-cpu-arguments-slope":12586,"equalsData-memory-arguments":1,"equalsInteger-cpu-arguments-intercept":208512,"equalsInteger-cpu-arguments-slope":421,"equalsInteger-memory-arguments":1,"equalsString-cpu-arguments-constant":187e3,"equalsString-cpu-arguments-intercept":1e3,"equalsString-cpu-arguments-slope":52998,"equalsString-memory-arguments":1,"fstPair-cpu-arguments":80436,"fstPair-memory-arguments":32,"headList-cpu-arguments":43249,"headList-memory-arguments":32,"iData-cpu-arguments":1e3,"iData-memory-arguments":32,"ifThenElse-cpu-arguments":80556,"ifThenElse-memory-arguments":1,"indexByteString-cpu-arguments":57667,"indexByteString-memory-arguments":4,"lengthOfByteString-cpu-arguments":1e3,"lengthOfByteString-memory-arguments":10,"lessThanByteString-cpu-arguments-intercept":197145,"lessThanByteString-cpu-arguments-slope":156,"lessThanByteString-memory-arguments":1,"lessThanEqualsByteString-cpu-arguments-intercept":197145,"lessThanEqualsByteString-cpu-arguments-slope":156,"lessThanEqualsByteString-memory-arguments":1,"lessThanEqualsInteger-cpu-arguments-intercept":204924,"lessThanEqualsInteger-cpu-arguments-slope":473,"lessThanEqualsInteger-memory-arguments":1,"lessThanInteger-cpu-arguments-intercept":208896,"lessThanInteger-cpu-arguments-slope":511,"lessThanInteger-memory-arguments":1,"listData-cpu-arguments":52467,"listData-memory-arguments":32,"mapData-cpu-arguments":64832,"mapData-memory-arguments":32,"mkCons-cpu-arguments":65493,"mkCons-memory-arguments":32,"mkNilData-cpu-arguments":22558,"mkNilData-memory-arguments":32,"mkNilPairData-cpu-arguments":16563,"mkNilPairData-memory-arguments":32,"mkPairData-cpu-arguments":76511,"mkPairData-memory-arguments":32,"modInteger-cpu-arguments-constant":196500,"modInteger-cpu-arguments-model-arguments-intercept":453240,"modInteger-cpu-arguments-model-arguments-slope":220,"modInteger-memory-arguments-intercept":0,"modInteger-memory-arguments-minimum":1,"modInteger-memory-arguments-slope":1,"multiplyInteger-cpu-arguments-intercept":69522,"multiplyInteger-cpu-arguments-slope":11687,"multiplyInteger-memory-arguments-intercept":0,"multiplyInteger-memory-arguments-slope":1,"nullList-cpu-arguments":60091,"nullList-memory-arguments":32,"quotientInteger-cpu-arguments-constant":196500,"quotientInteger-cpu-arguments-model-arguments-intercept":453240,"quotientInteger-cpu-arguments-model-arguments-slope":220,"quotientInteger-memory-arguments-intercept":0,"quotientInteger-memory-arguments-minimum":1,"quotientInteger-memory-arguments-slope":1,"remainderInteger-cpu-arguments-constant":196500,"remainderInteger-cpu-arguments-model-arguments-intercept":453240,"remainderInteger-cpu-arguments-model-arguments-slope":220,"remainderInteger-memory-arguments-intercept":0,"remainderInteger-memory-arguments-minimum":1,"remainderInteger-memory-arguments-slope":1,"sha2_256-cpu-arguments-intercept":806990,"sha2_256-cpu-arguments-slope":30482,"sha2_256-memory-arguments":4,"sha3_256-cpu-arguments-intercept":1927926,"sha3_256-cpu-arguments-slope":82523,"sha3_256-memory-arguments":4,"sliceByteString-cpu-arguments-intercept":265318,"sliceByteString-cpu-arguments-slope":0,"sliceByteString-memory-arguments-intercept":4,"sliceByteString-memory-arguments-slope":0,"sndPair-cpu-arguments":85931,"sndPair-memory-arguments":32,"subtractInteger-cpu-arguments-intercept":205665,"subtractInteger-cpu-arguments-slope":812,"subtractInteger-memory-arguments-intercept":1,"subtractInteger-memory-arguments-slope":1,"tailList-cpu-arguments":41182,"tailList-memory-arguments":32,"trace-cpu-arguments":212342,"trace-memory-arguments":32,"unBData-cpu-arguments":31220,"unBData-memory-arguments":32,"unConstrData-cpu-arguments":32696,"unConstrData-memory-arguments":32,"unIData-cpu-arguments":43357,"unIData-memory-arguments":32,"unListData-cpu-arguments":32247,"unListData-memory-arguments":32,"unMapData-cpu-arguments":38314,"unMapData-memory-arguments":32,"verifyEd25519Signature-cpu-arguments-intercept":9462713,"verifyEd25519Signature-cpu-arguments-slope":1021,"verifyEd25519Signature-memory-arguments":10},PlutusV2:{"addInteger-cpu-arguments-intercept":205665,"addInteger-cpu-arguments-slope":812,"addInteger-memory-arguments-intercept":1,"addInteger-memory-arguments-slope":1,"appendByteString-cpu-arguments-intercept":1e3,"appendByteString-cpu-arguments-slope":571,"appendByteString-memory-arguments-intercept":0,"appendByteString-memory-arguments-slope":1,"appendString-cpu-arguments-intercept":1e3,"appendString-cpu-arguments-slope":24177,"appendString-memory-arguments-intercept":4,"appendString-memory-arguments-slope":1,"bData-cpu-arguments":1e3,"bData-memory-arguments":32,"blake2b_256-cpu-arguments-intercept":117366,"blake2b_256-cpu-arguments-slope":10475,"blake2b_256-memory-arguments":4,"cekApplyCost-exBudgetCPU":23e3,"cekApplyCost-exBudgetMemory":100,"cekBuiltinCost-exBudgetCPU":23e3,"cekBuiltinCost-exBudgetMemory":100,"cekConstCost-exBudgetCPU":23e3,"cekConstCost-exBudgetMemory":100,"cekDelayCost-exBudgetCPU":23e3,"cekDelayCost-exBudgetMemory":100,"cekForceCost-exBudgetCPU":23e3,"cekForceCost-exBudgetMemory":100,"cekLamCost-exBudgetCPU":23e3,"cekLamCost-exBudgetMemory":100,"cekStartupCost-exBudgetCPU":100,"cekStartupCost-exBudgetMemory":100,"cekVarCost-exBudgetCPU":23e3,"cekVarCost-exBudgetMemory":100,"chooseData-cpu-arguments":19537,"chooseData-memory-arguments":32,"chooseList-cpu-arguments":175354,"chooseList-memory-arguments":32,"chooseUnit-cpu-arguments":46417,"chooseUnit-memory-arguments":4,"consByteString-cpu-arguments-intercept":221973,"consByteString-cpu-arguments-slope":511,"consByteString-memory-arguments-intercept":0,"consByteString-memory-arguments-slope":1,"constrData-cpu-arguments":89141,"constrData-memory-arguments":32,"decodeUtf8-cpu-arguments-intercept":497525,"decodeUtf8-cpu-arguments-slope":14068,"decodeUtf8-memory-arguments-intercept":4,"decodeUtf8-memory-arguments-slope":2,"divideInteger-cpu-arguments-constant":196500,"divideInteger-cpu-arguments-model-arguments-intercept":453240,"divideInteger-cpu-arguments-model-arguments-slope":220,"divideInteger-memory-arguments-intercept":0,"divideInteger-memory-arguments-minimum":1,"divideInteger-memory-arguments-slope":1,"encodeUtf8-cpu-arguments-intercept":1e3,"encodeUtf8-cpu-arguments-slope":28662,"encodeUtf8-memory-arguments-intercept":4,"encodeUtf8-memory-arguments-slope":2,"equalsByteString-cpu-arguments-constant":245e3,"equalsByteString-cpu-arguments-intercept":216773,"equalsByteString-cpu-arguments-slope":62,"equalsByteString-memory-arguments":1,"equalsData-cpu-arguments-intercept":1060367,"equalsData-cpu-arguments-slope":12586,"equalsData-memory-arguments":1,"equalsInteger-cpu-arguments-intercept":208512,"equalsInteger-cpu-arguments-slope":421,"equalsInteger-memory-arguments":1,"equalsString-cpu-arguments-constant":187e3,"equalsString-cpu-arguments-intercept":1e3,"equalsString-cpu-arguments-slope":52998,"equalsString-memory-arguments":1,"fstPair-cpu-arguments":80436,"fstPair-memory-arguments":32,"headList-cpu-arguments":43249,"headList-memory-arguments":32,"iData-cpu-arguments":1e3,"iData-memory-arguments":32,"ifThenElse-cpu-arguments":80556,"ifThenElse-memory-arguments":1,"indexByteString-cpu-arguments":57667,"indexByteString-memory-arguments":4,"lengthOfByteString-cpu-arguments":1e3,"lengthOfByteString-memory-arguments":10,"lessThanByteString-cpu-arguments-intercept":197145,"lessThanByteString-cpu-arguments-slope":156,"lessThanByteString-memory-arguments":1,"lessThanEqualsByteString-cpu-arguments-intercept":197145,"lessThanEqualsByteString-cpu-arguments-slope":156,"lessThanEqualsByteString-memory-arguments":1,"lessThanEqualsInteger-cpu-arguments-intercept":204924,"lessThanEqualsInteger-cpu-arguments-slope":473,"lessThanEqualsInteger-memory-arguments":1,"lessThanInteger-cpu-arguments-intercept":208896,"lessThanInteger-cpu-arguments-slope":511,"lessThanInteger-memory-arguments":1,"listData-cpu-arguments":52467,"listData-memory-arguments":32,"mapData-cpu-arguments":64832,"mapData-memory-arguments":32,"mkCons-cpu-arguments":65493,"mkCons-memory-arguments":32,"mkNilData-cpu-arguments":22558,"mkNilData-memory-arguments":32,"mkNilPairData-cpu-arguments":16563,"mkNilPairData-memory-arguments":32,"mkPairData-cpu-arguments":76511,"mkPairData-memory-arguments":32,"modInteger-cpu-arguments-constant":196500,"modInteger-cpu-arguments-model-arguments-intercept":453240,"modInteger-cpu-arguments-model-arguments-slope":220,"modInteger-memory-arguments-intercept":0,"modInteger-memory-arguments-minimum":1,"modInteger-memory-arguments-slope":1,"multiplyInteger-cpu-arguments-intercept":69522,"multiplyInteger-cpu-arguments-slope":11687,"multiplyInteger-memory-arguments-intercept":0,"multiplyInteger-memory-arguments-slope":1,"nullList-cpu-arguments":60091,"nullList-memory-arguments":32,"quotientInteger-cpu-arguments-constant":196500,"quotientInteger-cpu-arguments-model-arguments-intercept":453240,"quotientInteger-cpu-arguments-model-arguments-slope":220,"quotientInteger-memory-arguments-intercept":0,"quotientInteger-memory-arguments-minimum":1,"quotientInteger-memory-arguments-slope":1,"remainderInteger-cpu-arguments-constant":196500,"remainderInteger-cpu-arguments-model-arguments-intercept":453240,"remainderInteger-cpu-arguments-model-arguments-slope":220,"remainderInteger-memory-arguments-intercept":0,"remainderInteger-memory-arguments-minimum":1,"remainderInteger-memory-arguments-slope":1,"serialiseData-cpu-arguments-intercept":1159724,"serialiseData-cpu-arguments-slope":392670,"serialiseData-memory-arguments-intercept":0,"serialiseData-memory-arguments-slope":2,"sha2_256-cpu-arguments-intercept":806990,"sha2_256-cpu-arguments-slope":30482,"sha2_256-memory-arguments":4,"sha3_256-cpu-arguments-intercept":1927926,"sha3_256-cpu-arguments-slope":82523,"sha3_256-memory-arguments":4,"sliceByteString-cpu-arguments-intercept":265318,"sliceByteString-cpu-arguments-slope":0,"sliceByteString-memory-arguments-intercept":4,"sliceByteString-memory-arguments-slope":0,"sndPair-cpu-arguments":85931,"sndPair-memory-arguments":32,"subtractInteger-cpu-arguments-intercept":205665,"subtractInteger-cpu-arguments-slope":812,"subtractInteger-memory-arguments-intercept":1,"subtractInteger-memory-arguments-slope":1,"tailList-cpu-arguments":41182,"tailList-memory-arguments":32,"trace-cpu-arguments":212342,"trace-memory-arguments":32,"unBData-cpu-arguments":31220,"unBData-memory-arguments":32,"unConstrData-cpu-arguments":32696,"unConstrData-memory-arguments":32,"unIData-cpu-arguments":43357,"unIData-memory-arguments":32,"unListData-cpu-arguments":32247,"unListData-memory-arguments":32,"unMapData-cpu-arguments":38314,"unMapData-memory-arguments":32,"verifyEcdsaSecp256k1Signature-cpu-arguments":35892428,"verifyEcdsaSecp256k1Signature-memory-arguments":10,"verifyEd25519Signature-cpu-arguments-intercept":57996947,"verifyEd25519Signature-cpu-arguments-slope":18975,"verifyEd25519Signature-memory-arguments":10,"verifySchnorrSecp256k1Signature-cpu-arguments-intercept":38887044,"verifySchnorrSecp256k1Signature-cpu-arguments-slope":32947,"verifySchnorrSecp256k1Signature-memory-arguments":10}}};var vt=new TextEncoder().encode("0123456789abcdef");function os(a){return new Error("encoding/hex: invalid byte: "+new TextDecoder().decode(new Uint8Array([a])))}function as(){return new Error("encoding/hex: odd length hex string")}function dt(a){if(48<=a&&a<=57)return a-48;if(97<=a&&a<=102)return a-97+10;if(65<=a&&a<=70)return a-65+10;throw os(a)}function is(a){return a*2}function cs(a){let e=new Uint8Array(is(a.length));for(let t=0;t>4],e[t*2+1]=vt[s&15]}return e}function St(a){return new TextDecoder().decode(cs(a))}function ht(a){let e=new Uint8Array(us(a.length));for(let t=0;t>>1}function It(a){return ht(new TextEncoder().encode(a))}var A=function(a,e,t,s,r){if(s==="m")throw new TypeError("Private method is not writable");if(s==="a"&&!r)throw new TypeError("Private accessor was defined without a setter");if(typeof e=="function"?a!==e||!r:!e.has(a))throw new TypeError("Cannot write private member to an object whose class did not declare it");return s==="a"?r.call(a,t):r?r.value=t:e.set(a,t),t},w=function(a,e,t,s){if(t==="a"&&!s)throw new TypeError("Private accessor was defined without a getter");if(typeof e=="function"?a!==e||!s:!e.has(a))throw new TypeError("Cannot read private member from an object whose class did not declare it");return t==="m"?s:t==="a"?s.call(a):s?s.value:e.get(a)},me,ve,ee,Te,$e,ne,oe,ae,ie,ce,ue,le,de,Se,Pe,fe,Ye,ge,ls,ds,hs,ps,k="0123456789abcdef".split(""),ms=[-2147483648,8388608,32768,128],Q=[24,16,8,0],Xe=[1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298],q=[],Ae=class{constructor(e=!1,t=!1){me.set(this,void 0),ve.set(this,void 0),ee.set(this,void 0),Te.set(this,void 0),$e.set(this,void 0),ne.set(this,void 0),oe.set(this,void 0),ae.set(this,void 0),ie.set(this,void 0),ce.set(this,void 0),ue.set(this,void 0),le.set(this,void 0),de.set(this,void 0),Se.set(this,void 0),Pe.set(this,void 0),fe.set(this,void 0),Ye.set(this,0),ge.set(this,void 0),this.init(e,t)}init(e,t){t?(q[0]=q[16]=q[1]=q[2]=q[3]=q[4]=q[5]=q[6]=q[7]=q[8]=q[9]=q[10]=q[11]=q[12]=q[13]=q[14]=q[15]=0,A(this,ve,q,"f")):A(this,ve,[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],"f"),e?(A(this,ne,3238371032,"f"),A(this,oe,914150663,"f"),A(this,ae,812702999,"f"),A(this,ie,4144912697,"f"),A(this,ce,4290775857,"f"),A(this,ue,1750603025,"f"),A(this,le,1694076839,"f"),A(this,de,3204075428,"f")):(A(this,ne,1779033703,"f"),A(this,oe,3144134277,"f"),A(this,ae,1013904242,"f"),A(this,ie,2773480762,"f"),A(this,ce,1359893119,"f"),A(this,ue,2600822924,"f"),A(this,le,528734635,"f"),A(this,de,1541459225,"f")),A(this,me,A(this,ge,A(this,ee,A(this,Pe,0,"f"),"f"),"f"),"f"),A(this,Te,A(this,Se,!1,"f"),"f"),A(this,$e,!0,"f"),A(this,fe,e,"f")}update(e){if(w(this,Te,"f"))return this;let t;e instanceof ArrayBuffer?t=new Uint8Array(e):t=e;let s=0,r=t.length,n=w(this,ve,"f");for(;s>2]|=t[s]<>2]|=c<>2]|=(192|c>>6)<>2]|=(128|c&63)<=57344?(n[o>>2]|=(224|c>>12)<>2]|=(128|c>>6&63)<>2]|=(128|c&63)<>2]|=(240|c>>18)<>2]|=(128|c>>12&63)<>2]|=(128|c>>6&63)<>2]|=(128|c&63)<=64?(A(this,me,n[16],"f"),A(this,ge,o-64,"f"),this.hash(),A(this,Se,!0,"f")):A(this,ge,o,"f")}return w(this,ee,"f")>4294967295&&(A(this,Pe,w(this,Pe,"f")+(w(this,ee,"f")/4294967296<<0),"f"),A(this,ee,w(this,ee,"f")%4294967296,"f")),this}finalize(){if(w(this,Te,"f"))return;A(this,Te,!0,"f");let e=w(this,ve,"f"),t=w(this,Ye,"f");e[16]=w(this,me,"f"),e[t>>2]|=ms[t&3],A(this,me,e[16],"f"),t>=56&&(w(this,Se,"f")||this.hash(),e[0]=w(this,me,"f"),e[16]=e[1]=e[2]=e[3]=e[4]=e[5]=e[6]=e[7]=e[8]=e[9]=e[10]=e[11]=e[12]=e[13]=e[14]=e[15]=0),e[14]=w(this,Pe,"f")<<3|w(this,ee,"f")>>>29,e[15]=w(this,ee,"f")<<3,this.hash()}hash(){let e=w(this,ne,"f"),t=w(this,oe,"f"),s=w(this,ae,"f"),r=w(this,ie,"f"),n=w(this,ce,"f"),o=w(this,ue,"f"),c=w(this,le,"f"),u=w(this,de,"f"),l=w(this,ve,"f"),d,h,f,m,S,v,y,B,I,N;for(let T=16;T<64;++T)m=l[T-15],d=(m>>>7|m<<25)^(m>>>18|m<<14)^m>>>3,m=l[T-2],h=(m>>>17|m<<15)^(m>>>19|m<<13)^m>>>10,l[T]=l[T-16]+d+l[T-7]+h<<0;N=t&s;for(let T=0;T<64;T+=4)w(this,$e,"f")?(w(this,fe,"f")?(y=300032,m=l[0]-1413257819,u=m-150054599<<0,r=m+24177077<<0):(y=704751109,m=l[0]-210244248,u=m-1521486534<<0,r=m+143694565<<0),A(this,$e,!1,"f")):(d=(e>>>2|e<<30)^(e>>>13|e<<19)^(e>>>22|e<<10),h=(n>>>6|n<<26)^(n>>>11|n<<21)^(n>>>25|n<<7),y=e&t,f=y^e&s^N,v=n&o^~n&c,m=u+h+v+Xe[T]+l[T],S=d+f,u=r+m<<0,r=m+S<<0),d=(r>>>2|r<<30)^(r>>>13|r<<19)^(r>>>22|r<<10),h=(u>>>6|u<<26)^(u>>>11|u<<21)^(u>>>25|u<<7),B=r&e,f=B^r&t^y,v=u&n^~u&o,m=c+h+v+Xe[T+1]+l[T+1],S=d+f,c=s+m<<0,s=m+S<<0,d=(s>>>2|s<<30)^(s>>>13|s<<19)^(s>>>22|s<<10),h=(c>>>6|c<<26)^(c>>>11|c<<21)^(c>>>25|c<<7),I=s&r,f=I^s&e^B,v=c&u^~c&n,m=o+h+v+Xe[T+2]+l[T+2],S=d+f,o=t+m<<0,t=m+S<<0,d=(t>>>2|t<<30)^(t>>>13|t<<19)^(t>>>22|t<<10),h=(o>>>6|o<<26)^(o>>>11|o<<21)^(o>>>25|o<<7),N=t&s,f=N^t&r^I,v=o&c^~o&u,m=n+h+v+Xe[T+3]+l[T+3],S=d+f,n=e+m<<0,e=m+S<<0;A(this,ne,w(this,ne,"f")+e<<0,"f"),A(this,oe,w(this,oe,"f")+t<<0,"f"),A(this,ae,w(this,ae,"f")+s<<0,"f"),A(this,ie,w(this,ie,"f")+r<<0,"f"),A(this,ce,w(this,ce,"f")+n<<0,"f"),A(this,ue,w(this,ue,"f")+o<<0,"f"),A(this,le,w(this,le,"f")+c<<0,"f"),A(this,de,w(this,de,"f")+u<<0,"f")}hex(){this.finalize();let e=w(this,ne,"f"),t=w(this,oe,"f"),s=w(this,ae,"f"),r=w(this,ie,"f"),n=w(this,ce,"f"),o=w(this,ue,"f"),c=w(this,le,"f"),u=w(this,de,"f"),l=k[e>>28&15]+k[e>>24&15]+k[e>>20&15]+k[e>>16&15]+k[e>>12&15]+k[e>>8&15]+k[e>>4&15]+k[e&15]+k[t>>28&15]+k[t>>24&15]+k[t>>20&15]+k[t>>16&15]+k[t>>12&15]+k[t>>8&15]+k[t>>4&15]+k[t&15]+k[s>>28&15]+k[s>>24&15]+k[s>>20&15]+k[s>>16&15]+k[s>>12&15]+k[s>>8&15]+k[s>>4&15]+k[s&15]+k[r>>28&15]+k[r>>24&15]+k[r>>20&15]+k[r>>16&15]+k[r>>12&15]+k[r>>8&15]+k[r>>4&15]+k[r&15]+k[n>>28&15]+k[n>>24&15]+k[n>>20&15]+k[n>>16&15]+k[n>>12&15]+k[n>>8&15]+k[n>>4&15]+k[n&15]+k[o>>28&15]+k[o>>24&15]+k[o>>20&15]+k[o>>16&15]+k[o>>12&15]+k[o>>8&15]+k[o>>4&15]+k[o&15]+k[c>>28&15]+k[c>>24&15]+k[c>>20&15]+k[c>>16&15]+k[c>>12&15]+k[c>>8&15]+k[c>>4&15]+k[c&15];return w(this,fe,"f")||(l+=k[u>>28&15]+k[u>>24&15]+k[u>>20&15]+k[u>>16&15]+k[u>>12&15]+k[u>>8&15]+k[u>>4&15]+k[u&15]),l}toString(){return this.hex()}digest(){this.finalize();let e=w(this,ne,"f"),t=w(this,oe,"f"),s=w(this,ae,"f"),r=w(this,ie,"f"),n=w(this,ce,"f"),o=w(this,ue,"f"),c=w(this,le,"f"),u=w(this,de,"f"),l=[e>>24&255,e>>16&255,e>>8&255,e&255,t>>24&255,t>>16&255,t>>8&255,t&255,s>>24&255,s>>16&255,s>>8&255,s&255,r>>24&255,r>>16&255,r>>8&255,r&255,n>>24&255,n>>16&255,n>>8&255,n&255,o>>24&255,o>>16&255,o>>8&255,o&255,c>>24&255,c>>16&255,c>>8&255,c&255];return w(this,fe,"f")||l.push(u>>24&255,u>>16&255,u>>8&255,u&255),l}array(){return this.digest()}arrayBuffer(){this.finalize();let e=new ArrayBuffer(w(this,fe,"f")?28:32),t=new DataView(e);return t.setUint32(0,w(this,ne,"f")),t.setUint32(4,w(this,oe,"f")),t.setUint32(8,w(this,ae,"f")),t.setUint32(12,w(this,ie,"f")),t.setUint32(16,w(this,ce,"f")),t.setUint32(20,w(this,ue,"f")),t.setUint32(24,w(this,le,"f")),w(this,fe,"f")||t.setUint32(28,w(this,de,"f")),e}};me=new WeakMap,ve=new WeakMap,ee=new WeakMap,Te=new WeakMap,$e=new WeakMap,ne=new WeakMap,oe=new WeakMap,ae=new WeakMap,ie=new WeakMap,ce=new WeakMap,ue=new WeakMap,le=new WeakMap,de=new WeakMap,Se=new WeakMap,Pe=new WeakMap,fe=new WeakMap,Ye=new WeakMap,ge=new WeakMap;ls=new WeakMap,ds=new WeakMap,hs=new WeakMap,ps=new WeakMap;var Ct="Invalid mnemonic",Ie="Invalid entropy",fs="Invalid mnemonic checksum",Et=`A wordlist is required but a default could not be found. +Please pass a 2048 word array explicitly.`;function Bt(a,e){if(e=e||Ut,!e)throw new Error(Et);let t=xs(a).split(" ");if(t.length%3!==0)throw new Error(Ct);let s=t.map(d=>{let h=e.indexOf(d);if(h===-1)throw new Error(Ct);return At(h.toString(2),"0",11)}).join(""),r=Math.floor(s.length/33)*32,n=s.slice(0,r),o=s.slice(r),c=n.match(/(.{1,8})/g).map(Ot);if(c.length<16)throw new Error(Ie);if(c.length>32)throw new Error(Ie);if(c.length%4!==0)throw new Error(Ie);let u=new Uint8Array(c);if(Pt(u)!==o)throw new Error(fs);return b(u)}function gs(a){let s=new Uint8Array(a);if(a>4294967295)throw new RangeError("requested too many random bytes");if(a>0)if(a>65536)for(let r=0;r32)throw new TypeError(Ie);if(a.length%4!==0)throw new TypeError(Ie);let t=Ht(Array.from(a)),s=Pt(a),o=(t+s).match(/(.{1,11})/g).map(c=>{let u=Ot(c);return e[u]});return e[0]==="\u3042\u3044\u3053\u304F\u3057\u3093"?o.join("\u3000"):o.join(" ")}function Pt(a){let t=a.length*8/32,s=new Ae().update(a).digest();return Ht(Array.from(s)).slice(0,t)}function At(a,e,t){for(;a.lengthAt(e.toString(2),"0",8)).join("")}function xs(a){return(a||"").normalize("NFKD")}function Ot(a){return parseInt(a,2)}var Ut=["abandon","ability","able","about","above","absent","absorb","abstract","absurd","abuse","access","accident","account","accuse","achieve","acid","acoustic","acquire","across","act","action","actor","actress","actual","adapt","add","addict","address","adjust","admit","adult","advance","advice","aerobic","affair","afford","afraid","again","age","agent","agree","ahead","aim","air","airport","aisle","alarm","album","alcohol","alert","alien","all","alley","allow","almost","alone","alpha","already","also","alter","always","amateur","amazing","among","amount","amused","analyst","anchor","ancient","anger","angle","angry","animal","ankle","announce","annual","another","answer","antenna","antique","anxiety","any","apart","apology","appear","apple","approve","april","arch","arctic","area","arena","argue","arm","armed","armor","army","around","arrange","arrest","arrive","arrow","art","artefact","artist","artwork","ask","aspect","assault","asset","assist","assume","asthma","athlete","atom","attack","attend","attitude","attract","auction","audit","august","aunt","author","auto","autumn","average","avocado","avoid","awake","aware","away","awesome","awful","awkward","axis","baby","bachelor","bacon","badge","bag","balance","balcony","ball","bamboo","banana","banner","bar","barely","bargain","barrel","base","basic","basket","battle","beach","bean","beauty","because","become","beef","before","begin","behave","behind","believe","below","belt","bench","benefit","best","betray","better","between","beyond","bicycle","bid","bike","bind","biology","bird","birth","bitter","black","blade","blame","blanket","blast","bleak","bless","blind","blood","blossom","blouse","blue","blur","blush","board","boat","body","boil","bomb","bone","bonus","book","boost","border","boring","borrow","boss","bottom","bounce","box","boy","bracket","brain","brand","brass","brave","bread","breeze","brick","bridge","brief","bright","bring","brisk","broccoli","broken","bronze","broom","brother","brown","brush","bubble","buddy","budget","buffalo","build","bulb","bulk","bullet","bundle","bunker","burden","burger","burst","bus","business","busy","butter","buyer","buzz","cabbage","cabin","cable","cactus","cage","cake","call","calm","camera","camp","can","canal","cancel","candy","cannon","canoe","canvas","canyon","capable","capital","captain","car","carbon","card","cargo","carpet","carry","cart","case","cash","casino","castle","casual","cat","catalog","catch","category","cattle","caught","cause","caution","cave","ceiling","celery","cement","census","century","cereal","certain","chair","chalk","champion","change","chaos","chapter","charge","chase","chat","cheap","check","cheese","chef","cherry","chest","chicken","chief","child","chimney","choice","choose","chronic","chuckle","chunk","churn","cigar","cinnamon","circle","citizen","city","civil","claim","clap","clarify","claw","clay","clean","clerk","clever","click","client","cliff","climb","clinic","clip","clock","clog","close","cloth","cloud","clown","club","clump","cluster","clutch","coach","coast","coconut","code","coffee","coil","coin","collect","color","column","combine","come","comfort","comic","common","company","concert","conduct","confirm","congress","connect","consider","control","convince","cook","cool","copper","copy","coral","core","corn","correct","cost","cotton","couch","country","couple","course","cousin","cover","coyote","crack","cradle","craft","cram","crane","crash","crater","crawl","crazy","cream","credit","creek","crew","cricket","crime","crisp","critic","crop","cross","crouch","crowd","crucial","cruel","cruise","crumble","crunch","crush","cry","crystal","cube","culture","cup","cupboard","curious","current","curtain","curve","cushion","custom","cute","cycle","dad","damage","damp","dance","danger","daring","dash","daughter","dawn","day","deal","debate","debris","decade","december","decide","decline","decorate","decrease","deer","defense","define","defy","degree","delay","deliver","demand","demise","denial","dentist","deny","depart","depend","deposit","depth","deputy","derive","describe","desert","design","desk","despair","destroy","detail","detect","develop","device","devote","diagram","dial","diamond","diary","dice","diesel","diet","differ","digital","dignity","dilemma","dinner","dinosaur","direct","dirt","disagree","discover","disease","dish","dismiss","disorder","display","distance","divert","divide","divorce","dizzy","doctor","document","dog","doll","dolphin","domain","donate","donkey","donor","door","dose","double","dove","draft","dragon","drama","drastic","draw","dream","dress","drift","drill","drink","drip","drive","drop","drum","dry","duck","dumb","dune","during","dust","dutch","duty","dwarf","dynamic","eager","eagle","early","earn","earth","easily","east","easy","echo","ecology","economy","edge","edit","educate","effort","egg","eight","either","elbow","elder","electric","elegant","element","elephant","elevator","elite","else","embark","embody","embrace","emerge","emotion","employ","empower","empty","enable","enact","end","endless","endorse","enemy","energy","enforce","engage","engine","enhance","enjoy","enlist","enough","enrich","enroll","ensure","enter","entire","entry","envelope","episode","equal","equip","era","erase","erode","erosion","error","erupt","escape","essay","essence","estate","eternal","ethics","evidence","evil","evoke","evolve","exact","example","excess","exchange","excite","exclude","excuse","execute","exercise","exhaust","exhibit","exile","exist","exit","exotic","expand","expect","expire","explain","expose","express","extend","extra","eye","eyebrow","fabric","face","faculty","fade","faint","faith","fall","false","fame","family","famous","fan","fancy","fantasy","farm","fashion","fat","fatal","father","fatigue","fault","favorite","feature","february","federal","fee","feed","feel","female","fence","festival","fetch","fever","few","fiber","fiction","field","figure","file","film","filter","final","find","fine","finger","finish","fire","firm","first","fiscal","fish","fit","fitness","fix","flag","flame","flash","flat","flavor","flee","flight","flip","float","flock","floor","flower","fluid","flush","fly","foam","focus","fog","foil","fold","follow","food","foot","force","forest","forget","fork","fortune","forum","forward","fossil","foster","found","fox","fragile","frame","frequent","fresh","friend","fringe","frog","front","frost","frown","frozen","fruit","fuel","fun","funny","furnace","fury","future","gadget","gain","galaxy","gallery","game","gap","garage","garbage","garden","garlic","garment","gas","gasp","gate","gather","gauge","gaze","general","genius","genre","gentle","genuine","gesture","ghost","giant","gift","giggle","ginger","giraffe","girl","give","glad","glance","glare","glass","glide","glimpse","globe","gloom","glory","glove","glow","glue","goat","goddess","gold","good","goose","gorilla","gospel","gossip","govern","gown","grab","grace","grain","grant","grape","grass","gravity","great","green","grid","grief","grit","grocery","group","grow","grunt","guard","guess","guide","guilt","guitar","gun","gym","habit","hair","half","hammer","hamster","hand","happy","harbor","hard","harsh","harvest","hat","have","hawk","hazard","head","health","heart","heavy","hedgehog","height","hello","helmet","help","hen","hero","hidden","high","hill","hint","hip","hire","history","hobby","hockey","hold","hole","holiday","hollow","home","honey","hood","hope","horn","horror","horse","hospital","host","hotel","hour","hover","hub","huge","human","humble","humor","hundred","hungry","hunt","hurdle","hurry","hurt","husband","hybrid","ice","icon","idea","identify","idle","ignore","ill","illegal","illness","image","imitate","immense","immune","impact","impose","improve","impulse","inch","include","income","increase","index","indicate","indoor","industry","infant","inflict","inform","inhale","inherit","initial","inject","injury","inmate","inner","innocent","input","inquiry","insane","insect","inside","inspire","install","intact","interest","into","invest","invite","involve","iron","island","isolate","issue","item","ivory","jacket","jaguar","jar","jazz","jealous","jeans","jelly","jewel","job","join","joke","journey","joy","judge","juice","jump","jungle","junior","junk","just","kangaroo","keen","keep","ketchup","key","kick","kid","kidney","kind","kingdom","kiss","kit","kitchen","kite","kitten","kiwi","knee","knife","knock","know","lab","label","labor","ladder","lady","lake","lamp","language","laptop","large","later","latin","laugh","laundry","lava","law","lawn","lawsuit","layer","lazy","leader","leaf","learn","leave","lecture","left","leg","legal","legend","leisure","lemon","lend","length","lens","leopard","lesson","letter","level","liar","liberty","library","license","life","lift","light","like","limb","limit","link","lion","liquid","list","little","live","lizard","load","loan","lobster","local","lock","logic","lonely","long","loop","lottery","loud","lounge","love","loyal","lucky","luggage","lumber","lunar","lunch","luxury","lyrics","machine","mad","magic","magnet","maid","mail","main","major","make","mammal","man","manage","mandate","mango","mansion","manual","maple","marble","march","margin","marine","market","marriage","mask","mass","master","match","material","math","matrix","matter","maximum","maze","meadow","mean","measure","meat","mechanic","medal","media","melody","melt","member","memory","mention","menu","mercy","merge","merit","merry","mesh","message","metal","method","middle","midnight","milk","million","mimic","mind","minimum","minor","minute","miracle","mirror","misery","miss","mistake","mix","mixed","mixture","mobile","model","modify","mom","moment","monitor","monkey","monster","month","moon","moral","more","morning","mosquito","mother","motion","motor","mountain","mouse","move","movie","much","muffin","mule","multiply","muscle","museum","mushroom","music","must","mutual","myself","mystery","myth","naive","name","napkin","narrow","nasty","nation","nature","near","neck","need","negative","neglect","neither","nephew","nerve","nest","net","network","neutral","never","news","next","nice","night","noble","noise","nominee","noodle","normal","north","nose","notable","note","nothing","notice","novel","now","nuclear","number","nurse","nut","oak","obey","object","oblige","obscure","observe","obtain","obvious","occur","ocean","october","odor","off","offer","office","often","oil","okay","old","olive","olympic","omit","once","one","onion","online","only","open","opera","opinion","oppose","option","orange","orbit","orchard","order","ordinary","organ","orient","original","orphan","ostrich","other","outdoor","outer","output","outside","oval","oven","over","own","owner","oxygen","oyster","ozone","pact","paddle","page","pair","palace","palm","panda","panel","panic","panther","paper","parade","parent","park","parrot","party","pass","patch","path","patient","patrol","pattern","pause","pave","payment","peace","peanut","pear","peasant","pelican","pen","penalty","pencil","people","pepper","perfect","permit","person","pet","phone","photo","phrase","physical","piano","picnic","picture","piece","pig","pigeon","pill","pilot","pink","pioneer","pipe","pistol","pitch","pizza","place","planet","plastic","plate","play","please","pledge","pluck","plug","plunge","poem","poet","point","polar","pole","police","pond","pony","pool","popular","portion","position","possible","post","potato","pottery","poverty","powder","power","practice","praise","predict","prefer","prepare","present","pretty","prevent","price","pride","primary","print","priority","prison","private","prize","problem","process","produce","profit","program","project","promote","proof","property","prosper","protect","proud","provide","public","pudding","pull","pulp","pulse","pumpkin","punch","pupil","puppy","purchase","purity","purpose","purse","push","put","puzzle","pyramid","quality","quantum","quarter","question","quick","quit","quiz","quote","rabbit","raccoon","race","rack","radar","radio","rail","rain","raise","rally","ramp","ranch","random","range","rapid","rare","rate","rather","raven","raw","razor","ready","real","reason","rebel","rebuild","recall","receive","recipe","record","recycle","reduce","reflect","reform","refuse","region","regret","regular","reject","relax","release","relief","rely","remain","remember","remind","remove","render","renew","rent","reopen","repair","repeat","replace","report","require","rescue","resemble","resist","resource","response","result","retire","retreat","return","reunion","reveal","review","reward","rhythm","rib","ribbon","rice","rich","ride","ridge","rifle","right","rigid","ring","riot","ripple","risk","ritual","rival","river","road","roast","robot","robust","rocket","romance","roof","rookie","room","rose","rotate","rough","round","route","royal","rubber","rude","rug","rule","run","runway","rural","sad","saddle","sadness","safe","sail","salad","salmon","salon","salt","salute","same","sample","sand","satisfy","satoshi","sauce","sausage","save","say","scale","scan","scare","scatter","scene","scheme","school","science","scissors","scorpion","scout","scrap","screen","script","scrub","sea","search","season","seat","second","secret","section","security","seed","seek","segment","select","sell","seminar","senior","sense","sentence","series","service","session","settle","setup","seven","shadow","shaft","shallow","share","shed","shell","sheriff","shield","shift","shine","ship","shiver","shock","shoe","shoot","shop","short","shoulder","shove","shrimp","shrug","shuffle","shy","sibling","sick","side","siege","sight","sign","silent","silk","silly","silver","similar","simple","since","sing","siren","sister","situate","six","size","skate","sketch","ski","skill","skin","skirt","skull","slab","slam","sleep","slender","slice","slide","slight","slim","slogan","slot","slow","slush","small","smart","smile","smoke","smooth","snack","snake","snap","sniff","snow","soap","soccer","social","sock","soda","soft","solar","soldier","solid","solution","solve","someone","song","soon","sorry","sort","soul","sound","soup","source","south","space","spare","spatial","spawn","speak","special","speed","spell","spend","sphere","spice","spider","spike","spin","spirit","split","spoil","sponsor","spoon","sport","spot","spray","spread","spring","spy","square","squeeze","squirrel","stable","stadium","staff","stage","stairs","stamp","stand","start","state","stay","steak","steel","stem","step","stereo","stick","still","sting","stock","stomach","stone","stool","story","stove","strategy","street","strike","strong","struggle","student","stuff","stumble","style","subject","submit","subway","success","such","sudden","suffer","sugar","suggest","suit","summer","sun","sunny","sunset","super","supply","supreme","sure","surface","surge","surprise","surround","survey","suspect","sustain","swallow","swamp","swap","swarm","swear","sweet","swift","swim","swing","switch","sword","symbol","symptom","syrup","system","table","tackle","tag","tail","talent","talk","tank","tape","target","task","taste","tattoo","taxi","teach","team","tell","ten","tenant","tennis","tent","term","test","text","thank","that","theme","then","theory","there","they","thing","this","thought","three","thrive","throw","thumb","thunder","ticket","tide","tiger","tilt","timber","time","tiny","tip","tired","tissue","title","toast","tobacco","today","toddler","toe","together","toilet","token","tomato","tomorrow","tone","tongue","tonight","tool","tooth","top","topic","topple","torch","tornado","tortoise","toss","total","tourist","toward","tower","town","toy","track","trade","traffic","tragic","train","transfer","trap","trash","travel","tray","treat","tree","trend","trial","tribe","trick","trigger","trim","trip","trophy","trouble","truck","true","truly","trumpet","trust","truth","try","tube","tuition","tumble","tuna","tunnel","turkey","turn","turtle","twelve","twenty","twice","twin","twist","two","type","typical","ugly","umbrella","unable","unaware","uncle","uncover","under","undo","unfair","unfold","unhappy","uniform","unique","unit","universe","unknown","unlock","until","unusual","unveil","update","upgrade","uphold","upon","upper","upset","urban","urge","usage","use","used","useful","useless","usual","utility","vacant","vacuum","vague","valid","valley","valve","van","vanish","vapor","various","vast","vault","vehicle","velvet","vendor","venture","venue","verb","verify","version","very","vessel","veteran","viable","vibrant","vicious","victory","video","view","village","vintage","violin","virtual","virus","visa","visit","visual","vital","vivid","vocal","voice","void","volcano","volume","vote","voyage","wage","wagon","wait","walk","wall","walnut","want","warfare","warm","warrior","wash","wasp","waste","water","wave","way","wealth","weapon","wear","weasel","weather","web","wedding","weekend","weird","welcome","west","wet","whale","what","wheat","wheel","when","where","whip","whisper","wide","width","wife","wild","will","win","window","wine","wing","wink","winner","winter","wire","wisdom","wise","wish","witness","wolf","woman","wonder","wood","wool","word","work","world","worry","worth","wrap","wreck","wrestle","wrist","write","wrong","yard","year","yellow","you","young","youth","zebra","zero","zone","zoo"];var pt=[0,7,14,9,28,27,18,21,56,63,54,49,36,35,42,45,112,119,126,121,108,107,98,101,72,79,70,65,84,83,90,93,224,231,238,233,252,251,242,245,216,223,214,209,196,195,202,205,144,151,158,153,140,139,130,133,168,175,166,161,180,179,186,189,199,192,201,206,219,220,213,210,255,248,241,246,227,228,237,234,183,176,185,190,171,172,165,162,143,136,129,134,147,148,157,154,39,32,41,46,59,60,53,50,31,24,17,22,3,4,13,10,87,80,89,94,75,76,69,66,111,104,97,102,115,116,125,122,137,142,135,128,149,146,155,156,177,182,191,184,173,170,163,164,249,254,247,240,229,226,235,236,193,198,207,200,221,218,211,212,105,110,103,96,117,114,123,124,81,86,95,88,77,74,67,68,25,30,23,16,5,2,11,12,33,38,47,40,61,58,51,52,78,73,64,71,82,85,92,91,118,113,120,127,106,109,100,99,62,57,48,55,34,37,44,43,6,1,8,15,26,29,20,19,174,169,160,167,178,181,188,187,150,145,152,159,138,141,132,131,222,217,208,215,194,197,204,203,230,225,232,239,250,253,244,243];typeof Int32Array<"u"&&(pt=new Int32Array(pt));function Nt(a,e=0){let t=~~e;for(let s=0;sisNaN(n)).map(n=>e[n]).map(n=>typeof n=="string"?{[H]:"Literal",type:"string",const:n}:{[H]:"Literal",type:"number",const:n});return this.Create({...t,[H]:"Union",[Ce]:"Enum",anyOf:r})}Function(e,t,s={}){if(e[H]==="Tuple"){let r=e.items===void 0?[]:e.items;return this.Create({...s,[H]:"Function",type:"object",instanceOf:"Function",parameters:r,returns:t})}else{if(globalThis.Array.isArray(e))return this.Create({...s,[H]:"Function",type:"object",instanceOf:"Function",parameters:e,returns:t});throw new Error("TypeBuilder.Function: Invalid parameters")}}InstanceType(e,t={}){return{...t,...this.Clone(e.returns)}}Integer(e={}){return this.Create({...e,[H]:"Integer",type:"integer"})}Intersect(e,t={}){let s=c=>c[L]&&c[L]==="Optional"||c[L]==="ReadonlyOptional",[r,n]=[new Set,new Set];for(let c of e)for(let[u,l]of Object.entries(c.properties))s(l)&&n.add(u);for(let c of e)for(let u of Object.keys(c.properties))n.has(u)||r.add(u);let o={};for(let c of e)for(let[u,l]of Object.entries(c.properties))o[u]=o[u]===void 0?l:{[H]:"Union",anyOf:[o[u],{...l}]};return r.size>0?this.Create({...t,[H]:"Object",type:"object",properties:o,required:[...r]}):this.Create({...t,[H]:"Object",type:"object",properties:o})}KeyOf(e,t={}){let s=Object.keys(e.properties).map(r=>this.Create({...t,[H]:"Literal",type:"string",const:r}));return this.Create({...t,[H]:"Union",[Ce]:"KeyOf",anyOf:s})}Literal(e,t={}){return this.Create({...t,[H]:"Literal",const:e,type:typeof e})}Never(e={}){return this.Create({...e,[H]:"Never",allOf:[{type:"boolean",const:!1},{type:"boolean",const:!0}]})}Null(e={}){return this.Create({...e,[H]:"Null",type:"null"})}Number(e={}){return this.Create({...e,[H]:"Number",type:"number"})}Object(e,t={}){let s=Object.keys(e),r=s.filter(o=>{let u=e[o][L];return u&&(u==="Optional"||u==="ReadonlyOptional")}),n=s.filter(o=>!r.includes(o));return n.length>0?this.Create({...t,[H]:"Object",type:"object",properties:e,required:n}):this.Create({...t,[H]:"Object",type:"object",properties:e})}Omit(e,t,s={}){let r=t[H]==="Union"?t.anyOf.map(o=>o.const):t,n={...this.Clone(e),...s,[Ce]:"Omit"};n.required&&(n.required=n.required.filter(o=>!r.includes(o)),n.required.length===0&&delete n.required);for(let o of Object.keys(n.properties))r.includes(o)&&delete n.properties[o];return this.Create(n)}Parameters(e,t={}){return W.Tuple(e.parameters,{...t})}Partial(e,t={}){let s={...this.Clone(e),...t,[Ce]:"Partial"};delete s.required;for(let r of Object.keys(s.properties)){let n=s.properties[r];switch(n[L]){case"ReadonlyOptional":n[L]="ReadonlyOptional";break;case"Readonly":n[L]="ReadonlyOptional";break;case"Optional":n[L]="Optional";break;default:n[L]="Optional";break}}return this.Create(s)}Pick(e,t,s={}){let r=t[H]==="Union"?t.anyOf.map(o=>o.const):t,n={...this.Clone(e),...s,[Ce]:"Pick"};n.required&&(n.required=n.required.filter(o=>r.includes(o)),n.required.length===0&&delete n.required);for(let o of Object.keys(n.properties))r.includes(o)||delete n.properties[o];return this.Create(n)}Promise(e,t={}){return this.Create({...t,[H]:"Promise",type:"object",instanceOf:"Promise",item:e})}Record(e,t,s={}){if(e[H]==="Union")return this.Object(e.anyOf.reduce((n,o)=>({...n,[o.const]:t}),{}),{...s,[Ce]:"Record"});let r=["Integer","Number"].includes(e[H])?"^(0|[1-9][0-9]*)$":e[H]==="String"&&e.pattern?e.pattern:"^.*$";return this.Create({...s,[H]:"Record",type:"object",patternProperties:{[r]:t},additionalProperties:!1})}Recursive(e,t={}){t.$id===void 0&&(t.$id=`T${ws++}`);let s=e({[H]:"Self",$ref:`${t.$id}`});return s.$id=t.$id,this.Create({...t,...s})}Ref(e,t={}){if(e.$id===void 0)throw Error("TypeBuilder.Ref: Referenced schema must specify an $id");return this.Create({...t,[H]:"Ref",$ref:e.$id})}RegEx(e,t={}){return this.Create({...t,[H]:"String",type:"string",pattern:e.source})}Required(e,t={}){let s={...this.Clone(e),...t,[Ce]:"Required"};s.required=Object.keys(s.properties);for(let r of Object.keys(s.properties)){let n=s.properties[r];switch(n[L]){case"ReadonlyOptional":n[L]="Readonly";break;case"Readonly":n[L]="Readonly";break;case"Optional":delete n[L];break;default:delete n[L];break}}return this.Create(s)}ReturnType(e,t={}){return{...t,...this.Clone(e.returns)}}Strict(e){return JSON.parse(JSON.stringify(e))}String(e={}){return this.Create({...e,[H]:"String",type:"string"})}Tuple(e,t={}){let r=e.length,n=e.length,o=e.length>0?{...t,[H]:"Tuple",type:"array",items:e,additionalItems:!1,minItems:r,maxItems:n}:{...t,[H]:"Tuple",type:"array",minItems:r,maxItems:n};return this.Create(o)}Undefined(e={}){return this.Create({...e,[H]:"Undefined",type:"null",typeOf:"Undefined"})}Union(e,t={}){return e.length===0?W.Never({...t}):this.Create({...t,[H]:"Union",anyOf:e})}Uint8Array(e={}){return this.Create({...e,[H]:"Uint8Array",type:"object",instanceOf:"Uint8Array"})}Unknown(e={}){return this.Create({...e,[H]:"Unknown"})}Unsafe(e={}){return this.Create({...e,[H]:e[H]||"Unsafe"})}Void(e={}){return this.Create({...e,[H]:"Void",type:"null",typeOf:"Void"})}Create(e){return e}Clone(e){let t=r=>typeof r=="object"&&r!==null&&!Array.isArray(r),s=r=>typeof r=="object"&&r!==null&&Array.isArray(r);return t(e)?Object.keys(e).reduce((r,n)=>({...r,[n]:this.Clone(e[n])}),Object.getOwnPropertySymbols(e).reduce((r,n)=>({...r,[n]:this.Clone(e[n])}),{})):s(e)?e.map(r=>this.Clone(r)):e}},W=new mt;var z=class{constructor(e,t){Object.defineProperty(this,"index",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"fields",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.index=e,this.fields=t}},pe={Integer:function(a){let e=W.Unsafe({dataType:"integer"});return a&&Object.entries(a).forEach(([t,s])=>{e[t]=s}),e},Bytes:function(a){let e=W.Unsafe({dataType:"bytes"});return a&&Object.entries(a).forEach(([t,s])=>{e[t]=s}),e},Boolean:function(){return W.Unsafe({anyOf:[{title:"False",dataType:"constructor",index:0,fields:[]},{title:"True",dataType:"constructor",index:1,fields:[]}]})},Any:function(){return W.Unsafe({description:"Any Data."})},Array:function(a,e){let t=W.Array(a);return qe(t,{dataType:"list",items:a}),e&&Object.entries(e).forEach(([s,r])=>{t[s]=r}),t},Map:function(a,e,t){let s=W.Unsafe({dataType:"map",keys:a,values:e});return t&&Object.entries(t).forEach(([r,n])=>{s[r]=n}),s},Object:function(a,e){let t=W.Object(a);return qe(t,{anyOf:[{dataType:"constructor",index:0,fields:Object.entries(a).map(([s,r])=>({...r,title:s}))}]}),t.anyOf[0].hasConstr=typeof e?.hasConstr>"u"||e.hasConstr,t},Enum:function(a){let e=W.Union(a);return qe(e,{anyOf:a.map((t,s)=>t.anyOf[0].fields.length===0?{...t.anyOf[0],index:s}:{dataType:"constructor",title:(()=>{let r=t.anyOf[0].fields[0].title;if(r.charAt(0)!==r.charAt(0).toUpperCase())throw new Error(`Enum '${r}' needs to start with an uppercase letter.`);return t.anyOf[0].fields[0].title})(),index:s,fields:t.anyOf[0].fields[0].items||t.anyOf[0].fields[0].anyOf[0].fields})}),e},Tuple:function(a,e){let t=W.Tuple(a);return qe(t,{dataType:"list",items:a}),e&&Object.entries(e).forEach(([s,r])=>{t[s]=r}),t},Literal:function(a){if(a.charAt(0)!==a.charAt(0).toUpperCase())throw new Error(`Enum '${a}' needs to start with an uppercase letter.`);let e=W.Literal(a);return qe(e,{anyOf:[{dataType:"constructor",title:a,index:0,fields:[]}]}),e},Nullable:function(a){return W.Unsafe({anyOf:[{title:"Some",description:"An optional value.",dataType:"constructor",index:0,fields:[a]},{title:"None",description:"Nothing.",dataType:"constructor",index:1,fields:[]}]})},to:bs,from:_s,fromJson:ks,toJson:vs,void:function(){return"d87980"},castFrom:Y,castTo:te};function bs(a,e){function t(o){let c=[];try{if(typeof o=="bigint"){let u=i.BigInt.from_str(o.toString());return c.push(u),i.PlutusData.new_integer(u)}else{if(typeof o=="string")return i.PlutusData.new_bytes(g(o));if(o instanceof z){let{index:u,fields:l}=o,d=i.PlutusList.new();c.push(d),l.forEach(m=>{let S=t(m);d.add(S),c.push(S)});let h=i.BigNum.from_str(u.toString());c.push(h);let f=i.ConstrPlutusData.new(h,d);return c.push(f),i.PlutusData.new_constr_plutus_data(f)}else if(o instanceof Array){let u=i.PlutusList.new();return c.push(u),o.forEach(l=>{let d=t(l);u.add(d),c.push(d)}),i.PlutusData.new_list(u)}else if(o instanceof Map){let u=i.PlutusMap.new();c.push(u);for(let[l,d]of o.entries()){let h=t(l);c.push(h);let f=t(d);c.push(f),u.insert(h,f)}return i.PlutusData.new_map(u)}}throw new Error("Unsupported type")}catch(u){throw new Error("Could not serialize the data: "+u)}finally{_.free(...c)}}let s=e?te(a,e):a,r=t(s),n=b(r.to_bytes());return r.free(),n}function _s(a,e){function t(n){let o=[];try{if(n.kind()===0){let c=n.as_constr_plutus_data();o.push(c);let u=c.data();o.push(u);let l=[];for(let h=0;he(s));if(t instanceof Object){let s=new Map;return Object.entries(t).forEach(([r,n])=>{s.set(e(r),e(n))}),s}throw new Error("Unsupported type")}return e(a)}function vs(a){function e(t){if(typeof t=="bigint"||typeof t=="number"||typeof t=="string"&&!isNaN(parseInt(t))&&t.slice(-1)==="n"){let s=typeof t=="string"?BigInt(t.slice(0,-1)):t;return parseInt(s.toString())}if(typeof t=="string")try{return new TextDecoder(void 0,{fatal:!0}).decode(g(t))}catch{return"0x"+b(g(t))}if(t instanceof Array)return t.map(s=>e(s));if(t instanceof Map){let s={};return t.forEach((r,n)=>{let o=e(n);if(typeof o!="string"&&typeof o!="number")throw new Error("Unsupported type (Note: Only bytes or integers can be keys of a JSON object)");s[o]=e(r)}),s}throw new Error("Unsupported type (Note: Constructor cannot be converted to JSON)")}return e(a)}function Y(a,e){let t=e;if(!t)throw new Error("Could not type cast data.");switch((t.anyOf?"enum":"")||t.dataType){case"integer":{if(typeof a!="bigint")throw new Error("Could not type cast to integer.");return Rt(a,t),a}case"bytes":{if(typeof a!="string")throw new Error("Could not type cast to bytes.");return Mt(a,t),a}case"constructor":{if(Lt(t)){if(!(a instanceof z)||a.index!==0||a.fields.length!==0)throw new Error("Could not type cast to void.");return}else if(a instanceof z&&a.index===t.index&&(t.hasConstr||t.hasConstr===void 0)){let r={};if(t.fields.length!==a.fields.length)throw new Error("Could not type cast to object. Fields do not match.");return t.fields.forEach((n,o)=>{let c=n.title||"wrapper";if(/[A-Z]/.test(c[0]))throw new Error("Could not type cast to object. Object properties need to start with a lowercase letter.");r[c]=Y(a.fields[o],n)}),r}else if(a instanceof Array&&!t.hasConstr&&t.hasConstr!==void 0){let r={};if(t.fields.length!==a.length)throw new Error("Could not ype cast to object. Fields do not match.");return t.fields.forEach((n,o)=>{let c=n.title||"wrapper";if(/[A-Z]/.test(c[0]))throw new Error("Could not type cast to object. Object properties need to start with a lowercase letter.");r[c]=Y(a[o],n)}),r}throw new Error("Could not type cast to object.")}case"enum":{if(t.anyOf.length===1)return Y(a,t.anyOf[0]);if(!(a instanceof z))throw new Error("Could not type cast to enum.");let r=t.anyOf.find(n=>n.index===a.index);if(!r||r.fields.length!==a.fields.length)throw new Error("Could not type cast to enum.");if(Kt(t)){if(a.fields.length!==0)throw new Error("Could not type cast to boolean.");switch(a.index){case 0:return!1;case 1:return!0}throw new Error("Could not type cast to boolean.")}else if(zt(t)){switch(a.index){case 0:{if(a.fields.length!==1)throw new Error("Could not type cast to nullable object.");return Y(a.fields[0],t.anyOf[0].fields[0])}case 1:{if(a.fields.length!==0)throw new Error("Could not type cast to nullable object.");return null}}throw new Error("Could not type cast to nullable object.")}switch(r.dataType){case"constructor":if(r.fields.length===0){if(/[A-Z]/.test(r.title[0]))return r.title;throw new Error("Could not type cast to enum.")}else{if(!/[A-Z]/.test(r.title))throw new Error("Could not type cast to enum. Enums need to start with an uppercase letter.");if(r.fields.length!==a.fields.length)throw new Error("Could not type cast to enum.");let n=r.fields[0].title?Object.fromEntries(r.fields.map((o,c)=>[o.title,Y(a.fields[c],o)])):r.fields.map((o,c)=>Y(a.fields[c],o));return{[r.title]:n}}}throw new Error("Could not type cast to enum.")}case"list":if(t.items instanceof Array){if(a instanceof z&&a.index===0&&t.hasConstr)return a.fields.map((r,n)=>Y(r,t.items[n]));if(a instanceof Array&&!t.hasConstr)return a.map((r,n)=>Y(r,t.items[n]));throw new Error("Could not type cast to tuple.")}else{if(!(a instanceof Array))throw new Error("Could not type cast to array.");return $t(a,t),a.map(r=>Y(r,t.items))}case"map":{if(!(a instanceof Map))throw new Error("Could not type cast to map.");qt(a,t);let r=new Map;for(let[n,o]of a.entries())r.set(Y(n,t.keys),Y(o,t.values));return r}case void 0:return a}throw new Error("Could not type cast data.")}function te(a,e){let t=e;if(!t)throw new Error("Could not type cast struct.");switch((t.anyOf?"enum":"")||t.dataType){case"integer":{if(typeof a!="bigint")throw new Error("Could not type cast to integer.");return Rt(a,t),a}case"bytes":{if(typeof a!="string")throw new Error("Could not type cast to bytes.");return Mt(a,t),a}case"constructor":{if(Lt(t)){if(a!==void 0)throw new Error("Could not type cast to void.");return new z(0,[])}else if(typeof a!="object"||a===null||t.fields.length!==Object.keys(a).length)throw new Error("Could not type cast to constructor.");let r=t.fields.map(n=>te(a[n.title||"wrapper"],n));return t.hasConstr||t.hasConstr===void 0?new z(t.index,r):r}case"enum":{if(t.anyOf.length===1)return te(a,t.anyOf[0]);if(Kt(t)){if(typeof a!="boolean")throw new Error("Could not type cast to boolean.");return new z(a?1:0,[])}else if(zt(t)){if(a===null)return new z(1,[]);{let r=t.anyOf[0].fields;if(r.length!==1)throw new Error("Could not type cast to nullable object.");return new z(0,[te(a,r[0])])}}switch(typeof a){case"string":{if(!/[A-Z]/.test(a[0]))throw new Error("Could not type cast to enum. Enum needs to start with an uppercase letter.");let r=t.anyOf.findIndex(n=>n.dataType==="constructor"&&n.fields.length===0&&n.title===a);if(r===-1)throw new Error("Could not type cast to enum.");return new z(r,[])}case"object":{if(a===null)throw new Error("Could not type cast to enum.");let r=Object.keys(a)[0];if(!/[A-Z]/.test(r))throw new Error("Could not type cast to enum. Enum needs to start with an uppercase letter.");let n=t.anyOf.find(c=>c.dataType==="constructor"&&c.title===r);if(!n)throw new Error("Could not type cast to enum.");let o=a[r];return new z(n.index,o instanceof Array?o.map((c,u)=>te(c,n.fields[u])):n.fields.map(c=>{let[u,l]=Object.entries(o).find(([d])=>d===c.title);return te(l,c)}))}}throw new Error("Could not type cast to enum.")}case"list":{if(!(a instanceof Array))throw new Error("Could not type cast to array/tuple.");if(t.items instanceof Array){let r=a.map((n,o)=>te(n,t.items[o]));return t.hasConstr?new z(0,r):r}else return $t(a,t),a.map(r=>te(r,t.items))}case"map":{if(!(a instanceof Map))throw new Error("Could not type cast to map.");qt(a,t);let r=new Map;for(let[n,o]of a.entries())r.set(te(n,t.keys),te(o,t.values));return r}case void 0:return a}throw new Error("Could not type cast struct.")}function Rt(a,e){if(e.minimum&&aBigInt(e.maximum))throw new Error(`Integer ${a} is above the maxiumum ${e.maximum}.`);if(e.exclusiveMinimum&&a<=BigInt(e.exclusiveMinimum))throw new Error(`Integer ${a} is below the exclusive minimum ${e.exclusiveMinimum}.`);if(e.exclusiveMaximum&&a>=BigInt(e.exclusiveMaximum))throw new Error(`Integer ${a} is above the exclusive maximum ${e.exclusiveMaximum}.`)}function Mt(a,e){if(e.enum&&!e.enum.some(t=>t===a))throw new Error(`None of the keywords match with '${a}'.`);if(e.minLength&&a.length/2e.maxLength)throw new Error(`Bytes can have a length of at most ${e.minLength} bytes.`)}function $t(a,e){if(e.minItems&&a.lengthe.maxItems)throw new Error(`Array can contain at most ${e.maxItems} items.`);if(e.uniqueItems&&new Set(a).size!==a.length)throw new Error("Array constains duplicates.")}function qt(a,e){if(e.minItems&&a.sizee.maxItems)throw new Error(`Map can contain at most ${e.maxItems} items.`)}function Kt(a){return a.anyOf&&a.anyOf[0]?.title==="False"&&a.anyOf[1]?.title==="True"}function Lt(a){return a.index===0&&a.fields.length===0}function zt(a){return a.anyOf&&a.anyOf[0]?.title==="Some"&&a.anyOf[1]?.title==="None"}function qe(a,e){Object.keys(a).forEach(t=>{delete a[t]}),Object.assign(a,e)}var Ge=class{constructor(e){Object.defineProperty(this,"lucid",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.lucid=e}validatorToAddress(e,t){let s=[],r=Oe(this.lucid.network);try{let n=this.validatorToScriptHash(e);if(t){let o=i.ScriptHash.from_hex(n);s.push(o);let c=i.StakeCredential.from_scripthash(o);s.push(c);let u;if(t.type==="Key"){let h=i.Ed25519KeyHash.from_hex(t.hash);u=i.StakeCredential.from_keyhash(h),h.free()}else{let h=i.ScriptHash.from_hex(t.hash);u=i.StakeCredential.from_scripthash(h),h.free()}s.push(u);let l=i.BaseAddress.new(r,c,u);s.push(l);let d=l.to_address();return s.push(d),d.to_bech32(void 0)}else{let o=i.ScriptHash.from_hex(n);s.push(o);let c=i.StakeCredential.from_scripthash(o);s.push(c);let u=i.EnterpriseAddress.new(r,c);s.push(u);let l=u.to_address();return s.push(l),l.to_bech32(void 0)}}finally{_.free(...s)}}credentialToAddress(e,t){let s=Oe(this.lucid.network),r=[];try{if(t){let n,o;if(e.type==="Key"){let l=i.Ed25519KeyHash.from_hex(e.hash);r.push(l),n=i.StakeCredential.from_keyhash(l)}else{let l=i.ScriptHash.from_hex(e.hash);r.push(l),n=i.StakeCredential.from_scripthash(l)}if(r.push(n),t.type==="Key"){let l=i.Ed25519KeyHash.from_hex(t.hash);r.push(l),o=i.StakeCredential.from_keyhash(l)}else{let l=i.ScriptHash.from_hex(t.hash);r.push(l),o=i.StakeCredential.from_scripthash(l)}r.push(o);let c=i.BaseAddress.new(s,n,o);r.push(c);let u=c.to_address();return r.push(u),u.to_bech32(void 0)}else{let n;if(e.type==="Key"){let u=i.Ed25519KeyHash.from_hex(e.hash);r.push(u),n=i.StakeCredential.from_keyhash(u)}else{let u=i.ScriptHash.from_hex(e.hash);r.push(u),n=i.StakeCredential.from_scripthash(u)}r.push(n);let o=i.EnterpriseAddress.new(s,n);r.push(o);let c=o.to_address();return r.push(c),c.to_bech32(void 0)}}finally{_.free(...r)}}validatorToRewardAddress(e){let t=[],s=this.validatorToScriptHash(e),r=i.ScriptHash.from_hex(s);t.push(r);let n=i.StakeCredential.from_scripthash(r);t.push(n);let o=i.RewardAddress.new(Oe(this.lucid.network),n);t.push(o);let c=o.to_address();t.push(c);let u=c.to_bech32(void 0);return _.free(...t),u}credentialToRewardAddress(e){let t=[],s;if(e.type==="Key"){let c=i.Ed25519KeyHash.from_hex(e.hash);t.push(c),s=i.StakeCredential.from_keyhash(c)}else{let c=i.ScriptHash.from_hex(e.hash);t.push(c),s=i.StakeCredential.from_scripthash(c)}t.push(s);let r=i.RewardAddress.new(Oe(this.lucid.network),s);t.push(r);let n=r.to_address();t.push(n);let o=n.to_bech32(void 0);return _.free(...t),o}validatorToScriptHash(e){let t=[];try{switch(e.type){case"Native":{let s=i.NativeScript.from_bytes(g(e.script));t.push(s);let r=s.hash(i.ScriptHashNamespace.NativeScript);return t.push(r),r.to_hex()}case"PlutusV1":{let s=i.PlutusScript.from_bytes(g(Z(e.script)));t.push(s);let r=s.hash(i.ScriptHashNamespace.PlutusV1);return t.push(r),r.to_hex()}case"PlutusV2":{let s=i.PlutusScript.from_bytes(g(Z(e.script)));t.push(s);let r=s.hash(i.ScriptHashNamespace.PlutusV2);return t.push(r),r.to_hex()}default:throw new Error("No variant matched")}}finally{_.free(...t)}}mintingPolicyToId(e){return this.validatorToScriptHash(e)}datumToHash(e){let t=i.PlutusData.from_bytes(g(e)),s=i.hash_plutus_data(t);t.free();let r=s.to_hex();return s.free(),r}scriptHashToCredential(e){return{type:"Script",hash:e}}keyHashToCredential(e){return{type:"Key",hash:e}}generatePrivateKey(){return Is()}generateSeedPhrase(){return Cs()}unixTimeToSlot(e){return Dt(e,He[this.lucid.network])}slotToUnixTime(e){return jt(e,He[this.lucid.network])}getAddressDetails(e){return J(e)}nativeScriptFromJson(e){return Ps(e)}paymentCredentialOf(e){return ye(e)}stakeCredentialOf(e){return Ss(e)}getMinAdaForOutput(e){let t=i.min_ada_required(e,i.BigNum.from_str(this.lucid.protocolParameters.coinsPerUtxoByte.toString()));return BigInt(t.to_str()).valueOf()}};function Ze(a){try{return i.Address.from_bytes(g(a))}catch{try{return i.Address.from_bech32(a)}catch{throw new Error("Could not deserialize address.")}}}function J(a){let e=[];try{try{let t=Ze(a);e.push(t);let s=i.BaseAddress.from_address(t);e.push(s);let r,n=s.payment_cred();if(e.push(n),n.kind()===0){let l=n.to_keyhash();e.push(l),r={type:"Key",hash:b(l.to_bytes())}}else{let l=n.to_scripthash();e.push(l),r={type:"Script",hash:b(l.to_bytes())}}let o,c=s.stake_cred();if(e.push(c),c.kind()===0){let l=c.to_keyhash();e.push(l),o={type:"Key",hash:b(l.to_bytes())}}else{let l=c.to_scripthash();e.push(l),o={type:"Script",hash:b(l.to_bytes())}}let u=s.to_address();return e.push(u),{type:"Base",networkId:u.network_id(),address:{bech32:u.to_bech32(void 0),hex:b(u.to_bytes())},paymentCredential:r,stakeCredential:o}}catch{}try{let t=Ze(a);e.push(t);let s=i.EnterpriseAddress.from_address(t);e.push(s);let r,n=s.payment_cred();if(e.push(n),n.kind()===0){let c=n.to_keyhash();e.push(c),r={type:"Key",hash:b(c.to_bytes())}}else{let c=n.to_scripthash();e.push(c),r={type:"Script",hash:b(c.to_bytes())}}let o=s.to_address();return e.push(o),{type:"Enterprise",networkId:o.network_id(),address:{bech32:o.to_bech32(void 0),hex:b(o.to_bytes())},paymentCredential:r}}catch{}try{let t=Ze(a);e.push(t);let s=i.PointerAddress.from_address(t);e.push(s);let r,n=s.payment_cred();if(e.push(n),n.kind()===0){let c=n.to_keyhash();e.push(c),r={type:"Key",hash:b(c.to_bytes())}}else{let c=n.to_scripthash();e.push(c),r={type:"Script",hash:b(c.to_bytes())}}let o=s.to_address();return e.push(o),{type:"Pointer",networkId:o.network_id(),address:{bech32:o.to_bech32(void 0),hex:b(o.to_bytes())},paymentCredential:r}}catch{}try{let t=Ze(a);e.push(t);let s=i.RewardAddress.from_address(t);e.push(s);let r,n=s.payment_cred();if(e.push(n),n.kind()===0){let c=n.to_keyhash();e.push(c),r={type:"Key",hash:b(c.to_bytes())}}else{let c=n.to_scripthash();e.push(c),r={type:"Script",hash:b(c.to_bytes())}}let o=s.to_address();return e.push(o),{type:"Reward",networkId:o.network_id(),address:{bech32:o.to_bech32(void 0),hex:b(o.to_bytes())},stakeCredential:r}}catch{}try{let t=(r=>{try{return i.ByronAddress.from_bytes(g(r))}catch{try{return i.ByronAddress.from_base58(r)}catch{throw new Error("Could not deserialize address.")}}})(a);e.push(t);let s=t.to_address();return e.push(s),{type:"Byron",networkId:t.network_id(),address:{bech32:"",hex:b(s.to_bytes())}}}catch{}throw new Error("No address type matched for: "+a)}finally{_.free(...e)}}function ye(a){let{paymentCredential:e}=J(a);if(!e)throw new Error("The specified address does not contain a payment credential.");return e}function Ss(a){let{stakeCredential:e}=J(a);if(!e)throw new Error("The specified address does not contain a stake credential.");return e}function Is(){let a=i.PrivateKey.generate_ed25519(),e=a.to_bech32();return a.free(),e}function Cs(){return Tt(256)}function ft(a){let e=[],t={},s=a.coin();e.push(s),t.lovelace=BigInt(s.to_str());let r=a.multiasset();if(e.push(r),r){let n=r.keys();e.push(n);for(let o=0;ou!=="lovelace").map(u=>u.slice(0,56)))).forEach(u=>{let l=r.filter(f=>f.slice(0,56)===u),d=i.Assets.new();l.forEach(f=>{let m=i.AssetName.new(g(f.slice(56)));e.push(m);let S=i.BigNum.from_str(a[f].toString());e.push(S),d.insert(m,S)});let h=i.ScriptHash.from_bytes(g(u));e.push(h),t.insert(h,d)});let o=i.BigNum.from_str(s?s.toString():"0");e.push(o);let c=i.Value.new(o);return(r.length>1||!s)&&c.set_multiasset(t),_.free(...e),c}function Es(a){let e=[];try{let t=a.get();switch(e.push(t),t.kind()){case 0:{let r=t.as_native();return e.push(r),{type:"Native",script:b(r.to_bytes())}}case 1:{let r=t.as_plutus_v1();return e.push(r),{type:"PlutusV1",script:b(r.to_bytes())}}case 2:{let r=t.as_plutus_v2();return e.push(r),{type:"PlutusV2",script:b(r.to_bytes())}}default:throw new Error("No variant matched.")}}finally{_.free(...e)}}function Qe(a){let e=[];try{switch(a.type){case"Native":{let t=i.NativeScript.from_bytes(g(a.script));e.push(t);let s=i.Script.new_native(t);return e.push(s),i.ScriptRef.new(s)}case"PlutusV1":{let t=i.PlutusScript.from_bytes(g(Z(a.script)));e.push(t);let s=i.Script.new_plutus_v1(t);return e.push(s),i.ScriptRef.new(s)}case"PlutusV2":{let t=i.PlutusScript.from_bytes(g(Z(a.script)));e.push(t);let s=i.Script.new_plutus_v2(t);return e.push(s),i.ScriptRef.new(s)}default:throw new Error("No variant matched.")}}finally{_.free(...e)}}function we(a){let e=[],t=(()=>{try{return console.log("success"),i.Address.from_bech32(a.address)}catch{let d=i.ByronAddress.from_base58(a.address);return e.push(d),d.to_address()}})();e.push(t);let s=xe(a.assets);e.push(s);let r=i.TransactionOutput.new(t,s);if(e.push(r),a.datumHash){let l=i.DataHash.from_bytes(g(a.datumHash));e.push(l);let d=i.Datum.new_data_hash(l);e.push(d),r.set_datum(d)}if(!a.datumHash&&a.datum){let l=i.PlutusData.from_bytes(g(a.datum));e.push(l);let d=i.Data.new(l);e.push(d);let h=i.Datum.new_data(d);e.push(h),r.set_datum(h)}if(a.scriptRef){let l=Qe(a.scriptRef);e.push(l),r.set_script_ref(l)}let n=i.TransactionHash.from_bytes(g(a.txHash));e.push(n);let o=i.BigNum.from_str(a.outputIndex.toString());e.push(o);let c=i.TransactionInput.new(n,o);e.push(c);let u=i.TransactionUnspentOutput.new(c,r);return _.free(...e),u}function et(a){let e=[],t=a.input();e.push(t);let s=a.output();e.push(s);let r=t.transaction_id();e.push(r);let n=b(r.to_bytes()),o=t.index();e.push(o);let c=parseInt(o.to_str()),u=s.amount();e.push(u);let l=ft(u),d=s.address();e.push(d);let h=d.as_byron();e.push(h);let f=h?h.to_base58():d.to_bech32(void 0),m=s.datum();e.push(m);let S=m?.as_data_hash();e.push(S);let v=S?.to_hex(),y=m?.as_data();e.push(y);let B=y?.get();e.push(B);let I=B&&b(B.to_bytes()),N=s.script_ref();e.push(N);let T=N&&Es(N),$={txHash:n,outputIndex:c,assets:l,address:f,datumHash:v,datum:I,scriptRef:T};return _.free(...e),$}function Oe(a){switch(a){case"Preview":return 0;case"Preprod":return 0;case"Custom":return 0;case"Mainnet":return 1;default:throw new Error("Network not found")}}function g(a){return It(a)}function b(a){return St(a)}function ur(a){return new TextDecoder().decode(ht(new TextEncoder().encode(a)))}function Ft(a){return b(new TextEncoder().encode(a))}function lr(a){let e=i.PrivateKey.from_bech32(a),t=e.to_public(),s=t.to_bech32();return _.free(e,t),s}function Vt(a){return Nt(g(a)).toString(16).padStart(2,"0")}function Bs(a){if(a<0||a>65535)throw new Error(`Label ${a} out of range: min label 1 - max label 65535.`);let e=a.toString(16).padStart(4,"0");return"0"+e+Vt(e)+"0"}function Ts(a){if(a.length!==8||!(a[0]==="0"&&a[7]==="0"))return null;let e=a.slice(1,5),t=parseInt(e,16);return a.slice(5,7)===Vt(e)?t:null}function Wt(a,e,t){let s=Number.isInteger(t)?Bs(t):"",r=e||"";if((r+s).length>64)throw new Error("Asset name size exceeds 32 bytes.");if(a.length!==56)throw new Error(`Policy id invalid: ${a}.`);return a+s+r}function Ke(a){let e=a.slice(0,56),t=a.slice(56)||null,s=Ts(a.slice(56,64)),r=(()=>(Number.isInteger(s)?a.slice(64):a.slice(56))||null)();return{policyId:e,assetName:t,name:r,label:s}}function Ps(a){let e=i.encode_json_str_to_native_script(JSON.stringify(a),"",i.ScriptSchema.Node),t=b(e.to_bytes());return e.free(),{type:"Native",script:t}}function dr(a,e,t){let s=t?pe.castTo(e,t):e,r=i.PlutusScript.from_bytes(g(Z(a))),n=i.PlutusList.from_bytes(g(pe.to(s))),o=i.apply_params_to_plutus_script(n,r),c=b(o.to_bytes());return _.free(n,o),c}var Jt=(a,e)=>{let t=[],s=a.length,r=0;for(;r{for(let s in t)Object.hasOwn(t,s)&&(e[s]=(e[s]||0n)+t[s]);return e},{})}function As(a,e){if(a.length!==e.length)return!1;for(let t=0;tst(t)))}static fromHashes(e){return new this(e)}static buildRecursively(e){if(e.length<=0)return null;if(e.length===1)return{node:e[0],left:null,right:null};let t=Math.floor(e.length/2),[s,r]=[e.slice(0,t),e.slice(t)],n=this.buildRecursively(s),o=this.buildRecursively(r);return n===null||o===null?null:{node:gt(n.node,o.node),left:n,right:o}}rootHash(){if(this.root===null)throw new Error("Merkle tree root hash not found.");return this.root.node}getProof(e){let t=st(e),s=[],r=n=>{if(n&&tt(n.node,t))return!0;if(n?.right&&r(n.left))return s.push({right:n.right.node}),!0;if(n?.left&&r(n.right))return s.push({left:n.left.node}),!0};return r(this.root),s}size(){let e=t=>t===null?0:1+e(t.left)+e(t.right);return e(this.root)}static verify(e,t,s){let r=st(e),n=(o,c)=>{if(c.length<=0)return tt(t,o);let[u,l]=[c[0],c.slice(1)];return u.left?n(gt(u.left,o),l):u.right?n(gt(o,u.right),l):!1};return n(r,s)}toString(){let e=t=>t===null?null:{node:b(t.node),left:e(t.left),right:e(t.right)};return JSON.stringify(e(this.root),null,2)}};function st(a){return new Uint8Array(new Ae().update(a).arrayBuffer())}function gt(a,e){return st(Xt(a,e))}function Ue(a,e){let t=[];try{let s=i.PlutusData.from_bytes(g(a)),r=e?i.PlutusData.from_bytes(g(e)):void 0,n=i.PlutusWitness.new(s,r,void 0);return t.push(s,n),i.ScriptWitness.new_plutus_witness(n)}finally{_.free(...t)}}function nt(a,e){if(e==="Key"){let r=i.Ed25519KeyHash.from_bytes(g(a)),n=i.StakeCredential.from_keyhash(r);return _.free(r),n}let t=i.ScriptHash.from_bytes(g(a)),s=i.StakeCredential.from_scripthash(t);return _.free(t),s}async function yt(a,e){let t=[];try{let s=i.Ed25519KeyHashes.new();t.push(s),a.owners.forEach(I=>{let{stakeCredential:N}=e.utils.getAddressDetails(I);if(N?.type==="Key"){let T=i.Ed25519KeyHash.from_hex(N.hash);s.add(T),t.push(T)}else throw new Error("Only key hashes allowed for pool owners.")});let r=a.metadataUrl?await fetch(a.metadataUrl).then(I=>I.arrayBuffer()):null,n=r?i.PoolMetadataHash.from_bytes(i.hash_blake2b256(new Uint8Array(r))):null,o=i.Relays.new();t.push(n,o),a.relays.forEach(I=>{switch(I.type){case"SingleHostIp":{let N=I.ipV4?i.Ipv4.new(new Uint8Array(I.ipV4.split(".").map(G=>parseInt(G)))):void 0,T=I.ipV6?i.Ipv6.new(g(I.ipV6.replaceAll(":",""))):void 0,$=i.SingleHostAddr.new(I.port,N,T),V=i.Relay.new_single_host_addr($);t.push($,V),o.add(V);break}case"SingleHostDomainName":{let N=i.DNSRecordAorAAAA.new(I.domainName),T=i.SingleHostName.new(I.port,N),$=i.Relay.new_single_host_name(T);t.push(N,T,$),o.add($);break}case"MultiHost":{let N=i.DNSRecordSRV.new(I.domainName),T=i.MultiHostName.new(N),$=i.Relay.new_multi_host_name(T);t.push(N,T,$),o.add($);break}}});let c=i.Ed25519KeyHash.from_bech32(a.poolId),u=i.VRFKeyHash.from_hex(a.vrfKeyHash),l=i.BigNum.from_str(a.pledge.toString()),d=i.BigNum.from_str(a.cost.toString()),h=i.UnitInterval.from_float(a.margin),f=Ne(a.rewardAddress,e),m=i.RewardAddress.from_address(f),S=i.Url.new(a.metadataUrl),v=n?i.PoolMetadata.new(S,n):void 0;t.push(c,u,l,d,h,f,m,S,v);let y=i.PoolParams.new(c,u,l,d,h,m,s,o,v);return i.PoolRegistration.new(y)}finally{_.free(...t)}}function Le(a,{type:e,script:t}){if(e==="Native"){let s=i.NativeScript.from_bytes(g(t));a.txBuilder.add_native_script(s),_.free(s);return}else if(e==="PlutusV1"){let s=i.PlutusScript.from_bytes(g(Z(t)));a.txBuilder.add_plutus_script(s),_.free(s);return}else if(e==="PlutusV2"){let s=i.PlutusScript.from_bytes(g(Z(t)));a.txBuilder.add_plutus_v2_script(s),_.free(s);return}throw new Error("No variant matched.")}function Ne(a,e){let{type:t,networkId:s}=e.utils.getAddressDetails(a),r=Oe(e.network);if(s!==r)throw new Error(`Invalid address: Expected address with network id ${r}, but got ${s}`);if(t==="Byron"){let n=i.ByronAddress.from_base58(a),o=n.to_address();return n.free(),o}return i.Address.from_bech32(a)}function Yt(a){if(a?.hash){let e=i.DataHash.from_hex(a.hash),t=i.Datum.new_data_hash(e);return e.free(),{datum:t}}else if(a?.asHash){let e=i.PlutusData.from_bytes(g(a.asHash)),t=i.hash_plutus_data(e),s=i.Datum.new_data_hash(t);return t.free(),{plutusData:e,datum:s}}else if(a?.inline){let e=i.PlutusData.from_bytes(g(a.inline)),t=i.Data.new(e),s=i.Datum.new_data(t);return _.free(e,t),{datum:s}}else return{}}function xt({bucket:a,address:e,assets:t,outputData:s,lucid:r,txBuilder:n}){let o=Ne(e,r),c=xe(t),u=i.TransactionOutput.new(o,c);if(a.push(u,o,c),s.hash){let d=i.DataHash.from_hex(s.hash),h=i.Datum.new_data_hash(d);a.push(d,h),u.set_datum(h)}else if(s.asHash){let d=i.PlutusData.from_bytes(g(s.asHash)),h=i.hash_plutus_data(d),f=i.Datum.new_data_hash(h);a.push(d,h,f),u.set_datum(f),n.add_plutus_data(d)}else if(s.inline){let d=i.PlutusData.from_bytes(g(s.inline)),h=i.Data.new(d),f=i.Datum.new_data(h);a.push(d,h,f),u.set_datum(f)}let l=s.scriptRef;if(l){let d=Qe(l);a.push(d),u.set_script_ref(Qe(l))}return u}var Zt={enableChangeSplitting:!0,changeCollateral:"5000000",changeMinUtxo:"100000000",changeNativeAssetChunkSize:20};var ot=class{constructor(e,t){Object.defineProperty(this,"txSigned",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"lucid",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.lucid=e,this.txSigned=t}async submit(){return await(this.lucid.wallet||this.lucid.provider).submitTx(b(this.txSigned.to_bytes()))}toString(){return b(this.txSigned.to_bytes())}toHash(){let e=i.hash_transaction(this.txSigned.body()),t=e.to_hex();return e.free(),t}free(){this.txSigned.free()}};var je=class{constructor(e,t){Object.defineProperty(this,"txComplete",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"witnessSetBuilder",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"tasks",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"lucid",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"fee",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"exUnits",{enumerable:!0,configurable:!0,writable:!0,value:null});let s=[];this.lucid=e,this.txComplete=t,this.witnessSetBuilder=i.TransactionWitnessSetBuilder.new(),this.tasks=[];let r=t.body();s.push(r);let n=r.fee();s.push(n);let o=t.witness_set();s.push(o),this.fee=parseInt(n.to_str());let c=o.redeemers();if(s.push(c),c){let u={cpu:0,mem:0};for(let l=0;l{let e=await this.lucid.wallet.signTx(this.txComplete);this.witnessSetBuilder.add_existing(e),e.free()}),this}signWithPrivateKey(e){let t=[],s=i.PrivateKey.from_bech32(e);t.push(s);let r=this.txComplete.body();t.push(r);let n=i.hash_transaction(r);t.push(n);let o=i.make_vkey_witness(n,s);return t.push(o),this.witnessSetBuilder.add_vkey(o),_.free(...t),this}async partialSign(){let e=await this.lucid.wallet.signTx(this.txComplete);this.witnessSetBuilder.add_existing(e);let t=e.to_bytes();return e.free(),b(t)}partialSignWithPrivateKey(e){let t=[],s=i.PrivateKey.from_bech32(e);t.push(s);let r=this.txComplete.body();t.push(r);let n=i.hash_transaction(r);t.push(n);let o=i.make_vkey_witness(n,s);t.push(o),this.witnessSetBuilder.add_vkey(o);let c=i.TransactionWitnessSetBuilder.new();t.push(c),c.add_vkey(o);let u=c.build();t.push(u);let l=u.to_bytes();return _.free(...t),b(l)}assemble(e){return e.forEach(t=>{let s=i.TransactionWitnessSet.from_bytes(g(t));this.witnessSetBuilder.add_existing(s),s.free()}),this}async complete(){for(let c of this.tasks)await c();let e=[],t=this.txComplete.witness_set();e.push(t),this.witnessSetBuilder.add_existing(t);let s=this.txComplete.body();e.push(s);let r=this.witnessSetBuilder.build();e.push(r);let n=this.txComplete.auxiliary_data();e.push(n);let o=i.Transaction.new(s,r,n);return _.free(...e),new ot(this.lucid,o)}toString(){return b(this.txComplete.to_bytes())}toHash(){let e=this.txComplete.body(),t=i.hash_transaction(e),s=t.to_hex();return _.free(e,t),s}free(){this.txComplete.free(),this.witnessSetBuilder.free()}};var at=class{constructor(e){Object.defineProperty(this,"txBuilder",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"tasks",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"lucid",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"configuration",{enumerable:!0,configurable:!0,writable:!0,value:Zt}),this.lucid=e,this.txBuilder=i.TransactionBuilder.new(e.getTransactionBuilderConfig()),this.tasks=[]}readFrom(e){return this.tasks.push(async t=>{let s=[];try{for(let r of e){if(r.datumHash){r.datum=pe.to(await t.lucid.datumOf(r));let o=i.PlutusData.from_bytes(g(r.datum));s.push(o),t.txBuilder.add_plutus_data(o)}let n=we(r);s.push(n),t.txBuilder.add_reference_input(n)}}finally{_.free(...s)}}),this}config(e){return this.configuration={...this.configuration,...e},this}collectFrom(e,t){return this.tasks.push(async s=>{let r=[];try{for(let n of e){n.datumHash&&!n.datum&&(n.datum=pe.to(await s.lucid.datumOf(n)));let o=we(n);r.push(o);let c=t?Ue(t,n.datumHash&&n.datum?n.datum:void 0):void 0;s.txBuilder.add_input(o,c)}}finally{_.free(...r)}}),this}mintAssets(e,t){return this.tasks.push(s=>{let r=[];try{let n=Object.keys(e),o=n[0].slice(0,56),c=i.MintAssets.new();r.push(c),n.forEach(d=>{if(d.slice(0,56)!==o)throw new Error("Only one policy id allowed. You can chain multiple mintAssets functions together if you need to mint assets with different policy ids.");let h=i.AssetName.new(g(d.slice(56))),f=i.Int.from_str(e[d].toString());r.push(h),c.insert(h,f)});let u=i.ScriptHash.from_bytes(g(o)),l=t?Ue(t):void 0;r.push(u),s.txBuilder.add_mint(u,c,l)}finally{_.free(...r)}}),this}payToAddress(e,t){return this.tasks.push(s=>{let r=Ne(e,s.lucid),n=xe(t),o=i.TransactionOutput.new(r,n),c=s.lucid.utils.getMinAdaForOutput(o);t.lovelace=t.lovelace>c?t.lovelace:c;let u=xe(t),l=i.TransactionOutput.new(r,u);s.txBuilder.add_output(l),_.free(o,r,n,u,l)}),this}payToAddressWithData(e,t,s){return this.tasks.push(r=>{let n=[];try{if(typeof t=="string"&&(t={asHash:t}),[t.hash,t.asHash,t.inline].filter(d=>d).length>1)throw new Error("Not allowed to set hash, asHash and inline at the same time.");let o=xt({bucket:n,txBuilder:r.txBuilder,lucid:r.lucid,address:e,outputData:t,assets:s}),c=this.lucid.utils.getMinAdaForOutput(o),u={...s};u.lovelace=s.lovelace>c?s.lovelace:c;let l=xt({bucket:n,txBuilder:r.txBuilder,lucid:r.lucid,address:e,outputData:t,assets:u});n.push(o,l),r.txBuilder.add_output(l)}finally{_.free(...n)}}),this}payToContract(e,t,s){if(typeof t=="string"&&(t={asHash:t}),!(t.hash||t.asHash||t.inline))throw new Error("No datum set. Script output becomes unspendable without datum.");return this.payToAddressWithData(e,t,s)}delegateTo(e,t,s){return this.tasks.push(r=>{let n=r.lucid.utils.getAddressDetails(e);if(n.type!=="Reward"||!n.stakeCredential)throw new Error("Not a reward address provided.");let o=nt(n.stakeCredential.hash,n.stakeCredential.type),c=i.Ed25519KeyHash.from_bech32(t),u=i.StakeDelegation.new(o,c),l=s?Ue(s):void 0,d=i.Certificate.new_stake_delegation(u);r.txBuilder.add_certificate(d,l),_.free(c,u,o,d)}),this}registerStake(e){return this.tasks.push(t=>{let s=t.lucid.utils.getAddressDetails(e);if(s.type!=="Reward"||!s.stakeCredential)throw new Error("Not a reward address provided.");let r=nt(s.stakeCredential.hash,s.stakeCredential.type),n=i.StakeRegistration.new(r),o=i.Certificate.new_stake_registration(n);t.txBuilder.add_certificate(o,void 0),_.free(r,n,o)}),this}deregisterStake(e,t){return this.tasks.push(s=>{let r=s.lucid.utils.getAddressDetails(e);if(r.type!=="Reward"||!r.stakeCredential)throw new Error("Not a reward address provided.");let n=nt(r.stakeCredential.hash,r.stakeCredential.type),o=i.StakeDeregistration.new(n),c=i.Certificate.new_stake_deregistration(o),u=t?Ue(t):void 0;s.txBuilder.add_certificate(c,u),_.free(n,o,c)}),this}registerPool(e){return this.tasks.push(async t=>{let s=await yt(e,t.lucid),r=i.Certificate.new_pool_registration(s);t.txBuilder.add_certificate(r,void 0),_.free(r,s)}),this}updatePool(e){return this.tasks.push(async t=>{let s=await yt(e,t.lucid);s.set_is_update(!0);let r=i.Certificate.new_pool_registration(s);_.free(s,r),t.txBuilder.add_certificate(r,void 0)}),this}retirePool(e,t){return this.tasks.push(s=>{let r=i.Ed25519KeyHash.from_bech32(e),n=i.PoolRetirement.new(r,t),o=i.Certificate.new_pool_retirement(n);s.txBuilder.add_certificate(o,void 0),_.free(r,n,o)}),this}withdraw(e,t,s){return this.tasks.push(r=>{let n=Ne(e,r.lucid),o=i.RewardAddress.from_address(n),c=i.BigNum.from_str(t.toString()),u=s?Ue(s):void 0;r.txBuilder.add_withdrawal(o,c,u),_.free(n,o,c,u)}),this}addSigner(e){let t=this.lucid.utils.getAddressDetails(e);if(!t.paymentCredential&&!t.stakeCredential)throw new Error("Not a valid address.");let s=t.type==="Reward"?t.stakeCredential:t.paymentCredential;if(s.type==="Script")throw new Error("Only key hashes are allowed as signers.");return this.addSignerKey(s.hash)}addSignerKey(e){return this.tasks.push(t=>{let s=i.Ed25519KeyHash.from_bytes(g(e));t.txBuilder.add_required_signer(s),_.free(s)}),this}validFrom(e){return this.tasks.push(t=>{let s=t.lucid.utils.unixTimeToSlot(e),r=i.BigNum.from_str(s.toString());t.txBuilder.set_validity_start_interval(r),_.free(r)}),this}validTo(e){return this.tasks.push(t=>{let s=t.lucid.utils.unixTimeToSlot(e),r=i.BigNum.from_str(s.toString());t.txBuilder.set_ttl(r),_.free(r)}),this}attachMetadata(e,t){return this.tasks.push(s=>{let r=i.BigNum.from_str(e.toString());s.txBuilder.add_json_metadatum(r,JSON.stringify(t)),_.free(r)}),this}attachMetadataWithConversion(e,t){return this.tasks.push(s=>{let r=i.BigNum.from_str(e.toString());s.txBuilder.add_json_metadatum_with_schema(r,JSON.stringify(t),i.MetadataJsonSchema.BasicConversions),_.free(r)}),this}addNetworkId(e){return this.tasks.push(t=>{let s=i.NetworkId.from_bytes(g(e.toString(16).padStart(2,"0")));t.txBuilder.set_network_id(s),_.free(s)}),this}attachSpendingValidator(e){return this.tasks.push(t=>{Le(t,e)}),this}attachMintingPolicy(e){return this.tasks.push(t=>{Le(t,e)}),this}attachCertificateValidator(e){return this.tasks.push(t=>{Le(t,e)}),this}attachWithdrawalValidator(e){return this.tasks.push(t=>{Le(t,e)}),this}applyIf(e,t){return e&&this.tasks.push(s=>t(s)),this}apply(e){return this.tasks.push(t=>e(t)),this}compose(e){return e&&(this.tasks=this.tasks.concat(e.tasks)),this}free(){this.txBuilder.free()}async complete(e){let t=[],{enableChangeSplitting:s}=this.configuration;try{if([e?.change?.outputData?.hash,e?.change?.outputData?.asHash,e?.change?.outputData?.inline].filter(h=>h).length>1)throw new Error("Not allowed to set hash, asHash and inline at the same time.");let r=this.tasks.shift();for(;r;)await r(this),r=this.tasks.shift();let n=await this.lucid.wallet.getUtxosCore(),o=this.lucid.wallet.getCollateralCore(),c=Ne(e?.change?.address||await this.lucid.wallet.address(),this.lucid);(e?.coinSelection||e?.coinSelection===void 0)&&this.txBuilder.add_inputs_from_impl(n,c,"200,1000,1500,800,800,5000");let{datum:u,plutusData:l}=Yt(e?.change?.outputData);l&&this.txBuilder.add_plutus_data(l),t.push(u,l),s&&await this.splitChange(),this.txBuilder.balance(c,u);let d=await this.txBuilder.construct(o||n,c,e?.nativeUplc===void 0?!0:e?.nativeUplc);return new je(this.lucid,d)}finally{_.free(...t)}}async toString(){let e=this.tasks.shift();for(;e;)await e(this),e=this.tasks.shift();return b(this.txBuilder.to_bytes())}async splitChange(){let e=[],{coinsPerUtxoByte:t}=this.lucid.protocolParameters||Je,{changeNativeAssetChunkSize:s,changeMinUtxo:r}=this.configuration,n=this.txBuilder.get_explicit_input(),o=this.txBuilder.get_explicit_output();e.push(n,o);let c=n.checked_sub(o),u=c.coin(),l=ft(c);e.push(u);let d=Object.keys(l).filter(R=>R!=="lovelace").sort((R,K)=>R.localeCompare(K));l=d.reduce((R,K)=>Object.assign(R,{[K]:l[K]}),{});let h=Math.ceil(d.length/s),f=i.Address.from_bech32(await this.lucid.wallet.address());e.push(f);let m=this.txBuilder.outputs();e.push(m);for(let R=0;Rf.to_bech32(void 0).length)&&(f=K.address())}let S=xe(l),v=i.TransactionOutput.new(f,S),y=i.BigNum.from_str(t.toString()),B=i.min_ada_required(v,y);e.push(S,v,y,B);let I=i.BigNum.from_str(h.toString()),N=B.checked_mul(I);e.push(I,N);let T=N.compare(u)<0,$=c.multiasset();if(e.push($),$&&T){let R=Jt(d,20),K=R.length;for(let[re,be]of R.entries()){if(re===K-1)continue;let _e=xe(be.reduce((Ve,Me)=>Object.assign(Ve,{[Me]:l[Me]}),{}));e.push(_e);let De=i.Address.from_bech32(await this.lucid.wallet.address()),Re=i.TransactionOutput.new(De,_e),ke=i.BigNum.from_str(t.toString()),Ee=i.min_ada_required(Re,ke);_e.set_coin(Ee),u=u.checked_sub(Ee);let lt=i.TransactionOutput.new(De,_e);e.push(u,Re),this.txBuilder.add_output(lt)}}let V=i.BigNum.from_str("2"),G=i.BigNum.from_str(r),he=u.checked_div(V);for(e.push(V,G,he);he.compare(G)>=0;){let R=u.checked_div(V);u=u.checked_sub(R),he=u.checked_div(V);let K=i.Address.from_bech32(await this.lucid.wallet.address()),re=i.Value.new(R),be=i.TransactionOutput.new(K,re);e.push(R,u,he,K,re,be),this.txBuilder.add_output(be)}}};function Gt(a,e={addressType:"Base",accountIndex:0,network:"Mainnet"}){function t(m){if(typeof m!="number")throw new Error("Type number required here!");return 2147483648+m}let s=Bt(a),n=i.Bip32PrivateKey.from_bip39_entropy(g(s),e.password?new TextEncoder().encode(e.password):new Uint8Array).derive(t(1852)).derive(t(1815)).derive(t(e.accountIndex)),o=n.derive(0).derive(0).to_raw_key(),c=n.derive(2).derive(0).to_raw_key(),u=o.to_public().hash(),l=c.to_public().hash(),d=e.network==="Mainnet"?1:0,h=e.addressType==="Base"?i.BaseAddress.new(d,i.StakeCredential.from_keyhash(u),i.StakeCredential.from_keyhash(l)).to_address().to_bech32(void 0):i.EnterpriseAddress.new(d,i.StakeCredential.from_keyhash(u)).to_address().to_bech32(void 0),f=e.addressType==="Base"?i.RewardAddress.new(d,i.StakeCredential.from_keyhash(l)).to_address().to_bech32(void 0):null;return{address:h,rewardAddress:f,paymentKey:o.to_bech32(),stakeKey:e.addressType==="Base"?c.to_bech32():null}}function Qt(a,e,t){let s=[],r=a.body().inputs();for(let m=0;mI.txHash===v&&I.outputIndex===y);if(B){let{paymentCredential:I}=J(B.address);s.push(I?.hash)}}let n=a.body();function o(m){let S=m.certs();if(S)for(let v=0;vI.txHash===v&&I.outputIndex===y);if(B){let{paymentCredential:I}=J(B.address);s.push(I?.hash)}}return s.filter(m=>e.includes(m))}function ze(a,e,t){let s=D.HeaderMap.new();s.set_algorithm_id(D.Label.from_algorithm_id(D.AlgorithmId.EdDSA)),s.set_header(D.Label.new_text("address"),D.CBORValue.new_bytes(g(a)));let r=D.ProtectedHeaderMap.new(s),n=D.HeaderMap.new(),o=D.Headers.new(r,n),c=D.COSESign1Builder.new(o,g(e),!1),u=c.make_data_to_sign().to_bytes(),l=i.PrivateKey.from_bech32(t),d=l.sign(u).to_bytes(),h=c.build(d),f=D.COSEKey.new(D.Label.from_key_type(D.KeyType.OKP));return f.set_algorithm_id(D.Label.from_algorithm_id(D.AlgorithmId.EdDSA)),f.set_header(D.Label.new_int(D.Int.new_negative(D.BigNum.from_str("1"))),D.CBORValue.new_int(D.Int.new_i32(6))),f.set_header(D.Label.new_int(D.Int.new_negative(D.BigNum.from_str("2"))),D.CBORValue.new_bytes(l.to_public().as_bytes())),{signature:b(h.to_bytes()),key:b(f.to_bytes())}}function es(a,e,t,s){let r=D.COSESign1.from_bytes(g(s.signature)),n=D.COSEKey.from_bytes(g(s.key)),o=r.headers().protected().deserialized_headers(),c=(()=>{try{return b(o.header(D.Label.new_text("address"))?.as_bytes())}catch{throw new Error("No address found in signature.")}})(),u=(()=>{try{let y=o.algorithm_id()?.as_int();return y?.is_positive()?parseInt(y.as_positive()?.to_str()):parseInt(y?.as_negative()?.to_str())}catch{throw new Error("Failed to retrieve Algorithm Id.")}})(),l=(()=>{try{let y=n.algorithm_id()?.as_int();return y?.is_positive()?parseInt(y.as_positive()?.to_str()):parseInt(y?.as_negative()?.to_str())}catch{throw new Error("Failed to retrieve Algorithm Id.")}})(),d=(()=>{try{let y=n.header(D.Label.new_int(D.Int.new_negative(D.BigNum.from_str("1"))))?.as_int();return y?.is_positive()?parseInt(y.as_positive()?.to_str()):parseInt(y?.as_negative()?.to_str())}catch{throw new Error("Failed to retrieve Curve.")}})(),h=(()=>{try{let y=n.key_type().as_int();return y?.is_positive()?parseInt(y.as_positive()?.to_str()):parseInt(y?.as_negative()?.to_str())}catch{throw new Error("Failed to retrieve Key Type.")}})(),f=(()=>{try{return i.PublicKey.from_bytes(n.header(D.Label.new_int(D.Int.new_negative(D.BigNum.from_str("2"))))?.as_bytes())}catch{throw new Error("No public key found.")}})(),m=(()=>{try{return b(r.payload())}catch{throw new Error("No payload found.")}})(),S=i.Ed25519Signature.from_bytes(r.signature()),v=r.signed_data(void 0,void 0).to_bytes();return c!==a||e!==f.hash().to_hex()||u!==l&&u!==D.AlgorithmId.EdDSA||d!==6||h!==1||m!==t?!1:f.verify(v,S)}var it=class{constructor(e,t,s){Object.defineProperty(this,"lucid",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"address",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"payload",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.lucid=e,this.address=t,this.payload=s}sign(){return this.lucid.wallet.signMessage(this.address,this.payload)}signWithPrivateKey(e){let t=[];try{let{paymentCredential:s,stakeCredential:r,address:{hex:n}}=this.lucid.utils.getAddressDetails(this.address),o=s?.hash||r?.hash,c=i.PrivateKey.from_bech32(e);t.push(c);let u=c.to_public();t.push(u);let l=u.hash();t.push(l);let d=l.to_hex();if(!o||o!==d)throw new Error(`Cannot sign message for address: ${this.address}.`);return ze(n,this.payload,e)}finally{_.free(...t)}}};var ct=class{constructor(e,t=Je){Object.defineProperty(this,"ledger",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"mempool",{enumerable:!0,configurable:!0,writable:!0,value:{}}),Object.defineProperty(this,"chain",{enumerable:!0,configurable:!0,writable:!0,value:{}}),Object.defineProperty(this,"blockHeight",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"slot",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"time",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"protocolParameters",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"datumTable",{enumerable:!0,configurable:!0,writable:!0,value:{}});let s="00".repeat(32);this.blockHeight=0,this.slot=0,this.time=Date.now(),this.ledger={},e.forEach(({address:r,assets:n,outputData:o},c)=>{if([o?.hash,o?.asHash,o?.inline].filter(u=>u).length>1)throw new Error("Not allowed to set hash, asHash and inline at the same time.");this.ledger[s+c]={utxo:{txHash:s,outputIndex:c,address:r,assets:n,datumHash:o?.asHash?i.hash_plutus_data(i.PlutusData.from_bytes(g(o.asHash))).to_hex():o?.hash,datum:o?.inline,scriptRef:o?.scriptRef},spent:!1}}),this.protocolParameters=t}now(){return this.time}awaitSlot(e=1){this.slot+=e,this.time+=e*1e3;let t=this.blockHeight;if(this.blockHeight=Math.floor(this.slot/20),this.blockHeight>t){for(let[s,{utxo:r,spent:n}]of Object.entries(this.mempool))this.ledger[s]={utxo:r,spent:n};for(let[s,{spent:r}]of Object.entries(this.ledger))r&&delete this.ledger[s];this.mempool={}}}awaitBlock(e=1){this.blockHeight+=e,this.slot+=e*20,this.time+=e*20*1e3;for(let[t,{utxo:s,spent:r}]of Object.entries(this.mempool))this.ledger[t]={utxo:s,spent:r};for(let[t,{spent:s}]of Object.entries(this.ledger))s&&delete this.ledger[t];this.mempool={}}getUtxos(e){let t=Object.values(this.ledger).flatMap(({utxo:s})=>{if(typeof e=="string")return e===s.address?s:[];{let{paymentCredential:r}=J(s.address);return r?.hash===e.hash?s:[]}});return Promise.resolve(t)}getProtocolParameters(){return Promise.resolve(this.protocolParameters)}getDatum(e){return Promise.resolve(this.datumTable[e])}getUtxosWithUnit(e,t){let s=Object.values(this.ledger).flatMap(({utxo:r})=>{if(typeof e=="string")return e===r.address&&r.assets[t]>0n?r:[];{let{paymentCredential:n}=J(r.address);return n?.hash===e.hash&&r.assets[t]>0n?r:[]}});return Promise.resolve(s)}getUtxosByOutRef(e){return Promise.resolve(e.flatMap(t=>this.ledger[t.txHash+t.outputIndex]?.utxo||[]))}getUtxoByUnit(e){let t=Object.values(this.ledger).flatMap(({utxo:s})=>s.assets[e]>0n?s:[]);if(t.length>1)throw new Error("Unit needs to be an NFT or only held by one address.");return Promise.resolve(t[0])}getDelegation(e){return Promise.resolve({poolId:this.chain[e]?.delegation?.poolId||null,rewards:this.chain[e]?.delegation?.rewards||0n})}awaitTx(e){return this.mempool[e+0]&&this.awaitBlock(),Promise.resolve(!0)}distributeRewards(e){for(let[t,{registeredStake:s,delegation:r}]of Object.entries(this.chain))s&&r.poolId&&(this.chain[t]={registeredStake:s,delegation:{poolId:r.poolId,rewards:r.rewards+=e}});this.awaitBlock()}submitTx(e){let t=[],s=i.Transaction.from_bytes(g(e));t.push(s);let r=s.body();t.push(r);let n=s.witness_set();t.push(n);let o=n.plutus_data();t.push(o);let c=i.hash_transaction(r);t.push(c);let u=c.to_hex(),l=r.validity_start_interval();t.push(l);let d=l?parseInt(l.to_str()):null,h=r.ttl();t.push(h);let f=h?parseInt(h.to_str()):null;if(Number.isInteger(d)&&this.slotf)throw new Error(`Upper bound (${f}) not in slot range (${this.slot}).`);let m=(()=>{let p={};for(let x=0;x<(o?.len()||0);x++){let C=o.get(x);t.push(C);let E=i.hash_plutus_data(C);t.push(E);let O=E.to_hex();p[O]=b(C.to_bytes())}return p})(),S=new Set,v=(()=>{let p=[],x=n.vkeys();t.push(x);for(let C=0;C<(x?.len()||0);C++){let E=x.get(C);t.push(E);let O=E.vkey();t.push(O);let P=O.public_key();t.push(P);let U=P.hash();t.push(U);let j=U.to_hex();if(!P.verify(g(u),E.signature()))throw new Error(`Invalid vkey witness. Key hash: ${j}`);p.push(j)}return p})(),y=i.Ed25519KeyHashes.new();t.push(y),v.forEach(p=>{let x=i.Ed25519KeyHash.from_hex(p);t.push(x),y.add(x)});let B=(()=>{let p=[],x=n.native_scripts();t.push(x);for(let C=0;C<(x?.len()||0);C++){let E=x.get(C);t.push(E);let O=E.hash(i.ScriptHashNamespace.NativeScript);t.push(O);let P=O.to_hex(),U=Number.isInteger(d)?i.BigNum.from_str(d.toString()):void 0;t.push(U);let j=Number.isInteger(f)?i.BigNum.from_str(f.toString()):void 0;if(t.push(j),!E.verify(U,j,y))throw new Error(`Invalid native script witness. Script hash: ${P}`);let M=E.get_required_signers();t.push(M);for(let F=0;F{let p=[],x=n.plutus_scripts();t.push(x);for(let E=0;E<(x?.len()||0);E++){let O=x.get(E);t.push(O);let P=O.hash(i.ScriptHashNamespace.PlutusV1);t.push(P);let U=P.to_hex();p.push(U)}let C=n.plutus_v2_scripts();t.push(C);for(let E=0;E<(C?.len()||0);E++){let O=C.get(E);t.push(O);let P=O.hash(i.ScriptHashNamespace.PlutusV2);t.push(P);let U=P.to_hex();p.push(U)}return p})(),$=r.inputs();t.push($),$.sort();let V=[];for(let p=0;p<$.len();p++){let x=$.get(p);t.push(x);let C=x.transaction_id();t.push(C);let E=x.index();t.push(E);let O=C.to_hex()+E.to_str(),P=this.ledger[O],{entry:U,type:j}=P?{entry:P,type:"Ledger"}:{entry:this.mempool[O],type:"Mempool"};if(!U||U.spent)throw new Error(`Could not spend UTxO: ${JSON.stringify({txHash:U?.utxo.txHash,outputIndex:U?.utxo.outputIndex})} +It does not exist or was already spent.`);let M=U.utxo.scriptRef;if(M)switch(M.type){case"Native":{let F=i.NativeScript.from_bytes(g(M.script));t.push(F);let X=F.hash(i.ScriptHashNamespace.NativeScript);t.push(X),I[X.to_hex()]=F;break}case"PlutusV1":{let F=i.PlutusScript.from_bytes(g(M.script));t.push(F);let X=F.hash(i.ScriptHashNamespace.PlutusV1);t.push(X),N.push(X.to_hex());break}case"PlutusV2":{let F=i.PlutusScript.from_bytes(g(M.script));t.push(F);let X=F.hash(i.ScriptHashNamespace.PlutusV2);t.push(X),N.push(X.to_hex());break}}U.utxo.datumHash&&S.add(U.utxo.datumHash),V.push({entry:U,type:j})}let G=r.reference_inputs();t.push(G);for(let p=0;p<(G?.len()||0);p++){let x=G.get(p);t.push(x);let C=x.transaction_id();t.push(C);let E=x.index();t.push(E);let O=C.to_hex()+E.to_str(),P=this.ledger[O]||this.mempool[O];if(!P||P.spent)throw new Error(`Could not read UTxO: ${JSON.stringify({txHash:P?.utxo.txHash,outputIndex:P?.utxo.outputIndex})} +It does not exist or was already spent.`);let U=P.utxo.scriptRef;if(U)switch(U.type){case"Native":{let j=i.NativeScript.from_bytes(g(U.script));t.push(j);let M=j.hash(i.ScriptHashNamespace.NativeScript);t.push(M),I[M.to_hex()]=j;break}case"PlutusV1":{let j=i.PlutusScript.from_bytes(g(U.script));t.push(j);let M=j.hash(i.ScriptHashNamespace.PlutusV1);t.push(M),N.push(M.to_hex());break}case"PlutusV2":{let j=i.PlutusScript.from_bytes(g(U.script));t.push(j);let M=j.hash(i.ScriptHashNamespace.PlutusV2);t.push(M),N.push(M.to_hex());break}}P.utxo.datumHash&&S.add(P.utxo.datumHash)}let he=(()=>{let p={0:"Spend",1:"Mint",2:"Cert",3:"Reward"},x=[],C=n.redeemers();t.push(C);for(let E=0;E<(C?.len()||0);E++){let O=C.get(E);t.push(O);let P=O.tag();t.push(P);let U=O.index();t.push(U),x.push({tag:p[P.kind()],index:parseInt(U.to_str())})}return x})();function R(p,x,C){switch(p.type){case"Key":{if(!v.includes(p.hash))throw new Error(`Missing vkey witness. Key hash: ${p.hash}`);S.add(p.hash);break}case"Script":{if(B.includes(p.hash)){S.add(p.hash);break}else if(I[p.hash]){let E=Number.isInteger(d)?i.BigNum.from_str(d.toString()):void 0;t.push(E);let O=Number.isInteger(f)?i.BigNum.from_str(f.toString()):void 0;if(t.push(O),!I[p.hash].verify(E,O,y))throw new Error(`Invalid native script witness. Script hash: ${p.hash}`);break}else if((T.includes(p.hash)||N.includes(p.hash))&&he.find(E=>E.tag===x&&E.index===C)){S.add(p.hash);break}throw new Error(`Missing script witness. Script hash: ${p.hash}`)}}}let K=r.collateral();t.push(K);for(let p=0;p<(K?.len()||0);p++){let x=K.get(p);t.push(x);let C=x.transaction_id();t.push(C);let E=x.index();t.push(E);let O=C.to_hex()+E.to_str(),P=this.ledger[O]||this.mempool[O];if(!P||P.spent)throw new Error(`Could not read UTxO: ${JSON.stringify({txHash:P?.utxo.txHash,outputIndex:P?.utxo.outputIndex})} +It does not exist or was already spent.`);let{paymentCredential:U}=J(P.utxo.address);if(U?.type==="Script")throw new Error("Collateral inputs can only contain vkeys.");R(U,null,null)}let re=r.required_signers();t.push(re);for(let p=0;p<(re?.len()||0);p++){let x=re.get(p);t.push(x),R({type:"Key",hash:x.to_hex()},null,null)}let be=r.mint();t.push(be);let Fe=be?.keys();t.push(Fe);for(let p=0;p<(Fe?.len()||0);p++){let x=Fe.get(p);t.push(x);let C=x.to_hex();R({type:"Script",hash:C},"Mint",p)}let _e=[],De=r.withdrawals(),Re=De?.keys();for(let p=0;p<(Re?.len()||0);p++){let x=Re.get(p);t.push(x);let C=De.get(x);t.push(C);let E=BigInt(C.to_str()),O=x.to_address();t.push(O);let P=O.to_bech32(void 0),{stakeCredential:U}=J(P);if(R(U,"Reward",p),this.chain[P]?.delegation.rewards!==E)throw new Error("Withdrawal amount doesn't match actual reward balance.");_e.push({rewardAddress:P,withdrawal:E})}let ke=[],Ee=r.certs();t.push(Ee);for(let p=0;p<(Ee?.len()||0);p++){let x=Ee.get(p);switch(t.push(x),x.kind()){case 0:{let C=x.as_stake_registration();t.push(C);let E=i.NetworkInfo.testnet();t.push(E);let O=C.stake_credential();t.push(O);let P=i.RewardAddress.new(E.network_id(),O);t.push(P);let U=P.to_address();t.push(U);let j=U.to_bech32(void 0);if(this.chain[j]?.registeredStake)throw new Error(`Stake key is already registered. Reward address: ${j}`);ke.push({type:"Registration",rewardAddress:j});break}case 1:{let C=x.as_stake_deregistration();t.push(C);let E=i.NetworkInfo.testnet();t.push(E);let O=C.stake_credential();t.push(O);let P=i.RewardAddress.new(E.network_id(),O);t.push(P);let U=P.to_address();t.push(U);let j=U.to_bech32(void 0),{stakeCredential:M}=J(j);if(R(M,"Cert",p),!this.chain[j]?.registeredStake)throw new Error(`Stake key is already deregistered. Reward address: ${j}`);ke.push({type:"Deregistration",rewardAddress:j});break}case 2:{let C=x.as_stake_delegation();t.push(C);let E=i.NetworkInfo.testnet();t.push(E);let O=C.stake_credential();t.push(O);let P=i.RewardAddress.new(E.network_id(),O);t.push(P);let U=P.to_address();t.push(U);let j=U.to_bech32(void 0),M=C.pool_keyhash();t.push(M);let F=M.to_bech32("pool"),{stakeCredential:X}=J(j);if(R(X,"Cert",p),!this.chain[j]?.registeredStake&&!ke.find(We=>We.type==="Registration"&&We.rewardAddress===j))throw new Error(`Stake key is not registered. Reward address: ${j}`);ke.push({type:"Delegation",rewardAddress:j,poolId:F});break}}}V.forEach(({entry:{utxo:p}},x)=>{let{paymentCredential:C}=J(p.address);R(C,"Spend",x)});let lt=(()=>{let p=r.outputs();t.push(p);let x=[];for(let C=0;C!S.has(p));if(Ve)throw new Error(`Extraneous vkey witness. Key hash: ${Ve}`);let[Me]=B.filter(p=>!S.has(p));if(Me)throw new Error(`Extraneous native script. Script hash: ${Me}`);let[wt]=T.filter(p=>!S.has(p));if(wt)throw new Error(`Extraneous plutus script. Script hash: ${wt}`);let[bt]=Object.keys(m).filter(p=>!S.has(p));if(bt)throw new Error(`Extraneous plutus data. Datum hash: ${bt}`);V.forEach(({entry:p,type:x})=>{let C=p.utxo.txHash+p.utxo.outputIndex;p.spent=!0,x==="Ledger"?this.ledger[C]=p:x==="Mempool"&&(this.mempool[C]=p)}),_e.forEach(({rewardAddress:p,withdrawal:x})=>{this.chain[p].delegation.rewards-=x}),ke.forEach(({type:p,rewardAddress:x,poolId:C})=>{switch(p){case"Registration":{this.chain[x]?this.chain[x].registeredStake=!0:this.chain[x]={registeredStake:!0,delegation:{poolId:null,rewards:0n}};break}case"Deregistration":{this.chain[x].registeredStake=!1,this.chain[x].delegation.poolId=null;break}case"Delegation":this.chain[x].delegation.poolId=C}}),lt.forEach(({utxo:p,spent:x})=>{this.mempool[p.txHash+p.outputIndex]={utxo:p,spent:x}});for(let[p,x]of Object.entries(m))this.datumTable[p]=x;return Promise.resolve(u)}log(){function e(r){let n=r==="lovelace"?"1":r,o=0;for(let d=0;do.EnterpriseAddress.new(this.network==="Mainnet"?1:0,o.StakeCredential.from_keyhash(r)).to_address().to_bech32(void 0),rewardAddress:async()=>null,getCollateralCore:()=>{},getUtxos:async()=>await this.utxosAt(ie(await this.wallet.address())),getUtxosCore:async()=>{let s=await this.utxosAt(ie(await this.wallet.address())),n=o.TransactionUnspentOutputs.new();return s.forEach(i=>{n.add(ue(i))}),n},getDelegation:async()=>({poolId:null,rewards:0n}),signTx:async s=>{let n=o.make_vkey_witness(o.hash_transaction(s.body()),t),i=o.TransactionWitnessSetBuilder.new();return i.add_vkey(n),i.build()},signMessage:async(s,n)=>{let{paymentCredential:i,address:{hex:u}}=this.utils.getAddressDetails(s),c=i?.hash,m=r.to_hex();if(!c||c!==m)throw new Error(`Cannot sign message for address: ${s}.`);return Ie(u,n,e)},submitTx:async s=>await this.provider.submitTx(s)},this}selectWallet(e){let t=async()=>{let[r]=await e.getUsedAddresses();if(r)return r;let[s]=await e.getUnusedAddresses();return s};return this.wallet={address:async()=>o.Address.from_bytes(d(await t())).to_bech32(void 0),rewardAddress:async()=>{let[r]=await e.getRewardAddresses();return r?o.RewardAddress.from_address(o.Address.from_bytes(d(r))).to_address().to_bech32(void 0):null},getCollateralCore:()=>{},getUtxos:async()=>(await e.getUtxos()||[]).map(s=>{let n=o.TransactionUnspentOutput.from_bytes(d(s));return Oe(n)}),getUtxosCore:async()=>{let r=o.TransactionUnspentOutputs.new();return(await e.getUtxos()||[]).forEach(s=>{r.add(o.TransactionUnspentOutput.from_bytes(d(s)))}),r},getDelegation:async()=>{let r=await this.wallet.rewardAddress();return r?await this.delegationAt(r):{poolId:null,rewards:0n}},signTx:async r=>{let s=await e.signTx(y(r.to_bytes()),!0);return o.TransactionWitnessSet.from_bytes(d(s))},signMessage:async(r,s)=>{let n=y(o.Address.from_bech32(r).to_bytes());return await e.signData(n,s)},submitTx:async r=>await e.submitTx(r)},this}selectWalletFrom({address:e,utxos:t,rewardAddress:r,collateral:s}){let n=this.utils.getAddressDetails(e);return this.wallet={address:async()=>e,rewardAddress:async()=>(!r&&n.stakeCredential?(()=>n.stakeCredential.type==="Key"?o.RewardAddress.new(this.network==="Mainnet"?1:0,o.StakeCredential.from_keyhash(o.Ed25519KeyHash.from_hex(n.stakeCredential.hash))).to_address().to_bech32(void 0):o.RewardAddress.new(this.network==="Mainnet"?1:0,o.StakeCredential.from_scripthash(o.ScriptHash.from_hex(n.stakeCredential.hash))).to_address().to_bech32(void 0))():r)||null,getCollateralCore:()=>{if(!s||!s.length)return;let i=o.TransactionUnspentOutputs.new();return s.forEach(u=>i.add(ue(u))),i},getUtxos:async()=>t||await this.utxosAt(ie(e)),getUtxosCore:async()=>{let i=o.TransactionUnspentOutputs.new();return(t||await this.utxosAt(ie(e))).forEach(u=>i.add(ue(u))),i},getDelegation:async()=>{let i=await this.wallet.rewardAddress();return i?await this.delegationAt(i):{poolId:null,rewards:0n}},signTx:async()=>{throw new Error("Not implemented")},signMessage:async()=>{throw new Error("Not implemented")},submitTx:async i=>await this.provider.submitTx(i)},this}selectWalletFromSeed(e,t){let{address:r,rewardAddress:s,paymentKey:n,stakeKey:i}=Pt(e,{addressType:t?.addressType||"Base",accountIndex:t?.accountIndex||0,password:t?.password,network:this.network}),u=o.PrivateKey.from_bech32(n).to_public().hash().to_hex(),c=i?o.PrivateKey.from_bech32(i).to_public().hash().to_hex():"",m={[u]:n,[c]:i};return this.wallet={address:async()=>r,rewardAddress:async()=>s||null,getCollateralCore:()=>{},getUtxos:async()=>this.utxosAt(ie(r)),getUtxosCore:async()=>{let p=o.TransactionUnspentOutputs.new();return(await this.utxosAt(ie(r))).forEach(C=>p.add(ue(C))),p},getDelegation:async()=>{let p=await this.wallet.rewardAddress();return p?await this.delegationAt(p):{poolId:null,rewards:0n}},signTx:async p=>{let C=await this.utxosAt(r),h=Ot(p,[u,c],C),_=o.TransactionWitnessSetBuilder.new();return h.forEach(I=>{let w=o.make_vkey_witness(o.hash_transaction(p.body()),o.PrivateKey.from_bech32(m[I]));_.add_vkey(w)}),_.build()},signMessage:async(p,C)=>{let{paymentCredential:E,stakeCredential:h,address:{hex:_}}=this.utils.getAddressDetails(p),I=E?.hash||h?.hash,w=m[I];if(!w)throw new Error(`Cannot sign message for address: ${p}.`);return Ie(_,C,w)},submitTx:async p=>await this.provider.submitTx(p)},this}};var Ut=class{constructor(e,t){Object.defineProperty(this,"url",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"projectId",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.url=e,this.projectId=t||""}async getProtocolParameters(){let e=await fetch(`${this.url}/epochs/latest/parameters`,{headers:{project_id:this.projectId,lucid:W}}).then(t=>t.json());return{minFeeA:parseInt(e.min_fee_a),minFeeB:parseInt(e.min_fee_b),maxTxSize:parseInt(e.max_tx_size),maxValSize:parseInt(e.max_val_size),keyDeposit:BigInt(e.key_deposit),poolDeposit:BigInt(e.pool_deposit),priceMem:parseFloat(e.price_mem),priceStep:parseFloat(e.price_step),maxTxExMem:BigInt(e.max_tx_ex_mem),maxTxExSteps:BigInt(e.max_tx_ex_steps),coinsPerUtxoByte:BigInt(e.coins_per_utxo_size),collateralPercentage:parseInt(e.collateral_percent),maxCollateralInputs:parseInt(e.max_collateral_inputs),costModels:e.cost_models}}async getUtxos(e){let t=(()=>typeof e=="string"?e:e.type==="Key"?o.Ed25519KeyHash.from_hex(e.hash).to_bech32("addr_vkh"):o.ScriptHash.from_hex(e.hash).to_bech32("addr_vkh"))(),r=[],s=1;for(;;){let n=await fetch(`${this.url}/addresses/${t}/utxos?page=${s}`,{headers:{project_id:this.projectId,lucid:W}}).then(i=>i.json());if(n.error){if(n.status_code===404)return[];throw new Error("Could not fetch UTxOs from Blockfrost. Try again.")}if(r=r.concat(n),n.length<=0)break;s++}return this.blockfrostUtxosToUtxos(r)}async getUtxosWithUnit(e,t){let r=(()=>typeof e=="string"?e:e.type==="Key"?o.Ed25519KeyHash.from_hex(e.hash).to_bech32("addr_vkh"):o.ScriptHash.from_hex(e.hash).to_bech32("addr_vkh"))(),s=[],n=1;for(;;){let i=await fetch(`${this.url}/addresses/${r}/utxos/${t}?page=${n}`,{headers:{project_id:this.projectId,lucid:W}}).then(u=>u.json());if(i.error){if(i.status_code===404)return[];throw new Error("Could not fetch UTxOs from Blockfrost. Try again.")}if(s=s.concat(i),i.length<=0)break;n++}return this.blockfrostUtxosToUtxos(s)}async getUtxoByUnit(e){let t=await fetch(`${this.url}/assets/${e}/addresses?count=2`,{headers:{project_id:this.projectId,lucid:W}}).then(n=>n.json());if(!t||t.error)throw new Error("Unit not found.");if(t.length>1)throw new Error("Unit needs to be an NFT or only held by one address.");let r=t[0].address,s=await this.getUtxosWithUnit(r,e);if(s.length>1)throw new Error("Unit needs to be an NFT or only held by one address.");return s[0]}async getUtxosByOutRef(e){let t=[...new Set(e.map(s=>s.txHash))];return(await Promise.all(t.map(async s=>{let n=await fetch(`${this.url}/txs/${s}/utxos`,{headers:{project_id:this.projectId,lucid:W}}).then(u=>u.json());if(!n||n.error)return[];let i=n.outputs.map(u=>({...u,tx_hash:s}));return this.blockfrostUtxosToUtxos(i)}))).reduce((s,n)=>s.concat(n),[]).filter(s=>e.some(n=>s.txHash===n.txHash&&s.outputIndex===n.outputIndex))}async getDelegation(e){let t=await fetch(`${this.url}/accounts/${e}`,{headers:{project_id:this.projectId,lucid:W}}).then(r=>r.json());return!t||t.error?{poolId:null,rewards:0n}:{poolId:t.pool_id||null,rewards:BigInt(t.withdrawable_amount)}}async getDatum(e){let t=await fetch(`${this.url}/scripts/datum/${e}/cbor`,{headers:{project_id:this.projectId,lucid:W}}).then(r=>r.json()).then(r=>r.cbor);if(!t||t.error)throw new Error(`No datum found for datum hash: ${e}`);return t}awaitTx(e,t=3e3){return new Promise(r=>{let s=setInterval(async()=>{let n=await fetch(`${this.url}/txs/${e}`,{headers:{project_id:this.projectId,lucid:W}}).then(i=>i.json());if(n&&!n.error)return clearInterval(s),await new Promise(i=>setTimeout(()=>i(1),1e3)),r(!0)},t)})}async submitTx(e){let t=await fetch(`${this.url}/tx/submit`,{method:"POST",headers:{"Content-Type":"application/cbor",project_id:this.projectId,lucid:W},body:d(e)}).then(r=>r.json());if(!t||t.error)throw t?.status_code===400?new Error(t.message):new Error("Could not submit transaction.");return t}async blockfrostUtxosToUtxos(e){return await Promise.all(e.map(async t=>({txHash:t.tx_hash,outputIndex:t.output_index,assets:Object.fromEntries(t.amount.map(({unit:r,quantity:s})=>[r,BigInt(s)])),address:t.address,datumHash:!t.inline_datum&&t.data_hash||void 0,datum:t.inline_datum||void 0,scriptRef:t.reference_script_hash?await(async()=>{let{type:r}=await fetch(`${this.url}/scripts/${t.reference_script_hash}`,{headers:{project_id:this.projectId,lucid:W}}).then(n=>n.json());if(r==="Native"||r==="native")throw new Error("Native script ref not implemented!");let{cbor:s}=await fetch(`${this.url}/scripts/${t.reference_script_hash}/cbor`,{headers:{project_id:this.projectId,lucid:W}}).then(n=>n.json());return{type:r==="plutusV1"?"PlutusV1":"PlutusV2",script:q(s)}})():void 0})))}};function Ws(a){let e=t=>{if(isNaN(t.int)){if(t.bytes||!isNaN(Number(t.bytes)))return o.PlutusData.new_bytes(d(t.bytes));if(t.map){let r=o.PlutusMap.new();return t.map.forEach(({k:s,v:n})=>{r.insert(e(s),e(n))}),o.PlutusData.new_map(r)}else if(t.list){let r=o.PlutusList.new();return t.list.forEach(s=>{r.add(e(s))}),o.PlutusData.new_list(r)}else if(!isNaN(t.constructor)){let r=o.PlutusList.new();return t.fields.forEach(s=>{r.add(e(s))}),o.PlutusData.new_constr_plutus_data(o.ConstrPlutusData.new(o.BigNum.from_str(t.constructor.toString()),r))}}else return o.PlutusData.new_integer(o.BigInt.from_str(t.int.toString()));throw new Error("Unsupported type")};return y(e(a).to_bytes())}var W=ge.version;var Ht=class{constructor(e,t){Object.defineProperty(this,"kupoUrl",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"ogmiosUrl",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.kupoUrl=e,this.ogmiosUrl=t}async getProtocolParameters(){let e=await this.ogmiosWsp("Query",{query:"currentProtocolParameters"});return new Promise((t,r)=>{e.addEventListener("message",s=>{try{let{result:n}=JSON.parse(s.data),i={};Object.keys(n.costModels).forEach(C=>{let h="Plutus"+C.split(":")[1].toUpperCase();i[h]=n.costModels[C]});let[u,c]=n.prices.memory.split("/"),[m,p]=n.prices.steps.split("/");t({minFeeA:parseInt(n.minFeeCoefficient),minFeeB:parseInt(n.minFeeConstant),maxTxSize:parseInt(n.maxTxSize),maxValSize:parseInt(n.maxValueSize),keyDeposit:BigInt(n.stakeKeyDeposit),poolDeposit:BigInt(n.poolDeposit),priceMem:parseInt(u)/parseInt(c),priceStep:parseInt(m)/parseInt(p),maxTxExMem:BigInt(n.maxExecutionUnitsPerTransaction.memory),maxTxExSteps:BigInt(n.maxExecutionUnitsPerTransaction.steps),coinsPerUtxoByte:BigInt(n.coinsPerUtxoByte),collateralPercentage:parseInt(n.collateralPercentage),maxCollateralInputs:parseInt(n.maxCollateralInputs),costModels:i}),e.close()}catch(n){r(n)}},{once:!0})})}async getUtxos(e){let t=typeof e=="string",r=t?e:e.hash,s=await fetch(`${this.kupoUrl}/matches/${r}${t?"":"/*"}?unspent`).then(n=>n.json());return this.kupmiosUtxosToUtxos(s)}async getUtxosWithUnit(e,t){let r=typeof e=="string",s=r?e:e.hash,{policyId:n,assetName:i}=Ce(t),u=await fetch(`${this.kupoUrl}/matches/${s}${r?"":"/*"}?unspent&policy_id=${n}${i?`&asset_name=${i}`:""}`).then(c=>c.json());return this.kupmiosUtxosToUtxos(u)}async getUtxoByUnit(e){let{policyId:t,assetName:r}=Ce(e),s=await fetch(`${this.kupoUrl}/matches/${t}.${r?`${r}`:"*"}?unspent`).then(i=>i.json()),n=await this.kupmiosUtxosToUtxos(s);if(n.length>1)throw new Error("Unit needs to be an NFT or only held by one address.");return n[0]}async getUtxosByOutRef(e){let t=[...new Set(e.map(s=>s.txHash))];return(await Promise.all(t.map(async s=>{let n=await fetch(`${this.kupoUrl}/matches/*@${s}?unspent`).then(i=>i.json());return this.kupmiosUtxosToUtxos(n)}))).reduce((s,n)=>s.concat(n),[]).filter(s=>e.some(n=>s.txHash===n.txHash&&s.outputIndex===n.outputIndex))}async getDelegation(e){let t=await this.ogmiosWsp("Query",{query:{delegationsAndRewards:[e]}});return new Promise((r,s)=>{t.addEventListener("message",n=>{try{let{result:i}=JSON.parse(n.data),u=i?Object.values(i)[0]:{};r({poolId:u?.delegate||null,rewards:BigInt(u?.rewards||0)}),t.close()}catch(i){s(i)}},{once:!0})})}async getDatum(e){let t=await fetch(`${this.kupoUrl}/datums/${e}`).then(r=>r.json());if(!t||!t.datum)throw new Error(`No datum found for datum hash: ${e}`);return t.datum}awaitTx(e,t=3e3){return new Promise(r=>{let s=setInterval(async()=>{let n=await fetch(`${this.kupoUrl}/matches/*@${e}?unspent`).then(i=>i.json());if(n&&n.length>0)return clearInterval(s),await new Promise(i=>setTimeout(()=>i(1),1e3)),r(!0)},t)})}async submitTx(e){let t=await this.ogmiosWsp("SubmitTx",{submit:e});return new Promise((r,s)=>{t.addEventListener("message",n=>{try{let{result:i}=JSON.parse(n.data);i.SubmitSuccess?r(i.SubmitSuccess.txId):s(i.SubmitFail),t.close()}catch(i){s(i)}},{once:!0})})}kupmiosUtxosToUtxos(e){return Promise.all(e.map(async t=>({txHash:t.transaction_id,outputIndex:parseInt(t.output_index),address:t.address,assets:(()=>{let r={lovelace:BigInt(t.value.coins)};return Object.keys(t.value.assets).forEach(s=>{r[s.replace(".","")]=BigInt(t.value.assets[s])}),r})(),datumHash:t?.datum_type==="hash"?t.datum_hash:null,datum:t?.datum_type==="inline"?await this.getDatum(t.datum_hash):null,scriptRef:t.script_hash&&await(async()=>{let{script:r,language:s}=await fetch(`${this.kupoUrl}/scripts/${t.script_hash}`).then(n=>n.json());if(s==="native")return{type:"Native",script:r};if(s==="plutus:v1")return{type:"PlutusV1",script:y(o.PlutusScript.new(d(r)).to_bytes())};if(s==="plutus:v2")return{type:"PlutusV2",script:y(o.PlutusScript.new(d(r)).to_bytes())}})()})))}async ogmiosWsp(e,t){let r=new WebSocket(this.ogmiosUrl);return await new Promise(s=>{r.addEventListener("open",()=>s(1),{once:!0})}),r.send(JSON.stringify({type:"jsonwsp/request",version:"1.0",servicename:"ogmios",methodname:e,args:t})),r}};var jt=class{constructor({network:e,apiKey:t,turboSubmit:r=!1}){Object.defineProperty(this,"url",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"apiKey",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"turboSubmit",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.url=`https://${e}.gomaestro-api.org/v1`,this.apiKey=t,this.turboSubmit=r}async getProtocolParameters(){let t=(await fetch(`${this.url}/protocol-params`,{headers:this.commonHeaders()}).then(n=>n.json())).data,r=n=>{let i=n.indexOf("/");return parseInt(n.slice(0,i))/parseInt(n.slice(i+1))},s=(n,i)=>{let u=Object.keys(n).sort().map(c=>({[i[c]||c]:Object.fromEntries(Object.entries(n[c]).sort(([p,C],[E,h])=>p.localeCompare(E)))}));return Object.assign({},...u)};return{minFeeA:parseInt(t.min_fee_coefficient),minFeeB:parseInt(t.min_fee_constant),maxTxSize:parseInt(t.max_tx_size),maxValSize:parseInt(t.max_value_size),keyDeposit:BigInt(t.stake_key_deposit),poolDeposit:BigInt(t.pool_deposit),priceMem:r(t.prices.memory),priceStep:r(t.prices.steps),maxTxExMem:BigInt(t.max_execution_units_per_transaction.memory),maxTxExSteps:BigInt(t.max_execution_units_per_transaction.steps),coinsPerUtxoByte:BigInt(t.coins_per_utxo_byte),collateralPercentage:parseInt(t.collateral_percentage),maxCollateralInputs:parseInt(t.max_collateral_inputs),costModels:s(t.cost_models,{"plutus:v1":"PlutusV1","plutus:v2":"PlutusV2"})}}async getUtxos(e){let t=(()=>{if(typeof e=="string")return"/addresses/"+e;let n="/addresses/cred/";return n+=e.type==="Key"?o.Ed25519KeyHash.from_hex(e.hash).to_bech32("addr_vkh"):o.ScriptHash.from_hex(e.hash).to_bech32("addr_shared_vkh"),n})(),r=[],s=null;for(;;){let n=s===null?"":`&cursor=${s}`,i=await fetch(`${this.url}${t}/utxos?count=100${n}`,{headers:this.commonHeaders()}),u=await i.json();if(!i.ok)throw new Error("Could not fetch UTxOs from Maestro. Received status code: "+i.status);if(s=u.next_cursor,r=r.concat(u.data),s==null)break}return r.map(this.maestroUtxoToUtxo)}async getUtxosWithUnit(e,t){return(await this.getUtxos(e)).filter(s=>s.assets[t])}async getUtxoByUnit(e){let t=await fetch(`${this.url}/assets/${e}/addresses?count=2`,{headers:this.commonHeaders()}),r=await t.json();if(!t.ok)throw r.message?new Error(r.message):new Error("Couldn't perform query. Received status code: "+t.status);let s=r.data;if(s.length===0)throw new Error("Unit not found.");if(s.length>1)throw new Error("Unit needs to be an NFT or only held by one address.");let n=s[0].address,i=await this.getUtxosWithUnit(n,e);if(i.length>1)throw new Error("Unit needs to be an NFT or only held by one address.");return i[0]}async getUtxosByOutRef(e){let t=await fetch(`${this.url}/transactions/outputs`,{method:"POST",headers:{"Content-Type":"application/json",...this.commonHeaders()},body:JSON.stringify(e.map(({txHash:s,outputIndex:n})=>`${s}#${n}`))});return t.ok?(await t.json()).data.map(this.maestroUtxoToUtxo):[]}async getDelegation(e){let t=await fetch(`${this.url}/accounts/${e}`,{headers:this.commonHeaders()});if(!t.ok)return{poolId:null,rewards:0n};let s=(await t.json()).data;return{poolId:s.delegated_pool||null,rewards:BigInt(s.rewards_available)}}async getDatum(e){let t=await fetch(`${this.url}/datum/${e}`,{headers:this.commonHeaders()});if(!t.ok)throw t.status===404?new Error(`No datum found for datum hash: ${e}`):new Error("Couldn't successfully perform query. Received status code: "+t.status);return(await t.json()).data.bytes}awaitTx(e,t=3e3){return new Promise(r=>{let s=setInterval(async()=>{let n=await fetch(`${this.url}/transactions/${e}/cbor`,{headers:this.commonHeaders()});if(n.ok)return await n.json(),clearInterval(s),await new Promise(i=>setTimeout(()=>i(1),1e3)),r(!0)},t)})}async submitTx(e){let t=`${this.url}/txmanager`;t+=this.turboSubmit?"/turbosubmit":"";let r=await fetch(t,{method:"POST",headers:{"Content-Type":"application/cbor",Accept:"text/plain",...this.commonHeaders()},body:d(e)}),s=await r.text();if(!r.ok)throw r.status===400?new Error(s):new Error("Could not submit transaction. Received status code: "+r.status);return s}commonHeaders(){return{"api-key":this.apiKey,lucid:dr}}maestroUtxoToUtxo(e){return{txHash:e.tx_hash,outputIndex:e.index,assets:(()=>{let t={};return e.assets.forEach(r=>{t[r.unit]=BigInt(r.amount)}),t})(),address:e.address,datumHash:e.datum?e.datum.type=="inline"?void 0:e.datum.hash:void 0,datum:e.datum?.bytes,scriptRef:e.reference_script?e.reference_script.type=="native"?void 0:{type:e.reference_script.type=="plutusv1"?"PlutusV1":"PlutusV2",script:q(e.reference_script.bytes)}:void 0}}},dr=ge.version;export{Ut as Blockfrost,o as C,j as Constr,ee as Data,Re as Emulator,Ht as Kupmios,$e as Lucid,T as M,jt as Maestro,He as MerkleTree,et as PROTOCOL_PARAMETERS_DEFAULT,be as SLOT_CONFIG_NETWORK,De as Tx,_e as TxComplete,je as TxSigned,Pe as Utils,$r as addAssets,q as applyDoubleCborEncoding,Rr as applyParamsToScript,me as assetsToValue,It as chunk,Fe as combineHash,Et as concat,Oe as coreToUtxo,Qe as createCostModels,Ws as datumJsonToCbor,Ae as equals,d as fromHex,ir as fromLabel,ar as fromScriptRef,vt as fromText,Ce as fromUnit,sr as generatePrivateKey,nr as generateSeedPhrase,D as getAddressDetails,ur as nativeScriptFromJson,oe as networkToId,ie as paymentCredentialOf,Ue as sha256,pt as slotToBeginUnixTime,rr as stakeCredentialOf,y as toHex,or as toLabel,Mr as toPublicKey,Ve as toScriptRef,Dr as toText,Ct as toUnit,ft as unixTimeToEnclosingSlot,ue as utxoToCore,We as valueToAssets}; +`)}}};function ts(a,e,t){let s=[],r=i.TransactionBuilderConfigBuilder.new(),n=i.BigNum.from_str(a.coinsPerUtxoByte.toString());s.push(n);let o=r.coins_per_utxo_byte(n);r.free();let c=i.BigNum.from_str(a.minFeeA.toString());s.push(c);let u=i.BigNum.from_str(a.minFeeB.toString());s.push(u);let l=i.LinearFee.new(c,u);s.push(l),r=o.fee_algo(l),o.free();let d=i.BigNum.from_str(a.keyDeposit.toString());s.push(d),o=r.key_deposit(d),r.free();let h=i.BigNum.from_str(a.poolDeposit.toString());s.push(h),r=o.pool_deposit(h),o.free(),o=r.max_tx_size(a.maxTxSize),r.free(),r=o.max_value_size(a.maxValSize),o.free(),o=r.collateral_percentage(a.collateralPercentage),r.free(),r=o.max_collateral_inputs(a.maxCollateralInputs),o.free();let f=i.BigNum.from_str(a.maxTxExMem.toString());s.push(f);let m=i.BigNum.from_str(a.maxTxExSteps.toString());s.push(m);let S=i.ExUnits.new(f,m);s.push(S),o=r.max_tx_ex_units(S),r.free();let v=i.ExUnitPrices.from_float(a.priceMem,a.priceStep);s.push(v),r=o.ex_unit_prices(v),o.free();let y=i.BigNum.from_str(e.zeroTime.toString());s.push(y);let B=i.BigNum.from_str(e.zeroSlot.toString());s.push(B),o=r.slot_config(y,B,e.slotLength),r.free();let I=i.Blockfrost.new(t?.url??"utils/tx/evaulate",t?.projectId??"");s.push(I),r=o.blockfrost(I),o.free();let N=kt(a.costModels);s.push(N),o=r.costmdls(N);let T=o.build();return o.free(),_.free(...s),T}var ut=class{constructor(){Object.defineProperty(this,"protocolParameters",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"slotConfig",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"wallet",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"provider",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"network",{enumerable:!0,configurable:!0,writable:!0,value:"Mainnet"}),Object.defineProperty(this,"utils",{enumerable:!0,configurable:!0,writable:!0,value:void 0})}static async new({provider:e,network:t,protocolParameters:s}){let r=new this;if(t&&(r.network=t),s&&(r.protocolParameters=s),e&&(r.provider=e,r.provider instanceof ct&&(r.network="Custom",He[r.network]={zeroTime:r.provider.now(),zeroSlot:0,slotLength:1e3})),e&&!r.protocolParameters){let n=await e.getProtocolParameters();r.protocolParameters=n}return r.slotConfig=He[r.network],r.utils=new Ge(r),r}getTransactionBuilderConfig(){if(!this.protocolParameters)throw new Error("Protocol parameters or slot config not set. Set a provider or iniatilize with protocol parameters.");return ts(this.protocolParameters,this.slotConfig,{url:this.provider?.url,projectId:this.provider?.projectId})}async switchProvider(e,t){if(this.network==="Custom")throw new Error("Cannot switch when on custom network.");let s=await ut.new({provider:e,network:t});return this.protocolParameters=s.protocolParameters,this.slotConfig=s.slotConfig,this.provider=e||this.provider,!this.protocolParameters&&e&&(this.protocolParameters=await e.getProtocolParameters()),this.network=t||this.network,this.wallet=s.wallet,this}newTx(){return new at(this)}fromTx(e){return new je(this,i.Transaction.from_bytes(g(e)))}newMessage(e,t){return new it(this,e,t)}verifyMessage(e,t,s){let{paymentCredential:r,stakeCredential:n,address:{hex:o}}=this.utils.getAddressDetails(e),c=r?.hash||n?.hash;if(!c)throw new Error("Not a valid address provided.");return es(o,c,t,s)}currentSlot(){return this.utils.unixTimeToSlot(Date.now())}utxosAt(e){return this.provider.getUtxos(e)}utxosAtWithUnit(e,t){return this.provider.getUtxosWithUnit(e,t)}utxoByUnit(e){return this.provider.getUtxoByUnit(e)}utxosByOutRef(e){return this.provider.getUtxosByOutRef(e)}delegationAt(e){return this.provider.getDelegation(e)}awaitTx(e,t=3e3){return this.provider.awaitTx(e,t)}async datumOf(e,t){if(!e.datum){if(!e.datumHash)throw new Error("This UTxO does not have a datum hash.");e.datum=await this.provider.getDatum(e.datumHash)}return pe.from(e.datum,t)}async metadataOf(e){let{policyId:t,name:s,label:r}=Ke(e);switch(r){case 222:case 333:case 444:{let n=await this.utxoByUnit(Wt(t,s,100)),o=await this.datumOf(n);return pe.toJson(o.fields[0])}default:throw new Error("No variant matched.")}}selectWalletFromPrivateKey(e){let t=i.PrivateKey.from_bech32(e),s=t.to_public();t.free();let r=s.hash();return s.free(),this.wallet={address:()=>{let n=[],o=i.StakeCredential.from_keyhash(r);n.push(o);let c=i.EnterpriseAddress.new(this.network==="Mainnet"?1:0,o);n.push(c);let u=c.to_address();n.push(u);let l=u.to_bech32(void 0);return _.free(...n),Promise.resolve(l)},rewardAddress:()=>Promise.resolve(null),getCollateralCore:()=>{},getUtxos:async()=>await this.utxosAt(ye(await this.wallet.address())),getUtxosCore:async()=>{let n=await this.utxosAt(ye(await this.wallet.address())),o=i.TransactionUnspentOutputs.new();return n.forEach(c=>{let u=we(c);o.add(u),u.free()}),o},getDelegation:()=>Promise.resolve({poolId:null,rewards:0n}),signTx:n=>{let o=[],c=n.body();o.push(c);let u=i.hash_transaction(c);o.push(u);let l=i.make_vkey_witness(u,t);o.push(l);let d=i.TransactionWitnessSetBuilder.new();o.push(d),d.add_vkey(l);let h=d.build();return _.free(...o),Promise.resolve(h)},signMessage:(n,o)=>{let{paymentCredential:c,address:{hex:u}}=this.utils.getAddressDetails(n),l=c?.hash,d=r.to_hex();if(!l||l!==d)throw new Error(`Cannot sign message for address: ${n}.`);return Promise.resolve(ze(u,o,e))},submitTx:async n=>await this.provider.submitTx(n)},this}selectWallet(e){let t=async()=>{let[s]=await e.getUsedAddresses();if(s)return s;let[r]=await e.getUnusedAddresses();return r};return this.wallet={address:async()=>{let s=await t(),r=i.Address.from_bytes(g(s)),n=r.to_bech32(void 0);return r.free(),n},rewardAddress:async()=>{let[s]=await e.getRewardAddresses();if(s){let r=i.Address.from_bytes(g(s)),n=i.RewardAddress.from_address(r);r.free();let o=n.to_address();n.free();let c=o.to_bech32(void 0);return o.free(),c}return null},getCollateralCore:()=>{},getUtxos:async()=>(await e.getUtxos()||[]).map(r=>{let n=i.TransactionUnspentOutput.from_bytes(g(r)),o=et(n);return n.free(),o}),getUtxosCore:async()=>{let s=i.TransactionUnspentOutputs.new();return(await e.getUtxos()||[]).forEach(r=>{let n=i.TransactionUnspentOutput.from_bytes(g(r));s.add(n),n.free()}),s},getDelegation:async()=>{let s=await this.wallet.rewardAddress();return s?await this.delegationAt(s):{poolId:null,rewards:0n}},signTx:async s=>{let r=await e.signTx(b(s.to_bytes()),!0);return i.TransactionWitnessSet.from_bytes(g(r))},signMessage:async(s,r)=>{let n=i.Address.from_bech32(s),o=b(n.to_bytes());return n.free(),await e.signData(o,r)},submitTx:async s=>await e.submitTx(s)},this}selectWalletFrom({address:e,utxos:t,rewardAddress:s,collateral:r}){let n=this.utils.getAddressDetails(e);return this.wallet={address:()=>Promise.resolve(e),rewardAddress:()=>{if(!s&&n.stakeCredential&&n.stakeCredential.type==="Key"){let o=i.Ed25519KeyHash.from_hex(n.stakeCredential.hash),c=i.StakeCredential.from_keyhash(o);o.free();let u=i.RewardAddress.new(this.network==="Mainnet"?1:0,c);c.free();let l=u.to_address();u.free();let d=l.to_bech32(void 0);return l.free(),Promise.resolve(d)}return Promise.resolve(s??null)},getCollateralCore:()=>{if(!r||!r.length)return;let o=i.TransactionUnspentOutputs.new();return r.forEach(c=>o.add(we(c))),o},getUtxos:async()=>t||await this.utxosAt(ye(e)),getUtxosCore:async()=>{let o=i.TransactionUnspentOutputs.new();return(t||await this.utxosAt(ye(e))).forEach(c=>{let u=we(c);o.add(u),u.free()}),o},getDelegation:async()=>{let o=await this.wallet.rewardAddress();return o?await this.delegationAt(o):{poolId:null,rewards:0n}},signTx:()=>Promise.reject("Not implemented"),signMessage:()=>Promise.reject("Not implemented"),submitTx:o=>this.provider.submitTx(o)},this}selectWalletFromSeed(e,t){let s=[],{address:r,rewardAddress:n,paymentKey:o,stakeKey:c}=Gt(e,{addressType:t?.addressType||"Base",accountIndex:t?.accountIndex||0,password:t?.password,network:this.network}),u=i.PrivateKey.from_bech32(o);s.push(u);let l=u.to_public();s.push(l);let d=l.hash();s.push(d);let h=d.to_hex(),m=c?(v=>{let y=i.PrivateKey.from_bech32(v);s.push(y);let B=y.to_public();s.push(B);let I=B.hash();return s.push(I),I.to_hex()})(c):"",S={[h]:o,[m]:c};return this.wallet={address:()=>Promise.resolve(r),rewardAddress:()=>Promise.resolve(n||null),getUtxos:()=>this.utxosAt(ye(r)),getCollateralCore:()=>{},getUtxosCore:async()=>{let v=i.TransactionUnspentOutputs.new();return(await this.utxosAt(ye(r))).forEach(y=>{let B=we(y);v.add(B),B.free()}),v},getDelegation:async()=>{let v=await this.wallet.rewardAddress();return v?await this.delegationAt(v):{poolId:null,rewards:0n}},signTx:async v=>{let y=await this.utxosAt(r),I=Qt(v,[h,m],y),N=i.TransactionWitnessSetBuilder.new();I.forEach($=>{let V=v.body(),G=i.hash_transaction(V);V.free();let he=i.PrivateKey.from_bech32(S[$]),R=i.make_vkey_witness(G,he);G.free(),he.free(),N.add_vkey(R),R.free()});let T=N.build();return N.free(),T},signMessage:(v,y)=>{let{paymentCredential:B,stakeCredential:I,address:{hex:N}}=this.utils.getAddressDetails(v),T=B?.hash||I?.hash,$=S[T];if(!$)throw new Error(`Cannot sign message for address: ${v}.`);return Promise.resolve(ze(N,y,$))},submitTx:async v=>await this.provider.submitTx(v)},_.free(...s),this}};var ss=class{constructor(e,t){Object.defineProperty(this,"url",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"projectId",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.url=e,this.projectId=t||""}async getProtocolParameters(){let e=await fetch(`${this.url}/epochs/latest/parameters`,{headers:{project_id:this.projectId,lucid:se}}).then(t=>t.json());return{minFeeA:parseInt(e.min_fee_a),minFeeB:parseInt(e.min_fee_b),maxTxSize:parseInt(e.max_tx_size),maxValSize:parseInt(e.max_val_size),keyDeposit:BigInt(e.key_deposit),poolDeposit:BigInt(e.pool_deposit),priceMem:parseFloat(e.price_mem),priceStep:parseFloat(e.price_step),maxTxExMem:BigInt(e.max_tx_ex_mem),maxTxExSteps:BigInt(e.max_tx_ex_steps),coinsPerUtxoByte:BigInt(e.coins_per_utxo_size),collateralPercentage:parseInt(e.collateral_percent),maxCollateralInputs:parseInt(e.max_collateral_inputs),costModels:e.cost_models}}async getUtxos(e){let t=(()=>{if(typeof e=="string")return e;let n=e.type==="Key"?i.Ed25519KeyHash.from_hex(e.hash):i.ScriptHash.from_hex(e.hash),o=n.to_bech32("addr_vkh");return n.free(),o})(),s=[],r=1;for(;;){let n=await fetch(`${this.url}/addresses/${t}/utxos?page=${r}`,{headers:{project_id:this.projectId,lucid:se}}).then(o=>o.json());if(n.error){if(n.status_code===404)return[];throw new Error("Could not fetch UTxOs from Blockfrost. Try again.")}if(s=s.concat(n),n.length<=0)break;r++}return this.blockfrostUtxosToUtxos(s)}async getUtxosWithUnit(e,t){let s=(()=>{if(typeof e=="string")return e;let o=e.type==="Key"?i.Ed25519KeyHash.from_hex(e.hash):i.ScriptHash.from_hex(e.hash),c=o.to_bech32("addr_vkh");return o.free(),c})(),r=[],n=1;for(;;){let o=await fetch(`${this.url}/addresses/${s}/utxos/${t}?page=${n}`,{headers:{project_id:this.projectId,lucid:se}}).then(c=>c.json());if(o.error){if(o.status_code===404)return[];throw new Error("Could not fetch UTxOs from Blockfrost. Try again.")}if(r=r.concat(o),o.length<=0)break;n++}return this.blockfrostUtxosToUtxos(r)}async getUtxoByUnit(e){let t=await fetch(`${this.url}/assets/${e}/addresses?count=2`,{headers:{project_id:this.projectId,lucid:se}}).then(n=>n.json());if(!t||t.error)throw new Error("Unit not found.");if(t.length>1)throw new Error("Unit needs to be an NFT or only held by one address.");let s=t[0].address,r=await this.getUtxosWithUnit(s,e);if(r.length>1)throw new Error("Unit needs to be an NFT or only held by one address.");return r[0]}async getUtxosByOutRef(e){let t=[...new Set(e.map(r=>r.txHash))];return(await Promise.all(t.map(async r=>{let n=await fetch(`${this.url}/txs/${r}/utxos`,{headers:{project_id:this.projectId,lucid:se}}).then(c=>c.json());if(!n||n.error)return[];let o=n.outputs.map(c=>({...c,tx_hash:r}));return this.blockfrostUtxosToUtxos(o)}))).reduce((r,n)=>r.concat(n),[]).filter(r=>e.some(n=>r.txHash===n.txHash&&r.outputIndex===n.outputIndex))}async getDelegation(e){let t=await fetch(`${this.url}/accounts/${e}`,{headers:{project_id:this.projectId,lucid:se}}).then(s=>s.json());return!t||t.error?{poolId:null,rewards:0n}:{poolId:t.pool_id||null,rewards:BigInt(t.withdrawable_amount)}}async getDatum(e){let t=await fetch(`${this.url}/scripts/datum/${e}/cbor`,{headers:{project_id:this.projectId,lucid:se}}).then(s=>s.json()).then(s=>s.cbor);if(!t||t.error)throw new Error(`No datum found for datum hash: ${e}`);return t}awaitTx(e,t=3e3){return new Promise(s=>{let r=setInterval(async()=>{let n=await fetch(`${this.url}/txs/${e}`,{headers:{project_id:this.projectId,lucid:se}}).then(o=>o.json());if(n&&!n.error)return clearInterval(r),await new Promise(o=>setTimeout(()=>o(1),1e3)),s(!0)},t)})}async submitTx(e){let t=await fetch(`${this.url}/tx/submit`,{method:"POST",headers:{"Content-Type":"application/cbor",project_id:this.projectId,lucid:se},body:g(e)}).then(s=>s.json());if(!t||t.error)throw t?.status_code===400?new Error(t.message):new Error("Could not submit transaction.");return t}async blockfrostUtxosToUtxos(e){return await Promise.all(e.map(async t=>({txHash:t.tx_hash,outputIndex:t.output_index,assets:Object.fromEntries(t.amount.map(({unit:s,quantity:r})=>[s,BigInt(r)])),address:t.address,datumHash:!t.inline_datum&&t.data_hash||void 0,datum:t.inline_datum||void 0,scriptRef:t.reference_script_hash?await(async()=>{let{type:s}=await fetch(`${this.url}/scripts/${t.reference_script_hash}`,{headers:{project_id:this.projectId,lucid:se}}).then(n=>n.json());if(s==="Native"||s==="native")throw new Error("Native script ref not implemented!");let{cbor:r}=await fetch(`${this.url}/scripts/${t.reference_script_hash}/cbor`,{headers:{project_id:this.projectId,lucid:se}}).then(n=>n.json());return{type:s==="plutusV1"?"PlutusV1":"PlutusV2",script:Z(r)}})():void 0})))}};function On(a){let e=r=>{let n=[];try{if(isNaN(r.int)){if(r.bytes||!isNaN(Number(r.bytes)))return i.PlutusData.new_bytes(g(r.bytes));if(r.map){let o=i.PlutusMap.new();return n.push(o),r.map.forEach(({k:c,v:u})=>{let l=e(c);n.push(l);let d=e(u);n.push(d),o.insert(l,d)}),i.PlutusData.new_map(o)}else if(r.list){let o=i.PlutusList.new();return n.push(o),r.list.forEach(c=>{let u=e(c);n.push(u),o.add(u)}),i.PlutusData.new_list(o)}else if(!isNaN(r.constructor)){let o=i.PlutusList.new();n.push(o),r.fields.forEach(l=>{let d=e(l);n.push(d),o.add(d)});let c=i.BigNum.from_str(r.constructor.toString());n.push(c);let u=i.ConstrPlutusData.new(c,o);return n.push(u),i.PlutusData.new_constr_plutus_data(u)}}else{let o=i.BigInt.from_str(r.int.toString());return n.push(o),i.PlutusData.new_integer(o)}throw new Error("Unsupported type")}finally{_.free(...n)}},t=e(a),s=t.to_bytes();return t.free(),b(s)}var se=Be.version;var rs=class{constructor(e,t){Object.defineProperty(this,"kupoUrl",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"ogmiosUrl",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.kupoUrl=e,this.ogmiosUrl=t}async getProtocolParameters(){let e=await this.ogmiosWsp("Query",{query:"currentProtocolParameters"});return new Promise((t,s)=>{e.addEventListener("message",r=>{try{let{result:n}=JSON.parse(r.data),o={};Object.keys(n.costModels).forEach(h=>{let m="Plutus"+h.split(":")[1].toUpperCase();o[m]=n.costModels[h]});let[c,u]=n.prices.memory.split("/"),[l,d]=n.prices.steps.split("/");t({minFeeA:parseInt(n.minFeeCoefficient),minFeeB:parseInt(n.minFeeConstant),maxTxSize:parseInt(n.maxTxSize),maxValSize:parseInt(n.maxValueSize),keyDeposit:BigInt(n.stakeKeyDeposit),poolDeposit:BigInt(n.poolDeposit),priceMem:parseInt(c)/parseInt(u),priceStep:parseInt(l)/parseInt(d),maxTxExMem:BigInt(n.maxExecutionUnitsPerTransaction.memory),maxTxExSteps:BigInt(n.maxExecutionUnitsPerTransaction.steps),coinsPerUtxoByte:BigInt(n.coinsPerUtxoByte),collateralPercentage:parseInt(n.collateralPercentage),maxCollateralInputs:parseInt(n.maxCollateralInputs),costModels:o}),e.close()}catch(n){s(n)}},{once:!0})})}async getUtxos(e){let t=typeof e=="string",s=t?e:e.hash,r=await fetch(`${this.kupoUrl}/matches/${s}${t?"":"/*"}?unspent`).then(n=>n.json());return this.kupmiosUtxosToUtxos(r)}async getUtxosWithUnit(e,t){let s=typeof e=="string",r=s?e:e.hash,{policyId:n,assetName:o}=Ke(t),c=await fetch(`${this.kupoUrl}/matches/${r}${s?"":"/*"}?unspent&policy_id=${n}${o?`&asset_name=${o}`:""}`).then(u=>u.json());return this.kupmiosUtxosToUtxos(c)}async getUtxoByUnit(e){let{policyId:t,assetName:s}=Ke(e),r=await fetch(`${this.kupoUrl}/matches/${t}.${s?`${s}`:"*"}?unspent`).then(o=>o.json()),n=await this.kupmiosUtxosToUtxos(r);if(n.length>1)throw new Error("Unit needs to be an NFT or only held by one address.");return n[0]}async getUtxosByOutRef(e){let t=[...new Set(e.map(r=>r.txHash))];return(await Promise.all(t.map(async r=>{let n=await fetch(`${this.kupoUrl}/matches/*@${r}?unspent`).then(o=>o.json());return this.kupmiosUtxosToUtxos(n)}))).reduce((r,n)=>r.concat(n),[]).filter(r=>e.some(n=>r.txHash===n.txHash&&r.outputIndex===n.outputIndex))}async getDelegation(e){let t=await this.ogmiosWsp("Query",{query:{delegationsAndRewards:[e]}});return new Promise((s,r)=>{t.addEventListener("message",n=>{try{let{result:o}=JSON.parse(n.data),c=o?Object.values(o)[0]:{};s({poolId:c?.delegate||null,rewards:BigInt(c?.rewards||0)}),t.close()}catch(o){r(o)}},{once:!0})})}async getDatum(e){let t=await fetch(`${this.kupoUrl}/datums/${e}`).then(s=>s.json());if(!t||!t.datum)throw new Error(`No datum found for datum hash: ${e}`);return t.datum}awaitTx(e,t=3e3){return new Promise(s=>{let r=setInterval(async()=>{let n=await fetch(`${this.kupoUrl}/matches/*@${e}?unspent`).then(o=>o.json());if(n&&n.length>0)return clearInterval(r),await new Promise(o=>setTimeout(()=>o(1),1e3)),s(!0)},t)})}async submitTx(e){let t=await this.ogmiosWsp("SubmitTx",{submit:e});return new Promise((s,r)=>{t.addEventListener("message",n=>{try{let{result:o}=JSON.parse(n.data);o.SubmitSuccess?s(o.SubmitSuccess.txId):r(o.SubmitFail),t.close()}catch(o){r(o)}},{once:!0})})}kupmiosUtxosToUtxos(e){return Promise.all(e.map(async t=>({txHash:t.transaction_id,outputIndex:parseInt(t.output_index),address:t.address,assets:(()=>{let s={lovelace:BigInt(t.value.coins)};return Object.keys(t.value.assets).forEach(r=>{s[r.replace(".","")]=BigInt(t.value.assets[r])}),s})(),datumHash:t?.datum_type==="hash"?t.datum_hash:null,datum:t?.datum_type==="inline"?await this.getDatum(t.datum_hash):null,scriptRef:t.script_hash&&await(async()=>{let{script:s,language:r}=await fetch(`${this.kupoUrl}/scripts/${t.script_hash}`).then(n=>n.json());if(r==="native")return{type:"Native",script:s};if(r==="plutus:v1"){let n=i.PlutusScript.new(g(s)),o=n.to_bytes();return n.free(),{type:"PlutusV1",script:b(o)}}else if(r==="plutus:v2"){let n=i.PlutusScript.new(g(s)),o=n.to_bytes();return n.free(),{type:"PlutusV2",script:b(o)}}})()})))}async ogmiosWsp(e,t){let s=new WebSocket(this.ogmiosUrl);return await new Promise(r=>{s.addEventListener("open",()=>r(1),{once:!0})}),s.send(JSON.stringify({type:"jsonwsp/request",version:"1.0",servicename:"ogmios",methodname:e,args:t})),s}};var ns=class{constructor({network:e,apiKey:t,turboSubmit:s=!1}){Object.defineProperty(this,"url",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"apiKey",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"turboSubmit",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.url=`https://${e}.gomaestro-api.org/v1`,this.apiKey=t,this.turboSubmit=s}async getProtocolParameters(){let t=(await fetch(`${this.url}/protocol-params`,{headers:this.commonHeaders()}).then(n=>n.json())).data,s=n=>{let o=n.indexOf("/");return parseInt(n.slice(0,o))/parseInt(n.slice(o+1))},r=(n,o)=>{let c=Object.keys(n).sort().map(u=>({[o[u]||u]:Object.fromEntries(Object.entries(n[u]).sort(([d,h],[f,m])=>d.localeCompare(f)))}));return Object.assign({},...c)};return{minFeeA:parseInt(t.min_fee_coefficient),minFeeB:parseInt(t.min_fee_constant),maxTxSize:parseInt(t.max_tx_size),maxValSize:parseInt(t.max_value_size),keyDeposit:BigInt(t.stake_key_deposit),poolDeposit:BigInt(t.pool_deposit),priceMem:s(t.prices.memory),priceStep:s(t.prices.steps),maxTxExMem:BigInt(t.max_execution_units_per_transaction.memory),maxTxExSteps:BigInt(t.max_execution_units_per_transaction.steps),coinsPerUtxoByte:BigInt(t.coins_per_utxo_byte),collateralPercentage:parseInt(t.collateral_percentage),maxCollateralInputs:parseInt(t.max_collateral_inputs),costModels:r(t.cost_models,{"plutus:v1":"PlutusV1","plutus:v2":"PlutusV2"})}}async getUtxosInternal(e,t){let s=(()=>{if(typeof e=="string")return"/addresses/"+e;let o=e.type=="Key"?i.Ed25519KeyHash.from_hex(e.hash):i.ScriptHash.from_hex(e.hash),c="/addresses/cred/";return c+=e.type==="Key"?o.to_bech32("addr_vkh"):o.to_bech32("addr_shared_vkh"),o.free(),c})(),r=new URLSearchParams({count:"100",...t&&{asset:t}});return(await this.getAllPagesData(async o=>await fetch(o,{headers:this.commonHeaders()}),`${this.url}${s}/utxos`,r,"Location: getUtxosInternal. Error: Could not fetch UTxOs from Maestro")).map(this.maestroUtxoToUtxo)}getUtxos(e){return this.getUtxosInternal(e)}getUtxosWithUnit(e,t){return this.getUtxosInternal(e,t)}async getUtxoByUnit(e){let t=await fetch(`${this.url}/assets/${e}/addresses?count=2`,{headers:this.commonHeaders()}),s=await t.json();if(!t.ok)throw s.message?new Error(s.message):new Error("Location: getUtxoByUnit. Error: Couldn't perform query. Received status code: "+t.status);let r=s.data;if(r.length===0)throw new Error("Location: getUtxoByUnit. Error: Unit not found.");if(r.length>1)throw new Error("Location: getUtxoByUnit. Error: Unit needs to be an NFT or only held by one address.");let n=r[0].address,o=await this.getUtxosWithUnit(n,e);if(o.length>1)throw new Error("Location: getUtxoByUnit. Error: Unit needs to be an NFT or only held by one address.");return o[0]}async getUtxosByOutRef(e){let t=`${this.url}/transactions/outputs`,s=JSON.stringify(e.map(({txHash:n,outputIndex:o})=>`${n}#${o}`));return(await this.getAllPagesData(async n=>await fetch(n,{method:"POST",headers:{"Content-Type":"application/json",...this.commonHeaders()},body:s}),t,new URLSearchParams({}),"Location: getUtxosByOutRef. Error: Could not fetch UTxOs by references from Maestro")).map(this.maestroUtxoToUtxo)}async getDelegation(e){let t=await fetch(`${this.url}/accounts/${e}`,{headers:this.commonHeaders()});if(!t.ok)return{poolId:null,rewards:0n};let r=(await t.json()).data;return{poolId:r.delegated_pool||null,rewards:BigInt(r.rewards_available)}}async getDatum(e){let t=await fetch(`${this.url}/datum/${e}`,{headers:this.commonHeaders()});if(!t.ok)throw t.status===404?new Error(`No datum found for datum hash: ${e}`):new Error("Location: getDatum. Error: Couldn't successfully perform query. Received status code: "+t.status);return(await t.json()).data.bytes}awaitTx(e,t=3e3){return new Promise(s=>{let r=setInterval(async()=>{let n=await fetch(`${this.url}/transactions/${e}/cbor`,{headers:this.commonHeaders()});if(n.ok)return await n.json(),clearInterval(r),await new Promise(o=>setTimeout(()=>o(1),1e3)),s(!0)},t)})}async submitTx(e){let t=`${this.url}/txmanager`;t+=this.turboSubmit?"/turbosubmit":"";let s=await fetch(t,{method:"POST",headers:{"Content-Type":"application/cbor",Accept:"text/plain",...this.commonHeaders()},body:g(e)}),r=await s.text();if(!s.ok)throw s.status===400?new Error(r):new Error("Could not submit transaction. Received status code: "+s.status);return r}commonHeaders(){return{"api-key":this.apiKey,lucid:Os}}maestroUtxoToUtxo(e){return{txHash:e.tx_hash,outputIndex:e.index,assets:(()=>{let t={};return e.assets.forEach(s=>{t[s.unit]=BigInt(s.amount)}),t})(),address:e.address,datumHash:e.datum?e.datum.type=="inline"?void 0:e.datum.hash:void 0,datum:e.datum?.bytes,scriptRef:e.reference_script?e.reference_script.type=="native"?void 0:{type:e.reference_script.type=="plutusv1"?"PlutusV1":"PlutusV2",script:Z(e.reference_script.bytes)}:void 0}}async getAllPagesData(e,t,s,r){let n=null,o=[];for(;;){n!==null&&s.set("cursor",n);let c=await e(`${t}?`+s),u=await c.json();if(!c.ok)throw new Error(`${r}. Received status code: ${c.status}`);if(n=u.next_cursor,o=o.concat(u.data),n==null)break}return o}},Os=Be.version;export{ss as Blockfrost,i as C,z as Constr,pe as Data,ct as Emulator,_ as Freeables,rs as Kupmios,ut as Lucid,D as M,ns as Maestro,rt as MerkleTree,Je as PROTOCOL_PARAMETERS_DEFAULT,He as SLOT_CONFIG_NETWORK,at as Tx,je as TxComplete,ot as TxSigned,Ge as Utils,hr as addAssets,Ne as addressFromWithNetworkCheck,Z as applyDoubleCborEncoding,dr as applyParamsToScript,xe as assetsToValue,Le as attachScript,Jt as chunk,gt as combineHash,Xt as concat,et as coreToUtxo,kt as createCostModels,xt as createOutput,yt as createPoolRegistration,On as datumJsonToCbor,tt as equals,g as fromHex,Ts as fromLabel,Es as fromScriptRef,Ft as fromText,Ke as fromUnit,Is as generatePrivateKey,Cs as generateSeedPhrase,J as getAddressDetails,Yt as getDatumFromOutputData,Ue as getScriptWitness,nt as getStakeCredential,Ps as nativeScriptFromJson,Oe as networkToId,ye as paymentCredentialOf,st as sha256,jt as slotToBeginUnixTime,Ss as stakeCredentialOf,b as toHex,Bs as toLabel,lr as toPublicKey,Qe as toScriptRef,ur as toText,Wt as toUnit,Dt as unixTimeToEnclosingSlot,we as utxoToCore,ft as valueToAssets}; diff --git a/docs/docs/getting-started/choose-provider.md b/docs/docs/getting-started/choose-provider.md index 57e70046..920750a5 100644 --- a/docs/docs/getting-started/choose-provider.md +++ b/docs/docs/getting-started/choose-provider.md @@ -46,9 +46,9 @@ import { Lucid, Maestro } from "https://deno.land/x/lucid/mod.ts"; const lucid = await Lucid.new( new Maestro({ - network: "Preprod", // For MAINNET: "Mainnet". - apiKey: "", // Get yours by visiting https://docs.gomaestro.org/docs/Getting-started/Sign-up-login. - turboSubmit: false // Read about paid turbo transaction submission feature at https://docs.gomaestro.org/docs/Dapp%20Platform/Turbo%20Transaction. + network: "Preprod", // For MAINNET: "Mainnet". + apiKey: "", // Get yours by visiting https://docs.gomaestro.org/docs/Getting-started/Sign-up-login. + turboSubmit: false, // Read about paid turbo transaction submission feature at https://docs.gomaestro.org/docs/Dapp%20Platform/Turbo%20Transaction. }), "Preprod", // For MAINNET: "Mainnet". ); diff --git a/package.json b/package.json index 2aaa57c6..d73ae86c 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "@jpg-store/lucid-cardano", - "version": "0.10.12", + "version": "0.11.0", "license": "MIT", "description": "This is a fork of the original Lucid repo compiled into CommonJS. For more information check https://github.com/spacebudz/lucid", "repository": "https://github.com/jpg-store/lucid", diff --git a/src/core/libs/cardano_message_signing/cardano_message_signing.generated.js b/src/core/libs/cardano_message_signing/cardano_message_signing.generated.js index b7a65105..65870411 100644 --- a/src/core/libs/cardano_message_signing/cardano_message_signing.generated.js +++ b/src/core/libs/cardano_message_signing/cardano_message_signing.generated.js @@ -1144,7 +1144,7 @@ export class COSEEncrypt { ciphertext() { try { const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); - wasm.coseencrypt0_ciphertext(retptr, this.ptr); + wasm.coseencrypt_ciphertext(retptr, this.ptr); var r0 = getInt32Memory0()[retptr / 4 + 0]; var r1 = getInt32Memory0()[retptr / 4 + 1]; let v0; @@ -1745,7 +1745,7 @@ export class COSESign { payload() { try { const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); - wasm.coseencrypt0_ciphertext(retptr, this.ptr); + wasm.coseencrypt_ciphertext(retptr, this.ptr); var r0 = getInt32Memory0()[retptr / 4 + 0]; var r1 = getInt32Memory0()[retptr / 4 + 1]; let v0; @@ -1856,7 +1856,7 @@ export class COSESign1 { payload() { try { const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); - wasm.coseencrypt0_ciphertext(retptr, this.ptr); + wasm.coseencrypt_ciphertext(retptr, this.ptr); var r0 = getInt32Memory0()[retptr / 4 + 0]; var r1 = getInt32Memory0()[retptr / 4 + 1]; let v0; @@ -2154,7 +2154,7 @@ export class COSESignature { signature() { try { const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); - wasm.cosesignature_signature(retptr, this.ptr); + wasm.cosesign1_signature(retptr, this.ptr); var r0 = getInt32Memory0()[retptr / 4 + 0]; var r1 = getInt32Memory0()[retptr / 4 + 1]; var v0 = getArrayU8FromWasm0(r0, r1).slice(); diff --git a/src/core/libs/cardano_message_signing/cardano_message_signing_bg.wasm b/src/core/libs/cardano_message_signing/cardano_message_signing_bg.wasm index 005b5601..9497ff2c 100644 Binary files a/src/core/libs/cardano_message_signing/cardano_message_signing_bg.wasm and b/src/core/libs/cardano_message_signing/cardano_message_signing_bg.wasm differ diff --git a/src/core/libs/cardano_message_signing/nodejs/cardano_message_signing.generated.js b/src/core/libs/cardano_message_signing/nodejs/cardano_message_signing.generated.js index edefd41a..6222db2d 100644 --- a/src/core/libs/cardano_message_signing/nodejs/cardano_message_signing.generated.js +++ b/src/core/libs/cardano_message_signing/nodejs/cardano_message_signing.generated.js @@ -1162,7 +1162,7 @@ class COSEEncrypt { ciphertext() { try { const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); - wasm.coseencrypt0_ciphertext(retptr, this.ptr); + wasm.coseencrypt_ciphertext(retptr, this.ptr); var r0 = getInt32Memory0()[retptr / 4 + 0]; var r1 = getInt32Memory0()[retptr / 4 + 1]; let v0; @@ -1768,7 +1768,7 @@ class COSESign { payload() { try { const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); - wasm.coseencrypt0_ciphertext(retptr, this.ptr); + wasm.coseencrypt_ciphertext(retptr, this.ptr); var r0 = getInt32Memory0()[retptr / 4 + 0]; var r1 = getInt32Memory0()[retptr / 4 + 1]; let v0; @@ -1880,7 +1880,7 @@ class COSESign1 { payload() { try { const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); - wasm.coseencrypt0_ciphertext(retptr, this.ptr); + wasm.coseencrypt_ciphertext(retptr, this.ptr); var r0 = getInt32Memory0()[retptr / 4 + 0]; var r1 = getInt32Memory0()[retptr / 4 + 1]; let v0; @@ -2181,7 +2181,7 @@ class COSESignature { signature() { try { const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); - wasm.cosesignature_signature(retptr, this.ptr); + wasm.cosesign1_signature(retptr, this.ptr); var r0 = getInt32Memory0()[retptr / 4 + 0]; var r1 = getInt32Memory0()[retptr / 4 + 1]; var v0 = getArrayU8FromWasm0(r0, r1).slice(); diff --git a/src/core/libs/cardano_multiplatform_lib/cardano_multiplatform_lib.generated.js b/src/core/libs/cardano_multiplatform_lib/cardano_multiplatform_lib.generated.js index e57ad857..a4cb7aa5 100644 --- a/src/core/libs/cardano_multiplatform_lib/cardano_multiplatform_lib.generated.js +++ b/src/core/libs/cardano_multiplatform_lib/cardano_multiplatform_lib.generated.js @@ -1,9 +1,31 @@ // @generated file from wasmbuild -- do not edit // deno-lint-ignore-file // deno-fmt-ignore-file -// source-hash: ab17726f2df5571be15d036e67423022ed8f63e4 +// source-hash: fea5fc75a13596f0eb0af3e358328b34adb4ded3 let wasm; +const heap = new Array(128).fill(undefined); + +heap.push(undefined, null, true, false); + +function getObject(idx) { + return heap[idx]; +} + +let heap_next = heap.length; + +function dropObject(idx) { + if (idx < 132) return; + heap[idx] = heap_next; + heap_next = idx; +} + +function takeObject(idx) { + const ret = getObject(idx); + dropObject(idx); + return ret; +} + const cachedTextDecoder = new TextDecoder("utf-8", { ignoreBOM: true, fatal: true, @@ -24,12 +46,6 @@ function getStringFromWasm0(ptr, len) { return cachedTextDecoder.decode(getUint8Memory0().subarray(ptr, ptr + len)); } -const heap = new Array(128).fill(undefined); - -heap.push(undefined, null, true, false); - -let heap_next = heap.length; - function addHeapObject(obj) { if (heap_next === heap.length) heap.push(heap.length + 1); const idx = heap_next; @@ -39,22 +55,6 @@ function addHeapObject(obj) { return idx; } -function getObject(idx) { - return heap[idx]; -} - -function dropObject(idx) { - if (idx < 132) return; - heap[idx] = heap_next; - heap_next = idx; -} - -function takeObject(idx) { - const ret = getObject(idx); - dropObject(idx); - return ret; -} - let WASM_VECTOR_LEN = 0; const cachedTextEncoder = new TextEncoder("utf-8"); @@ -207,12 +207,11 @@ function makeMutClosure(arg0, arg1, dtor, f) { return real; } function __wbg_adapter_30(arg0, arg1, arg2) { - wasm - ._dyn_core__ops__function__FnMut__A____Output___R_as_wasm_bindgen__closure__WasmClosure___describe__invoke__h9de9452916ac8cca( - arg0, - arg1, - addHeapObject(arg2), - ); + wasm.wasm_bindgen__convert__closures__invoke1_mut__hee80fd123b909250( + arg0, + arg1, + addHeapObject(arg2), + ); } function _assertClass(instance, klass) { @@ -817,8 +816,8 @@ function handleError(f, args) { wasm.__wbindgen_exn_store(addHeapObject(e)); } } -function __wbg_adapter_1680(arg0, arg1, arg2, arg3) { - wasm.wasm_bindgen__convert__closures__invoke2_mut__h36afefe016e25d40( +function __wbg_adapter_1681(arg0, arg1, arg2, arg3) { + wasm.wasm_bindgen__convert__closures__invoke2_mut__h5b4d9f16616fac4b( arg0, arg1, addHeapObject(arg2), @@ -7935,7 +7934,7 @@ export class GovernanceActionId { * @returns {BigNum} */ governance_action_index() { - const ret = wasm.constrplutusdata_alternative(this.ptr); + const ret = wasm.governanceactionid_governance_action_index(this.ptr); return BigNum.__wrap(ret); } /** @@ -8391,7 +8390,7 @@ export class HeaderBody { * @returns {BigNum} */ slot() { - const ret = wasm.constrplutusdata_alternative(this.ptr); + const ret = wasm.headerbody_slot(this.ptr); return BigNum.__wrap(ret); } /** @@ -8658,7 +8657,7 @@ export class Int { as_i32_or_nothing() { try { const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); - wasm.int_as_i32(retptr, this.ptr); + wasm.int_as_i32_or_nothing(retptr, this.ptr); var r0 = getInt32Memory0()[retptr / 4 + 0]; var r1 = getInt32Memory0()[retptr / 4 + 1]; return r0 === 0 ? undefined : r1; @@ -9532,14 +9531,14 @@ export class LinearFee { * @returns {BigNum} */ constant() { - const ret = wasm.constrplutusdata_alternative(this.ptr); + const ret = wasm.linearfee_constant(this.ptr); return BigNum.__wrap(ret); } /** * @returns {BigNum} */ coefficient() { - const ret = wasm.exunits_steps(this.ptr); + const ret = wasm.linearfee_coefficient(this.ptr); return BigNum.__wrap(ret); } /** @@ -11819,7 +11818,7 @@ export class NewConstitution { * @returns {DataHash} */ hash() { - const ret = wasm.newconstitution_hash(this.ptr); + const ret = wasm.genesiskeydelegation_vrf_keyhash(this.ptr); return DataHash.__wrap(ret); } /** @@ -12080,7 +12079,7 @@ export class OperationalCert { * @returns {number} */ sequence_number() { - const ret = wasm.networkinfo_protocol_magic(this.ptr); + const ret = wasm.operationalcert_sequence_number(this.ptr); return ret >>> 0; } /** @@ -13484,28 +13483,28 @@ export class PoolParams { * @returns {VRFKeyHash} */ vrf_keyhash() { - const ret = wasm.poolparams_vrf_keyhash(this.ptr); + const ret = wasm.governanceactionid_transaction_id(this.ptr); return VRFKeyHash.__wrap(ret); } /** * @returns {BigNum} */ pledge() { - const ret = wasm.constrplutusdata_alternative(this.ptr); + const ret = wasm.governanceactionid_governance_action_index(this.ptr); return BigNum.__wrap(ret); } /** * @returns {BigNum} */ cost() { - const ret = wasm.exunits_steps(this.ptr); + const ret = wasm.poolparams_cost(this.ptr); return BigNum.__wrap(ret); } /** * @returns {UnitInterval} */ margin() { - const ret = wasm.drepvotingthresholds_committee_normal(this.ptr); + const ret = wasm.drepvotingthresholds_update_constitution(this.ptr); return UnitInterval.__wrap(ret); } /** @@ -13876,7 +13875,7 @@ export class PoolRetirement { * @returns {number} */ epoch() { - const ret = wasm.networkinfo_protocol_magic(this.ptr); + const ret = wasm.poolretirement_epoch(this.ptr); return ret >>> 0; } /** @@ -14425,7 +14424,7 @@ export class ProposalProcedure { * @returns {BigNum} */ deposit() { - const ret = wasm.constrplutusdata_alternative(this.ptr); + const ret = wasm.proposalprocedure_deposit(this.ptr); return BigNum.__wrap(ret); } /** @@ -15549,7 +15548,7 @@ export class ProtocolVersion { * @returns {number} */ minor() { - const ret = wasm.operationalcert_kes_period(this.ptr); + const ret = wasm.protocolversion_minor(this.ptr); return ret >>> 0; } /** @@ -15814,14 +15813,14 @@ export class Redeemer { * @returns {BigNum} */ index() { - const ret = wasm.constrplutusdata_alternative(this.ptr); + const ret = wasm.poolparams_cost(this.ptr); return BigNum.__wrap(ret); } /** * @returns {PlutusData} */ data() { - const ret = wasm.redeemer_data(this.ptr); + const ret = wasm.data_get(this.ptr); return PlutusData.__wrap(ret); } /** @@ -16378,14 +16377,14 @@ export class RegCommitteeHotKeyCert { * @returns {Ed25519KeyHash} */ committee_cold_keyhash() { - const ret = wasm.genesiskeydelegation_genesishash(this.ptr); + const ret = wasm.regcommitteehotkeycert_committee_cold_keyhash(this.ptr); return Ed25519KeyHash.__wrap(ret); } /** * @returns {Ed25519KeyHash} */ committee_hot_keyhash() { - const ret = wasm.genesiskeydelegation_genesis_delegate_hash(this.ptr); + const ret = wasm.regcommitteehotkeycert_committee_hot_keyhash(this.ptr); return Ed25519KeyHash.__wrap(ret); } /** @@ -16935,7 +16934,7 @@ export class RequiredWitnessSet { */ add_vkey_key(vkey) { _assertClass(vkey, Vkey); - wasm.requiredwitnessset_add_vkey(this.ptr, vkey.ptr); + wasm.requiredwitnessset_add_vkey_key(this.ptr, vkey.ptr); } /** * @param {Ed25519KeyHash} hash @@ -18355,14 +18354,14 @@ export class ScriptNOfK { * @returns {number} */ n() { - const ret = wasm.networkinfo_protocol_magic(this.ptr); + const ret = wasm.scriptnofk_n(this.ptr); return ret >>> 0; } /** * @returns {NativeScripts} */ native_scripts() { - const ret = wasm.scriptnofk_native_scripts(this.ptr); + const ret = wasm.scriptall_native_scripts(this.ptr); return NativeScripts.__wrap(ret); } /** @@ -18508,7 +18507,7 @@ export class ScriptPubkey { * @returns {Ed25519KeyHash} */ addr_keyhash() { - const ret = wasm.genesiskeydelegation_genesishash(this.ptr); + const ret = wasm.regcommitteehotkeycert_committee_cold_keyhash(this.ptr); return Ed25519KeyHash.__wrap(ret); } /** @@ -19110,7 +19109,7 @@ export class SingleHostName { * @returns {DNSRecordAorAAAA} */ dns_name() { - const ret = wasm.anchor_anchor_url(this.ptr); + const ret = wasm.singlehostname_dns_name(this.ptr); return DNSRecordAorAAAA.__wrap(ret); } /** @@ -19585,7 +19584,7 @@ export class StakeDelegation { * @returns {StakeCredential} */ stake_credential() { - const ret = wasm.stakedelegation_stake_credential(this.ptr); + const ret = wasm.baseaddress_payment_cred(this.ptr); return StakeCredential.__wrap(ret); } /** @@ -19742,7 +19741,7 @@ export class StakeDeregistration { * @returns {StakeCredential} */ stake_credential() { - const ret = wasm.stakedelegation_stake_credential(this.ptr); + const ret = wasm.baseaddress_payment_cred(this.ptr); return StakeCredential.__wrap(ret); } /** @@ -19887,7 +19886,7 @@ export class StakeRegDelegCert { * @returns {StakeCredential} */ stake_credential() { - const ret = wasm.regcert_stake_credential(this.ptr); + const ret = wasm.stakeregdelegcert_stake_credential(this.ptr); return StakeCredential.__wrap(ret); } /** @@ -20054,7 +20053,7 @@ export class StakeRegistration { * @returns {StakeCredential} */ stake_credential() { - const ret = wasm.stakedelegation_stake_credential(this.ptr); + const ret = wasm.baseaddress_payment_cred(this.ptr); return StakeCredential.__wrap(ret); } /** @@ -20199,14 +20198,14 @@ export class StakeVoteDelegCert { * @returns {StakeCredential} */ stake_credential() { - const ret = wasm.stakedelegation_stake_credential(this.ptr); + const ret = wasm.baseaddress_payment_cred(this.ptr); return StakeCredential.__wrap(ret); } /** * @returns {Ed25519KeyHash} */ pool_keyhash() { - const ret = wasm.stakedelegation_pool_keyhash(this.ptr); + const ret = wasm.stakevotedelegcert_pool_keyhash(this.ptr); return Ed25519KeyHash.__wrap(ret); } /** @@ -20366,7 +20365,7 @@ export class StakeVoteRegDelegCert { * @returns {StakeCredential} */ stake_credential() { - const ret = wasm.regcert_stake_credential(this.ptr); + const ret = wasm.stakevoteregdelegcert_stake_credential(this.ptr); return StakeCredential.__wrap(ret); } /** @@ -20610,7 +20609,7 @@ export class TimelockExpiry { * @returns {BigNum} */ slot() { - const ret = wasm.constrplutusdata_alternative(this.ptr); + const ret = wasm.linearfee_constant(this.ptr); return BigNum.__wrap(ret); } /** @@ -20755,7 +20754,7 @@ export class TimelockStart { * @returns {BigNum} */ slot() { - const ret = wasm.constrplutusdata_alternative(this.ptr); + const ret = wasm.linearfee_constant(this.ptr); return BigNum.__wrap(ret); } /** @@ -21252,7 +21251,7 @@ export class TransactionBody { * @returns {BigNum} */ fee() { - const ret = wasm.constrplutusdata_alternative(this.ptr); + const ret = wasm.transactionbody_fee(this.ptr); return BigNum.__wrap(ret); } /** @@ -21340,7 +21339,7 @@ export class TransactionBody { */ set_validity_start_interval(validity_start_interval) { _assertClass(validity_start_interval, BigNum); - wasm.transactionbody_set_validity_start_interval( + wasm.protocolparamupdate_set_minfee_b( this.ptr, validity_start_interval.ptr, ); @@ -21349,7 +21348,7 @@ export class TransactionBody { * @returns {BigNum | undefined} */ validity_start_interval() { - const ret = wasm.transactionbody_validity_start_interval(this.ptr); + const ret = wasm.protocolparamupdate_minfee_b(this.ptr); return ret === 0 ? undefined : BigNum.__wrap(ret); } /** @@ -21441,13 +21440,13 @@ export class TransactionBody { */ set_total_collateral(total_collateral) { _assertClass(total_collateral, BigNum); - wasm.transactionbody_set_total_collateral(this.ptr, total_collateral.ptr); + wasm.protocolparamupdate_set_key_deposit(this.ptr, total_collateral.ptr); } /** * @returns {BigNum | undefined} */ total_collateral() { - const ret = wasm.transactionbody_total_collateral(this.ptr); + const ret = wasm.protocolparamupdate_key_deposit(this.ptr); return ret === 0 ? undefined : BigNum.__wrap(ret); } /** @@ -21549,6 +21548,47 @@ export class TransactionBuilder { const ptr = this.__destroy_into_raw(); wasm.__wbg_transactionbuilder_free(ptr); } + /** + * This automatically selects and adds inputs from {inputs} consisting of just enough to cover + * the outputs that have already been added. + * This should be called after adding all certs/outputs/etc and will be an error otherwise. + * Adding a change output must be called after via TransactionBuilder::balance() + * inputs to cover the minimum fees. This does not, however, set the txbuilder's fee. + * + * change_address is required here in order to determine the min ada requirement precisely + * weights is a coma separated representation of a Uint32Arary + * @param {TransactionUnspentOutputs} inputs + * @param {Address} change_address + * @param {string} weights_str + */ + add_inputs_from_impl(inputs, change_address, weights_str) { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + _assertClass(inputs, TransactionUnspentOutputs); + _assertClass(change_address, Address); + const ptr0 = passStringToWasm0( + weights_str, + wasm.__wbindgen_malloc, + wasm.__wbindgen_realloc, + ); + const len0 = WASM_VECTOR_LEN; + wasm.transactionbuilder_add_inputs_from_impl( + retptr, + this.ptr, + inputs.ptr, + change_address.ptr, + ptr0, + len0, + ); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + if (r1) { + throw takeObject(r0); + } + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } /** * This automatically selects and adds inputs from {inputs} consisting of just enough to cover * the outputs that have already been added. @@ -21726,7 +21766,7 @@ export class TransactionBuilder { */ set_ttl(ttl) { _assertClass(ttl, BigNum); - wasm.transactionbuilder_set_ttl(this.ptr, ttl.ptr); + wasm.protocolparamupdate_set_minfee_b(this.ptr, ttl.ptr); } /** * @param {BigNum} validity_start_interval @@ -22108,7 +22148,7 @@ export class TransactionBuilder { * @returns {BigNum | undefined} */ get_fee_if_set() { - const ret = wasm.transactionbuilder_get_fee_if_set(this.ptr); + const ret = wasm.protocolparamupdate_minfee_a(this.ptr); return ret === 0 ? undefined : BigNum.__wrap(ret); } /** @@ -22906,7 +22946,7 @@ export class TransactionInput { * @returns {BigNum} */ index() { - const ret = wasm.constrplutusdata_alternative(this.ptr); + const ret = wasm.governanceactionid_governance_action_index(this.ptr); return BigNum.__wrap(ret); } /** @@ -25432,7 +25472,7 @@ export class UnregCommitteeHotKeyCert { * @returns {Ed25519KeyHash} */ committee_cold_keyhash() { - const ret = wasm.genesiskeydelegation_genesishash(this.ptr); + const ret = wasm.regcommitteehotkeycert_committee_cold_keyhash(this.ptr); return Ed25519KeyHash.__wrap(ret); } /** @@ -26449,7 +26489,7 @@ export class Value { * @returns {BigNum} */ coin() { - const ret = wasm.constrplutusdata_alternative(this.ptr); + const ret = wasm.value_coin(this.ptr); return BigNum.__wrap(ret); } /** @@ -26808,7 +26848,7 @@ export class Vkeywitness { * @returns {Vkey} */ vkey() { - const ret = wasm.vkey_new(this.ptr); + const ret = wasm.vkeywitness_vkey(this.ptr); return Vkey.__wrap(ret); } /** @@ -27162,14 +27202,14 @@ export class VoteDelegCert { * @returns {StakeCredential} */ stake_credential() { - const ret = wasm.stakedelegation_stake_credential(this.ptr); + const ret = wasm.baseaddress_payment_cred(this.ptr); return StakeCredential.__wrap(ret); } /** * @returns {Drep} */ drep() { - const ret = wasm.votedelegcert_drep(this.ptr); + const ret = wasm.stakevotedelegcert_drep(this.ptr); return Drep.__wrap(ret); } /** @@ -27699,7 +27739,7 @@ export class VotingProcedure { * @returns {GovernanceActionId} */ governance_action_id() { - const ret = wasm.transactionunspentoutput_input(this.ptr); + const ret = wasm.votingprocedure_governance_action_id(this.ptr); return GovernanceActionId.__wrap(ret); } /** @@ -28008,10 +28048,6 @@ export class Withdrawals { const imports = { __wbindgen_placeholder__: { - __wbindgen_string_new: function (arg0, arg1) { - const ret = getStringFromWasm0(arg0, arg1); - return addHeapObject(ret); - }, __wbindgen_object_drop_ref: function (arg0) { takeObject(arg0); }, @@ -28031,17 +28067,21 @@ const imports = { getInt32Memory0()[arg0 / 4 + 1] = len0; getInt32Memory0()[arg0 / 4 + 0] = ptr0; }, - __wbg_transaction_new: function (arg0) { - const ret = Transaction.__wrap(arg0); + __wbindgen_string_new: function (arg0, arg1) { + const ret = getStringFromWasm0(arg0, arg1); return addHeapObject(ret); }, __wbg_fetch_16f5dddfc5a913a4: function (arg0, arg1) { const ret = getObject(arg0).fetch(getObject(arg1)); return addHeapObject(ret); }, + __wbg_transaction_new: function (arg0) { + const ret = Transaction.__wrap(arg0); + return addHeapObject(ret); + }, __wbindgen_string_get: function (arg0, arg1) { const obj = getObject(arg1); - const ret = typeof (obj) === "string" ? obj : undefined; + const ret = typeof obj === "string" ? obj : undefined; var ptr0 = isLikeNone(ret) ? 0 : passStringToWasm0( @@ -28103,15 +28143,9 @@ const imports = { const ret = false; return ret; }, - __wbg_randomFillSync_2f6909f8132a175d: function () { - return handleError(function (arg0, arg1, arg2) { - getObject(arg0).randomFillSync(getArrayU8FromWasm0(arg1, arg2)); - }, arguments); - }, - __wbg_getRandomValues_11a236fbf9914290: function () { - return handleError(function (arg0, arg1) { - getObject(arg0).getRandomValues(getObject(arg1)); - }, arguments); + __wbg_static_accessor_NODE_MODULE_06b864c18e8ae506: function () { + const ret = module; + return addHeapObject(ret); }, __wbg_process_5615a087a47ba544: function (arg0) { const ret = getObject(arg0).process; @@ -28119,7 +28153,7 @@ const imports = { }, __wbindgen_is_object: function (arg0) { const val = getObject(arg0); - const ret = typeof (val) === "object" && val !== null; + const ret = typeof val === "object" && val !== null; return ret; }, __wbg_versions_8404a8b21b9337ae: function (arg0) { @@ -28148,9 +28182,15 @@ const imports = { const ret = getObject(arg0).msCrypto; return addHeapObject(ret); }, - __wbg_static_accessor_NODE_MODULE_06b864c18e8ae506: function () { - const ret = module; - return addHeapObject(ret); + __wbg_randomFillSync_2f6909f8132a175d: function () { + return handleError(function (arg0, arg1, arg2) { + getObject(arg0).randomFillSync(getArrayU8FromWasm0(arg1, arg2)); + }, arguments); + }, + __wbg_getRandomValues_11a236fbf9914290: function () { + return handleError(function (arg0, arg1) { + getObject(arg0).getRandomValues(getObject(arg1)); + }, arguments); }, __wbg_self_e7c1f827057f6584: function () { return handleError(function () { @@ -28221,7 +28261,7 @@ const imports = { const a = state0.a; state0.a = 0; try { - return __wbg_adapter_1680(a, state0.b, arg0, arg1); + return __wbg_adapter_1681(a, state0.b, arg0, arg1); } finally { state0.a = a; } @@ -28279,6 +28319,10 @@ const imports = { const ret = getObject(arg0).self; return addHeapObject(ret); }, + __wbg_require_0993fe224bf8e202: function (arg0, arg1) { + const ret = require(getStringFromWasm0(arg0, arg1)); + return addHeapObject(ret); + }, __wbg_crypto_e95a6e54c5c2e37f: function (arg0) { const ret = getObject(arg0).crypto; return addHeapObject(ret); @@ -28287,10 +28331,6 @@ const imports = { const ret = getObject(arg0).getRandomValues; return addHeapObject(ret); }, - __wbg_require_0993fe224bf8e202: function (arg0, arg1) { - const ret = require(getStringFromWasm0(arg0, arg1)); - return addHeapObject(ret); - }, __wbg_randomFillSync_dd2297de5917c74e: function (arg0, arg1, arg2) { getObject(arg0).randomFillSync(getArrayU8FromWasm0(arg1, arg2)); }, @@ -28315,8 +28355,8 @@ const imports = { const ret = wasm.memory; return addHeapObject(ret); }, - __wbindgen_closure_wrapper7018: function (arg0, arg1, arg2) { - const ret = makeMutClosure(arg0, arg1, 216, __wbg_adapter_30); + __wbindgen_closure_wrapper7021: function (arg0, arg1, arg2) { + const ret = makeMutClosure(arg0, arg1, 186, __wbg_adapter_30); return addHeapObject(ret); }, }, diff --git a/src/core/libs/cardano_multiplatform_lib/cardano_multiplatform_lib_bg.wasm b/src/core/libs/cardano_multiplatform_lib/cardano_multiplatform_lib_bg.wasm index c3c2bd39..2f771624 100644 Binary files a/src/core/libs/cardano_multiplatform_lib/cardano_multiplatform_lib_bg.wasm and b/src/core/libs/cardano_multiplatform_lib/cardano_multiplatform_lib_bg.wasm differ diff --git a/src/core/libs/cardano_multiplatform_lib/nodejs/cardano_multiplatform_lib.generated.js b/src/core/libs/cardano_multiplatform_lib/nodejs/cardano_multiplatform_lib.generated.js index c3ba5c58..77aa01ba 100644 --- a/src/core/libs/cardano_multiplatform_lib/nodejs/cardano_multiplatform_lib.generated.js +++ b/src/core/libs/cardano_multiplatform_lib/nodejs/cardano_multiplatform_lib.generated.js @@ -1,13 +1,35 @@ // @generated file from wasmbuild -- do not edit // deno-lint-ignore-file // deno-fmt-ignore-file -// source-hash: ab17726f2df5571be15d036e67423022ed8f63e4 +// source-hash: fea5fc75a13596f0eb0af3e358328b34adb4ded3 let imports = {}; imports["__wbindgen_placeholder__"] = module.exports; let wasm; const { TextDecoder, TextEncoder } = require(`util`); +const heap = new Array(128).fill(undefined); + +heap.push(undefined, null, true, false); + +function getObject(idx) { + return heap[idx]; +} + +let heap_next = heap.length; + +function dropObject(idx) { + if (idx < 132) return; + heap[idx] = heap_next; + heap_next = idx; +} + +function takeObject(idx) { + const ret = getObject(idx); + dropObject(idx); + return ret; +} + let cachedTextDecoder = new TextDecoder("utf-8", { ignoreBOM: true, fatal: true, @@ -28,12 +50,6 @@ function getStringFromWasm0(ptr, len) { return cachedTextDecoder.decode(getUint8Memory0().subarray(ptr, ptr + len)); } -const heap = new Array(128).fill(undefined); - -heap.push(undefined, null, true, false); - -let heap_next = heap.length; - function addHeapObject(obj) { if (heap_next === heap.length) heap.push(heap.length + 1); const idx = heap_next; @@ -43,22 +59,6 @@ function addHeapObject(obj) { return idx; } -function getObject(idx) { - return heap[idx]; -} - -function dropObject(idx) { - if (idx < 132) return; - heap[idx] = heap_next; - heap_next = idx; -} - -function takeObject(idx) { - const ret = getObject(idx); - dropObject(idx); - return ret; -} - let WASM_VECTOR_LEN = 0; let cachedTextEncoder = new TextEncoder("utf-8"); @@ -220,12 +220,11 @@ function makeMutClosure(arg0, arg1, dtor, f) { return real; } function __wbg_adapter_30(arg0, arg1, arg2) { - wasm - ._dyn_core__ops__function__FnMut__A____Output___R_as_wasm_bindgen__closure__WasmClosure___describe__invoke__h9de9452916ac8cca( - arg0, - arg1, - addHeapObject(arg2), - ); + wasm.wasm_bindgen__convert__closures__invoke1_mut__hee80fd123b909250( + arg0, + arg1, + addHeapObject(arg2), + ); } function _assertClass(instance, klass) { @@ -849,8 +848,8 @@ function handleError(f, args) { wasm.__wbindgen_exn_store(addHeapObject(e)); } } -function __wbg_adapter_1680(arg0, arg1, arg2, arg3) { - wasm.wasm_bindgen__convert__closures__invoke2_mut__h36afefe016e25d40( +function __wbg_adapter_1681(arg0, arg1, arg2, arg3) { + wasm.wasm_bindgen__convert__closures__invoke2_mut__h5b4d9f16616fac4b( arg0, arg1, addHeapObject(arg2), @@ -8010,7 +8009,7 @@ class GovernanceActionId { * @returns {BigNum} */ governance_action_index() { - const ret = wasm.constrplutusdata_alternative(this.ptr); + const ret = wasm.governanceactionid_governance_action_index(this.ptr); return BigNum.__wrap(ret); } /** @@ -8469,7 +8468,7 @@ class HeaderBody { * @returns {BigNum} */ slot() { - const ret = wasm.constrplutusdata_alternative(this.ptr); + const ret = wasm.headerbody_slot(this.ptr); return BigNum.__wrap(ret); } /** @@ -8737,7 +8736,7 @@ class Int { as_i32_or_nothing() { try { const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); - wasm.int_as_i32(retptr, this.ptr); + wasm.int_as_i32_or_nothing(retptr, this.ptr); var r0 = getInt32Memory0()[retptr / 4 + 0]; var r1 = getInt32Memory0()[retptr / 4 + 1]; return r0 === 0 ? undefined : r1; @@ -9619,14 +9618,14 @@ class LinearFee { * @returns {BigNum} */ constant() { - const ret = wasm.constrplutusdata_alternative(this.ptr); + const ret = wasm.linearfee_constant(this.ptr); return BigNum.__wrap(ret); } /** * @returns {BigNum} */ coefficient() { - const ret = wasm.exunits_steps(this.ptr); + const ret = wasm.linearfee_coefficient(this.ptr); return BigNum.__wrap(ret); } /** @@ -11921,7 +11920,7 @@ class NewConstitution { * @returns {DataHash} */ hash() { - const ret = wasm.newconstitution_hash(this.ptr); + const ret = wasm.genesiskeydelegation_vrf_keyhash(this.ptr); return DataHash.__wrap(ret); } /** @@ -12184,7 +12183,7 @@ class OperationalCert { * @returns {number} */ sequence_number() { - const ret = wasm.networkinfo_protocol_magic(this.ptr); + const ret = wasm.operationalcert_sequence_number(this.ptr); return ret >>> 0; } /** @@ -13600,28 +13599,28 @@ class PoolParams { * @returns {VRFKeyHash} */ vrf_keyhash() { - const ret = wasm.poolparams_vrf_keyhash(this.ptr); + const ret = wasm.governanceactionid_transaction_id(this.ptr); return VRFKeyHash.__wrap(ret); } /** * @returns {BigNum} */ pledge() { - const ret = wasm.constrplutusdata_alternative(this.ptr); + const ret = wasm.governanceactionid_governance_action_index(this.ptr); return BigNum.__wrap(ret); } /** * @returns {BigNum} */ cost() { - const ret = wasm.exunits_steps(this.ptr); + const ret = wasm.poolparams_cost(this.ptr); return BigNum.__wrap(ret); } /** * @returns {UnitInterval} */ margin() { - const ret = wasm.drepvotingthresholds_committee_normal(this.ptr); + const ret = wasm.drepvotingthresholds_update_constitution(this.ptr); return UnitInterval.__wrap(ret); } /** @@ -13994,7 +13993,7 @@ class PoolRetirement { * @returns {number} */ epoch() { - const ret = wasm.networkinfo_protocol_magic(this.ptr); + const ret = wasm.poolretirement_epoch(this.ptr); return ret >>> 0; } /** @@ -14546,7 +14545,7 @@ class ProposalProcedure { * @returns {BigNum} */ deposit() { - const ret = wasm.constrplutusdata_alternative(this.ptr); + const ret = wasm.proposalprocedure_deposit(this.ptr); return BigNum.__wrap(ret); } /** @@ -15675,7 +15674,7 @@ class ProtocolVersion { * @returns {number} */ minor() { - const ret = wasm.operationalcert_kes_period(this.ptr); + const ret = wasm.protocolversion_minor(this.ptr); return ret >>> 0; } /** @@ -15943,14 +15942,14 @@ class Redeemer { * @returns {BigNum} */ index() { - const ret = wasm.constrplutusdata_alternative(this.ptr); + const ret = wasm.poolparams_cost(this.ptr); return BigNum.__wrap(ret); } /** * @returns {PlutusData} */ data() { - const ret = wasm.redeemer_data(this.ptr); + const ret = wasm.data_get(this.ptr); return PlutusData.__wrap(ret); } /** @@ -16512,14 +16511,14 @@ class RegCommitteeHotKeyCert { * @returns {Ed25519KeyHash} */ committee_cold_keyhash() { - const ret = wasm.genesiskeydelegation_genesishash(this.ptr); + const ret = wasm.regcommitteehotkeycert_committee_cold_keyhash(this.ptr); return Ed25519KeyHash.__wrap(ret); } /** * @returns {Ed25519KeyHash} */ committee_hot_keyhash() { - const ret = wasm.genesiskeydelegation_genesis_delegate_hash(this.ptr); + const ret = wasm.regcommitteehotkeycert_committee_hot_keyhash(this.ptr); return Ed25519KeyHash.__wrap(ret); } /** @@ -17073,7 +17072,7 @@ class RequiredWitnessSet { */ add_vkey_key(vkey) { _assertClass(vkey, Vkey); - wasm.requiredwitnessset_add_vkey(this.ptr, vkey.ptr); + wasm.requiredwitnessset_add_vkey_key(this.ptr, vkey.ptr); } /** * @param {Ed25519KeyHash} hash @@ -18502,14 +18501,14 @@ class ScriptNOfK { * @returns {number} */ n() { - const ret = wasm.networkinfo_protocol_magic(this.ptr); + const ret = wasm.scriptnofk_n(this.ptr); return ret >>> 0; } /** * @returns {NativeScripts} */ native_scripts() { - const ret = wasm.scriptnofk_native_scripts(this.ptr); + const ret = wasm.scriptall_native_scripts(this.ptr); return NativeScripts.__wrap(ret); } /** @@ -18656,7 +18655,7 @@ class ScriptPubkey { * @returns {Ed25519KeyHash} */ addr_keyhash() { - const ret = wasm.genesiskeydelegation_genesishash(this.ptr); + const ret = wasm.regcommitteehotkeycert_committee_cold_keyhash(this.ptr); return Ed25519KeyHash.__wrap(ret); } /** @@ -19262,7 +19261,7 @@ class SingleHostName { * @returns {DNSRecordAorAAAA} */ dns_name() { - const ret = wasm.anchor_anchor_url(this.ptr); + const ret = wasm.singlehostname_dns_name(this.ptr); return DNSRecordAorAAAA.__wrap(ret); } /** @@ -19740,7 +19739,7 @@ class StakeDelegation { * @returns {StakeCredential} */ stake_credential() { - const ret = wasm.stakedelegation_stake_credential(this.ptr); + const ret = wasm.baseaddress_payment_cred(this.ptr); return StakeCredential.__wrap(ret); } /** @@ -19898,7 +19897,7 @@ class StakeDeregistration { * @returns {StakeCredential} */ stake_credential() { - const ret = wasm.stakedelegation_stake_credential(this.ptr); + const ret = wasm.baseaddress_payment_cred(this.ptr); return StakeCredential.__wrap(ret); } /** @@ -20044,7 +20043,7 @@ class StakeRegDelegCert { * @returns {StakeCredential} */ stake_credential() { - const ret = wasm.regcert_stake_credential(this.ptr); + const ret = wasm.stakeregdelegcert_stake_credential(this.ptr); return StakeCredential.__wrap(ret); } /** @@ -20212,7 +20211,7 @@ class StakeRegistration { * @returns {StakeCredential} */ stake_credential() { - const ret = wasm.stakedelegation_stake_credential(this.ptr); + const ret = wasm.baseaddress_payment_cred(this.ptr); return StakeCredential.__wrap(ret); } /** @@ -20358,14 +20357,14 @@ class StakeVoteDelegCert { * @returns {StakeCredential} */ stake_credential() { - const ret = wasm.stakedelegation_stake_credential(this.ptr); + const ret = wasm.baseaddress_payment_cred(this.ptr); return StakeCredential.__wrap(ret); } /** * @returns {Ed25519KeyHash} */ pool_keyhash() { - const ret = wasm.stakedelegation_pool_keyhash(this.ptr); + const ret = wasm.stakevotedelegcert_pool_keyhash(this.ptr); return Ed25519KeyHash.__wrap(ret); } /** @@ -20526,7 +20525,7 @@ class StakeVoteRegDelegCert { * @returns {StakeCredential} */ stake_credential() { - const ret = wasm.regcert_stake_credential(this.ptr); + const ret = wasm.stakevoteregdelegcert_stake_credential(this.ptr); return StakeCredential.__wrap(ret); } /** @@ -20772,7 +20771,7 @@ class TimelockExpiry { * @returns {BigNum} */ slot() { - const ret = wasm.constrplutusdata_alternative(this.ptr); + const ret = wasm.linearfee_constant(this.ptr); return BigNum.__wrap(ret); } /** @@ -20918,7 +20917,7 @@ class TimelockStart { * @returns {BigNum} */ slot() { - const ret = wasm.constrplutusdata_alternative(this.ptr); + const ret = wasm.linearfee_constant(this.ptr); return BigNum.__wrap(ret); } /** @@ -21418,7 +21417,7 @@ class TransactionBody { * @returns {BigNum} */ fee() { - const ret = wasm.constrplutusdata_alternative(this.ptr); + const ret = wasm.transactionbody_fee(this.ptr); return BigNum.__wrap(ret); } /** @@ -21506,7 +21505,7 @@ class TransactionBody { */ set_validity_start_interval(validity_start_interval) { _assertClass(validity_start_interval, BigNum); - wasm.transactionbody_set_validity_start_interval( + wasm.protocolparamupdate_set_minfee_b( this.ptr, validity_start_interval.ptr, ); @@ -21515,7 +21514,7 @@ class TransactionBody { * @returns {BigNum | undefined} */ validity_start_interval() { - const ret = wasm.transactionbody_validity_start_interval(this.ptr); + const ret = wasm.protocolparamupdate_minfee_b(this.ptr); return ret === 0 ? undefined : BigNum.__wrap(ret); } /** @@ -21607,13 +21606,13 @@ class TransactionBody { */ set_total_collateral(total_collateral) { _assertClass(total_collateral, BigNum); - wasm.transactionbody_set_total_collateral(this.ptr, total_collateral.ptr); + wasm.protocolparamupdate_set_key_deposit(this.ptr, total_collateral.ptr); } /** * @returns {BigNum | undefined} */ total_collateral() { - const ret = wasm.transactionbody_total_collateral(this.ptr); + const ret = wasm.protocolparamupdate_key_deposit(this.ptr); return ret === 0 ? undefined : BigNum.__wrap(ret); } /** @@ -21716,6 +21715,47 @@ class TransactionBuilder { const ptr = this.__destroy_into_raw(); wasm.__wbg_transactionbuilder_free(ptr); } + /** + * This automatically selects and adds inputs from {inputs} consisting of just enough to cover + * the outputs that have already been added. + * This should be called after adding all certs/outputs/etc and will be an error otherwise. + * Adding a change output must be called after via TransactionBuilder::balance() + * inputs to cover the minimum fees. This does not, however, set the txbuilder's fee. + * + * change_address is required here in order to determine the min ada requirement precisely + * weights is a coma separated representation of a Uint32Arary + * @param {TransactionUnspentOutputs} inputs + * @param {Address} change_address + * @param {string} weights_str + */ + add_inputs_from_impl(inputs, change_address, weights_str) { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + _assertClass(inputs, TransactionUnspentOutputs); + _assertClass(change_address, Address); + const ptr0 = passStringToWasm0( + weights_str, + wasm.__wbindgen_malloc, + wasm.__wbindgen_realloc, + ); + const len0 = WASM_VECTOR_LEN; + wasm.transactionbuilder_add_inputs_from_impl( + retptr, + this.ptr, + inputs.ptr, + change_address.ptr, + ptr0, + len0, + ); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + if (r1) { + throw takeObject(r0); + } + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + } + } /** * This automatically selects and adds inputs from {inputs} consisting of just enough to cover * the outputs that have already been added. @@ -21893,7 +21933,7 @@ class TransactionBuilder { */ set_ttl(ttl) { _assertClass(ttl, BigNum); - wasm.transactionbuilder_set_ttl(this.ptr, ttl.ptr); + wasm.protocolparamupdate_set_minfee_b(this.ptr, ttl.ptr); } /** * @param {BigNum} validity_start_interval @@ -22275,7 +22315,7 @@ class TransactionBuilder { * @returns {BigNum | undefined} */ get_fee_if_set() { - const ret = wasm.transactionbuilder_get_fee_if_set(this.ptr); + const ret = wasm.protocolparamupdate_minfee_a(this.ptr); return ret === 0 ? undefined : BigNum.__wrap(ret); } /** @@ -23079,7 +23119,7 @@ class TransactionInput { * @returns {BigNum} */ index() { - const ret = wasm.constrplutusdata_alternative(this.ptr); + const ret = wasm.governanceactionid_governance_action_index(this.ptr); return BigNum.__wrap(ret); } /** @@ -25622,7 +25662,7 @@ class UnregCommitteeHotKeyCert { * @returns {Ed25519KeyHash} */ committee_cold_keyhash() { - const ret = wasm.genesiskeydelegation_genesishash(this.ptr); + const ret = wasm.regcommitteehotkeycert_committee_cold_keyhash(this.ptr); return Ed25519KeyHash.__wrap(ret); } /** @@ -26646,7 +26686,7 @@ class Value { * @returns {BigNum} */ coin() { - const ret = wasm.constrplutusdata_alternative(this.ptr); + const ret = wasm.value_coin(this.ptr); return BigNum.__wrap(ret); } /** @@ -27008,7 +27048,7 @@ class Vkeywitness { * @returns {Vkey} */ vkey() { - const ret = wasm.vkey_new(this.ptr); + const ret = wasm.vkeywitness_vkey(this.ptr); return Vkey.__wrap(ret); } /** @@ -27365,14 +27405,14 @@ class VoteDelegCert { * @returns {StakeCredential} */ stake_credential() { - const ret = wasm.stakedelegation_stake_credential(this.ptr); + const ret = wasm.baseaddress_payment_cred(this.ptr); return StakeCredential.__wrap(ret); } /** * @returns {Drep} */ drep() { - const ret = wasm.votedelegcert_drep(this.ptr); + const ret = wasm.stakevotedelegcert_drep(this.ptr); return Drep.__wrap(ret); } /** @@ -27905,7 +27945,7 @@ class VotingProcedure { * @returns {GovernanceActionId} */ governance_action_id() { - const ret = wasm.transactionunspentoutput_input(this.ptr); + const ret = wasm.votingprocedure_governance_action_id(this.ptr); return GovernanceActionId.__wrap(ret); } /** @@ -28215,11 +28255,6 @@ class Withdrawals { } module.exports.Withdrawals = Withdrawals; -module.exports.__wbindgen_string_new = function (arg0, arg1) { - const ret = getStringFromWasm0(arg0, arg1); - return addHeapObject(ret); -}; - module.exports.__wbindgen_object_drop_ref = function (arg0) { takeObject(arg0); }; @@ -28242,8 +28277,8 @@ module.exports.__wbindgen_json_serialize = function (arg0, arg1) { getInt32Memory0()[arg0 / 4 + 0] = ptr0; }; -module.exports.__wbg_transaction_new = function (arg0) { - const ret = Transaction.__wrap(arg0); +module.exports.__wbindgen_string_new = function (arg0, arg1) { + const ret = getStringFromWasm0(arg0, arg1); return addHeapObject(ret); }; @@ -28252,9 +28287,14 @@ module.exports.__wbg_fetch_16f5dddfc5a913a4 = function (arg0, arg1) { return addHeapObject(ret); }; +module.exports.__wbg_transaction_new = function (arg0) { + const ret = Transaction.__wrap(arg0); + return addHeapObject(ret); +}; + module.exports.__wbindgen_string_get = function (arg0, arg1) { const obj = getObject(arg1); - const ret = typeof (obj) === "string" ? obj : undefined; + const ret = typeof obj === "string" ? obj : undefined; var ptr0 = isLikeNone(ret) ? 0 : passStringToWasm0(ret, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc); @@ -28317,17 +28357,11 @@ module.exports.__wbindgen_cb_drop = function (arg0) { return ret; }; -module.exports.__wbg_randomFillSync_2f6909f8132a175d = function () { - return handleError(function (arg0, arg1, arg2) { - getObject(arg0).randomFillSync(getArrayU8FromWasm0(arg1, arg2)); - }, arguments); -}; - -module.exports.__wbg_getRandomValues_11a236fbf9914290 = function () { - return handleError(function (arg0, arg1) { - getObject(arg0).getRandomValues(getObject(arg1)); - }, arguments); -}; +module.exports.__wbg_static_accessor_NODE_MODULE_06b864c18e8ae506 = + function () { + const ret = module; + return addHeapObject(ret); + }; module.exports.__wbg_process_5615a087a47ba544 = function (arg0) { const ret = getObject(arg0).process; @@ -28336,7 +28370,7 @@ module.exports.__wbg_process_5615a087a47ba544 = function (arg0) { module.exports.__wbindgen_is_object = function (arg0) { const val = getObject(arg0); - const ret = typeof (val) === "object" && val !== null; + const ret = typeof val === "object" && val !== null; return ret; }; @@ -28372,11 +28406,17 @@ module.exports.__wbg_msCrypto_1088c21440b2d7e4 = function (arg0) { return addHeapObject(ret); }; -module.exports.__wbg_static_accessor_NODE_MODULE_06b864c18e8ae506 = - function () { - const ret = module; - return addHeapObject(ret); - }; +module.exports.__wbg_randomFillSync_2f6909f8132a175d = function () { + return handleError(function (arg0, arg1, arg2) { + getObject(arg0).randomFillSync(getArrayU8FromWasm0(arg1, arg2)); + }, arguments); +}; + +module.exports.__wbg_getRandomValues_11a236fbf9914290 = function () { + return handleError(function (arg0, arg1) { + getObject(arg0).getRandomValues(getObject(arg1)); + }, arguments); +}; module.exports.__wbg_self_e7c1f827057f6584 = function () { return handleError(function () { @@ -28454,7 +28494,7 @@ module.exports.__wbg_new_9d3a9ce4282a18a8 = function (arg0, arg1) { const a = state0.a; state0.a = 0; try { - return __wbg_adapter_1680(a, state0.b, arg0, arg1); + return __wbg_adapter_1681(a, state0.b, arg0, arg1); } finally { state0.a = a; } @@ -28525,6 +28565,11 @@ module.exports.__wbg_self_e0b3266d2d9eba1a = function (arg0) { return addHeapObject(ret); }; +module.exports.__wbg_require_0993fe224bf8e202 = function (arg0, arg1) { + const ret = require(getStringFromWasm0(arg0, arg1)); + return addHeapObject(ret); +}; + module.exports.__wbg_crypto_e95a6e54c5c2e37f = function (arg0) { const ret = getObject(arg0).crypto; return addHeapObject(ret); @@ -28535,11 +28580,6 @@ module.exports.__wbg_getRandomValues_dc67302a7bd1aec5 = function (arg0) { return addHeapObject(ret); }; -module.exports.__wbg_require_0993fe224bf8e202 = function (arg0, arg1) { - const ret = require(getStringFromWasm0(arg0, arg1)); - return addHeapObject(ret); -}; - module.exports.__wbg_randomFillSync_dd2297de5917c74e = function ( arg0, arg1, @@ -28577,8 +28617,8 @@ module.exports.__wbindgen_memory = function () { return addHeapObject(ret); }; -module.exports.__wbindgen_closure_wrapper7018 = function (arg0, arg1, arg2) { - const ret = makeMutClosure(arg0, arg1, 216, __wbg_adapter_30); +module.exports.__wbindgen_closure_wrapper7021 = function (arg0, arg1, arg2) { + const ret = makeMutClosure(arg0, arg1, 186, __wbg_adapter_30); return addHeapObject(ret); }; diff --git a/src/core/libs/cardano_multiplatform_lib/src/tx_builder.rs b/src/core/libs/cardano_multiplatform_lib/src/tx_builder.rs index f077ac7d..af0daccd 100644 --- a/src/core/libs/cardano_multiplatform_lib/src/tx_builder.rs +++ b/src/core/libs/cardano_multiplatform_lib/src/tx_builder.rs @@ -517,6 +517,34 @@ pub struct TransactionBuilder { #[wasm_bindgen] impl TransactionBuilder { + /// This automatically selects and adds inputs from {inputs} consisting of just enough to cover + /// the outputs that have already been added. + /// This should be called after adding all certs/outputs/etc and will be an error otherwise. + /// Adding a change output must be called after via TransactionBuilder::balance() + /// inputs to cover the minimum fees. This does not, however, set the txbuilder's fee. + /// + /// change_address is required here in order to determine the min ada requirement precisely + /// weights is a coma separated representation of a Uint32Arary + pub fn add_inputs_from_impl( + &mut self, + inputs: &TransactionUnspentOutputs, + change_address: &Address, + weights_str: String, + ) -> Result<(), JsError> { + //convert weights to Vec, don't use unwrap + //empty array + let mut weights: Vec = Vec::new(); + for weight in weights_str.split(",") { + let parsed_weight = weight.parse::(); + if parsed_weight.is_err() { + return Err(JsError::from_str( + "weights must be a comma separated Uint32Array", + )); + } + weights.push(parsed_weight.unwrap()); + } + return self.add_inputs_from(inputs, change_address, &weights); + } /// This automatically selects and adds inputs from {inputs} consisting of just enough to cover /// the outputs that have already been added. /// This should be called after adding all certs/outputs/etc and will be an error otherwise. diff --git a/src/examples/pool_registration.ts b/src/examples/pool_registration.ts index be734e8a..e79e66d6 100644 --- a/src/examples/pool_registration.ts +++ b/src/examples/pool_registration.ts @@ -1,8 +1,19 @@ -import { Blockfrost, C, fromHex, Lucid, PoolParams } from "../mod.ts"; +import { + Blockfrost, + C, + FreeableBucket, + Freeables, + fromHex, + Lucid, + PoolParams, +} from "../mod.ts"; + +/** When working with objects from the C module or objects that have fields we need to always free their memory when we're done to prevent memory leaks. A FreeableBucket is one way to do that.*/ +const bucket: FreeableBucket = []; const lucid = await Lucid.new( new Blockfrost("https://cardano-preview.blockfrost.io/api/v0", ""), - "Preview", + "Preview" ); lucid.selectWalletFromSeed("car rare ..."); @@ -10,18 +21,28 @@ lucid.selectWalletFromSeed("car rare ..."); /** StakePoolSigningKey_ed25519 cborHex from the cardano-cli */ const coldKey = C.PrivateKey.from_bytes( fromHex( - "58204de30f983ed860524d00059c7f2b1d63240fba805bee043604aa7ccb13d387e9", - ), + "58204de30f983ed860524d00059c7f2b1d63240fba805bee043604aa7ccb13d387e9" + ) ); +bucket.push(coldKey); /** VrfVerificationKey_PraosVRF cborHex from the cardano-cli */ -const vrfKeyHash = C.VRFVKey.from_bytes( +const vrfVKey = C.VRFVKey.from_bytes( fromHex( - "5820c9cf07d863c8a2351662c9759ca1d9858b536bab50ad575b5de161e1af18f887", - ), -).hash().to_hex(); + "5820c9cf07d863c8a2351662c9759ca1d9858b536bab50ad575b5de161e1af18f887" + ) +); +bucket.push(vrfVKey); -const poolId = coldKey.to_public().hash().to_bech32("pool"); +const vrfVKeyHash = vrfVKey.hash(); +bucket.push(vrfVKeyHash); +const vrfKeyHash = vrfVKeyHash.to_hex(); + +const publicKey = coldKey.to_public(); +bucket.push(publicKey); +const publicKeyHash = publicKey.hash(); +bucket.push(publicKeyHash); +const poolId = publicKeyHash.to_bech32("pool"); const rewardOwnerAddress = (await lucid.wallet.rewardAddress())!; @@ -37,13 +58,19 @@ const poolParams: PoolParams = { metadataUrl: "https://...", // metadata needs to be hosted already before registering the pool }; -const tx = await lucid.newTx() - .registerPool(poolParams).complete(); +const tx = lucid.newTx().registerPool(poolParams); +bucket.push(tx); +const completeTX = await lucid.newTx().registerPool(poolParams).complete(); +bucket.push(completeTX); -const signedTx = await tx.sign() +const signedTx = await completeTX + .sign() .signWithPrivateKey(coldKey.to_bech32()) .complete(); +bucket.push(signedTx); const txHash = await signedTx.submit(); +Freeables.free(...bucket); + console.log(txHash); diff --git a/src/lucid/lucid.ts b/src/lucid/lucid.ts index ef7093f2..60f1d52d 100644 --- a/src/lucid/lucid.ts +++ b/src/lucid/lucid.ts @@ -1,7 +1,6 @@ import { C } from "../core/mod.ts"; import { coreToUtxo, - createCostModels, fromHex, fromUnit, paymentCredentialOf, @@ -26,6 +25,7 @@ import { RewardAddress, SignedMessage, Slot, + SlotConfig, Transaction, TxHash, Unit, @@ -41,6 +41,8 @@ import { Message } from "./message.ts"; import { SLOT_CONFIG_NETWORK } from "../plutus/time.ts"; import { Constr, Data } from "../plutus/data.ts"; import { Emulator } from "../provider/emulator.ts"; +import { Freeable, Freeables } from "../utils/freeable.ts"; +import { getTransactionBuilderConfig } from "../utils/transaction_builder_config.ts"; type LucidConstructorArgs = { provider?: Provider; @@ -49,8 +51,8 @@ type LucidConstructorArgs = { }; export class Lucid { - protocolParameters: ProtocolParameters; - txBuilderConfig!: C.TransactionBuilderConfig; + protocolParameters?: ProtocolParameters; + slotConfig!: SlotConfig; wallet!: Wallet; provider!: Provider; network: Network = "Mainnet"; @@ -77,67 +79,34 @@ export class Lucid { }; } } - if (provider && !protocolParameters) { - const protocolParams = await provider.getProtocolParameters(); - lucid.protocolParameters = protocolParams; - } - if (lucid.protocolParameters) { - const slotConfig = SLOT_CONFIG_NETWORK[lucid.network]; - lucid.txBuilderConfig = C.TransactionBuilderConfigBuilder.new() - .coins_per_utxo_byte( - C.BigNum.from_str( - lucid.protocolParameters.coinsPerUtxoByte.toString() - ) - ) - .fee_algo( - C.LinearFee.new( - C.BigNum.from_str(lucid.protocolParameters.minFeeA.toString()), - C.BigNum.from_str(lucid.protocolParameters.minFeeB.toString()) - ) - ) - .key_deposit( - C.BigNum.from_str(lucid.protocolParameters.keyDeposit.toString()) - ) - .pool_deposit( - C.BigNum.from_str(lucid.protocolParameters.poolDeposit.toString()) - ) - .max_tx_size(lucid.protocolParameters.maxTxSize) - .max_value_size(lucid.protocolParameters.maxValSize) - .collateral_percentage(lucid.protocolParameters.collateralPercentage) - .max_collateral_inputs(lucid.protocolParameters.maxCollateralInputs) - .max_tx_ex_units( - C.ExUnits.new( - C.BigNum.from_str(lucid.protocolParameters.maxTxExMem.toString()), - C.BigNum.from_str(lucid.protocolParameters.maxTxExSteps.toString()) - ) - ) - .ex_unit_prices( - C.ExUnitPrices.from_float( - lucid.protocolParameters.priceMem, - lucid.protocolParameters.priceStep - ) - ) - .slot_config( - C.BigNum.from_str(slotConfig.zeroTime.toString()), - C.BigNum.from_str(slotConfig.zeroSlot.toString()), - slotConfig.slotLength - ) - .blockfrost( - // We have Aiken now as native plutus core engine (primary), but we still support blockfrost (secondary) in case of bugs. - C.Blockfrost.new( - // deno-lint-ignore no-explicit-any - ((provider as any)?.url || "") + "/utils/txs/evaluate", - // deno-lint-ignore no-explicit-any - (provider as any)?.projectId || "" - ) - ) - .costmdls(createCostModels(lucid.protocolParameters.costModels)) - .build(); + if (provider && !lucid.protocolParameters) { + const protocolParameters = await provider.getProtocolParameters(); + lucid.protocolParameters = protocolParameters; } + lucid.slotConfig = SLOT_CONFIG_NETWORK[lucid.network]; + lucid.utils = new Utils(lucid); return lucid; } + getTransactionBuilderConfig(): C.TransactionBuilderConfig { + if (!this.protocolParameters) { + throw new Error( + "Protocol parameters or slot config not set. Set a provider or iniatilize with protocol parameters.", + ); + } + return getTransactionBuilderConfig( + this.protocolParameters, + this.slotConfig, + { + // deno-lint-ignore no-explicit-any + url: (this.provider as any)?.url, + // deno-lint-ignore no-explicit-any + projectId: (this.provider as any)?.projectId, + }, + ); + } + /** * Switch provider and/or network. * If provider or network unset, no overwriting happens. Provider or network from current instance are taken then. @@ -146,11 +115,17 @@ export class Lucid { if (this.network === "Custom") { throw new Error("Cannot switch when on custom network."); } - const lucid = await Lucid.new(provider, network); - this.txBuilderConfig = lucid.txBuilderConfig; + const lucid = await Lucid.new({ provider, network }); + this.protocolParameters = lucid.protocolParameters; + this.slotConfig = lucid.slotConfig; this.provider = provider || this.provider; + // Given that protoclParameters and provider are optional we should fetch protocol parameters if they are not set when switiching providers + if (!this.protocolParameters && provider) { + this.protocolParameters = await provider.getProtocolParameters(); + } this.network = network || this.network; this.wallet = lucid.wallet; + return this; } @@ -171,7 +146,7 @@ export class Lucid { verifyMessage( address: Address | RewardAddress, payload: Payload, - signedMessage: SignedMessage + signedMessage: SignedMessage, ): boolean { const { paymentCredential, @@ -194,7 +169,7 @@ export class Lucid { utxosAtWithUnit( addressOrCredential: Address | Credential, - unit: Unit + unit: Unit, ): Promise { return this.provider.getUtxosWithUnit(addressOrCredential, unit); } @@ -248,55 +223,72 @@ export class Lucid { */ selectWalletFromPrivateKey(privateKey: PrivateKey): Lucid { const priv = C.PrivateKey.from_bech32(privateKey); - const pubKeyHash = priv.to_public().hash(); + const publicKey = priv.to_public(); + priv.free(); + const pubKeyHash = publicKey.hash(); + publicKey.free(); this.wallet = { - // deno-lint-ignore require-await - address: async (): Promise
=> - C.EnterpriseAddress.new( + address: (): Promise
=> { + const bucket: Freeable[] = []; + const stakeCredential = C.StakeCredential.from_keyhash(pubKeyHash); + bucket.push(stakeCredential); + const enterpriseAddress = C.EnterpriseAddress.new( this.network === "Mainnet" ? 1 : 0, - C.StakeCredential.from_keyhash(pubKeyHash) - ) - .to_address() - .to_bech32(undefined), - // deno-lint-ignore require-await - rewardAddress: async (): Promise => null, + stakeCredential, + ); + bucket.push(enterpriseAddress); + const address = enterpriseAddress.to_address(); + bucket.push(address); + const bech32 = address.to_bech32(undefined); + Freeables.free(...bucket); + + return Promise.resolve(bech32); + }, + + rewardAddress: (): Promise => Promise.resolve(null), getCollateralCore: (): C.TransactionUnspentOutputs | undefined => { return undefined; }, getUtxos: async (): Promise => { return await this.utxosAt( - paymentCredentialOf(await this.wallet.address()) + paymentCredentialOf(await this.wallet.address()), ); }, getUtxosCore: async (): Promise => { const utxos = await this.utxosAt( - paymentCredentialOf(await this.wallet.address()) + paymentCredentialOf(await this.wallet.address()), ); const coreUtxos = C.TransactionUnspentOutputs.new(); utxos.forEach((utxo) => { - coreUtxos.add(utxoToCore(utxo)); + const coreUtxo = utxoToCore(utxo); + coreUtxos.add(coreUtxo); + coreUtxo.free(); }); return coreUtxos; }, - // deno-lint-ignore require-await - getDelegation: async (): Promise => { - return { poolId: null, rewards: 0n }; + getDelegation: (): Promise => { + return Promise.resolve({ poolId: null, rewards: 0n }); }, - // deno-lint-ignore require-await - signTx: async (tx: C.Transaction): Promise => { - const witness = C.make_vkey_witness( - C.hash_transaction(tx.body()), - priv - ); + signTx: (tx: C.Transaction): Promise => { + const bucket: Freeable[] = []; + const txBody = tx.body(); + bucket.push(txBody); + const hash = C.hash_transaction(txBody); + bucket.push(hash); + const witness = C.make_vkey_witness(hash, priv); + bucket.push(witness); const txWitnessSetBuilder = C.TransactionWitnessSetBuilder.new(); + bucket.push(txWitnessSetBuilder); txWitnessSetBuilder.add_vkey(witness); - return txWitnessSetBuilder.build(); + const witnessSet = txWitnessSetBuilder.build(); + + Freeables.free(...bucket); + return Promise.resolve(witnessSet); }, - // deno-lint-ignore require-await - signMessage: async ( + signMessage: ( address: Address | RewardAddress, - payload: Payload + payload: Payload, ): Promise => { const { paymentCredential, @@ -310,12 +302,13 @@ export class Lucid { throw new Error(`Cannot sign message for address: ${address}.`); } - return signData(hexAddress, payload, privateKey); + return Promise.resolve(signData(hexAddress, payload, privateKey)); }, submitTx: async (tx: Transaction): Promise => { return await this.provider.submitTx(tx); }, }; + return this; } @@ -329,20 +322,27 @@ export class Lucid { }; this.wallet = { - address: async (): Promise
=> - C.Address.from_bytes(fromHex(await getAddressHex())).to_bech32( - undefined - ), + address: async (): Promise
=> { + const addressHex = await getAddressHex(); + const address = C.Address.from_bytes(fromHex(addressHex)); + const bech32 = address.to_bech32(undefined); + address.free(); + return bech32; + }, + rewardAddress: async (): Promise => { const [rewardAddressHex] = await api.getRewardAddresses(); - const rewardAddress = rewardAddressHex - ? C.RewardAddress.from_address( - C.Address.from_bytes(fromHex(rewardAddressHex)) - )! - .to_address() - .to_bech32(undefined) - : null; - return rewardAddress; + if (rewardAddressHex) { + const address = C.Address.from_bytes(fromHex(rewardAddressHex)); + const rewardAddress = C.RewardAddress.from_address(address)!; + address.free(); + const addr = rewardAddress.to_address(); + rewardAddress.free(); + const bech32 = addr.to_bech32(undefined); + addr.free(); + return bech32; + } + return null; }, getCollateralCore: (): C.TransactionUnspentOutputs | undefined => { return undefined; @@ -350,16 +350,20 @@ export class Lucid { getUtxos: async (): Promise => { const utxos = ((await api.getUtxos()) || []).map((utxo) => { const parsedUtxo = C.TransactionUnspentOutput.from_bytes( - fromHex(utxo) + fromHex(utxo), ); - return coreToUtxo(parsedUtxo); + const finalUtxo = coreToUtxo(parsedUtxo); + parsedUtxo.free(); + return finalUtxo; }); return utxos; }, getUtxosCore: async (): Promise => { const utxos = C.TransactionUnspentOutputs.new(); ((await api.getUtxos()) || []).forEach((utxo) => { - utxos.add(C.TransactionUnspentOutput.from_bytes(fromHex(utxo))); + const coreUtxo = C.TransactionUnspentOutput.from_bytes(fromHex(utxo)); + utxos.add(coreUtxo); + coreUtxo.free(); }); return utxos; }, @@ -376,9 +380,11 @@ export class Lucid { }, signMessage: async ( address: Address | RewardAddress, - payload: Payload + payload: Payload, ): Promise => { - const hexAddress = toHex(C.Address.from_bech32(address).to_bytes()); + const cAddress = C.Address.from_bech32(address); + const hexAddress = toHex(cAddress.to_bytes()); + cAddress.free(); return await api.signData(hexAddress, payload); }, submitTx: async (tx: Transaction): Promise => { @@ -401,36 +407,29 @@ export class Lucid { }: ExternalWallet): Lucid { const addressDetails = this.utils.getAddressDetails(address); this.wallet = { - // deno-lint-ignore require-await - address: async (): Promise
=> address, - // deno-lint-ignore require-await - rewardAddress: async (): Promise => { - const rewardAddr = - !rewardAddress && addressDetails.stakeCredential - ? (() => { - if (addressDetails.stakeCredential.type === "Key") { - return C.RewardAddress.new( - this.network === "Mainnet" ? 1 : 0, - C.StakeCredential.from_keyhash( - C.Ed25519KeyHash.from_hex( - addressDetails.stakeCredential.hash - ) - ) - ) - .to_address() - .to_bech32(undefined); - } - return C.RewardAddress.new( - this.network === "Mainnet" ? 1 : 0, - C.StakeCredential.from_scripthash( - C.ScriptHash.from_hex(addressDetails.stakeCredential.hash) - ) - ) - .to_address() - .to_bech32(undefined); - })() - : rewardAddress; - return rewardAddr || null; + address: (): Promise
=> Promise.resolve(address), + rewardAddress: (): Promise => { + if (!rewardAddress && addressDetails.stakeCredential) { + if (addressDetails.stakeCredential.type === "Key") { + const keyHash = C.Ed25519KeyHash.from_hex( + addressDetails.stakeCredential.hash, + ); + const stakeCredential = C.StakeCredential.from_keyhash(keyHash); + keyHash.free(); + const rewardAddress = C.RewardAddress.new( + this.network === "Mainnet" ? 1 : 0, + stakeCredential, + ); + stakeCredential.free(); + const address = rewardAddress.to_address(); + rewardAddress.free(); + const bech32 = address.to_bech32(undefined); + address.free(); + return Promise.resolve(bech32); + } + } + + return Promise.resolve(rewardAddress ?? null); }, getCollateralCore: (): C.TransactionUnspentOutputs | undefined => { if (!collateral || !collateral.length) { @@ -449,7 +448,12 @@ export class Lucid { (utxos ? utxos : await this.utxosAt(paymentCredentialOf(address)) - ).forEach((utxo) => coreUtxos.add(utxoToCore(utxo))); + ).forEach((utxo) => { + const coreUtxo = utxoToCore(utxo); + coreUtxos.add(coreUtxo); + coreUtxo.free(); + }); + return coreUtxos; }, getDelegation: async (): Promise => { @@ -459,17 +463,14 @@ export class Lucid { ? await this.delegationAt(rewardAddr) : { poolId: null, rewards: 0n }; }, - // deno-lint-ignore require-await - signTx: async (): Promise => { - throw new Error("Not implemented"); - }, - // deno-lint-ignore require-await - signMessage: async (): Promise => { - throw new Error("Not implemented"); - }, - submitTx: async (tx: Transaction): Promise => { - return await this.provider.submitTx(tx); - }, + signTx: (): Promise => + Promise.reject("Not implemented"), + + signMessage: (): Promise => + Promise.reject("Not implemented"), + + submitTx: (tx: Transaction): Promise => + this.provider.submitTx(tx), }; return this; } @@ -484,8 +485,9 @@ export class Lucid { addressType?: "Base" | "Enterprise"; accountIndex?: number; password?: string; - } + }, ): Lucid { + const bucket: Freeable[] = []; const { address, rewardAddress, paymentKey, stakeKey } = walletFromSeed( seed, { @@ -493,16 +495,29 @@ export class Lucid { accountIndex: options?.accountIndex || 0, password: options?.password, network: this.network, - } + }, ); - const paymentKeyHash = C.PrivateKey.from_bech32(paymentKey) - .to_public() - .hash() - .to_hex(); - const stakeKeyHash = stakeKey - ? C.PrivateKey.from_bech32(stakeKey).to_public().hash().to_hex() - : ""; + const paymentPrivateKey = C.PrivateKey.from_bech32(paymentKey); + bucket.push(paymentPrivateKey); + const paymentPublicKey = paymentPrivateKey.to_public(); + bucket.push(paymentPublicKey); + const paymentPubKeyHash = paymentPublicKey.hash(); + bucket.push(paymentPubKeyHash); + const paymentKeyHash = paymentPubKeyHash.to_hex(); + + const getStakeKeyHash = (stakeKey: string) => { + const stakePrivateKey = C.PrivateKey.from_bech32(stakeKey); + bucket.push(stakePrivateKey); + const stakePublicKey = stakePrivateKey.to_public(); + bucket.push(stakePublicKey); + const stakePubKeyHash = stakePublicKey.hash(); + bucket.push(stakePubKeyHash); + const stakeKeyHash = stakePubKeyHash.to_hex(); + return stakeKeyHash; + }; + + const stakeKeyHash = stakeKey ? getStakeKeyHash(stakeKey) : ""; const privKeyHashMap = { [paymentKeyHash]: paymentKey, @@ -510,22 +525,21 @@ export class Lucid { }; this.wallet = { - // deno-lint-ignore require-await - address: async (): Promise
=> address, - // deno-lint-ignore require-await - rewardAddress: async (): Promise => - rewardAddress || null, + address: (): Promise
=> Promise.resolve(address), + rewardAddress: (): Promise => + Promise.resolve(rewardAddress || null), + getUtxos: (): Promise => + this.utxosAt(paymentCredentialOf(address)), getCollateralCore: (): C.TransactionUnspentOutputs | undefined => { return undefined; }, - // deno-lint-ignore require-await - getUtxos: async (): Promise => - this.utxosAt(paymentCredentialOf(address)), getUtxosCore: async (): Promise => { const coreUtxos = C.TransactionUnspentOutputs.new(); - (await this.utxosAt(paymentCredentialOf(address))).forEach((utxo) => - coreUtxos.add(utxoToCore(utxo)) - ); + (await this.utxosAt(paymentCredentialOf(address))).forEach((utxo) => { + const coreUtxo = utxoToCore(utxo); + coreUtxos.add(coreUtxo); + coreUtxo.free(); + }); return coreUtxos; }, getDelegation: async (): Promise => { @@ -543,23 +557,29 @@ export class Lucid { const usedKeyHashes = discoverOwnUsedTxKeyHashes( tx, ownKeyHashes, - utxos + utxos, ); const txWitnessSetBuilder = C.TransactionWitnessSetBuilder.new(); usedKeyHashes.forEach((keyHash) => { - const witness = C.make_vkey_witness( - C.hash_transaction(tx.body()), - C.PrivateKey.from_bech32(privKeyHashMap[keyHash]!) - ); + const txBody = tx.body(); + const hash = C.hash_transaction(txBody); + txBody.free(); + const privateKey = C.PrivateKey.from_bech32(privKeyHashMap[keyHash]!); + const witness = C.make_vkey_witness(hash, privateKey); + hash.free(); + privateKey.free(); txWitnessSetBuilder.add_vkey(witness); + witness.free(); }); - return txWitnessSetBuilder.build(); + + const txWitnessSet = txWitnessSetBuilder.build(); + txWitnessSetBuilder.free(); + return txWitnessSet; }, - // deno-lint-ignore require-await - signMessage: async ( + signMessage: ( address: Address | RewardAddress, - payload: Payload + payload: Payload, ): Promise => { const { paymentCredential, @@ -575,12 +595,14 @@ export class Lucid { throw new Error(`Cannot sign message for address: ${address}.`); } - return signData(hexAddress, payload, privateKey); + return Promise.resolve(signData(hexAddress, payload, privateKey)); }, submitTx: async (tx: Transaction): Promise => { return await this.provider.submitTx(tx); }, }; + + Freeables.free(...bucket); return this; } } diff --git a/src/lucid/message.ts b/src/lucid/message.ts index fb71194c..a43ee0ee 100644 --- a/src/lucid/message.ts +++ b/src/lucid/message.ts @@ -8,6 +8,7 @@ import { } from "../types/mod.ts"; import { signData } from "../misc/sign_data.ts"; import { C } from "../mod.ts"; +import { FreeableBucket, Freeables } from "../utils/freeable.ts"; export class Message { lucid: Lucid; @@ -17,7 +18,7 @@ export class Message { constructor( lucid: Lucid, address: Address | RewardAddress, - payload: Payload, + payload: Payload ) { this.lucid = lucid; this.address = address; @@ -31,18 +32,31 @@ export class Message { /** Sign message with a separate private key. */ signWithPrivateKey(privateKey: PrivateKey): SignedMessage { - const { paymentCredential, stakeCredential, address: { hex: hexAddress } } = - this.lucid.utils.getAddressDetails(this.address); - - const keyHash = paymentCredential?.hash || stakeCredential?.hash; - - const keyHashOriginal = C.PrivateKey.from_bech32(privateKey).to_public() - .hash().to_hex(); - - if (!keyHash || keyHash !== keyHashOriginal) { - throw new Error(`Cannot sign message for address: ${this.address}.`); + const bucket: FreeableBucket = []; + try { + const { + paymentCredential, + stakeCredential, + address: { hex: hexAddress }, + } = this.lucid.utils.getAddressDetails(this.address); + + const keyHash = paymentCredential?.hash || stakeCredential?.hash; + + const skey = C.PrivateKey.from_bech32(privateKey); + bucket.push(skey); + const vkey = skey.to_public(); + bucket.push(vkey); + const hash = vkey.hash(); + bucket.push(hash); + const keyHashOriginal = hash.to_hex(); + + if (!keyHash || keyHash !== keyHashOriginal) { + throw new Error(`Cannot sign message for address: ${this.address}.`); + } + + return signData(hexAddress, this.payload, privateKey); + } finally { + Freeables.free(...bucket); } - - return signData(hexAddress, this.payload, privateKey); } } diff --git a/src/lucid/tx.ts b/src/lucid/tx.ts index a980498c..98eec024 100644 --- a/src/lucid/tx.ts +++ b/src/lucid/tx.ts @@ -1,5 +1,5 @@ import { C } from "../core/mod.ts"; -import { Data } from "../mod.ts"; +import { Data, PROTOCOL_PARAMETERS_DEFAULT } from "../mod.ts"; import { Address, Assets, @@ -22,17 +22,24 @@ import { UTxO, WithdrawalValidator, } from "../types/mod.ts"; +import { + addressFromWithNetworkCheck, + attachScript, + createPoolRegistration, + getDatumFromOutputData, + getScriptWitness, + getStakeCredential, +} from "../utils/cml.ts"; +import { type FreeableBucket, Freeables } from "../utils/freeable.ts"; import { assetsToValue, fromHex, - networkToId, toHex, - toScriptRef, utxoToCore, valueToAssets, chunk, + createOutput, } from "../utils/mod.ts"; -import { applyDoubleCborEncoding } from "../utils/utils.ts"; import { Lucid } from "./lucid.ts"; import { defaultConfig } from "./tx_config.ts"; import { TxComplete } from "./tx_complete.ts"; @@ -46,22 +53,31 @@ export class Tx { constructor(lucid: Lucid) { this.lucid = lucid; - this.txBuilder = C.TransactionBuilder.new(this.lucid.txBuilderConfig); + this.txBuilder = C.TransactionBuilder.new( + lucid.getTransactionBuilderConfig(), + ); this.tasks = []; } /** Read data from utxos. These utxos are only referenced and not spent. */ readFrom(utxos: UTxO[]): Tx { this.tasks.push(async (that) => { - for (const utxo of utxos) { - if (utxo.datumHash) { - utxo.datum = Data.to(await that.lucid.datumOf(utxo)); - // Add datum to witness set, so it can be read from validators - const plutusData = C.PlutusData.from_bytes(fromHex(utxo.datum!)); - that.txBuilder.add_plutus_data(plutusData); + const bucket: FreeableBucket = []; + try { + for (const utxo of utxos) { + if (utxo.datumHash) { + utxo.datum = Data.to(await that.lucid.datumOf(utxo)); + // Add datum to witness set, so it can be read from validators + const plutusData = C.PlutusData.from_bytes(fromHex(utxo.datum!)); + bucket.push(plutusData); + that.txBuilder.add_plutus_data(plutusData); + } + const coreUtxo = utxoToCore(utxo); + bucket.push(coreUtxo); + that.txBuilder.add_reference_input(coreUtxo); } - const coreUtxo = utxoToCore(utxo); - that.txBuilder.add_reference_input(coreUtxo); + } finally { + Freeables.free(...bucket); } }); return this; @@ -81,24 +97,26 @@ export class Tx { */ collectFrom(utxos: UTxO[], redeemer?: Redeemer): Tx { this.tasks.push(async (that) => { - for (const utxo of utxos) { - if (utxo.datumHash && !utxo.datum) { - utxo.datum = Data.to(await that.lucid.datumOf(utxo)); - } - const coreUtxo = utxoToCore(utxo); - that.txBuilder.add_input( - coreUtxo, - (redeemer as undefined) && - C.ScriptWitness.new_plutus_witness( - C.PlutusWitness.new( - C.PlutusData.from_bytes(fromHex(redeemer!)), - utxo.datumHash && utxo.datum - ? C.PlutusData.from_bytes(fromHex(utxo.datum!)) - : undefined, - undefined + const bucket: FreeableBucket = []; + try { + for (const utxo of utxos) { + if (utxo.datumHash && !utxo.datum) { + utxo.datum = Data.to(await that.lucid.datumOf(utxo)); + } + const coreUtxo = utxoToCore(utxo); + bucket.push(coreUtxo); + // We don't free Options as the ownership is passed to the txBuilder + const scriptWitness = redeemer + ? getScriptWitness( + redeemer, + utxo.datumHash && utxo.datum ? utxo.datum : undefined, ) - ) - ); + : undefined; + + that.txBuilder.add_input(coreUtxo, scriptWitness); + } + } finally { + Freeables.free(...bucket); } }); return this; @@ -111,34 +129,32 @@ export class Tx { */ mintAssets(assets: Assets, redeemer?: Redeemer): Tx { this.tasks.push((that) => { - const units = Object.keys(assets); - const policyId = units[0].slice(0, 56); - const mintAssets = C.MintAssets.new(); - units.forEach((unit) => { - if (unit.slice(0, 56) !== policyId) { - throw new Error( - "Only one policy id allowed. You can chain multiple mintAssets functions together if you need to mint assets with different policy ids." - ); - } - mintAssets.insert( - C.AssetName.new(fromHex(unit.slice(56))), - C.Int.from_str(assets[unit].toString()) - ); - }); - const scriptHash = C.ScriptHash.from_bytes(fromHex(policyId)); - that.txBuilder.add_mint( - scriptHash, - mintAssets, - redeemer - ? C.ScriptWitness.new_plutus_witness( - C.PlutusWitness.new( - C.PlutusData.from_bytes(fromHex(redeemer!)), - undefined, - undefined - ) - ) - : undefined - ); + const bucket: FreeableBucket = []; + try { + const units = Object.keys(assets); + const policyId = units[0].slice(0, 56); + const mintAssets = C.MintAssets.new(); + bucket.push(mintAssets); + units.forEach((unit) => { + if (unit.slice(0, 56) !== policyId) { + throw new Error( + "Only one policy id allowed. You can chain multiple mintAssets functions together if you need to mint assets with different policy ids.", + ); + } + const assetName = C.AssetName.new(fromHex(unit.slice(56))); + const int = C.Int.from_str(assets[unit].toString()); + // Int is being passed by value so we don't need to free it + bucket.push(assetName); + mintAssets.insert(assetName, int); + }); + const scriptHash = C.ScriptHash.from_bytes(fromHex(policyId)); + // We don't free Options as the ownership is passed to the txBuilder + const scriptWitness = redeemer ? getScriptWitness(redeemer) : undefined; + bucket.push(scriptHash); + that.txBuilder.add_mint(scriptHash, mintAssets, scriptWitness); + } finally { + Freeables.free(...bucket); + } }); return this; } @@ -146,17 +162,16 @@ export class Tx { /** Pay to a public key or native script address. */ payToAddress(address: Address, assets: Assets): Tx { this.tasks.push((that) => { - let output = C.TransactionOutput.new( - addressFromWithNetworkCheck(address, that.lucid), - assetsToValue(assets) - ); + const addr = addressFromWithNetworkCheck(address, that.lucid); + const value = assetsToValue(assets); + + const output = C.TransactionOutput.new(addr, value); const minAda = that.lucid.utils.getMinAdaForOutput(output); assets.lovelace = assets.lovelace > minAda ? assets.lovelace : minAda; - output = C.TransactionOutput.new( - addressFromWithNetworkCheck(address, that.lucid), - assetsToValue(assets) - ); - that.txBuilder.add_output(output); + const valueWithMinAda = assetsToValue(assets); + const outputWithMinAda = C.TransactionOutput.new(addr, valueWithMinAda); + that.txBuilder.add_output(outputWithMinAda); + Freeables.free(output, addr, value, valueWithMinAda, outputWithMinAda); }); return this; } @@ -165,57 +180,51 @@ export class Tx { payToAddressWithData( address: Address, outputData: Datum | OutputData, - assets: Assets + assets: Assets, ): Tx { this.tasks.push((that) => { - if (typeof outputData === "string") { - outputData = { asHash: outputData }; - } - - if ( - [outputData.hash, outputData.asHash, outputData.inline].filter((b) => b) - .length > 1 - ) { - throw new Error( - "Not allowed to set hash, asHash and inline at the same time." - ); - } - const createOutput = (_assets: Assets, _outputData: OutputData) => { - const output = C.TransactionOutput.new( - addressFromWithNetworkCheck(address, that.lucid), - assetsToValue(_assets) - ); + const bucket: FreeableBucket = []; + try { + if (typeof outputData === "string") { + outputData = { asHash: outputData }; + } - if (_outputData.hash) { - output.set_datum( - C.Datum.new_data_hash(C.DataHash.from_hex(_outputData.hash)) - ); - } else if (_outputData.asHash) { - const plutusData = C.PlutusData.from_bytes( - fromHex(_outputData.asHash) - ); - output.set_datum( - C.Datum.new_data_hash(C.hash_plutus_data(plutusData)) - ); - that.txBuilder.add_plutus_data(plutusData); - } else if (_outputData.inline) { - const plutusData = C.PlutusData.from_bytes( - fromHex(_outputData.inline) + if ( + [outputData.hash, outputData.asHash, outputData.inline].filter( + (b) => b, + ).length > 1 + ) { + throw new Error( + "Not allowed to set hash, asHash and inline at the same time.", ); - output.set_datum(C.Datum.new_data(C.Data.new(plutusData))); } - const script = _outputData.scriptRef; - if (script) { - output.set_script_ref(toScriptRef(script)); - } - return output; - }; - let output = createOutput(assets, outputData); - const minAda = this.lucid.utils.getMinAdaForOutput(output); - assets.lovelace = assets.lovelace > minAda ? assets.lovelace : minAda; - output = createOutput(assets, outputData); - that.txBuilder.add_output(output); + const output = createOutput({ + bucket, + txBuilder: that.txBuilder, + lucid: that.lucid, + address, + outputData, + assets, + }); + const minAda = this.lucid.utils.getMinAdaForOutput(output); + const assetsWithMinAda = { ...assets }; + assetsWithMinAda.lovelace = + assets.lovelace > minAda ? assets.lovelace : minAda; + const outputWithMinAda = createOutput({ + bucket, + txBuilder: that.txBuilder, + lucid: that.lucid, + address, + outputData, + assets: assetsWithMinAda, + }); + bucket.push(output, outputWithMinAda); + + that.txBuilder.add_output(outputWithMinAda); + } finally { + Freeables.free(...bucket); + } }); return this; } @@ -224,7 +233,7 @@ export class Tx { payToContract( address: Address, outputData: Datum | OutputData, - assets: Assets + assets: Assets, ): Tx { if (typeof outputData === "string") { outputData = { asHash: outputData }; @@ -232,7 +241,7 @@ export class Tx { if (!(outputData.hash || outputData.asHash || outputData.inline)) { throw new Error( - "No datum set. Script output becomes unspendable without datum." + "No datum set. Script output becomes unspendable without datum.", ); } return this.payToAddressWithData(address, outputData, assets); @@ -242,7 +251,7 @@ export class Tx { delegateTo( rewardAddress: RewardAddress, poolId: PoolId, - redeemer?: Redeemer + redeemer?: Redeemer, ): Tx { this.tasks.push((that) => { const addressDetails = that.lucid.utils.getAddressDetails(rewardAddress); @@ -250,36 +259,18 @@ export class Tx { if (addressDetails.type !== "Reward" || !addressDetails.stakeCredential) { throw new Error("Not a reward address provided."); } - const credential = - addressDetails.stakeCredential.type === "Key" - ? C.StakeCredential.from_keyhash( - C.Ed25519KeyHash.from_bytes( - fromHex(addressDetails.stakeCredential.hash) - ) - ) - : C.StakeCredential.from_scripthash( - C.ScriptHash.from_bytes( - fromHex(addressDetails.stakeCredential.hash) - ) - ); - - that.txBuilder.add_certificate( - C.Certificate.new_stake_delegation( - C.StakeDelegation.new( - credential, - C.Ed25519KeyHash.from_bech32(poolId) - ) - ), - redeemer - ? C.ScriptWitness.new_plutus_witness( - C.PlutusWitness.new( - C.PlutusData.from_bytes(fromHex(redeemer!)), - undefined, - undefined - ) - ) - : undefined + const credential = getStakeCredential( + addressDetails.stakeCredential.hash, + addressDetails.stakeCredential.type, ); + + const keyHash = C.Ed25519KeyHash.from_bech32(poolId); + const delegation = C.StakeDelegation.new(credential, keyHash); + // We don't free Options as the ownership is passed to the txBuilder + const scriptWitness = redeemer ? getScriptWitness(redeemer) : undefined; + const certificate = C.Certificate.new_stake_delegation(delegation); + that.txBuilder.add_certificate(certificate, scriptWitness); + Freeables.free(keyHash, delegation, credential, certificate); }); return this; } @@ -292,25 +283,16 @@ export class Tx { if (addressDetails.type !== "Reward" || !addressDetails.stakeCredential) { throw new Error("Not a reward address provided."); } - const credential = - addressDetails.stakeCredential.type === "Key" - ? C.StakeCredential.from_keyhash( - C.Ed25519KeyHash.from_bytes( - fromHex(addressDetails.stakeCredential.hash) - ) - ) - : C.StakeCredential.from_scripthash( - C.ScriptHash.from_bytes( - fromHex(addressDetails.stakeCredential.hash) - ) - ); - - that.txBuilder.add_certificate( - C.Certificate.new_stake_registration( - C.StakeRegistration.new(credential) - ), - undefined + const credential = getStakeCredential( + addressDetails.stakeCredential.hash, + addressDetails.stakeCredential.type, ); + const stakeRegistration = C.StakeRegistration.new(credential); + const certificate = + C.Certificate.new_stake_registration(stakeRegistration); + + that.txBuilder.add_certificate(certificate, undefined); + Freeables.free(credential, stakeRegistration, certificate); }); return this; } @@ -323,33 +305,18 @@ export class Tx { if (addressDetails.type !== "Reward" || !addressDetails.stakeCredential) { throw new Error("Not a reward address provided."); } - const credential = - addressDetails.stakeCredential.type === "Key" - ? C.StakeCredential.from_keyhash( - C.Ed25519KeyHash.from_bytes( - fromHex(addressDetails.stakeCredential.hash) - ) - ) - : C.StakeCredential.from_scripthash( - C.ScriptHash.from_bytes( - fromHex(addressDetails.stakeCredential.hash) - ) - ); - - that.txBuilder.add_certificate( - C.Certificate.new_stake_deregistration( - C.StakeDeregistration.new(credential) - ), - redeemer - ? C.ScriptWitness.new_plutus_witness( - C.PlutusWitness.new( - C.PlutusData.from_bytes(fromHex(redeemer!)), - undefined, - undefined - ) - ) - : undefined + const credential = getStakeCredential( + addressDetails.stakeCredential.hash, + addressDetails.stakeCredential.type, ); + const stakeDeregistration = C.StakeDeregistration.new(credential); + const certificate = + C.Certificate.new_stake_deregistration(stakeDeregistration); + // We don't free Options as the ownership is passed to the txBuilder + const scriptWitness = redeemer ? getScriptWitness(redeemer) : undefined; + + that.txBuilder.add_certificate(certificate, scriptWitness); + Freeables.free(credential, stakeDeregistration, certificate); }); return this; } @@ -359,12 +326,13 @@ export class Tx { this.tasks.push(async (that) => { const poolRegistration = await createPoolRegistration( poolParams, - that.lucid + that.lucid, ); const certificate = C.Certificate.new_pool_registration(poolRegistration); that.txBuilder.add_certificate(certificate, undefined); + Freeables.free(certificate, poolRegistration); }); return this; } @@ -374,13 +342,14 @@ export class Tx { this.tasks.push(async (that) => { const poolRegistration = await createPoolRegistration( poolParams, - that.lucid + that.lucid, ); // This flag makes sure a pool deposit is not required poolRegistration.set_is_update(true); const certificate = C.Certificate.new_pool_registration(poolRegistration); + Freeables.free(poolRegistration, certificate); that.txBuilder.add_certificate(certificate, undefined); }); @@ -392,10 +361,11 @@ export class Tx { */ retirePool(poolId: PoolId, epoch: number): Tx { this.tasks.push((that) => { - const certificate = C.Certificate.new_pool_retirement( - C.PoolRetirement.new(C.Ed25519KeyHash.from_bech32(poolId), epoch) - ); + const keyHash = C.Ed25519KeyHash.from_bech32(poolId); + const poolRetirement = C.PoolRetirement.new(keyHash, epoch); + const certificate = C.Certificate.new_pool_retirement(poolRetirement); that.txBuilder.add_certificate(certificate, undefined); + Freeables.free(keyHash, poolRetirement, certificate); }); return this; } @@ -403,24 +373,15 @@ export class Tx { withdraw( rewardAddress: RewardAddress, amount: Lovelace, - redeemer?: Redeemer + redeemer?: Redeemer, ): Tx { this.tasks.push((that) => { - that.txBuilder.add_withdrawal( - C.RewardAddress.from_address( - addressFromWithNetworkCheck(rewardAddress, that.lucid) - )!, - C.BigNum.from_str(amount.toString()), - redeemer - ? C.ScriptWitness.new_plutus_witness( - C.PlutusWitness.new( - C.PlutusData.from_bytes(fromHex(redeemer!)), - undefined, - undefined - ) - ) - : undefined - ); + const addr = addressFromWithNetworkCheck(rewardAddress, that.lucid); + const rewardAddr = C.RewardAddress.from_address(addr)!; + const amountBigNum = C.BigNum.from_str(amount.toString()); + const scriptWitness = redeemer ? getScriptWitness(redeemer) : undefined; + that.txBuilder.add_withdrawal(rewardAddr, amountBigNum, scriptWitness); + Freeables.free(addr, rewardAddr, amountBigNum, scriptWitness); }); return this; } @@ -451,9 +412,9 @@ export class Tx { /** Add a payment or stake key hash as a required signer of the transaction. */ addSignerKey(keyHash: PaymentKeyHash | StakeKeyHash): Tx { this.tasks.push((that) => { - that.txBuilder.add_required_signer( - C.Ed25519KeyHash.from_bytes(fromHex(keyHash)) - ); + const key = C.Ed25519KeyHash.from_bytes(fromHex(keyHash)); + that.txBuilder.add_required_signer(key); + Freeables.free(key); }); return this; } @@ -461,9 +422,9 @@ export class Tx { validFrom(unixTime: UnixTime): Tx { this.tasks.push((that) => { const slot = that.lucid.utils.unixTimeToSlot(unixTime); - that.txBuilder.set_validity_start_interval( - C.BigNum.from_str(slot.toString()) - ); + const slotNum = C.BigNum.from_str(slot.toString()); + that.txBuilder.set_validity_start_interval(slotNum); + Freeables.free(slotNum); }); return this; } @@ -471,17 +432,18 @@ export class Tx { validTo(unixTime: UnixTime): Tx { this.tasks.push((that) => { const slot = that.lucid.utils.unixTimeToSlot(unixTime); - that.txBuilder.set_ttl(C.BigNum.from_str(slot.toString())); + const slotNum = C.BigNum.from_str(slot.toString()); + that.txBuilder.set_ttl(slotNum); + Freeables.free(slotNum); }); return this; } attachMetadata(label: Label, metadata: Json): Tx { this.tasks.push((that) => { - that.txBuilder.add_json_metadatum( - C.BigNum.from_str(label.toString()), - JSON.stringify(metadata) - ); + const labelNum = C.BigNum.from_str(label.toString()); + that.txBuilder.add_json_metadatum(labelNum, JSON.stringify(metadata)); + Freeables.free(labelNum); }); return this; } @@ -489,11 +451,13 @@ export class Tx { /** Converts strings to bytes if prefixed with **'0x'**. */ attachMetadataWithConversion(label: Label, metadata: Json): Tx { this.tasks.push((that) => { + const labelNum = C.BigNum.from_str(label.toString()); that.txBuilder.add_json_metadatum_with_schema( - C.BigNum.from_str(label.toString()), + labelNum, JSON.stringify(metadata), - C.MetadataJsonSchema.BasicConversions + C.MetadataJsonSchema.BasicConversions, ); + Freeables.free(labelNum); }); return this; } @@ -501,9 +465,11 @@ export class Tx { /** Explicitely set the network id in the transaction body. */ addNetworkId(id: number): Tx { this.tasks.push((that) => { - that.txBuilder.set_network_id( - C.NetworkId.from_bytes(fromHex(id.toString(16).padStart(2, "0"))) + const networkId = C.NetworkId.from_bytes( + fromHex(id.toString(16).padStart(2, "0")), ); + that.txBuilder.set_network_id(networkId); + Freeables.free(networkId); }); return this; } @@ -554,93 +520,86 @@ export class Tx { return this; } + free() { + this.txBuilder.free(); + } + + /** Completes the transaction. This might fail, you should free the txBuilder when you are done with it. */ async complete(options?: { change?: { address?: Address; outputData?: OutputData }; coinSelection?: boolean; nativeUplc?: boolean; }): Promise { + const bucket: FreeableBucket = []; const { enableChangeSplitting } = this.configuration; - if ( - [ - options?.change?.outputData?.hash, - options?.change?.outputData?.asHash, - options?.change?.outputData?.inline, - ].filter((b) => b).length > 1 - ) { - throw new Error( - "Not allowed to set hash, asHash and inline at the same time." - ); - } + try { + if ( + [ + options?.change?.outputData?.hash, + options?.change?.outputData?.asHash, + options?.change?.outputData?.inline, + ].filter((b) => b).length > 1 + ) { + throw new Error( + "Not allowed to set hash, asHash and inline at the same time.", + ); + } - let task = this.tasks.shift(); - while (task) { - await task(this); - task = this.tasks.shift(); - } + let task = this.tasks.shift(); + while (task) { + await task(this); + task = this.tasks.shift(); + } - const utxos = await this.lucid.wallet.getUtxosCore(); - const collateral = await this.lucid.wallet.getCollateralCore(); + // We don't free `utxos` as it is passed as an Option to the txBuilder and the ownership is passed when passing an Option + const utxos = await this.lucid.wallet.getUtxosCore(); - const changeAddress: C.Address = addressFromWithNetworkCheck( - options?.change?.address || (await this.lucid.wallet.address()), - this.lucid - ); + const collateral = this.lucid.wallet.getCollateralCore(); - if (options?.coinSelection || options?.coinSelection === undefined) { - this.txBuilder.add_inputs_from( - utxos, - changeAddress, - Uint32Array.from([ - 200, // weight ideal > 100 inputs - 1000, // weight ideal < 100 inputs - 1500, // weight assets if plutus - 800, // weight assets if not plutus - 800, // weight distance if not plutus - 5000, // weight utxos - ]) + // We don't free `changeAddress` as it is passed as an Option to the txBuilder and the ownership is passed when passing an Option + const changeAddress: C.Address = addressFromWithNetworkCheck( + options?.change?.address || (await this.lucid.wallet.address()), + this.lucid, ); - } - if (enableChangeSplitting) { - await this.splitChange(); - } + if (options?.coinSelection || options?.coinSelection === undefined) { + this.txBuilder.add_inputs_from_impl( + utxos, + changeAddress, + // Uint32Array.from([ + // 200, // weight ideal > 100 inputs + // 1000, // weight ideal < 100 inputs + // 1500, // weight assets if plutus + // 800, // weight assets if not plutus + // 800, // weight distance if not plutus + // 5000, // weight utxos + // ]), + "200,1000,1500,800,800,5000", + ); + } - this.txBuilder.balance( - changeAddress, - (() => { - if (options?.change?.outputData?.hash) { - return C.Datum.new_data_hash( - C.DataHash.from_hex(options.change.outputData.hash) - ); - } else if (options?.change?.outputData?.asHash) { - this.txBuilder.add_plutus_data( - C.PlutusData.from_bytes(fromHex(options.change.outputData.asHash)) - ); - return C.Datum.new_data_hash( - C.hash_plutus_data( - C.PlutusData.from_bytes(fromHex(options.change.outputData.asHash)) - ) - ); - } else if (options?.change?.outputData?.inline) { - return C.Datum.new_data( - C.Data.new( - C.PlutusData.from_bytes(fromHex(options.change.outputData.inline)) - ) - ); - } else { - return undefined; - } - })() - ); + const { datum, plutusData } = getDatumFromOutputData( + options?.change?.outputData, + ); + if (plutusData) { + this.txBuilder.add_plutus_data(plutusData); + } + bucket.push(datum, plutusData); + if (enableChangeSplitting) { + await this.splitChange(); + } + this.txBuilder.balance(changeAddress, datum); - return new TxComplete( - this.lucid, - await this.txBuilder.construct( + const tx = await this.txBuilder.construct( collateral || utxos, changeAddress, - options?.nativeUplc === undefined ? true : options?.nativeUplc - ) - ); + options?.nativeUplc === undefined ? true : options?.nativeUplc, + ); + + return new TxComplete(this.lucid, tx); + } finally { + Freeables.free(...bucket); + } } /** Return the current transaction body in Hex encoded Cbor. */ @@ -670,16 +629,20 @@ export class Tx { * This is the advanced UTxO management algorithm used by Eternl */ private async splitChange() { - const { coinsPerUtxoByte } = await this.lucid.protocolParameters; + const bucket: FreeableBucket = []; + const { coinsPerUtxoByte } = + this.lucid.protocolParameters || PROTOCOL_PARAMETERS_DEFAULT; const { changeNativeAssetChunkSize, changeMinUtxo } = this.configuration; - const change = this.txBuilder - .get_explicit_input() - .checked_sub(this.txBuilder.get_explicit_output()); + const txInputs = this.txBuilder.get_explicit_input(); + const txOutputs = this.txBuilder.get_explicit_output(); + bucket.push(txInputs, txOutputs); + const change = txInputs.checked_sub(txOutputs); let changeAda = change.coin(); let changeAssets = valueToAssets(change); + bucket.push(changeAda); const changeAssetsArray = Object.keys(changeAssets) .filter((v) => v !== "lovelace") // Sort canonically so we group policy IDs together @@ -687,42 +650,59 @@ export class Tx { changeAssets = changeAssetsArray.reduce( (res, key) => Object.assign(res, { [key]: changeAssets[key] }), - {} + {}, ); const numOutputsWithNativeAssets = Math.ceil( - changeAssetsArray.length / changeNativeAssetChunkSize + changeAssetsArray.length / changeNativeAssetChunkSize, ); let longestAddress = C.Address.from_bech32( - await this.lucid.wallet.address() + await this.lucid.wallet.address(), ); + bucket.push(longestAddress); const outputs = this.txBuilder.outputs(); + bucket.push(outputs); for (let i = 0; i < outputs.len(); i++) { const output = outputs.get(i); + bucket.push(output); + const outputAddress = output.address(); if ( !longestAddress || - output.address().to_bech32(undefined).length > + outputAddress.to_bech32(undefined).length > longestAddress.to_bech32(undefined).length ) { longestAddress = output.address(); } } - const minAdaPerOutput = C.min_ada_required( - C.TransactionOutput.new(longestAddress, assetsToValue(changeAssets)), - C.BigNum.from_str(coinsPerUtxoByte.toString()) + const txOutputValue = assetsToValue(changeAssets); + const transactionOutput = C.TransactionOutput.new( + longestAddress, + txOutputValue, + ); + const coinUtxoByte = C.BigNum.from_str(coinsPerUtxoByte.toString()); + const minAdaPerOutput = C.min_ada_required(transactionOutput, coinUtxoByte); + bucket.push( + txOutputValue, + transactionOutput, + coinUtxoByte, + minAdaPerOutput, ); // Do we have enough ADA in the change to split and still // statisfy minADA requirements? - const shouldSplitChange = - minAdaPerOutput - .checked_mul(C.BigNum.from_str(numOutputsWithNativeAssets.toString())) - .compare(changeAda) < 0; + const numOutputsWithAssets = C.BigNum.from_str( + numOutputsWithNativeAssets.toString(), + ); + const changeAmount = minAdaPerOutput.checked_mul(numOutputsWithAssets); + bucket.push(numOutputsWithAssets, changeAmount); + const shouldSplitChange = changeAmount.compare(changeAda) < 0; - if (change.multiasset() && shouldSplitChange) { + const changeMultiAsset = change.multiasset(); + bucket.push(changeMultiAsset); + if (changeMultiAsset && shouldSplitChange) { const assetChunks = chunk(changeAssetsArray, 20); const totalChunks = assetChunks.length; @@ -734,169 +714,52 @@ export class Tx { const val = assetsToValue( piece.reduce( (res, key) => Object.assign(res, { [key]: changeAssets[key] }), - {} - ) - ); - const minAda = C.min_ada_required( - C.TransactionOutput.new( - C.Address.from_bech32(await this.lucid.wallet.address()), - val + {}, ), - C.BigNum.from_str(coinsPerUtxoByte.toString()) ); + bucket.push(val); + const changeAddress = C.Address.from_bech32( + await this.lucid.wallet.address(), + ); + const minAdaTxOutput = C.TransactionOutput.new(changeAddress, val); - const coin = minAda; - - val.set_coin(coin); - changeAda = changeAda.checked_sub(coin); + const coinUtxoByte = C.BigNum.from_str(coinsPerUtxoByte.toString()); + const minAda = C.min_ada_required(minAdaTxOutput, coinUtxoByte); - this.txBuilder.add_output( - C.TransactionOutput.new( - C.Address.from_bech32(await this.lucid.wallet.address()), - val - ) - ); + val.set_coin(minAda); + changeAda = changeAda.checked_sub(minAda); + const txOutputWithMinAda = C.TransactionOutput.new(changeAddress, val); + bucket.push(changeAda, minAdaTxOutput); + this.txBuilder.add_output(txOutputWithMinAda); } } + const two = C.BigNum.from_str("2"); + const changeMinUtxoBigNum = C.BigNum.from_str(changeMinUtxo); + let split = changeAda.checked_div(two); + bucket.push(two, changeMinUtxoBigNum, split); while ( // If the half is more than the minimum, we can split it - changeAda - .checked_div(C.BigNum.from_str("2")) - .compare(C.BigNum.from_str(changeMinUtxo)) >= 0 + split.compare(changeMinUtxoBigNum) >= 0 ) { - const half = changeAda.checked_div(C.BigNum.from_str("2")); + const half = changeAda.checked_div(two); changeAda = changeAda.checked_sub(half); - this.txBuilder.add_output( - C.TransactionOutput.new( - C.Address.from_bech32(await this.lucid.wallet.address()), - C.Value.new(half) - ) - ); - } - } -} - -function attachScript( - tx: Tx, - { - type, - script, - }: - | SpendingValidator - | MintingPolicy - | CertificateValidator - | WithdrawalValidator -) { - if (type === "Native") { - return tx.txBuilder.add_native_script( - C.NativeScript.from_bytes(fromHex(script)) - ); - } else if (type === "PlutusV1") { - return tx.txBuilder.add_plutus_script( - C.PlutusScript.from_bytes(fromHex(applyDoubleCborEncoding(script))) - ); - } else if (type === "PlutusV2") { - return tx.txBuilder.add_plutus_v2_script( - C.PlutusScript.from_bytes(fromHex(applyDoubleCborEncoding(script))) - ); - } - throw new Error("No variant matched."); -} + split = changeAda.checked_div(two); -async function createPoolRegistration( - poolParams: PoolParams, - lucid: Lucid -): Promise { - const poolOwners = C.Ed25519KeyHashes.new(); - poolParams.owners.forEach((owner) => { - const { stakeCredential } = lucid.utils.getAddressDetails(owner); - if (stakeCredential?.type === "Key") { - poolOwners.add(C.Ed25519KeyHash.from_hex(stakeCredential.hash)); - } else throw new Error("Only key hashes allowed for pool owners."); - }); - - const metadata = poolParams.metadataUrl - ? await fetch(poolParams.metadataUrl).then((res) => res.arrayBuffer()) - : null; - - const metadataHash = metadata - ? C.PoolMetadataHash.from_bytes(C.hash_blake2b256(new Uint8Array(metadata))) - : null; - - const relays = C.Relays.new(); - poolParams.relays.forEach((relay) => { - switch (relay.type) { - case "SingleHostIp": { - const ipV4 = relay.ipV4 - ? C.Ipv4.new( - new Uint8Array(relay.ipV4.split(".").map((b) => parseInt(b))) - ) - : undefined; - const ipV6 = relay.ipV6 - ? C.Ipv6.new(fromHex(relay.ipV6.replaceAll(":", ""))) - : undefined; - relays.add( - C.Relay.new_single_host_addr( - C.SingleHostAddr.new(relay.port, ipV4, ipV6) - ) - ); - break; - } - case "SingleHostDomainName": { - relays.add( - C.Relay.new_single_host_name( - C.SingleHostName.new( - relay.port, - C.DNSRecordAorAAAA.new(relay.domainName!) - ) - ) - ); - break; - } - case "MultiHost": { - relays.add( - C.Relay.new_multi_host_name( - C.MultiHostName.new(C.DNSRecordSRV.new(relay.domainName!)) - ) - ); - break; - } + const changeAddress = C.Address.from_bech32( + await this.lucid.wallet.address(), + ); + const halfValue = C.Value.new(half); + const changeOutput = C.TransactionOutput.new(changeAddress, halfValue); + bucket.push( + half, + changeAda, + split, + changeAddress, + halfValue, + changeOutput, + ); + this.txBuilder.add_output(changeOutput); } - }); - - return C.PoolRegistration.new( - C.PoolParams.new( - C.Ed25519KeyHash.from_bech32(poolParams.poolId), - C.VRFKeyHash.from_hex(poolParams.vrfKeyHash), - C.BigNum.from_str(poolParams.pledge.toString()), - C.BigNum.from_str(poolParams.cost.toString()), - C.UnitInterval.from_float(poolParams.margin), - C.RewardAddress.from_address( - addressFromWithNetworkCheck(poolParams.rewardAddress, lucid) - )!, - poolOwners, - relays, - metadataHash - ? C.PoolMetadata.new(C.Url.new(poolParams.metadataUrl!), metadataHash) - : undefined - ) - ); -} - -function addressFromWithNetworkCheck( - address: Address | RewardAddress, - lucid: Lucid -): C.Address { - const { type, networkId } = lucid.utils.getAddressDetails(address); - - const actualNetworkId = networkToId(lucid.network); - if (networkId !== actualNetworkId) { - throw new Error( - `Invalid address: Expected address with network id ${actualNetworkId}, but got ${networkId}`, - ); } - return type === "Byron" - ? C.ByronAddress.from_base58(address).to_address() - : C.Address.from_bech32(address); } diff --git a/src/lucid/tx_complete.ts b/src/lucid/tx_complete.ts index 1566b4dd..ce396b7e 100644 --- a/src/lucid/tx_complete.ts +++ b/src/lucid/tx_complete.ts @@ -8,6 +8,7 @@ import { import { Lucid } from "./lucid.ts"; import { TxSigned } from "./tx_signed.ts"; import { fromHex, toHex } from "../utils/mod.ts"; +import { FreeableBucket, Freeables } from "../utils/freeable.ts"; export class TxComplete { txComplete: C.Transaction; @@ -18,39 +19,64 @@ export class TxComplete { exUnits: { cpu: number; mem: number } | null = null; constructor(lucid: Lucid, tx: C.Transaction) { + const bucket: FreeableBucket = []; this.lucid = lucid; this.txComplete = tx; this.witnessSetBuilder = C.TransactionWitnessSetBuilder.new(); this.tasks = []; - this.fee = parseInt(tx.body().fee().to_str()); - const redeemers = tx.witness_set().redeemers(); + const body = tx.body(); + bucket.push(body); + const fee = body.fee(); + bucket.push(fee); + const witnessSet = tx.witness_set(); + bucket.push(witnessSet); + + this.fee = parseInt(fee.to_str()); + const redeemers = witnessSet.redeemers(); + bucket.push(redeemers); if (redeemers) { const exUnits = { cpu: 0, mem: 0 }; for (let i = 0; i < redeemers.len(); i++) { const redeemer = redeemers.get(i); - exUnits.cpu += parseInt(redeemer.ex_units().steps().to_str()); - exUnits.mem += parseInt(redeemer.ex_units().mem().to_str()); + bucket.push(redeemer); + const cExUnits = redeemer.ex_units(); + bucket.push(cExUnits); + const steps = cExUnits.steps(); + bucket.push(steps); + const mem = cExUnits.mem(); + bucket.push(mem); + + exUnits.cpu += parseInt(steps.to_str()); + exUnits.mem += parseInt(mem.to_str()); } this.exUnits = exUnits; } + + Freeables.free(...bucket); } sign(): TxComplete { this.tasks.push(async () => { const witnesses = await this.lucid.wallet.signTx(this.txComplete); this.witnessSetBuilder.add_existing(witnesses); + witnesses.free(); }); return this; } /** Add an extra signature from a private key. */ signWithPrivateKey(privateKey: PrivateKey): TxComplete { + const bucket: FreeableBucket = []; const priv = C.PrivateKey.from_bech32(privateKey); - const witness = C.make_vkey_witness( - C.hash_transaction(this.txComplete.body()), - priv, - ); + bucket.push(priv); + const body = this.txComplete.body(); + bucket.push(body); + const hash = C.hash_transaction(body); + bucket.push(hash); + const witness = C.make_vkey_witness(hash, priv); + bucket.push(witness); this.witnessSetBuilder.add_vkey(witness); + Freeables.free(...bucket); return this; } @@ -58,7 +84,9 @@ export class TxComplete { async partialSign(): Promise { const witnesses = await this.lucid.wallet.signTx(this.txComplete); this.witnessSetBuilder.add_existing(witnesses); - return toHex(witnesses.to_bytes()); + const bytes = witnesses.to_bytes(); + witnesses.free(); + return toHex(bytes); } /** @@ -66,24 +94,36 @@ export class TxComplete { * Add an extra signature from a private key. */ partialSignWithPrivateKey(privateKey: PrivateKey): TransactionWitnesses { + const bucket: FreeableBucket = []; const priv = C.PrivateKey.from_bech32(privateKey); - const witness = C.make_vkey_witness( - C.hash_transaction(this.txComplete.body()), - priv, - ); + bucket.push(priv); + const body = this.txComplete.body(); + bucket.push(body); + const hash = C.hash_transaction(body); + bucket.push(hash); + const witness = C.make_vkey_witness(hash, priv); + bucket.push(witness); + this.witnessSetBuilder.add_vkey(witness); const witnesses = C.TransactionWitnessSetBuilder.new(); + bucket.push(witnesses); witnesses.add_vkey(witness); - return toHex(witnesses.build().to_bytes()); + const witnessSet = witnesses.build(); + bucket.push(witnessSet); + const bytes = witnessSet.to_bytes(); + + Freeables.free(...bucket); + return toHex(bytes); } /** Sign the transaction with the given witnesses. */ assemble(witnesses: TransactionWitnesses[]): TxComplete { witnesses.forEach((witness) => { const witnessParsed = C.TransactionWitnessSet.from_bytes( - fromHex(witness), + fromHex(witness) ); this.witnessSetBuilder.add_existing(witnessParsed); + witnessParsed.free(); }); return this; } @@ -93,12 +133,19 @@ export class TxComplete { await task(); } - this.witnessSetBuilder.add_existing(this.txComplete.witness_set()); - const signedTx = C.Transaction.new( - this.txComplete.body(), - this.witnessSetBuilder.build(), - this.txComplete.auxiliary_data(), - ); + const bucket: FreeableBucket = []; + const txCompleteWitnessSet = this.txComplete.witness_set(); + bucket.push(txCompleteWitnessSet); + this.witnessSetBuilder.add_existing(txCompleteWitnessSet); + const body = this.txComplete.body(); + bucket.push(body); + const witnessSet = this.witnessSetBuilder.build(); + bucket.push(witnessSet); + const auxiliaryData = this.txComplete.auxiliary_data(); + bucket.push(auxiliaryData); + const signedTx = C.Transaction.new(body, witnessSet, auxiliaryData); + + Freeables.free(...bucket); return new TxSigned(this.lucid, signedTx); } @@ -109,6 +156,16 @@ export class TxComplete { /** Return the transaction hash. */ toHash(): TxHash { - return C.hash_transaction(this.txComplete.body()).to_hex(); + const body = this.txComplete.body(); + const hash = C.hash_transaction(body); + const txHash = hash.to_hex(); + Freeables.free(body, hash); + return txHash; + } + + /** Since this object has WASM fields, we must use the free method to free the fields */ + free() { + this.txComplete.free(); + this.witnessSetBuilder.free(); } } diff --git a/src/lucid/tx_signed.ts b/src/lucid/tx_signed.ts index 5d7bf2b9..4d1be552 100644 --- a/src/lucid/tx_signed.ts +++ b/src/lucid/tx_signed.ts @@ -13,7 +13,7 @@ export class TxSigned { async submit(): Promise { return await (this.lucid.wallet || this.lucid.provider).submitTx( - toHex(this.txSigned.to_bytes()), + toHex(this.txSigned.to_bytes()) ); } @@ -24,6 +24,14 @@ export class TxSigned { /** Return the transaction hash. */ toHash(): TxHash { - return C.hash_transaction(this.txSigned.body()).to_hex(); + const hash = C.hash_transaction(this.txSigned.body()); + const txHash = hash.to_hex(); + hash.free(); + return txHash; + } + + /** Since this object has WASM fields, we must use the free method to free the fields */ + free() { + this.txSigned.free(); } } diff --git a/src/plutus/data.ts b/src/plutus/data.ts index 2468c725..5e54f3a9 100644 --- a/src/plutus/data.ts +++ b/src/plutus/data.ts @@ -10,6 +10,7 @@ import { import { C } from "../core/mod.ts"; import { Datum, Exact, Json, Redeemer } from "../types/mod.ts"; import { fromHex, fromText, toHex } from "../utils/utils.ts"; +import { FreeableBucket, Freeables } from "../utils/freeable.ts"; export class Constr { index: number; @@ -38,14 +39,12 @@ export type Data = export const Data = { // Types // Note: Recursive types are not supported (yet) - Integer: function ( - options?: { - minimum?: number; - maximum?: number; - exclusiveMinimum?: number; - exclusiveMaximum?: number; - }, - ) { + Integer: function (options?: { + minimum?: number; + maximum?: number; + exclusiveMinimum?: number; + exclusiveMaximum?: number; + }) { const integer = Type.Unsafe({ dataType: "integer" }); if (options) { Object.entries(options).forEach(([key, value]) => { @@ -54,9 +53,11 @@ export const Data = { } return integer; }, - Bytes: function ( - options?: { minLength?: number; maxLength?: number; enum?: string[] }, - ) { + Bytes: function (options?: { + minLength?: number; + maxLength?: number; + enum?: string[]; + }) { const bytes = Type.Unsafe({ dataType: "bytes" }); if (options) { Object.entries(options).forEach(([key, value]) => { @@ -88,7 +89,7 @@ export const Data = { }, Array: function ( items: T, - options?: { minItems?: number; maxItems?: number; uniqueItems?: boolean }, + options?: { minItems?: number; maxItems?: number; uniqueItems?: boolean } ) { const array = Type.Array(items); replaceProperties(array, { dataType: "list", items }); @@ -102,7 +103,7 @@ export const Data = { Map: function ( keys: T, values: U, - options?: { minItems?: number; maxItems?: number }, + options?: { minItems?: number; maxItems?: number } ) { const map = Type.Unsafe, Data.Static>>({ dataType: "map", @@ -122,55 +123,55 @@ export const Data = { */ Object: function ( properties: T, - options?: { hasConstr?: boolean }, + options?: { hasConstr?: boolean } ) { const object = Type.Object(properties); replaceProperties(object, { - anyOf: [{ - dataType: "constructor", - index: 0, // Will be replaced when using Data.Enum - fields: Object.entries(properties).map(([title, p]) => ({ - ...p, - title, - })), - }], + anyOf: [ + { + dataType: "constructor", + index: 0, // Will be replaced when using Data.Enum + fields: Object.entries(properties).map(([title, p]) => ({ + ...p, + title, + })), + }, + ], }); - object.anyOf[0].hasConstr = typeof options?.hasConstr === "undefined" || - options.hasConstr; + object.anyOf[0].hasConstr = + typeof options?.hasConstr === "undefined" || options.hasConstr; return object; }, Enum: function (items: T[]) { const union = Type.Union(items); - replaceProperties( - union, - { - anyOf: items.map((item, index) => - item.anyOf[0].fields.length === 0 - ? ({ + replaceProperties(union, { + anyOf: items.map((item, index) => + item.anyOf[0].fields.length === 0 + ? { ...item.anyOf[0], index, - }) - : ({ + } + : { dataType: "constructor", title: (() => { const title = item.anyOf[0].fields[0].title; if ( (title as string).charAt(0) !== - (title as string).charAt(0).toUpperCase() + (title as string).charAt(0).toUpperCase() ) { throw new Error( - `Enum '${title}' needs to start with an uppercase letter.`, + `Enum '${title}' needs to start with an uppercase letter.` ); } return item.anyOf[0].fields[0].title; })(), index, - fields: item.anyOf[0].fields[0].items || + fields: + item.anyOf[0].fields[0].items || item.anyOf[0].fields[0].anyOf[0].fields, - }) - ), - }, - ); + } + ), + }); return union; }, /** @@ -179,7 +180,7 @@ export const Data = { */ Tuple: function ( items: [...T], - options?: { hasConstr?: boolean }, + options?: { hasConstr?: boolean } ) { const tuple = Type.Tuple(items); replaceProperties(tuple, { @@ -198,17 +199,19 @@ export const Data = { (title as string).charAt(0) !== (title as string).charAt(0).toUpperCase() ) { throw new Error( - `Enum '${title}' needs to start with an uppercase letter.`, + `Enum '${title}' needs to start with an uppercase letter.` ); } const literal = Type.Literal(title); replaceProperties(literal, { - anyOf: [{ - dataType: "constructor", - title, - index: 0, // Will be replaced in Data.Enum - fields: [], - }], + anyOf: [ + { + dataType: "constructor", + title, + index: 0, // Will be replaced in Data.Enum + fields: [], + }, + ], }); return literal; }, @@ -220,9 +223,7 @@ export const Data = { description: "An optional value.", dataType: "constructor", index: 0, - fields: [ - item, - ], + fields: [item], }, { title: "None", @@ -264,36 +265,51 @@ export const Data = { */ function to(data: Exact, type?: T): Datum | Redeemer { function serialize(data: Data): C.PlutusData { + const bucket: FreeableBucket = []; try { - if ( - typeof data === "bigint" - ) { - return C.PlutusData.new_integer(C.BigInt.from_str(data.toString())); + if (typeof data === "bigint") { + const integer = C.BigInt.from_str(data.toString()); + bucket.push(integer); + return C.PlutusData.new_integer(integer); } else if (typeof data === "string") { return C.PlutusData.new_bytes(fromHex(data)); } else if (data instanceof Constr) { const { index, fields } = data; const plutusList = C.PlutusList.new(); - - fields.forEach((field) => plutusList.add(serialize(field))); - - return C.PlutusData.new_constr_plutus_data( - C.ConstrPlutusData.new( - C.BigNum.from_str(index.toString()), - plutusList, - ), + bucket.push(plutusList); + fields.forEach((field) => { + const serializedField = serialize(field); + plutusList.add(serializedField); + bucket.push(serializedField); + }); + + const constrIndex = C.BigNum.from_str(index.toString()); + bucket.push(constrIndex); + const cosntrPlutusData = C.ConstrPlutusData.new( + constrIndex, + plutusList ); + bucket.push(cosntrPlutusData); + return C.PlutusData.new_constr_plutus_data(cosntrPlutusData); } else if (data instanceof Array) { const plutusList = C.PlutusList.new(); - - data.forEach((arg) => plutusList.add(serialize(arg))); + bucket.push(plutusList); + data.forEach((arg) => { + const serializedArg = serialize(arg); + plutusList.add(serializedArg); + bucket.push(serializedArg); + }); return C.PlutusData.new_list(plutusList); } else if (data instanceof Map) { const plutusMap = C.PlutusMap.new(); - + bucket.push(plutusMap); for (const [key, value] of data.entries()) { - plutusMap.insert(serialize(key), serialize(value)); + const serializedKey = serialize(key); + bucket.push(serializedKey); + const serializedValue = serialize(value); + bucket.push(serializedValue); + plutusMap.insert(serializedKey, serializedValue); } return C.PlutusData.new_map(plutusMap); @@ -301,10 +317,15 @@ function to(data: Exact, type?: T): Datum | Redeemer { throw new Error("Unsupported type"); } catch (error) { throw new Error("Could not serialize the data: " + error); + } finally { + Freeables.free(...bucket); } } - const d = type ? castTo(data, type) : data as Data; - return toHex(serialize(d).to_bytes()) as Datum | Redeemer; + const d = type ? castTo(data, type) : (data as Data); + const serializedD = serialize(d); + const result = toHex(serializedD.to_bytes()) as Datum | Redeemer; + serializedD.free(); + return result; } /** @@ -313,39 +334,63 @@ function to(data: Exact, type?: T): Datum | Redeemer { */ function from(raw: Datum | Redeemer, type?: T): T { function deserialize(data: C.PlutusData): Data { - if (data.kind() === 0) { - const constr = data.as_constr_plutus_data()!; - const l = constr.data(); - const desL = []; - for (let i = 0; i < l.len(); i++) { - desL.push(deserialize(l.get(i))); - } - return new Constr(parseInt(constr.alternative().to_str()), desL); - } else if (data.kind() === 1) { - const m = data.as_map()!; - const desM: Map = new Map(); - const keys = m.keys(); - for (let i = 0; i < keys.len(); i++) { - desM.set(deserialize(keys.get(i)), deserialize(m.get(keys.get(i))!)); - } - return desM; - } else if (data.kind() === 2) { - const l = data.as_list()!; - const desL = []; - for (let i = 0; i < l.len(); i++) { - desL.push(deserialize(l.get(i))); + const bucket: FreeableBucket = []; + try { + if (data.kind() === 0) { + const constr = data.as_constr_plutus_data()!; + bucket.push(constr); + const l = constr.data(); + bucket.push(l); + const desL = []; + for (let i = 0; i < l.len(); i++) { + const des = l.get(i); + bucket.push(des); + desL.push(deserialize(des)); + } + const alternativeConstr = constr.alternative(); + bucket.push(alternativeConstr); + return new Constr(parseInt(alternativeConstr.to_str()), desL); + } else if (data.kind() === 1) { + const m = data.as_map()!; + bucket.push(m); + const desM: Map = new Map(); + const keys = m.keys(); + bucket.push(keys); + for (let i = 0; i < keys.len(); i++) { + const key = keys.get(i); + bucket.push(key); + const value = m.get(key)!; + bucket.push(value); + desM.set(deserialize(key), deserialize(value)); + } + return desM; + } else if (data.kind() === 2) { + const l = data.as_list()!; + bucket.push(l); + const desL = []; + for (let i = 0; i < l.len(); i++) { + const elem = l.get(i); + bucket.push(elem); + desL.push(deserialize(elem)); + } + return desL; + } else if (data.kind() === 3) { + const i = data.as_integer()!; + bucket.push(i); + return BigInt(i.to_str()); + } else if (data.kind() === 4) { + return toHex(data.as_bytes()!); } - return desL; - } else if (data.kind() === 3) { - return BigInt(data.as_integer()!.to_str()); - } else if (data.kind() === 4) { - return toHex(data.as_bytes()!); + throw new Error("Unsupported type"); + } finally { + Freeables.free(...bucket); } - throw new Error("Unsupported type"); } - const data = deserialize(C.PlutusData.from_bytes(fromHex(raw))); + const plutusData = C.PlutusData.from_bytes(fromHex(raw)); + const data = deserialize(plutusData); + plutusData.free(); - return type ? castFrom(data, type) : data as T; + return type ? castFrom(data, type) : (data as T); } /** @@ -386,15 +431,14 @@ function toJson(plutusData: Data): Json { !isNaN(parseInt(data)) && data.slice(-1) === "n") ) { - const bigint = typeof data === "string" - ? BigInt(data.slice(0, -1)) - : data; + const bigint = + typeof data === "string" ? BigInt(data.slice(0, -1)) : data; return parseInt(bigint.toString()); } if (typeof data === "string") { try { return new TextDecoder(undefined, { fatal: true }).decode( - fromHex(data), + fromHex(data) ); } catch (_) { return "0x" + toHex(fromHex(data)); @@ -410,7 +454,7 @@ function toJson(plutusData: Data): Json { typeof convertedKey !== "number" ) { throw new Error( - "Unsupported type (Note: Only bytes or integers can be keys of a JSON object)", + "Unsupported type (Note: Only bytes or integers can be keys of a JSON object)" ); } tempJson[convertedKey] = fromData(value); @@ -418,7 +462,7 @@ function toJson(plutusData: Data): Json { return tempJson; } throw new Error( - "Unsupported type (Note: Constructor cannot be converted to JSON)", + "Unsupported type (Note: Constructor cannot be converted to JSON)" ); } return fromData(plutusData); @@ -447,59 +491,52 @@ function castFrom(data: Data, type: T): T { case "constructor": { if (isVoid(shape)) { if ( - !(data instanceof Constr) || data.index !== 0 || + !(data instanceof Constr) || + data.index !== 0 || data.fields.length !== 0 ) { throw new Error("Could not type cast to void."); } return undefined as T; } else if ( - data instanceof Constr && data.index === shape.index && + data instanceof Constr && + data.index === shape.index && (shape.hasConstr || shape.hasConstr === undefined) ) { const fields: Record = {}; if (shape.fields.length !== data.fields.length) { throw new Error( - "Could not type cast to object. Fields do not match.", + "Could not type cast to object. Fields do not match." ); } - shape.fields.forEach( - (field: Json, fieldIndex: number) => { - const title = field.title || "wrapper"; - if ((/[A-Z]/.test(title[0]))) { - throw new Error( - "Could not type cast to object. Object properties need to start with a lowercase letter.", - ); - } - fields[title] = castFrom( - data.fields[fieldIndex], - field, + shape.fields.forEach((field: Json, fieldIndex: number) => { + const title = field.title || "wrapper"; + if (/[A-Z]/.test(title[0])) { + throw new Error( + "Could not type cast to object. Object properties need to start with a lowercase letter." ); - }, - ); + } + fields[title] = castFrom(data.fields[fieldIndex], field); + }); return fields as T; } else if ( - data instanceof Array && !shape.hasConstr && + data instanceof Array && + !shape.hasConstr && shape.hasConstr !== undefined ) { const fields: Record = {}; if (shape.fields.length !== data.length) { throw new Error("Could not ype cast to object. Fields do not match."); } - shape.fields.forEach( - (field: Json, fieldIndex: number) => { - const title = field.title || "wrapper"; - if ((/[A-Z]/.test(title[0]))) { - throw new Error( - "Could not type cast to object. Object properties need to start with a lowercase letter.", - ); - } - fields[title] = castFrom( - data[fieldIndex], - field, + shape.fields.forEach((field: Json, fieldIndex: number) => { + const title = field.title || "wrapper"; + if (/[A-Z]/.test(title[0])) { + throw new Error( + "Could not type cast to object. Object properties need to start with a lowercase letter." ); - }, - ); + } + fields[title] = castFrom(data[fieldIndex], field); + }); return fields as T; } throw new Error("Could not type cast to object."); @@ -514,8 +551,8 @@ function castFrom(data: Data, type: T): T { throw new Error("Could not type cast to enum."); } - const enumShape = shape.anyOf.find((entry: Json) => - entry.index === data.index + const enumShape = shape.anyOf.find( + (entry: Json) => entry.index === data.index ); if (!enumShape || enumShape.fields.length !== data.fields.length) { throw new Error("Could not type cast to enum."); @@ -534,17 +571,13 @@ function castFrom(data: Data, type: T): T { } else if (isNullable(shape)) { switch (data.index) { case 0: { - if ( - data.fields.length !== 1 - ) { + if (data.fields.length !== 1) { throw new Error("Could not type cast to nullable object."); } return castFrom(data.fields[0], shape.anyOf[0].fields[0]); } case 1: { - if ( - data.fields.length !== 0 - ) { + if (data.fields.length !== 0) { throw new Error("Could not type cast to nullable object."); } return null as T; @@ -555,16 +588,14 @@ function castFrom(data: Data, type: T): T { switch (enumShape.dataType) { case "constructor": { if (enumShape.fields.length === 0) { - if ( - /[A-Z]/.test(enumShape.title[0]) - ) { + if (/[A-Z]/.test(enumShape.title[0])) { return enumShape.title as T; } throw new Error("Could not type cast to enum."); } else { - if (!(/[A-Z]/.test(enumShape.title))) { + if (!/[A-Z]/.test(enumShape.title)) { throw new Error( - "Could not type cast to enum. Enums need to start with an uppercase letter.", + "Could not type cast to enum. Enums need to start with an uppercase letter." ); } @@ -574,14 +605,15 @@ function castFrom(data: Data, type: T): T { // check if named args const args = enumShape.fields[0].title - ? Object.fromEntries(enumShape.fields.map(( - field: Json, - index: number, - ) => [field.title, castFrom(data.fields[index], field)])) - : enumShape.fields.map(( - field: Json, - index: number, - ) => castFrom(data.fields[index], field)); + ? Object.fromEntries( + enumShape.fields.map((field: Json, index: number) => [ + field.title, + castFrom(data.fields[index], field), + ]) + ) + : enumShape.fields.map((field: Json, index: number) => + castFrom(data.fields[index], field) + ); return { [enumShape.title]: args, @@ -594,11 +626,7 @@ function castFrom(data: Data, type: T): T { case "list": { if (shape.items instanceof Array) { // tuple - if ( - data instanceof Constr && - data.index === 0 && - shape.hasConstr - ) { + if (data instanceof Constr && data.index === 0 && shape.hasConstr) { return data.fields.map((field, index) => castFrom(field, shape.items[index]) ) as T; @@ -625,10 +653,7 @@ function castFrom(data: Data, type: T): T { } mapConstraints(data, shape); const map = new Map(); - for ( - const [key, value] of (data) - .entries() - ) { + for (const [key, value] of data.entries()) { map.set(castFrom(key, shape.keys), castFrom(value, shape.values)); } return map as T; @@ -667,7 +692,8 @@ function castTo(struct: Exact, type: T): Data { } return new Constr(0, []); } else if ( - typeof struct !== "object" || struct === null || + typeof struct !== "object" || + struct === null || shape.fields.length !== Object.keys(struct).length ) { throw new Error("Could not type cast to constructor."); @@ -675,10 +701,10 @@ function castTo(struct: Exact, type: T): Data { const fields = shape.fields.map((field: Json) => castTo( (struct as Record)[field.title || "wrapper"], - field, + field ) ); - return (shape.hasConstr || shape.hasConstr === undefined) + return shape.hasConstr || shape.hasConstr === undefined ? new Constr(shape.index, fields) : fields; } @@ -690,9 +716,7 @@ function castTo(struct: Exact, type: T): Data { if (isBoolean(shape)) { if (typeof struct !== "boolean") { - throw new Error( - "Could not type cast to boolean.", - ); + throw new Error("Could not type cast to boolean."); } return new Constr(struct ? 1 : 0, []); } else if (isNullable(shape)) { @@ -702,24 +726,21 @@ function castTo(struct: Exact, type: T): Data { if (fields.length !== 1) { throw new Error("Could not type cast to nullable object."); } - return new Constr(0, [ - castTo(struct, fields[0]), - ]); + return new Constr(0, [castTo(struct, fields[0])]); } } switch (typeof struct) { case "string": { - if (!(/[A-Z]/.test(struct[0]))) { + if (!/[A-Z]/.test(struct[0])) { throw new Error( - "Could not type cast to enum. Enum needs to start with an uppercase letter.", + "Could not type cast to enum. Enum needs to start with an uppercase letter." ); } - const enumIndex = (shape as TEnum).anyOf.findIndex(( - s: TLiteral, - ) => - s.dataType === "constructor" && - s.fields.length === 0 && - s.title === struct + const enumIndex = (shape as TEnum).anyOf.findIndex( + (s: TLiteral) => + s.dataType === "constructor" && + s.fields.length === 0 && + s.title === struct ); if (enumIndex === -1) throw new Error("Could not type cast to enum."); return new Constr(enumIndex, []); @@ -728,14 +749,13 @@ function castTo(struct: Exact, type: T): Data { if (struct === null) throw new Error("Could not type cast to enum."); const structTitle = Object.keys(struct)[0]; - if (!(/[A-Z]/.test(structTitle))) { + if (!/[A-Z]/.test(structTitle)) { throw new Error( - "Could not type cast to enum. Enum needs to start with an uppercase letter.", + "Could not type cast to enum. Enum needs to start with an uppercase letter." ); } - const enumEntry = shape.anyOf.find((s: Json) => - s.dataType === "constructor" && - s.title === structTitle + const enumEntry = shape.anyOf.find( + (s: Json) => s.dataType === "constructor" && s.title === structTitle ); if (!enumEntry) throw new Error("Could not type cast to enum."); @@ -747,16 +767,14 @@ function castTo(struct: Exact, type: T): Data { // check if named args args instanceof Array ? args.map((item, index) => - castTo(item, enumEntry.fields[index]) - ) - : enumEntry.fields.map( - (entry: Json) => { - const [_, item]: [string, Json] = Object.entries(args).find(( - [title], - ) => title === entry.title)!; + castTo(item, enumEntry.fields[index]) + ) + : enumEntry.fields.map((entry: Json) => { + const [_, item]: [string, Json] = Object.entries(args).find( + ([title]) => title === entry.title + )!; return castTo(item, entry); - }, - ), + }) ); } } @@ -786,10 +804,7 @@ function castTo(struct: Exact, type: T): Data { mapConstraints(struct, shape); const map = new Map(); - for ( - const [key, value] of (struct) - .entries() - ) { + for (const [key, value] of struct.entries()) { map.set(castTo(key, shape.keys), castTo(value, shape.values)); } return map; @@ -804,79 +819,72 @@ function castTo(struct: Exact, type: T): Data { function integerConstraints(integer: bigint, shape: TSchema) { if (shape.minimum && integer < BigInt(shape.minimum)) { throw new Error( - `Integer ${integer} is below the minimum ${shape.minimum}.`, + `Integer ${integer} is below the minimum ${shape.minimum}.` ); } if (shape.maximum && integer > BigInt(shape.maximum)) { throw new Error( - `Integer ${integer} is above the maxiumum ${shape.maximum}.`, + `Integer ${integer} is above the maxiumum ${shape.maximum}.` ); } if (shape.exclusiveMinimum && integer <= BigInt(shape.exclusiveMinimum)) { throw new Error( - `Integer ${integer} is below the exclusive minimum ${shape.exclusiveMinimum}.`, + `Integer ${integer} is below the exclusive minimum ${shape.exclusiveMinimum}.` ); } if (shape.exclusiveMaximum && integer >= BigInt(shape.exclusiveMaximum)) { throw new Error( - `Integer ${integer} is above the exclusive maximum ${shape.exclusiveMaximum}.`, + `Integer ${integer} is above the exclusive maximum ${shape.exclusiveMaximum}.` ); } } function bytesConstraints(bytes: string, shape: TSchema) { - if ( - shape.enum && !shape.enum.some((keyword: string) => keyword === bytes) - ) throw new Error(`None of the keywords match with '${bytes}'.`); + if (shape.enum && !shape.enum.some((keyword: string) => keyword === bytes)) { + throw new Error(`None of the keywords match with '${bytes}'.`); + } if (shape.minLength && bytes.length / 2 < shape.minLength) { throw new Error( - `Bytes need to have a length of at least ${shape.minLength} bytes.`, + `Bytes need to have a length of at least ${shape.minLength} bytes.` ); } if (shape.maxLength && bytes.length / 2 > shape.maxLength) { throw new Error( - `Bytes can have a length of at most ${shape.minLength} bytes.`, + `Bytes can have a length of at most ${shape.minLength} bytes.` ); } } function listConstraints(list: Array, shape: TSchema) { if (shape.minItems && list.length < shape.minItems) { - throw new Error( - `Array needs to contain at least ${shape.minItems} items.`, - ); + throw new Error(`Array needs to contain at least ${shape.minItems} items.`); } if (shape.maxItems && list.length > shape.maxItems) { - throw new Error( - `Array can contain at most ${shape.maxItems} items.`, - ); + throw new Error(`Array can contain at most ${shape.maxItems} items.`); } - if (shape.uniqueItems && (new Set(list)).size !== list.length) { + if (shape.uniqueItems && new Set(list).size !== list.length) { // Note this only works for primitive types like string and bigint. - throw new Error( - "Array constains duplicates.", - ); + throw new Error("Array constains duplicates."); } } function mapConstraints(map: Map, shape: TSchema) { if (shape.minItems && map.size < shape.minItems) { - throw new Error( - `Map needs to contain at least ${shape.minItems} items.`, - ); + throw new Error(`Map needs to contain at least ${shape.minItems} items.`); } if (shape.maxItems && map.size > shape.maxItems) { - throw new Error( - `Map can contain at most ${shape.maxItems} items.`, - ); + throw new Error(`Map can contain at most ${shape.maxItems} items.`); } } function isBoolean(shape: TSchema): boolean { - return shape.anyOf && shape.anyOf[0]?.title === "False" && - shape.anyOf[1]?.title === "True"; + return ( + shape.anyOf && + shape.anyOf[0]?.title === "False" && + shape.anyOf[1]?.title === "True" + ); } function isVoid(shape: TSchema): boolean { @@ -884,8 +892,11 @@ function isVoid(shape: TSchema): boolean { } function isNullable(shape: TSchema): boolean { - return shape.anyOf && shape.anyOf[0]?.title === "Some" && - shape.anyOf[1]?.title === "None"; + return ( + shape.anyOf && + shape.anyOf[0]?.title === "Some" && + shape.anyOf[1]?.title === "None" + ); } function replaceProperties(object: Json, properties: Json) { diff --git a/src/provider/blockfrost.ts b/src/provider/blockfrost.ts index b0991796..3960dbef 100644 --- a/src/provider/blockfrost.ts +++ b/src/provider/blockfrost.ts @@ -16,6 +16,7 @@ import { UTxO, } from "../types/mod.ts"; import packageJson from "../../package.json" assert { type: "json" }; +import { FreeableBucket, Freeables } from "../utils/freeable.ts"; export class Blockfrost implements Provider { url: string; @@ -52,13 +53,13 @@ export class Blockfrost implements Provider { async getUtxos(addressOrCredential: Address | Credential): Promise { const queryPredicate = (() => { if (typeof addressOrCredential === "string") return addressOrCredential; - const credentialBech32 = addressOrCredential.type === "Key" - ? C.Ed25519KeyHash.from_hex(addressOrCredential.hash).to_bech32( - "addr_vkh", - ) - : C.ScriptHash.from_hex(addressOrCredential.hash).to_bech32( - "addr_vkh", - ); // should be 'script' (CIP-0005) + const hash = + addressOrCredential.type === "Key" + ? C.Ed25519KeyHash.from_hex(addressOrCredential.hash) + : C.ScriptHash.from_hex(addressOrCredential.hash); + + const credentialBech32 = hash.to_bech32("addr_vkh"); // should be 'script' according to CIP-0005, but to maintain bakcwards compatabiltiy I am not changing this + hash.free(); return credentialBech32; })(); let result: BlockfrostUtxoResult = []; @@ -67,7 +68,7 @@ export class Blockfrost implements Provider { const pageResult: BlockfrostUtxoResult | BlockfrostUtxoError = await fetch( `${this.url}/addresses/${queryPredicate}/utxos?page=${page}`, - { headers: { project_id: this.projectId, lucid } }, + { headers: { project_id: this.projectId, lucid } } ).then((res) => res.json()); if ((pageResult as BlockfrostUtxoError).error) { if ((pageResult as BlockfrostUtxoError).status_code === 404) { @@ -86,17 +87,17 @@ export class Blockfrost implements Provider { async getUtxosWithUnit( addressOrCredential: Address | Credential, - unit: Unit, + unit: Unit ): Promise { const queryPredicate = (() => { if (typeof addressOrCredential === "string") return addressOrCredential; - const credentialBech32 = addressOrCredential.type === "Key" - ? C.Ed25519KeyHash.from_hex(addressOrCredential.hash).to_bech32( - "addr_vkh", - ) - : C.ScriptHash.from_hex(addressOrCredential.hash).to_bech32( - "addr_vkh", - ); // should be 'script' (CIP-0005) + const hash = + addressOrCredential.type === "Key" + ? C.Ed25519KeyHash.from_hex(addressOrCredential.hash) + : C.ScriptHash.from_hex(addressOrCredential.hash); + + const credentialBech32 = hash.to_bech32("addr_vkh"); // should be 'script' according to CIP-0005, but to maintain bakcwards compatabiltiy I am not changing this + hash.free(); return credentialBech32; })(); let result: BlockfrostUtxoResult = []; @@ -105,7 +106,7 @@ export class Blockfrost implements Provider { const pageResult: BlockfrostUtxoResult | BlockfrostUtxoError = await fetch( `${this.url}/addresses/${queryPredicate}/utxos/${unit}?page=${page}`, - { headers: { project_id: this.projectId, lucid } }, + { headers: { project_id: this.projectId, lucid } } ).then((res) => res.json()); if ((pageResult as BlockfrostUtxoError).error) { if ((pageResult as BlockfrostUtxoError).status_code === 404) { @@ -125,7 +126,7 @@ export class Blockfrost implements Provider { async getUtxoByUnit(unit: Unit): Promise { const addresses = await fetch( `${this.url}/assets/${unit}/addresses?count=2`, - { headers: { project_id: this.projectId, lucid } }, + { headers: { project_id: this.projectId, lucid } } ).then((res) => res.json()); if (!addresses || addresses.error) { @@ -149,36 +150,42 @@ export class Blockfrost implements Provider { async getUtxosByOutRef(outRefs: OutRef[]): Promise { // TODO: Make sure old already spent UTxOs are not retrievable. const queryHashes = [...new Set(outRefs.map((outRef) => outRef.txHash))]; - const utxos = await Promise.all(queryHashes.map(async (txHash) => { - const result = await fetch( - `${this.url}/txs/${txHash}/utxos`, - { headers: { project_id: this.projectId, lucid } }, - ).then((res) => res.json()); - if (!result || result.error) { - return []; - } - const utxosResult: BlockfrostUtxoResult = result.outputs.map(( - // deno-lint-ignore no-explicit-any - r: any, - ) => ({ - ...r, - tx_hash: txHash, - })); - return this.blockfrostUtxosToUtxos(utxosResult); - })); - - return utxos.reduce((acc, utxos) => acc.concat(utxos), []).filter((utxo) => - outRefs.some((outRef) => - utxo.txHash === outRef.txHash && utxo.outputIndex === outRef.outputIndex - ) + const utxos = await Promise.all( + queryHashes.map(async (txHash) => { + const result = await fetch(`${this.url}/txs/${txHash}/utxos`, { + headers: { project_id: this.projectId, lucid }, + }).then((res) => res.json()); + if (!result || result.error) { + return []; + } + const utxosResult: BlockfrostUtxoResult = result.outputs.map( + ( + // deno-lint-ignore no-explicit-any + r: any + ) => ({ + ...r, + tx_hash: txHash, + }) + ); + return this.blockfrostUtxosToUtxos(utxosResult); + }) ); + + return utxos + .reduce((acc, utxos) => acc.concat(utxos), []) + .filter((utxo) => + outRefs.some( + (outRef) => + utxo.txHash === outRef.txHash && + utxo.outputIndex === outRef.outputIndex + ) + ); } async getDelegation(rewardAddress: RewardAddress): Promise { - const result = await fetch( - `${this.url}/accounts/${rewardAddress}`, - { headers: { project_id: this.projectId, lucid } }, - ).then((res) => res.json()); + const result = await fetch(`${this.url}/accounts/${rewardAddress}`, { + headers: { project_id: this.projectId, lucid }, + }).then((res) => res.json()); if (!result || result.error) { return { poolId: null, rewards: 0n }; } @@ -189,12 +196,9 @@ export class Blockfrost implements Provider { } async getDatum(datumHash: DatumHash): Promise { - const datum = await fetch( - `${this.url}/scripts/datum/${datumHash}/cbor`, - { - headers: { project_id: this.projectId, lucid }, - }, - ) + const datum = await fetch(`${this.url}/scripts/datum/${datumHash}/cbor`, { + headers: { project_id: this.projectId, lucid }, + }) .then((res) => res.json()) .then((res) => res.cbor); if (!datum || datum.error) { @@ -236,43 +240,41 @@ export class Blockfrost implements Provider { } private async blockfrostUtxosToUtxos( - result: BlockfrostUtxoResult, + result: BlockfrostUtxoResult ): Promise { return (await Promise.all( result.map(async (r) => ({ txHash: r.tx_hash, outputIndex: r.output_index, assets: Object.fromEntries( - r.amount.map(({ unit, quantity }) => [unit, BigInt(quantity)]), + r.amount.map(({ unit, quantity }) => [unit, BigInt(quantity)]) ), address: r.address, datumHash: (!r.inline_datum && r.data_hash) || undefined, datum: r.inline_datum || undefined, scriptRef: r.reference_script_hash - ? (await (async () => { - const { - type, - } = await fetch( - `${this.url}/scripts/${r.reference_script_hash}`, - { - headers: { project_id: this.projectId, lucid }, - }, - ).then((res) => res.json()); - // TODO: support native scripts - if (type === "Native" || type === "native") { - throw new Error("Native script ref not implemented!"); - } - const { cbor: script } = await fetch( - `${this.url}/scripts/${r.reference_script_hash}/cbor`, - { headers: { project_id: this.projectId, lucid } }, - ).then((res) => res.json()); - return { - type: type === "plutusV1" ? "PlutusV1" : "PlutusV2", - script: applyDoubleCborEncoding(script), - }; - })()) + ? await (async () => { + const { type } = await fetch( + `${this.url}/scripts/${r.reference_script_hash}`, + { + headers: { project_id: this.projectId, lucid }, + } + ).then((res) => res.json()); + // TODO: support native scripts + if (type === "Native" || type === "native") { + throw new Error("Native script ref not implemented!"); + } + const { cbor: script } = await fetch( + `${this.url}/scripts/${r.reference_script_hash}/cbor`, + { headers: { project_id: this.projectId, lucid } } + ).then((res) => res.json()); + return { + type: type === "plutusV1" ? "PlutusV1" : "PlutusV2", + script: applyDoubleCborEncoding(script), + }; + })() : undefined, - })), + })) )) as UTxO[]; } } @@ -283,38 +285,61 @@ export class Blockfrost implements Provider { */ export function datumJsonToCbor(json: DatumJson): Datum { const convert = (json: DatumJson): C.PlutusData => { - if (!isNaN(json.int!)) { - return C.PlutusData.new_integer(C.BigInt.from_str(json.int!.toString())); - } else if (json.bytes || !isNaN(Number(json.bytes))) { - return C.PlutusData.new_bytes(fromHex(json.bytes!)); - } else if (json.map) { - const m = C.PlutusMap.new(); - json.map.forEach(({ k, v }: { k: unknown; v: unknown }) => { - m.insert(convert(k as DatumJson), convert(v as DatumJson)); - }); - return C.PlutusData.new_map(m); - } else if (json.list) { - const l = C.PlutusList.new(); - json.list.forEach((v: DatumJson) => { - l.add(convert(v)); - }); - return C.PlutusData.new_list(l); - } else if (!isNaN(json.constructor! as unknown as number)) { - const l = C.PlutusList.new(); - json.fields!.forEach((v: DatumJson) => { - l.add(convert(v)); - }); - return C.PlutusData.new_constr_plutus_data( - C.ConstrPlutusData.new( - C.BigNum.from_str(json.constructor!.toString()), - l, - ), - ); + const bucket: FreeableBucket = []; + try { + if (!isNaN(json.int!)) { + const int = C.BigInt.from_str(json.int!.toString()); + bucket.push(int); + return C.PlutusData.new_integer(int); + } else if (json.bytes || !isNaN(Number(json.bytes))) { + return C.PlutusData.new_bytes(fromHex(json.bytes!)); + } else if (json.map) { + const m = C.PlutusMap.new(); + bucket.push(m); + json.map.forEach(({ k, v }: { k: unknown; v: unknown }) => { + const key = convert(k as DatumJson); + bucket.push(key); + const value = convert(v as DatumJson); + bucket.push(value); + + m.insert(key, value); + }); + return C.PlutusData.new_map(m); + } else if (json.list) { + const l = C.PlutusList.new(); + bucket.push(l); + json.list.forEach((v: DatumJson) => { + const value = convert(v); + bucket.push(value); + l.add(value); + }); + return C.PlutusData.new_list(l); + } else if (!isNaN(json.constructor! as unknown as number)) { + const l = C.PlutusList.new(); + bucket.push(l); + json.fields!.forEach((v: DatumJson) => { + const value = convert(v); + bucket.push(value); + l.add(value); + }); + const constructorIndex = C.BigNum.from_str( + json.constructor!.toString() + ); + bucket.push(constructorIndex); + const plutusData = C.ConstrPlutusData.new(constructorIndex, l); + bucket.push(plutusData); + return C.PlutusData.new_constr_plutus_data(plutusData); + } + throw new Error("Unsupported type"); + } finally { + Freeables.free(...bucket); } - throw new Error("Unsupported type"); }; - return toHex(convert(json).to_bytes()); + const convertedJson = convert(json); + const cbor = convertedJson.to_bytes(); + convertedJson.free(); + return toHex(cbor); } type DatumJson = { diff --git a/src/provider/emulator.ts b/src/provider/emulator.ts index a6b5464b..efd311b1 100644 --- a/src/provider/emulator.ts +++ b/src/provider/emulator.ts @@ -20,6 +20,7 @@ import { UnixTime, UTxO, } from "../types/types.ts"; +import { FreeableBucket } from "../utils/freeable.ts"; import { PROTOCOL_PARAMETERS_DEFAULT } from "../utils/mod.ts"; import { coreToUtxo, @@ -54,7 +55,7 @@ export class Emulator implements Provider { assets: Assets; outputData?: OutputData; }[], - protocolParameters: ProtocolParameters = PROTOCOL_PARAMETERS_DEFAULT, + protocolParameters: ProtocolParameters = PROTOCOL_PARAMETERS_DEFAULT ) { const GENESIS_HASH = "00".repeat(32); this.blockHeight = 0; @@ -63,15 +64,12 @@ export class Emulator implements Provider { this.ledger = {}; accounts.forEach(({ address, assets, outputData }, index) => { if ( - [ - outputData?.hash, - outputData?.asHash, - outputData?.inline, - ].filter((b) => b) - .length > 1 + [outputData?.hash, outputData?.asHash, outputData?.inline].filter( + (b) => b + ).length > 1 ) { throw new Error( - "Not allowed to set hash, asHash and inline at the same time.", + "Not allowed to set hash, asHash and inline at the same time." ); } @@ -83,8 +81,8 @@ export class Emulator implements Provider { assets, datumHash: outputData?.asHash ? C.hash_plutus_data( - C.PlutusData.from_bytes(fromHex(outputData.asHash)), - ).to_hex() + C.PlutusData.from_bytes(fromHex(outputData.asHash)) + ).to_hex() : outputData?.hash, datum: outputData?.inline, scriptRef: outputData?.scriptRef, @@ -139,16 +137,12 @@ export class Emulator implements Provider { if (typeof addressOrCredential === "string") { return addressOrCredential === utxo.address ? utxo : []; } else { - const { paymentCredential } = getAddressDetails( - utxo.address, - ); + const { paymentCredential } = getAddressDetails(utxo.address); return paymentCredential?.hash === addressOrCredential.hash ? utxo : []; } }); - return Promise.resolve( - utxos, - ); + return Promise.resolve(utxos); } getProtocolParameters(): Promise { @@ -161,7 +155,7 @@ export class Emulator implements Provider { getUtxosWithUnit( addressOrCredential: Address | Credential, - unit: Unit, + unit: Unit ): Promise { const utxos: UTxO[] = Object.values(this.ledger).flatMap(({ utxo }) => { if (typeof addressOrCredential === "string") { @@ -169,26 +163,22 @@ export class Emulator implements Provider { ? utxo : []; } else { - const { paymentCredential } = getAddressDetails( - utxo.address, - ); + const { paymentCredential } = getAddressDetails(utxo.address); return paymentCredential?.hash === addressOrCredential.hash && - utxo.assets[unit] > 0n + utxo.assets[unit] > 0n ? utxo : []; } }); - return Promise.resolve( - utxos, - ); + return Promise.resolve(utxos); } getUtxosByOutRef(outRefs: OutRef[]): Promise { return Promise.resolve( - outRefs.flatMap((outRef) => - this.ledger[outRef.txHash + outRef.outputIndex]?.utxo || [] - ), + outRefs.flatMap( + (outRef) => this.ledger[outRef.txHash + outRef.outputIndex]?.utxo || [] + ) ); } @@ -224,17 +214,16 @@ export class Emulator implements Provider { * Stake keys need to be registered and delegated like on a real chain in order to receive rewards. */ distributeRewards(rewards: Lovelace) { - for ( - const [rewardAddress, { registeredStake, delegation }] of Object.entries( - this.chain, - ) - ) { + for (const [ + rewardAddress, + { registeredStake, delegation }, + ] of Object.entries(this.chain)) { if (registeredStake && delegation.poolId) { this.chain[rewardAddress] = { registeredStake, delegation: { poolId: delegation.poolId, - rewards: delegation.rewards += rewards, + rewards: (delegation.rewards += rewards), }, }; } @@ -260,31 +249,42 @@ export class Emulator implements Provider { - Validity interval */ + const bucket: FreeableBucket = []; const desTx = C.Transaction.from_bytes(fromHex(tx)); + bucket.push(desTx); const body = desTx.body(); + bucket.push(body); const witnesses = desTx.witness_set(); + bucket.push(witnesses); const datums = witnesses.plutus_data(); + bucket.push(datums); - const txHash = C.hash_transaction(body).to_hex(); + const transactionHash = C.hash_transaction(body); + bucket.push(transactionHash); + const txHash = transactionHash.to_hex(); // Validity interval // Lower bound is inclusive? // Upper bound is inclusive? - const lowerBound = body.validity_start_interval() - ? parseInt(body.validity_start_interval()!.to_str()) + const validityStartInterval = body.validity_start_interval(); + bucket.push(validityStartInterval); + const lowerBound = validityStartInterval + ? parseInt(validityStartInterval.to_str()) : null; - const upperBound = body.ttl() ? parseInt(body.ttl()!.to_str()) : null; + const ttl = body.ttl(); + bucket.push(ttl); + const upperBound = ttl ? parseInt(ttl.to_str()) : null; if (Number.isInteger(lowerBound) && this.slot < lowerBound!) { throw new Error( - `Lower bound (${lowerBound}) not in slot range (${this.slot}).`, + `Lower bound (${lowerBound}) not in slot range (${this.slot}).` ); } if (Number.isInteger(upperBound) && this.slot > upperBound!) { throw new Error( - `Upper bound (${upperBound}) not in slot range (${this.slot}).`, + `Upper bound (${upperBound}) not in slot range (${this.slot}).` ); } @@ -293,7 +293,10 @@ export class Emulator implements Provider { const table: Record = {}; for (let i = 0; i < (datums?.len() || 0); i++) { const datum = datums!.get(i); - const datumHash = C.hash_plutus_data(datum).to_hex(); + bucket.push(datum); + const plutusDataHash = C.hash_plutus_data(datum); + bucket.push(plutusDataHash); + const datumHash = plutusDataHash.to_hex(); table[datumHash] = toHex(datum.to_bytes()); } return table; @@ -304,15 +307,21 @@ export class Emulator implements Provider { // Witness keys const keyHashes = (() => { const keyHashes = []; - for (let i = 0; i < (witnesses.vkeys()?.len() || 0); i++) { - const witness = witnesses.vkeys()!.get(i); - const publicKey = witness.vkey().public_key(); - const keyHash = publicKey.hash().to_hex(); + const vkeys = witnesses.vkeys(); + bucket.push(vkeys); + for (let i = 0; i < (vkeys?.len() || 0); i++) { + const witness = vkeys!.get(i); + bucket.push(witness); + const vkey = witness.vkey(); + bucket.push(vkey); + const publicKey = vkey.public_key(); + bucket.push(publicKey); + const hash = publicKey.hash(); + bucket.push(hash); + const keyHash = hash.to_hex(); if (!publicKey.verify(fromHex(txHash), witness.signature())) { - throw new Error( - `Invalid vkey witness. Key hash: ${keyHash}`, - ); + throw new Error(`Invalid vkey witness. Key hash: ${keyHash}`); } keyHashes.push(keyHash); } @@ -321,35 +330,43 @@ export class Emulator implements Provider { // We only need this to verify native scripts. The check happens in the CML. const edKeyHashes = C.Ed25519KeyHashes.new(); - keyHashes.forEach((keyHash) => - edKeyHashes.add(C.Ed25519KeyHash.from_hex(keyHash)) - ); + bucket.push(edKeyHashes); + keyHashes.forEach((keyHash) => { + const ed25519KeyHash = C.Ed25519KeyHash.from_hex(keyHash); + bucket.push(ed25519KeyHash); + edKeyHashes.add(ed25519KeyHash); + }); const nativeHashes = (() => { const scriptHashes = []; - - for (let i = 0; i < (witnesses.native_scripts()?.len() || 0); i++) { - const witness = witnesses.native_scripts()!.get(i); - const scriptHash = witness.hash(C.ScriptHashNamespace.NativeScript) - .to_hex(); - - if ( - !witness.verify( - Number.isInteger(lowerBound) - ? C.BigNum.from_str(lowerBound!.toString()) - : undefined, - Number.isInteger(upperBound) - ? C.BigNum.from_str(upperBound!.toString()) - : undefined, - edKeyHashes, - ) - ) { + const nativeScripts = witnesses.native_scripts(); + bucket.push(nativeScripts); + for (let i = 0; i < (nativeScripts?.len() || 0); i++) { + const witness = nativeScripts!.get(i); + bucket.push(witness); + const hash = witness.hash(C.ScriptHashNamespace.NativeScript); + bucket.push(hash); + const scriptHash = hash.to_hex(); + + const lBound = Number.isInteger(lowerBound) + ? C.BigNum.from_str(lowerBound!.toString()) + : undefined; + bucket.push(lBound); + const uBound = Number.isInteger(upperBound) + ? C.BigNum.from_str(upperBound!.toString()) + : undefined; + bucket.push(uBound); + if (!witness.verify(lBound, uBound, edKeyHashes)) { throw new Error( - `Invalid native script witness. Script hash: ${scriptHash}`, + `Invalid native script witness. Script hash: ${scriptHash}` ); } - for (let i = 0; i < witness.get_required_signers().len(); i++) { - const keyHash = witness.get_required_signers().get(i).to_hex(); + const requiredSigners = witness.get_required_signers(); + bucket.push(requiredSigners); + for (let i = 0; i < requiredSigners.len(); i++) { + const hash = requiredSigners.get(i); + bucket.push(hash); + const keyHash = hash.to_hex(); consumedHashes.add(keyHash); } scriptHashes.push(scriptHash); @@ -362,17 +379,26 @@ export class Emulator implements Provider { const plutusHashes = (() => { const scriptHashes = []; - for (let i = 0; i < (witnesses.plutus_scripts()?.len() || 0); i++) { - const script = witnesses.plutus_scripts()!.get(i); - const scriptHash = script.hash(C.ScriptHashNamespace.PlutusV1) - .to_hex(); + const plutusScripts = witnesses.plutus_scripts(); + bucket.push(plutusScripts); + for (let i = 0; i < (plutusScripts?.len() || 0); i++) { + const script = plutusScripts!.get(i); + bucket.push(script); + const hash = script.hash(C.ScriptHashNamespace.PlutusV1); + bucket.push(hash); + const scriptHash = hash.to_hex(); scriptHashes.push(scriptHash); } - for (let i = 0; i < (witnesses.plutus_v2_scripts()?.len() || 0); i++) { - const script = witnesses.plutus_v2_scripts()!.get(i); - const scriptHash = script.hash(C.ScriptHashNamespace.PlutusV2) - .to_hex(); + + const plutusV2Scripts = witnesses.plutus_v2_scripts(); + bucket.push(plutusV2Scripts); + for (let i = 0; i < (plutusV2Scripts?.len() || 0); i++) { + const script = plutusV2Scripts!.get(i); + bucket.push(script); + const hash = script.hash(C.ScriptHashNamespace.PlutusV2); + bucket.push(hash); + const scriptHash = hash.to_hex(); scriptHashes.push(scriptHash); } @@ -380,6 +406,7 @@ export class Emulator implements Provider { })(); const inputs = body.inputs(); + bucket.push(inputs); inputs.sort(); type ResolvedInput = { @@ -392,8 +419,13 @@ export class Emulator implements Provider { // Check existence of inputs and look for script refs. for (let i = 0; i < inputs.len(); i++) { const input = inputs.get(i); + bucket.push(input); + const transactionId = input.transaction_id(); + bucket.push(transactionId); + const transactionIndex = input.index(); + bucket.push(transactionIndex); - const outRef = input.transaction_id().to_hex() + input.index().to_str(); + const outRef = transactionId.to_hex() + transactionIndex.to_str(); const entryLedger = this.ledger[outRef]; @@ -403,12 +435,10 @@ export class Emulator implements Provider { if (!entry || entry.spent) { throw new Error( - `Could not spend UTxO: ${ - JSON.stringify({ - txHash: entry?.utxo.txHash, - outputIndex: entry?.utxo.outputIndex, - }) - }\nIt does not exist or was already spent.`, + `Could not spend UTxO: ${JSON.stringify({ + txHash: entry?.utxo.txHash, + outputIndex: entry?.utxo.outputIndex, + })}\nIt does not exist or was already spent.` ); } @@ -417,23 +447,27 @@ export class Emulator implements Provider { switch (scriptRef.type) { case "Native": { const script = C.NativeScript.from_bytes(fromHex(scriptRef.script)); - nativeHashesOptional[ - script.hash(C.ScriptHashNamespace.NativeScript).to_hex() - ] = script; + bucket.push(script); + const hash = script.hash(C.ScriptHashNamespace.NativeScript); + bucket.push(hash); + + nativeHashesOptional[hash.to_hex()] = script; break; } case "PlutusV1": { const script = C.PlutusScript.from_bytes(fromHex(scriptRef.script)); - plutusHashesOptional.push( - script.hash(C.ScriptHashNamespace.PlutusV1).to_hex(), - ); + bucket.push(script); + const hash = script.hash(C.ScriptHashNamespace.PlutusV1); + bucket.push(hash); + plutusHashesOptional.push(hash.to_hex()); break; } case "PlutusV2": { const script = C.PlutusScript.from_bytes(fromHex(scriptRef.script)); - plutusHashesOptional.push( - script.hash(C.ScriptHashNamespace.PlutusV2).to_hex(), - ); + bucket.push(script); + const hash = script.hash(C.ScriptHashNamespace.PlutusV2); + bucket.push(hash); + plutusHashesOptional.push(hash.to_hex()); break; } } @@ -445,21 +479,27 @@ export class Emulator implements Provider { } // Check existence of reference inputs and look for script refs. - for (let i = 0; i < (body.reference_inputs()?.len() || 0); i++) { - const input = body.reference_inputs()!.get(i); + const referenceInputs = body.reference_inputs(); + bucket.push(referenceInputs); + for (let i = 0; i < (referenceInputs?.len() || 0); i++) { + const input = referenceInputs!.get(i); + bucket.push(input); + + const inputId = input.transaction_id(); + bucket.push(inputId); + const inputIndex = input.index(); + bucket.push(inputIndex); - const outRef = input.transaction_id().to_hex() + input.index().to_str(); + const outRef = inputId.to_hex() + inputIndex.to_str(); const entry = this.ledger[outRef] || this.mempool[outRef]; if (!entry || entry.spent) { throw new Error( - `Could not read UTxO: ${ - JSON.stringify({ - txHash: entry?.utxo.txHash, - outputIndex: entry?.utxo.outputIndex, - }) - }\nIt does not exist or was already spent.`, + `Could not read UTxO: ${JSON.stringify({ + txHash: entry?.utxo.txHash, + outputIndex: entry?.utxo.outputIndex, + })}\nIt does not exist or was already spent.` ); } @@ -468,23 +508,27 @@ export class Emulator implements Provider { switch (scriptRef.type) { case "Native": { const script = C.NativeScript.from_bytes(fromHex(scriptRef.script)); - nativeHashesOptional[ - script.hash(C.ScriptHashNamespace.NativeScript).to_hex() - ] = script; + bucket.push(script); + const hash = script.hash(C.ScriptHashNamespace.NativeScript); + bucket.push(hash); + + nativeHashesOptional[hash.to_hex()] = script; break; } case "PlutusV1": { const script = C.PlutusScript.from_bytes(fromHex(scriptRef.script)); - plutusHashesOptional.push( - script.hash(C.ScriptHashNamespace.PlutusV1).to_hex(), - ); + bucket.push(script); + const hash = script.hash(C.ScriptHashNamespace.PlutusV1); + bucket.push(hash); + plutusHashesOptional.push(hash.to_hex()); break; } case "PlutusV2": { const script = C.PlutusScript.from_bytes(fromHex(scriptRef.script)); - plutusHashesOptional.push( - script.hash(C.ScriptHashNamespace.PlutusV2).to_hex(), - ); + bucket.push(script); + const hash = script.hash(C.ScriptHashNamespace.PlutusV2); + bucket.push(hash); + plutusHashesOptional.push(hash.to_hex()); break; } } @@ -503,11 +547,19 @@ export class Emulator implements Provider { 3: "Reward", }; const collected = []; - for (let i = 0; i < (witnesses.redeemers()?.len() || 0); i++) { - const redeemer = witnesses.redeemers()!.get(i); + const redeemers = witnesses.redeemers(); + bucket.push(redeemers); + for (let i = 0; i < (redeemers?.len() || 0); i++) { + const redeemer = redeemers!.get(i); + bucket.push(redeemer); + const tag = redeemer.tag(); + bucket.push(tag); + + const redeemerIndex = redeemer.index(); + bucket.push(redeemerIndex); collected.push({ - tag: tagMap[redeemer.tag().kind()], - index: parseInt(redeemer.index().to_str()), + tag: tagMap[tag.kind()], + index: parseInt(redeemerIndex.to_str()), }); } return collected; @@ -516,13 +568,13 @@ export class Emulator implements Provider { function checkAndConsumeHash( credential: Credential, tag: Tag | null, - index: number | null, + index: number | null ) { switch (credential.type) { case "Key": { if (!keyHashes.includes(credential.hash)) { throw new Error( - `Missing vkey witness. Key hash: ${credential.hash}`, + `Missing vkey witness. Key hash: ${credential.hash}` ); } consumedHashes.add(credential.hash); @@ -533,19 +585,24 @@ export class Emulator implements Provider { consumedHashes.add(credential.hash); break; } else if (nativeHashesOptional[credential.hash]) { + const lBound = Number.isInteger(lowerBound) + ? C.BigNum.from_str(lowerBound!.toString()) + : undefined; + bucket.push(lBound); + const uBound = Number.isInteger(upperBound) + ? C.BigNum.from_str(upperBound!.toString()) + : undefined; + bucket.push(uBound); + if ( !nativeHashesOptional[credential.hash].verify( - Number.isInteger(lowerBound) - ? C.BigNum.from_str(lowerBound!.toString()) - : undefined, - Number.isInteger(upperBound) - ? C.BigNum.from_str(upperBound!.toString()) - : undefined, - edKeyHashes, + lBound, + uBound, + edKeyHashes ) ) { throw new Error( - `Invalid native script witness. Script hash: ${credential.hash}`, + `Invalid native script witness. Script hash: ${credential.hash}` ); } break; @@ -554,8 +611,8 @@ export class Emulator implements Provider { plutusHashesOptional.includes(credential.hash) ) { if ( - redeemers.find((redeemer) => - redeemer.tag === tag && redeemer.index === index + redeemers.find( + (redeemer) => redeemer.tag === tag && redeemer.index === index ) ) { consumedHashes.add(credential.hash); @@ -563,29 +620,34 @@ export class Emulator implements Provider { } } throw new Error( - `Missing script witness. Script hash: ${credential.hash}`, + `Missing script witness. Script hash: ${credential.hash}` ); } } } // Check collateral inputs + const collateral = body.collateral(); + bucket.push(collateral); + for (let i = 0; i < (collateral?.len() || 0); i++) { + const input = collateral!.get(i); + bucket.push(input); - for (let i = 0; i < (body.collateral()?.len() || 0); i++) { - const input = body.collateral()!.get(i); + const transactionId = input.transaction_id(); + bucket.push(transactionId); + const transactionIndex = input.index(); + bucket.push(transactionIndex); - const outRef = input.transaction_id().to_hex() + input.index().to_str(); + const outRef = transactionId.to_hex() + transactionIndex.to_str(); const entry = this.ledger[outRef] || this.mempool[outRef]; if (!entry || entry.spent) { throw new Error( - `Could not read UTxO: ${ - JSON.stringify({ - txHash: entry?.utxo.txHash, - outputIndex: entry?.utxo.outputIndex, - }) - }\nIt does not exist or was already spent.`, + `Could not read UTxO: ${JSON.stringify({ + txHash: entry?.utxo.txHash, + outputIndex: entry?.utxo.outputIndex, + })}\nIt does not exist or was already spent.` ); } @@ -597,17 +659,24 @@ export class Emulator implements Provider { } // Check required signers - - for (let i = 0; i < (body.required_signers()?.len() || 0); i++) { - const signer = body.required_signers()!.get(i); + const requiredSigners = body.required_signers(); + bucket.push(requiredSigners); + for (let i = 0; i < (requiredSigners?.len() || 0); i++) { + const signer = requiredSigners!.get(i); + bucket.push(signer); checkAndConsumeHash({ type: "Key", hash: signer.to_hex() }, null, null); } // Check mint witnesses - - for (let index = 0; index < (body.mint()?.keys().len() || 0); index++) { - const policyId = body.mint()!.keys().get(index).to_hex(); - checkAndConsumeHash({ type: "Script", hash: policyId }, "Mint", index); + const mint = body.mint(); + bucket.push(mint); + const mintKeys = mint?.keys(); + bucket.push(mintKeys); + for (let index = 0; index < (mintKeys?.len() || 0); index++) { + const policy = mintKeys!.get(index); + bucket.push(policy); + const hash = policy.to_hex(); + checkAndConsumeHash({ type: "Script", hash }, "Mint", index); } // Check withdrawal witnesses @@ -617,23 +686,22 @@ export class Emulator implements Provider { withdrawal: Lovelace; }[] = []; - for ( - let index = 0; - index < (body.withdrawals()?.keys().len() || 0); - index++ - ) { - const rawAddress = body.withdrawals()!.keys().get(index); - const withdrawal: Lovelace = BigInt( - body.withdrawals()!.get(rawAddress)!.to_str(), - ); - const rewardAddress = rawAddress.to_address().to_bech32(undefined); - const { stakeCredential } = getAddressDetails( - rewardAddress, - ); + const withdrawals = body.withdrawals(); + const withdrawalKeys = withdrawals?.keys(); + for (let index = 0; index < (withdrawalKeys?.len() || 0); index++) { + const rawAddress = withdrawalKeys!.get(index); + bucket.push(rawAddress); + const cWithdrawal = withdrawals!.get(rawAddress); + bucket.push(cWithdrawal); + const withdrawal: Lovelace = BigInt(cWithdrawal!.to_str()); + const cAddress = rawAddress.to_address(); + bucket.push(cAddress); + const rewardAddress = cAddress.to_bech32(undefined); + const { stakeCredential } = getAddressDetails(rewardAddress); checkAndConsumeHash(stakeCredential!, "Reward", index); if (this.chain[rewardAddress]?.delegation.rewards !== withdrawal) { throw new Error( - "Withdrawal amount doesn't match actual reward balance.", + "Withdrawal amount doesn't match actual reward balance." ); } withdrawalRequests.push({ rewardAddress, withdrawal }); @@ -647,7 +715,9 @@ export class Emulator implements Provider { poolId?: PoolId; }[] = []; - for (let index = 0; index < (body.certs()?.len() || 0); index++) { + const certs = body.certs(); + bucket.push(certs); + for (let index = 0; index < (certs?.len() || 0); index++) { /* Checking only: 1. Stake registration @@ -656,17 +726,27 @@ export class Emulator implements Provider { All other certificate types are not checked and considered valid. */ - const cert = body.certs()!.get(index); + const cert = certs!.get(index); + bucket.push(cert); switch (cert.kind()) { case 0: { const registration = cert.as_stake_registration()!; - const rewardAddress = C.RewardAddress.new( - C.NetworkInfo.testnet().network_id(), - registration.stake_credential(), - ).to_address().to_bech32(undefined); + bucket.push(registration); + const networkInfo = C.NetworkInfo.testnet(); + bucket.push(networkInfo); + const stakeCredential = registration.stake_credential(); + bucket.push(stakeCredential); + const cRewardAddress = C.RewardAddress.new( + networkInfo.network_id(), + stakeCredential + ); + bucket.push(cRewardAddress); + const address = cRewardAddress.to_address(); + bucket.push(address); + const rewardAddress = address.to_bech32(undefined); if (this.chain[rewardAddress]?.registeredStake) { throw new Error( - `Stake key is already registered. Reward address: ${rewardAddress}`, + `Stake key is already registered. Reward address: ${rewardAddress}` ); } certRequests.push({ type: "Registration", rewardAddress }); @@ -674,17 +754,26 @@ export class Emulator implements Provider { } case 1: { const deregistration = cert.as_stake_deregistration()!; - const rewardAddress = C.RewardAddress.new( - C.NetworkInfo.testnet().network_id(), - deregistration.stake_credential(), - ).to_address().to_bech32(undefined); + bucket.push(deregistration); + const networkInfo = C.NetworkInfo.testnet(); + bucket.push(networkInfo); + const cStakeCredential = deregistration.stake_credential(); + bucket.push(cStakeCredential); + const cRewardAddress = C.RewardAddress.new( + networkInfo.network_id(), + cStakeCredential + ); + bucket.push(cRewardAddress); + const address = cRewardAddress.to_address(); + bucket.push(address); + const rewardAddress = address.to_bech32(undefined); const { stakeCredential } = getAddressDetails(rewardAddress); checkAndConsumeHash(stakeCredential!, "Cert", index); if (!this.chain[rewardAddress]?.registeredStake) { throw new Error( - `Stake key is already deregistered. Reward address: ${rewardAddress}`, + `Stake key is already deregistered. Reward address: ${rewardAddress}` ); } certRequests.push({ type: "Deregistration", rewardAddress }); @@ -692,24 +781,36 @@ export class Emulator implements Provider { } case 2: { const delegation = cert.as_stake_delegation()!; - const rewardAddress = C.RewardAddress.new( - C.NetworkInfo.testnet().network_id(), - delegation.stake_credential(), - ).to_address().to_bech32(undefined); - const poolId = delegation.pool_keyhash().to_bech32("pool"); + bucket.push(delegation); + const networkInfo = C.NetworkInfo.testnet(); + bucket.push(networkInfo); + const cStakeCredential = delegation.stake_credential(); + bucket.push(cStakeCredential); + const cRewardAddress = C.RewardAddress.new( + networkInfo.network_id(), + cStakeCredential + ); + bucket.push(cRewardAddress); + const address = cRewardAddress.to_address(); + bucket.push(address); + const rewardAddress = address.to_bech32(undefined); + const poolKeyHash = delegation.pool_keyhash(); + bucket.push(poolKeyHash); + const poolId = poolKeyHash.to_bech32("pool"); const { stakeCredential } = getAddressDetails(rewardAddress); checkAndConsumeHash(stakeCredential!, "Cert", index); if ( !this.chain[rewardAddress]?.registeredStake && - !certRequests.find((request) => - request.type === "Registration" && - request.rewardAddress === rewardAddress + !certRequests.find( + (request) => + request.type === "Registration" && + request.rewardAddress === rewardAddress ) ) { throw new Error( - `Stake key is not registered. Reward address: ${rewardAddress}`, + `Stake key is not registered. Reward address: ${rewardAddress}` ); } certRequests.push({ type: "Delegation", rewardAddress, poolId }); @@ -727,60 +828,65 @@ export class Emulator implements Provider { // Create outputs and consume datum hashes const outputs = (() => { + const outputs = body.outputs(); + bucket.push(outputs); const collected = []; - for (let i = 0; i < body.outputs().len(); i++) { - const output = body.outputs().get(i); + for (let i = 0; i < outputs.len(); i++) { + const output = outputs.get(i); + bucket.push(output); + const transactionHash = C.TransactionHash.from_hex(txHash); + bucket.push(transactionHash); + const index = C.BigNum.from_str(i.toString()); + bucket.push(index); + const transactionInput = C.TransactionInput.new(transactionHash, index); + bucket.push(transactionInput); const unspentOutput = C.TransactionUnspentOutput.new( - C.TransactionInput.new( - C.TransactionHash.from_hex(txHash), - C.BigNum.from_str(i.toString()), - ), - output, + transactionInput, + output ); + bucket.push(unspentOutput); const utxo = coreToUtxo(unspentOutput); if (utxo.datumHash) consumedHashes.add(utxo.datumHash); - collected.push( - { - utxo, - spent: false, - }, - ); + collected.push({ + utxo, + spent: false, + }); } return collected; })(); // Check consumed witnesses - const [extraKeyHash] = keyHashes.filter((keyHash) => - !consumedHashes.has(keyHash) + const [extraKeyHash] = keyHashes.filter( + (keyHash) => !consumedHashes.has(keyHash) ); if (extraKeyHash) { throw new Error(`Extraneous vkey witness. Key hash: ${extraKeyHash}`); } - const [extraNativeHash] = nativeHashes.filter((scriptHash) => - !consumedHashes.has(scriptHash) + const [extraNativeHash] = nativeHashes.filter( + (scriptHash) => !consumedHashes.has(scriptHash) ); if (extraNativeHash) { throw new Error( - `Extraneous native script. Script hash: ${extraNativeHash}`, + `Extraneous native script. Script hash: ${extraNativeHash}` ); } - const [extraPlutusHash] = plutusHashes.filter((scriptHash) => - !consumedHashes.has(scriptHash) + const [extraPlutusHash] = plutusHashes.filter( + (scriptHash) => !consumedHashes.has(scriptHash) ); if (extraPlutusHash) { throw new Error( - `Extraneous plutus script. Script hash: ${extraPlutusHash}`, + `Extraneous plutus script. Script hash: ${extraPlutusHash}` ); } - const [extraDatumHash] = Object.keys(datumTable).filter((datumHash) => - !consumedHashes.has(datumHash) + const [extraDatumHash] = Object.keys(datumTable).filter( + (datumHash) => !consumedHashes.has(datumHash) ); if (extraDatumHash) { throw new Error(`Extraneous plutus data. Datum hash: ${extraDatumHash}`); @@ -888,21 +994,15 @@ export class Emulator implements Provider { "color:white", "color:yellow", "color:white", - "color:yellow", + "color:yellow" ); console.log("\n"); for (const [address, assets] of Object.entries(balances)) { - console.log( - `Address: %c${address}`, - "color:blue", - "\n", - ); + console.log(`Address: %c${address}`, "color:blue", "\n"); for (const [unit, quantity] of Object.entries(assets)) { const barLength = Math.max( - Math.floor( - 60 * (Number(quantity) / Number(totalBalances[unit])), - ), - 1, + Math.floor(60 * (Number(quantity) / Number(totalBalances[unit]))), + 1 ); console.log( `%c${"\u2586".repeat(barLength) + " ".repeat(60 - barLength)}`, @@ -910,12 +1010,10 @@ export class Emulator implements Provider { "", `${unit}:`, quantity, - "", + "" ); } - console.log( - `\n${"\u2581".repeat(60)}\n`, - ); + console.log(`\n${"\u2581".repeat(60)}\n`); } } } diff --git a/src/provider/kupmios.ts b/src/provider/kupmios.ts index 06214db7..b4dd4ecd 100644 --- a/src/provider/kupmios.ts +++ b/src/provider/kupmios.ts @@ -36,22 +36,23 @@ export class Kupmios implements Provider { }); return new Promise((res, rej) => { - client.addEventListener("message", (msg: MessageEvent) => { - try { - const { result } = JSON.parse(msg.data); + client.addEventListener( + "message", + (msg: MessageEvent) => { + try { + const { result } = JSON.parse(msg.data); - // deno-lint-ignore no-explicit-any - const costModels: any = {}; - Object.keys(result.costModels).forEach((v) => { - const version = v.split(":")[1].toUpperCase(); - const plutusVersion = "Plutus" + version; - costModels[plutusVersion] = result.costModels[v]; - }); - const [memNum, memDenom] = result.prices.memory.split("/"); - const [stepsNum, stepsDenom] = result.prices.steps.split("/"); + // deno-lint-ignore no-explicit-any + const costModels: any = {}; + Object.keys(result.costModels).forEach((v) => { + const version = v.split(":")[1].toUpperCase(); + const plutusVersion = "Plutus" + version; + costModels[plutusVersion] = result.costModels[v]; + }); + const [memNum, memDenom] = result.prices.memory.split("/"); + const [stepsNum, stepsDenom] = result.prices.steps.split("/"); - res( - { + res({ minFeeA: parseInt(result.minFeeCoefficient), minFeeB: parseInt(result.minFeeConstant), maxTxSize: parseInt(result.maxTxSize), @@ -62,19 +63,20 @@ export class Kupmios implements Provider { priceStep: parseInt(stepsNum) / parseInt(stepsDenom), maxTxExMem: BigInt(result.maxExecutionUnitsPerTransaction.memory), maxTxExSteps: BigInt( - result.maxExecutionUnitsPerTransaction.steps, + result.maxExecutionUnitsPerTransaction.steps ), coinsPerUtxoByte: BigInt(result.coinsPerUtxoByte), collateralPercentage: parseInt(result.collateralPercentage), maxCollateralInputs: parseInt(result.maxCollateralInputs), costModels, - }, - ); - client.close(); - } catch (e) { - rej(e); - } - }, { once: true }); + }); + client.close(); + } catch (e) { + rej(e); + } + }, + { once: true } + ); }); } @@ -86,15 +88,14 @@ export class Kupmios implements Provider { const result = await fetch( `${this.kupoUrl}/matches/${queryPredicate}${ isAddress ? "" : "/*" - }?unspent`, - ) - .then((res) => res.json()); + }?unspent` + ).then((res) => res.json()); return this.kupmiosUtxosToUtxos(result); } async getUtxosWithUnit( addressOrCredential: Address | Credential, - unit: Unit, + unit: Unit ): Promise { const isAddress = typeof addressOrCredential === "string"; const queryPredicate = isAddress @@ -106,9 +107,8 @@ export class Kupmios implements Provider { isAddress ? "" : "/*" }?unspent&policy_id=${policyId}${ assetName ? `&asset_name=${assetName}` : "" - }`, - ) - .then((res) => res.json()); + }` + ).then((res) => res.json()); return this.kupmiosUtxosToUtxos(result); } @@ -117,9 +117,8 @@ export class Kupmios implements Provider { const result = await fetch( `${this.kupoUrl}/matches/${policyId}.${ assetName ? `${assetName}` : "*" - }?unspent`, - ) - .then((res) => res.json()); + }?unspent` + ).then((res) => res.json()); const utxos = await this.kupmiosUtxosToUtxos(result); @@ -133,51 +132,59 @@ export class Kupmios implements Provider { async getUtxosByOutRef(outRefs: Array): Promise { const queryHashes = [...new Set(outRefs.map((outRef) => outRef.txHash))]; - const utxos = await Promise.all(queryHashes.map(async (txHash) => { - const result = await fetch( - `${this.kupoUrl}/matches/*@${txHash}?unspent`, - ).then((res) => res.json()); - return this.kupmiosUtxosToUtxos(result); - })); - - return utxos.reduce((acc, utxos) => acc.concat(utxos), []).filter((utxo) => - outRefs.some((outRef) => - utxo.txHash === outRef.txHash && utxo.outputIndex === outRef.outputIndex - ) + const utxos = await Promise.all( + queryHashes.map(async (txHash) => { + const result = await fetch( + `${this.kupoUrl}/matches/*@${txHash}?unspent` + ).then((res) => res.json()); + return this.kupmiosUtxosToUtxos(result); + }) ); + + return utxos + .reduce((acc, utxos) => acc.concat(utxos), []) + .filter((utxo) => + outRefs.some( + (outRef) => + utxo.txHash === outRef.txHash && + utxo.outputIndex === outRef.outputIndex + ) + ); } async getDelegation(rewardAddress: RewardAddress): Promise { const client = await this.ogmiosWsp("Query", { - query: { "delegationsAndRewards": [rewardAddress] }, + query: { delegationsAndRewards: [rewardAddress] }, }); return new Promise((res, rej) => { - client.addEventListener("message", (msg: MessageEvent) => { - try { - const { result } = JSON.parse(msg.data); - const delegation = (result ? Object.values(result)[0] : {}) as { - delegate: string; - rewards: number; - }; - res( - { + client.addEventListener( + "message", + (msg: MessageEvent) => { + try { + const { result } = JSON.parse(msg.data); + const delegation = (result ? Object.values(result)[0] : {}) as { + delegate: string; + rewards: number; + }; + res({ poolId: delegation?.delegate || null, rewards: BigInt(delegation?.rewards || 0), - }, - ); - client.close(); - } catch (e) { - rej(e); - } - }, { once: true }); + }); + client.close(); + } catch (e) { + rej(e); + } + }, + { once: true } + ); }); } async getDatum(datumHash: DatumHash): Promise { - const result = await fetch( - `${this.kupoUrl}/datums/${datumHash}`, - ).then((res) => res.json()); + const result = await fetch(`${this.kupoUrl}/datums/${datumHash}`).then( + (res) => res.json() + ); if (!result || !result.datum) { throw new Error(`No datum found for datum hash: ${datumHash}`); } @@ -188,7 +195,7 @@ export class Kupmios implements Provider { return new Promise((res) => { const confirmation = setInterval(async () => { const isConfirmed = await fetch( - `${this.kupoUrl}/matches/*@${txHash}?unspent`, + `${this.kupoUrl}/matches/*@${txHash}?unspent` ).then((res) => res.json()); if (isConfirmed && isConfirmed.length > 0) { clearInterval(confirmation); @@ -205,80 +212,94 @@ export class Kupmios implements Provider { }); return new Promise((res, rej) => { - client.addEventListener("message", (msg: MessageEvent) => { - try { - const { result } = JSON.parse(msg.data); + client.addEventListener( + "message", + (msg: MessageEvent) => { + try { + const { result } = JSON.parse(msg.data); - if (result.SubmitSuccess) res(result.SubmitSuccess.txId); - else rej(result.SubmitFail); - client.close(); - } catch (e) { - rej(e); - } - }, { once: true }); + if (result.SubmitSuccess) res(result.SubmitSuccess.txId); + else rej(result.SubmitFail); + client.close(); + } catch (e) { + rej(e); + } + }, + { once: true } + ); }); } private kupmiosUtxosToUtxos(utxos: unknown): Promise { - // deno-lint-ignore no-explicit-any - return Promise.all((utxos as any).map(async (utxo: any) => { - return ({ - txHash: utxo.transaction_id, - outputIndex: parseInt(utxo.output_index), - address: utxo.address, - assets: (() => { - const a: Assets = { lovelace: BigInt(utxo.value.coins) }; - Object.keys(utxo.value.assets).forEach((unit) => { - a[unit.replace(".", "")] = BigInt(utxo.value.assets[unit]); - }); - return a; - })(), - datumHash: utxo?.datum_type === "hash" ? utxo.datum_hash : null, - datum: utxo?.datum_type === "inline" - ? await this.getDatum(utxo.datum_hash) - : null, - scriptRef: utxo.script_hash && - (await (async () => { - const { - script, - language, - } = await fetch( - `${this.kupoUrl}/scripts/${utxo.script_hash}`, - ).then((res) => res.json()); + return Promise.all( + // deno-lint-ignore no-explicit-any + (utxos as any).map(async (utxo: any) => { + return { + txHash: utxo.transaction_id, + outputIndex: parseInt(utxo.output_index), + address: utxo.address, + assets: (() => { + const a: Assets = { lovelace: BigInt(utxo.value.coins) }; + Object.keys(utxo.value.assets).forEach((unit) => { + a[unit.replace(".", "")] = BigInt(utxo.value.assets[unit]); + }); + return a; + })(), + datumHash: utxo?.datum_type === "hash" ? utxo.datum_hash : null, + datum: + utxo?.datum_type === "inline" + ? await this.getDatum(utxo.datum_hash) + : null, + scriptRef: + utxo.script_hash && + (await (async () => { + const { script, language } = await fetch( + `${this.kupoUrl}/scripts/${utxo.script_hash}` + ).then((res) => res.json()); - if (language === "native") { - return { type: "Native", script }; - } else if (language === "plutus:v1") { - return { - type: "PlutusV1", - script: toHex(C.PlutusScript.new(fromHex(script)).to_bytes()), - }; - } else if (language === "plutus:v2") { - return { - type: "PlutusV2", - script: toHex(C.PlutusScript.new(fromHex(script)).to_bytes()), - }; - } - })()), - }) as UTxO; - })); + if (language === "native") { + return { type: "Native", script }; + } else if (language === "plutus:v1") { + const plutusScript = C.PlutusScript.new(fromHex(script)); + const scriptBytes = plutusScript.to_bytes(); + plutusScript.free(); + return { + type: "PlutusV1", + script: toHex(scriptBytes), + }; + } else if (language === "plutus:v2") { + const plutusScript = C.PlutusScript.new(fromHex(script)); + const scriptBytes = plutusScript.to_bytes(); + plutusScript.free(); + + return { + type: "PlutusV2", + script: toHex(scriptBytes), + }; + } + })()), + } as UTxO; + }) + ); } private async ogmiosWsp( methodname: string, - args: unknown, + args: unknown ): Promise { const client = new WebSocket(this.ogmiosUrl); await new Promise((res) => { client.addEventListener("open", () => res(1), { once: true }); }); - client.send(JSON.stringify({ - type: "jsonwsp/request", - version: "1.0", - servicename: "ogmios", - methodname, - args, - })); + client.send( + JSON.stringify({ + type: "jsonwsp/request", + version: "1.0", + servicename: "ogmios", + methodname, + args, + }) + ); return client; } } diff --git a/src/provider/maestro.ts b/src/provider/maestro.ts index 26f37113..8b1f16b2 100644 --- a/src/provider/maestro.ts +++ b/src/provider/maestro.ts @@ -46,22 +46,26 @@ export class Maestro implements Provider { // Decimal numbers in Maestro are given as ratio of two numbers represented by string of format "firstNumber/secondNumber". const decimalFromRationalString = (str: string): number => { const forwardSlashIndex = str.indexOf("/"); - return parseInt(str.slice(0, forwardSlashIndex)) / - parseInt(str.slice(forwardSlashIndex + 1)); + return ( + parseInt(str.slice(0, forwardSlashIndex)) / + parseInt(str.slice(forwardSlashIndex + 1)) + ); }; // To rename keys in an object by the given key-map. // deno-lint-ignore no-explicit-any const renameKeysAndSort = (obj: any, newKeys: any) => { - const entries = Object.keys(obj).sort().map((key) => { - const newKey = newKeys[key] || key; - return { - [newKey]: Object.fromEntries( - Object.entries(obj[key]).sort(([k, _v], [k2, _v2]) => - k.localeCompare(k2) + const entries = Object.keys(obj) + .sort() + .map((key) => { + const newKey = newKeys[key] || key; + return { + [newKey]: Object.fromEntries( + Object.entries(obj[key]).sort(([k, _v], [k2, _v2]) => + k.localeCompare(k2) + ) ), - ), - }; - }); + }; + }); return Object.assign({}, ...entries); }; return { @@ -87,20 +91,24 @@ export class Maestro implements Provider { private async getUtxosInternal( addressOrCredential: Address | Credential, - unit?: Unit, + unit?: Unit ): Promise { const queryPredicate = (() => { if (typeof addressOrCredential === "string") { return "/addresses/" + addressOrCredential; } + const hash = + addressOrCredential.type == "Key" + ? C.Ed25519KeyHash.from_hex(addressOrCredential.hash) + : C.ScriptHash.from_hex(addressOrCredential.hash); let credentialBech32Query = "/addresses/cred/"; - credentialBech32Query += addressOrCredential.type === "Key" - ? C.Ed25519KeyHash.from_hex(addressOrCredential.hash).to_bech32( - "addr_vkh", - ) - : C.ScriptHash.from_hex(addressOrCredential.hash).to_bech32( - "addr_shared_vkh", - ); + credentialBech32Query += + addressOrCredential.type === "Key" + ? hash.to_bech32("addr_vkh") + : hash.to_bech32("addr_shared_vkh"); + + hash.free(); + return credentialBech32Query; })(); const qparams = new URLSearchParams({ @@ -112,7 +120,7 @@ export class Maestro implements Provider { await fetch(qry, { headers: this.commonHeaders() }), `${this.url}${queryPredicate}/utxos`, qparams, - "Location: getUtxosInternal. Error: Could not fetch UTxOs from Maestro", + "Location: getUtxosInternal. Error: Could not fetch UTxOs from Maestro" ); return result.map(this.maestroUtxoToUtxo); } @@ -123,7 +131,7 @@ export class Maestro implements Provider { getUtxosWithUnit( addressOrCredential: Address | Credential, - unit: Unit, + unit: Unit ): Promise { return this.getUtxosInternal(addressOrCredential, unit); } @@ -131,7 +139,7 @@ export class Maestro implements Provider { async getUtxoByUnit(unit: Unit): Promise { const timestampedAddressesResponse = await fetch( `${this.url}/assets/${unit}/addresses?count=2`, - { headers: this.commonHeaders() }, + { headers: this.commonHeaders() } ); const timestampedAddresses = await timestampedAddressesResponse.json(); if (!timestampedAddressesResponse.ok) { @@ -140,7 +148,7 @@ export class Maestro implements Provider { } throw new Error( "Location: getUtxoByUnit. Error: Couldn't perform query. Received status code: " + - timestampedAddressesResponse.status, + timestampedAddressesResponse.status ); } const addressesWithAmount = timestampedAddresses.data; @@ -149,7 +157,7 @@ export class Maestro implements Provider { } if (addressesWithAmount.length > 1) { throw new Error( - "Location: getUtxoByUnit. Error: Unit needs to be an NFT or only held by one address.", + "Location: getUtxoByUnit. Error: Unit needs to be an NFT or only held by one address." ); } @@ -159,7 +167,7 @@ export class Maestro implements Provider { if (utxos.length > 1) { throw new Error( - "Location: getUtxoByUnit. Error: Unit needs to be an NFT or only held by one address.", + "Location: getUtxoByUnit. Error: Unit needs to be an NFT or only held by one address." ); } @@ -169,7 +177,7 @@ export class Maestro implements Provider { async getUtxosByOutRef(outRefs: OutRef[]): Promise { const qry = `${this.url}/transactions/outputs`; const body = JSON.stringify( - outRefs.map(({ txHash, outputIndex }) => `${txHash}#${outputIndex}`), + outRefs.map(({ txHash, outputIndex }) => `${txHash}#${outputIndex}`) ); const utxos = await this.getAllPagesData( async (qry: string) => @@ -183,7 +191,7 @@ export class Maestro implements Provider { }), qry, new URLSearchParams({}), - "Location: getUtxosByOutRef. Error: Could not fetch UTxOs by references from Maestro", + "Location: getUtxosByOutRef. Error: Could not fetch UTxOs by references from Maestro" ); return utxos.map(this.maestroUtxoToUtxo); } @@ -191,7 +199,7 @@ export class Maestro implements Provider { async getDelegation(rewardAddress: RewardAddress): Promise { const timestampedResultResponse = await fetch( `${this.url}/accounts/${rewardAddress}`, - { headers: this.commonHeaders() }, + { headers: this.commonHeaders() } ); if (!timestampedResultResponse.ok) { return { poolId: null, rewards: 0n }; @@ -209,7 +217,7 @@ export class Maestro implements Provider { `${this.url}/datum/${datumHash}`, { headers: this.commonHeaders(), - }, + } ); if (!timestampedResultResponse.ok) { if (timestampedResultResponse.status === 404) { @@ -217,7 +225,7 @@ export class Maestro implements Provider { } else { throw new Error( "Location: getDatum. Error: Couldn't successfully perform query. Received status code: " + - timestampedResultResponse.status, + timestampedResultResponse.status ); } } @@ -232,7 +240,7 @@ export class Maestro implements Provider { `${this.url}/transactions/${txHash}/cbor`, { headers: this.commonHeaders(), - }, + } ); if (isConfirmedResponse.ok) { await isConfirmedResponse.json(); @@ -251,7 +259,7 @@ export class Maestro implements Provider { method: "POST", headers: { "Content-Type": "application/cbor", - "Accept": "text/plain", + Accept: "text/plain", ...this.commonHeaders(), }, body: fromHex(tx), @@ -259,10 +267,12 @@ export class Maestro implements Provider { const result = await response.text(); if (!response.ok) { if (response.status === 400) throw new Error(result); - else {throw new Error( + else { + throw new Error( "Could not submit transaction. Received status code: " + - response.status, - );} + response.status + ); + } } return result; } @@ -284,16 +294,21 @@ export class Maestro implements Provider { })(), address: result.address, datumHash: result.datum - ? result.datum.type == "inline" ? undefined : result.datum.hash + ? result.datum.type == "inline" + ? undefined + : result.datum.hash : undefined, datum: result.datum?.bytes, scriptRef: result.reference_script - ? result.reference_script.type == "native" ? undefined : { - type: result.reference_script.type == "plutusv1" - ? "PlutusV1" - : "PlutusV2", - script: applyDoubleCborEncoding(result.reference_script.bytes!), - } + ? result.reference_script.type == "native" + ? undefined + : { + type: + result.reference_script.type == "plutusv1" + ? "PlutusV1" + : "PlutusV2", + script: applyDoubleCborEncoding(result.reference_script.bytes!), + } : undefined, }; } @@ -301,7 +316,7 @@ export class Maestro implements Provider { getResponse: (qry: string) => Promise, qry: string, paramsGiven: URLSearchParams, - errorMsg: string, + errorMsg: string ): Promise> { let nextCursor = null; let result: Array = []; @@ -313,7 +328,7 @@ export class Maestro implements Provider { const pageResult = await response.json(); if (!response.ok) { throw new Error( - `${errorMsg}. Received status code: ${response.status}`, + `${errorMsg}. Received status code: ${response.status}` ); } nextCursor = pageResult.next_cursor; diff --git a/src/utils/cml.ts b/src/utils/cml.ts new file mode 100644 index 00000000..5a535a88 --- /dev/null +++ b/src/utils/cml.ts @@ -0,0 +1,298 @@ +import { TransactionBuilder } from "../core/libs/cardano_multiplatform_lib/nodejs/cardano_multiplatform_lib.generated.js"; +import { + Address, + Assets, + C, + CertificateValidator, + Datum, + Lucid, + MintingPolicy, + OutputData, + PoolParams, + Redeemer, + RewardAddress, + SpendingValidator, + Tx, + WithdrawalValidator, + applyDoubleCborEncoding, + assetsToValue, + fromHex, + networkToId, + toScriptRef, +} from "../mod.ts"; +import { FreeableBucket, Freeables } from "./freeable.ts"; + +export function getScriptWitness( + redeemer: Redeemer, + datum?: Datum, +): C.ScriptWitness { + const bucket: FreeableBucket = []; + try { + const plutusRedeemer = C.PlutusData.from_bytes(fromHex(redeemer!)); + const plutusData = datum + ? C.PlutusData.from_bytes(fromHex(datum)) + : undefined; + const plutusWitness = C.PlutusWitness.new( + plutusRedeemer, + plutusData, + undefined, + ); + // We shouldn't free plutusData as it is an Option + bucket.push(plutusRedeemer, plutusWitness); + return C.ScriptWitness.new_plutus_witness(plutusWitness); + } finally { + Freeables.free(...bucket); + } +} + +export function getStakeCredential(hash: string, type: "Key" | "Script") { + if (type === "Key") { + const keyHash = C.Ed25519KeyHash.from_bytes(fromHex(hash)); + const credential = C.StakeCredential.from_keyhash(keyHash); + Freeables.free(keyHash); + return credential; + } + const scriptHash = C.ScriptHash.from_bytes(fromHex(hash)); + const credential = C.StakeCredential.from_scripthash(scriptHash); + Freeables.free(scriptHash); + return credential; +} + +export async function createPoolRegistration( + poolParams: PoolParams, + lucid: Lucid, +): Promise { + const bucket: FreeableBucket = []; + try { + const poolOwners = C.Ed25519KeyHashes.new(); + bucket.push(poolOwners); + poolParams.owners.forEach((owner) => { + const { stakeCredential } = lucid.utils.getAddressDetails(owner); + if (stakeCredential?.type === "Key") { + const keyHash = C.Ed25519KeyHash.from_hex(stakeCredential.hash); + poolOwners.add(keyHash); + bucket.push(keyHash); + } else throw new Error("Only key hashes allowed for pool owners."); + }); + + const metadata = poolParams.metadataUrl + ? await fetch(poolParams.metadataUrl).then((res) => res.arrayBuffer()) + : null; + + const metadataHash = metadata + ? C.PoolMetadataHash.from_bytes( + C.hash_blake2b256(new Uint8Array(metadata)), + ) + : null; + + const relays = C.Relays.new(); + bucket.push(metadataHash, relays); + poolParams.relays.forEach((relay) => { + switch (relay.type) { + case "SingleHostIp": { + const ipV4 = relay.ipV4 + ? C.Ipv4.new( + new Uint8Array(relay.ipV4.split(".").map((b) => parseInt(b))), + ) + : undefined; + const ipV6 = relay.ipV6 + ? C.Ipv6.new(fromHex(relay.ipV6.replaceAll(":", ""))) + : undefined; + const host = C.SingleHostAddr.new(relay.port, ipV4, ipV6); + const newRelay = C.Relay.new_single_host_addr(host); + //We shouldn't free ipV4 and ipV6 as they are optionals + bucket.push(host, newRelay); + relays.add(newRelay); + break; + } + case "SingleHostDomainName": { + const record = C.DNSRecordAorAAAA.new(relay.domainName!); + const host = C.SingleHostName.new(relay.port, record); + const newRelay = C.Relay.new_single_host_name(host); + bucket.push(record, host, newRelay); + relays.add(newRelay); + break; + } + case "MultiHost": { + const record = C.DNSRecordSRV.new(relay.domainName!); + const host = C.MultiHostName.new(record); + const newRelay = C.Relay.new_multi_host_name(host); + bucket.push(record, host, newRelay); + relays.add(newRelay); + break; + } + } + }); + + const operator = C.Ed25519KeyHash.from_bech32(poolParams.poolId); + const vrfKeyHash = C.VRFKeyHash.from_hex(poolParams.vrfKeyHash); + const pledge = C.BigNum.from_str(poolParams.pledge.toString()); + const cost = C.BigNum.from_str(poolParams.cost.toString()); + + const margin = C.UnitInterval.from_float(poolParams.margin); + const addr = addressFromWithNetworkCheck(poolParams.rewardAddress, lucid); + const rewardAddress = C.RewardAddress.from_address(addr); + const url = C.Url.new(poolParams.metadataUrl!); + const poolMetadata = metadataHash + ? C.PoolMetadata.new(url, metadataHash) + : undefined; + bucket.push( + operator, + vrfKeyHash, + pledge, + cost, + margin, + addr, + rewardAddress, + url, + poolMetadata, + ); + + const params = C.PoolParams.new( + operator, + vrfKeyHash, + pledge, + cost, + margin, + rewardAddress!, + poolOwners, + relays, + poolMetadata, + ); + + const poolRegistration = C.PoolRegistration.new(params); + return poolRegistration; + } finally { + Freeables.free(...bucket); + } +} + +export function attachScript( + tx: Tx, + { + type, + script, + }: + | SpendingValidator + | MintingPolicy + | CertificateValidator + | WithdrawalValidator, +) { + if (type === "Native") { + const nativeScript = C.NativeScript.from_bytes(fromHex(script)); + tx.txBuilder.add_native_script(nativeScript); + Freeables.free(nativeScript); + return; + } else if (type === "PlutusV1") { + const plutusScript = C.PlutusScript.from_bytes( + fromHex(applyDoubleCborEncoding(script)), + ); + tx.txBuilder.add_plutus_script(plutusScript); + Freeables.free(plutusScript); + return; + } else if (type === "PlutusV2") { + const plutusScript = C.PlutusScript.from_bytes( + fromHex(applyDoubleCborEncoding(script)), + ); + tx.txBuilder.add_plutus_v2_script(plutusScript); + Freeables.free(plutusScript); + return; + } + throw new Error("No variant matched."); +} + +export function addressFromWithNetworkCheck( + address: Address | RewardAddress, + lucid: Lucid, +): C.Address { + const { type, networkId } = lucid.utils.getAddressDetails(address); + + const actualNetworkId = networkToId(lucid.network); + if (networkId !== actualNetworkId) { + throw new Error( + `Invalid address: Expected address with network id ${actualNetworkId}, but got ${networkId}`, + ); + } + if (type === "Byron") { + const byron = C.ByronAddress.from_base58(address); + const addr = byron.to_address(); + byron.free(); + return addr; + } + return C.Address.from_bech32(address); +} + +export function getDatumFromOutputData(outputData?: OutputData): { + datum?: C.Datum | undefined; + plutusData?: C.PlutusData; +} { + if (outputData?.hash) { + const hash = C.DataHash.from_hex(outputData.hash); + const datum = C.Datum.new_data_hash(hash); + hash.free(); + return { datum }; + } else if (outputData?.asHash) { + const plutusData = C.PlutusData.from_bytes(fromHex(outputData.asHash)); + const dataHash = C.hash_plutus_data(plutusData); + const datum = C.Datum.new_data_hash(dataHash); + dataHash.free(); + return { plutusData, datum }; + } else if (outputData?.inline) { + const plutusData = C.PlutusData.from_bytes(fromHex(outputData.inline)); + const data = C.Data.new(plutusData); + const datum = C.Datum.new_data(data); + Freeables.free(plutusData, data); + return { datum }; + } else { + return {}; + } +} + +export function createOutput({ + bucket, + address, + assets, + outputData, + lucid, + txBuilder, +}: { + bucket: FreeableBucket; + address: Address; + assets: Assets; + outputData: OutputData; + lucid: Lucid; + txBuilder: TransactionBuilder; +}) { + const addr = addressFromWithNetworkCheck(address, lucid); + const value = assetsToValue(assets); + const output = C.TransactionOutput.new(addr, value); + bucket.push(output, addr, value); + + if (outputData.hash) { + const dataHash = C.DataHash.from_hex(outputData.hash); + const datum = C.Datum.new_data_hash(dataHash); + bucket.push(dataHash, datum); + output.set_datum(datum); + } else if (outputData.asHash) { + const plutusData = C.PlutusData.from_bytes(fromHex(outputData.asHash)); + const dataHash = C.hash_plutus_data(plutusData); + const datum = C.Datum.new_data_hash(dataHash); + bucket.push(plutusData, dataHash, datum); + output.set_datum(datum); + txBuilder.add_plutus_data(plutusData); + } else if (outputData.inline) { + const plutusData = C.PlutusData.from_bytes(fromHex(outputData.inline)); + const data = C.Data.new(plutusData); + const datum = C.Datum.new_data(data); + bucket.push(plutusData, data, datum); + output.set_datum(datum); + } + + const script = outputData.scriptRef; + if (script) { + const scriptRef = toScriptRef(script); + bucket.push(scriptRef); + output.set_script_ref(toScriptRef(script)); + } + return output; +} diff --git a/src/utils/cost_model.ts b/src/utils/cost_model.ts index ed1e40db..62d8484b 100644 --- a/src/utils/cost_model.ts +++ b/src/utils/cost_model.ts @@ -1,25 +1,45 @@ import { C } from "../core/mod.ts"; import { CostModels } from "../mod.ts"; import { ProtocolParameters } from "../types/types.ts"; +import { Freeable, Freeables } from "./freeable.ts"; export function createCostModels(costModels: CostModels): C.Costmdls { - const costmdls = C.Costmdls.new(); + const bucket: Freeable[] = []; + try { + const costmdls = C.Costmdls.new(); - // add plutus v1 - const costmdlV1 = C.CostModel.new(); - Object.values(costModels.PlutusV1).forEach((cost, index) => { - costmdlV1.set(index, C.Int.new(C.BigNum.from_str(cost.toString()))); - }); - costmdls.insert(C.Language.new_plutus_v1(), costmdlV1); + // add plutus v1 + const costmdlV1 = C.CostModel.new(); + bucket.push(costmdlV1); + Object.values(costModels.PlutusV1).forEach((cost, index) => { + const bigNumVal = C.BigNum.from_str(cost.toString()); + bucket.push(bigNumVal); + const intVal = C.Int.new(bigNumVal); + bucket.push(intVal); + costmdlV1.set(index, intVal); + }); + const plutusV1 = C.Language.new_plutus_v1(); + bucket.push(plutusV1); + costmdls.insert(plutusV1, costmdlV1); - // add plutus v2 - const costmdlV2 = C.CostModel.new_plutus_v2(); - Object.values(costModels.PlutusV2 || []).forEach((cost, index) => { - costmdlV2.set(index, C.Int.new(C.BigNum.from_str(cost.toString()))); - }); - costmdls.insert(C.Language.new_plutus_v2(), costmdlV2); + // add plutus v2 + const costmdlV2 = C.CostModel.new_plutus_v2(); + bucket.push(costmdlV2); + Object.values(costModels.PlutusV2 || []).forEach((cost, index) => { + const bigNumVal = C.BigNum.from_str(cost.toString()); + bucket.push(bigNumVal); + const intVal = C.Int.new(bigNumVal); + bucket.push(intVal); + costmdlV2.set(index, intVal); + }); + const plutusV2 = C.Language.new_plutus_v2(); + bucket.push(plutusV2); + costmdls.insert(plutusV2, costmdlV2); - return costmdls; + return costmdls; + } finally { + Freeables.free(...bucket); + } } export const PROTOCOL_PARAMETERS_DEFAULT: ProtocolParameters = { diff --git a/src/utils/freeable.ts b/src/utils/freeable.ts new file mode 100644 index 00000000..99b2d215 --- /dev/null +++ b/src/utils/freeable.ts @@ -0,0 +1,33 @@ +/** + * These types and classes are used to help with freeing memory. + * Objects passed from the WASM to JS (Objects from Rust libraries, for example) are not freed automatically, or at least inconsistently. + * This can lead to memory leaks. + * In order to free these objects, we need to call the `free()` method on them. These types make it easier. + */ + +/** This interface represents WASM objects that can and need to be freed. */ +export interface Freeable { + free(): void; +} + +export type FreeableBucket = Array; + +/** This class makes it easier to free large sets of memory. It can be used like this: + * ```ts + * const bucket: FreeableBucket = []; + * try { + * const rustObject = C.some_rust_object(); + * bucket.push(rustObject); + * ... + * } finally { + * Freeables.free(...bucket); + * } + * ``` + */ +export abstract class Freeables { + static free(...bucket: FreeableBucket) { + bucket.forEach((freeable) => { + freeable?.free(); + }); + } +} diff --git a/src/utils/mod.ts b/src/utils/mod.ts index 429b6c2c..972e4c7b 100644 --- a/src/utils/mod.ts +++ b/src/utils/mod.ts @@ -1,3 +1,5 @@ export * from "./cost_model.ts"; export * from "./utils.ts"; export * from "./merkle_tree.ts"; +export * from "./cml.ts"; +export * from "./freeable.ts"; diff --git a/src/utils/transaction_builder_config.ts b/src/utils/transaction_builder_config.ts new file mode 100644 index 00000000..40d0af65 --- /dev/null +++ b/src/utils/transaction_builder_config.ts @@ -0,0 +1,108 @@ +import { C, SlotConfig } from "../mod.ts"; +import { ProtocolParameters } from "../types/mod.ts"; +import { createCostModels } from "./cost_model.ts"; +import { Freeable, Freeables } from "./freeable.ts"; + +export function getTransactionBuilderConfig( + protocolParameters: ProtocolParameters, + slotConfig: SlotConfig, + blockfrostConfig: { + url?: string; + projectId?: string; + }, +) { + const bucket: Freeable[] = []; + let builderA = C.TransactionBuilderConfigBuilder.new(); + + const coinsPerUtxoByte = C.BigNum.from_str( + protocolParameters.coinsPerUtxoByte.toString(), + ); + bucket.push(coinsPerUtxoByte); + let builderB = builderA.coins_per_utxo_byte(coinsPerUtxoByte); + builderA.free(); + + const minFeeA = C.BigNum.from_str(protocolParameters.minFeeA.toString()); + bucket.push(minFeeA); + const minFeeB = C.BigNum.from_str(protocolParameters.minFeeB.toString()); + bucket.push(minFeeB); + const linearFee = C.LinearFee.new(minFeeA, minFeeB); + bucket.push(linearFee); + builderA = builderB.fee_algo(linearFee); + builderB.free(); + + const keyDeposit = C.BigNum.from_str( + protocolParameters.keyDeposit.toString(), + ); + bucket.push(keyDeposit); + builderB = builderA.key_deposit(keyDeposit); + builderA.free(); + + const poolDeposit = C.BigNum.from_str( + protocolParameters.poolDeposit.toString(), + ); + bucket.push(poolDeposit); + builderA = builderB.pool_deposit(poolDeposit); + builderB.free(); + + builderB = builderA.max_tx_size(protocolParameters.maxTxSize); + builderA.free(); + + builderA = builderB.max_value_size(protocolParameters.maxValSize); + builderB.free(); + + builderB = builderA.collateral_percentage( + protocolParameters.collateralPercentage, + ); + builderA.free(); + + builderA = builderB.max_collateral_inputs( + protocolParameters.maxCollateralInputs, + ); + builderB.free(); + + const maxTxExMem = C.BigNum.from_str( + protocolParameters.maxTxExMem.toString(), + ); + bucket.push(maxTxExMem); + const maxTxExSteps = C.BigNum.from_str( + protocolParameters.maxTxExSteps.toString(), + ); + bucket.push(maxTxExSteps); + const exUnits = C.ExUnits.new(maxTxExMem, maxTxExSteps); + bucket.push(exUnits); + builderB = builderA.max_tx_ex_units(exUnits); + builderA.free(); + + const exUnitPrices = C.ExUnitPrices.from_float( + protocolParameters.priceMem, + protocolParameters.priceStep, + ); + bucket.push(exUnitPrices); + builderA = builderB.ex_unit_prices(exUnitPrices); + builderB.free(); + + const zeroTime = C.BigNum.from_str(slotConfig.zeroTime.toString()); + bucket.push(zeroTime); + const zeroSlot = C.BigNum.from_str(slotConfig.zeroSlot.toString()); + bucket.push(zeroSlot); + builderB = builderA.slot_config(zeroTime, zeroSlot, slotConfig.slotLength); + builderA.free(); + + const blockfrost = C.Blockfrost.new( + blockfrostConfig?.url ?? "" + "utils/tx/evaulate", + blockfrostConfig?.projectId ?? "", + ); + bucket.push(blockfrost); + builderA = builderB.blockfrost(blockfrost); + builderB.free(); + + const costModels = createCostModels(protocolParameters.costModels); + bucket.push(costModels); + builderB = builderA.costmdls(costModels); + + const config = builderB.build(); + builderB.free(); + Freeables.free(...bucket); + + return config; +} diff --git a/src/utils/utils.ts b/src/utils/utils.ts index f65b69ac..5aba9841 100644 --- a/src/utils/utils.ts +++ b/src/utils/utils.ts @@ -40,6 +40,7 @@ import { unixTimeToEnclosingSlot, } from "../plutus/time.ts"; import { Data } from "../plutus/data.ts"; +import { FreeableBucket, Freeables } from "./freeable.ts"; export class Utils { private lucid: Lucid; @@ -49,120 +50,215 @@ export class Utils { validatorToAddress( validator: SpendingValidator, - stakeCredential?: Credential + stakeCredential?: Credential, ): Address { - const validatorHash = this.validatorToScriptHash(validator); - if (stakeCredential) { - return C.BaseAddress.new( - networkToId(this.lucid.network), - C.StakeCredential.from_scripthash(C.ScriptHash.from_hex(validatorHash)), - stakeCredential.type === "Key" - ? C.StakeCredential.from_keyhash( - C.Ed25519KeyHash.from_hex(stakeCredential.hash) - ) - : C.StakeCredential.from_scripthash( - C.ScriptHash.from_hex(stakeCredential.hash) - ) - ) - .to_address() - .to_bech32(undefined); - } else { - return C.EnterpriseAddress.new( - networkToId(this.lucid.network), - C.StakeCredential.from_scripthash(C.ScriptHash.from_hex(validatorHash)) - ) - .to_address() - .to_bech32(undefined); + const bucket: FreeableBucket = []; + const networkId = networkToId(this.lucid.network); + try { + const validatorHash = this.validatorToScriptHash(validator); + if (stakeCredential) { + const validatorScriptHash = C.ScriptHash.from_hex(validatorHash); + bucket.push(validatorScriptHash); + const paymentPart = + C.StakeCredential.from_scripthash(validatorScriptHash); + bucket.push(paymentPart); + let stakePart: C.StakeCredential; + if (stakeCredential.type === "Key") { + const keyHash = C.Ed25519KeyHash.from_hex(stakeCredential.hash); + stakePart = C.StakeCredential.from_keyhash(keyHash); + keyHash.free(); + } else { + const scriptHash = C.ScriptHash.from_hex(stakeCredential.hash); + stakePart = C.StakeCredential.from_scripthash(scriptHash); + scriptHash.free(); + } + bucket.push(stakePart); + const baseAddress = C.BaseAddress.new( + networkId, + paymentPart, + stakePart, + ); + bucket.push(baseAddress); + const address = baseAddress.to_address(); + bucket.push(address); + + return address.to_bech32(undefined); + } else { + const validatorScriptHash = C.ScriptHash.from_hex(validatorHash); + bucket.push(validatorScriptHash); + + const paymentPart = + C.StakeCredential.from_scripthash(validatorScriptHash); + bucket.push(paymentPart); + const enterpriseAddress = C.EnterpriseAddress.new( + networkId, + paymentPart, + ); + bucket.push(enterpriseAddress); + const address = enterpriseAddress.to_address(); + bucket.push(address); + + return address.to_bech32(undefined); + } + } finally { + Freeables.free(...bucket); } } credentialToAddress( paymentCredential: Credential, - stakeCredential?: Credential + stakeCredential?: Credential, ): Address { - if (stakeCredential) { - return C.BaseAddress.new( - networkToId(this.lucid.network), - paymentCredential.type === "Key" - ? C.StakeCredential.from_keyhash( - C.Ed25519KeyHash.from_hex(paymentCredential.hash) - ) - : C.StakeCredential.from_scripthash( - C.ScriptHash.from_hex(paymentCredential.hash) - ), - stakeCredential.type === "Key" - ? C.StakeCredential.from_keyhash( - C.Ed25519KeyHash.from_hex(stakeCredential.hash) - ) - : C.StakeCredential.from_scripthash( - C.ScriptHash.from_hex(stakeCredential.hash) - ) - ) - .to_address() - .to_bech32(undefined); - } else { - return C.EnterpriseAddress.new( - networkToId(this.lucid.network), - paymentCredential.type === "Key" - ? C.StakeCredential.from_keyhash( - C.Ed25519KeyHash.from_hex(paymentCredential.hash) - ) - : C.StakeCredential.from_scripthash( - C.ScriptHash.from_hex(paymentCredential.hash) - ) - ) - .to_address() - .to_bech32(undefined); + const networkId = networkToId(this.lucid.network); + const bucket: FreeableBucket = []; + try { + if (stakeCredential) { + let paymentPart: C.StakeCredential; + let stakePart: C.StakeCredential; + if (paymentCredential.type === "Key") { + const keyHash = C.Ed25519KeyHash.from_hex(paymentCredential.hash); + bucket.push(keyHash); + paymentPart = C.StakeCredential.from_keyhash(keyHash); + } else { + const scriptHash = C.ScriptHash.from_hex(paymentCredential.hash); + bucket.push(scriptHash); + paymentPart = C.StakeCredential.from_scripthash(scriptHash); + } + bucket.push(paymentPart); + if (stakeCredential.type === "Key") { + const keyHash = C.Ed25519KeyHash.from_hex(stakeCredential.hash); + bucket.push(keyHash); + stakePart = C.StakeCredential.from_keyhash(keyHash); + } else { + const scriptHash = C.ScriptHash.from_hex(stakeCredential.hash); + bucket.push(scriptHash); + stakePart = C.StakeCredential.from_scripthash(scriptHash); + } + bucket.push(stakePart); + + const baseAddress = C.BaseAddress.new( + networkId, + paymentPart, + stakePart, + ); + bucket.push(baseAddress); + const address = baseAddress.to_address(); + bucket.push(address); + + return address.to_bech32(undefined); + } else { + let paymentPart: C.StakeCredential; + if (paymentCredential.type === "Key") { + const keyHash = C.Ed25519KeyHash.from_hex(paymentCredential.hash); + bucket.push(keyHash); + paymentPart = C.StakeCredential.from_keyhash(keyHash); + } else { + const scriptHash = C.ScriptHash.from_hex(paymentCredential.hash); + bucket.push(scriptHash); + paymentPart = C.StakeCredential.from_scripthash(scriptHash); + } + bucket.push(paymentPart); + + const enterpriseAddress = C.EnterpriseAddress.new( + networkId, + paymentPart, + ); + bucket.push(enterpriseAddress); + const address = enterpriseAddress.to_address(); + bucket.push(address); + + return address.to_bech32(undefined); + } + } finally { + Freeables.free(...bucket); } } validatorToRewardAddress( - validator: CertificateValidator | WithdrawalValidator + validator: CertificateValidator | WithdrawalValidator, ): RewardAddress { + const bucket: FreeableBucket = []; const validatorHash = this.validatorToScriptHash(validator); - return C.RewardAddress.new( + const scriptHash = C.ScriptHash.from_hex(validatorHash); + bucket.push(scriptHash); + const stakePart = C.StakeCredential.from_scripthash(scriptHash); + bucket.push(stakePart); + const rewardAddress = C.RewardAddress.new( networkToId(this.lucid.network), - C.StakeCredential.from_scripthash(C.ScriptHash.from_hex(validatorHash)) - ) - .to_address() - .to_bech32(undefined); + stakePart, + ); + bucket.push(rewardAddress); + const address = rewardAddress.to_address(); + bucket.push(address); + const bech32 = address.to_bech32(undefined); + + Freeables.free(...bucket); + return bech32; } credentialToRewardAddress(stakeCredential: Credential): RewardAddress { - return C.RewardAddress.new( + const bucket: FreeableBucket = []; + let stakePart: C.StakeCredential; + if (stakeCredential.type === "Key") { + const keyHash = C.Ed25519KeyHash.from_hex(stakeCredential.hash); + bucket.push(keyHash); + stakePart = C.StakeCredential.from_keyhash(keyHash); + } else { + const scriptHash = C.ScriptHash.from_hex(stakeCredential.hash); + bucket.push(scriptHash); + stakePart = C.StakeCredential.from_scripthash(scriptHash); + } + bucket.push(stakePart); + + const rewardAddress = C.RewardAddress.new( networkToId(this.lucid.network), - stakeCredential.type === "Key" - ? C.StakeCredential.from_keyhash( - C.Ed25519KeyHash.from_hex(stakeCredential.hash) - ) - : C.StakeCredential.from_scripthash( - C.ScriptHash.from_hex(stakeCredential.hash) - ) - ) - .to_address() - .to_bech32(undefined); + stakePart, + ); + bucket.push(rewardAddress); + const address = rewardAddress.to_address(); + bucket.push(address); + const bech32 = address.to_bech32(undefined); + Freeables.free(...bucket); + + return bech32; } validatorToScriptHash(validator: Validator): ScriptHash { - switch (validator.type) { - case "Native": - return C.NativeScript.from_bytes(fromHex(validator.script)) - .hash(C.ScriptHashNamespace.NativeScript) - .to_hex(); - case "PlutusV1": - return C.PlutusScript.from_bytes( - fromHex(applyDoubleCborEncoding(validator.script)) - ) - .hash(C.ScriptHashNamespace.PlutusV1) - .to_hex(); - case "PlutusV2": - return C.PlutusScript.from_bytes( - fromHex(applyDoubleCborEncoding(validator.script)) - ) - .hash(C.ScriptHashNamespace.PlutusV2) - .to_hex(); - default: - throw new Error("No variant matched"); + const bucket: FreeableBucket = []; + try { + switch (validator.type) { + case "Native": { + const nativeScript = C.NativeScript.from_bytes( + fromHex(validator.script), + ); + bucket.push(nativeScript); + const hash = nativeScript.hash(C.ScriptHashNamespace.NativeScript); + bucket.push(hash); + return hash.to_hex(); + } + case "PlutusV1": { + const plutusScript = C.PlutusScript.from_bytes( + fromHex(applyDoubleCborEncoding(validator.script)), + ); + bucket.push(plutusScript); + const hash = plutusScript.hash(C.ScriptHashNamespace.PlutusV1); + bucket.push(hash); + return hash.to_hex(); + } + case "PlutusV2": { + const plutusScript = C.PlutusScript.from_bytes( + fromHex(applyDoubleCborEncoding(validator.script)), + ); + bucket.push(plutusScript); + const hash = plutusScript.hash(C.ScriptHashNamespace.PlutusV2); + bucket.push(hash); + return hash.to_hex(); + } + default: + throw new Error("No variant matched"); + } + } finally { + Freeables.free(...bucket); } } @@ -171,7 +267,12 @@ export class Utils { } datumToHash(datum: Datum): DatumHash { - return C.hash_plutus_data(C.PlutusData.from_bytes(fromHex(datum))).to_hex(); + const plutusData = C.PlutusData.from_bytes(fromHex(datum)); + const hash = C.hash_plutus_data(plutusData); + plutusData.free(); + const datumHash = hash.to_hex(); + hash.free(); + return datumHash; } scriptHashToCredential(scriptHash: ScriptHash): Credential { @@ -199,7 +300,7 @@ export class Utils { unixTimeToSlot(unixTime: UnixTime): Slot { return unixTimeToEnclosingSlot( unixTime, - SLOT_CONFIG_NETWORK[this.lucid.network] + SLOT_CONFIG_NETWORK[this.lucid.network], ); } @@ -232,8 +333,8 @@ export class Utils { const minAda = C.min_ada_required( output, C.BigNum.from_str( - this.lucid.protocolParameters.coinsPerUtxoByte.toString() - ) + this.lucid.protocolParameters.coinsPerUtxoByte.toString(), + ), ); return BigInt(minAda.to_str()).valueOf(); } @@ -253,169 +354,238 @@ function addressFromHexOrBech32(address: string): C.Address { /** Address can be in Bech32 or Hex. */ export function getAddressDetails(address: string): AddressDetails { - // Base Address + const bucket: FreeableBucket = []; + // wrapped in an outer try to ensure that memory is freed try { - const parsedAddress = C.BaseAddress.from_address( - addressFromHexOrBech32(address) - )!; - const paymentCredential: Credential = - parsedAddress.payment_cred().kind() === 0 - ? { - type: "Key", - hash: toHex(parsedAddress.payment_cred().to_keyhash()!.to_bytes()), - } - : { - type: "Script", - hash: toHex( - parsedAddress.payment_cred().to_scripthash()!.to_bytes() - ), - }; - const stakeCredential: Credential = - parsedAddress.stake_cred().kind() === 0 - ? { - type: "Key", - hash: toHex(parsedAddress.stake_cred().to_keyhash()!.to_bytes()), - } - : { - type: "Script", - hash: toHex(parsedAddress.stake_cred().to_scripthash()!.to_bytes()), - }; - return { - type: "Base", - networkId: parsedAddress.to_address().network_id(), - address: { - bech32: parsedAddress.to_address().to_bech32(undefined), - hex: toHex(parsedAddress.to_address().to_bytes()), - }, - paymentCredential, - stakeCredential, - }; - } catch (_e) { - /* pass */ - } + // Base Address + try { + const parsedAddress = addressFromHexOrBech32(address); + bucket.push(parsedAddress); + const baseAddress = C.BaseAddress.from_address(parsedAddress)!; + bucket.push(baseAddress); - // Enterprise Address - try { - const parsedAddress = C.EnterpriseAddress.from_address( - addressFromHexOrBech32(address) - )!; - const paymentCredential: Credential = - parsedAddress.payment_cred().kind() === 0 - ? { - type: "Key", - hash: toHex(parsedAddress.payment_cred().to_keyhash()!.to_bytes()), - } - : { - type: "Script", - hash: toHex( - parsedAddress.payment_cred().to_scripthash()!.to_bytes() - ), - }; - return { - type: "Enterprise", - networkId: parsedAddress.to_address().network_id(), - address: { - bech32: parsedAddress.to_address().to_bech32(undefined), - hex: toHex(parsedAddress.to_address().to_bytes()), - }, - paymentCredential, - }; - } catch (_e) { - /* pass */ - } + let paymentCredential: Credential; + const paymentCred = baseAddress.payment_cred(); + bucket.push(paymentCred); + if (paymentCred.kind() === 0) { + const keyHash = paymentCred.to_keyhash()!; + bucket.push(keyHash); + paymentCredential = { + type: "Key", + hash: toHex(keyHash.to_bytes()), + }; + } else { + const scriptHash = paymentCred.to_scripthash()!; + bucket.push(scriptHash); + paymentCredential = { + type: "Script", + hash: toHex(scriptHash.to_bytes()), + }; + } - // Pointer Address - try { - const parsedAddress = C.PointerAddress.from_address( - addressFromHexOrBech32(address) - )!; - const paymentCredential: Credential = - parsedAddress.payment_cred().kind() === 0 - ? { - type: "Key", - hash: toHex(parsedAddress.payment_cred().to_keyhash()!.to_bytes()), - } - : { - type: "Script", - hash: toHex( - parsedAddress.payment_cred().to_scripthash()!.to_bytes() - ), - }; - return { - type: "Pointer", - networkId: parsedAddress.to_address().network_id(), - address: { - bech32: parsedAddress.to_address().to_bech32(undefined), - hex: toHex(parsedAddress.to_address().to_bytes()), - }, - paymentCredential, - }; - } catch (_e) { - /* pass */ - } + let stakeCredential: Credential; + const stakeCred = baseAddress.stake_cred(); + bucket.push(stakeCred); + if (stakeCred.kind() === 0) { + const keyHash = stakeCred.to_keyhash()!; + bucket.push(keyHash); + stakeCredential = { + type: "Key", + hash: toHex(keyHash.to_bytes()), + }; + } else { + const scriptHash = stakeCred.to_scripthash()!; + bucket.push(scriptHash); + stakeCredential = { + type: "Script", + hash: toHex(scriptHash.to_bytes()), + }; + } - // Reward Address - try { - const parsedAddress = C.RewardAddress.from_address( - addressFromHexOrBech32(address) - )!; - const stakeCredential: Credential = - parsedAddress.payment_cred().kind() === 0 - ? { - type: "Key", - hash: toHex(parsedAddress.payment_cred().to_keyhash()!.to_bytes()), - } - : { - type: "Script", - hash: toHex( - parsedAddress.payment_cred().to_scripthash()!.to_bytes() - ), - }; - return { - type: "Reward", - networkId: parsedAddress.to_address().network_id(), - address: { - bech32: parsedAddress.to_address().to_bech32(undefined), - hex: toHex(parsedAddress.to_address().to_bytes()), - }, - stakeCredential, - }; - } catch (_e) { - /* pass */ - } + const cAddress = baseAddress.to_address(); + bucket.push(cAddress); - // Limited support for Byron addresses - try { - const parsedAddress = ((address: string): C.ByronAddress => { - try { - return C.ByronAddress.from_bytes(fromHex(address)); - } catch (_e) { + return { + type: "Base", + networkId: cAddress.network_id(), + address: { + bech32: cAddress.to_bech32(undefined), + hex: toHex(cAddress.to_bytes()), + }, + paymentCredential, + stakeCredential, + }; + } catch (_e) { + /* pass */ + } + + // Enterprise Address + try { + const parsedAddress = addressFromHexOrBech32(address); + bucket.push(parsedAddress); + const enterpriseAddress = + C.EnterpriseAddress.from_address(parsedAddress)!; + bucket.push(enterpriseAddress); + + let paymentCredential: Credential; + const paymentCred = enterpriseAddress.payment_cred(); + bucket.push(paymentCred); + if (paymentCred.kind() === 0) { + const keyHash = paymentCred.to_keyhash()!; + bucket.push(keyHash); + paymentCredential = { + type: "Key", + hash: toHex(keyHash.to_bytes()), + }; + } else { + const scriptHash = paymentCred.to_scripthash()!; + bucket.push(scriptHash); + paymentCredential = { + type: "Script", + hash: toHex(scriptHash.to_bytes()), + }; + } + + const cAddress = enterpriseAddress.to_address(); + bucket.push(cAddress); + return { + type: "Enterprise", + networkId: cAddress.network_id(), + address: { + bech32: cAddress.to_bech32(undefined), + hex: toHex(cAddress.to_bytes()), + }, + paymentCredential, + }; + } catch (_e) { + /* pass */ + } + + // Pointer Address + try { + const parsedAddress = addressFromHexOrBech32(address); + bucket.push(parsedAddress); + const pointerAddress = C.PointerAddress.from_address(parsedAddress)!; + bucket.push(pointerAddress); + + let paymentCredential: Credential; + const paymentCred = pointerAddress.payment_cred(); + bucket.push(paymentCred); + if (paymentCred.kind() === 0) { + const keyHash = paymentCred.to_keyhash()!; + bucket.push(keyHash); + paymentCredential = { + type: "Key", + hash: toHex(keyHash.to_bytes()), + }; + } else { + const scriptHash = paymentCred.to_scripthash()!; + bucket.push(scriptHash); + paymentCredential = { + type: "Script", + hash: toHex(scriptHash.to_bytes()), + }; + } + + const cAddress = pointerAddress.to_address(); + bucket.push(cAddress); + + return { + type: "Pointer", + networkId: cAddress.network_id(), + address: { + bech32: cAddress.to_bech32(undefined), + hex: toHex(cAddress.to_bytes()), + }, + paymentCredential, + }; + } catch (_e) { + /* pass */ + } + + // Reward Address + try { + const parsedAddress = addressFromHexOrBech32(address); + bucket.push(parsedAddress); + const rewardAddress = C.RewardAddress.from_address(parsedAddress)!; + bucket.push(rewardAddress); + + let stakeCredential: Credential; + const paymentCred = rewardAddress.payment_cred(); + bucket.push(paymentCred); + if (paymentCred.kind() === 0) { + const keyHash = paymentCred.to_keyhash()!; + bucket.push(keyHash); + stakeCredential = { + type: "Key", + hash: toHex(keyHash.to_bytes()), + }; + } else { + const scriptHash = paymentCred.to_scripthash()!; + bucket.push(scriptHash); + stakeCredential = { + type: "Script", + hash: toHex(scriptHash.to_bytes()), + }; + } + + const cAddress = rewardAddress.to_address(); + bucket.push(cAddress); + + return { + type: "Reward", + networkId: cAddress.network_id(), + address: { + bech32: cAddress.to_bech32(undefined), + hex: toHex(cAddress.to_bytes()), + }, + stakeCredential, + }; + } catch (_e) { + /* pass */ + } + + // Limited support for Byron addresses + try { + const parsedAddress = ((address: string): C.ByronAddress => { try { - return C.ByronAddress.from_base58(address); + return C.ByronAddress.from_bytes(fromHex(address)); } catch (_e) { - throw new Error("Could not deserialize address."); + try { + return C.ByronAddress.from_base58(address); + } catch (_e) { + throw new Error("Could not deserialize address."); + } } - } - })(address); + })(address); + bucket.push(parsedAddress); - return { - type: "Byron", - networkId: parsedAddress.network_id(), - address: { - bech32: "", - hex: toHex(parsedAddress.to_address().to_bytes()), - }, - }; - } catch (_e) { /* pass */ } + const cAddress = parsedAddress.to_address(); + bucket.push(cAddress); + + return { + type: "Byron", + networkId: parsedAddress.network_id(), + address: { + bech32: "", + hex: toHex(cAddress.to_bytes()), + }, + }; + } catch (_e) { + /* pass */ + } - throw new Error("No address type matched for: " + address); + throw new Error("No address type matched for: " + address); + } finally { + Freeables.free(...bucket); + } } export function paymentCredentialOf(address: Address): Credential { const { paymentCredential } = getAddressDetails(address); if (!paymentCredential) { throw new Error( - "The specified address does not contain a payment credential." + "The specified address does not contain a payment credential.", ); } return paymentCredential; @@ -425,14 +595,17 @@ export function stakeCredentialOf(rewardAddress: RewardAddress): Credential { const { stakeCredential } = getAddressDetails(rewardAddress); if (!stakeCredential) { throw new Error( - "The specified address does not contain a stake credential." + "The specified address does not contain a stake credential.", ); } return stakeCredential; } export function generatePrivateKey(): PrivateKey { - return C.PrivateKey.generate_ed25519().to_bech32(); + const ed25519 = C.PrivateKey.generate_ed25519(); + const bech32 = ed25519.to_bech32(); + ed25519.free(); + return bech32; } export function generateSeedPhrase(): string { @@ -440,156 +613,257 @@ export function generateSeedPhrase(): string { } export function valueToAssets(value: C.Value): Assets { + const bucket: FreeableBucket = []; const assets: Assets = {}; - assets["lovelace"] = BigInt(value.coin().to_str()); + const lovelace = value.coin(); + bucket.push(lovelace); + assets["lovelace"] = BigInt(lovelace.to_str()); const ma = value.multiasset(); + bucket.push(ma); if (ma) { const multiAssets = ma.keys(); + bucket.push(multiAssets); for (let j = 0; j < multiAssets.len(); j++) { const policy = multiAssets.get(j); + bucket.push(policy); const policyAssets = ma.get(policy)!; + bucket.push(policyAssets); const assetNames = policyAssets.keys(); + bucket.push(assetNames); for (let k = 0; k < assetNames.len(); k++) { const policyAsset = assetNames.get(k); + bucket.push(policyAsset); const quantity = policyAssets.get(policyAsset)!; + bucket.push(quantity); const unit = toHex(policy.to_bytes()) + toHex(policyAsset.name()); assets[unit] = BigInt(quantity.to_str()); } } } + Freeables.free(...bucket); return assets; } export function assetsToValue(assets: Assets): C.Value { + const bucket: FreeableBucket = []; const multiAsset = C.MultiAsset.new(); + bucket.push(multiAsset); const lovelace = assets["lovelace"]; const units = Object.keys(assets); const policies = Array.from( new Set( units .filter((unit) => unit !== "lovelace") - .map((unit) => unit.slice(0, 56)) - ) + .map((unit) => unit.slice(0, 56)), + ), ); policies.forEach((policy) => { const policyUnits = units.filter((unit) => unit.slice(0, 56) === policy); const assetsValue = C.Assets.new(); policyUnits.forEach((unit) => { - assetsValue.insert( - C.AssetName.new(fromHex(unit.slice(56))), - C.BigNum.from_str(assets[unit].toString()) - ); + const assetName = C.AssetName.new(fromHex(unit.slice(56))); + bucket.push(assetName); + const quantity = C.BigNum.from_str(assets[unit].toString()); + bucket.push(quantity); + + assetsValue.insert(assetName, quantity); }); - multiAsset.insert(C.ScriptHash.from_bytes(fromHex(policy)), assetsValue); + const policyId = C.ScriptHash.from_bytes(fromHex(policy)); + bucket.push(policyId); + multiAsset.insert(policyId, assetsValue); }); - const value = C.Value.new( - C.BigNum.from_str(lovelace ? lovelace.toString() : "0") - ); + const coin = C.BigNum.from_str(lovelace ? lovelace.toString() : "0"); + bucket.push(coin); + + const value = C.Value.new(coin); if (units.length > 1 || !lovelace) value.set_multiasset(multiAsset); + + Freeables.free(...bucket); return value; } export function fromScriptRef(scriptRef: C.ScriptRef): Script { - const kind = scriptRef.get().kind(); - switch (kind) { - case 0: - return { - type: "Native", - script: toHex(scriptRef.get().as_native()!.to_bytes()), - }; - case 1: - return { - type: "PlutusV1", - script: toHex(scriptRef.get().as_plutus_v1()!.to_bytes()), - }; - case 2: - return { - type: "PlutusV2", - script: toHex(scriptRef.get().as_plutus_v2()!.to_bytes()), - }; - default: - throw new Error("No variant matched."); + const bucket: FreeableBucket = []; + try { + const script = scriptRef.get(); + bucket.push(script); + const kind = script.kind(); + switch (kind) { + case 0: { + const native = script.as_native()!; + bucket.push(native); + return { + type: "Native", + script: toHex(native.to_bytes()), + }; + } + case 1: { + const plutusV1 = script.as_plutus_v1()!; + bucket.push(plutusV1); + return { + type: "PlutusV1", + script: toHex(plutusV1.to_bytes()), + }; + } + case 2: { + const plutusV2 = script.as_plutus_v2()!; + bucket.push(plutusV2); + return { + type: "PlutusV2", + script: toHex(plutusV2.to_bytes()), + }; + } + default: + throw new Error("No variant matched."); + } + } finally { + Freeables.free(...bucket); } } export function toScriptRef(script: Script): C.ScriptRef { - switch (script.type) { - case "Native": - return C.ScriptRef.new( - C.Script.new_native(C.NativeScript.from_bytes(fromHex(script.script))) - ); - case "PlutusV1": - return C.ScriptRef.new( - C.Script.new_plutus_v1( - C.PlutusScript.from_bytes( - fromHex(applyDoubleCborEncoding(script.script)) - ) - ) - ); - case "PlutusV2": - return C.ScriptRef.new( - C.Script.new_plutus_v2( - C.PlutusScript.from_bytes( - fromHex(applyDoubleCborEncoding(script.script)) - ) - ) - ); - default: - throw new Error("No variant matched."); + const bucket: FreeableBucket = []; + try { + switch (script.type) { + case "Native": { + const nativeScript = C.NativeScript.from_bytes(fromHex(script.script)); + bucket.push(nativeScript); + const cScript = C.Script.new_native(nativeScript); + bucket.push(cScript); + return C.ScriptRef.new(cScript); + } + case "PlutusV1": { + const plutusScript = C.PlutusScript.from_bytes( + fromHex(applyDoubleCborEncoding(script.script)), + ); + bucket.push(plutusScript); + const cScript = C.Script.new_plutus_v1(plutusScript); + bucket.push(cScript); + return C.ScriptRef.new(cScript); + } + case "PlutusV2": { + const plutusScript = C.PlutusScript.from_bytes( + fromHex(applyDoubleCborEncoding(script.script)), + ); + bucket.push(plutusScript); + const cScript = C.Script.new_plutus_v2(plutusScript); + bucket.push(cScript); + return C.ScriptRef.new(cScript); + } + default: + throw new Error("No variant matched."); + } + } finally { + Freeables.free(...bucket); } } export function utxoToCore(utxo: UTxO): C.TransactionUnspentOutput { + const bucket: FreeableBucket = []; const address: C.Address = (() => { try { + console.log("success"); return C.Address.from_bech32(utxo.address); } catch (_e) { - return C.ByronAddress.from_base58(utxo.address).to_address(); + const byronAddress = C.ByronAddress.from_base58(utxo.address); + bucket.push(byronAddress); + return byronAddress.to_address(); } })(); - const output = C.TransactionOutput.new(address, assetsToValue(utxo.assets)); + bucket.push(address); + const value = assetsToValue(utxo.assets); + bucket.push(value); + const output = C.TransactionOutput.new(address, value); + bucket.push(output); if (utxo.datumHash) { - output.set_datum( - C.Datum.new_data_hash(C.DataHash.from_bytes(fromHex(utxo.datumHash))) - ); + const dataHash = C.DataHash.from_bytes(fromHex(utxo.datumHash)); + bucket.push(dataHash); + const datum = C.Datum.new_data_hash(dataHash); + bucket.push(datum); + output.set_datum(datum); } // inline datum if (!utxo.datumHash && utxo.datum) { - output.set_datum( - C.Datum.new_data(C.Data.new(C.PlutusData.from_bytes(fromHex(utxo.datum)))) - ); + const plutusData = C.PlutusData.from_bytes(fromHex(utxo.datum)); + bucket.push(plutusData); + const data = C.Data.new(plutusData); + bucket.push(data); + const datum = C.Datum.new_data(data); + bucket.push(datum); + output.set_datum(datum); } if (utxo.scriptRef) { - output.set_script_ref(toScriptRef(utxo.scriptRef)); + const scriptRef = toScriptRef(utxo.scriptRef); + bucket.push(scriptRef); + output.set_script_ref(scriptRef); } - return C.TransactionUnspentOutput.new( - C.TransactionInput.new( - C.TransactionHash.from_bytes(fromHex(utxo.txHash)), - C.BigNum.from_str(utxo.outputIndex.toString()) - ), - output - ); + const hash = C.TransactionHash.from_bytes(fromHex(utxo.txHash)); + bucket.push(hash); + const index = C.BigNum.from_str(utxo.outputIndex.toString()); + bucket.push(index); + const input = C.TransactionInput.new(hash, index); + bucket.push(input); + const coreUtxo = C.TransactionUnspentOutput.new(input, output); + + Freeables.free(...bucket); + return coreUtxo; } export function coreToUtxo(coreUtxo: C.TransactionUnspentOutput): UTxO { - const datum = coreUtxo.output()?.datum()?.as_data()?.get(); - const datumHash = coreUtxo.output()?.datum()?.as_data_hash()?.to_hex(); + const bucket: FreeableBucket = []; + const input = coreUtxo.input(); + bucket.push(input); + const output = coreUtxo.output(); + bucket.push(output); - return { - txHash: toHex(coreUtxo.input().transaction_id().to_bytes()), - outputIndex: parseInt(coreUtxo.input().index().to_str()), - assets: valueToAssets(coreUtxo.output().amount()), - address: coreUtxo.output().address().as_byron() - ? coreUtxo.output().address().as_byron()?.to_base58()! - : coreUtxo.output().address().to_bech32(undefined), - datumHash: datum ? C.hash_plutus_data(datum).to_hex() : datumHash, - datum: datum && toHex(datum.to_bytes()), - scriptRef: - coreUtxo.output()?.script_ref() && - fromScriptRef(coreUtxo.output().script_ref()!), + const txId = input.transaction_id(); + bucket.push(txId); + const txHash = toHex(txId.to_bytes()); + + const index = input.index(); + bucket.push(index); + const outputIndex = parseInt(index.to_str()); + + const amount = output.amount(); + bucket.push(amount); + const assets = valueToAssets(amount); + + const cAddress = output.address(); + bucket.push(cAddress); + const byronAddress = cAddress.as_byron(); + bucket.push(byronAddress); + const address = byronAddress + ? byronAddress.to_base58() + : cAddress.to_bech32(undefined); + + const cDatum = output.datum(); + bucket.push(cDatum); + const dataHash = cDatum?.as_data_hash(); + bucket.push(dataHash); + const datumHash = dataHash?.to_hex(); + + const cDatumData = cDatum?.as_data(); + bucket.push(cDatumData); + const plutusData = cDatumData?.get(); + bucket.push(plutusData); + const datum = plutusData && toHex(plutusData.to_bytes()); + const cScriptRef = output.script_ref(); + bucket.push(cScriptRef); + const scriptRef = cScriptRef && fromScriptRef(cScriptRef); + const utxo = { + txHash, + outputIndex, + assets, + address, + datumHash, + datum, + scriptRef, }; + + Freeables.free(...bucket); + return utxo; } export function networkToId(network: Network): number { @@ -626,7 +900,12 @@ export function fromText(text: string): string { } export function toPublicKey(privateKey: PrivateKey): PublicKey { - return C.PrivateKey.from_bech32(privateKey).to_public().to_bech32(); + const sKey = C.PrivateKey.from_bech32(privateKey); + const vKey = sKey.to_public(); + const bech32 = vKey.to_bech32(); + Freeables.free(sKey, vKey); + + return bech32; } /** Padded number in Hex. */ @@ -637,7 +916,7 @@ function checksum(num: string): string { export function toLabel(num: number): string { if (num < 0 || num > 65535) { throw new Error( - `Label ${num} out of range: min label 1 - max label 65535.` + `Label ${num} out of range: min label 1 - max label 65535.`, ); } const numHex = num.toString(16).padStart(4, "0"); @@ -660,7 +939,7 @@ export function fromLabel(label: string): number | null { export function toUnit( policyId: PolicyId, name?: string | null, - label?: number | null + label?: number | null, ): Unit { const hexLabel = Number.isInteger(label) ? toLabel(label!) : ""; const n = name ? name : ""; @@ -698,31 +977,36 @@ export function fromUnit(unit: Unit): { * It follows this Json format: https://github.com/input-output-hk/cardano-node/blob/master/doc/reference/simple-scripts.md */ export function nativeScriptFromJson(nativeScript: NativeScript): Script { + const cNativeScript = C.encode_json_str_to_native_script( + JSON.stringify(nativeScript), + "", + C.ScriptSchema.Node, + ); + const script = toHex(cNativeScript.to_bytes()); + cNativeScript.free(); + return { type: "Native", - script: toHex( - C.encode_json_str_to_native_script( - JSON.stringify(nativeScript), - "", - C.ScriptSchema.Node - ).to_bytes() - ), + script, }; } export function applyParamsToScript( plutusScript: string, params: Exact<[...T]>, - type?: T + type?: T, ): string { const p = (type ? Data.castTo(params, type) : params) as Data[]; - return toHex( - C.apply_params_to_plutus_script( - C.PlutusList.from_bytes(fromHex(Data.to(p))), - - C.PlutusScript.from_bytes(fromHex(applyDoubleCborEncoding(plutusScript))) - ).to_bytes() + // cPlutusScript ownership is passed to rust, so don't free + const cPlutusScript = C.PlutusScript.from_bytes( + fromHex(applyDoubleCborEncoding(plutusScript)), ); + const cParams = C.PlutusList.from_bytes(fromHex(Data.to(p))); + const cScript = C.apply_params_to_plutus_script(cParams, cPlutusScript); + const script = toHex(cScript.to_bytes()); + Freeables.free(cParams, cScript); + + return script; } export const chunk = (array: T[], size: number) => { @@ -742,11 +1026,14 @@ export const chunk = (array: T[], size: number) => { export function applyDoubleCborEncoding(script: string): string { try { C.PlutusScript.from_bytes( - C.PlutusScript.from_bytes(fromHex(script)).bytes() + C.PlutusScript.from_bytes(fromHex(script)).bytes(), ); return script; } catch (_e) { - return toHex(C.PlutusScript.new(fromHex(script)).to_bytes()); + const plutusScript = C.PlutusScript.new(fromHex(script)); + const bytes = plutusScript.to_bytes(); + plutusScript.free(); + return toHex(bytes); } } diff --git a/tests/mod.test.ts b/tests/mod.test.ts index 18cf8cd2..38c912bd 100644 --- a/tests/mod.test.ts +++ b/tests/mod.test.ts @@ -42,53 +42,14 @@ const slotConfig = SLOT_CONFIG_NETWORK[lucid.network]; const protocolParameters = PROTOCOL_PARAMETERS_DEFAULT; lucid.protocolParameters = protocolParameters; - -lucid.txBuilderConfig = C.TransactionBuilderConfigBuilder.new() - .coins_per_utxo_byte( - C.BigNum.from_str(protocolParameters.coinsPerUtxoByte.toString()), - ) - .fee_algo( - C.LinearFee.new( - C.BigNum.from_str(protocolParameters.minFeeA.toString()), - C.BigNum.from_str(protocolParameters.minFeeB.toString()), - ), - ) - .key_deposit( - C.BigNum.from_str(protocolParameters.keyDeposit.toString()), - ) - .pool_deposit( - C.BigNum.from_str(protocolParameters.poolDeposit.toString()), - ) - .max_tx_size(protocolParameters.maxTxSize) - .max_value_size(protocolParameters.maxValSize) - .collateral_percentage(protocolParameters.collateralPercentage) - .max_collateral_inputs(protocolParameters.maxCollateralInputs) - .max_tx_ex_units( - C.ExUnits.new( - C.BigNum.from_str(protocolParameters.maxTxExMem.toString()), - C.BigNum.from_str(protocolParameters.maxTxExSteps.toString()), - ), - ) - .ex_unit_prices( - C.ExUnitPrices.from_float( - protocolParameters.priceMem, - protocolParameters.priceStep, - ), - ) - .slot_config( - C.BigNum.from_str(slotConfig.zeroTime.toString()), - C.BigNum.from_str(slotConfig.zeroSlot.toString()), - slotConfig.slotLength, - ) - .costmdls(createCostModels(protocolParameters.costModels)) - .build(); +lucid.slotConfig = slotConfig; lucid.selectWalletFromPrivateKey(privateKey); Deno.test("PaymentKeyHash length", async () => { const lucid = await initLucid(); const { paymentCredential } = lucid.utils.getAddressDetails( - await lucid.wallet.address() + await lucid.wallet.address(), ); if (paymentCredential) { assertEquals(fromHex(paymentCredential.hash).length, 28); @@ -103,7 +64,7 @@ Deno.test("Address type", async () => { address: { bech32 }, } = lucid.utils.getAddressDetails(await lucid.wallet.address()); const enterpriseAddress = C.EnterpriseAddress.from_address( - C.Address.from_bech32(bech32) + C.Address.from_bech32(bech32), )! .to_address() .to_bech32(undefined); @@ -114,7 +75,7 @@ Deno.test("Address type", async () => { Deno.test("No reward address", async () => { const lucid = await initLucid(); const { stakeCredential } = lucid.utils.getAddressDetails( - await lucid.wallet.address() + await lucid.wallet.address(), ); assertEquals(stakeCredential, undefined); assertEquals(await lucid.wallet.rewardAddress(), null); @@ -141,12 +102,12 @@ Deno.test("Wallet from utxos roundtrip (legacy utxos)", async () => { address: "addr_test1qzfauplclmk6fxuncn8adqt7hnahhlz2pvvzxlqpj6eqtk35g6en4e2aya53ewldpqxl2xpzvtps0ndtvtf6fzpl880srm02gc", utxos: rawUtxos.map((raw) => - coreToUtxo(C.TransactionUnspentOutput.from_bytes(fromHex(raw))) + coreToUtxo(C.TransactionUnspentOutput.from_bytes(fromHex(raw))), ), }); const rawUtxos_ = (await lucid.wallet.getUtxos()).map((utxo) => - toHex(utxoToCore(utxo).to_legacy_bytes()) + toHex(utxoToCore(utxo).to_legacy_bytes()), ); assertEquals(rawUtxos, rawUtxos_); @@ -154,7 +115,7 @@ Deno.test("Wallet from utxos roundtrip (legacy utxos)", async () => { Deno.test("Construct plutus data", () => { const data = Data.to( - new Constr(1, [BigInt(1), "abcd", "deff", new Constr(0, [])]) + new Constr(1, [BigInt(1), "abcd", "deff", new Constr(0, [])]), ); assertEquals(data, "d87a9f0142abcd42deffd87980ff"); @@ -319,26 +280,26 @@ Deno.test("Assets/value conversion property test", () => { fc.tuple( fc.uint8Array({ minLength: 28, maxLength: 28 }), fc.uint8Array({ minLength: 0, maxLength: 32 }), - fc.bigInt({ min: 0n, max: 18446744073709551615n }) - ) + fc.bigInt({ min: 0n, max: 18446744073709551615n }), + ), ), fc.bigInt({ min: 0n, max: 18446744073709551615n }), ( assetsArray: Array<[Uint8Array, Uint8Array, bigint]>, - lovelace: bigint + lovelace: bigint, ) => { const assets: Assets = assetsArray.reduce( (acc, asset) => ({ ...acc, [toHex(asset[0]) + toHex(asset[1])]: asset[2], }), - {} + {}, ); assets.lovelace = lovelace; assertEquals(assets, valueToAssets(assetsToValue(assets))); - } - ) + }, + ), ); }); @@ -363,10 +324,10 @@ Deno.test("Merkle tree property test", () => { assert(MerkleTree.verify(data[index], rootHash, proof)); assertEquals( merkleTree.size(), - Math.max(0, data.length + (data.length - 1)) + Math.max(0, data.length + (data.length - 1)), ); - } - ) + }, + ), ); }); @@ -388,7 +349,7 @@ Deno.test("JSON Metadata to CBOR Datum", () => { const cborDatum = Data.to( Data.fromJson({ test: 123, - }) + }), ); assertEquals(cborDatum, "a14474657374187b"); }); @@ -413,7 +374,7 @@ Deno.test("toLabel/fromLabel property test", () => { } else { assertEquals(n, fromLabel(toLabel(n))); } - }) + }), ); }); @@ -433,8 +394,8 @@ Deno.test("toUnit/fromUnit property test", () => { name, label, }); - } - ) + }, + ), ); }); @@ -442,58 +403,77 @@ Deno.test("Preserve task/transaction order", async () => { lucid.selectWalletFrom({ address: "addr_test1qq90qrxyw5qtkex0l7mc86xy9a6xkn5t3fcwm6wq33c38t8nhh356yzp7k3qwmhe4fk0g5u6kx5ka4rz5qcq4j7mvh2sts2cfa", - utxos: [{ - txHash: - "2eefc93bc0dda80e78890f1f965733239e1f64f76555e8dcde1a4aa7db67b129", - outputIndex: 3, - assets: { lovelace: 6770556044n }, - address: - "addr_test1qq90qrxyw5qtkex0l7mc86xy9a6xkn5t3fcwm6wq33c38t8nhh356yzp7k3qwmhe4fk0g5u6kx5ka4rz5qcq4j7mvh2sts2cfa", - datumHash: null, - datum: null, - scriptRef: null, - }], + utxos: [ + { + txHash: + "2eefc93bc0dda80e78890f1f965733239e1f64f76555e8dcde1a4aa7db67b129", + outputIndex: 3, + assets: { lovelace: 6770556044n }, + address: + "addr_test1qq90qrxyw5qtkex0l7mc86xy9a6xkn5t3fcwm6wq33c38t8nhh356yzp7k3qwmhe4fk0g5u6kx5ka4rz5qcq4j7mvh2sts2cfa", + datumHash: null, + datum: null, + scriptRef: null, + }, + ], }); - const txCompA = lucid.newTx().payToAddressWithData( - await lucid.wallet.address(), - { inline: Data.to(0n) }, - {}, - ); + const txCompA = lucid + .newTx() + .payToAddressWithData( + await lucid.wallet.address(), + { inline: Data.to(0n) }, + {}, + ); - const txCompB = lucid.newTx() + const txCompB = lucid + .newTx() .payToAddressWithData( await lucid.wallet.address(), { inline: Data.to(10n) }, {}, ) .compose( - lucid.newTx().payToAddressWithData( - await lucid.wallet.address(), - { inline: Data.to(1n) }, - {}, - ).compose( - lucid.newTx().payToAddressWithData( + lucid + .newTx() + .payToAddressWithData( await lucid.wallet.address(), - { inline: Data.to(2n) }, + { inline: Data.to(1n) }, {}, + ) + .compose( + lucid + .newTx() + .payToAddressWithData( + await lucid.wallet.address(), + { inline: Data.to(2n) }, + {}, + ), ), - ), ); - const tx = await lucid.newTx() + const tx = await lucid + .newTx() .compose(txCompA) .compose(txCompB) .payToAddressWithData( await lucid.wallet.address(), { inline: Data.to(3n) }, {}, - ).complete(); + ) + .complete(); [0n, 10n, 1n, 2n, 3n].forEach((num, i) => { const outputNum = BigInt( - tx.txComplete.body().outputs().get(i).datum()?.as_data()?.get() - .as_integer()?.to_str()!, + tx.txComplete + .body() + .outputs() + .get(i) + .datum() + ?.as_data() + ?.get() + .as_integer() + ?.to_str()!, ); assertEquals(num, outputNum); });