@meshsdk/wallet 1.6.0-alpha.21 → 1.6.1

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 ADDED
@@ -0,0 +1,6 @@
1
+ "use strict";var P=Object.defineProperty;var V=Object.getOwnPropertyDescriptor;var z=Object.getOwnPropertyNames;var G=Object.prototype.hasOwnProperty;var F=(o,e)=>{for(var t in e)P(o,t,{get:e[t],enumerable:!0})},M=(o,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of z(e))!G.call(o,s)&&s!==t&&P(o,s,{get:()=>e[s],enumerable:!(r=V(e,s))||r.enumerable});return o};var q=o=>M(P({},"__esModule",{value:!0}),o);var te={};F(te,{AppWallet:()=>E,BrowserWallet:()=>C,EmbeddedWallet:()=>p,MeshWallet:()=>B,WalletStaticMethods:()=>y});module.exports=q(te);var A=require("@meshsdk/core-cst");function O(o){if(!Number.isSafeInteger(o))throw new Error(`Wrong integer: ${o}`)}function j(o){return o instanceof Uint8Array||o!=null&&typeof o=="object"&&o.constructor.name==="Uint8Array"}function J(...o){let e=n=>n,t=(n,c)=>d=>n(c(d)),r=o.map(n=>n.encode).reduceRight(t,e),s=o.map(n=>n.decode).reduce(t,e);return{encode:r,decode:s}}function Y(o){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>=o.length)throw new Error(`Digit index outside alphabet: ${t} (alphabet: ${o.length})`);return o[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=o.indexOf(t);if(r===-1)throw new Error(`Unknown letter: "${t}". Allowed: ${o}`);return r})}}}function Q(o=""){if(typeof o!="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(o)},decode:e=>{if(typeof e!="string")throw new Error("join.decode input should be string");return e.split(o)}}}var N=(o,e)=>e?N(e,o%e):o,U=(o,e)=>o+(e-N(o,e));function v(o,e,t,r){if(!Array.isArray(o))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(U(e,t)>32)throw new Error(`convertRadix2: carry overflow from=${e} to=${t} carryBits=${U(e,t)}`);let s=0,n=0,c=2**t-1,d=[];for(let u of o){if(u>=2**e)throw new Error(`convertRadix2: invalid data word=${u} from=${e}`);if(s=s<<e|u,n+e>32)throw new Error(`convertRadix2: carry overflow pos=${n} from=${e}`);for(n+=e;n>=t;n-=t)d.push((s>>n-t&c)>>>0);s&=2**n-1}if(s=s<<t-n&c,!r&&n>=e)throw new Error("Excess padding");if(!r&&s)throw new Error(`Non-zero padding: ${s}`);return r&&n>0&&d.push(s>>>0),d}function X(o,e=!1){if(o<=0||o>32)throw new Error("radix2: bits should be in (0..32]");if(U(8,o)>32||U(o,8)>32)throw new Error("radix2: carry overflow");return{encode:t=>{if(!j(t))throw new Error("radix2.encode input should be Uint8Array");return v(Array.from(t),8,o,!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(v(t,o,8,e))}}}function $(o){if(typeof o!="function")throw new Error("unsafeWrapper fn should be function");return function(...e){try{return o.apply(null,e)}catch{}}}var _=J(Y("qpzry9x8gf2tvdw0s3jn54khce6mua7l"),Q("")),D=[996825010,642813549,513874426,1027748829,705979059];function I(o){let e=o>>25,t=(o&33554431)<<5;for(let r=0;r<D.length;r++)(e>>r&1)===1&&(t^=D[r]);return t}function H(o,e,t=1){let r=o.length,s=1;for(let n=0;n<r;n++){let c=o.charCodeAt(n);if(c<33||c>126)throw new Error(`Invalid prefix (${o})`);s=I(s)^c>>5}s=I(s);for(let n=0;n<r;n++)s=I(s)^o.charCodeAt(n)&31;for(let n of e)s=I(s)^n;for(let n=0;n<6;n++)s=I(s);return s^=t,_.encode(v([s%2**30],30,5,!1))}function Z(o){let e=o==="bech32"?1:734539939,t=X(5),r=t.decode,s=t.encode,n=$(r);function c(l,g,h=90){if(typeof l!="string")throw new Error(`bech32.encode prefix should be string, not ${typeof l}`);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(l.length===0)throw new TypeError(`Invalid prefix length ${l.length}`);let x=l.length+7+g.length;if(h!==!1&&x>h)throw new TypeError(`Length ${x} exceeds limit ${h}`);let T=l.toLowerCase(),k=H(T,g,e);return`${T}1${_.encode(g)}${k}`}function d(l,g=90){if(typeof l!="string")throw new Error(`bech32.decode input should be string, not ${typeof l}`);if(l.length<8||g!==!1&&l.length>g)throw new TypeError(`Wrong string length: ${l.length} (${l}). Expected (8..${g})`);let h=l.toLowerCase();if(l!==h&&l!==l.toUpperCase())throw new Error("String must be lowercase or uppercase");let x=h.lastIndexOf("1");if(x===0||x===-1)throw new Error('Letter "1" must be present between prefix and data only');let T=h.slice(0,x),k=h.slice(x+1);if(k.length<6)throw new Error("Data must be at least 6 characters long");let W=_.decode(k).slice(0,-6),K=H(T,W,e);if(!k.endsWith(K))throw new Error(`Invalid checksum in ${l}: expected "${K}"`);return{prefix:T,words:W}}let u=$(d);function S(l){let{prefix:g,words:h}=d(l,!1);return{prefix:g,words:h,bytes:r(h)}}return{encode:c,decode:d,decodeToBytes:S,decodeUnsafe:u,fromWords:r,fromWordsUnsafe:n,toWords:s}}var R=Z("bech32");var b=require("@meshsdk/common"),i=require("@meshsdk/core-cst"),y=class{static privateKeyToEntropy(e){let t=R.decodeToBytes(e).bytes,r=i.Bip32PrivateKey.fromBytes(t);return(0,b.bytesToHex)(r.bytes())}static mnemonicToEntropy(e){let t=(0,b.mnemonicToEntropy)(e.join(" ")),r=(0,i.buildBip32PrivateKey)(t);return(0,b.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 s=(0,i.buildBaseAddress)(r,i.Hash28ByteBase16.fromEd25519KeyHashHex((0,i.Ed25519KeyHashHex)(e.toPublicKey().hash().toString("hex"))),i.Hash28ByteBase16.fromEd25519KeyHashHex((0,i.Ed25519KeyHashHex)(t.toPublicKey().hash().toString("hex")))),n=(0,i.buildEnterpriseAddress)(r,i.Hash28ByteBase16.fromEd25519KeyHashHex((0,i.Ed25519KeyHashHex)(e.toPublicKey().hash().toString("hex")))),c=(0,i.buildRewardAddress)(r,i.Hash28ByteBase16.fromEd25519KeyHashHex((0,i.Ed25519KeyHashHex)(t.toPublicKey().hash().toString("hex"))));return{baseAddress:s.toAddress(),enterpriseAddress:n.toAddress(),rewardAddress:c.toAddress()}}static generateMnemonic(e=256){return(0,b.generateMnemonic)(e).split(" ")}static addWitnessSets(e,t){let r=(0,i.deserializeTx)(e),s=r.witnessSet(),n=s.vkeys(),c=n?[...n.values(),...t]:t;return s.setVkeys(i.Serialization.CborSet.fromCore(c.map(d=>d.toCore()),i.VkeyWitness.fromCore)),new i.Transaction(r.body(),s,r.auxiliaryData()).toCbor()}},p=class extends y{_entropy;_networkId;constructor(e){switch(super(),this._networkId=e.networkId,e.key.type){case"mnemonic":this._entropy=y.mnemonicToEntropy(e.key.words);break;case"root":this._entropy=y.privateKeyToEntropy(e.key.bech32);break;case"cli":this._entropy=y.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:s}=(0,i.buildKeys)(this._entropy,e,t),{baseAddress:n,enterpriseAddress:c,rewardAddress:d}=y.getAddresses(r,s,this._networkId);return{baseAddress:n,enterpriseAddress:c,rewardAddress:d,baseAddressBech32:n.toBech32(),enterpriseAddressBech32:c.toBech32(),rewardAddressBech32:d.toBech32(),paymentKey:r,stakeKey:s,paymentKeyHex:r.toBytes().toString("hex"),stakeKeyHex:s.toBytes().toString("hex")}}getNetworkId(){return this._networkId}signData(e,t,r=0,s=0){try{let n=this.getAccount(r,s);if([n.baseAddress,n.enterpriseAddress,n.rewardAddress].find(d=>d.toBech32()===e)===void 0)throw new Error(`[EmbeddedWallet] Address: ${e} doesn't belong to this account.`);return(0,i.signData)(t,n.paymentKey)}catch(n){throw new Error(`[EmbeddedWallet] An error occurred during signData: ${n}.`)}}signTx(e,t=0,r=0){try{let s=(0,i.deserializeTxHash)((0,i.resolveTxHash)(e)),n=this.getAccount(t,r);return new i.VkeyWitness((0,i.Ed25519PublicKeyHex)(n.paymentKey.toPublicKey().toBytes().toString("hex")),(0,i.Ed25519SignatureHex)(n.paymentKey.sign(Buffer.from(s,"hex")).toString("hex")))}catch(s){throw new Error(`[EmbeddedWallet] An error occurred during signTx: ${s}.`)}}};var E=class{_fetcher;_submitter;_wallet;constructor(e){switch(this._fetcher=e.fetcher,this._submitter=e.submitter,e.key.type){case"mnemonic":this._wallet=new p({networkId:e.networkId,key:{type:"mnemonic",words:e.key.words}});break;case"root":this._wallet=new p({networkId:e.networkId,key:{type:"root",bech32:e.key.bech32}});break;case"cli":this._wallet=new p({networkId:e.networkId,key:{type:"cli",payment:e.key.payment,stake:e.key.stake}})}}async getCollateralUnspentOutput(e=0,t="payment"){let s=(await this.getUnspentOutputs(e,t)).filter(n=>n.output().amount().multiasset()===void 0);s.sort((n,c)=>Number(n.output().amount().coin())-Number(c.output().amount().coin()));for(let n of s)if(Number(n.output().amount().coin())>=5e6)return[n];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,A.toAddress)(this.getEnterpriseAddress(e,t)):(0,A.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(n=>(0,A.toTxUnspentOutput)(n))}signData(e,t,r=0,s=0){try{return this._wallet.signData(e,t,r,s)}catch(n){throw new Error(`[AppWallet] An error occurred during signData: ${n}.`)}}signTx(e,t=!1,r=0,s=0){try{let n=(0,A.deserializeTx)(e);if(!t&&n.witnessSet().vkeys()!==void 0&&n.witnessSet().vkeys().size()!==0)throw new Error("Signatures already exist in the transaction in a non partial sign call");let c=this._wallet.signTx(e,r,s);return p.addWitnessSets(e,[c])}catch(n){throw new Error(`[AppWallet] An error occurred during signTx: ${n}.`)}}signTxSync(e,t=!1,r=0,s=0){try{return"signedTx"}catch(n){throw new Error(`[AppWallet] An error occurred during signTx: ${n}.`)}}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 p.generateMnemonic(e)}};var w=require("@meshsdk/common"),a=require("@meshsdk/core-cst"),C=class o{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:r.name,icon:r.icon,version:r.apiVersion})}catch{}return e}static async enable(e){try{let t=await o.resolveInstance(e);if(t!==void 0)return new o(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 console.log("witness",r),o.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(n=>({cbor:n,partialSign:t}))):this._walletInstance.experimental.signTxs&&(r=await this._walletInstance.experimental.signTxs(e.map(n=>({cbor:n,partialSign:t}))));break}if(!r)throw new Error("Wallet does not support signTxs");let s=[];for(let n=0;n<r.length;n++){let c=e[n],d=r[n],u=o.addBrowserWitnesses(c,d);s.push(u)}return s}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),s=t.unit.slice(w.POLICY_ID_LENGTH),n=(0,w.resolveFingerprint)(r,s);return{unit:t.unit,policyId:r,assetName:s,fingerprint:n,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 s=(0,a.deserializeTx)(e),n=s.witnessSet(),c=n.vkeys(),d=c?[...c.values(),...r]:[...r];return n.setVkeys(a.Serialization.CborSet.fromCore(d.map(u=>u.toCore()),a.VkeyWitness.fromCore)),new a.Transaction(s.body(),n,s.auxiliaryData()).toCbor()}};var f=require("@meshsdk/common"),m=require("@meshsdk/core-cst"),L=require("@meshsdk/transaction");var B=class{_wallet;constructor(e){switch(e.key.type){case"root":this._wallet=new E({networkId:e.networkId,fetcher:e.fetcher,submitter:e.submitter,key:{type:"root",bech32:e.key.bech32}});break;case"cli":this._wallet=new E({networkId:e.networkId,fetcher:e.fetcher,submitter:e.submitter,key:{type:"cli",payment:e.key.payment,stake:e.key.stake}});break;case"mnemonic":this._wallet=new E({networkId:e.networkId,fetcher:e.fetcher,submitter:e.submitter,key:{type:"mnemonic",words:e.key.words}});break}}async getBalance(){let e=await this.getUnspentOutputs(),t=new Map;return e.map(s=>{(0,m.fromTxUnspentOutput)(s).output.amount.map(c=>{let d=c.unit,u=Number(c.quantity);if(t.has(d)){let S=t.get(d);t.set(d,S+u)}else t.set(d,u)})}),Array.from(t,([s,n])=>({unit:s,quantity:n.toString()}))}getChangeAddress(){return this._wallet.getPaymentAddress()}async getCollateral(e="payment"){return(await this._wallet.getCollateralUnspentOutput(0,e)).map((r,s)=>(0,m.fromTxUnspentOutput)(r))}getNetworkId(){return this._wallet.getNetworkId()}getRewardAddresses(){return[this._wallet.getRewardAddress()]}getUnusedAddresses(){return[this.getChangeAddress()]}getUsedAddresses(){return[this.getChangeAddress()]}async getUsedCollateral(){return(await this.getCollateral()).map(r=>(0,m.toTxUnspentOutput)(r))}async getUsedUTxOs(e){return await this.getUnspentOutputs(e)}async getUtxos(e){return(await this.getUsedUTxOs(e)).map(r=>(0,m.fromTxUnspentOutput)(r))}signData(e){return this._wallet.signData(this.getChangeAddress(),e)}signTx(e,t=!1){return this._wallet.signTx(e,t)}signTxs(e,t=!1){let r=[];for(let s of e){let n=this.signTx(s,t);r.push(n)}return r}async submitTx(e){return await this._wallet.submitTx(e)}getUsedAddress(e){return this._wallet.getUsedAddress(0,0,e)}async getUnspentOutputs(e){return await this._wallet.getUnspentOutputs(0,e)}async getAssets(){return(await this.getBalance()).filter(t=>t.unit!=="lovelace").map(t=>{let r=t.unit.slice(0,f.POLICY_ID_LENGTH),s=t.unit.slice(f.POLICY_ID_LENGTH),n=(0,f.resolveFingerprint)(r,s);return{unit:t.unit,policyId:r,assetName:(0,f.toUTF8)(s),fingerprint:n,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.POLICY_ID_LENGTH)))).filter(t=>t!=="lovelace")}async createCollateral(){let e=new L.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=p.generateMnemonic(t);return e?(0,m.resolvePrivateKey)(r):r}};0&&(module.exports={AppWallet,BrowserWallet,EmbeddedWallet,MeshWallet,WalletStaticMethods});
2
+ /*! Bundled license information:
3
+
4
+ @scure/base/lib/esm/index.js:
5
+ (*! scure-base - MIT License (c) 2022 Paul Miller (paulmillr.com) *)
6
+ */