From a549b40efcb1871b95fbf44d215931766b8762bf Mon Sep 17 00:00:00 2001 From: Joaquin Hoyos Date: Tue, 1 Aug 2023 10:43:43 -0300 Subject: [PATCH] fix: update emulator logic branch --- dist/esm/src/lucid/lucid.js | 8 +-- dist/package-lock.json | 122 +++++++++++++++++++++++++++++++++++- dist/src/src/lucid/lucid.ts | 9 ++- dist/web/mod.js | 2 +- src/lucid/lucid.ts | 9 ++- 5 files changed, 134 insertions(+), 16 deletions(-) diff --git a/dist/esm/src/lucid/lucid.js b/dist/esm/src/lucid/lucid.js index 7b92095f..12b0f831 100644 --- a/dist/esm/src/lucid/lucid.js +++ b/dist/esm/src/lucid/lucid.js @@ -56,10 +56,6 @@ export class Lucid { } if (provider) { lucid.provider = provider; - } - if (provider && !protocolParameters) { - const protocolParams = await provider.getProtocolParameters(); - lucid.protocolParameters = protocolParams; if (lucid.provider instanceof Emulator) { lucid.network = "Custom"; SLOT_CONFIG_NETWORK[lucid.network] = { @@ -69,6 +65,10 @@ 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() diff --git a/dist/package-lock.json b/dist/package-lock.json index 64ed13ea..3fd603f1 100644 --- a/dist/package-lock.json +++ b/dist/package-lock.json @@ -1,7 +1,7 @@ { "name": "@jpg-store/lucid-cardano", "version": "0.10.10", - "lockfileVersion": 3, + "lockfileVersion": 2, "requires": true, "packages": { "": { @@ -203,5 +203,125 @@ } } } + }, + "dependencies": { + "@peculiar/asn1-schema": { + "version": "2.3.6", + "resolved": "https://registry.npmjs.org/@peculiar/asn1-schema/-/asn1-schema-2.3.6.tgz", + "integrity": "sha512-izNRxPoaeJeg/AyH8hER6s+H7p4itk+03QCa4sbxI3lNdseQYCuxzgsuNK8bTXChtLTjpJz6NmXKA73qLa3rCA==", + "requires": { + "asn1js": "^3.0.5", + "pvtsutils": "^1.3.2", + "tslib": "^2.4.0" + } + }, + "@peculiar/json-schema": { + "version": "1.1.12", + "resolved": "https://registry.npmjs.org/@peculiar/json-schema/-/json-schema-1.1.12.tgz", + "integrity": "sha512-coUfuoMeIB7B8/NMekxaDzLhaYmp0HZNPEjYRm9goRou8UZIC3z21s0sL9AWoCw4EG876QyO3kYrc61WNF9B/w==", + "requires": { + "tslib": "^2.0.0" + } + }, + "@peculiar/webcrypto": { + "version": "1.4.3", + "resolved": "https://registry.npmjs.org/@peculiar/webcrypto/-/webcrypto-1.4.3.tgz", + "integrity": "sha512-VtaY4spKTdN5LjJ04im/d/joXuvLbQdgy5Z4DXF4MFZhQ+MTrejbNMkfZBp1Bs3O5+bFqnJgyGdPuZQflvIa5A==", + "requires": { + "@peculiar/asn1-schema": "^2.3.6", + "@peculiar/json-schema": "^1.1.12", + "pvtsutils": "^1.3.2", + "tslib": "^2.5.0", + "webcrypto-core": "^1.7.7" + } + }, + "asn1js": { + "version": "3.0.5", + "resolved": "https://registry.npmjs.org/asn1js/-/asn1js-3.0.5.tgz", + "integrity": "sha512-FVnvrKJwpt9LP2lAMl8qZswRNm3T4q9CON+bxldk2iwk3FFpuwhx2FfinyitizWHsVYyaY+y5JzDR0rCMV5yTQ==", + "requires": { + "pvtsutils": "^1.3.2", + "pvutils": "^1.1.3", + "tslib": "^2.4.0" + } + }, + "data-uri-to-buffer": { + "version": "4.0.1", + "resolved": "https://registry.npmjs.org/data-uri-to-buffer/-/data-uri-to-buffer-4.0.1.tgz", + "integrity": "sha512-0R9ikRb668HB7QDxT1vkpuUBtqc53YyAwMwGeUFKRojY/NWKvdZ+9UYtRfGmhqNbRkTSVpMbmyhXipFFv2cb/A==" + }, + "fetch-blob": { + "version": "3.2.0", + "resolved": "https://registry.npmjs.org/fetch-blob/-/fetch-blob-3.2.0.tgz", + "integrity": "sha512-7yAQpD2UMJzLi1Dqv7qFYnPbaPx7ZfFK6PiIxQ4PfkGPyNyl2Ugx+a/umUonmKqjhM4DnfbMvdX6otXq83soQQ==", + "requires": { + "node-domexception": "^1.0.0", + "web-streams-polyfill": "^3.0.3" + } + }, + "formdata-polyfill": { + "version": "4.0.10", + "resolved": "https://registry.npmjs.org/formdata-polyfill/-/formdata-polyfill-4.0.10.tgz", + "integrity": "sha512-buewHzMvYL29jdeQTVILecSaZKnt/RJWjoZCF5OW60Z67/GmSLBkOFM7qh1PI3zFNtJbaZL5eQu1vLfazOwj4g==", + "requires": { + "fetch-blob": "^3.1.2" + } + }, + "node-domexception": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/node-domexception/-/node-domexception-1.0.0.tgz", + "integrity": "sha512-/jKZoMpw0F8GRwl4/eLROPA3cfcXtLApP0QzLmUT/HuPCZWyB7IY9ZrMeKw2O/nFIqPQB3PVM9aYm0F312AXDQ==" + }, + "node-fetch": { + "version": "3.3.2", + "resolved": "https://registry.npmjs.org/node-fetch/-/node-fetch-3.3.2.tgz", + "integrity": "sha512-dRB78srN/l6gqWulah9SrxeYnxeddIG30+GOqK/9OlLVyLg3HPnr6SqOWTWOXKRwC2eGYCkZ59NNuSgvSrpgOA==", + "requires": { + "data-uri-to-buffer": "^4.0.0", + "fetch-blob": "^3.1.4", + "formdata-polyfill": "^4.0.10" + } + }, + "pvtsutils": { + "version": "1.3.2", + "resolved": "https://registry.npmjs.org/pvtsutils/-/pvtsutils-1.3.2.tgz", + "integrity": "sha512-+Ipe2iNUyrZz+8K/2IOo+kKikdtfhRKzNpQbruF2URmqPtoqAs8g3xS7TJvFF2GcPXjh7DkqMnpVveRFq4PgEQ==", + "requires": { + "tslib": "^2.4.0" + } + }, + "pvutils": { + "version": "1.1.3", + "resolved": "https://registry.npmjs.org/pvutils/-/pvutils-1.1.3.tgz", + "integrity": "sha512-pMpnA0qRdFp32b1sJl1wOJNxZLQ2cbQx+k6tjNtZ8CpvVhNqEPRgivZ2WOUev2YMajecdH7ctUPDvEe87nariQ==" + }, + "tslib": { + "version": "2.6.1", + "resolved": "https://registry.npmjs.org/tslib/-/tslib-2.6.1.tgz", + "integrity": "sha512-t0hLfiEKfMUoqhG+U1oid7Pva4bbDPHYfJNiB7BiIjRkj1pyC++4N3huJfqY6aRH6VTB0rvtzQwjM4K6qpfOig==" + }, + "web-streams-polyfill": { + "version": "3.2.1", + "resolved": "https://registry.npmjs.org/web-streams-polyfill/-/web-streams-polyfill-3.2.1.tgz", + "integrity": "sha512-e0MO3wdXWKrLbL0DgGnUV7WHVuw9OUvL4hjgnPkIeEvESk74gAITi5G606JtZPp39cd8HA9VQzCIvA49LpPN5Q==" + }, + "webcrypto-core": { + "version": "1.7.7", + "resolved": "https://registry.npmjs.org/webcrypto-core/-/webcrypto-core-1.7.7.tgz", + "integrity": "sha512-7FjigXNsBfopEj+5DV2nhNpfic2vumtjjgPmeDKk45z+MJwXKKfhPB7118Pfzrmh4jqOMST6Ch37iPAHoImg5g==", + "requires": { + "@peculiar/asn1-schema": "^2.3.6", + "@peculiar/json-schema": "^1.1.12", + "asn1js": "^3.0.1", + "pvtsutils": "^1.3.2", + "tslib": "^2.4.0" + } + }, + "ws": { + "version": "8.13.0", + "resolved": "https://registry.npmjs.org/ws/-/ws-8.13.0.tgz", + "integrity": "sha512-x9vcZYTrFPC7aSIbj7sRCYo7L/Xb8Iy+pW0ng0wt2vCJv7M9HOMy0UoN3rr+IFC7hb7vXoqS+P9ktyLLLhO+LA==", + "requires": {} + } } } diff --git a/dist/src/src/lucid/lucid.ts b/dist/src/src/lucid/lucid.ts index e79e8739..072c13fb 100644 --- a/dist/src/src/lucid/lucid.ts +++ b/dist/src/src/lucid/lucid.ts @@ -68,11 +68,6 @@ export class Lucid { } if (provider) { lucid.provider = provider; - } - if (provider && !protocolParameters) { - const protocolParams = await provider.getProtocolParameters(); - lucid.protocolParameters = protocolParams; - if (lucid.provider instanceof Emulator) { lucid.network = "Custom"; SLOT_CONFIG_NETWORK[lucid.network] = { @@ -82,6 +77,10 @@ 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() diff --git a/dist/web/mod.js b/dist/web/mod.js index 76ac5245..5c4b3945 100644 --- a/dist/web/mod.js +++ b/dist/web/mod.js @@ -11,4 +11,4 @@ It does not exist or was already spent.`);let{paymentCredential:P}=D(b.utxo.addr `);for(let[r,a]of Object.entries(s)){console.log(`Address: %c${r}`,"color:blue",` `);for(let[i,u]of Object.entries(a)){let c=Math.max(Math.floor(60*(Number(u)/Number(t[i]))),1);console.log(`%c${"\u2586".repeat(c)+" ".repeat(60-c)}`,`color: ${e(i)}`,"",`${i}:`,u,"")}console.log(` ${"\u2581".repeat(60)} -`)}}};var $e=class{constructor(){Object.defineProperty(this,"protocolParameters",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"txBuilderConfig",{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),e&&!s){let a=await e.getProtocolParameters();r.protocolParameters=a,r.provider instanceof Re&&(r.network="Custom",be[r.network]={zeroTime:r.provider.now(),zeroSlot:0,slotLength:1e3})}if(r.protocolParameters){let a=be[r.network];r.txBuilderConfig=o.TransactionBuilderConfigBuilder.new().coins_per_utxo_byte(o.BigNum.from_str(r.protocolParameters.coinsPerUtxoByte.toString())).fee_algo(o.LinearFee.new(o.BigNum.from_str(r.protocolParameters.minFeeA.toString()),o.BigNum.from_str(r.protocolParameters.minFeeB.toString()))).key_deposit(o.BigNum.from_str(r.protocolParameters.keyDeposit.toString())).pool_deposit(o.BigNum.from_str(r.protocolParameters.poolDeposit.toString())).max_tx_size(r.protocolParameters.maxTxSize).max_value_size(r.protocolParameters.maxValSize).collateral_percentage(r.protocolParameters.collateralPercentage).max_collateral_inputs(r.protocolParameters.maxCollateralInputs).max_tx_ex_units(o.ExUnits.new(o.BigNum.from_str(r.protocolParameters.maxTxExMem.toString()),o.BigNum.from_str(r.protocolParameters.maxTxExSteps.toString()))).ex_unit_prices(o.ExUnitPrices.from_float(r.protocolParameters.priceMem,r.protocolParameters.priceStep)).slot_config(o.BigNum.from_str(a.zeroTime.toString()),o.BigNum.from_str(a.zeroSlot.toString()),a.slotLength).blockfrost(o.Blockfrost.new((e?.url||"")+"/utils/txs/evaluate",e?.projectId||"")).costmdls(Qe(r.protocolParameters.costModels)).build()}return r.utils=new Pe(r),r}async switchProvider(e,t){if(this.network==="Custom")throw new Error("Cannot switch when on custom network.");let s=await $e.new(e,t);return this.txBuilderConfig=s.txBuilderConfig,this.provider=e||this.provider,this.network=t||this.network,this.wallet=s.wallet,this}newTx(){return new De(this)}fromTx(e){return new _e(this,o.Transaction.from_bytes(d(e)))}newMessage(e,t){return new Me(this,e,t)}verifyMessage(e,t,s){let{paymentCredential:r,stakeCredential:a,address:{hex:i}}=this.utils.getAddressDetails(e),u=r?.hash||a?.hash;if(!u)throw new Error("Not a valid address provided.");return At(i,u,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 ee.from(e.datum,t)}async metadataOf(e){let{policyId:t,name:s,label:r}=Ce(e);switch(r){case 222:case 333:case 444:{let a=await this.utxoByUnit(Ct(t,s,100)),i=await this.datumOf(a);return ee.toJson(i.fields[0])}default:throw new Error("No variant matched.")}}selectWalletFromPrivateKey(e){let t=o.PrivateKey.from_bech32(e),s=t.to_public().hash();return this.wallet={address:async()=>o.EnterpriseAddress.new(this.network==="Mainnet"?1:0,o.StakeCredential.from_keyhash(s)).to_address().to_bech32(void 0),rewardAddress:async()=>null,getCollateralCore:()=>{},getUtxos:async()=>await this.utxosAt(ie(await this.wallet.address())),getUtxosCore:async()=>{let r=await this.utxosAt(ie(await this.wallet.address())),a=o.TransactionUnspentOutputs.new();return r.forEach(i=>{a.add(ue(i))}),a},getDelegation:async()=>({poolId:null,rewards:0n}),signTx:async r=>{let a=o.make_vkey_witness(o.hash_transaction(r.body()),t),i=o.TransactionWitnessSetBuilder.new();return i.add_vkey(a),i.build()},signMessage:async(r,a)=>{let{paymentCredential:i,address:{hex:u}}=this.utils.getAddressDetails(r),c=i?.hash,m=s.to_hex();if(!c||c!==m)throw new Error(`Cannot sign message for address: ${r}.`);return Ie(u,a,e)},submitTx:async r=>await this.provider.submitTx(r)},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()=>o.Address.from_bytes(d(await t())).to_bech32(void 0),rewardAddress:async()=>{let[s]=await e.getRewardAddresses();return s?o.RewardAddress.from_address(o.Address.from_bytes(d(s))).to_address().to_bech32(void 0):null},getCollateralCore:()=>{},getUtxos:async()=>(await e.getUtxos()||[]).map(r=>{let a=o.TransactionUnspentOutput.from_bytes(d(r));return Oe(a)}),getUtxosCore:async()=>{let s=o.TransactionUnspentOutputs.new();return(await e.getUtxos()||[]).forEach(r=>{s.add(o.TransactionUnspentOutput.from_bytes(d(r)))}),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(y(s.to_bytes()),!0);return o.TransactionWitnessSet.from_bytes(d(r))},signMessage:async(s,r)=>{let a=y(o.Address.from_bech32(s).to_bytes());return await e.signData(a,r)},submitTx:async s=>await e.submitTx(s)},this}selectWalletFrom({address:e,utxos:t,rewardAddress:s,collateral:r}){let a=this.utils.getAddressDetails(e);return this.wallet={address:async()=>e,rewardAddress:async()=>(!s&&a.stakeCredential?(()=>a.stakeCredential.type==="Key"?o.RewardAddress.new(this.network==="Mainnet"?1:0,o.StakeCredential.from_keyhash(o.Ed25519KeyHash.from_hex(a.stakeCredential.hash))).to_address().to_bech32(void 0):o.RewardAddress.new(this.network==="Mainnet"?1:0,o.StakeCredential.from_scripthash(o.ScriptHash.from_hex(a.stakeCredential.hash))).to_address().to_bech32(void 0))():s)||null,getCollateralCore:()=>{if(!r||!r.length)return;let i=o.TransactionUnspentOutputs.new();return r.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:s,rewardAddress:r,paymentKey:a,stakeKey:i}=Pt(e,{addressType:t?.addressType||"Base",accountIndex:t?.accountIndex||0,password:t?.password,network:this.network}),u=o.PrivateKey.from_bech32(a).to_public().hash().to_hex(),c=i?o.PrivateKey.from_bech32(i).to_public().hash().to_hex():"",m={[u]:a,[c]:i};return this.wallet={address:async()=>s,rewardAddress:async()=>r||null,getCollateralCore:()=>{},getUtxos:async()=>this.utxosAt(ie(s)),getUtxosCore:async()=>{let p=o.TransactionUnspentOutputs.new();return(await this.utxosAt(ie(s))).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(s),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 Ht=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:V}}).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"))(),s=[],r=1;for(;;){let a=await fetch(`${this.url}/addresses/${t}/utxos?page=${r}`,{headers:{project_id:this.projectId,lucid:V}}).then(i=>i.json());if(a.error){if(a.status_code===404)return[];throw new Error("Could not fetch UTxOs from Blockfrost. Try again.")}if(s=s.concat(a),a.length<=0)break;r++}return this.blockfrostUtxosToUtxos(s)}async getUtxosWithUnit(e,t){let s=(()=>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=[],a=1;for(;;){let i=await fetch(`${this.url}/addresses/${s}/utxos/${t}?page=${a}`,{headers:{project_id:this.projectId,lucid:V}}).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(r=r.concat(i),i.length<=0)break;a++}return this.blockfrostUtxosToUtxos(r)}async getUtxoByUnit(e){let t=await fetch(`${this.url}/assets/${e}/addresses?count=2`,{headers:{project_id:this.projectId,lucid:V}}).then(a=>a.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 a=await fetch(`${this.url}/txs/${r}/utxos`,{headers:{project_id:this.projectId,lucid:V}}).then(u=>u.json());if(!a||a.error)return[];let i=a.outputs.map(u=>({...u,tx_hash:r}));return this.blockfrostUtxosToUtxos(i)}))).reduce((r,a)=>r.concat(a),[]).filter(r=>e.some(a=>r.txHash===a.txHash&&r.outputIndex===a.outputIndex))}async getDelegation(e){let t=await fetch(`${this.url}/accounts/${e}`,{headers:{project_id:this.projectId,lucid:V}}).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:V}}).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 a=await fetch(`${this.url}/txs/${e}`,{headers:{project_id:this.projectId,lucid:V}}).then(i=>i.json());if(a&&!a.error)return clearInterval(r),await new Promise(i=>setTimeout(()=>i(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:V},body:d(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:V}}).then(a=>a.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:V}}).then(a=>a.json());return{type:s==="plutusV1"?"PlutusV1":"PlutusV2",script:q(r)}})():void 0})))}};function Vs(n){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 s=o.PlutusMap.new();return t.map.forEach(({k:r,v:a})=>{s.insert(e(r),e(a))}),o.PlutusData.new_map(s)}else if(t.list){let s=o.PlutusList.new();return t.list.forEach(r=>{s.add(e(r))}),o.PlutusData.new_list(s)}else if(!isNaN(t.constructor)){let s=o.PlutusList.new();return t.fields.forEach(r=>{s.add(e(r))}),o.PlutusData.new_constr_plutus_data(o.ConstrPlutusData.new(o.BigNum.from_str(t.constructor.toString()),s))}}else return o.PlutusData.new_integer(o.BigInt.from_str(t.int.toString()));throw new Error("Unsupported type")};return y(e(n).to_bytes())}var V=ge.version;var Ut=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:a}=JSON.parse(r.data),i={};Object.keys(a.costModels).forEach(C=>{let h="Plutus"+C.split(":")[1].toUpperCase();i[h]=a.costModels[C]});let[u,c]=a.prices.memory.split("/"),[m,p]=a.prices.steps.split("/");t({minFeeA:parseInt(a.minFeeCoefficient),minFeeB:parseInt(a.minFeeConstant),maxTxSize:parseInt(a.maxTxSize),maxValSize:parseInt(a.maxValueSize),keyDeposit:BigInt(a.stakeKeyDeposit),poolDeposit:BigInt(a.poolDeposit),priceMem:parseInt(u)/parseInt(c),priceStep:parseInt(m)/parseInt(p),maxTxExMem:BigInt(a.maxExecutionUnitsPerTransaction.memory),maxTxExSteps:BigInt(a.maxExecutionUnitsPerTransaction.steps),coinsPerUtxoByte:BigInt(a.coinsPerUtxoByte),collateralPercentage:parseInt(a.collateralPercentage),maxCollateralInputs:parseInt(a.maxCollateralInputs),costModels:i}),e.close()}catch(a){s(a)}},{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(a=>a.json());return this.kupmiosUtxosToUtxos(r)}async getUtxosWithUnit(e,t){let s=typeof e=="string",r=s?e:e.hash,{policyId:a,assetName:i}=Ce(t),u=await fetch(`${this.kupoUrl}/matches/${r}${s?"":"/*"}?unspent&policy_id=${a}${i?`&asset_name=${i}`:""}`).then(c=>c.json());return this.kupmiosUtxosToUtxos(u)}async getUtxoByUnit(e){let{policyId:t,assetName:s}=Ce(e),r=await fetch(`${this.kupoUrl}/matches/${t}.${s?`${s}`:"*"}?unspent`).then(i=>i.json()),a=await this.kupmiosUtxosToUtxos(r);if(a.length>1)throw new Error("Unit needs to be an NFT or only held by one address.");return a[0]}async getUtxosByOutRef(e){let t=[...new Set(e.map(r=>r.txHash))];return(await Promise.all(t.map(async r=>{let a=await fetch(`${this.kupoUrl}/matches/*@${r}?unspent`).then(i=>i.json());return this.kupmiosUtxosToUtxos(a)}))).reduce((r,a)=>r.concat(a),[]).filter(r=>e.some(a=>r.txHash===a.txHash&&r.outputIndex===a.outputIndex))}async getDelegation(e){let t=await this.ogmiosWsp("Query",{query:{delegationsAndRewards:[e]}});return new Promise((s,r)=>{t.addEventListener("message",a=>{try{let{result:i}=JSON.parse(a.data),u=i?Object.values(i)[0]:{};s({poolId:u?.delegate||null,rewards:BigInt(u?.rewards||0)}),t.close()}catch(i){r(i)}},{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 a=await fetch(`${this.kupoUrl}/matches/*@${e}?unspent`).then(i=>i.json());if(a&&a.length>0)return clearInterval(r),await new Promise(i=>setTimeout(()=>i(1),1e3)),s(!0)},t)})}async submitTx(e){let t=await this.ogmiosWsp("SubmitTx",{submit:e});return new Promise((s,r)=>{t.addEventListener("message",a=>{try{let{result:i}=JSON.parse(a.data);i.SubmitSuccess?s(i.SubmitSuccess.txId):r(i.SubmitFail),t.close()}catch(i){r(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 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(a=>a.json());if(r==="native")return{type:"Native",script:s};if(r==="plutus:v1")return{type:"PlutusV1",script:y(o.PlutusScript.new(d(s)).to_bytes())};if(r==="plutus:v2")return{type:"PlutusV2",script:y(o.PlutusScript.new(d(s)).to_bytes())}})()})))}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 jt=class{constructor(e,t=""){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}),this.url=e.slice(-1)==="/"?e.slice(0,-1):e,this.apiKey=t}async getProtocolParameters(){let e=await fetch(`${this.url}/protocol-params`,{headers:this.commonHeaders()}).then(r=>r.json()),t=r=>{let a=r.indexOf("/");return parseInt(r.slice(0,a))/parseInt(r.slice(a+1))},s=(r,a)=>{let i=Object.keys(r).map(u=>({[a[u]||u]:Object.fromEntries(Object.entries(r[u]).sort(([m,p],[C,E])=>m.localeCompare(C)))}));return Object.assign({},...i)};return{minFeeA:parseInt(e.min_fee_coefficient),minFeeB:parseInt(e.min_fee_constant),maxTxSize:parseInt(e.max_tx_size),maxValSize:parseInt(e.max_value_size),keyDeposit:BigInt(e.stake_key_deposit),poolDeposit:BigInt(e.pool_deposit),priceMem:t(e.prices.memory),priceStep:t(e.prices.steps),maxTxExMem:BigInt(e.max_execution_units_per_transaction.memory),maxTxExSteps:BigInt(e.max_execution_units_per_transaction.steps),coinsPerUtxoByte:BigInt(e.coins_per_utxo_byte),collateralPercentage:parseInt(e.collateral_percentage),maxCollateralInputs:parseInt(e.max_collateral_inputs),costModels:s(e.cost_models,{"plutus:v1":"PlutusV1","plutus:v2":"PlutusV2"})}}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("script"))(),s=[],r=1;for(;;){let a=await fetch(`${this.url}/addresses/${t}/utxos?page=${r}`,{headers:this.commonHeaders()}),i=await a.json();if(!a.ok)throw new Error("Could not fetch UTxOs from Maestro. Try again.");if(s=s.concat(i),i.length<=0)break;r++}return s.map(this.maestroUtxoToUtxo)}async getUtxosWithUnit(e,t){return(await this.getUtxos(e)).filter(r=>r.assets[t])}async getUtxoByUnit(e){let t=await fetch(`${this.url}/assets/${e}/addresses?count=2`,{headers:this.commonHeaders()}).then(a=>a.json());if(t.length===0)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],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){return(await Promise.all(e.map(async s=>{let r=await fetch(`${this.url}/transactions/${s.txHash}/outputs/${s.outputIndex}/utxo`,{headers:this.commonHeaders()}).then(a=>a.json());return!r||r.message?[]:[this.maestroUtxoToUtxo(r)]}))).reduce((s,r)=>s.concat(r),[])}async getDelegation(e){let t=await fetch(`${this.url}/accounts/${e}`,{headers:this.commonHeaders()}).then(s=>s.json());return!t||t.message?{poolId:null,rewards:0n}:{poolId:t.delegated_pool||null,rewards:BigInt(t.rewards_available)}}async getDatum(e){let t=await fetch(`${this.url}/datum/${e}`,{headers:this.commonHeaders()}).then(s=>s.json());if(!t||t.message)throw new Error(`No datum found for datum hash: ${e}`);return t.bytes}awaitTx(e,t=3e3){return new Promise(s=>{let r=setInterval(async()=>{let a=await fetch(`${this.url}/transactions/${e}/cbor`,{headers:this.commonHeaders()}).then(i=>i.json());if(a&&!a.message)return clearInterval(r),await new Promise(i=>setTimeout(()=>i(1),1e3)),s(!0)},t)})}async submitTx(e){let t=await fetch(`${this.url}/txmanager`,{method:"POST",headers:{"Content-Type":"application/cbor",...this.commonHeaders()},body:d(e)}),s=await t.text();if(!t.ok)throw t.status===400?new Error(s):new Error("Could not submit transaction.");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(s=>{t[s.unit.replace("#","")]=BigInt(s.quantity)}),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{Ht as Blockfrost,o as C,j as Constr,ee as Data,Re as Emulator,Ut as Kupmios,$e as Lucid,T as M,jt as Maestro,Ue 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,Vs 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,He as sha256,pt as slotToBeginUnixTime,rr as stakeCredentialOf,y as toHex,or as toLabel,Mr as toPublicKey,We as toScriptRef,Dr as toText,Ct as toUnit,ft as unixTimeToEnclosingSlot,ue as utxoToCore,Ve as valueToAssets}; +`)}}};var $e=class{constructor(){Object.defineProperty(this,"protocolParameters",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"txBuilderConfig",{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 Re&&(r.network="Custom",be[r.network]={zeroTime:r.provider.now(),zeroSlot:0,slotLength:1e3})),e&&!s){let a=await e.getProtocolParameters();r.protocolParameters=a}if(r.protocolParameters){let a=be[r.network];r.txBuilderConfig=o.TransactionBuilderConfigBuilder.new().coins_per_utxo_byte(o.BigNum.from_str(r.protocolParameters.coinsPerUtxoByte.toString())).fee_algo(o.LinearFee.new(o.BigNum.from_str(r.protocolParameters.minFeeA.toString()),o.BigNum.from_str(r.protocolParameters.minFeeB.toString()))).key_deposit(o.BigNum.from_str(r.protocolParameters.keyDeposit.toString())).pool_deposit(o.BigNum.from_str(r.protocolParameters.poolDeposit.toString())).max_tx_size(r.protocolParameters.maxTxSize).max_value_size(r.protocolParameters.maxValSize).collateral_percentage(r.protocolParameters.collateralPercentage).max_collateral_inputs(r.protocolParameters.maxCollateralInputs).max_tx_ex_units(o.ExUnits.new(o.BigNum.from_str(r.protocolParameters.maxTxExMem.toString()),o.BigNum.from_str(r.protocolParameters.maxTxExSteps.toString()))).ex_unit_prices(o.ExUnitPrices.from_float(r.protocolParameters.priceMem,r.protocolParameters.priceStep)).slot_config(o.BigNum.from_str(a.zeroTime.toString()),o.BigNum.from_str(a.zeroSlot.toString()),a.slotLength).blockfrost(o.Blockfrost.new((e?.url||"")+"/utils/txs/evaluate",e?.projectId||"")).costmdls(Qe(r.protocolParameters.costModels)).build()}return r.utils=new Pe(r),r}async switchProvider(e,t){if(this.network==="Custom")throw new Error("Cannot switch when on custom network.");let s=await $e.new(e,t);return this.txBuilderConfig=s.txBuilderConfig,this.provider=e||this.provider,this.network=t||this.network,this.wallet=s.wallet,this}newTx(){return new De(this)}fromTx(e){return new _e(this,o.Transaction.from_bytes(d(e)))}newMessage(e,t){return new Me(this,e,t)}verifyMessage(e,t,s){let{paymentCredential:r,stakeCredential:a,address:{hex:i}}=this.utils.getAddressDetails(e),u=r?.hash||a?.hash;if(!u)throw new Error("Not a valid address provided.");return At(i,u,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 ee.from(e.datum,t)}async metadataOf(e){let{policyId:t,name:s,label:r}=Ce(e);switch(r){case 222:case 333:case 444:{let a=await this.utxoByUnit(Ct(t,s,100)),i=await this.datumOf(a);return ee.toJson(i.fields[0])}default:throw new Error("No variant matched.")}}selectWalletFromPrivateKey(e){let t=o.PrivateKey.from_bech32(e),s=t.to_public().hash();return this.wallet={address:async()=>o.EnterpriseAddress.new(this.network==="Mainnet"?1:0,o.StakeCredential.from_keyhash(s)).to_address().to_bech32(void 0),rewardAddress:async()=>null,getCollateralCore:()=>{},getUtxos:async()=>await this.utxosAt(ie(await this.wallet.address())),getUtxosCore:async()=>{let r=await this.utxosAt(ie(await this.wallet.address())),a=o.TransactionUnspentOutputs.new();return r.forEach(i=>{a.add(ue(i))}),a},getDelegation:async()=>({poolId:null,rewards:0n}),signTx:async r=>{let a=o.make_vkey_witness(o.hash_transaction(r.body()),t),i=o.TransactionWitnessSetBuilder.new();return i.add_vkey(a),i.build()},signMessage:async(r,a)=>{let{paymentCredential:i,address:{hex:u}}=this.utils.getAddressDetails(r),c=i?.hash,m=s.to_hex();if(!c||c!==m)throw new Error(`Cannot sign message for address: ${r}.`);return Ie(u,a,e)},submitTx:async r=>await this.provider.submitTx(r)},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()=>o.Address.from_bytes(d(await t())).to_bech32(void 0),rewardAddress:async()=>{let[s]=await e.getRewardAddresses();return s?o.RewardAddress.from_address(o.Address.from_bytes(d(s))).to_address().to_bech32(void 0):null},getCollateralCore:()=>{},getUtxos:async()=>(await e.getUtxos()||[]).map(r=>{let a=o.TransactionUnspentOutput.from_bytes(d(r));return Oe(a)}),getUtxosCore:async()=>{let s=o.TransactionUnspentOutputs.new();return(await e.getUtxos()||[]).forEach(r=>{s.add(o.TransactionUnspentOutput.from_bytes(d(r)))}),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(y(s.to_bytes()),!0);return o.TransactionWitnessSet.from_bytes(d(r))},signMessage:async(s,r)=>{let a=y(o.Address.from_bech32(s).to_bytes());return await e.signData(a,r)},submitTx:async s=>await e.submitTx(s)},this}selectWalletFrom({address:e,utxos:t,rewardAddress:s,collateral:r}){let a=this.utils.getAddressDetails(e);return this.wallet={address:async()=>e,rewardAddress:async()=>(!s&&a.stakeCredential?(()=>a.stakeCredential.type==="Key"?o.RewardAddress.new(this.network==="Mainnet"?1:0,o.StakeCredential.from_keyhash(o.Ed25519KeyHash.from_hex(a.stakeCredential.hash))).to_address().to_bech32(void 0):o.RewardAddress.new(this.network==="Mainnet"?1:0,o.StakeCredential.from_scripthash(o.ScriptHash.from_hex(a.stakeCredential.hash))).to_address().to_bech32(void 0))():s)||null,getCollateralCore:()=>{if(!r||!r.length)return;let i=o.TransactionUnspentOutputs.new();return r.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:s,rewardAddress:r,paymentKey:a,stakeKey:i}=Pt(e,{addressType:t?.addressType||"Base",accountIndex:t?.accountIndex||0,password:t?.password,network:this.network}),u=o.PrivateKey.from_bech32(a).to_public().hash().to_hex(),c=i?o.PrivateKey.from_bech32(i).to_public().hash().to_hex():"",m={[u]:a,[c]:i};return this.wallet={address:async()=>s,rewardAddress:async()=>r||null,getCollateralCore:()=>{},getUtxos:async()=>this.utxosAt(ie(s)),getUtxosCore:async()=>{let p=o.TransactionUnspentOutputs.new();return(await this.utxosAt(ie(s))).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(s),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 Ht=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:V}}).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"))(),s=[],r=1;for(;;){let a=await fetch(`${this.url}/addresses/${t}/utxos?page=${r}`,{headers:{project_id:this.projectId,lucid:V}}).then(i=>i.json());if(a.error){if(a.status_code===404)return[];throw new Error("Could not fetch UTxOs from Blockfrost. Try again.")}if(s=s.concat(a),a.length<=0)break;r++}return this.blockfrostUtxosToUtxos(s)}async getUtxosWithUnit(e,t){let s=(()=>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=[],a=1;for(;;){let i=await fetch(`${this.url}/addresses/${s}/utxos/${t}?page=${a}`,{headers:{project_id:this.projectId,lucid:V}}).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(r=r.concat(i),i.length<=0)break;a++}return this.blockfrostUtxosToUtxos(r)}async getUtxoByUnit(e){let t=await fetch(`${this.url}/assets/${e}/addresses?count=2`,{headers:{project_id:this.projectId,lucid:V}}).then(a=>a.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 a=await fetch(`${this.url}/txs/${r}/utxos`,{headers:{project_id:this.projectId,lucid:V}}).then(u=>u.json());if(!a||a.error)return[];let i=a.outputs.map(u=>({...u,tx_hash:r}));return this.blockfrostUtxosToUtxos(i)}))).reduce((r,a)=>r.concat(a),[]).filter(r=>e.some(a=>r.txHash===a.txHash&&r.outputIndex===a.outputIndex))}async getDelegation(e){let t=await fetch(`${this.url}/accounts/${e}`,{headers:{project_id:this.projectId,lucid:V}}).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:V}}).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 a=await fetch(`${this.url}/txs/${e}`,{headers:{project_id:this.projectId,lucid:V}}).then(i=>i.json());if(a&&!a.error)return clearInterval(r),await new Promise(i=>setTimeout(()=>i(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:V},body:d(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:V}}).then(a=>a.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:V}}).then(a=>a.json());return{type:s==="plutusV1"?"PlutusV1":"PlutusV2",script:q(r)}})():void 0})))}};function Vs(n){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 s=o.PlutusMap.new();return t.map.forEach(({k:r,v:a})=>{s.insert(e(r),e(a))}),o.PlutusData.new_map(s)}else if(t.list){let s=o.PlutusList.new();return t.list.forEach(r=>{s.add(e(r))}),o.PlutusData.new_list(s)}else if(!isNaN(t.constructor)){let s=o.PlutusList.new();return t.fields.forEach(r=>{s.add(e(r))}),o.PlutusData.new_constr_plutus_data(o.ConstrPlutusData.new(o.BigNum.from_str(t.constructor.toString()),s))}}else return o.PlutusData.new_integer(o.BigInt.from_str(t.int.toString()));throw new Error("Unsupported type")};return y(e(n).to_bytes())}var V=ge.version;var Ut=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:a}=JSON.parse(r.data),i={};Object.keys(a.costModels).forEach(C=>{let h="Plutus"+C.split(":")[1].toUpperCase();i[h]=a.costModels[C]});let[u,c]=a.prices.memory.split("/"),[m,p]=a.prices.steps.split("/");t({minFeeA:parseInt(a.minFeeCoefficient),minFeeB:parseInt(a.minFeeConstant),maxTxSize:parseInt(a.maxTxSize),maxValSize:parseInt(a.maxValueSize),keyDeposit:BigInt(a.stakeKeyDeposit),poolDeposit:BigInt(a.poolDeposit),priceMem:parseInt(u)/parseInt(c),priceStep:parseInt(m)/parseInt(p),maxTxExMem:BigInt(a.maxExecutionUnitsPerTransaction.memory),maxTxExSteps:BigInt(a.maxExecutionUnitsPerTransaction.steps),coinsPerUtxoByte:BigInt(a.coinsPerUtxoByte),collateralPercentage:parseInt(a.collateralPercentage),maxCollateralInputs:parseInt(a.maxCollateralInputs),costModels:i}),e.close()}catch(a){s(a)}},{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(a=>a.json());return this.kupmiosUtxosToUtxos(r)}async getUtxosWithUnit(e,t){let s=typeof e=="string",r=s?e:e.hash,{policyId:a,assetName:i}=Ce(t),u=await fetch(`${this.kupoUrl}/matches/${r}${s?"":"/*"}?unspent&policy_id=${a}${i?`&asset_name=${i}`:""}`).then(c=>c.json());return this.kupmiosUtxosToUtxos(u)}async getUtxoByUnit(e){let{policyId:t,assetName:s}=Ce(e),r=await fetch(`${this.kupoUrl}/matches/${t}.${s?`${s}`:"*"}?unspent`).then(i=>i.json()),a=await this.kupmiosUtxosToUtxos(r);if(a.length>1)throw new Error("Unit needs to be an NFT or only held by one address.");return a[0]}async getUtxosByOutRef(e){let t=[...new Set(e.map(r=>r.txHash))];return(await Promise.all(t.map(async r=>{let a=await fetch(`${this.kupoUrl}/matches/*@${r}?unspent`).then(i=>i.json());return this.kupmiosUtxosToUtxos(a)}))).reduce((r,a)=>r.concat(a),[]).filter(r=>e.some(a=>r.txHash===a.txHash&&r.outputIndex===a.outputIndex))}async getDelegation(e){let t=await this.ogmiosWsp("Query",{query:{delegationsAndRewards:[e]}});return new Promise((s,r)=>{t.addEventListener("message",a=>{try{let{result:i}=JSON.parse(a.data),u=i?Object.values(i)[0]:{};s({poolId:u?.delegate||null,rewards:BigInt(u?.rewards||0)}),t.close()}catch(i){r(i)}},{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 a=await fetch(`${this.kupoUrl}/matches/*@${e}?unspent`).then(i=>i.json());if(a&&a.length>0)return clearInterval(r),await new Promise(i=>setTimeout(()=>i(1),1e3)),s(!0)},t)})}async submitTx(e){let t=await this.ogmiosWsp("SubmitTx",{submit:e});return new Promise((s,r)=>{t.addEventListener("message",a=>{try{let{result:i}=JSON.parse(a.data);i.SubmitSuccess?s(i.SubmitSuccess.txId):r(i.SubmitFail),t.close()}catch(i){r(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 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(a=>a.json());if(r==="native")return{type:"Native",script:s};if(r==="plutus:v1")return{type:"PlutusV1",script:y(o.PlutusScript.new(d(s)).to_bytes())};if(r==="plutus:v2")return{type:"PlutusV2",script:y(o.PlutusScript.new(d(s)).to_bytes())}})()})))}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 jt=class{constructor(e,t=""){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}),this.url=e.slice(-1)==="/"?e.slice(0,-1):e,this.apiKey=t}async getProtocolParameters(){let e=await fetch(`${this.url}/protocol-params`,{headers:this.commonHeaders()}).then(r=>r.json()),t=r=>{let a=r.indexOf("/");return parseInt(r.slice(0,a))/parseInt(r.slice(a+1))},s=(r,a)=>{let i=Object.keys(r).map(u=>({[a[u]||u]:Object.fromEntries(Object.entries(r[u]).sort(([m,p],[C,E])=>m.localeCompare(C)))}));return Object.assign({},...i)};return{minFeeA:parseInt(e.min_fee_coefficient),minFeeB:parseInt(e.min_fee_constant),maxTxSize:parseInt(e.max_tx_size),maxValSize:parseInt(e.max_value_size),keyDeposit:BigInt(e.stake_key_deposit),poolDeposit:BigInt(e.pool_deposit),priceMem:t(e.prices.memory),priceStep:t(e.prices.steps),maxTxExMem:BigInt(e.max_execution_units_per_transaction.memory),maxTxExSteps:BigInt(e.max_execution_units_per_transaction.steps),coinsPerUtxoByte:BigInt(e.coins_per_utxo_byte),collateralPercentage:parseInt(e.collateral_percentage),maxCollateralInputs:parseInt(e.max_collateral_inputs),costModels:s(e.cost_models,{"plutus:v1":"PlutusV1","plutus:v2":"PlutusV2"})}}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("script"))(),s=[],r=1;for(;;){let a=await fetch(`${this.url}/addresses/${t}/utxos?page=${r}`,{headers:this.commonHeaders()}),i=await a.json();if(!a.ok)throw new Error("Could not fetch UTxOs from Maestro. Try again.");if(s=s.concat(i),i.length<=0)break;r++}return s.map(this.maestroUtxoToUtxo)}async getUtxosWithUnit(e,t){return(await this.getUtxos(e)).filter(r=>r.assets[t])}async getUtxoByUnit(e){let t=await fetch(`${this.url}/assets/${e}/addresses?count=2`,{headers:this.commonHeaders()}).then(a=>a.json());if(t.length===0)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],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){return(await Promise.all(e.map(async s=>{let r=await fetch(`${this.url}/transactions/${s.txHash}/outputs/${s.outputIndex}/utxo`,{headers:this.commonHeaders()}).then(a=>a.json());return!r||r.message?[]:[this.maestroUtxoToUtxo(r)]}))).reduce((s,r)=>s.concat(r),[])}async getDelegation(e){let t=await fetch(`${this.url}/accounts/${e}`,{headers:this.commonHeaders()}).then(s=>s.json());return!t||t.message?{poolId:null,rewards:0n}:{poolId:t.delegated_pool||null,rewards:BigInt(t.rewards_available)}}async getDatum(e){let t=await fetch(`${this.url}/datum/${e}`,{headers:this.commonHeaders()}).then(s=>s.json());if(!t||t.message)throw new Error(`No datum found for datum hash: ${e}`);return t.bytes}awaitTx(e,t=3e3){return new Promise(s=>{let r=setInterval(async()=>{let a=await fetch(`${this.url}/transactions/${e}/cbor`,{headers:this.commonHeaders()}).then(i=>i.json());if(a&&!a.message)return clearInterval(r),await new Promise(i=>setTimeout(()=>i(1),1e3)),s(!0)},t)})}async submitTx(e){let t=await fetch(`${this.url}/txmanager`,{method:"POST",headers:{"Content-Type":"application/cbor",...this.commonHeaders()},body:d(e)}),s=await t.text();if(!t.ok)throw t.status===400?new Error(s):new Error("Could not submit transaction.");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(s=>{t[s.unit.replace("#","")]=BigInt(s.quantity)}),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{Ht as Blockfrost,o as C,j as Constr,ee as Data,Re as Emulator,Ut as Kupmios,$e as Lucid,T as M,jt as Maestro,Ue 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,Vs 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,He as sha256,pt as slotToBeginUnixTime,rr as stakeCredentialOf,y as toHex,or as toLabel,Mr as toPublicKey,We as toScriptRef,Dr as toText,Ct as toUnit,ft as unixTimeToEnclosingSlot,ue as utxoToCore,Ve as valueToAssets}; diff --git a/src/lucid/lucid.ts b/src/lucid/lucid.ts index 2e76a052..ef7093f2 100644 --- a/src/lucid/lucid.ts +++ b/src/lucid/lucid.ts @@ -68,11 +68,6 @@ export class Lucid { } if (provider) { lucid.provider = provider; - } - if (provider && !protocolParameters) { - const protocolParams = await provider.getProtocolParameters(); - lucid.protocolParameters = protocolParams; - if (lucid.provider instanceof Emulator) { lucid.network = "Custom"; SLOT_CONFIG_NETWORK[lucid.network] = { @@ -82,6 +77,10 @@ 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()