@meshsdk/wallet 1.6.2 → 1.6.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs CHANGED
@@ -1,4 +1,1473 @@
1
- "use strict";var Z=Object.create;var D=Object.defineProperty;var R=Object.getOwnPropertyDescriptor;var $=Object.getOwnPropertyNames;var J=Object.getPrototypeOf,V=Object.prototype.hasOwnProperty;var X=(i,e)=>{for(var t in e)D(i,t,{get:e[t],enumerable:!0})},Y=(i,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of $(e))!V.call(i,n)&&n!==t&&D(i,n,{get:()=>e[n],enumerable:!(r=R(e,n))||r.enumerable});return i};var q=(i,e,t)=>(t=i!=null?Z(J(i)):{},Y(e||!i||!i.__esModule?D(t,"default",{value:i,enumerable:!0}):t,i)),ee=i=>Y(D({},"__esModule",{value:!0}),i);var ue={};X(ue,{AppWallet:()=>b,BrowserWallet:()=>z,EmbeddedWallet:()=>M,MeshWallet:()=>k,WalletStaticMethods:()=>L});module.exports=ee(ue);var j=require("@meshsdk/core-cst");function S(i){if(!Number.isSafeInteger(i))throw new Error(`Wrong integer: ${i}`)}function te(i){return i instanceof Uint8Array||i!=null&&typeof i=="object"&&i.constructor.name==="Uint8Array"}function re(...i){let e=s=>s,t=(s,d)=>c=>s(d(c)),r=i.map(s=>s.encode).reduceRight(t,e),n=i.map(s=>s.decode).reduce(t,e);return{encode:r,decode:n}}function se(i){return{encode:e=>{if(!Array.isArray(e)||e.length&&typeof e[0]!="number")throw new Error("alphabet.encode input should be an array of numbers");return e.map(t=>{if(t<0||t>=i.length)throw new Error(`Digit index outside alphabet: ${t} (alphabet: ${i.length})`);return i[t]})},decode:e=>{if(!Array.isArray(e)||e.length&&typeof e[0]!="string")throw new Error("alphabet.decode input should be array of strings");return e.map(t=>{if(typeof t!="string")throw new Error(`alphabet.decode: not string element=${t}`);let r=i.indexOf(t);if(r===-1)throw new Error(`Unknown letter: "${t}". Allowed: ${i}`);return r})}}}function ne(i=""){if(typeof i!="string")throw new Error("join separator should be string");return{encode:e=>{if(!Array.isArray(e)||e.length&&typeof e[0]!="string")throw new Error("join.encode input should be array of strings");for(let t of e)if(typeof t!="string")throw new Error(`join.encode: non-string input=${t}`);return e.join(i)},decode:e=>{if(typeof e!="string")throw new Error("join.decode input should be string");return e.split(i)}}}var W=(i,e)=>e?W(e,i%e):i,T=(i,e)=>i+(e-W(i,e));function m(i,e,t,r){if(!Array.isArray(i))throw new Error("convertRadix2: data should be array");if(e<=0||e>32)throw new Error(`convertRadix2: wrong from=${e}`);if(t<=0||t>32)throw new Error(`convertRadix2: wrong to=${t}`);if(T(e,t)>32)throw new Error(`convertRadix2: carry overflow from=${e} to=${t} carryBits=${T(e,t)}`);let n=0,s=0,d=2**t-1,c=[];for(let y of i){if(y>=2**e)throw new Error(`convertRadix2: invalid data word=${y} from=${e}`);if(n=n<<e|y,s+e>32)throw new Error(`convertRadix2: carry overflow pos=${s} from=${e}`);for(s+=e;s>=t;s-=t)c.push((n>>s-t&d)>>>0);n&=2**s-1}if(n=n<<t-s&d,!r&&s>=e)throw new Error("Excess padding");if(!r&&n)throw new Error(`Non-zero padding: ${n}`);return r&&s>0&&c.push(n>>>0),c}function ie(i,e=!1){if(i<=0||i>32)throw new Error("radix2: bits should be in (0..32]");if(T(8,i)>32||T(i,8)>32)throw new Error("radix2: carry overflow");return{encode:t=>{if(!te(t))throw new Error("radix2.encode input should be Uint8Array");return m(Array.from(t),8,i,!e)},decode:t=>{if(!Array.isArray(t)||t.length&&typeof t[0]!="number")throw new Error("radix2.decode input should be array of numbers");return Uint8Array.from(m(t,i,8,e))}}}function B(i){if(typeof i!="function")throw new Error("unsafeWrapper fn should be function");return function(...e){try{return i.apply(null,e)}catch{}}}var f=re(se("qpzry9x8gf2tvdw0s3jn54khce6mua7l"),ne("")),v=[996825010,642813549,513874426,1027748829,705979059];function C(i){let e=i>>25,t=(i&33554431)<<5;for(let r=0;r<v.length;r++)(e>>r&1)===1&&(t^=v[r]);return t}function P(i,e,t=1){let r=i.length,n=1;for(let s=0;s<r;s++){let d=i.charCodeAt(s);if(d<33||d>126)throw new Error(`Invalid prefix (${i})`);n=C(n)^d>>5}n=C(n);for(let s=0;s<r;s++)n=C(n)^i.charCodeAt(s)&31;for(let s of e)n=C(n)^s;for(let s=0;s<6;s++)n=C(n);return n^=t,f.encode(m([n%2**30],30,5,!1))}function oe(i){let e=i==="bech32"?1:734539939,t=ie(5),r=t.decode,n=t.encode,s=B(r);function d(g,I,l=90){if(typeof g!="string")throw new Error(`bech32.encode prefix should be string, not ${typeof g}`);if(!Array.isArray(I)||I.length&&typeof I[0]!="number")throw new Error(`bech32.encode words should be array of numbers, not ${typeof I}`);if(g.length===0)throw new TypeError(`Invalid prefix length ${g.length}`);let x=g.length+7+I.length;if(l!==!1&&x>l)throw new TypeError(`Length ${x} exceeds limit ${l}`);let N=g.toLowerCase(),p=P(N,I,e);return`${N}1${f.encode(I)}${p}`}function c(g,I=90){if(typeof g!="string")throw new Error(`bech32.decode input should be string, not ${typeof g}`);if(g.length<8||I!==!1&&g.length>I)throw new TypeError(`Wrong string length: ${g.length} (${g}). Expected (8..${I})`);let l=g.toLowerCase();if(g!==l&&g!==g.toUpperCase())throw new Error("String must be lowercase or uppercase");let x=l.lastIndexOf("1");if(x===0||x===-1)throw new Error('Letter "1" must be present between prefix and data only');let N=l.slice(0,x),p=l.slice(x+1);if(p.length<6)throw new Error("Data must be at least 6 characters long");let O=f.decode(p).slice(0,-6),U=P(N,O,e);if(!p.endsWith(U))throw new Error(`Invalid checksum in ${g}: expected "${U}"`);return{prefix:N,words:O}}let y=B(c);function E(g){let{prefix:I,words:l}=c(g,!1);return{prefix:I,words:l,bytes:r(l)}}return{encode:d,decode:c,decodeToBytes:E,decodeUnsafe:y,fromWords:r,fromWordsUnsafe:s,toWords:n}}var Q=oe("bech32");var h=require("@meshsdk/common"),o=require("@meshsdk/core-cst"),L=class{static privateKeyToEntropy(e){let t=Q.decodeToBytes(e).bytes,r=o.Bip32PrivateKey.fromBytes(t);return(0,h.bytesToHex)(r.bytes())}static mnemonicToEntropy(e){let t=(0,h.mnemonicToEntropy)(e.join(" ")),r=(0,o.buildBip32PrivateKey)(t);return(0,h.bytesToHex)(r.bytes())}static signingKeyToEntropy(e,t){return[e.startsWith("5820")?e.slice(4):e,t.startsWith("5820")?t.slice(4):t]}static getAddresses(e,t,r=0){let n=(0,o.buildBaseAddress)(r,o.Hash28ByteBase16.fromEd25519KeyHashHex((0,o.Ed25519KeyHashHex)(e.toPublicKey().hash().toString("hex"))),o.Hash28ByteBase16.fromEd25519KeyHashHex((0,o.Ed25519KeyHashHex)(t.toPublicKey().hash().toString("hex")))),s=(0,o.buildEnterpriseAddress)(r,o.Hash28ByteBase16.fromEd25519KeyHashHex((0,o.Ed25519KeyHashHex)(e.toPublicKey().hash().toString("hex")))),d=(0,o.buildRewardAddress)(r,o.Hash28ByteBase16.fromEd25519KeyHashHex((0,o.Ed25519KeyHashHex)(t.toPublicKey().hash().toString("hex"))));return{baseAddress:n.toAddress(),enterpriseAddress:s.toAddress(),rewardAddress:d.toAddress()}}static generateMnemonic(e=256){return(0,h.generateMnemonic)(e).split(" ")}static addWitnessSets(e,t){let r=(0,o.deserializeTx)(e),n=r.witnessSet(),s=n.vkeys(),d=s?[...s.values(),...t]:t;return n.setVkeys(o.Serialization.CborSet.fromCore(d.map(c=>c.toCore()),o.VkeyWitness.fromCore)),new o.Transaction(r.body(),n,r.auxiliaryData()).toCbor()}},M=class extends L{_entropy;_networkId;constructor(e){switch(super(),this._networkId=e.networkId,e.key.type){case"mnemonic":this._entropy=L.mnemonicToEntropy(e.key.words);break;case"root":this._entropy=L.privateKeyToEntropy(e.key.bech32);break;case"cli":this._entropy=L.signingKeyToEntropy(e.key.payment,e.key.stake??"f0".repeat(32));break}}getAccount(e=0,t=0){if(this._entropy==null)throw new Error("[EmbeddedWallet] No keys initialized");let{paymentKey:r,stakeKey:n}=(0,o.buildKeys)(this._entropy,e,t),{baseAddress:s,enterpriseAddress:d,rewardAddress:c}=L.getAddresses(r,n,this._networkId);return{baseAddress:s,enterpriseAddress:d,rewardAddress:c,baseAddressBech32:s.toBech32(),enterpriseAddressBech32:d.toBech32(),rewardAddressBech32:c.toBech32(),paymentKey:r,stakeKey:n,paymentKeyHex:r.toBytes().toString("hex"),stakeKeyHex:n.toBytes().toString("hex")}}getNetworkId(){return this._networkId}signData(e,t,r=0,n=0){try{let s=this.getAccount(r,n);if([s.baseAddress,s.enterpriseAddress,s.rewardAddress].find(c=>c.toBech32()===e)===void 0)throw new Error(`[EmbeddedWallet] Address: ${e} doesn't belong to this account.`);return(0,o.signData)(t,s.paymentKey)}catch(s){throw new Error(`[EmbeddedWallet] An error occurred during signData: ${s}.`)}}signTx(e,t=0,r=0){try{let n=(0,o.deserializeTxHash)((0,o.resolveTxHash)(e)),s=this.getAccount(t,r);return new o.VkeyWitness((0,o.Ed25519PublicKeyHex)(s.paymentKey.toPublicKey().toBytes().toString("hex")),(0,o.Ed25519SignatureHex)(s.paymentKey.sign(Buffer.from(n,"hex")).toString("hex")))}catch(n){throw new Error(`[EmbeddedWallet] An error occurred during signTx: ${n}.`)}}};var b=class{_fetcher;_submitter;_wallet;constructor(e){switch(this._fetcher=e.fetcher,this._submitter=e.submitter,e.key.type){case"mnemonic":this._wallet=new M({networkId:e.networkId,key:{type:"mnemonic",words:e.key.words}});break;case"root":this._wallet=new M({networkId:e.networkId,key:{type:"root",bech32:e.key.bech32}});break;case"cli":this._wallet=new M({networkId:e.networkId,key:{type:"cli",payment:e.key.payment,stake:e.key.stake}})}}async getCollateralUnspentOutput(e=0,t="payment"){let n=(await this.getUnspentOutputs(e,t)).filter(s=>s.output().amount().multiasset()===void 0);n.sort((s,d)=>Number(s.output().amount().coin())-Number(d.output().amount().coin()));for(let s of n)if(Number(s.output().amount().coin())>=5e6)return[s];return[]}getEnterpriseAddress(e=0,t=0){return this._wallet.getAccount(e,t).enterpriseAddressBech32}getPaymentAddress(e=0,t=0){return this._wallet.getAccount(e,t).baseAddressBech32}getRewardAddress(e=0,t=0){return this._wallet.getAccount(e,t).rewardAddressBech32}getNetworkId(){return this._wallet.getNetworkId()}getUsedAddress(e=0,t=0,r="payment"){return r==="enterprise"?(0,j.toAddress)(this.getEnterpriseAddress(e,t)):(0,j.toAddress)(this.getPaymentAddress(e,t))}async getUnspentOutputs(e=0,t="payment"){if(!this._fetcher)throw new Error("[AppWallet] Fetcher is required to fetch UTxOs. Please provide a fetcher.");let r=this._wallet.getAccount(e);return(await this._fetcher.fetchAddressUTxOs(t=="enterprise"?r.enterpriseAddressBech32:r.baseAddressBech32)).map(s=>(0,j.toTxUnspentOutput)(s))}signData(e,t,r=0,n=0){try{return this._wallet.signData(e,t,r,n)}catch(s){throw new Error(`[AppWallet] An error occurred during signData: ${s}.`)}}signTx(e,t=!1,r=0,n=0){try{let s=(0,j.deserializeTx)(e);if(!t&&s.witnessSet().vkeys()!==void 0&&s.witnessSet().vkeys().size()!==0)throw new Error("Signatures already exist in the transaction in a non partial sign call");let d=this._wallet.signTx(e,r,n);return M.addWitnessSets(e,[d])}catch(s){throw new Error(`[AppWallet] An error occurred during signTx: ${s}.`)}}signTxSync(e,t=!1,r=0,n=0){try{return"signedTx"}catch(s){throw new Error(`[AppWallet] An error occurred during signTx: ${s}.`)}}async signTxs(e,t){throw new Error("[AppWallet] signTxs() is not implemented.")}submitTx(e){if(!this._submitter)throw new Error("[AppWallet] Submitter is required to submit transactions. Please provide a submitter.");return this._submitter.submitTx(e)}static brew(e=256){return M.generateMnemonic(e)}};var w=require("@meshsdk/common"),a=require("@meshsdk/core-cst");var G=require("@nufi/dapp-client-cardano"),_=q(require("@nufi/dapp-client-core"),1),H={production:"https://wallet.nu.fi",mainnet:"https://wallet-staging.nu.fi",preprod:"https://wallet-testnet-staging.nu.fi",preview:"https://wallet-preview-staging.nu.fi"};function K(i="preprod"){try{let e=_.default.default;return Object.keys(H).includes(i)?e.init(H[i]):e.init(i),new Promise(t=>{e.getApi().isMetamaskInstalled().then(r=>{r?((0,G.initNufiDappCardanoSdk)(e,"snap"),t({id:"nufiSnap",name:"MetaMask",icon:"data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0iVVRGLTgiPz4KPHN2ZyBpZD0iTGF5ZXJfMiIgZGF0YS1uYW1lPSJMYXllciAyIiB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHZpZXdCb3g9IjAgMCAxNjkuMiAxNjMuNzEiPgogIDxkZWZzPgogICAgPHN0eWxlPgogICAgICAuY2xzLTEgewogICAgICAgIGZpbGw6ICNlMjc2MjU7CiAgICAgIH0KCiAgICAgIC5jbHMtMSwgLmNscy0yLCAuY2xzLTMsIC5jbHMtNCwgLmNscy01LCAuY2xzLTYsIC5jbHMtNywgLmNscy04LCAuY2xzLTkgewogICAgICAgIHN0cm9rZS13aWR0aDogMHB4OwogICAgICB9CgogICAgICAuY2xzLTIgewogICAgICAgIGZpbGw6ICM3NjNlMWE7CiAgICAgIH0KCiAgICAgIC5jbHMtMyB7CiAgICAgICAgZmlsbDogI2MwYWQ5ZTsKICAgICAgfQoKICAgICAgLmNscy00IHsKICAgICAgICBmaWxsOiAjMzQ2OGQxOwogICAgICB9CgogICAgICAuY2xzLTUgewogICAgICAgIGZpbGw6ICNjYzYyMjg7CiAgICAgIH0KCiAgICAgIC5jbHMtNiB7CiAgICAgICAgZmlsbDogI2Y1ODQxZjsKICAgICAgfQoKICAgICAgLmNscy03IHsKICAgICAgICBmaWxsOiAjZDdjMWIzOwogICAgICB9CgogICAgICAuY2xzLTggewogICAgICAgIGZpbGw6ICNmZmY7CiAgICAgICAgZmlsbC1ydWxlOiBldmVub2RkOwogICAgICB9CgogICAgICAuY2xzLTkgewogICAgICAgIGZpbGw6ICMyZjM0M2I7CiAgICAgIH0KICAgIDwvc3R5bGU+CiAgPC9kZWZzPgogIDxnIGlkPSJMYXllc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wWk0xMjguMzcsMTQ3LjhjLjkzLDAsMS42OC43NSwxLjY4LDEuNjgsMCwuOTMtLjc1LDEuNjgtMS42OCwxLjY4LS45MywwLTEuNjgtLjc1LTEuNjgtMS42OHMuNzUtMS42OCwxLjY4LTEuNjhoMFpNMTQzLjI0LDE0Ni42OGMuNzcsMCwxLjQuNjMsMS40LDEuNCwwLC43Ny0uNjMsMS40LTEuNCwxLjRzLTEuNC0uNjMtMS40LTEuNGgwYzAtLjc3LjYzLTEuNCwxLjQtMS40Wk0xMTMuNSwxNDYuNjhjLjc3LDAsMS40LjYzLDEuNCwxLjRzLS42MywxLjQtMS40LDEuNC0xLjQtLjYzLTEuNC0xLjRoMGMwLS43Ny42My0xLjQsMS40LTEuNFpNMTEzLjUsOTUuNjNjLjc3LDAsMS40LjYzLDEuNCwxLjRzLS42MywxLjQtMS40LDEuNC0xLjQtLjYzLTEuNC0xLjRoMGMwLS43Ny42My0xLjQsMS40LTEuNGgwWk0xNDMuMjQsOTUuNjNjLjc3LDAsMS40LjYzLDEuNCwxLjQsMCwuNzctLjYzLDEuNC0xLjQsMS40cy0xLjQtLjYzLTEuNC0xLjRoMGMwLS43Ny42My0xLjQsMS40LTEuNGgwWk0xNTcuODMsMTIxLjE2Yy43NywwLDEuNC42MywxLjQsMS40LDAsLjc3LS42MywxLjQtMS40LDEuNHMtMS40LS42My0xLjQtMS40aDBjMC0uNzguNjMtMS40LDEuNC0xLjRoMFpNOTguOTEsMTIxLjE2Yy43NywwLDEuNC42MywxLjQsMS40cy0uNjMsMS40LTEuNCwxLjQtMS40LS42My0xLjQtMS40aDBjMC0uNzguNjMtMS40LDEuNC0xLjRoMFoiLz4KICAgICAgPC9nPgogICAgPC9nPgogIDwvZz4KPC9zdmc+",version:"version"})):t(void 0)})})}catch{return Promise.resolve(void 0)}}var z=class i{constructor(e,t){this._walletInstance=e;this._walletName=t;this.walletInstance={...e}}walletInstance;static getInstalledWallets(){if(window===void 0)return[];if(window.cardano===void 0)return[];let e=[];for(let t in window.cardano)try{let r=window.cardano[t];if(r===void 0||r.name===void 0||r.icon===void 0||r.apiVersion===void 0)continue;e.push({id:t,name:t=="nufiSnap"?"MetaMask":r.name,icon:r.icon,version:r.apiVersion})}catch{}return e}static async getAvailableWallets({nufiNetwork:e="preprod"}={}){return window===void 0?[]:(await K(e),i.getInstalledWallets())}static async enable(e){try{let t=await i.resolveInstance(e);if(t!==void 0)return new i(t,e);throw new Error(`Couldn't create an instance of wallet: ${e}`)}catch(t){throw new Error(`[BrowserWallet] An error occurred during enable: ${JSON.stringify(t)}.`)}}async getBalance(){let e=await this._walletInstance.getBalance();return(0,a.fromValue)((0,a.deserializeValue)(e))}async getChangeAddress(){let e=await this._walletInstance.getChangeAddress();return(0,a.addressToBech32)((0,a.deserializeAddress)(e))}async getCollateral(){return(await this.getCollateralUnspentOutput()).map(t=>(0,a.fromTxUnspentOutput)(t))}getNetworkId(){return this._walletInstance.getNetworkId()}async getRewardAddresses(){return(await this._walletInstance.getRewardAddresses()).map(t=>(0,a.addressToBech32)((0,a.deserializeAddress)(t)))}async getUnusedAddresses(){return(await this._walletInstance.getUnusedAddresses()).map(t=>(0,a.addressToBech32)((0,a.deserializeAddress)(t)))}async getUsedAddresses(){return(await this._walletInstance.getUsedAddresses()).map(t=>(0,a.addressToBech32)((0,a.deserializeAddress)(t)))}async getUsedCollateral(e=w.DEFAULT_PROTOCOL_PARAMETERS.maxCollateralInputs){return(await this._walletInstance.experimental.getCollateral()??[]).map(r=>(0,a.deserializeTxUnspentOutput)(r)).slice(0,e)}async getUtxos(){return(await this.getUsedUTxOs()).map(t=>(0,a.fromTxUnspentOutput)(t))}signData(e,t){let r=(0,a.toAddress)(e).toBytes().toString();return this._walletInstance.signData(r,(0,w.fromUTF8)(t))}async signTx(e,t=!1){let r=await this._walletInstance.signTx(e,t);return i.addBrowserWitnesses(e,r)}async signTxs(e,t=!1){let r;switch(this._walletName){case"Typhon Wallet":this._walletInstance.signTxs&&(r=await this._walletInstance.signTxs(e,t));break;default:this._walletInstance.signTxs?r=await this._walletInstance.signTxs(e.map(s=>({cbor:s,partialSign:t}))):this._walletInstance.experimental.signTxs&&(r=await this._walletInstance.experimental.signTxs(e.map(s=>({cbor:s,partialSign:t}))));break}if(!r)throw new Error("Wallet does not support signTxs");let n=[];for(let s=0;s<r.length;s++){let d=e[s],c=r[s],y=i.addBrowserWitnesses(d,c);n.push(y)}return n}submitTx(e){return this._walletInstance.submitTx(e)}async getUsedAddress(){let e=await this._walletInstance.getUsedAddresses();if(e.length===0)throw new Error("No used addresses found");return(0,a.deserializeAddress)(e[0])}async getCollateralUnspentOutput(){return(await this._walletInstance.experimental.getCollateral()??[]).map(t=>(0,a.deserializeTxUnspentOutput)(t))}async getUsedUTxOs(){return(await this._walletInstance.getUtxos()??[]).map(t=>(0,a.deserializeTxUnspentOutput)(t))}async getAssets(){return(await this.getBalance()).filter(t=>t.unit!=="lovelace").map(t=>{let r=t.unit.slice(0,w.POLICY_ID_LENGTH),n=t.unit.slice(w.POLICY_ID_LENGTH),s=(0,w.resolveFingerprint)(r,n);return{unit:t.unit,policyId:r,assetName:n,fingerprint:s,quantity:t.quantity}})}async getLovelace(){let t=(await this.getBalance()).find(r=>r.unit==="lovelace");return t!==void 0?t.quantity:"0"}async getPolicyIdAssets(e){return(await this.getAssets()).filter(r=>r.policyId===e)}async getPolicyIds(){let e=await this.getBalance();return Array.from(new Set(e.map(t=>t.unit.slice(0,w.POLICY_ID_LENGTH)))).filter(t=>t!=="lovelace")}static resolveInstance(e){return window.cardano===void 0||window.cardano[e]===void 0?void 0:window.cardano[e]?.enable()}static addBrowserWitnesses(e,t){let r=a.Serialization.TransactionWitnessSet.fromCbor(a.CardanoSDKUtil.HexBlob(t)).vkeys()?.values();if(r===void 0)return e;let n=(0,a.deserializeTx)(e),s=n.witnessSet(),d=s.vkeys(),c=d?[...d.values(),...r]:[...r];return s.setVkeys(a.Serialization.CborSet.fromCore(c.map(y=>y.toCore()),a.VkeyWitness.fromCore)),new a.Transaction(n.body(),s,n.auxiliaryData()).toCbor()}};var A=require("@meshsdk/common"),u=require("@meshsdk/core-cst"),F=require("@meshsdk/transaction");var k=class{_wallet;_accountIndex=0;_keyIndex=0;_fetcher;_submitter;_networkId;_addresses={};constructor(e){switch(e.key.type){case"root":this._wallet=new M({networkId:e.networkId,key:{type:"root",bech32:e.key.bech32}}),this.getAddressesFromWallet(this._wallet);break;case"cli":this._wallet=new M({networkId:e.networkId,key:{type:"cli",payment:e.key.payment,stake:e.key.stake}}),this.getAddressesFromWallet(this._wallet);break;case"mnemonic":this._wallet=new M({networkId:e.networkId,key:{type:"mnemonic",words:e.key.words}}),this.getAddressesFromWallet(this._wallet);break}this._networkId=e.networkId,e.fetcher&&(this._fetcher=e.fetcher),e.submitter&&(this._submitter=e.submitter),e.accountIndex&&(this._accountIndex=e.accountIndex),e.keyIndex&&(this._keyIndex=e.keyIndex)}async getBalance(){let e=await this.getUnspentOutputs(),t=new Map;return e.map(n=>{(0,u.fromTxUnspentOutput)(n).output.amount.map(d=>{let c=d.unit,y=Number(d.quantity);if(t.has(c)){let E=t.get(c);t.set(c,E+y)}else t.set(c,y)})}),Array.from(t,([n,s])=>({unit:n,quantity:s.toString()}))}getChangeAddress(){return this._addresses.baseAddressBech32}async getCollateral(e="payment"){return(await this.getCollateralUnspentOutput(e)).map((r,n)=>(0,u.fromTxUnspentOutput)(r))}async getCollateralUnspentOutput(e="payment"){let r=(await this.getUnspentOutputs(e)).filter(n=>n.output().amount().multiasset()===void 0);r.sort((n,s)=>Number(n.output().amount().coin())-Number(s.output().amount().coin()));for(let n of r)if(Number(n.output().amount().coin())>=5e6)return[n];return[]}getNetworkId(){return this._networkId}getRewardAddresses(){return[this._addresses.rewardAddressBech32]}getUnusedAddresses(){return[this.getChangeAddress()]}getUsedAddresses(){return[this.getChangeAddress()]}async getUsedCollateral(){return(await this.getCollateral()).map(r=>(0,u.toTxUnspentOutput)(r))}async getUsedUTxOs(e){return await this.getUnspentOutputs(e)}async getUtxos(e){return(await this.getUsedUTxOs(e)).map(r=>(0,u.fromTxUnspentOutput)(r))}signData(e){if(!this._wallet)throw new Error("[MeshWallet] Read only wallet does not support signing data.");return this._wallet.signData(this.getChangeAddress(),e)}signTx(e,t=!1){if(!this._wallet)throw new Error("[MeshWallet] Read only wallet does not support signing data.");let r=(0,u.deserializeTx)(e);if(!t&&r.witnessSet().vkeys()!==void 0&&r.witnessSet().vkeys().size()!==0)throw new Error("Signatures already exist in the transaction in a non partial sign call");let n=this._wallet.signTx(e,this._accountIndex,this._keyIndex);return M.addWitnessSets(e,[n])}signTxs(e,t=!1){let r=[];for(let n of e){let s=this.signTx(n,t);r.push(s)}return r}async submitTx(e){if(!this._submitter)throw new Error("[AppWallet] Submitter is required to submit transactions. Please provide a submitter.");return this._submitter.submitTx(e)}getUsedAddress(e){return e==="enterprise"?(0,u.toAddress)(this._addresses.enterpriseAddressBech32):(0,u.toAddress)(this._addresses.baseAddressBech32)}async getUnspentOutputs(e){if(!this._fetcher)throw new Error("[AppWallet] Fetcher is required to fetch UTxOs. Please provide a fetcher.");return(await this._fetcher.fetchAddressUTxOs(e=="enterprise"?this._addresses.enterpriseAddressBech32:this._addresses.baseAddressBech32)).map(r=>(0,u.toTxUnspentOutput)(r))}async getAssets(){return(await this.getBalance()).filter(t=>t.unit!=="lovelace").map(t=>{let r=t.unit.slice(0,A.POLICY_ID_LENGTH),n=t.unit.slice(A.POLICY_ID_LENGTH),s=(0,A.resolveFingerprint)(r,n);return{unit:t.unit,policyId:r,assetName:(0,A.toUTF8)(n),fingerprint:s,quantity:t.quantity}})}async getLovelace(){let t=(await this.getBalance()).find(r=>r.unit==="lovelace");return t!==void 0?t.quantity:"0"}async getPolicyIdAssets(e){return(await this.getAssets()).filter(r=>r.policyId===e)}async getPolicyIds(){let e=await this.getBalance();return Array.from(new Set(e.map(t=>t.unit.slice(0,A.POLICY_ID_LENGTH)))).filter(t=>t!=="lovelace")}async createCollateral(){let e=new F.Transaction({initiator:this});e.sendLovelace(this.getChangeAddress(),"5000000");let t=await e.build(),r=await this.signTx(t);return await this.submitTx(r)}static brew(e=!1,t=256){let r=M.generateMnemonic(t);return e?(0,u.resolvePrivateKey)(r):r}getAddressesFromWallet(e){let t=e.getAccount(this._accountIndex,this._keyIndex);this._addresses={baseAddress:t.baseAddress,enterpriseAddress:t.enterpriseAddress,rewardAddress:t.rewardAddress,baseAddressBech32:t.baseAddressBech32,enterpriseAddressBech32:t.enterpriseAddressBech32,rewardAddressBech32:t.rewardAddressBech32}}buildAddressFromBech32Address(e){let r=new u.CardanoSDKSerializer().deserializer.key.deserializeAddress(e);r.pubKeyHash&&r.stakeCredentialHash&&(this._addresses.baseAddress=(0,u.buildBaseAddress)(this._networkId,u.Hash28ByteBase16.fromEd25519KeyHashHex((0,u.Ed25519KeyHashHex)(r.pubKeyHash)),u.Hash28ByteBase16.fromEd25519KeyHashHex((0,u.Ed25519KeyHashHex)((0,u.Ed25519KeyHashHex)(r.stakeCredentialHash)))).toAddress(),this._addresses.baseAddressBech32=this._addresses.baseAddress.toBech32()),r.pubKeyHash&&(this._addresses.enterpriseAddress=(0,u.buildEnterpriseAddress)(this._networkId,u.Hash28ByteBase16.fromEd25519KeyHashHex((0,u.Ed25519KeyHashHex)(r.pubKeyHash))).toAddress(),this._addresses.enterpriseAddressBech32=this._addresses.enterpriseAddress.toBech32()),r.stakeCredentialHash&&(this._addresses.rewardAddress=(0,u.buildRewardAddress)(this._networkId,u.Hash28ByteBase16.fromEd25519KeyHashHex((0,u.Ed25519KeyHashHex)(r.stakeCredentialHash))).toAddress(),this._addresses.rewardAddressBech32=this._addresses.rewardAddress.toBech32())}};0&&(module.exports={AppWallet,BrowserWallet,EmbeddedWallet,MeshWallet,WalletStaticMethods});
1
+ "use strict";
2
+ var __create = Object.create;
3
+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getProtoOf = Object.getPrototypeOf;
7
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
8
+ var __export = (target, all) => {
9
+ for (var name in all)
10
+ __defProp(target, name, { get: all[name], enumerable: true });
11
+ };
12
+ var __copyProps = (to, from, except, desc) => {
13
+ if (from && typeof from === "object" || typeof from === "function") {
14
+ for (let key of __getOwnPropNames(from))
15
+ if (!__hasOwnProp.call(to, key) && key !== except)
16
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
17
+ }
18
+ return to;
19
+ };
20
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
+ // If the importer is in node compatibility mode or this is not an ESM
22
+ // file that has been converted to a CommonJS file using a Babel-
23
+ // compatible transform (i.e. "__esModule" has not been set), then set
24
+ // "default" to the CommonJS "module.exports" for node compatibility.
25
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
26
+ mod
27
+ ));
28
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
29
+
30
+ // src/index.ts
31
+ var src_exports = {};
32
+ __export(src_exports, {
33
+ AppWallet: () => AppWallet,
34
+ BrowserWallet: () => BrowserWallet,
35
+ EmbeddedWallet: () => EmbeddedWallet,
36
+ MeshWallet: () => MeshWallet,
37
+ WalletStaticMethods: () => WalletStaticMethods
38
+ });
39
+ module.exports = __toCommonJS(src_exports);
40
+
41
+ // src/app/index.ts
42
+ var import_core_cst2 = require("@meshsdk/core-cst");
43
+
44
+ // ../../node_modules/@scure/base/lib/esm/index.js
45
+ // @__NO_SIDE_EFFECTS__
46
+ function assertNumber(n) {
47
+ if (!Number.isSafeInteger(n))
48
+ throw new Error(`Wrong integer: ${n}`);
49
+ }
50
+ function isBytes(a) {
51
+ return a instanceof Uint8Array || a != null && typeof a === "object" && a.constructor.name === "Uint8Array";
52
+ }
53
+ // @__NO_SIDE_EFFECTS__
54
+ function chain(...args) {
55
+ const id = (a) => a;
56
+ const wrap = (a, b) => (c) => a(b(c));
57
+ const encode = args.map((x) => x.encode).reduceRight(wrap, id);
58
+ const decode = args.map((x) => x.decode).reduce(wrap, id);
59
+ return { encode, decode };
60
+ }
61
+ // @__NO_SIDE_EFFECTS__
62
+ function alphabet(alphabet2) {
63
+ return {
64
+ encode: (digits) => {
65
+ if (!Array.isArray(digits) || digits.length && typeof digits[0] !== "number")
66
+ throw new Error("alphabet.encode input should be an array of numbers");
67
+ return digits.map((i) => {
68
+ /* @__PURE__ */ assertNumber(i);
69
+ if (i < 0 || i >= alphabet2.length)
70
+ throw new Error(`Digit index outside alphabet: ${i} (alphabet: ${alphabet2.length})`);
71
+ return alphabet2[i];
72
+ });
73
+ },
74
+ decode: (input) => {
75
+ if (!Array.isArray(input) || input.length && typeof input[0] !== "string")
76
+ throw new Error("alphabet.decode input should be array of strings");
77
+ return input.map((letter) => {
78
+ if (typeof letter !== "string")
79
+ throw new Error(`alphabet.decode: not string element=${letter}`);
80
+ const index = alphabet2.indexOf(letter);
81
+ if (index === -1)
82
+ throw new Error(`Unknown letter: "${letter}". Allowed: ${alphabet2}`);
83
+ return index;
84
+ });
85
+ }
86
+ };
87
+ }
88
+ // @__NO_SIDE_EFFECTS__
89
+ function join(separator = "") {
90
+ if (typeof separator !== "string")
91
+ throw new Error("join separator should be string");
92
+ return {
93
+ encode: (from) => {
94
+ if (!Array.isArray(from) || from.length && typeof from[0] !== "string")
95
+ throw new Error("join.encode input should be array of strings");
96
+ for (let i of from)
97
+ if (typeof i !== "string")
98
+ throw new Error(`join.encode: non-string input=${i}`);
99
+ return from.join(separator);
100
+ },
101
+ decode: (to) => {
102
+ if (typeof to !== "string")
103
+ throw new Error("join.decode input should be string");
104
+ return to.split(separator);
105
+ }
106
+ };
107
+ }
108
+ var gcd = /* @__NO_SIDE_EFFECTS__ */ (a, b) => !b ? a : /* @__PURE__ */ gcd(b, a % b);
109
+ var radix2carry = /* @__NO_SIDE_EFFECTS__ */ (from, to) => from + (to - /* @__PURE__ */ gcd(from, to));
110
+ // @__NO_SIDE_EFFECTS__
111
+ function convertRadix2(data, from, to, padding) {
112
+ if (!Array.isArray(data))
113
+ throw new Error("convertRadix2: data should be array");
114
+ if (from <= 0 || from > 32)
115
+ throw new Error(`convertRadix2: wrong from=${from}`);
116
+ if (to <= 0 || to > 32)
117
+ throw new Error(`convertRadix2: wrong to=${to}`);
118
+ if (/* @__PURE__ */ radix2carry(from, to) > 32) {
119
+ throw new Error(`convertRadix2: carry overflow from=${from} to=${to} carryBits=${/* @__PURE__ */ radix2carry(from, to)}`);
120
+ }
121
+ let carry = 0;
122
+ let pos = 0;
123
+ const mask = 2 ** to - 1;
124
+ const res = [];
125
+ for (const n of data) {
126
+ /* @__PURE__ */ assertNumber(n);
127
+ if (n >= 2 ** from)
128
+ throw new Error(`convertRadix2: invalid data word=${n} from=${from}`);
129
+ carry = carry << from | n;
130
+ if (pos + from > 32)
131
+ throw new Error(`convertRadix2: carry overflow pos=${pos} from=${from}`);
132
+ pos += from;
133
+ for (; pos >= to; pos -= to)
134
+ res.push((carry >> pos - to & mask) >>> 0);
135
+ carry &= 2 ** pos - 1;
136
+ }
137
+ carry = carry << to - pos & mask;
138
+ if (!padding && pos >= from)
139
+ throw new Error("Excess padding");
140
+ if (!padding && carry)
141
+ throw new Error(`Non-zero padding: ${carry}`);
142
+ if (padding && pos > 0)
143
+ res.push(carry >>> 0);
144
+ return res;
145
+ }
146
+ // @__NO_SIDE_EFFECTS__
147
+ function radix2(bits, revPadding = false) {
148
+ /* @__PURE__ */ assertNumber(bits);
149
+ if (bits <= 0 || bits > 32)
150
+ throw new Error("radix2: bits should be in (0..32]");
151
+ if (/* @__PURE__ */ radix2carry(8, bits) > 32 || /* @__PURE__ */ radix2carry(bits, 8) > 32)
152
+ throw new Error("radix2: carry overflow");
153
+ return {
154
+ encode: (bytes) => {
155
+ if (!isBytes(bytes))
156
+ throw new Error("radix2.encode input should be Uint8Array");
157
+ return /* @__PURE__ */ convertRadix2(Array.from(bytes), 8, bits, !revPadding);
158
+ },
159
+ decode: (digits) => {
160
+ if (!Array.isArray(digits) || digits.length && typeof digits[0] !== "number")
161
+ throw new Error("radix2.decode input should be array of numbers");
162
+ return Uint8Array.from(/* @__PURE__ */ convertRadix2(digits, bits, 8, revPadding));
163
+ }
164
+ };
165
+ }
166
+ // @__NO_SIDE_EFFECTS__
167
+ function unsafeWrapper(fn) {
168
+ if (typeof fn !== "function")
169
+ throw new Error("unsafeWrapper fn should be function");
170
+ return function(...args) {
171
+ try {
172
+ return fn.apply(null, args);
173
+ } catch (e) {
174
+ }
175
+ };
176
+ }
177
+ var BECH_ALPHABET = /* @__PURE__ */ chain(/* @__PURE__ */ alphabet("qpzry9x8gf2tvdw0s3jn54khce6mua7l"), /* @__PURE__ */ join(""));
178
+ var POLYMOD_GENERATORS = [996825010, 642813549, 513874426, 1027748829, 705979059];
179
+ // @__NO_SIDE_EFFECTS__
180
+ function bech32Polymod(pre) {
181
+ const b = pre >> 25;
182
+ let chk = (pre & 33554431) << 5;
183
+ for (let i = 0; i < POLYMOD_GENERATORS.length; i++) {
184
+ if ((b >> i & 1) === 1)
185
+ chk ^= POLYMOD_GENERATORS[i];
186
+ }
187
+ return chk;
188
+ }
189
+ // @__NO_SIDE_EFFECTS__
190
+ function bechChecksum(prefix, words, encodingConst = 1) {
191
+ const len = prefix.length;
192
+ let chk = 1;
193
+ for (let i = 0; i < len; i++) {
194
+ const c = prefix.charCodeAt(i);
195
+ if (c < 33 || c > 126)
196
+ throw new Error(`Invalid prefix (${prefix})`);
197
+ chk = /* @__PURE__ */ bech32Polymod(chk) ^ c >> 5;
198
+ }
199
+ chk = /* @__PURE__ */ bech32Polymod(chk);
200
+ for (let i = 0; i < len; i++)
201
+ chk = /* @__PURE__ */ bech32Polymod(chk) ^ prefix.charCodeAt(i) & 31;
202
+ for (let v of words)
203
+ chk = /* @__PURE__ */ bech32Polymod(chk) ^ v;
204
+ for (let i = 0; i < 6; i++)
205
+ chk = /* @__PURE__ */ bech32Polymod(chk);
206
+ chk ^= encodingConst;
207
+ return BECH_ALPHABET.encode(/* @__PURE__ */ convertRadix2([chk % 2 ** 30], 30, 5, false));
208
+ }
209
+ // @__NO_SIDE_EFFECTS__
210
+ function genBech32(encoding) {
211
+ const ENCODING_CONST = encoding === "bech32" ? 1 : 734539939;
212
+ const _words = /* @__PURE__ */ radix2(5);
213
+ const fromWords = _words.decode;
214
+ const toWords = _words.encode;
215
+ const fromWordsUnsafe = /* @__PURE__ */ unsafeWrapper(fromWords);
216
+ function encode(prefix, words, limit = 90) {
217
+ if (typeof prefix !== "string")
218
+ throw new Error(`bech32.encode prefix should be string, not ${typeof prefix}`);
219
+ if (!Array.isArray(words) || words.length && typeof words[0] !== "number")
220
+ throw new Error(`bech32.encode words should be array of numbers, not ${typeof words}`);
221
+ if (prefix.length === 0)
222
+ throw new TypeError(`Invalid prefix length ${prefix.length}`);
223
+ const actualLength = prefix.length + 7 + words.length;
224
+ if (limit !== false && actualLength > limit)
225
+ throw new TypeError(`Length ${actualLength} exceeds limit ${limit}`);
226
+ const lowered = prefix.toLowerCase();
227
+ const sum = /* @__PURE__ */ bechChecksum(lowered, words, ENCODING_CONST);
228
+ return `${lowered}1${BECH_ALPHABET.encode(words)}${sum}`;
229
+ }
230
+ function decode(str, limit = 90) {
231
+ if (typeof str !== "string")
232
+ throw new Error(`bech32.decode input should be string, not ${typeof str}`);
233
+ if (str.length < 8 || limit !== false && str.length > limit)
234
+ throw new TypeError(`Wrong string length: ${str.length} (${str}). Expected (8..${limit})`);
235
+ const lowered = str.toLowerCase();
236
+ if (str !== lowered && str !== str.toUpperCase())
237
+ throw new Error(`String must be lowercase or uppercase`);
238
+ const sepIndex = lowered.lastIndexOf("1");
239
+ if (sepIndex === 0 || sepIndex === -1)
240
+ throw new Error(`Letter "1" must be present between prefix and data only`);
241
+ const prefix = lowered.slice(0, sepIndex);
242
+ const data = lowered.slice(sepIndex + 1);
243
+ if (data.length < 6)
244
+ throw new Error("Data must be at least 6 characters long");
245
+ const words = BECH_ALPHABET.decode(data).slice(0, -6);
246
+ const sum = /* @__PURE__ */ bechChecksum(prefix, words, ENCODING_CONST);
247
+ if (!data.endsWith(sum))
248
+ throw new Error(`Invalid checksum in ${str}: expected "${sum}"`);
249
+ return { prefix, words };
250
+ }
251
+ const decodeUnsafe = /* @__PURE__ */ unsafeWrapper(decode);
252
+ function decodeToBytes(str) {
253
+ const { prefix, words } = decode(str, false);
254
+ return { prefix, words, bytes: fromWords(words) };
255
+ }
256
+ return { encode, decode, decodeToBytes, decodeUnsafe, fromWords, fromWordsUnsafe, toWords };
257
+ }
258
+ var bech32 = /* @__PURE__ */ genBech32("bech32");
259
+
260
+ // src/embedded/index.ts
261
+ var import_common = require("@meshsdk/common");
262
+ var import_core_cst = require("@meshsdk/core-cst");
263
+ var WalletStaticMethods = class {
264
+ static privateKeyToEntropy(bech322) {
265
+ const bech32DecodedBytes = bech32.decodeToBytes(bech322).bytes;
266
+ const bip32PrivateKey = import_core_cst.Bip32PrivateKey.fromBytes(bech32DecodedBytes);
267
+ return (0, import_common.bytesToHex)(bip32PrivateKey.bytes());
268
+ }
269
+ static mnemonicToEntropy(words) {
270
+ const entropy = (0, import_common.mnemonicToEntropy)(words.join(" "));
271
+ const bip32PrivateKey = (0, import_core_cst.buildBip32PrivateKey)(entropy);
272
+ return (0, import_common.bytesToHex)(bip32PrivateKey.bytes());
273
+ }
274
+ static signingKeyToEntropy(paymentKey, stakeKey) {
275
+ return [
276
+ paymentKey.startsWith("5820") ? paymentKey.slice(4) : paymentKey,
277
+ stakeKey.startsWith("5820") ? stakeKey.slice(4) : stakeKey
278
+ ];
279
+ }
280
+ static getAddresses(paymentKey, stakingKey, networkId = 0) {
281
+ const baseAddress = (0, import_core_cst.buildBaseAddress)(
282
+ networkId,
283
+ import_core_cst.Hash28ByteBase16.fromEd25519KeyHashHex(
284
+ (0, import_core_cst.Ed25519KeyHashHex)(paymentKey.toPublicKey().hash().toString("hex"))
285
+ ),
286
+ import_core_cst.Hash28ByteBase16.fromEd25519KeyHashHex(
287
+ (0, import_core_cst.Ed25519KeyHashHex)(stakingKey.toPublicKey().hash().toString("hex"))
288
+ )
289
+ );
290
+ const enterpriseAddress = (0, import_core_cst.buildEnterpriseAddress)(
291
+ networkId,
292
+ import_core_cst.Hash28ByteBase16.fromEd25519KeyHashHex(
293
+ (0, import_core_cst.Ed25519KeyHashHex)(paymentKey.toPublicKey().hash().toString("hex"))
294
+ )
295
+ );
296
+ const rewardAddress = (0, import_core_cst.buildRewardAddress)(
297
+ networkId,
298
+ import_core_cst.Hash28ByteBase16.fromEd25519KeyHashHex(
299
+ (0, import_core_cst.Ed25519KeyHashHex)(stakingKey.toPublicKey().hash().toString("hex"))
300
+ )
301
+ );
302
+ return {
303
+ baseAddress: baseAddress.toAddress(),
304
+ enterpriseAddress: enterpriseAddress.toAddress(),
305
+ rewardAddress: rewardAddress.toAddress()
306
+ };
307
+ }
308
+ static generateMnemonic(strength = 256) {
309
+ const mnemonic = (0, import_common.generateMnemonic)(strength);
310
+ return mnemonic.split(" ");
311
+ }
312
+ static addWitnessSets(txHex, witnesses) {
313
+ let tx = (0, import_core_cst.deserializeTx)(txHex);
314
+ let witnessSet = tx.witnessSet();
315
+ let witnessSetVkeys = witnessSet.vkeys();
316
+ let witnessSetVkeysValues = witnessSetVkeys ? [...witnessSetVkeys.values(), ...witnesses] : witnesses;
317
+ witnessSet.setVkeys(
318
+ import_core_cst.Serialization.CborSet.fromCore(
319
+ witnessSetVkeysValues.map((vkw) => vkw.toCore()),
320
+ import_core_cst.VkeyWitness.fromCore
321
+ )
322
+ );
323
+ return new import_core_cst.Transaction(tx.body(), witnessSet, tx.auxiliaryData()).toCbor();
324
+ }
325
+ };
326
+ var EmbeddedWallet = class extends WalletStaticMethods {
327
+ _entropy;
328
+ _networkId;
329
+ constructor(options) {
330
+ super();
331
+ this._networkId = options.networkId;
332
+ switch (options.key.type) {
333
+ case "mnemonic":
334
+ this._entropy = WalletStaticMethods.mnemonicToEntropy(
335
+ options.key.words
336
+ );
337
+ break;
338
+ case "root":
339
+ this._entropy = WalletStaticMethods.privateKeyToEntropy(
340
+ options.key.bech32
341
+ );
342
+ break;
343
+ case "cli":
344
+ this._entropy = WalletStaticMethods.signingKeyToEntropy(
345
+ options.key.payment,
346
+ options.key.stake ?? "f0".repeat(32)
347
+ );
348
+ break;
349
+ }
350
+ }
351
+ getAccount(accountIndex = 0, keyIndex = 0) {
352
+ if (this._entropy == void 0)
353
+ throw new Error("[EmbeddedWallet] No keys initialized");
354
+ const { paymentKey, stakeKey } = (0, import_core_cst.buildKeys)(
355
+ this._entropy,
356
+ accountIndex,
357
+ keyIndex
358
+ );
359
+ const { baseAddress, enterpriseAddress, rewardAddress } = WalletStaticMethods.getAddresses(paymentKey, stakeKey, this._networkId);
360
+ return {
361
+ baseAddress,
362
+ enterpriseAddress,
363
+ rewardAddress,
364
+ baseAddressBech32: baseAddress.toBech32(),
365
+ enterpriseAddressBech32: enterpriseAddress.toBech32(),
366
+ rewardAddressBech32: rewardAddress.toBech32(),
367
+ paymentKey,
368
+ stakeKey,
369
+ paymentKeyHex: paymentKey.toBytes().toString("hex"),
370
+ stakeKeyHex: stakeKey.toBytes().toString("hex")
371
+ };
372
+ }
373
+ getNetworkId() {
374
+ return this._networkId;
375
+ }
376
+ signData(address, payload, accountIndex = 0, keyIndex = 0) {
377
+ try {
378
+ const account = this.getAccount(accountIndex, keyIndex);
379
+ const foundAddress = [
380
+ account.baseAddress,
381
+ account.enterpriseAddress,
382
+ account.rewardAddress
383
+ ].find((a) => a.toBech32() === address);
384
+ if (foundAddress === void 0)
385
+ throw new Error(
386
+ `[EmbeddedWallet] Address: ${address} doesn't belong to this account.`
387
+ );
388
+ return (0, import_core_cst.signData)(payload, {
389
+ address: import_core_cst.Address.fromBech32(address),
390
+ key: account.paymentKey
391
+ });
392
+ } catch (error) {
393
+ throw new Error(
394
+ `[EmbeddedWallet] An error occurred during signData: ${error}.`
395
+ );
396
+ }
397
+ }
398
+ signTx(unsignedTx, accountIndex = 0, keyIndex = 0) {
399
+ try {
400
+ const txHash = (0, import_core_cst.deserializeTxHash)((0, import_core_cst.resolveTxHash)(unsignedTx));
401
+ const account = this.getAccount(accountIndex, keyIndex);
402
+ const vKeyWitness = new import_core_cst.VkeyWitness(
403
+ (0, import_core_cst.Ed25519PublicKeyHex)(
404
+ account.paymentKey.toPublicKey().toBytes().toString("hex")
405
+ ),
406
+ (0, import_core_cst.Ed25519SignatureHex)(
407
+ account.paymentKey.sign(Buffer.from(txHash, "hex")).toString("hex")
408
+ )
409
+ );
410
+ return vKeyWitness;
411
+ } catch (error) {
412
+ throw new Error(
413
+ `[EmbeddedWallet] An error occurred during signTx: ${error}.`
414
+ );
415
+ }
416
+ }
417
+ };
418
+
419
+ // src/app/index.ts
420
+ var AppWallet = class {
421
+ _fetcher;
422
+ _submitter;
423
+ _wallet;
424
+ constructor(options) {
425
+ this._fetcher = options.fetcher;
426
+ this._submitter = options.submitter;
427
+ switch (options.key.type) {
428
+ case "mnemonic":
429
+ this._wallet = new EmbeddedWallet({
430
+ networkId: options.networkId,
431
+ key: {
432
+ type: "mnemonic",
433
+ words: options.key.words
434
+ }
435
+ });
436
+ break;
437
+ case "root":
438
+ this._wallet = new EmbeddedWallet({
439
+ networkId: options.networkId,
440
+ key: {
441
+ type: "root",
442
+ bech32: options.key.bech32
443
+ }
444
+ });
445
+ break;
446
+ case "cli":
447
+ this._wallet = new EmbeddedWallet({
448
+ networkId: options.networkId,
449
+ key: {
450
+ type: "cli",
451
+ payment: options.key.payment,
452
+ stake: options.key.stake
453
+ }
454
+ });
455
+ }
456
+ }
457
+ /**
458
+ * Get a list of UTXOs to be used as collateral inputs for transactions with plutus script inputs.
459
+ *
460
+ * This is used in transaction building.
461
+ *
462
+ * @returns a list of UTXOs
463
+ */
464
+ async getCollateralUnspentOutput(accountIndex = 0, addressType = "payment") {
465
+ const utxos = await this.getUnspentOutputs(accountIndex, addressType);
466
+ const pureAdaUtxos = utxos.filter((utxo) => {
467
+ return utxo.output().amount().multiasset() === void 0;
468
+ });
469
+ pureAdaUtxos.sort((a, b) => {
470
+ return Number(a.output().amount().coin()) - Number(b.output().amount().coin());
471
+ });
472
+ for (const utxo of pureAdaUtxos) {
473
+ if (Number(utxo.output().amount().coin()) >= 5e6) {
474
+ return [utxo];
475
+ }
476
+ }
477
+ return [];
478
+ }
479
+ getEnterpriseAddress(accountIndex = 0, keyIndex = 0) {
480
+ const account = this._wallet.getAccount(accountIndex, keyIndex);
481
+ return account.enterpriseAddressBech32;
482
+ }
483
+ getPaymentAddress(accountIndex = 0, keyIndex = 0) {
484
+ const account = this._wallet.getAccount(accountIndex, keyIndex);
485
+ return account.baseAddressBech32;
486
+ }
487
+ getRewardAddress(accountIndex = 0, keyIndex = 0) {
488
+ const account = this._wallet.getAccount(accountIndex, keyIndex);
489
+ return account.rewardAddressBech32;
490
+ }
491
+ getNetworkId() {
492
+ return this._wallet.getNetworkId();
493
+ }
494
+ getUsedAddress(accountIndex = 0, keyIndex = 0, addressType = "payment") {
495
+ if (addressType === "enterprise") {
496
+ return (0, import_core_cst2.toAddress)(this.getEnterpriseAddress(accountIndex, keyIndex));
497
+ } else {
498
+ return (0, import_core_cst2.toAddress)(this.getPaymentAddress(accountIndex, keyIndex));
499
+ }
500
+ }
501
+ async getUnspentOutputs(accountIndex = 0, addressType = "payment") {
502
+ if (!this._fetcher) {
503
+ throw new Error(
504
+ "[AppWallet] Fetcher is required to fetch UTxOs. Please provide a fetcher."
505
+ );
506
+ }
507
+ const account = this._wallet.getAccount(accountIndex);
508
+ const utxos = await this._fetcher.fetchAddressUTxOs(
509
+ addressType == "enterprise" ? account.enterpriseAddressBech32 : account.baseAddressBech32
510
+ );
511
+ return utxos.map((utxo) => (0, import_core_cst2.toTxUnspentOutput)(utxo));
512
+ }
513
+ signData(address, payload, accountIndex = 0, keyIndex = 0) {
514
+ try {
515
+ return this._wallet.signData(address, payload, accountIndex, keyIndex);
516
+ } catch (error) {
517
+ throw new Error(
518
+ `[AppWallet] An error occurred during signData: ${error}.`
519
+ );
520
+ }
521
+ }
522
+ signTx(unsignedTx, partialSign = false, accountIndex = 0, keyIndex = 0) {
523
+ try {
524
+ const tx = (0, import_core_cst2.deserializeTx)(unsignedTx);
525
+ if (!partialSign && tx.witnessSet().vkeys() !== void 0 && tx.witnessSet().vkeys().size() !== 0)
526
+ throw new Error(
527
+ "Signatures already exist in the transaction in a non partial sign call"
528
+ );
529
+ const newSignatures = this._wallet.signTx(
530
+ unsignedTx,
531
+ accountIndex,
532
+ keyIndex
533
+ );
534
+ let signedTx = EmbeddedWallet.addWitnessSets(unsignedTx, [newSignatures]);
535
+ return signedTx;
536
+ } catch (error) {
537
+ throw new Error(`[AppWallet] An error occurred during signTx: ${error}.`);
538
+ }
539
+ }
540
+ signTxSync(unsignedTx, partialSign = false, accountIndex = 0, keyIndex = 0) {
541
+ try {
542
+ throw new Error(`[AppWallet] signTxSync() is not implemented.`);
543
+ } catch (error) {
544
+ throw new Error(`[AppWallet] An error occurred during signTx: ${error}.`);
545
+ }
546
+ }
547
+ async signTxs(unsignedTxs, partialSign) {
548
+ throw new Error(`[AppWallet] signTxs() is not implemented.`);
549
+ }
550
+ submitTx(tx) {
551
+ if (!this._submitter) {
552
+ throw new Error(
553
+ "[AppWallet] Submitter is required to submit transactions. Please provide a submitter."
554
+ );
555
+ }
556
+ return this._submitter.submitTx(tx);
557
+ }
558
+ static brew(strength = 256) {
559
+ return EmbeddedWallet.generateMnemonic(strength);
560
+ }
561
+ };
562
+
563
+ // src/browser/index.ts
564
+ var import_common2 = require("@meshsdk/common");
565
+ var import_core_cst3 = require("@meshsdk/core-cst");
566
+
567
+ // src/browser/metamask.ts
568
+ var import_dapp_client_cardano = require("@nufi/dapp-client-cardano");
569
+ var import_dapp_client_core = __toESM(require("@nufi/dapp-client-core"), 1);
570
+
571
+ // src/types/nufisnap.ts
572
+ var nufiSnap = {
573
+ id: "nufiSnap",
574
+ name: "MetaMask",
575
+ icon: "data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0iVVRGLTgiPz4KPHN2ZyBpZD0iTGF5ZXJfMiIgZGF0YS1uYW1lPSJMYXllciAyIiB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHZpZXdCb3g9IjAgMCAxNjkuMiAxNjMuNzEiPgogIDxkZWZzPgogICAgPHN0eWxlPgogICAgICAuY2xzLTEgewogICAgICAgIGZpbGw6ICNlMjc2MjU7CiAgICAgIH0KCiAgICAgIC5jbHMtMSwgLmNscy0yLCAuY2xzLTMsIC5jbHMtNCwgLmNscy01LCAuY2xzLTYsIC5jbHMtNywgLmNscy04LCAuY2xzLTkgewogICAgICAgIHN0cm9rZS13aWR0aDogMHB4OwogICAgICB9CgogICAgICAuY2xzLTIgewogICAgICAgIGZpbGw6ICM3NjNlMWE7CiAgICAgIH0KCiAgICAgIC5jbHMtMyB7CiAgICAgICAgZmlsbDogI2MwYWQ5ZTsKICAgICAgfQoKICAgICAgLmNscy00IHsKICAgICAgICBmaWxsOiAjMzQ2OGQxOwogICAgICB9CgogICAgICAuY2xzLTUgewogICAgICAgIGZpbGw6ICNjYzYyMjg7CiAgICAgIH0KCiAgICAgIC5jbHMtNiB7CiAgICAgICAgZmlsbDogI2Y1ODQxZjsKICAgICAgfQoKICAgICAgLmNscy03IHsKICAgICAgICBmaWxsOiAjZDdjMWIzOwogICAgICB9CgogICAgICAuY2xzLTggewogICAgICAgIGZpbGw6ICNmZmY7CiAgICAgICAgZmlsbC1ydWxlOiBldmVub2RkOwogICAgICB9CgogICAgICAuY2xzLTkgewogICAgICAgIGZpbGw6ICMyZjM0M2I7CiAgICAgIH0KICAgIDwvc3R5bGU+CiAgPC9kZWZzPgogIDxnIGlkPSJMYXllcl8xLTIiIGRhdGEtbmFtZT0iTGF5ZXIgMSI+CiAgICA8ZyBpZD0iTU1f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TMtLjc1LDEuNjgtMS42OCwxLjY4LS45MywwLTEuNjgtLjc1LTEuNjgtMS42OHMuNzUtMS42OCwxLjY4LTEuNjhoMFpNMTQzLjI0LDE0Ni42OGMuNzcsMCwxLjQuNjMsMS40LDEuNCwwLC43Ny0uNjMsMS40LTEuNCwxLjRzLTEuNC0uNjMtMS40LTEuNGgwYzAtLjc3LjYzLTEuNCwxLjQtMS40Wk0xMTMuNSwxNDYuNjhjLjc3LDAsMS40LjYzLDEuNCwxLjRzLS42MywxLjQtMS40LDEuNC0xLjQtLjYzLTEuNC0xLjRoMGMwLS43Ny42My0xLjQsMS40LTEuNFpNMTEzLjUsOTUuNjNjLjc3LDAsMS40LjYzLDEuNCwxLjRzLS42MywxLjQtMS40LDEuNC0xLjQtLjYzLTEuNC0xLjRoMGMwLS43Ny42My0xLjQsMS40LTEuNGgwWk0xNDMuMjQsOTUuNjNjLjc3LDAsMS40LjYzLDEuNCwxLjQsMCwuNzctLjYzLDEuNC0xLjQsMS40cy0xLjQtLjYzLTEuNC0xLjRoMGMwLS43Ny42My0xLjQsMS40LTEuNGgwWk0xNTcuODMsMTIxLjE2Yy43NywwLDEuNC42MywxLjQsMS40LDAsLjc3LS42MywxLjQtMS40LDEuNHMtMS40LS42My0xLjQtMS40aDBjMC0uNzguNjMtMS40LDEuNC0xLjRoMFpNOTguOTEsMTIxLjE2Yy43NywwLDEuNC42MywxLjQsMS40cy0uNjMsMS40LTEuNCwxLjQtMS40LS42My0xLjQtMS40aDBjMC0uNzguNjMtMS40LDEuNC0xLjRoMFoiLz4KICAgICAgPC9nPgogICAgPC9nPgogIDwvZz4KPC9zdmc+",
576
+ version: "version"
577
+ };
578
+
579
+ // src/browser/metamask.ts
580
+ var nufiDomain = {
581
+ production: "https://wallet.nu.fi",
582
+ mainnet: "https://wallet-staging.nu.fi",
583
+ preprod: "https://wallet-testnet-staging.nu.fi",
584
+ preview: "https://wallet-preview-staging.nu.fi"
585
+ };
586
+ async function checkIfMetamaskInstalled(network = "preprod") {
587
+ try {
588
+ const _nufiCoreSdk = import_dapp_client_core.default.default;
589
+ if (Object.keys(nufiDomain).includes(network)) {
590
+ _nufiCoreSdk.init(nufiDomain[network]);
591
+ } else {
592
+ _nufiCoreSdk.init(network);
593
+ }
594
+ const metamask = window.ethereum._metamask;
595
+ if (metamask) {
596
+ (0, import_dapp_client_cardano.initNufiDappCardanoSdk)(_nufiCoreSdk, "snap");
597
+ return nufiSnap;
598
+ }
599
+ return void 0;
600
+ } catch (err) {
601
+ return Promise.resolve(void 0);
602
+ }
603
+ }
604
+
605
+ // src/browser/index.ts
606
+ var BrowserWallet = class _BrowserWallet {
607
+ constructor(_walletInstance, _walletName) {
608
+ this._walletInstance = _walletInstance;
609
+ this._walletName = _walletName;
610
+ this.walletInstance = { ..._walletInstance };
611
+ }
612
+ walletInstance;
613
+ /**
614
+ * Returns a list of wallets installed on user's device. Each wallet is an object with the following properties:
615
+ * - A name is provided to display wallet's name on the user interface.
616
+ * - A version is provided to display wallet's version on the user interface.
617
+ * - An icon is provided to display wallet's icon on the user interface.
618
+ *
619
+ * @returns a list of wallet names
620
+ */
621
+ static async getAvailableWallets({
622
+ metamask = {
623
+ network: "preprod"
624
+ }
625
+ } = {}) {
626
+ if (window === void 0) return [];
627
+ if (metamask) await checkIfMetamaskInstalled(metamask.network);
628
+ const wallets = _BrowserWallet.getInstalledWallets();
629
+ return wallets;
630
+ }
631
+ /**
632
+ * Returns a list of wallets installed on user's device. Each wallet is an object with the following properties:
633
+ * - A name is provided to display wallet's name on the user interface.
634
+ * - A version is provided to display wallet's version on the user interface.
635
+ * - An icon is provided to display wallet's icon on the user interface.
636
+ *
637
+ * @returns a list of wallet names
638
+ */
639
+ static getInstalledWallets() {
640
+ if (window === void 0) return [];
641
+ if (window.cardano === void 0) return [];
642
+ let wallets = [];
643
+ for (const key in window.cardano) {
644
+ try {
645
+ const _wallet = window.cardano[key];
646
+ if (_wallet === void 0) continue;
647
+ if (_wallet.name === void 0) continue;
648
+ if (_wallet.icon === void 0) continue;
649
+ if (_wallet.apiVersion === void 0) continue;
650
+ wallets.push({
651
+ id: key,
652
+ name: key == "nufiSnap" ? "MetaMask" : _wallet.name,
653
+ icon: _wallet.icon,
654
+ version: _wallet.apiVersion
655
+ });
656
+ } catch (e) {
657
+ }
658
+ }
659
+ return wallets;
660
+ }
661
+ /**
662
+ * This is the entrypoint to start communication with the user's wallet. The wallet should request the user's permission to connect the web page to the user's wallet, and if permission has been granted, the wallet will be returned and exposing the full API for the dApp to use.
663
+ *
664
+ * Query BrowserWallet.getInstalledWallets() to get a list of available wallets, then provide the wallet name for which wallet the user would like to connect with.
665
+ *
666
+ * @param walletName - the name of the wallet to enable (e.g. "eternl", "begin", "nufiSnap")
667
+ * @param extensions - optional, a list of CIPs that the wallet should support
668
+ * @returns WalletInstance
669
+ */
670
+ static async enable(walletName, extensions = []) {
671
+ try {
672
+ const walletInstance = await _BrowserWallet.resolveInstance(
673
+ walletName,
674
+ extensions
675
+ );
676
+ if (walletInstance !== void 0)
677
+ return new _BrowserWallet(walletInstance, walletName);
678
+ throw new Error(`Couldn't create an instance of wallet: ${walletName}`);
679
+ } catch (error) {
680
+ throw new Error(
681
+ `[BrowserWallet] An error occurred during enable: ${JSON.stringify(
682
+ error
683
+ )}.`
684
+ );
685
+ }
686
+ }
687
+ /**
688
+ * Returns a list of assets in the wallet. This API will return every assets in the wallet. Each asset is an object with the following properties:
689
+ * - A unit is provided to display asset's name on the user interface.
690
+ * - A quantity is provided to display asset's quantity on the user interface.
691
+ *
692
+ * @returns a list of assets and their quantities
693
+ */
694
+ async getBalance() {
695
+ const balance = await this._walletInstance.getBalance();
696
+ return (0, import_core_cst3.fromValue)((0, import_core_cst3.deserializeValue)(balance));
697
+ }
698
+ /**
699
+ * Returns an address owned by the wallet that should be used as a change address to return leftover assets during transaction creation back to the connected wallet.
700
+ *
701
+ * @returns an address
702
+ */
703
+ async getChangeAddress() {
704
+ const changeAddress = await this._walletInstance.getChangeAddress();
705
+ return (0, import_core_cst3.addressToBech32)((0, import_core_cst3.deserializeAddress)(changeAddress));
706
+ }
707
+ /**
708
+ * This function shall return a list of one or more UTXOs (unspent transaction outputs) controlled by the wallet that are required to reach AT LEAST the combined ADA value target specified in amount AND the best suitable to be used as collateral inputs for transactions with plutus script inputs (pure ADA-only UTXOs).
709
+ *
710
+ * If this cannot be attained, an error message with an explanation of the blocking problem shall be returned. NOTE: wallets are free to return UTXOs that add up to a greater total ADA value than requested in the amount parameter, but wallets must never return any result where UTXOs would sum up to a smaller total ADA value, instead in a case like that an error message must be returned.
711
+ *
712
+ * @param limit
713
+ * @returns a list of UTXOs
714
+ */
715
+ async getCollateral() {
716
+ const deserializedCollateral = await this.getCollateralUnspentOutput();
717
+ return deserializedCollateral.map((dc) => (0, import_core_cst3.fromTxUnspentOutput)(dc));
718
+ }
719
+ /**
720
+ * Return a list of supported CIPs of the wallet.
721
+ *
722
+ * @returns a list of CIPs
723
+ */
724
+ async getExtensions() {
725
+ try {
726
+ const _extensions = await this._walletInstance.getExtensions();
727
+ return _extensions.map((e) => e.cip);
728
+ } catch (e) {
729
+ return [];
730
+ }
731
+ }
732
+ /**
733
+ * Returns the network ID of the currently connected account. 0 is testnet and 1 is mainnet but other networks can possibly be returned by wallets. Those other network ID values are not governed by CIP-30. This result will stay the same unless the connected account has changed.
734
+ *
735
+ * @returns network ID
736
+ */
737
+ getNetworkId() {
738
+ return this._walletInstance.getNetworkId();
739
+ }
740
+ /**
741
+ * Returns a list of reward addresses owned by the wallet. A reward address is a stake address that is used to receive rewards from staking, generally starts from `stake` prefix.
742
+ *
743
+ * @returns a list of reward addresses
744
+ */
745
+ async getRewardAddresses() {
746
+ const rewardAddresses = await this._walletInstance.getRewardAddresses();
747
+ return rewardAddresses.map((ra) => (0, import_core_cst3.addressToBech32)((0, import_core_cst3.deserializeAddress)(ra)));
748
+ }
749
+ /**
750
+ * Returns a list of unused addresses controlled by the wallet.
751
+ *
752
+ * @returns a list of unused addresses
753
+ */
754
+ async getUnusedAddresses() {
755
+ const unusedAddresses = await this._walletInstance.getUnusedAddresses();
756
+ return unusedAddresses.map(
757
+ (una) => (0, import_core_cst3.addressToBech32)((0, import_core_cst3.deserializeAddress)(una))
758
+ );
759
+ }
760
+ /**
761
+ * Returns a list of used addresses controlled by the wallet.
762
+ *
763
+ * @returns a list of used addresses
764
+ */
765
+ async getUsedAddresses() {
766
+ const usedAddresses = await this._walletInstance.getUsedAddresses();
767
+ return usedAddresses.map((usa) => (0, import_core_cst3.addressToBech32)((0, import_core_cst3.deserializeAddress)(usa)));
768
+ }
769
+ /**
770
+ * Get a list of UTXOs to be used as collateral inputs for transactions with plutus script inputs.
771
+ *
772
+ * This is used in transaction building.
773
+ *
774
+ * @returns a list of UTXOs
775
+ */
776
+ async getUsedCollateral(limit = import_common2.DEFAULT_PROTOCOL_PARAMETERS.maxCollateralInputs) {
777
+ const collateral = await this._walletInstance.experimental.getCollateral() ?? [];
778
+ return collateral.map((c) => (0, import_core_cst3.deserializeTxUnspentOutput)(c)).slice(0, limit);
779
+ }
780
+ /**
781
+ * Return a list of all UTXOs (unspent transaction outputs) controlled by the wallet.
782
+ *
783
+ * @returns a list of UTXOs
784
+ */
785
+ async getUtxos() {
786
+ const deserializedUTxOs = await this.getUsedUTxOs();
787
+ return deserializedUTxOs.map((du) => (0, import_core_cst3.fromTxUnspentOutput)(du));
788
+ }
789
+ /**
790
+ * This endpoint utilizes the [CIP-8 - Message Signing](https://cips.cardano.org/cips/cip8/) to sign arbitrary data, to verify the data was signed by the owner of the private key.
791
+ *
792
+ * @param payload - the data to be signed
793
+ * @param address - optional, if not provided, the first staking address will be used
794
+ * @returns a signature
795
+ */
796
+ async signData(payload, address) {
797
+ if (address === void 0) {
798
+ address = (await this.getUsedAddresses())[0];
799
+ }
800
+ const signerAddress = (0, import_core_cst3.toAddress)(address).toBytes().toString();
801
+ return this._walletInstance.signData(signerAddress, (0, import_common2.fromUTF8)(payload));
802
+ }
803
+ /**
804
+ * Requests user to sign the provided transaction (tx). The wallet should ask the user for permission, and if given, try to sign the supplied body and return a signed transaction. partialSign should be true if the transaction provided requires multiple signatures.
805
+ *
806
+ * @param unsignedTx - a transaction in CBOR
807
+ * @param partialSign - if the transaction is signed partially
808
+ * @returns a signed transaction in CBOR
809
+ */
810
+ async signTx(unsignedTx, partialSign = false) {
811
+ const witness = await this._walletInstance.signTx(unsignedTx, partialSign);
812
+ return _BrowserWallet.addBrowserWitnesses(unsignedTx, witness);
813
+ }
814
+ /**
815
+ * Experimental feature - sign multiple transactions at once (Supported wallet(s): Typhon)
816
+ *
817
+ * @param unsignedTxs - array of unsigned transactions in CborHex string
818
+ * @param partialSign - if the transactions are signed partially
819
+ * @returns array of signed transactions CborHex string
820
+ */
821
+ async signTxs(unsignedTxs, partialSign = false) {
822
+ let witnessSets = void 0;
823
+ switch (this._walletName) {
824
+ case "Typhon Wallet":
825
+ if (this._walletInstance.signTxs) {
826
+ witnessSets = await this._walletInstance.signTxs(
827
+ unsignedTxs,
828
+ partialSign
829
+ );
830
+ }
831
+ break;
832
+ default:
833
+ if (this._walletInstance.signTxs) {
834
+ witnessSets = await this._walletInstance.signTxs(
835
+ unsignedTxs.map((cbor) => ({
836
+ cbor,
837
+ partialSign
838
+ }))
839
+ );
840
+ } else if (this._walletInstance.experimental.signTxs) {
841
+ witnessSets = await this._walletInstance.experimental.signTxs(
842
+ unsignedTxs.map((cbor) => ({
843
+ cbor,
844
+ partialSign
845
+ }))
846
+ );
847
+ }
848
+ break;
849
+ }
850
+ if (!witnessSets) throw new Error("Wallet does not support signTxs");
851
+ const signedTxs = [];
852
+ for (let i = 0; i < witnessSets.length; i++) {
853
+ const unsignedTx = unsignedTxs[i];
854
+ const cWitness = witnessSets[i];
855
+ const signedTx = _BrowserWallet.addBrowserWitnesses(unsignedTx, cWitness);
856
+ signedTxs.push(signedTx);
857
+ }
858
+ return signedTxs;
859
+ }
860
+ /**
861
+ * Submits the signed transaction to the blockchain network.
862
+ *
863
+ * As wallets should already have this ability to submit transaction, we allow dApps to request that a transaction be sent through it. If the wallet accepts the transaction and tries to send it, it shall return the transaction ID for the dApp to track. The wallet can return error messages or failure if there was an error in sending it.
864
+ *
865
+ * @param tx
866
+ * @returns a transaction hash
867
+ */
868
+ submitTx(tx) {
869
+ return this._walletInstance.submitTx(tx);
870
+ }
871
+ /**
872
+ * Get a used address of type Address from the wallet.
873
+ *
874
+ * This is used in transaction building.
875
+ *
876
+ * @returns an Address object
877
+ */
878
+ async getUsedAddress() {
879
+ const usedAddresses = await this._walletInstance.getUsedAddresses();
880
+ if (usedAddresses.length === 0) throw new Error("No used addresses found");
881
+ return (0, import_core_cst3.deserializeAddress)(usedAddresses[0]);
882
+ }
883
+ /**
884
+ * Get a list of UTXOs to be used as collateral inputs for transactions with plutus script inputs.
885
+ *
886
+ * This is used in transaction building.
887
+ *
888
+ * @returns a list of UTXOs
889
+ */
890
+ async getCollateralUnspentOutput() {
891
+ const collateral = await this._walletInstance.experimental.getCollateral() ?? [];
892
+ return collateral.map((c) => (0, import_core_cst3.deserializeTxUnspentOutput)(c));
893
+ }
894
+ /**
895
+ * Get a list of UTXOs to be used for transaction building.
896
+ *
897
+ * This is used in transaction building.
898
+ *
899
+ * @returns a list of UTXOs
900
+ */
901
+ async getUsedUTxOs() {
902
+ const utxos = await this._walletInstance.getUtxos() ?? [];
903
+ return utxos.map((u) => (0, import_core_cst3.deserializeTxUnspentOutput)(u));
904
+ }
905
+ /**
906
+ * A helper function to get the assets in the wallet.
907
+ *
908
+ * @returns a list of assets
909
+ */
910
+ async getAssets() {
911
+ const balance = await this.getBalance();
912
+ return balance.filter((v) => v.unit !== "lovelace").map((v) => {
913
+ const policyId = v.unit.slice(0, import_common2.POLICY_ID_LENGTH);
914
+ const assetName = v.unit.slice(import_common2.POLICY_ID_LENGTH);
915
+ const fingerprint = (0, import_common2.resolveFingerprint)(policyId, assetName);
916
+ return {
917
+ unit: v.unit,
918
+ policyId,
919
+ assetName,
920
+ fingerprint,
921
+ quantity: v.quantity
922
+ };
923
+ });
924
+ }
925
+ /**
926
+ * A helper function to get the lovelace balance in the wallet.
927
+ *
928
+ * @returns lovelace balance
929
+ */
930
+ async getLovelace() {
931
+ const balance = await this.getBalance();
932
+ const nativeAsset = balance.find((v) => v.unit === "lovelace");
933
+ return nativeAsset !== void 0 ? nativeAsset.quantity : "0";
934
+ }
935
+ /**
936
+ * A helper function to get the assets of a specific policy ID in the wallet.
937
+ *
938
+ * @param policyId
939
+ * @returns a list of assets
940
+ */
941
+ async getPolicyIdAssets(policyId) {
942
+ const assets = await this.getAssets();
943
+ return assets.filter((v) => v.policyId === policyId);
944
+ }
945
+ /**
946
+ * A helper function to get the policy IDs of all the assets in the wallet.
947
+ *
948
+ * @returns a list of policy IDs
949
+ */
950
+ async getPolicyIds() {
951
+ const balance = await this.getBalance();
952
+ return Array.from(
953
+ new Set(balance.map((v) => v.unit.slice(0, import_common2.POLICY_ID_LENGTH)))
954
+ ).filter((p) => p !== "lovelace");
955
+ }
956
+ async getPubDRepKey() {
957
+ try {
958
+ if (this._walletInstance.cip95 === void 0) return void 0;
959
+ const dRepKey = await this._walletInstance.cip95.getPubDRepKey();
960
+ const dRepKeyHex = (0, import_core_cst3.Ed25519PublicKeyHex)(dRepKey);
961
+ const dRepID = import_core_cst3.Ed25519PublicKey.fromHex(dRepKeyHex);
962
+ const dRepIDHex = (await dRepID.hash()).hex();
963
+ const networkId = await this.getNetworkId();
964
+ const dRepId = (0, import_core_cst3.buildDRepID)(dRepKeyHex, networkId);
965
+ return {
966
+ pubDRepKey: dRepKey,
967
+ dRepIDHash: dRepIDHex,
968
+ dRepIDBech32: dRepId
969
+ // todo to check
970
+ };
971
+ } catch (e) {
972
+ console.log(e);
973
+ return void 0;
974
+ }
975
+ }
976
+ async getRegisteredPubStakeKeys() {
977
+ try {
978
+ if (this._walletInstance.cip95 === void 0) return void 0;
979
+ const pubStakeKeys = await this._walletInstance.cip95.getRegisteredPubStakeKeys();
980
+ const pubStakeKeyHashes = await Promise.all(
981
+ pubStakeKeys.map(async (pubStakeKey) => {
982
+ const pubStakeKeyHex = (0, import_core_cst3.Ed25519PublicKeyHex)(pubStakeKey);
983
+ const pubStakeKeyPubKey = import_core_cst3.Ed25519PublicKey.fromHex(pubStakeKeyHex);
984
+ const pubStakeKeyHash = (await pubStakeKeyPubKey.hash()).hex();
985
+ return pubStakeKeyHash.toString();
986
+ })
987
+ );
988
+ return {
989
+ pubStakeKeys,
990
+ pubStakeKeyHashes
991
+ };
992
+ } catch (e) {
993
+ console.log(e);
994
+ return void 0;
995
+ }
996
+ }
997
+ static resolveInstance(walletName, extensions = []) {
998
+ if (window.cardano === void 0) return void 0;
999
+ if (window.cardano[walletName] === void 0) return void 0;
1000
+ const wallet = window.cardano[walletName];
1001
+ if (extensions.length > 0) {
1002
+ const _extensions = extensions.map((e) => ({ cip: e }));
1003
+ return wallet.enable({ extensions: _extensions });
1004
+ } else {
1005
+ return wallet?.enable();
1006
+ }
1007
+ }
1008
+ static addBrowserWitnesses(unsignedTx, witnesses) {
1009
+ const cWitness = import_core_cst3.Serialization.TransactionWitnessSet.fromCbor(
1010
+ import_core_cst3.CardanoSDKUtil.HexBlob(witnesses)
1011
+ ).vkeys()?.values();
1012
+ if (cWitness === void 0) {
1013
+ return unsignedTx;
1014
+ }
1015
+ let tx = (0, import_core_cst3.deserializeTx)(unsignedTx);
1016
+ let witnessSet = tx.witnessSet();
1017
+ let witnessSetVkeys = witnessSet.vkeys();
1018
+ let witnessSetVkeysValues = witnessSetVkeys ? [...witnessSetVkeys.values(), ...cWitness] : [...cWitness];
1019
+ witnessSet.setVkeys(
1020
+ import_core_cst3.Serialization.CborSet.fromCore(
1021
+ witnessSetVkeysValues.map((vkw) => vkw.toCore()),
1022
+ import_core_cst3.VkeyWitness.fromCore
1023
+ )
1024
+ );
1025
+ return new import_core_cst3.Transaction(tx.body(), witnessSet, tx.auxiliaryData()).toCbor();
1026
+ }
1027
+ static getSupportedExtensions(wallet) {
1028
+ const _supportedExtensions = window?.cardano?.[wallet]?.supportedExtensions;
1029
+ if (_supportedExtensions) return _supportedExtensions;
1030
+ else return [];
1031
+ }
1032
+ };
1033
+
1034
+ // src/mesh/index.ts
1035
+ var import_common3 = require("@meshsdk/common");
1036
+ var import_core_csl = require("@meshsdk/core-csl");
1037
+ var import_core_cst4 = require("@meshsdk/core-cst");
1038
+ var import_transaction = require("@meshsdk/transaction");
1039
+ var MeshWallet = class {
1040
+ _wallet;
1041
+ // private readonly _account: Account;
1042
+ _accountIndex = 0;
1043
+ _keyIndex = 0;
1044
+ _fetcher;
1045
+ _submitter;
1046
+ _networkId;
1047
+ _addresses = {};
1048
+ constructor(options) {
1049
+ switch (options.key.type) {
1050
+ case "root":
1051
+ this._wallet = new EmbeddedWallet({
1052
+ networkId: options.networkId,
1053
+ key: {
1054
+ type: "root",
1055
+ bech32: options.key.bech32
1056
+ }
1057
+ });
1058
+ this.getAddressesFromWallet(this._wallet);
1059
+ break;
1060
+ case "cli":
1061
+ this._wallet = new EmbeddedWallet({
1062
+ networkId: options.networkId,
1063
+ key: {
1064
+ type: "cli",
1065
+ payment: options.key.payment,
1066
+ stake: options.key.stake
1067
+ }
1068
+ });
1069
+ this.getAddressesFromWallet(this._wallet);
1070
+ break;
1071
+ case "mnemonic":
1072
+ this._wallet = new EmbeddedWallet({
1073
+ networkId: options.networkId,
1074
+ key: {
1075
+ type: "mnemonic",
1076
+ words: options.key.words
1077
+ }
1078
+ });
1079
+ this.getAddressesFromWallet(this._wallet);
1080
+ break;
1081
+ }
1082
+ this._networkId = options.networkId;
1083
+ if (options.fetcher) this._fetcher = options.fetcher;
1084
+ if (options.submitter) this._submitter = options.submitter;
1085
+ if (options.accountIndex) this._accountIndex = options.accountIndex;
1086
+ if (options.keyIndex) this._keyIndex = options.keyIndex;
1087
+ }
1088
+ /**
1089
+ * Returns a list of assets in the wallet. This API will return every assets in the wallet. Each asset is an object with the following properties:
1090
+ * - A unit is provided to display asset's name on the user interface.
1091
+ * - A quantity is provided to display asset's quantity on the user interface.
1092
+ *
1093
+ * @returns a list of assets and their quantities
1094
+ */
1095
+ async getBalance() {
1096
+ const utxos = await this.getUnspentOutputs();
1097
+ const assets = /* @__PURE__ */ new Map();
1098
+ utxos.map((utxo) => {
1099
+ const _utxo = (0, import_core_cst4.fromTxUnspentOutput)(utxo);
1100
+ _utxo.output.amount.map((asset) => {
1101
+ const assetId = asset.unit;
1102
+ const amount = Number(asset.quantity);
1103
+ if (assets.has(assetId)) {
1104
+ const quantity = assets.get(assetId);
1105
+ assets.set(assetId, quantity + amount);
1106
+ } else {
1107
+ assets.set(assetId, amount);
1108
+ }
1109
+ });
1110
+ });
1111
+ const arrayAssets = Array.from(assets, ([unit, quantity]) => ({
1112
+ unit,
1113
+ quantity: quantity.toString()
1114
+ }));
1115
+ return arrayAssets;
1116
+ }
1117
+ /**
1118
+ * Returns an address owned by the wallet that should be used as a change address to return leftover assets during transaction creation back to the connected wallet.
1119
+ *
1120
+ * @returns an address
1121
+ */
1122
+ getChangeAddress() {
1123
+ return this._addresses.baseAddressBech32;
1124
+ }
1125
+ /**
1126
+ * This function shall return a list of one or more UTXOs (unspent transaction outputs) controlled by the wallet that are required to reach AT LEAST the combined ADA value target specified in amount AND the best suitable to be used as collateral inputs for transactions with plutus script inputs (pure ADA-only UTXOs).
1127
+ *
1128
+ * If this cannot be attained, an error message with an explanation of the blocking problem shall be returned. NOTE: wallets are free to return UTXOs that add up to a greater total ADA value than requested in the amount parameter, but wallets must never return any result where UTXOs would sum up to a smaller total ADA value, instead in a case like that an error message must be returned.
1129
+ *
1130
+ * @param addressType - the type of address to fetch UTXOs from (default: payment)
1131
+ * @returns a list of UTXOs
1132
+ */
1133
+ async getCollateral(addressType = "payment") {
1134
+ const utxos = await this.getCollateralUnspentOutput(addressType);
1135
+ return utxos.map((utxo, i) => {
1136
+ return (0, import_core_cst4.fromTxUnspentOutput)(utxo);
1137
+ });
1138
+ }
1139
+ /**
1140
+ * Get a list of UTXOs to be used as collateral inputs for transactions with plutus script inputs.
1141
+ *
1142
+ * This is used in transaction building.
1143
+ *
1144
+ * @param addressType - the type of address to fetch UTXOs from (default: payment)
1145
+ * @returns a list of UTXOs
1146
+ */
1147
+ async getCollateralUnspentOutput(addressType = "payment") {
1148
+ const utxos = await this.getUnspentOutputs(addressType);
1149
+ const pureAdaUtxos = utxos.filter((utxo) => {
1150
+ return utxo.output().amount().multiasset() === void 0;
1151
+ });
1152
+ pureAdaUtxos.sort((a, b) => {
1153
+ return Number(a.output().amount().coin()) - Number(b.output().amount().coin());
1154
+ });
1155
+ for (const utxo of pureAdaUtxos) {
1156
+ if (Number(utxo.output().amount().coin()) >= 5e6) {
1157
+ return [utxo];
1158
+ }
1159
+ }
1160
+ return [];
1161
+ }
1162
+ /**
1163
+ * Returns the network ID of the currently connected account. 0 is testnet and 1 is mainnet but other networks can possibly be returned by wallets. Those other network ID values are not governed by CIP-30. This result will stay the same unless the connected account has changed.
1164
+ *
1165
+ * @returns network ID
1166
+ */
1167
+ getNetworkId() {
1168
+ return this._networkId;
1169
+ }
1170
+ /**
1171
+ * Returns a list of reward addresses owned by the wallet. A reward address is a stake address that is used to receive rewards from staking, generally starts from `stake` prefix.
1172
+ *
1173
+ * @returns a list of reward addresses
1174
+ */
1175
+ getRewardAddresses() {
1176
+ return [this._addresses.rewardAddressBech32];
1177
+ }
1178
+ /**
1179
+ * Returns a list of unused addresses controlled by the wallet.
1180
+ *
1181
+ * @returns a list of unused addresses
1182
+ */
1183
+ getUnusedAddresses() {
1184
+ return [this.getChangeAddress()];
1185
+ }
1186
+ /**
1187
+ * Returns a list of used addresses controlled by the wallet.
1188
+ *
1189
+ * @returns a list of used addresses
1190
+ */
1191
+ getUsedAddresses() {
1192
+ return [this.getChangeAddress()];
1193
+ }
1194
+ /**
1195
+ * Get a list of UTXOs to be used as collateral inputs for transactions with plutus script inputs.
1196
+ *
1197
+ * This is used in transaction building.
1198
+ *
1199
+ * @returns a list of UTXOs
1200
+ */
1201
+ async getUsedCollateral() {
1202
+ const collateralUtxo = await this.getCollateral();
1203
+ const unspentOutput = collateralUtxo.map((utxo) => {
1204
+ return (0, import_core_cst4.toTxUnspentOutput)(utxo);
1205
+ });
1206
+ return unspentOutput;
1207
+ }
1208
+ /**
1209
+ * Get a list of UTXOs to be used for transaction building.
1210
+ *
1211
+ * This is used in transaction building.
1212
+ *
1213
+ * @param addressType - the type of address to fetch UTXOs from (default: payment)
1214
+ * @returns a list of UTXOs
1215
+ */
1216
+ async getUsedUTxOs(addressType) {
1217
+ return await this.getUnspentOutputs(addressType);
1218
+ }
1219
+ /**
1220
+ * Return a list of all UTXOs (unspent transaction outputs) controlled by the wallet.
1221
+ *
1222
+ * @param addressType - the type of address to fetch UTXOs from (default: payment)
1223
+ * @returns a list of UTXOs
1224
+ */
1225
+ async getUtxos(addressType) {
1226
+ const utxos = await this.getUsedUTxOs(addressType);
1227
+ return utxos.map((c) => (0, import_core_cst4.fromTxUnspentOutput)(c));
1228
+ }
1229
+ /**
1230
+ * This endpoint utilizes the [CIP-8 - Message Signing](https://cips.cardano.org/cips/cip8/) to sign arbitrary data, to verify the data was signed by the owner of the private key.
1231
+ *
1232
+ * @param payload - the payload to sign
1233
+ * @param address - the address to use for signing (optional)
1234
+ * @returns a signature
1235
+ */
1236
+ signData(payload, address) {
1237
+ if (!this._wallet) {
1238
+ throw new Error(
1239
+ "[MeshWallet] Read only wallet does not support signing data."
1240
+ );
1241
+ }
1242
+ if (address === void 0) {
1243
+ address = this.getChangeAddress();
1244
+ }
1245
+ return this._wallet.signData(address, payload);
1246
+ }
1247
+ /**
1248
+ * Requests user to sign the provided transaction (tx). The wallet should ask the user for permission, and if given, try to sign the supplied body and return a signed transaction. partialSign should be true if the transaction provided requires multiple signatures.
1249
+ *
1250
+ * @param unsignedTx - a transaction in CBOR
1251
+ * @param partialSign - if the transaction is partially signed (default: false)
1252
+ * @returns a signed transaction in CBOR
1253
+ */
1254
+ signTx(unsignedTx, partialSign = false) {
1255
+ if (!this._wallet) {
1256
+ throw new Error(
1257
+ "[MeshWallet] Read only wallet does not support signing data."
1258
+ );
1259
+ }
1260
+ const tx = (0, import_core_cst4.deserializeTx)(unsignedTx);
1261
+ if (!partialSign && tx.witnessSet().vkeys() !== void 0 && tx.witnessSet().vkeys().size() !== 0)
1262
+ throw new Error(
1263
+ "Signatures already exist in the transaction in a non partial sign call"
1264
+ );
1265
+ const newSignatures = this._wallet.signTx(
1266
+ unsignedTx,
1267
+ this._accountIndex,
1268
+ this._keyIndex
1269
+ );
1270
+ let signedTx = EmbeddedWallet.addWitnessSets(unsignedTx, [newSignatures]);
1271
+ return signedTx;
1272
+ }
1273
+ /**
1274
+ * Experimental feature - sign multiple transactions at once.
1275
+ *
1276
+ * @param unsignedTxs - array of unsigned transactions in CborHex string
1277
+ * @param partialSign - if the transactions are signed partially
1278
+ * @returns array of signed transactions CborHex string
1279
+ */
1280
+ signTxs(unsignedTxs, partialSign = false) {
1281
+ const signedTxs = [];
1282
+ for (const unsignedTx of unsignedTxs) {
1283
+ const signedTx = this.signTx(unsignedTx, partialSign);
1284
+ signedTxs.push(signedTx);
1285
+ }
1286
+ return signedTxs;
1287
+ }
1288
+ /**
1289
+ * Submits the signed transaction to the blockchain network.
1290
+ *
1291
+ * As wallets should already have this ability to submit transaction, we allow dApps to request that a transaction be sent through it. If the wallet accepts the transaction and tries to send it, it shall return the transaction ID for the dApp to track. The wallet can return error messages or failure if there was an error in sending it.
1292
+ *
1293
+ * @param tx - a signed transaction in CBOR
1294
+ * @returns a transaction hash
1295
+ */
1296
+ async submitTx(tx) {
1297
+ if (!this._submitter) {
1298
+ throw new Error(
1299
+ "[AppWallet] Submitter is required to submit transactions. Please provide a submitter."
1300
+ );
1301
+ }
1302
+ return this._submitter.submitTx(tx);
1303
+ }
1304
+ /**
1305
+ * Get a used address of type Address from the wallet.
1306
+ *
1307
+ * This is used in transaction building.
1308
+ *
1309
+ * @param addressType - the type of address to fetch UTXOs from (default: payment)
1310
+ * @returns an Address object
1311
+ */
1312
+ getUsedAddress(addressType) {
1313
+ if (addressType === "enterprise") {
1314
+ return (0, import_core_cst4.toAddress)(this._addresses.enterpriseAddressBech32);
1315
+ } else {
1316
+ return (0, import_core_cst4.toAddress)(this._addresses.baseAddressBech32);
1317
+ }
1318
+ }
1319
+ /**
1320
+ * Get a list of UTXOs to be used for transaction building.
1321
+ *
1322
+ * This is used in transaction building.
1323
+ *
1324
+ * @param addressType - the type of address to fetch UTXOs from (default: payment)
1325
+ * @returns a list of UTXOs
1326
+ */
1327
+ async getUnspentOutputs(addressType) {
1328
+ if (!this._fetcher) {
1329
+ throw new Error(
1330
+ "[AppWallet] Fetcher is required to fetch UTxOs. Please provide a fetcher."
1331
+ );
1332
+ }
1333
+ const utxos = await this._fetcher.fetchAddressUTxOs(
1334
+ addressType == "enterprise" ? this._addresses.enterpriseAddressBech32 : this._addresses.baseAddressBech32
1335
+ );
1336
+ return utxos.map((utxo) => (0, import_core_cst4.toTxUnspentOutput)(utxo));
1337
+ }
1338
+ /**
1339
+ * A helper function to get the assets in the wallet.
1340
+ *
1341
+ * @returns a list of assets
1342
+ */
1343
+ async getAssets() {
1344
+ const balance = await this.getBalance();
1345
+ return balance.filter((v) => v.unit !== "lovelace").map((v) => {
1346
+ const policyId = v.unit.slice(0, import_common3.POLICY_ID_LENGTH);
1347
+ const assetName = v.unit.slice(import_common3.POLICY_ID_LENGTH);
1348
+ const fingerprint = (0, import_common3.resolveFingerprint)(policyId, assetName);
1349
+ return {
1350
+ unit: v.unit,
1351
+ policyId,
1352
+ assetName: (0, import_common3.toUTF8)(assetName),
1353
+ fingerprint,
1354
+ quantity: v.quantity
1355
+ };
1356
+ });
1357
+ }
1358
+ /**
1359
+ * A helper function to get the lovelace balance in the wallet.
1360
+ *
1361
+ * @returns lovelace balance
1362
+ */
1363
+ async getLovelace() {
1364
+ const balance = await this.getBalance();
1365
+ const nativeAsset = balance.find((v) => v.unit === "lovelace");
1366
+ return nativeAsset !== void 0 ? nativeAsset.quantity : "0";
1367
+ }
1368
+ /**
1369
+ * A helper function to get the assets of a specific policy ID in the wallet.
1370
+ *
1371
+ * @param policyId
1372
+ * @returns a list of assets
1373
+ */
1374
+ async getPolicyIdAssets(policyId) {
1375
+ const assets = await this.getAssets();
1376
+ return assets.filter((v) => v.policyId === policyId);
1377
+ }
1378
+ /**
1379
+ * A helper function to get the policy IDs of all the assets in the wallet.
1380
+ *
1381
+ * @returns a list of policy IDs
1382
+ */
1383
+ async getPolicyIds() {
1384
+ const balance = await this.getBalance();
1385
+ return Array.from(
1386
+ new Set(balance.map((v) => v.unit.slice(0, import_common3.POLICY_ID_LENGTH)))
1387
+ ).filter((p) => p !== "lovelace");
1388
+ }
1389
+ /**
1390
+ * A helper function to create a collateral input for a transaction.
1391
+ *
1392
+ * @returns a transaction hash
1393
+ */
1394
+ async createCollateral() {
1395
+ const tx = new import_transaction.Transaction({ initiator: this });
1396
+ tx.sendLovelace(this.getChangeAddress(), "5000000");
1397
+ const unsignedTx = await tx.build();
1398
+ const signedTx = await this.signTx(unsignedTx);
1399
+ const txHash = await this.submitTx(signedTx);
1400
+ return txHash;
1401
+ }
1402
+ /**
1403
+ * Generate mnemonic or private key
1404
+ *
1405
+ * @param privateKey return private key if true
1406
+ * @returns a transaction hash
1407
+ */
1408
+ static brew(privateKey = false, strength = 256) {
1409
+ const mnemonic = EmbeddedWallet.generateMnemonic(strength);
1410
+ if (privateKey) {
1411
+ return (0, import_core_csl.resolvePrivateKey)(mnemonic);
1412
+ }
1413
+ return mnemonic;
1414
+ }
1415
+ getAddressesFromWallet(wallet) {
1416
+ const account = wallet.getAccount(this._accountIndex, this._keyIndex);
1417
+ this._addresses = {
1418
+ baseAddress: account.baseAddress,
1419
+ enterpriseAddress: account.enterpriseAddress,
1420
+ rewardAddress: account.rewardAddress,
1421
+ baseAddressBech32: account.baseAddressBech32,
1422
+ enterpriseAddressBech32: account.enterpriseAddressBech32,
1423
+ rewardAddressBech32: account.rewardAddressBech32
1424
+ };
1425
+ }
1426
+ buildAddressFromBech32Address(address) {
1427
+ const serializer = new import_core_cst4.CardanoSDKSerializer();
1428
+ const deserializedAddress = serializer.deserializer.key.deserializeAddress(address);
1429
+ if (deserializedAddress.pubKeyHash && deserializedAddress.stakeCredentialHash) {
1430
+ this._addresses.baseAddress = (0, import_core_cst4.buildBaseAddress)(
1431
+ this._networkId,
1432
+ import_core_cst4.Hash28ByteBase16.fromEd25519KeyHashHex(
1433
+ (0, import_core_cst4.Ed25519KeyHashHex)(deserializedAddress.pubKeyHash)
1434
+ ),
1435
+ import_core_cst4.Hash28ByteBase16.fromEd25519KeyHashHex(
1436
+ (0, import_core_cst4.Ed25519KeyHashHex)(
1437
+ (0, import_core_cst4.Ed25519KeyHashHex)(deserializedAddress.stakeCredentialHash)
1438
+ )
1439
+ )
1440
+ ).toAddress();
1441
+ this._addresses.baseAddressBech32 = this._addresses.baseAddress.toBech32();
1442
+ }
1443
+ if (deserializedAddress.pubKeyHash) {
1444
+ this._addresses.enterpriseAddress = (0, import_core_cst4.buildEnterpriseAddress)(
1445
+ this._networkId,
1446
+ import_core_cst4.Hash28ByteBase16.fromEd25519KeyHashHex(
1447
+ (0, import_core_cst4.Ed25519KeyHashHex)(deserializedAddress.pubKeyHash)
1448
+ )
1449
+ ).toAddress();
1450
+ this._addresses.enterpriseAddressBech32 = this._addresses.enterpriseAddress.toBech32();
1451
+ }
1452
+ if (deserializedAddress.stakeCredentialHash) {
1453
+ this._addresses.rewardAddress = (0, import_core_cst4.buildRewardAddress)(
1454
+ this._networkId,
1455
+ import_core_cst4.Hash28ByteBase16.fromEd25519KeyHashHex(
1456
+ (0, import_core_cst4.Ed25519KeyHashHex)(deserializedAddress.stakeCredentialHash)
1457
+ )
1458
+ ).toAddress();
1459
+ this._addresses.rewardAddressBech32 = this._addresses.rewardAddress.toBech32();
1460
+ }
1461
+ }
1462
+ };
1463
+ // Annotate the CommonJS export names for ESM import in node:
1464
+ 0 && (module.exports = {
1465
+ AppWallet,
1466
+ BrowserWallet,
1467
+ EmbeddedWallet,
1468
+ MeshWallet,
1469
+ WalletStaticMethods
1470
+ });
2
1471
  /*! Bundled license information:
3
1472
 
4
1473
  @scure/base/lib/esm/index.js: