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