@asichain/asi-wallet-sdk 0.1.6 → 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs CHANGED
@@ -1,3 +1,4 @@
1
- "use strict";var e=require("bs58"),t=require("bip39"),r=require("buffer"),s=require("@noble/secp256k1"),n=require("bip32"),o=require("blakejs"),a=require("js-sha3"),i=require("axios");function l(e){return e&&e.__esModule?e:{default:e}}function c(e){if(e&&e.__esModule)return e;var t=Object.create(null);return e&&Object.keys(e).forEach(function(r){if("default"!==r){var s=Object.getOwnPropertyDescriptor(e,r);Object.defineProperty(t,r,s.get?s:{enumerable:!0,get:function(){return e[r]}})}}),t.default=e,Object.freeze(t)}var d=l(e),u=c(t),h=l(o),p=l(a),y=l(i);const f={coinId:"000000",version:"00"},g={BASE_FEE:.0025,VARIATION_RANGE:.1,LABEL:"ASI",TRANSFER:"0.0025",DEPLOY:"0.0025"},E=BigInt(10)**BigInt(8),m={coinType:60,account:0,change:0,index:0};var w;class I{}w=I,I.generateRandomGasFee=()=>{const e=2*(Math.random()-.5)*g.VARIATION_RANGE;return(g.BASE_FEE*(1+e)).toFixed(4)},I.getGasFeeAsNumber=()=>g.BASE_FEE,I.formatGasFee=e=>`${e||w.generateRandomGasFee()} ${g.LABEL}`;const A=e=>{const t=v(e);return d.default.encode(t)},N=e=>d.default.decode(e),v=e=>{const t=new Uint8Array(e.length/2);for(let r=0;r<e.length;r+=2)t[r/2]=parseInt(e.substr(r,2),16);return t},b=e=>Array.from(e,e=>e.toString(16).padStart(2,"0")).join(""),S=e=>{const t=new Uint8Array(e);let r="";for(let e=0;e<t.byteLength;e++)r+=String.fromCharCode(t[e]);return btoa(r)},D=e=>{const t=atob(e),r=new Uint8Array(t.length);for(let e=0;e<t.length;e++)r[e]=t.charCodeAt(e);return r.buffer},R=e=>BigInt("0x"+Buffer.from(e).toString("hex")),x=e=>Uint8Array.from(Buffer.from(e.toString(16).padStart(64,"0"),"hex"));var L;!function(e){e.ENCRYPT="encrypt",e.DECRYPT="decrypt",e.DERIVATION="deriveKey"}(L||(L={}));const _=2,O=12,C=16,T=256,P="AES-GCM",U="SHA-256",k="raw",B="PBKDF2",V=1e5;L.ENCRYPT,L.DECRYPT;class K{static async encryptWithPassword(e,t){const r=crypto.getRandomValues(new Uint8Array(C)),s=crypto.getRandomValues(new Uint8Array(O)),n=await this.deriveKey(t,r),o=await crypto.subtle.encrypt({name:P,iv:s},n,(new TextEncoder).encode(e));return{data:S(o),salt:S(r.buffer),iv:S(s.buffer),version:_}}static async decryptWithPassword(e,t){if(e.version!==_)throw new Error(`Unsupported version ${e.version}`);const r=new Uint8Array(D(e.salt)),s=new Uint8Array(D(e.iv)),n=await this.deriveKey(t,r),o=await crypto.subtle.decrypt({name:P,iv:s},n,D(e.data));return(new TextDecoder).decode(o)}static async deriveKey(e,t){const r=await crypto.subtle.importKey(k,(new TextEncoder).encode(e),B,!1,[L.DERIVATION]);return crypto.subtle.deriveKey({name:B,salt:new Uint8Array(t),iterations:V,hash:U},r,{name:P,length:T},!1,[L.ENCRYPT,L.DECRYPT])}}const M=()=>{"undefined"==typeof window||window.Buffer||(window.Buffer=r.Buffer)};var F;M(),exports.MnemonicStrength=void 0,(F=exports.MnemonicStrength||(exports.MnemonicStrength={}))[F.TWELVE_WORDS=128]="TWELVE_WORDS",F[F.TWENTY_FOUR_WORDS=256]="TWENTY_FOUR_WORDS";class W{static generateMnemonic(e=exports.MnemonicStrength.TWELVE_WORDS){return u.generateMnemonic(e)}static generateMnemonicArray(e=exports.MnemonicStrength.TWELVE_WORDS){return this.mnemonicToWordArray(this.generateMnemonic(e))}static isMnemonicValid(e){return u.validateMnemonic(e)}static mnemonicToWordArray(e){return e.trim().split(" ")}static wordArrayToMnemonic(e){return e.join(" ")}}
2
- /*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */function H(e){if(!Number.isSafeInteger(e)||e<0)throw new Error("positive integer expected, got "+e)}function G(e,...t){if(!((r=e)instanceof Uint8Array||ArrayBuffer.isView(r)&&"Uint8Array"===r.constructor.name))throw new Error("Uint8Array expected");var r;if(t.length>0&&!t.includes(e.length))throw new Error("Uint8Array expected of length "+t+", got length="+e.length)}function $(e,t=!0){if(e.destroyed)throw new Error("Hash instance has been destroyed");if(t&&e.finished)throw new Error("Hash#digest() has already been called")}function Y(...e){for(let t=0;t<e.length;t++)e[t].fill(0)}function j(e){return new DataView(e.buffer,e.byteOffset,e.byteLength)}function z(e,t){return e<<32-t|e>>>t}function X(e){return"string"==typeof e&&(e=function(e){if("string"!=typeof e)throw new Error("string expected");return new Uint8Array((new TextEncoder).encode(e))}(e)),G(e),e}class J{}function q(e){const t=t=>e().update(X(t)).digest(),r=e();return t.outputLen=r.outputLen,t.blockLen=r.blockLen,t.create=()=>e(),t}function Z(e,t,r){return e&t^~e&r}function Q(e,t,r){return e&t^e&r^t&r}class ee extends J{constructor(e,t,r,s){super(),this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.blockLen=e,this.outputLen=t,this.padOffset=r,this.isLE=s,this.buffer=new Uint8Array(e),this.view=j(this.buffer)}update(e){$(this),G(e=X(e));const{view:t,buffer:r,blockLen:s}=this,n=e.length;for(let o=0;o<n;){const a=Math.min(s-this.pos,n-o);if(a===s){const t=j(e);for(;s<=n-o;o+=s)this.process(t,o);continue}r.set(e.subarray(o,o+a),this.pos),this.pos+=a,o+=a,this.pos===s&&(this.process(t,0),this.pos=0)}return this.length+=e.length,this.roundClean(),this}digestInto(e){$(this),function(e,t){G(e);const r=t.outputLen;if(e.length<r)throw new Error("digestInto() expects output buffer of length at least "+r)}(e,this),this.finished=!0;const{buffer:t,view:r,blockLen:s,isLE:n}=this;let{pos:o}=this;t[o++]=128,Y(this.buffer.subarray(o)),this.padOffset>s-o&&(this.process(r,0),o=0);for(let e=o;e<s;e++)t[e]=0;!function(e,t,r,s){if("function"==typeof e.setBigUint64)return e.setBigUint64(t,r,s);const n=BigInt(32),o=BigInt(4294967295),a=Number(r>>n&o),i=Number(r&o),l=s?4:0,c=s?0:4;e.setUint32(t+l,a,s),e.setUint32(t+c,i,s)}(r,s-8,BigInt(8*this.length),n),this.process(r,0);const a=j(e),i=this.outputLen;if(i%4)throw new Error("_sha2: outputLen should be aligned to 32bit");const l=i/4,c=this.get();if(l>c.length)throw new Error("_sha2: outputLen bigger than state");for(let e=0;e<l;e++)a.setUint32(4*e,c[e],n)}digest(){const{buffer:e,outputLen:t}=this;this.digestInto(e);const r=e.slice(0,t);return this.destroy(),r}_cloneInto(e){e||(e=new this.constructor),e.set(...this.get());const{blockLen:t,buffer:r,length:s,finished:n,destroyed:o,pos:a}=this;return e.destroyed=o,e.finished=n,e.length=s,e.pos=a,s%t&&e.buffer.set(r),e}clone(){return this._cloneInto()}}const te=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),re=Uint32Array.from([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),se=new Uint32Array(64);class ne extends ee{constructor(e=32){super(64,e,8,!1),this.A=0|te[0],this.B=0|te[1],this.C=0|te[2],this.D=0|te[3],this.E=0|te[4],this.F=0|te[5],this.G=0|te[6],this.H=0|te[7]}get(){const{A:e,B:t,C:r,D:s,E:n,F:o,G:a,H:i}=this;return[e,t,r,s,n,o,a,i]}set(e,t,r,s,n,o,a,i){this.A=0|e,this.B=0|t,this.C=0|r,this.D=0|s,this.E=0|n,this.F=0|o,this.G=0|a,this.H=0|i}process(e,t){for(let r=0;r<16;r++,t+=4)se[r]=e.getUint32(t,!1);for(let e=16;e<64;e++){const t=se[e-15],r=se[e-2],s=z(t,7)^z(t,18)^t>>>3,n=z(r,17)^z(r,19)^r>>>10;se[e]=n+se[e-7]+s+se[e-16]|0}let{A:r,B:s,C:n,D:o,E:a,F:i,G:l,H:c}=this;for(let e=0;e<64;e++){const t=c+(z(a,6)^z(a,11)^z(a,25))+Z(a,i,l)+re[e]+se[e]|0,d=(z(r,2)^z(r,13)^z(r,22))+Q(r,s,n)|0;c=l,l=i,i=a,a=o+t|0,o=n,n=s,s=r,r=t+d|0}r=r+this.A|0,s=s+this.B|0,n=n+this.C|0,o=o+this.D|0,a=a+this.E|0,i=i+this.F|0,l=l+this.G|0,c=c+this.H|0,this.set(r,s,n,o,a,i,l,c)}roundClean(){Y(se)}destroy(){this.set(0,0,0,0,0,0,0,0),Y(this.buffer)}}const oe=q(()=>new ne);class ae extends J{constructor(e,t){super(),this.finished=!1,this.destroyed=!1,function(e){if("function"!=typeof e||"function"!=typeof e.create)throw new Error("Hash should be wrapped by utils.createHasher");H(e.outputLen),H(e.blockLen)}(e);const r=X(t);if(this.iHash=e.create(),"function"!=typeof this.iHash.update)throw new Error("Expected instance of class which extends utils.Hash");this.blockLen=this.iHash.blockLen,this.outputLen=this.iHash.outputLen;const s=this.blockLen,n=new Uint8Array(s);n.set(r.length>s?e.create().update(r).digest():r);for(let e=0;e<n.length;e++)n[e]^=54;this.iHash.update(n),this.oHash=e.create();for(let e=0;e<n.length;e++)n[e]^=106;this.oHash.update(n),Y(n)}update(e){return $(this),this.iHash.update(e),this}digestInto(e){$(this),G(e,this.outputLen),this.finished=!0,this.iHash.digestInto(e),this.oHash.update(e),this.oHash.digestInto(e),this.destroy()}digest(){const e=new Uint8Array(this.oHash.outputLen);return this.digestInto(e),e}_cloneInto(e){e||(e=Object.create(Object.getPrototypeOf(this),{}));const{oHash:t,iHash:r,finished:s,destroyed:n,blockLen:o,outputLen:a}=this;return e.finished=s,e.destroyed=n,e.blockLen=o,e.outputLen=a,e.oHash=t._cloneInto(e.oHash),e.iHash=r._cloneInto(e.iHash),e}clone(){return this._cloneInto()}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}}const ie=(e,t,r)=>new ae(e,t).update(r).digest();ie.create=(e,t)=>new ae(e,t),s.utils.hmacSha256Sync=(e,...t)=>ie(oe,e,s.utils.concatBytes(...t));const le=s.CURVE.n,ce={isPoint(e){try{return s.Point.fromHex(e),!0}catch{return!1}},isPrivate(e){if(32!==e.length)return!1;const t=R(e);return t>0n&&t<le},pointFromScalar(e,t=!0){try{return s.getPublicKey(e,t)}catch{return null}},pointAddScalar(e,t,r=!0){try{const n=s.Point.fromHex(e),o=R(t),a=s.Point.BASE.multiply(o);return n.add(a).toRawBytes(r)}catch{return null}},privateAdd(e,t){const r=(R(e)+R(t))%le;return 0n===r?null:x(r)},privateNegate(e){const t=R(e);return x((le-t)%le)},sign:(e,t)=>s.signSync(e,t,{der:!1}),verify:(e,t,r)=>s.verify(r,e,t)};M();class de{static buildBip44Path({coinType:e=60,account:t=0,change:r=0,index:s=0}){return`m/44'/${e}'/${t}'/${r}/${s}`}static derivePrivateKey(e,t){const r=e.derivePath(t);if(!r.privateKey)throw new Error("No private key at derived node");return new Uint8Array(r.privateKey)}static async mnemonicToSeed(e,r=""){return"string"==typeof e?await t.mnemonicToSeed(e,r):await t.mnemonicToSeed(W.wordArrayToMnemonic(e),r)}static seedToMasterNode(e){return n.BIP32Factory(ce).fromSeed(e)}static async deriveKeyFromMnemonic(e,t=m){const r=this.buildBip44Path(t),s=await de.mnemonicToSeed(e),n=de.seedToMasterNode(s);return de.derivePrivateKey(n,r)}static async deriveNextKeyFromMnemonic(e,t,r=m){const s=t+1;return await this.deriveKeyFromMnemonic(e,{...r,index:s})}}const{randomBytes:ue,bytesToHex:he}=s.utils;class pe{static generateRandomKey(e=32){if(!e||e<0||!Number.isInteger(e))throw new Error("PrivateKeyLength must be a positive integer");return ue(e)}static generateKeyPair(e=32){if(!e||e<0||!Number.isInteger(e))throw new Error("PrivateKeyLength must be a positive integer");const t=ue(e);return{privateKey:t,publicKey:s.getPublicKey(t)}}static getKeyPairFromPrivateKey(e){return{privateKey:e,publicKey:s.getPublicKey(e)}}static getPublicKeyFromPrivateKey(e){return s.getPublicKey(e)}static convertKeyToHex(e){return he(e)}static async deriveKeyFromMnemonic(e,t){return await de.deriveKeyFromMnemonic(e,t)}static generateMpcKeyPair(){throw new Error("MPC key generation is not implemented yet.")}}const{blake2bHex:ye}=h.default,{keccak256:fe}=p.default;class ge{static createWallet(e,t){let r;r=e?pe.getKeyPairFromPrivateKey(e):pe.generateKeyPair();return{address:this.deriveAddressFromPublicKey(r.publicKey),publicKey:r.publicKey,privateKey:r.privateKey}}static async createWalletFromMnemonic(e,t){const r=e?W.mnemonicToWordArray(e):W.generateMnemonicArray(),s=W.wordArrayToMnemonic(r);if(!s||!W.isMnemonicValid(s))throw new Error("WalletsService.createWalletFromMnemonic: Recovery mnemonic is missing or invalid");const n=await de.mnemonicToSeed(r),o=de.seedToMasterNode(n),a=de.buildBip44Path({coinType:60,account:0,change:0,index:t||0}),i=de.derivePrivateKey(o,a);return{...this.createWallet(i),mnemonic:s}}static deriveAddressFromPrivateKey(e){const t=pe.getKeyPairFromPrivateKey(e);return this.deriveAddressFromPublicKey(t.publicKey)}static deriveAddressFromPublicKey(e){const t=fe(e.slice(1)),r=v(t.slice(-40)),s=fe(r),n=`${f.coinId}${f.version}${s}`,o=v(n),a=ye(o,void 0,32).slice(0,8);return A(`${n}${a}`)}}function Ee(e,t,r,s,n,o){function a(e){if(void 0!==e&&"function"!=typeof e)throw new TypeError("Function expected");return e}for(var i,l=s.kind,c="getter"===l?"get":"setter"===l?"set":"value",d=!t&&e?s.static?e:e.prototype:null,u=t||(d?Object.getOwnPropertyDescriptor(d,s.name):{}),h=!1,p=r.length-1;p>=0;p--){var y={};for(var f in s)y[f]="access"===f?{}:s[f];for(var f in s.access)y.access[f]=s.access[f];y.addInitializer=function(e){if(h)throw new TypeError("Cannot add initializers after decoration has completed");o.push(a(e||null))};var g=(0,r[p])("accessor"===l?{get:u.get,set:u.set}:u[c],y);if("accessor"===l){if(void 0===g)continue;if(null===g||"object"!=typeof g)throw new TypeError("Object expected");(i=a(g.get))&&(u.get=i),(i=a(g.set))&&(u.set=i),(i=a(g.init))&&n.unshift(i)}else(i=a(g))&&("field"===l?n.unshift(i):u[c]=i)}d&&Object.defineProperty(d,s.name,u),h=!0}function me(e,t,r){for(var s=arguments.length>2,n=0;n<t.length;n++)r=s?t[n].call(e,r):t[n].call(e);return s?r:void 0}var we,Ie;"function"==typeof SuppressedError&&SuppressedError,exports.RecoverableDeployErrors=void 0,(we=exports.RecoverableDeployErrors||(exports.RecoverableDeployErrors={})).READ_ONLY_NODE="READ_ONLY_NODE",we.CASPER_INSTANCE_UNAVAILABLE="CASPER_INSTANCE_UNAVAILABLE",we.INVALID_DEPLOY_ID="INVALID_DEPLOY_ID",we.INVALID_BLOCK_NUMBER="INVALID_BLOCK_NUMBER",exports.FatalDeployErrors=void 0,(Ie=exports.FatalDeployErrors||(exports.FatalDeployErrors={})).INSUFFICIENT_BALANCE="INSUFFICIENT_BALANCE",Ie.WRONG_NETWORK="WRONG_NETWORK",Ie.PARSING_ERROR="PARSING_ERROR",Ie.LOW_PHLO_PRICE="LOW_PHLO_PRICE",Ie.SIGNATURE_ERROR="SIGNATURE_ERROR",Ie.STORAGE_RETRIEVAL_ERROR="STORAGE_RETRIEVAL_ERROR",Ie.UNKNOWN_ERROR="UNKNOWN_ERROR",Ie.DEPLOY_SUBMIT_TIMEOUT="DEPLOY_SUBMIT_TIMEOUT",Ie.BLOCK_INCLUSION_TIMEOUT="BLOCK_INCLUSION_TIMEOUT",Ie.FINALIZATION_TIMEOUT="FINALIZATION_TIMEOUT";const Ae={[exports.RecoverableDeployErrors.READ_ONLY_NODE]:"Node is read-only. Trying another node...",[exports.RecoverableDeployErrors.CASPER_INSTANCE_UNAVAILABLE]:"Casper instance not available. Trying another node...",[exports.RecoverableDeployErrors.INVALID_DEPLOY_ID]:"Invalid deploy ID. Please try again.",[exports.RecoverableDeployErrors.INVALID_BLOCK_NUMBER]:"Invalid block number. Please try again.",[exports.FatalDeployErrors.INSUFFICIENT_BALANCE]:"Insufficient balance. Please top up your account.",[exports.FatalDeployErrors.WRONG_NETWORK]:"Wrong network. Please contact technical support.",[exports.FatalDeployErrors.PARSING_ERROR]:"Parsing error. Please contact technical support.",[exports.FatalDeployErrors.LOW_PHLO_PRICE]:"Phlo price too low. Please rebuild the transaction with a higher phlo price.",[exports.FatalDeployErrors.SIGNATURE_ERROR]:"Signature verification failed. Please try again.",[exports.FatalDeployErrors.STORAGE_RETRIEVAL_ERROR]:"Storage retrieval error. Please try again later.",[exports.FatalDeployErrors.UNKNOWN_ERROR]:"An unknown error occurred. Please try again.",[exports.FatalDeployErrors.DEPLOY_SUBMIT_TIMEOUT]:"Deploy submission timed out. Please try again.",[exports.FatalDeployErrors.BLOCK_INCLUSION_TIMEOUT]:"Deploy was not included in a block within the expected time.",[exports.FatalDeployErrors.FINALIZATION_TIMEOUT]:"Block finalization polling timed out."};function Ne(e,t){return function(...t){return"string"==typeof t[0]&&(t[0]=t[0].toLowerCase()),e.apply(this,t)}}let ve=(()=>{var e;let t,r,s=[];return e=class{parseDeploymentError(e){return e.includes("read only")?exports.RecoverableDeployErrors.READ_ONLY_NODE:e.includes("casper instance")?exports.RecoverableDeployErrors.CASPER_INSTANCE_UNAVAILABLE:e.includes("invalid deploy ID")?exports.RecoverableDeployErrors.INVALID_DEPLOY_ID:e.includes("invalid block number")?exports.RecoverableDeployErrors.INVALID_BLOCK_NUMBER:e.includes("insufficient balance")?exports.FatalDeployErrors.INSUFFICIENT_BALANCE:e.includes("wrong network")?exports.FatalDeployErrors.WRONG_NETWORK:e.includes("parsing error")?exports.FatalDeployErrors.PARSING_ERROR:e.includes("low")&&e.includes("phlo")?exports.FatalDeployErrors.LOW_PHLO_PRICE:e.includes("signature")||e.includes("sign")||e.includes("invalid signature")?exports.FatalDeployErrors.SIGNATURE_ERROR:e.includes("storage")||e.includes("retrieval")?exports.FatalDeployErrors.STORAGE_RETRIEVAL_ERROR:exports.FatalDeployErrors.UNKNOWN_ERROR}isDeploymentErrorRecoverable(e){return Object.values(exports.RecoverableDeployErrors).includes(e)}isDeploymentErrorFatal(e){return Object.values(exports.FatalDeployErrors).includes(e)}isPollingErrorRecoverable(e){return e.includes("casper instance")||e.includes("storage")||e.includes("parsing")}getErrorMessageByErrorType(e){return Ae[e]??Ae[exports.FatalDeployErrors.UNKNOWN_ERROR]}constructor(){me(this,s)}},(()=>{const n="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;t=[Ne],r=[Ne],Ee(e,null,t,{kind:"method",name:"parseDeploymentError",static:!1,private:!1,access:{has:e=>"parseDeploymentError"in e,get:e=>e.parseDeploymentError},metadata:n},null,s),Ee(e,null,r,{kind:"method",name:"isPollingErrorRecoverable",static:!1,private:!1,access:{has:e=>"isPollingErrorRecoverable"in e,get:e=>e.isPollingErrorRecoverable},metadata:n},null,s),n&&Object.defineProperty(e,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:n})})(),e})();class be{constructor(e){this.client=e}async get(e){return(await this.client.get(e)).data}async post(e,t){return(await this.client.post(e,t)).data}getBaseUrl(){return this.client.defaults.baseURL}}var Se,De;exports.DeployStatus=void 0,(Se=exports.DeployStatus||(exports.DeployStatus={})).DEPLOYING="Deploying",Se.INCLUDED_IN_BLOCK="IncludedInBlock",Se.FINALIZED="Finalized",Se.CHECK_ERROR="CheckingError";class Re{constructor(e,t){this.validatorClient=e,this.indexerClient=t}static createHttpClient(e){const t=y.default.create({baseURL:e.baseUrl,...e.axiosConfig});return new be(t)}changeValidator(e){return this.validatorClient=Re.createHttpClient(e),this}changeIndexer(e){return this.indexerClient=Re.createHttpClient(e),this}static init(e){return Re.instance=new Re(this.createHttpClient(e.validator),this.createHttpClient(e.indexer)),Re.instance}static isInitialized(){return void 0!==Re?.instance}static getInstance(){if(!Re.isInitialized())throw new Error("BlockchainGateway is not initialized. Call BlockchainGateway.init() first.");return Re.instance}getValidatorClientUrl(){return this.validatorClient.getBaseUrl()??""}async submitDeploy(e){try{const t=await this.validatorClient.post("/api/deploy",e,{headers:{"Content-Type":"application/json"}});if(console.log("BlockchainGateway.submitDeploy: Deploy result:",t),"string"==typeof t){const e=/DeployId is:\s*([a-fA-F0-9]+)/.exec(t);return e?e[1]:t}return t.signature||t.deployId||t}catch(e){const t="BlockchainGateway.submitDeploy: "+this.getGatewayErrorMessage(e);throw new Error(t)}}async submitExploratoryDeploy(e){try{return await this.indexerClient.post("/api/explore-deploy",e)}catch(e){const t="BlockchainGateway.submitExploratoryDeploy: "+this.getGatewayErrorMessage(e);throw new Error(t)}}async exploreDeployData(e){try{return(await this.submitExploratoryDeploy(e)).expr}catch(e){const t="BlockchainGateway.exploreDeployData: "+this.getGatewayErrorMessage(e);throw console.error(t),new Error(t)}}async getDeploy(e){return await this.indexerClient.get(`/api/deploy/${e}`)}async isDeployFinalized(e){return e.faultTolerance>=.99}async getDeployStatus(e){try{let t;if(t=await this.getDeploy(e),!t?.blockHash)return{status:exports.DeployStatus.DEPLOYING};return{status:await this.isDeployFinalized(t)?exports.DeployStatus.FINALIZED:exports.DeployStatus.INCLUDED_IN_BLOCK}}catch(e){const t="BlockchainGateway.getDeployStatus: "+this.getGatewayErrorMessage(e);return{status:exports.DeployStatus.CHECK_ERROR,errorMessage:t}}}async getBlock(e){const t=await this.indexerClient.get(`/api/block/${e}`);return t?.blockInfo}async getLatestBlockNumber(){try{const e=await this.getLatestBlock();return e?.blockNumber??-1}catch(e){const t="BlockchainGateway.getLatestBlockNumber: "+this.getGatewayErrorMessage(e);return console.error(t),-1}}async isValidatorActive(){try{return await this.validatorClient.get("/status"),!0}catch(e){return console.error("BlockchainGateway.isValidatorActive: Node health check failed:",e),!1}}getGatewayErrorMessage(e){if(y.default.isAxiosError(e)){const t=e.response?.status??e.code,r=e.response?.statusText??"";return`Axios error while requesting "${e.config?.url??""}": [${t}] ${r} - ${e.message}`}return e instanceof Error?e.message:String(e)}validateBlocksResponse(e){if(!e?.length){throw new Error("BlockchainGateway.validateBlocksResponse: No blocks returned from /api/blocks endpoint")}}async getLatestBlock(){const e=await this.indexerClient.get("/api/blocks/1");return this.validateBlocksResponse(e),e[0]}}exports.WalletClientModes=void 0,(De=exports.WalletClientModes||(exports.WalletClientModes={})).LOCAL="local",De.MPC="mpc";const xe={mode:exports.WalletClientModes.LOCAL},Le=5e5,_e={phloPrice:1,useRandomNode:!0,deployValiditySeconds:80,nodeSelectionAttempts:3,deployRetries:3,deployIntervalSeconds:5,pollingIntervalSeconds:3};function Oe(e,t){return function(...r){if(!Re.isInitialized())throw new Error(`${t.kind} ${String(t.name)}: BlockchainGateway is not initialized. Call BlockchainGateway.init() first.`);return e.apply(this,r)}}let Ce=(()=>{var e;let t,r,s=[];return e=class{constructor(e,t,r){if(this.retriesLeft=me(this,s),this.inactiveNodesUrls=new Set,this.currentNodeUrl="",!e?.length)throw new Error("At least one node URL must be provided");this.availableNodesUrls=e,this.useRandomNode=r,this.retriesLeft=t}static initialize(t,r=_e.nodeSelectionAttempts,s=_e.useRandomNode){const n=s?Math.max(1,r):0,o=new e(t,n,s);return e.instance=o,o}async connectDefaultNode(){if(this.useRandomNode)throw new Error("NodeManager.connectDefaultNode: Random node selection is enabled, cannot connect to default node");await this.connectNode(this.availableNodesUrls[0])}async connectNode(e){Re.getInstance().getValidatorClientUrl()!==e&&Re.getInstance().changeValidator({baseUrl:e});if(!await Re.getInstance().isValidatorActive()){this.deactivateNode(e);const t=`NodeManager.connectNode: Node ${e} is not active`;throw console.error(t),new Error(t)}this.currentNodeUrl=e}static getInstance(){if(!e.instance)throw new Error("NodeManager is not initialized. Call NodeManager.initialize() first.");return e.instance}isInitialized(){return!!this.currentNodeUrl}markNodeInactive(e){this.inactiveNodesUrls.add(e)}deactivateCurrentNode(){this.isInitialized()&&this.deactivateNode(this.currentNodeUrl)}deactivateNode(e){this.retriesLeft--,this.markNodeInactive(e),this.currentNodeUrl===e&&(this.currentNodeUrl="")}getAvailableNodesUrls(){return this.availableNodesUrls.filter(e=>!this.inactiveNodesUrls.has(e))}getRetriesLeft(){return this.retriesLeft}getRandomAvailableNodeUrl(){const e=this.getAvailableNodesUrls();if(!e?.length)throw console.error("NodeManager.getRandomAvailableNodeUrl: No available node URLs to select"),new Error("NodeManager: no available node URLs");return e[Math.floor(Math.random()*e.length)]}async connectActiveRandomNode(){if(!this.useRandomNode)throw new Error("NodeManager.connectActiveRandomNode: Random node selection is disabled, connect to default node");for(;this.retriesLeft>0;){const e=this.getRandomAvailableNodeUrl();if(console.log(`NodeManager.connectActiveRandomNode: Attempting to connect to node ${e}. Retries left: ${this.retriesLeft}`),e){try{await this.connectNode(e)}catch(e){continue}return}}throw new Error("NodeManager.connectActiveRandomNode: No active node URL found after all attempts")}},(()=>{const n="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;t=[Oe],r=[Oe],Ee(e,null,t,{kind:"method",name:"connectDefaultNode",static:!1,private:!1,access:{has:e=>"connectDefaultNode"in e,get:e=>e.connectDefaultNode},metadata:n},null,s),Ee(e,null,r,{kind:"method",name:"connectActiveRandomNode",static:!1,private:!1,access:{has:e=>"connectActiveRandomNode"in e,get:e=>e.connectActiveRandomNode},metadata:n},null,s),n&&Object.defineProperty(e,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:n})})(),e})();const Te=127;class Pe{constructor(){this.buffer=[]}writeString(e,t){if(!t)return;const r=e<<3|2;this.writeInteger(r);const s=(new TextEncoder).encode(t);this.writeInteger(s.length),this.buffer.push(...Array.from(s))}writeInt64(e,t){if(!t)return;const r=e<<3;this.writeInteger(r),this.writeInteger64(t)}writeInteger(e){for(;e>Te;)this.buffer.push(e&Te|128),e>>>=7;this.buffer.push(e)}writeInteger64(e){for(;e>Te;)this.buffer.push(e&Te|128),e=Math.floor(e/128);this.buffer.push(e)}getResultBuffer(){return new Uint8Array(this.buffer)}}const{blake2bHex:Ue}=h.default;class ke{static async sign(e,t){const{wallet:r,data:s}=e;try{const e=await t();return await r.withSigningCapability(e,async e=>{const t=this.deployDataProtobufSerialize(s),r=Ue(t,void 0,32),n=Uint8Array.from(Buffer.from(r,"hex")),o=await e.signDigest(n),a=e.getPublicKey();return{data:{term:s.term,timestamp:s.timestamp,phloPrice:s.phloPrice,phloLimit:s.phloLimit,validAfterBlockNumber:s.validAfterBlockNumber,shardId:s.shardId},deployer:b(a),signature:b(o),sigAlgorithm:"secp256k1"}})}catch(e){const t=`SignerService.sign: ${e.message}`;throw new Error(t)}}}ke.deployDataProtobufSerialize=e=>{const{term:t,timestamp:r,phloPrice:s,phloLimit:n,validAfterBlockNumber:o,shardId:a=""}=e,i=new Pe;return i.writeString(2,t),i.writeInt64(3,r),i.writeInt64(7,s),i.writeInt64(8,n),i.writeInt64(10,o),i.writeString(11,a),i.getResultBuffer()};const Be=/[,\s]+/g,Ve=/^\d+(?:\.\d+)?$/,Ke=/(\.\d*?[1-9])0+$/,Me=/\.0+$/,Fe=e=>{const t=e/E,r=e%E,s=E.toString().length-1,n=r.toString().padStart(s,"0");return`${t.toString()}.${n}`.replace(Ke,"$1").replace(Me,"")},We=Fe,{blake2bHex:He}=h.default,Ge=/[<>:"/\\|?*]/,$e=/^[a-zA-Z0-9]+$/,Ye=/^[1-9A-HJ-NP-Za-km-z]+$/,je=`${f.coinId}${f.version}`;var ze;exports.AddressValidationErrorCode=void 0,(ze=exports.AddressValidationErrorCode||(exports.AddressValidationErrorCode={})).INVALID_PREFIX="INVALID_PREFIX",ze.INVALID_LENGTH="INVALID_LENGTH",ze.INVALID_ALPHABET="INVALID_ALPHABET",ze.INVALID_BASE58="INVALID_BASE58",ze.INVALID_HEX_LENGTH="INVALID_HEX_LENGTH",ze.INVALID_CHAIN_PREFIX="INVALID_CHAIN_PREFIX",ze.INVALID_CHECKSUM="INVALID_CHECKSUM",ze.NON_CANONICAL="NON_CANONICAL";const Xe=e=>({isValid:!1,errorCode:e}),Je=e=>{if(!e.startsWith("1111"))return Xe(exports.AddressValidationErrorCode.INVALID_PREFIX);if(e.length<50||e.length>54)return Xe(exports.AddressValidationErrorCode.INVALID_LENGTH);if(!$e.test(e))return Xe(exports.AddressValidationErrorCode.INVALID_ALPHABET);if(!Ye.test(e))return Xe(exports.AddressValidationErrorCode.INVALID_BASE58);const t=b(N(e));if(80!==t.length)return Xe(exports.AddressValidationErrorCode.INVALID_HEX_LENGTH);if(A(t)!==e)return Xe(exports.AddressValidationErrorCode.NON_CANONICAL);const r=t.slice(0,72),s=t.slice(72);if(!r.startsWith(je))return Xe(exports.AddressValidationErrorCode.INVALID_CHAIN_PREFIX);const n=He(v(r),void 0,32).slice(0,8);return 8!==s.length||s!==n?Xe(exports.AddressValidationErrorCode.INVALID_CHECKSUM):{isValid:!0}};const qe=e=>e.replace(/\\/g,"\\\\").replace(/"/g,'\\"').replace(/\n/g,"\\n").replace(/\r/g,"\\r").replace(/\t/g,"\\t");let Ze=(()=>{var e;let t,r,s=[];return e=class{getBlockchainGateway(){return Re.getInstance()}async transfer(e,t,r,s,n,o=5e5){try{const a=Je(e);if(!a.isValid)throw new Error(`AssetsService.transfer: Invalid 'fromAddress': ${a.errorCode??"UNKNOWN"}`);const i=Je(t);if(!i.isValid)throw new Error(`AssetsService.transfer: Invalid 'toAddress': ${i.errorCode??"UNKNOWN"}`);if(e===t)throw new Error("AssetsService.transfer: Sender and recipient addresses cannot be the same");if(r<=0n)throw new Error("AssetsService.transfer: Transfer amount must be greater than zero");const l=this.getBlockchainGateway(),c=((e,t,r)=>{if(r<=0n)throw new Error("Transfer amount must be greater than zero");const s=qe(e),n=qe(t),o=r.toString();return`\n new \n deployerId(\`rho:rchain:deployerId\`),\n stdout(\`rho:io:stdout\`),\n rl(\`rho:registry:lookup\`),\n ASIVaultCh,\n vaultCh,\n toVaultCh,\n asiVaultkeyCh,\n resultCh\n in {\n rl!(\`rho:rchain:asiVault\`, *ASIVaultCh) |\n for (@(_, ASIVault) <- ASIVaultCh) {\n @ASIVault!("findOrCreate", "${s}", *vaultCh) |\n @ASIVault!("findOrCreate", "${n}", *toVaultCh) |\n @ASIVault!("deployerAuthKey", *deployerId, *asiVaultkeyCh) |\n for (@(true, vault) <- vaultCh; key <- asiVaultkeyCh; @(true, toVault) <- toVaultCh) {\n @vault!("transfer", "${n}", ${o}, *key, *resultCh) |\n for (@result <- resultCh) {\n match result {\n (true, Nil) => {\n stdout!(("Transfer successful:", ${o}, "ASI"))\n }\n (false, reason) => {\n stdout!(("Transfer failed:", reason))\n }\n }\n }\n } |\n for (@(false, errorMsg) <- vaultCh) {\n stdout!(("Sender vault error:", errorMsg))\n } |\n for (@(false, errorMsg) <- toVaultCh) {\n stdout!(("Destination vault error:", errorMsg))\n }\n }\n }\n `})(e,t,r),d=await l.getLatestBlockNumber();if(-1===d)throw new Error("AssetsService.transfer: Invalid block number");const u={term:c,phloLimit:o,phloPrice:1,validAfterBlockNumber:d-1,timestamp:Date.now(),shardId:"root"},h=await ke.sign({wallet:s,data:u},n);return await l.submitDeploy(h)}catch(e){const t="AssetsService.transfer: "+e.message;throw new Error(t)}}async getASIBalance(e){const t=Je(e);if(!t.isValid)throw new Error(`AssetsService.getASIBalance: Invalid address: ${t.errorCode??"UNKNOWN"}`);const r=this.getBlockchainGateway(),s=(e=>`\n new return, rl(\`rho:registry:lookup\`), ASIVaultCh, vaultCh in {\n rl!(\`rho:rchain:asiVault\`, *ASIVaultCh) |\n for (@(_, ASIVault) <- ASIVaultCh) {\n @ASIVault!("findOrCreate", "${qe(e)}", *vaultCh) |\n for (@maybeVault <- vaultCh) {\n match maybeVault {\n (true, vault) => @vault!("balance", *return)\n (false, err) => return!(err)\n }\n }\n }\n }\n`)(e);try{const e=await r.exploreDeployData(s);if(e&&e.length>0){const t=e[0];if(t?.ExprInt?.data)return BigInt(t.ExprInt.data);if(t?.ExprString?.data)throw new Error("Balance check error:")}return BigInt(0)}catch(e){return BigInt(0)}}constructor(){me(this,s)}},(()=>{const n="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;t=[Oe],r=[Oe],Ee(e,null,t,{kind:"method",name:"transfer",static:!1,private:!1,access:{has:e=>"transfer"in e,get:e=>e.transfer},metadata:n},null,s),Ee(e,null,r,{kind:"method",name:"getASIBalance",static:!1,private:!1,access:{has:e=>"getASIBalance"in e,get:e=>e.getASIBalance},metadata:n},null,s),n&&Object.defineProperty(e,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:n})})(),e})();class Qe{static async createAndEncrypt(e,t){const r=await K.encryptWithPassword(e,t);return new Qe(r)}static createFromEncryptedData(e){return new Qe(e)}static createFromStringifiedEncryptedData(e){return new Qe(JSON.parse(e))}constructor(e){this.encryptedSeedData=e}async decrypt(e){return await K.decryptWithPassword(this.encryptedSeedData,e)}toString(){return JSON.stringify(this.encryptedSeedData)}}var et;exports.WalletMemoryKeys=void 0,(et=exports.WalletMemoryKeys||(exports.WalletMemoryKeys={})).PRIVATE_KEY="private_key",et.CRYPTO_SALT="crypto_salt",et.CRYPTO_IV="crypto_iv",et.CRYPTO_VERSION="crypto version";class tt{constructor(e,t,r,s,n){this.name=e,this.index=n,this.masterNodeId=s,this.address=t,this.privateKey=r,this.assets=new Map,this.isLocked=!0}static async fromPrivateKey(e,t,r,s=null,n=null){const o=ge.deriveAddressFromPrivateKey(t),a=await this.encryptPrivateKey(t,r);return new tt(e,o,a,s,n)}static fromEncryptedData(e,t,r,s,n){const o=Je(t);if(!o.isValid)throw new Error(`Invalid address format: ${o.errorCode??"UNKNOWN"}`);return new tt(e,t,r,s,n)}async decrypt(e){if(!tt.unsafeRawKeyExportEnabled)throw new Error("Wallet.decrypt is disabled by default for security. Use withSigningCapability() instead.");return await this.decryptPrivateKey(e)}static enableUnsafeRawKeyExportForLegacyInterop(){tt.unsafeRawKeyExportEnabled=!0}static disableUnsafeRawKeyExport(){tt.unsafeRawKeyExportEnabled=!1}static isUnsafeRawKeyExportEnabled(){return tt.unsafeRawKeyExportEnabled}async decryptPrivateKey(e){try{const t=await K.decryptWithPassword(this.privateKey,e),r=JSON.parse(t);if(r&&"object"==typeof r&&!Array.isArray(r)){const e=Object.keys(r).sort((e,t)=>Number(e)-Number(t)).map(e=>{const t=r[e],s="string"==typeof t?Number(t):t;return"number"!=typeof s||isNaN(s)?0:s});return new Uint8Array(e)}return new Uint8Array(r)}catch(e){throw new Error("Unlock Failed: "+e?.message)}}async withSigningCapability(e,t){const r=await this.decryptPrivateKey(e);let n=!1;const o={signDigest:async e=>{if(n)throw new Error("Signing capability has expired");return await s.sign(e,r)},getPublicKey:()=>{if(n)throw new Error("Signing capability has expired");return pe.getPublicKeyFromPrivateKey(r)}};try{return await t(o)}finally{n=!0,r.fill(0)}}getEncryptedPrivateKey(){return this.privateKey}registerAsset(e){this.assets.set(e.getId(),e)}getAddress(){return this.address}getName(){return this.name}getIndex(){return this.index}getAssets(){return this.assets}isWalletLocked(){return this.isLocked}toString(){const e={name:this.name,address:this.address,encryptedPrivateKey:JSON.stringify(this.privateKey),masterNodeId:this.masterNodeId??"",index:this.index?.toString()??""};return JSON.stringify(e)}static async encryptPrivateKey(e,t){return await K.encryptWithPassword(JSON.stringify(e),t)}}tt.unsafeRawKeyExportEnabled=!1;class rt{constructor(e){if("undefined"==typeof window)throw new Error("getVault can only be called in a browser environment");if(this.isLocked=!1,this.wallets=new Map,this.seeds=new Map,this.encryptedVaultData=null,!e)return;const t=JSON.parse(e);this.encryptedVaultData=t,this.isLocked=!0}static getSavedVaultKeys(){this.ensureBrowserEnvironment();const e=[];for(let t=0;t<localStorage.length;t++){const r=localStorage.key(t);r&&r.startsWith(this.vaultPrefix)&&e.push(r)}return e}static getVaultDataFromStorage(e){return this.ensureBrowserEnvironment(),localStorage.getItem(e)}isVaultLocked(){return this.isLocked}save(e="0"){if(rt.ensureBrowserEnvironment(),!this.isLocked)throw new Error("Cannot save an unlocked vault");const t=`${rt.vaultPrefix}_${e}`;localStorage.setItem(t,JSON.stringify(this.encryptedVaultData))}async lock(e){this.ensureUnlocked();const t=this.toString();this.encryptedVaultData=await K.encryptWithPassword(t,e),this.wallets=new Map,this.seeds=new Map,this.isLocked=!0}async unlock(e){if(!this.isLocked)return;if(!this.encryptedVaultData)throw new Error("Vault was unlocked on undefined encryptedVaultData");const t=await K.decryptWithPassword(this.encryptedVaultData,e),{wallets:r,seeds:s}=JSON.parse(t);this.metaToWallets(r),this.metaToSeeds(s),this.isLocked=!1}isEmpty(){return this.ensureUnlocked(),0===this.wallets.size}getWallets(){return Array.from(this.wallets.values())}getWalletsCount(){return this.ensureUnlocked(),this.wallets.size}getWalletAddresses(){return this.ensureUnlocked(),Array.from(this.wallets.keys())}addWallet(e){this.ensureUnlocked(),this.wallets.set(e.getAddress(),e)}removeWallet(e){this.ensureUnlocked(),this.wallets.delete(e)}getWallet(e){return this.ensureUnlocked(),this.wallets.get(e)}hasWallet(e){return this.ensureUnlocked(),this.wallets.has(e)}hasSeed(e){return this.ensureUnlocked(),this.seeds.has(e)}metaToWallets(e){const t=new Map;Object.keys(e).forEach(r=>{const s=JSON.parse(e[r]),n=tt.fromEncryptedData(s.name,s.address,JSON.parse(s.encryptedPrivateKey),s.masterNodeId,s.index?+s.index:null);t.set(r,n)}),this.wallets=t}metaToSeeds(e){const t=new Map;Object.keys(e).forEach(r=>{const s=Qe.createFromStringifiedEncryptedData(e[r]);t.set(r,s)}),this.seeds=t}getSeeds(){return this.ensureUnlocked(),Array.from(this.seeds.values())}getSeed(e){return this.ensureUnlocked(),this.seeds.get(e)}addSeed(e,t){this.ensureUnlocked(),this.seeds.set(e,t)}removeSeed(e){this.ensureUnlocked(),this.seeds.delete(e)}getSeedsIds(){return this.ensureUnlocked(),Array.from(this.seeds.keys())}toString(){const e={},t={};this.ensureUnlocked();const r=this.getWalletAddresses(),s=this.getSeedsIds();return r.forEach(e=>{const r=this.getWallet(e);r&&(t[e]=r.toString())}),s.forEach(t=>{const r=this.getSeed(t);r&&(e[t]=r.toString())}),JSON.stringify({wallets:t,seeds:e})}ensureUnlocked(){if(this.isLocked)throw new Error("Attempted to access locked vault")}static ensureBrowserEnvironment(){if("undefined"==typeof window)throw new Error("getVault can only be called in a browser environment")}}rt.vaultPrefix="ASI_WALLETS_VAULT";class st{constructor(e){this.vault=e}static async create(e={}){const t=e.vault||new rt;if(t.isVaultLocked()){if(!e.password)throw new Error("Vault is locked. Please provide a password to unlock it.");await t.unlock(e.password)}return new st(t)}async createWallet(e,t,r){const s=await tt.fromPrivateKey(e,t,r);return this.vault.addWallet(s),s}selectActiveWallet(e){return!!this.vault.hasWallet(e)&&(this.activeWalletAddress=e,!0)}getActiveWallet(){if(this.activeWalletAddress)return this.vault.getWallet(this.activeWalletAddress)}getWallets(){return this.vault.getWallets()}}exports.ASI_BASE_UNIT=E,exports.ASI_CHAIN_PREFIX=f,exports.ASI_COIN_TYPE=60,exports.ASI_DECIMALS=8,exports.Asset=class{constructor(e,t,r=8){this.id=e,this.name=t,this.decimals=r}getId(){return this.id}getName(){return this.name}getDecimals(){return this.decimals}},exports.AssetsService=Ze,exports.AxiosHttpClient=be,exports.BinaryWriter=Pe,exports.BlockchainGateway=Re,exports.Client=st,exports.CryptoService=K,exports.DEFAULT_AXIOS_TIMEOUT_MS=3e4,exports.DEFAULT_BIP_44_PATH_OPTIONS=m,exports.DEFAULT_CLIENT_CONFIG=xe,exports.DEFAULT_DECIMALS_AMOUNT=8,exports.DEFAULT_PHLO_LIMIT=Le,exports.DEFAULT_RESUBMIT_CONFIG=_e,exports.DEFAULT_STORAGE_KEY="0",exports.DeployResubmitter=class{constructor(e,t){if(this.startSubmissionTime=0,this.config=e,this.nodeManager=Ce.initialize(t,e.nodeSelectionAttempts,e.useRandomNode),this.errorHandler=new ve,!Re.isInitialized())throw new Error("BlockchainGateway is not initialized")}isDeployExpired(){return Date.now()-this.startSubmissionTime>=1e3*this.config.deployValiditySeconds}sleep(e){return new Promise(t=>setTimeout(t,1e3*e))}async retryDeployToOneNode(e,t,r,s){let n=this.config.deployRetries,o={success:!1};for(;n>0&&!this.isDeployExpired();){try{const n=Re.getInstance(),a=await n.getLatestBlockNumber();if(-1===a)throw new Error("DeployResubmitter.retryDeployToOneNode: Invalid block number");const i={term:e,phloLimit:s||Le,phloPrice:1,validAfterBlockNumber:a-1,timestamp:Date.now(),shardId:"root"},l=await ke.sign({wallet:t,data:i},r),c=await n.submitDeploy(l);if("string"!=typeof c){throw new Error("Invalid deploy ID received: "+c)}return o={success:!0,deployId:c},o}catch(e){const t="DeployResubmitter.retryDeployToOneNode:"+e.message,r=this.errorHandler.parseDeploymentError(t);if(console.error(t),o.error={blockchainError:{type:r,message:t}},this.errorHandler.isDeploymentErrorFatal(r))break;n--}await this.sleep(this.config.deployIntervalSeconds)}return this.isDeployExpired()&&(o.error=o?.error||{},o.error.exceededTimeout=exports.FatalDeployErrors.DEPLOY_SUBMIT_TIMEOUT),{success:!1,error:o.error}}async retryDeployToRandomNodes(e,t,r,s){let n={success:!1};for(;!this.isDeployExpired()&&this.nodeManager.getRetriesLeft()>0&&(await this.nodeManager.connectActiveRandomNode(),n=await this.retryDeployToOneNode(e,t,r,s),!n.success)&&(this.nodeManager.deactivateCurrentNode(),n.error?.blockchainError?.type)&&!this.errorHandler.isDeploymentErrorFatal(n.error?.blockchainError?.type););return n}async pollDeployStatus(e){let t;for(;!this.isDeployExpired();){const r=await Re.getInstance().getDeployStatus(e),s=r.status;if(s===exports.DeployStatus.CHECK_ERROR){const e=`DeployResubmitter.pollDeployStatus: ${"errorMessage"in r?r.errorMessage:"Unknown error"}`,s=this.errorHandler.parseDeploymentError(e);console.error(e);const n={type:s,message:e};if(this.errorHandler.isDeploymentErrorFatal(s)&&!e.includes("Bad Request"))return{success:!1,deployStatus:exports.DeployStatus.CHECK_ERROR,error:{blockchainError:n}};t=n}if(console.log("DeployResubmitter.pollDeployStatus: current deploy status:",s),s==exports.DeployStatus.INCLUDED_IN_BLOCK||s==exports.DeployStatus.FINALIZED)return{success:!0,deployStatus:r.status};await this.sleep(this.config.pollingIntervalSeconds)}return{success:!1,deployStatus:t?exports.DeployStatus.CHECK_ERROR:exports.DeployStatus.DEPLOYING,error:{...t,exceededTimeout:exports.FatalDeployErrors.BLOCK_INCLUSION_TIMEOUT}}}async resubmit(e,t,r,s){let n;if(console.log("DeployResubmitter: starting deploy submission with resubmission logic"),this.startSubmissionTime=Date.now(),this.config.useRandomNode?n=await this.retryDeployToRandomNodes(e,t,r,s):(await this.nodeManager.connectDefaultNode(),n=await this.retryDeployToOneNode(e,t,r,s)),!n.success||!n?.deployId)return n;console.log(`DeployResubmitter: deploy submitted successfully with ID: ${n.deployId}. Starting to poll for status...`);const o=await this.pollDeployStatus(n.deployId);return console.log(`DeployResubmitter: finished polling deploy status. Final status: ${o.deployStatus}, success: ${o.success}`),o}},exports.DeploymentErrorHandler=ve,exports.EncryptedRecord=Qe,exports.FAULT_TOLERANCE_THRESHOLD=.99,exports.FeeService=I,exports.GasFee=g,exports.HEX_BYTE_PADDING=64,exports.HEX_RADIX=16,exports.INVALID_BLOCK_NUMBER=-1,exports.KeyDerivationService=de,exports.KeysManager=pe,exports.MAX_WALLETS_PER_ACCOUNT=20,exports.MnemonicService=W,exports.POWER_BASE=10,exports.PRIVATE_KEY_LENGTH=32,exports.ResubmitNodeManager=Ce,exports.SecureStorage=class{constructor(e="storage_prefix"){if("undefined"==typeof localStorage)throw new Error("localStorage is not supported in this environment.");this.prefix=e}write(e,t){localStorage.setItem(this.createKey(e),t)}read(e){return localStorage.getItem(this.createKey(e))}delete(e){localStorage.removeItem(this.createKey(e))}has(e){return!!localStorage.getItem(this.createKey(e))}isEmpty(){return!this.getIds().length}clear(){this.getIds().forEach(e=>localStorage.removeItem(e))}getIds(){const e=[];for(let t=0;t<localStorage.length;t++){const r=localStorage.key(t);if(!r)break;r.startsWith(`${this.prefix}`)&&e.push(r)}return e}createKey(e){return`${this.prefix}_${e}`}},exports.SignerService=ke,exports.Vault=rt,exports.Wallet=tt,exports.WalletsService=ge,exports.arrayBufferToBase64=S,exports.base64ToArrayBuffer=D,exports.bigIntToBuffer=x,exports.bufferToBigInt=R,exports.decodeBase16=v,exports.decodeBase58=N,exports.deploymentErrorMessages=Ae,exports.encodeBase16=b,exports.encodeBase58=A,exports.fromAtomicAmount=We,exports.fromAtomicAmountToNumber=e=>{const t=e/E,r=e%E;return t>BigInt(Number.MAX_SAFE_INTEGER)?(console.warn("Integer part exceeds Number.MAX_SAFE_INTEGER; returning imprecise Number"),Number(Fe(e))):Number(t)+Number(r)/Number(E)},exports.fromAtomicAmountToString=Fe,exports.genRandomHex=e=>[...Array(e)].map(()=>Math.floor(16*Math.random()).toString(16)).join(""),exports.getDeploymentErrorMessage=function(e){return Ae[e]??"An unknown error occurred. Please try again."},exports.isAddress=e=>Je(e).isValid,exports.setupBufferPolyfill=M,exports.toAtomicAmount=e=>{const t=E.toString().length-1;if("number"==typeof e){if(!Number.isFinite(e))throw new Error("Invalid number");e=String(e)}let r=String(e).trim();if(!r.length)throw new Error("Cannot process empty amount");let s=!1;if(r.startsWith("-")&&(s=!0,r=r.slice(1)),r=r.replace(Be,""),!Ve.test(r))throw new Error("Invalid amount format");const[n,o=""]=r.split("."),a=n||"0";let i=o;i.length>t&&(console.warn(`Fraction ${i} has more than allowed decimals; truncating`),i=i.slice(0,t)),i=i.padEnd(t,"0");const l=BigInt(a)*E+BigInt(i||"0");return s?-l:l},exports.validateAccountName=(e,t=30)=>e&&0!==e.trim().length?e.length>t?{isValid:!1,error:`Account name must be ${t} characters or less`}:Ge.test(e)?{isValid:!1,error:"Account name contains invalid characters"}:{isValid:!0}:{isValid:!1,error:"Account name is required"},exports.validateAddress=Je;
1
+ "use strict";var e=require("buffer"),t=require("bs58"),r=require("blakejs"),n=require("js-sha3"),a=require("bip39"),i=require("@noble/secp256k1"),s=require("bip32"),o=require("axios"),c=require("node-persist");function l(e){return e&&e.__esModule?e:{default:e}}function d(e){if(e&&e.__esModule)return e;var t=Object.create(null);return e&&Object.keys(e).forEach(function(r){if("default"!==r){var n=Object.getOwnPropertyDescriptor(e,r);Object.defineProperty(t,r,n.get?n:{enumerable:!0,get:function(){return e[r]}})}}),t.default=e,Object.freeze(t)}var u=l(t),h=l(r),g=l(n),p=d(a),w=l(o),y=l(c);const f=5e5,m="./storage",I={MIN:170000n,MAX:250000n},v=18e4,A=3e5,b={coinId:"000000",version:"00"},E=BigInt(10)**BigInt(8),x={coinType:60,account:0,change:0,index:0},T=()=>{"undefined"==typeof window||window.Buffer||(window.Buffer=e.Buffer)},S=e=>{const t=D(e);return u.default.encode(t)},C=e=>u.default.decode(e),D=e=>{const t=new Uint8Array(e.length/2);for(let r=0;r<e.length;r+=2)t[r/2]=parseInt(e.substr(r,2),16);return t},N=e=>Array.from(e,e=>e.toString(16).padStart(2,"0")).join(""),P=e=>{const t=new Uint8Array(e);let r="";for(let e=0;e<t.byteLength;e++)r+=String.fromCharCode(t[e]);return btoa(r)},k=e=>{const t=atob(e),r=new Uint8Array(t.length);for(let e=0;e<t.length;e++)r[e]=t.charCodeAt(e);return r.buffer},M=e=>BigInt("0x"+Buffer.from(e).toString("hex")),_=e=>Uint8Array.from(Buffer.from(e.toString(16).padStart(64,"0"),"hex")),R=e=>[...Array(e)].map(()=>Math.floor(16*Math.random()).toString(16)).join(""),O=()=>`res_${Date.now()}_${R(8)}`,B=/[,\s]+/g,L=/^\d+(?:\.\d+)?$/,z=/(\.\d*?[1-9])0+$/,H=/\.0+$/,K=(e,t)=>{const r=(BigInt(10)**BigInt(t)).toString().length-1;if("number"==typeof e){if(!Number.isFinite(e))throw new Error("Invalid number");e=String(e)}let n=String(e).trim();if(!n.length)throw new Error("Cannot process empty amount");let a=!1;if(n.startsWith("-")&&(a=!0,n=n.slice(1)),n=n.replace(B,""),!L.test(n))throw new Error("Invalid amount format");const[i,s=""]=n.split("."),o=i||"0";let c=s;c.length>r&&(console.warn(`Fraction ${c} has more than allowed decimals; truncating`),c=c.slice(0,r)),c=c.padEnd(r,"0");const l=BigInt(o)*E+BigInt(c||"0");return a?-l:l},V=(e,t)=>{const r=e<0n,n=r?-e:e,a=BigInt(10)**BigInt(t),i=n/a,s=n%a,o=a.toString().length-1,c=s.toString().padStart(o,"0");return`${r?"-":""}${i.toString()}.${c}`.replace(z,"$1").replace(H,"")},W=V,U=e=>{if(e instanceof Uint8Array)return e;if("object"==typeof e&&null!==e&&"type"in e&&"Buffer"===e.type&&"data"in e&&Array.isArray(e.data))return Uint8Array.from(e.data);if(Array.isArray(e))return Uint8Array.from(e);if("object"==typeof e&&null!==e)return Uint8Array.from(Object.values(e));throw new Error("Unsupported data format")},F=(e,t={})=>{let r=e;Object.entries(t.path??{}).forEach(([e,t])=>{void 0!==t&&(r=r.replace(`:${e}`,encodeURIComponent(String(t))))});const n=new URLSearchParams;Object.entries(t.query??{}).forEach(([e,t])=>{null!=t&&n.append(e,String(t))});const a=n.toString();return a?`${r}?${a}`:r};function $(e){return e?.trim().toLowerCase()??""}const{blake2bHex:j}=h.default,X=/[<>:"/\\|?*]/,G=/^[a-zA-Z0-9]+$/,Y=/^[1-9A-HJ-NP-Za-km-z]+$/,q=`${b.coinId}${b.version}`;var J;exports.AddressValidationErrorCode=void 0,(J=exports.AddressValidationErrorCode||(exports.AddressValidationErrorCode={})).INVALID_PREFIX="INVALID_PREFIX",J.INVALID_LENGTH="INVALID_LENGTH",J.INVALID_ALPHABET="INVALID_ALPHABET",J.INVALID_BASE58="INVALID_BASE58",J.INVALID_HEX_LENGTH="INVALID_HEX_LENGTH",J.INVALID_CHAIN_PREFIX="INVALID_CHAIN_PREFIX",J.INVALID_CHECKSUM="INVALID_CHECKSUM",J.NON_CANONICAL="NON_CANONICAL";const Z=e=>({isValid:!1,errorCode:e}),Q=e=>{if(!e.startsWith("1111"))return Z(exports.AddressValidationErrorCode.INVALID_PREFIX);if(e.length<50||e.length>54)return Z(exports.AddressValidationErrorCode.INVALID_LENGTH);if(!G.test(e))return Z(exports.AddressValidationErrorCode.INVALID_ALPHABET);if(!Y.test(e))return Z(exports.AddressValidationErrorCode.INVALID_BASE58);const t=N(C(e));if(80!==t.length)return Z(exports.AddressValidationErrorCode.INVALID_HEX_LENGTH);if(S(t)!==e)return Z(exports.AddressValidationErrorCode.NON_CANONICAL);const r=t.slice(0,72),n=t.slice(72);if(!r.startsWith(q))return Z(exports.AddressValidationErrorCode.INVALID_CHAIN_PREFIX);const a=j(D(r),void 0,32).slice(0,8);return 8!==n.length||n!==a?Z(exports.AddressValidationErrorCode.INVALID_CHECKSUM):{isValid:!0}};class ee{constructor({id:e,name:t,decimals:r,contractAddress:n}){this.id=e,this.name=t,this.decimals=r??8,this.contractAddress=n??null}getId(){return this.id}getName(){return this.name}getDecimals(){return this.decimals}getContractAddress(){return this.contractAddress}}const te=new ee({id:O(),name:"ASI"});var re;T(),exports.MnemonicStrength=void 0,(re=exports.MnemonicStrength||(exports.MnemonicStrength={}))[re.TWELVE_WORDS=128]="TWELVE_WORDS",re[re.TWENTY_FOUR_WORDS=256]="TWENTY_FOUR_WORDS";class ne{static generateMnemonic(e=exports.MnemonicStrength.TWELVE_WORDS){return p.generateMnemonic(e)}static generateMnemonicArray(e=exports.MnemonicStrength.TWELVE_WORDS){return this.mnemonicToWordArray(this.generateMnemonic(e))}static isMnemonicValid(e){return p.validateMnemonic(e)}static mnemonicToWordArray(e){return e.trim().split(" ")}static wordArrayToMnemonic(e){return e.join(" ")}static async mnemonicToSeed(e,t=""){return"string"==typeof e?await p.mnemonicToSeed(e,t):await p.mnemonicToSeed(this.wordArrayToMnemonic(e),t)}}class ae{constructor({coinType:e,account:t=0,change:r=0,index:n=0}){if(e<0)throw new Error("coinType must be non-negative");if(t<0)throw new Error("account must be non-negative");if(r<ae.MIN_CHANGE||r>ae.MAX_CHANGE)throw new Error("change must be 0 or 1");if(n<0)throw new Error("index must be non-negative");this.coinType=e,this.account=t,this.change=r,this.index=n}static parse(e){const t=e.split("/");if("m"!==t[0])throw new Error("Path must start with 'm'");if(t.length!==ae.PATH_COMPONENTS_COUNT)throw new Error("Invalid BIP-44 path: expected 6 components (m/44'/coinType'/account'/change/index)");const r=t[ae.COIN_TYPE_INDEX].replace("'",""),n=t[ae.ACCOUNT_INDEX].replace("'",""),a=t[ae.CHANGE_INDEX],i=t[ae.INDEX_COMPONENT_INDEX],s=parseInt(r,ae.DECIMAL_RADIX),o=parseInt(n,ae.DECIMAL_RADIX),c=parseInt(a,ae.DECIMAL_RADIX),l=parseInt(i,ae.DECIMAL_RADIX);if(isNaN(s)||isNaN(o)||isNaN(c)||isNaN(l))throw new Error("Invalid BIP-44 path: path components must be numbers");if(t[ae.PURPOSE_INDEX]!==`${ae.BIP44_PURPOSE}'`)throw new Error("BIP-44 path must use 44' as the purpose");return new ae({coinType:s,account:o,change:c,index:l})}toString(){return`m/44'/${this.coinType}'/${this.account}'/${this.change}/${this.index}`}getCoinType(){return this.coinType}getAccount(){return this.account}getChange(){return this.change}getIndex(){return this.index}setCoinType(e){if(e<0)throw new Error("coinType must be non-negative");this.coinType=e}setAccount(e){if(e<0)throw new Error("account must be non-negative");this.account=e}setChange(e){if(e<ae.MIN_CHANGE||e>ae.MAX_CHANGE)throw new Error("change must be 0 or 1");this.change=e}setIndex(e){if(e<0)throw new Error("index must be non-negative");this.index=e}static fromOptions(e){return new ae({coinType:e.coinType,account:e.account??0,change:e.change??0,index:e.index??0})}toOptions(){return{coinType:this.coinType,account:this.account,change:this.change,index:this.index}}clone(){return new ae({coinType:this.coinType,account:this.account,change:this.change,index:this.index})}nextIndex(){return new ae({coinType:this.coinType,account:this.account,change:this.change,index:this.index+1})}}function ie(e){if(!Number.isSafeInteger(e)||e<0)throw new Error("positive integer expected, got "+e)}function se(e,...t){if(!((r=e)instanceof Uint8Array||ArrayBuffer.isView(r)&&"Uint8Array"===r.constructor.name))throw new Error("Uint8Array expected");
2
+ /*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */
3
+ var r;if(t.length>0&&!t.includes(e.length))throw new Error("Uint8Array expected of length "+t+", got length="+e.length)}function oe(e,t=!0){if(e.destroyed)throw new Error("Hash instance has been destroyed");if(t&&e.finished)throw new Error("Hash#digest() has already been called")}function ce(...e){for(let t=0;t<e.length;t++)e[t].fill(0)}function le(e){return new DataView(e.buffer,e.byteOffset,e.byteLength)}function de(e,t){return e<<32-t|e>>>t}function ue(e){return"string"==typeof e&&(e=function(e){if("string"!=typeof e)throw new Error("string expected");return new Uint8Array((new TextEncoder).encode(e))}(e)),se(e),e}ae.BIP44_PURPOSE=44,ae.MIN_CHANGE=0,ae.MAX_CHANGE=1,ae.PATH_COMPONENTS_COUNT=6,ae.PURPOSE_INDEX=1,ae.COIN_TYPE_INDEX=2,ae.ACCOUNT_INDEX=3,ae.CHANGE_INDEX=4,ae.INDEX_COMPONENT_INDEX=5,ae.DECIMAL_RADIX=10;class he{}function ge(e){const t=t=>e().update(ue(t)).digest(),r=e();return t.outputLen=r.outputLen,t.blockLen=r.blockLen,t.create=()=>e(),t}function pe(e,t,r){return e&t^~e&r}function we(e,t,r){return e&t^e&r^t&r}class ye extends he{constructor(e,t,r,n){super(),this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.blockLen=e,this.outputLen=t,this.padOffset=r,this.isLE=n,this.buffer=new Uint8Array(e),this.view=le(this.buffer)}update(e){oe(this),se(e=ue(e));const{view:t,buffer:r,blockLen:n}=this,a=e.length;for(let i=0;i<a;){const s=Math.min(n-this.pos,a-i);if(s===n){const t=le(e);for(;n<=a-i;i+=n)this.process(t,i);continue}r.set(e.subarray(i,i+s),this.pos),this.pos+=s,i+=s,this.pos===n&&(this.process(t,0),this.pos=0)}return this.length+=e.length,this.roundClean(),this}digestInto(e){oe(this),function(e,t){se(e);const r=t.outputLen;if(e.length<r)throw new Error("digestInto() expects output buffer of length at least "+r)}(e,this),this.finished=!0;const{buffer:t,view:r,blockLen:n,isLE:a}=this;let{pos:i}=this;t[i++]=128,ce(this.buffer.subarray(i)),this.padOffset>n-i&&(this.process(r,0),i=0);for(let e=i;e<n;e++)t[e]=0;!function(e,t,r,n){if("function"==typeof e.setBigUint64)return e.setBigUint64(t,r,n);const a=BigInt(32),i=BigInt(4294967295),s=Number(r>>a&i),o=Number(r&i),c=n?4:0,l=n?0:4;e.setUint32(t+c,s,n),e.setUint32(t+l,o,n)}(r,n-8,BigInt(8*this.length),a),this.process(r,0);const s=le(e),o=this.outputLen;if(o%4)throw new Error("_sha2: outputLen should be aligned to 32bit");const c=o/4,l=this.get();if(c>l.length)throw new Error("_sha2: outputLen bigger than state");for(let e=0;e<c;e++)s.setUint32(4*e,l[e],a)}digest(){const{buffer:e,outputLen:t}=this;this.digestInto(e);const r=e.slice(0,t);return this.destroy(),r}_cloneInto(e){e||(e=new this.constructor),e.set(...this.get());const{blockLen:t,buffer:r,length:n,finished:a,destroyed:i,pos:s}=this;return e.destroyed=i,e.finished=a,e.length=n,e.pos=s,n%t&&e.buffer.set(r),e}clone(){return this._cloneInto()}}const fe=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),me=Uint32Array.from([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),Ie=new Uint32Array(64);class ve extends ye{constructor(e=32){super(64,e,8,!1),this.A=0|fe[0],this.B=0|fe[1],this.C=0|fe[2],this.D=0|fe[3],this.E=0|fe[4],this.F=0|fe[5],this.G=0|fe[6],this.H=0|fe[7]}get(){const{A:e,B:t,C:r,D:n,E:a,F:i,G:s,H:o}=this;return[e,t,r,n,a,i,s,o]}set(e,t,r,n,a,i,s,o){this.A=0|e,this.B=0|t,this.C=0|r,this.D=0|n,this.E=0|a,this.F=0|i,this.G=0|s,this.H=0|o}process(e,t){for(let r=0;r<16;r++,t+=4)Ie[r]=e.getUint32(t,!1);for(let e=16;e<64;e++){const t=Ie[e-15],r=Ie[e-2],n=de(t,7)^de(t,18)^t>>>3,a=de(r,17)^de(r,19)^r>>>10;Ie[e]=a+Ie[e-7]+n+Ie[e-16]|0}let{A:r,B:n,C:a,D:i,E:s,F:o,G:c,H:l}=this;for(let e=0;e<64;e++){const t=l+(de(s,6)^de(s,11)^de(s,25))+pe(s,o,c)+me[e]+Ie[e]|0,d=(de(r,2)^de(r,13)^de(r,22))+we(r,n,a)|0;l=c,c=o,o=s,s=i+t|0,i=a,a=n,n=r,r=t+d|0}r=r+this.A|0,n=n+this.B|0,a=a+this.C|0,i=i+this.D|0,s=s+this.E|0,o=o+this.F|0,c=c+this.G|0,l=l+this.H|0,this.set(r,n,a,i,s,o,c,l)}roundClean(){ce(Ie)}destroy(){this.set(0,0,0,0,0,0,0,0),ce(this.buffer)}}const Ae=ge(()=>new ve);class be extends he{constructor(e,t){super(),this.finished=!1,this.destroyed=!1,function(e){if("function"!=typeof e||"function"!=typeof e.create)throw new Error("Hash should be wrapped by utils.createHasher");ie(e.outputLen),ie(e.blockLen)}(e);const r=ue(t);if(this.iHash=e.create(),"function"!=typeof this.iHash.update)throw new Error("Expected instance of class which extends utils.Hash");this.blockLen=this.iHash.blockLen,this.outputLen=this.iHash.outputLen;const n=this.blockLen,a=new Uint8Array(n);a.set(r.length>n?e.create().update(r).digest():r);for(let e=0;e<a.length;e++)a[e]^=54;this.iHash.update(a),this.oHash=e.create();for(let e=0;e<a.length;e++)a[e]^=106;this.oHash.update(a),ce(a)}update(e){return oe(this),this.iHash.update(e),this}digestInto(e){oe(this),se(e,this.outputLen),this.finished=!0,this.iHash.digestInto(e),this.oHash.update(e),this.oHash.digestInto(e),this.destroy()}digest(){const e=new Uint8Array(this.oHash.outputLen);return this.digestInto(e),e}_cloneInto(e){e||(e=Object.create(Object.getPrototypeOf(this),{}));const{oHash:t,iHash:r,finished:n,destroyed:a,blockLen:i,outputLen:s}=this;return e.finished=n,e.destroyed=a,e.blockLen=i,e.outputLen=s,e.oHash=t._cloneInto(e.oHash),e.iHash=r._cloneInto(e.iHash),e}clone(){return this._cloneInto()}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}}const Ee=(e,t,r)=>new be(e,t).update(r).digest();Ee.create=(e,t)=>new be(e,t),i.utils.hmacSha256Sync=(e,...t)=>Ee(Ae,e,i.utils.concatBytes(...t));const xe=i.CURVE.n,Te={isPoint(e){try{return i.Point.fromHex(e),!0}catch{return!1}},isPrivate(e){if(32!==e.length)return!1;const t=M(e);return t>0n&&t<xe},pointFromScalar(e,t=!0){try{return i.getPublicKey(e,t)}catch{return null}},pointAddScalar(e,t,r=!0){try{const n=i.Point.fromHex(e),a=M(t),s=i.Point.BASE.multiply(a);return n.add(s).toRawBytes(r)}catch{return null}},privateAdd(e,t){const r=(M(e)+M(t))%xe;return 0n===r?null:_(r)},privateNegate(e){const t=M(e);return _((xe-t)%xe)},sign:(e,t)=>i.signSync(e,t,{der:!1}),verify:(e,t,r)=>i.verify(r,e,t)};T();class Se{static async deriveKeyFromMnemonic(e,t){const r="string"==typeof t?t:t.toString(),n=await ne.mnemonicToSeed(e),a=s.BIP32Factory(Te).fromSeed(Buffer.from(n));n.fill(0);const i=a.derivePath(r);if(!i.privateKey)throw new Error("No private key at derived node");return new Uint8Array(i.privateKey)}static derivePrivateKey(e,t){const r=e.derivePath(t.toString());if(!r.privateKey)throw new Error("No private key at derived node");return new Uint8Array(r.privateKey)}static async mnemonicToSeed(e,t=""){return"string"==typeof e?await a.mnemonicToSeed(e,t):await a.mnemonicToSeed(ne.wordArrayToMnemonic(e),t)}static seedToMasterNode(e){return s.BIP32Factory(Te).fromSeed(Buffer.from(e))}static async deriveNextKeyFromMnemonic(e,t,r=x){const n=new ae({...r,index:t+1});return await this.deriveKeyFromMnemonic(e,n)}}const{randomBytes:Ce,bytesToHex:De}=i.utils;class Ne{static generateRandomKey(e=32){if(!e||e<0||!Number.isInteger(e))throw new Error("PrivateKeyLength must be a positive integer");return Ce(e)}static generateKeyPair(e=32){const t=this.generateRandomKey(e);return{privateKey:t,publicKey:i.getPublicKey(t)}}static getKeyPairFromPrivateKey(e){return{privateKey:e,publicKey:i.getPublicKey(e)}}static getPublicKeyFromPrivateKey(e){return i.getPublicKey(e)}static convertKeyToHex(e){return De(e)}static async getInitialHDPathFromOptions(e){return"customHDPath"in e?e.customHDPath:new ae({coinType:60,account:0,change:0,index:e.index})}static async getPrivateDataFromSeed(e,t){const r=Se.seedToMasterNode(e);return{privateKey:Se.derivePrivateKey(r,t),path:t,index:t.getIndex()}}}const{blake2bHex:Pe}=h.default,{keccak256:ke}=g.default;class Me{static createWallet(e,t){let r;r=e?Ne.getKeyPairFromPrivateKey(e):Ne.generateKeyPair();return{address:this.deriveAddressFromPublicKey(r.publicKey),publicKey:r.publicKey,privateKey:r.privateKey}}static async createFirstWalletWithMnemonic(e,t){const r=e?ne.mnemonicToWordArray(e):ne.generateMnemonicArray(),n=ne.wordArrayToMnemonic(r);if(!n||!ne.isMnemonicValid(n))throw new Error("WalletsService.createFirstWalletWithMnemonic: Recovery mnemonic is missing or invalid");const a=await Se.mnemonicToSeed(r),i=Se.seedToMasterNode(a),s=new ae({coinType:60,account:0,change:0,index:t||0}),o=Se.derivePrivateKey(i,s);return{...this.createWallet(o),mnemonic:n}}static deriveAddressFromPrivateKey(e){const t=Ne.getKeyPairFromPrivateKey(e);return this.deriveAddressFromPublicKey(t.publicKey)}static deriveAddressFromPublicKey(e){const t=ke(e.slice(1)),r=D(t.slice(-40)),n=ke(r),a=`${b.coinId}${b.version}${n}`,i=D(a),s=Pe(i,void 0,32).slice(0,8);return S(`${a}${s}`)}}function _e(e,t,r,n,a,i){function s(e){if(void 0!==e&&"function"!=typeof e)throw new TypeError("Function expected");return e}for(var o,c=n.kind,l="getter"===c?"get":"setter"===c?"set":"value",d=!t&&e?n.static?e:e.prototype:null,u=t||(d?Object.getOwnPropertyDescriptor(d,n.name):{}),h=!1,g=r.length-1;g>=0;g--){var p={};for(var w in n)p[w]="access"===w?{}:n[w];for(var w in n.access)p.access[w]=n.access[w];p.addInitializer=function(e){if(h)throw new TypeError("Cannot add initializers after decoration has completed");i.push(s(e||null))};var y=(0,r[g])("accessor"===c?{get:u.get,set:u.set}:u[l],p);if("accessor"===c){if(void 0===y)continue;if(null===y||"object"!=typeof y)throw new TypeError("Object expected");(o=s(y.get))&&(u.get=o),(o=s(y.set))&&(u.set=o),(o=s(y.init))&&a.unshift(o)}else(o=s(y))&&("field"===c?a.unshift(o):u[l]=o)}d&&Object.defineProperty(d,n.name,u),h=!0}function Re(e,t,r){for(var n=arguments.length>2,a=0;a<t.length;a++)r=n?t[a].call(e,r):t[a].call(e);return n?r:void 0}"function"==typeof SuppressedError&&SuppressedError;class Oe{constructor(e){this.client=w.default.create({baseURL:e.baseUrl,headers:{"Content-Type":"application/json"},...e.axiosConfig})}async query(e,t){const r=await this.client.post("",{query:e,variables:t},{headers:{"Content-Type":"application/json"}});if(r.data.errors?.length)throw new Error(JSON.stringify(r.data.errors));return r.data.data}}function Be(e,t,r){const n=$(r);return $(e)===n?"send":"receive"}function Le(e){if(void 0===e||""===e)return new Date(0);if("number"==typeof e)return ze(e);const t=e.trim();if(/^\d+$/.test(t))return ze(Number(t));const r=Date.parse(t);return Number.isFinite(r)?new Date(r):new Date(0)}function ze(e){return new Date(e<1e10?1e3*e:e)}class He{static isRecord(e){return"object"==typeof e&&null!==e}static isDefined(e){return void 0!==e}static createTransactionHistoryRequest(e,t={}){const r={address:e.trim(),offset:t.offset??0};return void 0!==t.limit&&(r.limit=t.limit),{query:"\n query GetTransactionHistory($address: String!, $offset: Int!, $limit: Int) {\n transfers(\n where: {\n _or: [\n {from_address: {_eq: $address}},\n {to_address: {_eq: $address}}\n ]\n },\n order_by: {block_number: desc},\n offset: $offset,\n limit: $limit\n ) {\n deploy_id\n block_number\n from_address\n to_address\n amount_asi\n timestamp\n from_public_key\n }\n }\n",variables:r}}static mapTransactionHistory(e,t,r){return e&&e.transfers?e.transfers.map(e=>function(e,t){const r=e.from_address?.trim(),n=e.to_address?.trim();var a;if(e.deploy_id&&r&&n)return{id:e.deploy_id,timestamp:Le(e.timestamp),type:Be(r,0,t.accountAddress),from:r,to:n,amount:(a=e.amount_asi,void 0===a?void 0:String(a)),deployId:e.deploy_id,blockHash:e.block_hash,status:"confirmed",networkName:t.networkName,detectedBy:"auto"}}(e,{accountAddress:t,networkName:r})).filter(this.isDefined):[]}static unwrapGraphqlEnvelope(e){if(this.isRecord(e)){if("transfers"in e)return{data:e};const t=e.data;if(this.isRecord(t)&&("data"in t||"errors"in t))return t}return e}static isRecoverableNetworkError(e){const t=String(e?.message??"");return"ERR_NETWORK"===e?.code||t.includes("CORS")||t.includes("ERR_FAILED")}}class Ke extends Oe{async getTransactionHistory(e,t={}){const{query:r,variables:n}=He.createTransactionHistoryRequest(e,t);return this.query(r,n)}}class Ve{constructor(e){this.client=w.default.create({baseURL:e.baseUrl,...e.axiosConfig})}async get(e,t){return(await this.client.get(e,t)).data}async post(e,t,r){return(await this.client.post(e,t,r)).data}}class We extends Ve{getDeploy(e){return this.get(`/api/deploy/${e}`)}getBlock(e){return this.get(`/api/block/${e}`)}getBlocks(e={}){const{start:t,end:r,view:n}=e,a=F("api/blocks",{path:{start:t,end:r,view:n}});return this.get(a,n?{params:{view:n}}:void 0)}}class Ue extends Ve{submitDeploy(e){return this.post("/api/deploy",e)}submitExploratoryDeploy(e){return this.post("/api/explore-deploy",e)}getStatus(){return this.get("/status")}}class Fe{constructor(){this.networksConfig=null}initialize(e){this.networksConfig=e}get(e){if(!this.networksConfig)throw new Error("Network config is not initialized");return this.networksConfig[e]}getNetworkNames(){if(!this.networksConfig)throw new Error("Network config is not initialized");return Object.keys(this.networksConfig)}isReady(){return null!==this.networksConfig}}function $e(e,t){return function(...t){if(!this.isReady())throw new Error("ApiClientManager is not initialized");return e.apply(this,t)}}function je(e,t){return function(...t){if(!this.networkConfigProvider.isReady())throw new Error("ApiClientManager config is not initialized");return e.apply(this,t)}}let Xe=(()=>{var e;let t,r,n,a,i,s,o,c=[];return e=class{constructor(){this.networkConfigProvider=Re(this,c),this.validatorClient=null,this.observerClient=null,this.indexerClient=null,this.currentNetwork=null,this.isInitialized=!1,this.networkConfigProvider=new Fe}static getInstance(){return e.instance||(e.instance=new e),e.instance}initialize(e,t){if(this.isInitialized)return;this.networkConfigProvider.initialize(e);const r=t??Object.keys(e)[0];this.switchNetwork(r),this.isInitialized=!0}switchNetwork(e){const t=this.networkConfigProvider.get(e);this.validatorClient=new Ue({baseUrl:t.ValidatorURL}),this.observerClient=new We({baseUrl:t.ReadOnlyURL}),this.indexerClient=new Ke({baseUrl:t.IndexerURL}),this.currentNetwork=e}getValidatorClient(){return this.validatorClient}getObserverClient(){return this.observerClient}getIndexerClient(){return this.indexerClient}getClients(){return{validator:this.validatorClient,observer:this.observerClient,indexer:this.indexerClient}}getNetwork(){return this.currentNetwork}getNetworkNames(){return this.networkConfigProvider.getNetworkNames()}isReady(){return this.isInitialized}close(){this.validatorClient=null,this.observerClient=null,this.indexerClient=null,this.currentNetwork=null,this.isInitialized=!1}},(()=>{const l="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;t=[je],r=[$e],n=[$e],a=[$e],i=[$e],s=[$e],o=[$e,je],_e(e,null,t,{kind:"method",name:"switchNetwork",static:!1,private:!1,access:{has:e=>"switchNetwork"in e,get:e=>e.switchNetwork},metadata:l},null,c),_e(e,null,r,{kind:"method",name:"getValidatorClient",static:!1,private:!1,access:{has:e=>"getValidatorClient"in e,get:e=>e.getValidatorClient},metadata:l},null,c),_e(e,null,n,{kind:"method",name:"getObserverClient",static:!1,private:!1,access:{has:e=>"getObserverClient"in e,get:e=>e.getObserverClient},metadata:l},null,c),_e(e,null,a,{kind:"method",name:"getIndexerClient",static:!1,private:!1,access:{has:e=>"getIndexerClient"in e,get:e=>e.getIndexerClient},metadata:l},null,c),_e(e,null,i,{kind:"method",name:"getClients",static:!1,private:!1,access:{has:e=>"getClients"in e,get:e=>e.getClients},metadata:l},null,c),_e(e,null,s,{kind:"method",name:"getNetwork",static:!1,private:!1,access:{has:e=>"getNetwork"in e,get:e=>e.getNetwork},metadata:l},null,c),_e(e,null,o,{kind:"method",name:"getNetworkNames",static:!1,private:!1,access:{has:e=>"getNetworkNames"in e,get:e=>e.getNetworkNames},metadata:l},null,c),l&&Object.defineProperty(e,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:l})})(),e})();class Ge{constructor(e){this.apiClientManager=e??Xe.getInstance()}async getTransactionHistory(e,t,r={}){try{const n=t??Xe.getInstance().getNetwork(),a=await this.apiClientManager.getIndexerClient().getTransactionHistory(e,r);return He.mapTransactionHistory(a,e,n)}catch(e){return He.isRecoverableNetworkError(e)?(console.warn("[GraphQL] Network error while loading transaction history. Returning an empty history."),[]):(console.error("AccountDataService.getTransactionHistory:",e),[])}}}const Ye=e=>e.replace(/\\/g,"\\\\").replace(/"/g,'\\"').replace(/\n/g,"\\n").replace(/\r/g,"\\r").replace(/\t/g,"\\t");class qe{constructor(e){this.deployService=e}async getBalance(e,t){const r=Q(e);if(!r.isValid)throw new Error(`AssetsService.getBalance: Invalid address: ${r.errorCode??"UNKNOWN"}`);const n=(e=>`\n new return, rl(\`rho:registry:lookup\`), ASIVaultCh, vaultCh in {\n rl!(\`rho:rchain:asiVault\`, *ASIVaultCh) |\n for (@(_, ASIVault) <- ASIVaultCh) {\n @ASIVault!("findOrCreate", "${Ye(e)}", *vaultCh) |\n for (@maybeVault <- vaultCh) {\n match maybeVault {\n (true, vault) => @vault!("balance", *return)\n (false, err) => return!(err)\n }\n }\n }\n }\n`)(e);try{const e=await this.deployService.exploreDeployData(n);if(e?.length>0){const r=e[0];if(void 0!==r?.ExprInt?.data)return{amount:BigInt(r.ExprInt.data),asset:t};if(void 0!==r?.ExprString?.data)throw new Error("Balance check error")}return{amount:0n,asset:t}}catch{return{amount:0n,asset:t}}}}class Je{constructor(e){this.apiClientManager=e??Xe.getInstance()}async getBlock(e){const t=this.apiClientManager.getObserverClient();return(await t.getBlock(e)).blockInfo}async getLatestBlock(){const e=await this.apiClientManager.getObserverClient().getBlocks();if(!e?.length)throw new Error("BlockService.getLatestBlock: No blocks returned from /api/blocks");return e[0]}async getLatestBlockNumber(){try{return(await this.getLatestBlock()).blockNumber??-1}catch{return-1}}async isValidatorActive(){try{return await this.apiClientManager.getValidatorClient().getStatus(),!0}catch{return!1}}}var Ze;exports.DeployStatus=void 0,(Ze=exports.DeployStatus||(exports.DeployStatus={})).DEPLOYING="Deploying",Ze.INCLUDED_IN_BLOCK="IncludedInBlock",Ze.FINALIZED="Finalized",Ze.CHECK_ERROR="CheckingError";class Qe{constructor(e){this.apiClientManager=e??Xe.getInstance()}extractDeployId(e){if("string"==typeof e){const t=/DeployId is:\s*([a-fA-F0-9]+)/.exec(e);return t?.[1]??e}if(e&&"object"==typeof e){const t=e;return t.deployId??t.signature}}async submitSignedDeploy(e){try{const t=await this.apiClientManager.getValidatorClient().submitDeploy(e);return this.extractDeployId(t)}catch(e){throw new Error(`DeployService.submitDeploy: ${e instanceof Error?e.message:String(e)}`)}}async exploreDeployData(e){try{return(await this.apiClientManager.getValidatorClient().submitExploratoryDeploy(e)).expr}catch(e){throw new Error("DeployService.exploreDeployData: "+(e instanceof Error?e.message:String(e)))}}async getDeploy(e){return this.apiClientManager.getObserverClient().getDeploy(e)}async isDeployFinalized(e){return e.faultTolerance>=.99}async getDeployStatus(e){try{const t=await this.getDeploy(e);if(!t?.blockHash)return{status:exports.DeployStatus.DEPLOYING};return{status:await this.isDeployFinalized(t)?exports.DeployStatus.FINALIZED:exports.DeployStatus.INCLUDED_IN_BLOCK}}catch(e){return{status:exports.DeployStatus.CHECK_ERROR,errorMessage:e instanceof Error?e.message:String(e)}}}}class et{constructor(e){this.deployService=e}watch(e,t={},{intervalMs:r=5e3,timeoutMs:n=18e4}={}){const a=Date.now()+n;let i,s,o,c=!1,l=!1;const d=new Promise((e,t)=>{s=e,o=t}),u=()=>{l||(l=!0,clearInterval(i))},h=e=>{u(),t.onError?.(e),o(e)},g=async()=>{if(!c&&!l){c=!0;try{const n=await this.deployService.getDeployStatus(e);if(t.onStatus?.(n,e),n.status===exports.DeployStatus.FINALIZED)return r={deployId:e},u(),t.onConfirmed?.(r),void s(r);Date.now()>a&&h(new Error(`DeployStatusPoller: timeout for ${e}`))}catch(e){h(e instanceof Error?e:new Error(String(e)))}finally{c=!1}var r}};return i=setInterval(g,r),g(),d.catch(()=>{}),{cancel:u,done:d}}waitFor(e,t){return this.watch(e,{},t).done}}const tt=127;class rt{constructor(){this.buffer=[]}writeString(e,t){if(!t)return;const r=e<<3|2;this.writeInteger(r);const n=(new TextEncoder).encode(t);this.writeInteger(n.length),this.buffer.push(...Array.from(n))}writeInt64(e,t){if(!t)return;const r=e<<3;this.writeInteger(r),this.writeInteger64(t)}writeInteger(e){for(;e>tt;)this.buffer.push(e&tt|128),e>>>=7;this.buffer.push(e)}writeInteger64(e){for(;e>tt;)this.buffer.push(e&tt|128),e=Math.floor(e/128);this.buffer.push(e)}getResultBuffer(){return new Uint8Array(this.buffer)}}class nt{}var at;nt.deployDataProtobufSerialize=e=>{const{term:t,timestamp:r,phloPrice:n,phloLimit:a,validAfterBlockNumber:i,shardId:s=""}=e,o=new rt;return o.writeString(2,t),o.writeInt64(3,r),o.writeInt64(7,n),o.writeInt64(8,a),o.writeInt64(10,i),o.writeString(11,s),o.getResultBuffer()},exports.WalletTypes=void 0,(at=exports.WalletTypes||(exports.WalletTypes={})).PRIVATE_KEY="private-key",at.HD="hd";class it{constructor({id:e,encryptedSecret:t}){this.id=e,this.encryptedSecret=t}getId(){return this.id}getEncryptedSecret(){return this.encryptedSecret}}const{blake2bHex:st}=h.default;class ot{constructor(e,t){this.deployService=e,this.blockService=t}async signDeploy(e,t,r){const n=nt.deployDataProtobufSerialize(t),a=st(n,void 0,32),i=await e.sign(a,r);return{data:t,deployer:N(i.publicKey),signature:N(i.signature),sigAlgorithm:"secp256k1"}}async transfer({walletType:e,account:t,signer:r,details:n,passwordProvider:a}){if(!t)throw new Error("Wallet has no active account");const i=t.getAddress(),s=Q(n.to);if(!s.isValid)throw new Error(`Invalid recipient address: ${s.errorCode}`);if(n.amount<=0n)throw new Error("Amount must be greater than zero");if(n.phloLimit&&n.phloLimit<=0n)throw new Error("Phlo limit must be greater than zero");if(n.phloPrice&&n.phloPrice<=0n)throw new Error("Phlo price must be greater than zero");const o=((e,t,r)=>{if(r<=0n)throw new Error("Transfer amount must be greater than zero");const n=Ye(e),a=Ye(t),i=r.toString();return`\n new \n deployerId(\`rho:rchain:deployerId\`),\n stdout(\`rho:io:stdout\`),\n rl(\`rho:registry:lookup\`),\n ASIVaultCh,\n vaultCh,\n toVaultCh,\n asiVaultkeyCh,\n resultCh\n in {\n rl!(\`rho:rchain:asiVault\`, *ASIVaultCh) |\n for (@(_, ASIVault) <- ASIVaultCh) {\n @ASIVault!("findOrCreate", "${n}", *vaultCh) |\n @ASIVault!("findOrCreate", "${a}", *toVaultCh) |\n @ASIVault!("deployerAuthKey", *deployerId, *asiVaultkeyCh) |\n for (@(true, vault) <- vaultCh; key <- asiVaultkeyCh; @(true, toVault) <- toVaultCh) {\n @vault!("transfer", "${a}", ${i}, *key, *resultCh) |\n for (@result <- resultCh) {\n match result {\n (true, Nil) => {\n stdout!(("Transfer successful:", ${i}, "ASI"))\n }\n (false, reason) => {\n stdout!(("Transfer failed:", reason))\n }\n }\n }\n } |\n for (@(false, errorMsg) <- vaultCh) {\n stdout!(("Sender vault error:", errorMsg))\n } |\n for (@(false, errorMsg) <- toVaultCh) {\n stdout!(("Destination vault error:", errorMsg))\n }\n }\n }\n `})(i,n.to,n.amount),c=await this.blockService.getLatestBlockNumber();if(-1===c)throw new Error("TransactionService.transfer: Invalid block number");const l=e!==exports.WalletTypes.HD?{passwordProvider:a}:{passwordProvider:a,index:t.getIndex()},d=await this.signDeploy(r,{term:o,phloLimit:n.phloLimit??f,phloPrice:n.phloPrice??1,validAfterBlockNumber:c-1,timestamp:Date.now(),shardId:n.shardId??"root"},l);try{const e=await this.deployService.submitSignedDeploy(d);if(!e)throw new Error("Error on submitted deploy parsing - not found deploy id");return e}catch(e){throw e}}}class ct{constructor(e){this.deploy=new Qe(e),this.blocks=new Je(e),this.accountData=new Ge(e),this.assets=new qe(this.deploy),this.transactions=new ot(this.deploy,this.blocks),this.poller=new et(this.deploy)}static getInstance(e){return ct.instance||(ct.instance=new ct(e??Xe.getInstance())),ct.instance}}class lt{constructor({id:e,name:t,index:r,portfolioOptions:n,address:a}){this.id=e??O(),this.name=t,this.index=r,this.address=a,this.assets=n?.assets??new Map([[te.getId(),te]]),this.primaryAsset=n?.primaryAsset??te}getId(){return this.id}getName(){return this.name}getIndex(){return this.index}listAssets(){return Array.from(this.assets.values())}getAddress(){return this.address}getAsset(e){return this.assets.get(e)??null}registerAsset(e){this.assets.set(e.getId(),e)}setPrimaryAsset(e){const t=this.assets.get(e);t?this.primaryAsset=t:console.error("Cannot set primary asset with incorrect id")}static async create(e,t){const r=t.getSecret();if((e=>"privateKey"in e)(r)){const t=Me.deriveAddressFromPrivateKey(r.privateKey);return new lt({...e,index:null,address:t})}void 0!==e.index&&r.rootHDPath.setIndex(e.index);const n=await Se.deriveKeyFromMnemonic(r.seed,r.rootHDPath),a=Me.deriveAddressFromPrivateKey(n);return n.fill(0),new lt({...e,index:r.rootHDPath.getIndex(),address:a})}update(e){e.name&&(this.name=e.name)}async getBalance(){return ct.getInstance().assets.getBalance(this.address,this.primaryAsset)}async getTransactionsHistory(e,t){return ct.getInstance().accountData.getTransactionHistory(this.address,e,t)}}function dt(e,t){return async function(...t){return await this.init(),await e.apply(this,t)}}function ut(e,t){return async function(...t){const r=t[0];if("string"!=typeof r)throw new Error("Table name must be a string and should be the first argument of the method. Received: "+typeof t[0]);if(!await this.tableExists(r))throw new Error(`Table '${r}' does not exist. Use createTable() first.`);return await e.apply(this,t)}}function ht(e,t){return async function(...t){if(this.isInitialized())return await e.apply(this,t)}}function gt(e,t){return async function(...t){const r=t[0];if("string"!=typeof r)throw new Error("Table name must be a string and should be the first argument of the method. Received: "+typeof t[0]);if(!await this.tableExists(r))return await e.apply(this,t)}}function pt(e,t){return async function(...t){if(this.getType()!==exports.WalletTypes.HD)throw new Error("This operation is available only for HD wallets");return await e.apply(this,t)}}function wt(e,t){return function(...t){if(!this.accountManager.getActiveAccount())throw new Error("Wallet hasn't active account for transfer!");return e.apply(this,t)}}function yt(e,t){return function(...t){if(!this.flags?.withInsensitiveCacheStorage)throw new Error("You cannot get insensitive account data when storage flag inactive!");return e.apply(this,t)}}let ft=(()=>{var e;let t,r,n,a,i=[];return e=class{constructor(e="AppDatabase"){this.name=Re(this,i),this.storageInterface=null,this.name=e}static getInstance(t){return e.instance||(e.instance=new e(t)),e.instance}async init(){return this.storageInterface?this.storageInterface:new Promise((e,t)=>{const r=indexedDB.open(this.name);r.onsuccess=()=>{this.storageInterface=r.result,this.storageInterface.onclose=()=>{this.storageInterface=null},this.storageInterface.onversionchange=()=>{this.storageInterface?.close(),this.storageInterface=null},e(this.storageInterface)},r.onerror=()=>{t(new Error(`Failed to open database: ${r.error?.message}`))}})}async createTable(e,t="id"){const r=this.storageInterface.version+1;return await this.close(),new Promise((n,a)=>{const i=indexedDB.open(this.name,r);i.onupgradeneeded=r=>{const n=i.result;if(!n.objectStoreNames.contains(e)){n.createObjectStore(e,{keyPath:t}).createIndex("createdAt","createdAt",{unique:!1})}},i.onsuccess=()=>{this.storageInterface=i.result,n()},i.onerror=()=>{a(new Error(`Failed to create table: ${i.error?.message}`))}})}async insert(e,t){const r={...t,createdAt:t.createdAt||Date.now(),updatedAt:Date.now()};await this.executeTransaction(e,"readwrite",e=>e.add(r))}async insertMany(e,t){const r=t.map(e=>({...e,createdAt:e.createdAt||Date.now(),updatedAt:Date.now()}));await this.executeTransaction(e,"readwrite",e=>{for(const t of r)e.add(t)})}async getById(e,t){return await this.executeTransaction(e,"readonly",e=>e.get(t))||null}async getAll(e){return await this.executeTransaction(e,"readonly",e=>e.getAll())||[]}async update(e,t,r){const n=await this.getById(e,t);if(!n)throw new Error(`Record with id '${t}' not found in table '${e}'`);const a={...n,...r,id:n.id,updatedAt:Date.now()};await this.executeTransaction(e,"readwrite",e=>e.put(a))}async delete(e,t){await this.executeTransaction(e,"readwrite",e=>e.delete(t))}async deleteMany(e,t){await this.executeTransaction(e,"readwrite",e=>{for(const r of t)e.delete(r)})}async clearTable(e){await this.executeTransaction(e,"readwrite",e=>e.clear())}async dropTable(e){const t=this.storageInterface.version+1;return await this.close(),new Promise((r,n)=>{const a=indexedDB.open(this.name,t);a.onupgradeneeded=t=>{const r=a.result;r.objectStoreNames.contains(e)&&r.deleteObjectStore(e)},a.onsuccess=()=>{this.storageInterface=a.result,r()},a.onerror=()=>{n(new Error(`Failed to drop table: ${a.error?.message}`))}})}async tableExists(e){return this.storageInterface?.objectStoreNames.contains(e)??!1}getVersion(){return this.storageInterface?.version??0}getDatabaseName(){return this.name}getTableNamesList(){return this.storageInterface?Array.from(this.storageInterface.objectStoreNames):[]}async executeTransaction(e,t,r){return new Promise((n,a)=>{if(!this.storageInterface)return void a(new Error("Database not initialized"));const i=this.storageInterface.transaction(e,t),s=i.objectStore(e),o=r(s);i.oncomplete=()=>{n(o&&"result"in o?o.result:void 0)},i.onerror=()=>{a(new Error(`Transaction failed: ${i.error?.message}`))},i.onabort=()=>{a(new Error("Transaction aborted"))}})}isInitialized(){return!!this.storageInterface}async close(){this.storageInterface&&(this.storageInterface.close(),this.storageInterface=null)}},(()=>{const s="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;t=[dt],r=[dt,ut],n=[dt],a=[dt,ut],_e(e,null,t,{kind:"method",name:"createTable",static:!1,private:!1,access:{has:e=>"createTable"in e,get:e=>e.createTable},metadata:s},null,i),_e(e,null,r,{kind:"method",name:"dropTable",static:!1,private:!1,access:{has:e=>"dropTable"in e,get:e=>e.dropTable},metadata:s},null,i),_e(e,null,n,{kind:"method",name:"tableExists",static:!1,private:!1,access:{has:e=>"tableExists"in e,get:e=>e.tableExists},metadata:s},null,i),_e(e,null,a,{kind:"method",name:"executeTransaction",static:!1,private:!1,access:{has:e=>"executeTransaction"in e,get:e=>e.executeTransaction},metadata:s},null,i),s&&Object.defineProperty(e,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:s})})(),e.instance=null,e})();const mt="__tables__";let It=(()=>{var e;let t,r,n,a,i,s,o,c,l=[];return e=class{constructor(e=m){this.storageDir=Re(this,l),this.storageInterface=null,this.storageDir=e}static getInstance(t){return e.instance||(e.instance=new e(t)),e.instance}async init(){this.storageInterface||(this.storageInterface=y.default.create({dir:this.storageDir}),await this.storageInterface.init())}getTableKey(e){return`table:${e}`}async getTable(e){return this.storageInterface.getItem(this.getTableKey(e))}async saveTable(e,t){await this.storageInterface.setItem(this.getTableKey(e),t)}async createTable(e,t){await this.storageInterface.setItem(this.getTableKey(e),{});const r=await this.storageInterface.getItem(mt)??[];r.push(e),await this.storageInterface.setItem(mt,r)}async insert(e,t){const r=await this.getTable(e);if(r[String(t.id)])throw new Error(`Record with id '${t.id}' already exists`);r[String(t.id)]={...t,createdAt:t.createdAt||Date.now(),updatedAt:Date.now()},await this.saveTable(e,r)}async insertMany(e,t){const r=await this.getTable(e);for(const e of t)r[String(e.id)]={...e,createdAt:e.createdAt||Date.now(),updatedAt:Date.now()};await this.saveTable(e,r)}async getById(e,t){return(await this.getTable(e))[String(t)]||null}async getAll(e){const t=await this.getTable(e);return Object.values(t)}async update(e,t,r){const n=await this.getTable(e),a=n[String(t)];if(!a)throw new Error(`Record with id '${t}' not found in table '${e}'`);n[String(t)]={...a,...r,id:a.id,updatedAt:Date.now()},await this.saveTable(e,n)}async delete(e,t){const r=await this.getTable(e);delete r[String(t)],await this.saveTable(e,r)}async deleteMany(e,t){const r=await this.getTable(e);for(const e of t)delete r[String(e)];await this.saveTable(e,r)}async clearTable(e){await this.saveTable(e,{})}async dropTable(e){await this.storageInterface.removeItem(this.getTableKey(e));const t=await this.storageInterface.getItem(mt);await this.storageInterface.setItem(mt,t.filter(t=>t!==e))}isInitialized(){return!!this.storageInterface}getKeys(){return this.storageInterface.keys()}async tableExists(e){return(await this.storageInterface.keys(t=>t.key===this.getTableKey(e))).length>0}async close(){this.storageInterface=null}},(()=>{const d="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;t=[dt,ut],r=[dt],n=[dt,gt],a=[ut],i=[dt,ut],s=[dt],o=[dt],c=[ht],_e(e,null,t,{kind:"method",name:"getTable",static:!1,private:!1,access:{has:e=>"getTable"in e,get:e=>e.getTable},metadata:d},null,l),_e(e,null,r,{kind:"method",name:"saveTable",static:!1,private:!1,access:{has:e=>"saveTable"in e,get:e=>e.saveTable},metadata:d},null,l),_e(e,null,n,{kind:"method",name:"createTable",static:!1,private:!1,access:{has:e=>"createTable"in e,get:e=>e.createTable},metadata:d},null,l),_e(e,null,a,{kind:"method",name:"clearTable",static:!1,private:!1,access:{has:e=>"clearTable"in e,get:e=>e.clearTable},metadata:d},null,l),_e(e,null,i,{kind:"method",name:"dropTable",static:!1,private:!1,access:{has:e=>"dropTable"in e,get:e=>e.dropTable},metadata:d},null,l),_e(e,null,s,{kind:"method",name:"getKeys",static:!1,private:!1,access:{has:e=>"getKeys"in e,get:e=>e.getKeys},metadata:d},null,l),_e(e,null,o,{kind:"method",name:"tableExists",static:!1,private:!1,access:{has:e=>"tableExists"in e,get:e=>e.tableExists},metadata:d},null,l),_e(e,null,c,{kind:"method",name:"close",static:!1,private:!1,access:{has:e=>"close"in e,get:e=>e.close},metadata:d},null,l),d&&Object.defineProperty(e,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:d})})(),e.instance=null,e})();const vt=e=>"undefined"!=typeof window?ft.getInstance():It.getInstance(e?.nodeStorageDir),At="ACCOUNTS";class bt{constructor(e){this.isInitialized=!1,this.initPromise=null,this.storageInterface=vt(e)}static getInstance(e){return bt.instance||(bt.instance=new bt(e)),bt.instance}async initialize(){if(!this.isInitialized){if(this.initPromise)return this.initPromise;this.initPromise=this.doInitialize();try{await this.initPromise}finally{this.initPromise=null}}}async doInitialize(){try{await this.storageInterface.tableExists(At)||await this.storageInterface.createTable(At,"id"),this.isInitialized=!0}catch(e){throw e}}async ensureInitialized(){this.isInitialized||await this.initialize()}getRawDB(){return this.storageInterface}async saveAccount(e,t,r,n){await this.ensureInitialized(),await this.storageInterface.insert(At,{id:e,signerId:t,name:r,index:n,createdAt:Date.now()})}async saveAccounts(e){await this.ensureInitialized(),await this.storageInterface.insertMany(At,e)}async getAccount(e){return await this.ensureInitialized(),this.storageInterface.getById(At,e)}async getAllAccounts(){return await this.ensureInitialized(),this.storageInterface.getAll(At)}async updateAccount(e,t){await this.ensureInitialized(),await this.storageInterface.update(At,e,t)}async deleteAccount(e){await this.ensureInitialized(),await this.storageInterface.delete(At,e)}async deleteMultipleAccounts(e){await this.ensureInitialized(),await this.storageInterface.deleteMany(At,e)}async hasAccount(e){await this.ensureInitialized();return null!==await this.getAccount(e)}async getAccountsCount(){await this.ensureInitialized();return(await this.getAllAccounts()).length}async clearAllData(){await this.ensureInitialized(),await this.storageInterface.clearTable(At)}async clearTable(e){if(await this.ensureInitialized(),![At].includes(e))throw new Error(`Invalid table name: ${e}`);await this.storageInterface.clearTable(e)}isReady(){return this.isInitialized}async getTablesList(){return await this.ensureInitialized(),[At]}close(){this.storageInterface.close(),this.isInitialized=!1}}var Et;!function(e){e.ENCRYPT="encrypt",e.DECRYPT="decrypt",e.DERIVATION="deriveKey"}(Et||(Et={}));const xt=2,Tt=12,St=16,Ct=256,Dt="AES-GCM",Nt="SHA-256",Pt="raw",kt="PBKDF2",Mt=1e5;Et.ENCRYPT,Et.DECRYPT;class _t{static async encryptWithPassword(e,t){const r=crypto.getRandomValues(new Uint8Array(St)),n=crypto.getRandomValues(new Uint8Array(Tt)),a=await this.deriveKey(t,r),i=await crypto.subtle.encrypt({name:Dt,iv:n},a,(new TextEncoder).encode(e));return{data:P(i),salt:P(r.buffer),iv:P(n.buffer),version:xt}}static async decryptWithPassword(e,t){if(e.version!==xt)throw new Error(`Unsupported version ${e.version}`);const r=new Uint8Array(k(e.salt)),n=new Uint8Array(k(e.iv)),a=await this.deriveKey(t,r),i=await crypto.subtle.decrypt({name:Dt,iv:n},a,k(e.data));return(new TextDecoder).decode(i)}static async decryptSignerData(e,t){const r=await _t.decryptWithPassword(e,t.getSecret().password),n=JSON.parse(r);if("privateKey"in n){return{privateKey:U(n.privateKey)}}const a=ae.parse(n.rootHDPath);return{seed:n.seed,rootHDPath:a}}static async deriveKey(e,t){const r=await crypto.subtle.importKey(Pt,(new TextEncoder).encode(e),kt,!1,[Et.DERIVATION]);return crypto.subtle.deriveKey({name:kt,salt:new Uint8Array(t),iterations:Mt,hash:Nt},r,{name:Dt,length:Ct},!1,[Et.ENCRYPT,Et.DECRYPT])}}class Rt extends it{async sign(e,t){const r=await _t.decryptWithPassword(this.encryptedSecret,t.passwordProvider.getSecret().password),n=JSON.parse(r),a=ae.parse(n.rootHDPath);a.setIndex(t.index);const s=await Se.deriveKeyFromMnemonic(n.seed,a),o=Ne.getPublicKeyFromPrivateKey(s);try{return{signature:await i.sign(e,s),publicKey:o}}finally{s.fill(0)}}}class Ot extends it{async sign(e,t){const{privateKey:r}=await _t.decryptSignerData(this.encryptedSecret,t.passwordProvider),n=Ne.getPublicKeyFromPrivateKey(r);try{return{signature:await i.sign(e,r),publicKey:n}}finally{r.fill(0)}}}const Bt=async e=>{const{password:t,secret:r}=e.secretProvider.getSecret(),n=await _t.encryptWithPassword(JSON.stringify(r),t);switch(e.type){case exports.WalletTypes.PRIVATE_KEY:return new Ot({id:e.id,encryptedSecret:n});case exports.WalletTypes.HD:return new Rt({id:e.id,encryptedSecret:n})}};var Lt;class zt{constructor(e){Lt.set(this,void 0),function(e,t,r,n,a){if("m"===n)throw new TypeError("Private method is not writable");if("a"===n&&!a)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!a:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");"a"===n?a.call(e,r):a?a.value=r:t.set(e,r)}(this,Lt,e,"f")}getSecret(){return function(e,t,r,n){if("a"===r&&!n)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===r?n:"a"===r?n.call(e):n?n.value:t.get(e)}(this,Lt,"f").call(this)}}Lt=new WeakMap;class Ht{constructor(e=new Map){this.items=e}add(e,t){this.items.set(e,t)}remove(e){if(!this.items.has(e))throw new Error("ItemManager.remove: not found item by id");const t=this.get(e);return this.items.delete(e),t}get(e){return this.items.get(e)??null}hasByFilter(e){return Array.from(this.items.values()).some(e)}has(e){return this.items.has(e)}getAll(){return Array.from(this.items.values())}getMap(){return this.items}clear(){this.items.clear()}}class Kt extends Ht{constructor(e=new Map,t=null){super(e),this.activeAccount=t??e.values().next().value??null}async create(e,t){const r=O(),n=await lt.create({id:r,...e},t);return this.add(r,n),this.activeAccount||(this.activeAccount=n),{account:n,accountId:r}}remove(e){const t=super.remove(e);return this.activeAccount=this.items.values().next().value??null,t}update(e,t){const r=this.get(e);r?r.update(t):console.error("Cannot update missing account")}setActiveAccount(e){const t=this.get(e);t?this.activeAccount=t:console.error("Cannot set active account")}getActiveAccount(){return this.activeAccount}getAccounts(){return this.getAll()}getAccountsMap(){return this.getMap()}getAccount(e){return this.get(e)}}let Vt=(()=>{var e;let t,r,n=[];return e=class{constructor({id:e,type:t,signer:r,accounts:a,activeAccount:i}){this.id=Re(this,n),this.id=e??O(),this.type=t,this.signer=r,this.accountManager=new Kt(a,i??null)}getId(){return this.id}getType(){return this.type}getSigner(){return this.signer}getAccounts(){return this.accountManager.getAccounts()}getAccountsMap(){return this.accountManager.getAccountsMap()}getActiveAccount(){return this.accountManager.getActiveAccount()}setActiveAccount(e){this.accountManager.setActiveAccount(e)}getDerivationIndex(e){const t=e.getIndex(),r=this.getAccounts().map(e=>e.getIndex()).filter(e=>null!==e).sort((e,t)=>e-t);if(!r.length)return t;let n=t+1;for(const e of r)if(e!==n){if(e>n)return n}else n++;return n}async deriveAccount(e,t){const r=await _t.decryptSignerData(this.signer.getEncryptedSecret(),t),n=new zt(()=>r),a=this.getDerivationIndex(r.rootHDPath);return this.accountManager.create({...e,index:a??void 0},n)}removeAccount(e){return this.accountManager.remove(e)}updateAccount(e,t){this.accountManager.update(e,t)}static async createPk(t,r){const n=await Bt({id:O(),type:exports.WalletTypes.PRIVATE_KEY,secretProvider:r}),a=await lt.create(t,new zt(()=>r.getSecret().secret)),i=new Map([[a.getId(),a]]);return new e({type:exports.WalletTypes.PRIVATE_KEY,signer:n,accounts:i,activeAccount:a})}static async createHD(t,r){const n=await Ne.getInitialHDPathFromOptions(t.pathOptions),a=new zt(()=>({secret:{rootHDPath:n.toString(),seed:t.mnemonic},password:r.getSecret().password})),i=await Bt({id:O(),type:exports.WalletTypes.HD,secretProvider:a}),s=new zt(()=>({rootHDPath:n,seed:t.mnemonic})),o=await lt.create(t.accountOptions,s),c=new Map([[o.getId(),o]]);return new e({type:exports.WalletTypes.HD,signer:i,accounts:c,activeAccount:o})}static async restore(t,r){const{signerRecord:n,accountRecords:a}=t,i=(({id:e,type:t,encryptedData:r})=>{switch(t){case exports.WalletTypes.PRIVATE_KEY:return new Ot({id:e,encryptedSecret:r});case exports.WalletTypes.HD:return new Rt({id:e,encryptedSecret:r})}})(n),s=await _t.decryptSignerData(i.getEncryptedSecret(),r),o=new zt(()=>s),c=new Map;for(const e of a){const t=await lt.create({id:e.id,name:e.name,index:e.index??void 0},o);c.set(t.getId(),t)}return new e({type:n.type,signer:i,accounts:c})}async transfer(e,t){return ct.getInstance().transactions.transfer({walletType:this.type,account:this.getActiveAccount(),signer:this.signer,details:e,passwordProvider:t})}},(()=>{const a="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;t=[pt],r=[wt],_e(e,null,t,{kind:"method",name:"deriveAccount",static:!1,private:!1,access:{has:e=>"deriveAccount"in e,get:e=>e.deriveAccount},metadata:a},null,n),_e(e,null,r,{kind:"method",name:"transfer",static:!1,private:!1,access:{has:e=>"transfer"in e,get:e=>e.transfer},metadata:a},null,n),a&&Object.defineProperty(e,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:a})})(),e})();const Wt="SIGNERS";class Ut{constructor(e){this.isInitialized=!1,this.initPromise=null,this.storageInterface=vt(e)}static getInstance(e){return Ut.instance||(Ut.instance=new Ut(e)),Ut.instance}async initialize(){if(!this.isInitialized){if(this.initPromise)return this.initPromise;this.initPromise=this.doInitialize();try{await this.initPromise}finally{this.initPromise=null}}}async doInitialize(){try{await this.storageInterface.tableExists(Wt)||await this.storageInterface.createTable(Wt,"id"),this.isInitialized=!0}catch(e){throw e}}async ensureInitialized(){this.isInitialized||await this.initialize()}getRawDB(){return this.storageInterface}async saveSigner(e,t,r){await this.ensureInitialized(),await this.storageInterface.insert(Wt,{id:e,type:t,encryptedData:r,createdAt:Date.now()})}async getSigner(e){return await this.ensureInitialized(),this.storageInterface.getById(Wt,e)}async getAllSigners(){return await this.ensureInitialized(),this.storageInterface.getAll(Wt)}async updateSigner(e,t){await this.ensureInitialized(),await this.storageInterface.update(Wt,e,t)}async deleteSigner(e){await this.ensureInitialized(),await this.storageInterface.delete(Wt,e)}async deleteMultipleSigners(e){await this.ensureInitialized(),await this.storageInterface.deleteMany(Wt,e)}async hasSigner(e){await this.ensureInitialized();return null!==await this.getSigner(e)}async getSignersCount(){await this.ensureInitialized();return(await this.getAllSigners()).length}async clearAllData(){await this.ensureInitialized(),await this.storageInterface.clearTable(Wt)}async clearTable(e){if(await this.ensureInitialized(),e!==Wt)throw new Error(`Invalid table name: ${e}`);await this.storageInterface.clearTable(e)}isReady(){return this.isInitialized}async getTablesList(){return await this.ensureInitialized(),[Wt]}close(){this.storageInterface.close(),this.isInitialized=!1}}const Ft="TRANSACTION_RESERVATIONS";class $t{constructor(e){this.isInitialized=!1,this.initPromise=null,this.storageInterface=vt(e)}static getInstance(e){return $t.instance||($t.instance=new $t(e)),$t.instance}async initialize(){if(!this.isInitialized){if(this.initPromise)return this.initPromise;this.initPromise=this.doInitialize();try{await this.initPromise}finally{this.initPromise=null}}}async doInitialize(){await this.storageInterface.tableExists(Ft)||await this.storageInterface.createTable(Ft,"id"),this.isInitialized=!0}async ensureInitialized(){this.isInitialized||await this.initialize()}getRawDB(){return this.storageInterface}async saveTransactionReservation(e,t,r,n){await this.ensureInitialized(),await this.storageInterface.insert(Ft,{id:e,networkName:t,signerId:r,encryptedData:n,createdAt:Date.now()})}async getTransactionReservations(e){return await this.ensureInitialized(),this.storageInterface.getById(Ft,e)}async getAllTransactionReservations(){return await this.ensureInitialized(),this.storageInterface.getAll(Ft)}async updateTransactionReservation(e,t){await this.ensureInitialized(),await this.storageInterface.update(Ft,e,t)}async deleteTransactionReservation(e){await this.ensureInitialized(),await this.storageInterface.delete(Ft,e)}async deleteMultipleTransactionReservations(e){await this.ensureInitialized(),await this.storageInterface.deleteMany(Ft,e)}async hasTransactionReservations(e){await this.ensureInitialized();return null!==await this.getTransactionReservations(e)}async getTransactionReservationsCount(){await this.ensureInitialized();return(await this.getAllTransactionReservations()).length}async clearAllData(){await this.ensureInitialized(),await this.storageInterface.clearTable(Ft)}async clearTable(e){if(await this.ensureInitialized(),e!==Ft)throw new Error(`Invalid table name: ${e}`);await this.storageInterface.clearTable(e)}isReady(){return this.isInitialized}async getTablesList(){return await this.ensureInitialized(),[Ft]}close(){this.storageInterface.close(),this.isInitialized=!1}}var jt;class Xt{}jt=Xt,Xt.init=async e=>{await Ut.getInstance(e).initialize(),await bt.getInstance(e).initialize(),await $t.getInstance(e).initialize()},Xt.saveSigner=async({id:e,type:t,signer:r})=>{await Ut.getInstance().saveSigner(e,t,r.getEncryptedSecret())},Xt.saveSigners=async e=>Promise.all(e.map(e=>Ut.getInstance().saveSigner(e.id,e.type,e.signer.getEncryptedSecret()))),Xt.getSigner=async e=>{const t=await Ut.getInstance().getSigner(e);if(!t)throw new Error("Signer with this id not found");return{id:t.id,type:t.type,encryptedData:t.encryptedData}},Xt.getSigners=async()=>Ut.getInstance().getAllSigners(),Xt.updateSigner=async(e,t)=>{await Ut.getInstance().updateSigner(e,t)},Xt.deleteSigner=async e=>{await Ut.getInstance().deleteSigner(e)},Xt.deleteMultipleSigners=async e=>{await Ut.getInstance().deleteMultipleSigners(e)},Xt.saveAccount=async({id:e,account:t,signerId:r})=>{await bt.getInstance().saveAccount(e,r,t.getName(),t.getIndex())},Xt.saveAccounts=async e=>{const t=e.map(({id:e,account:t,signerId:r})=>({id:e,signerId:r,name:t.getName(),index:t.getIndex(),createdAt:Date.now()}));await bt.getInstance().saveAccounts(t)},Xt.getAccount=async e=>{const t=await bt.getInstance().getAccount(e);if(!t)throw new Error("Account with this id not found");return t},Xt.getAccounts=async()=>bt.getInstance().getAllAccounts(),Xt.updateAccount=async(e,t)=>{await bt.getInstance().updateAccount(e,t)},Xt.deleteAccount=async e=>{await bt.getInstance().deleteAccount(e)},Xt.deleteMultipleAccounts=async e=>{await bt.getInstance().deleteMultipleAccounts(e)},Xt.saveWallet=async({signerId:e,wallet:t})=>{const r=t.getSigner();await jt.saveSigner({id:e,type:t.getType(),signer:r}),await jt.saveAccounts(Array.from(t.getAccountsMap()).map(([t,r])=>({id:t,account:r,signerId:e})))},Xt.saveWallets=async e=>Promise.all(e.map(e=>jt.saveWallet(e))),Xt.getWallet=async({signerId:e,passwordProvider:t})=>{const r=await jt.getSigner(e),n=(await jt.getAccounts()).filter(t=>t.signerId===e);return Vt.restore({signerRecord:r,accountRecords:n},t)},Xt.getWallets=async()=>{const e=await jt.getSigners(),t=await jt.getAccounts();return e.map(e=>({signer:e,accounts:t.filter(t=>t.signerId===e.id)}))},Xt.saveTransactionReservation=async({id:e,networkName:t,signerId:r,encryptedData:n})=>{await $t.getInstance().saveTransactionReservation(e,t,r,n)},Xt.getTransactionReservationsBySignerId=async(e,t)=>(await $t.getInstance().getAllTransactionReservations()).filter(r=>r.signerId===e&&r.networkName===t),Xt.updateTransactionReservation=async(e,t)=>{await $t.getInstance().updateTransactionReservation(e,t)},Xt.deleteTransactionReservation=async e=>{await $t.getInstance().deleteTransactionReservation(e)},Xt.deleteMultipleTransactionReservations=async e=>{await $t.getInstance().deleteMultipleTransactionReservations(e)},Xt.clear=async()=>{await Ut.getInstance().clearAllData(),await bt.getInstance().clearAllData(),await $t.getInstance().clearAllData()},Xt.close=()=>{Ut.getInstance().close(),bt.getInstance().close(),$t.getInstance().close()};class Gt extends Ht{async createHD({mnemonic:e,accountName:t,index:r},n){const a=await Vt.createHD({mnemonic:e,pathOptions:{index:r??0},accountOptions:{name:t}},n);return await this.persist(a),a}async createPrivateKey(e,t){const r=await Vt.createPk({name:e},t);return await this.persist(r),r}async unlock(e,t){const r=await Xt.getWallet({signerId:e,passwordProvider:t});return this.add(r.getId(),r),r}async delete(e){const t=super.remove(e),r=Array.from(t.getAccountsMap().keys());return r.length&&await Xt.deleteMultipleAccounts(r),await Xt.deleteSigner(t.getSigner().getId()),t}async deriveAccount(e,t,r){const n=this.get(e);if(!n)throw new Error("WalletManager.deriveAccount: unknown wallet id");const a=n.getSigner().getId(),{account:i,accountId:s}=await n.deriveAccount({name:t},r);return await Xt.saveAccount({id:s,account:i,signerId:a}),{accountId:s,account:i}}async removeAccount(e,t){const r=this.get(e);if(!r)throw new Error("WalletManager.removeAccount: unknown wallet id");const n=r.removeAccount(t);return await Xt.deleteAccount(t),n}async renameAccount(e,t,r){const n=this.get(e);if(!n)throw new Error("WalletManager.renameAccount: unknown wallet id");n.updateAccount(t,{name:r}),await Xt.updateAccount(t,{name:r})}setActiveAccount(e,t){const r=this.get(e);if(!r)throw new Error("WalletManager.setActiveAccount: unknown wallet id");r.setActiveAccount(t)}async getPublicWalletsMetadata(){return(await Xt.getWallets()).map(({signer:e,accounts:t})=>({signerId:e.id,type:e.type,accounts:t.map(e=>({id:e.id,name:e.name,index:e.index}))}))}async count(){return this.items.size}async countInStorage(){return(await Xt.getSigners()).length}async persist(e){await Xt.saveWallet({signerId:e.getSigner().getId(),wallet:e}),this.add(e.getId(),e)}}class Yt{constructor(e,t={}){this.reservations=new Map,this.watchers=new Map,this.expirationTimers=new Map,this.onConfirmed=t.onConfirmed,this.onExpired=t.onExpired,this.onFailed=t.onFailed,this.watchCallbacks=t.watchCallbacks,this.watchOptions={...t.watchOptions,timeoutMs:t.watchOptions?.timeoutMs??v};for(const t of e)this.track(t)}add(e){this.track(e)}remove(e){return this.stopWatch(e),this.clearExpiration(e),this.reservations.delete(e)}get(e){return this.reservations.get(e)??null}getAll(){return Array.from(this.reservations.values())}getByAccountAddress(e){return this.getAll().filter(t=>t.accountAddress===e)}dispose(){for(const e of Array.from(this.watchers.keys()))this.stopWatch(e);for(const e of Array.from(this.expirationTimers.keys()))this.clearExpiration(e);this.reservations.clear()}track(e){this.reservations.set(e.id,e),this.watch(e),this.scheduleExpiration(e)}watch(e){if(!e.deployId)return;const t=ct.getInstance().poller.watch(e.deployId,{...this.watchCallbacks,onConfirmed:t=>{this.watchCallbacks?.onConfirmed?.(t),this.handleConfirmed(e)},onError:t=>{this.watchCallbacks?.onError?.(t),this.handleFailed(e,t)}},this.watchOptions);this.watchers.set(e.id,t)}scheduleExpiration(e){const t=e.expirationTime-Date.now();if(t<=0)return void this.handleExpired(e);const r=setTimeout(()=>this.handleExpired(e),t);this.expirationTimers.set(e.id,r)}stopWatch(e){this.watchers.get(e)?.cancel(),this.watchers.delete(e)}clearExpiration(e){const t=this.expirationTimers.get(e);t&&(clearTimeout(t),this.expirationTimers.delete(e))}handleConfirmed(e){this.stopWatch(e.id),this.clearExpiration(e.id),this.reservations.delete(e.id),this.onConfirmed?.(e)}handleExpired(e){this.stopWatch(e.id),this.clearExpiration(e.id),this.reservations.delete(e.id),this.onExpired?.(e)}handleFailed(e,t){this.stopWatch(e.id),this.clearExpiration(e.id),this.reservations.delete(e.id),this.onFailed?.(e,t)}}class qt{constructor(e,t){const r=e=>{Xt.deleteTransactionReservation(e.id).catch(e=>console.error("ReservationAdapter: failed to delete released reservation:",e))};this.reservationsManager=new Yt(e,{onConfirmed:r,onExpired:r,...t})}static async create(e,t,r){const n=Xe.getInstance().getNetwork(),a=e.getSigner().getId(),i=await Xt.getTransactionReservationsBySignerId(a,n),s=t.getSecret().password,o=[];for(const e of i){const t=await _t.decryptWithPassword(e.encryptedData,s),r=JSON.parse(t);r.expirationTime<=Date.now()?await Xt.deleteTransactionReservation(e.id):o.push({id:e.id,networkName:e.networkName,timestamp:new Date(r.timestamp),accountAddress:r.accountAddress,pendingAmount:r.pendingAmount,deployId:r.deployId,expirationTime:r.expirationTime})}return new qt(o,r)}getReservedAmount(e){const t=this.reservationsManager.getByAccountAddress(e);return t.reduce((e,t)=>e+BigInt(t.pendingAmount),0n)+BigInt(t.length)*I.MAX}async getBalance(e){const t=await e.getBalance(),r=this.getReservedAmount(e.getAddress());return{...t,amount:t.amount-r}}getReservations(){return this.reservationsManager.getAll()}dispose(){this.reservationsManager.dispose()}async persistReservation(e,t,r){const n=r.getSecret().password,a={timestamp:e.timestamp,accountAddress:e.accountAddress,pendingAmount:e.pendingAmount,deployId:e.deployId,expirationTime:e.expirationTime},i=await _t.encryptWithPassword(JSON.stringify(a),n);await Xt.saveTransactionReservation({id:e.id,networkName:e.networkName,signerId:t.getSigner().getId(),encryptedData:i})}async validateSufficientBalance(e,t){const r=this.getReservedAmount(e.getAddress())+t;return(await e.getBalance()).amount-r>0n}async transfer(e,t,r){const n=e.getActiveAccount();if(!await this.validateSufficientBalance(n,t.amount))throw new Error("ReservationAdapter.transfer: Insufficient balance");const a=await e.transfer(t,r),i={id:O(),deployId:a,timestamp:new Date,accountAddress:n.getAddress(),pendingAmount:t.amount.toString(),networkName:Xe.getInstance().getNetwork(),expirationTime:Date.now()+A};return await this.persistReservation(i,e,r),this.reservationsManager.add(i),a}}class Jt extends Ht{add(e,t){this.get(e)?.dispose(),super.add(e,t)}remove(e){return this.get(e)?.dispose(),super.remove(e)}clear(){for(const e of this.getAll())e.dispose();super.clear()}}class Zt extends Jt{async create(e,t){const r=await qt.create(e,t);return super.add(e.getId(),r),r}}const Qt="INSENSITIVE_CACHE";class er{constructor(){this.isInitialized=!1,this.initPromise=null,this.storageInterface=vt()}static getInstance(){return er.instance||(er.instance=new er),er.instance}async initialize(){if(!this.isInitialized){if(this.initPromise)return this.initPromise;this.initPromise=this.doInitialize();try{await this.initPromise}finally{this.initPromise=null}}}async doInitialize(){await this.storageInterface.tableExists(Qt)||await this.storageInterface.createTable(Qt,"id"),this.isInitialized=!0}async ensureInitialized(){this.isInitialized||await this.initialize()}async saveRecord(e){await this.ensureInitialized(),await this.storageInterface.insert(Qt,e)}async getRecord(e){return await this.ensureInitialized(),this.storageInterface.getById(Qt,e)}async getAllRecords(){return await this.ensureInitialized(),this.storageInterface.getAll(Qt)}async updateRecord(e,t){await this.ensureInitialized(),await this.storageInterface.update(Qt,e,t)}async deleteRecord(e){await this.ensureInitialized(),await this.storageInterface.delete(Qt,e)}async clear(){await this.ensureInitialized(),await this.storageInterface.clearTable(Qt)}close(){this.storageInterface.close(),this.isInitialized=!1}}var tr;class rr{}tr=rr,rr.init=async()=>{await er.getInstance().initialize()},rr.save=async e=>{await er.getInstance().saveRecord(e)},rr.get=async e=>er.getInstance().getRecord(e),rr.getAll=async()=>er.getInstance().getAllRecords(),rr.update=async(e,t)=>{await er.getInstance().updateRecord(e,t)},rr.delete=async e=>{await er.getInstance().deleteRecord(e)},rr.deleteAll=async e=>{for(const t of e)await tr.delete(t)},rr.clear=async()=>{await er.getInstance().clear()},rr.close=()=>{er.getInstance().close()};class nr{}nr.serialize=e=>({id:e.getId(),address:e.getAddress()});let ar=(()=>{var e;let t,r=[];return e=class{constructor({walletsMap:e,reservationAdaptersMap:t,eventDispatcher:n,flags:a}){this.walletManager=Re(this,r),this.walletManager=new Gt(e),this.reservationAdapterManager=new Zt(t),this.eventDispatcher=n,this.flags=a}static async create({networksConfig:t,defaultNetwork:r,storageOptions:n,eventDispatcher:a,flags:i}){return await Xt.init(n),Xe.getInstance().initialize(t,r),ct.getInstance(),i?.withInsensitiveCacheStorage&&await rr.init(),new e({eventDispatcher:a,flags:i})}getWalletManager(){return this.walletManager}getInsensitiveAccountsData(){return rr.getAll()}async clearPersistence(){this.walletManager.clear(),this.reservationAdapterManager.clear(),await Xt.clear(),await this.emitWalletsChanged()}close(){this.walletManager.clear(),this.reservationAdapterManager.clear(),Xt.close(),Xe.getInstance().close()}generateMnemonic(e=exports.MnemonicStrength.TWELVE_WORDS){return ne.generateMnemonic(e)}generatePrivateKey(){return Ne.generateKeyPair().privateKey}async createHDWallet({mnemonic:e,accountName:t,index:r},n){const a=this.createPasswordProvider(n),i=await this.walletManager.createHD({mnemonic:e,accountName:t,index:r},a);return await this.reservationAdapterManager.create(i,a),await this.emitWalletsChanged(),this.flags?.withInsensitiveCacheStorage&&rr.save(nr.serialize(i.getActiveAccount())),i}async createPrivateKeyWallet({privateKey:e,accountName:t},r){const n=new zt(()=>({password:r,secret:{privateKey:e}})),a=await this.walletManager.createPrivateKey(t,n);return await this.reservationAdapterManager.create(a,n),await this.emitWalletsChanged(),this.flags?.withInsensitiveCacheStorage&&rr.save(nr.serialize(a.getActiveAccount())),a}async removeWallet(e){const t=await this.walletManager.delete(e);this.reservationAdapterManager.remove(e),this.flags?.withInsensitiveCacheStorage&&rr.deleteAll(Array.from(t.getAccountsMap().keys())),await this.emitWalletsChanged()}async unlockWallet(e,t){if(this.walletManager.hasByFilter(t=>t.getSigner().getId()===e))throw new Error("Client.unlockWallet: This wallet already unlocked");const r=this.createPasswordProvider(t),n=await this.walletManager.unlock(e,r);return await this.reservationAdapterManager.create(n,r),n}async deriveAccount(e,t,r){const n=this.createPasswordProvider(r),a=await this.walletManager.deriveAccount(e,t,n);return this.emitAccountsChanged(e),this.flags?.withInsensitiveCacheStorage&&rr.save(nr.serialize(a.account)),a}async removeAccount(e,t){const r=await this.walletManager.removeAccount(e,t);this.flags?.withInsensitiveCacheStorage&&rr.delete(r.getId()),this.emitAccountsChanged(e)}async renameAccount(e,t,r){await this.walletManager.renameAccount(e,t,r),this.emitAccountsChanged(e)}setActiveAccount(e,t){this.walletManager.setActiveAccount(e,t)}getNetworksNames(){return Xe.getInstance().getNetworkNames()}getCurrentNetwork(){return Xe.getInstance().getNetwork()}setNetwork(e){Xe.getInstance().switchNetwork(e),this.eventDispatcher?.onNetworkChanged?.(e)}async getBalance(e){return(await ct.getInstance().assets.getBalance(e,te)).amount}async getAvailableBalance(e,t){const r=this.getUnlockedWallet(e),n=this.getAccount(r,t),a=this.reservationAdapterManager.get(e);if(!a)throw new Error("Client.getAvailableBalance: Not found reservation adapter");return(await a.getBalance(n)).amount}async getReservations(e){const t=this.reservationAdapterManager.get(e);if(!t)throw new Error("Client.getReservations: Not found reservation adapter");return t.getReservations()}async transfer({walletId:e,accountId:t,to:r,amount:n},a){const i=this.getUnlockedWallet(e);i.setActiveAccount(t);const s=this.createPasswordProvider(a),o=this.reservationAdapterManager.get(e);if(!o)throw new Error("Client.transfer: Not found reservation adapter");const c=await o.transfer(i,{to:r,amount:n,asset:te},s);return this.eventDispatcher?.onReservationsChanged?.(e,o.getReservations()),c}toDisplayAmount(e){return W(e,8)}toAtomicAmount(e){return K(e,8)}getUnlockedWallet(e){const t=this.walletManager.get(e);if(!t)throw new Error(`Wallet ${e} is not unlocked`);return t}getAccount(e,t){const r=e.getAccountsMap().get(t);if(!r)throw new Error(`Account ${t} not found`);return r}createPasswordProvider(e){return new zt(()=>({password:e}))}emitAccountsChanged(e){if(!this.eventDispatcher?.onAccountsChanged)return;const t=this.walletManager.get(e);t&&this.eventDispatcher.onAccountsChanged(e,t.getAccounts())}async emitWalletsChanged(){this.eventDispatcher?.onWalletsChanged&&this.eventDispatcher.onWalletsChanged(this.walletManager.getAll())}},(()=>{const n="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;t=[yt],_e(e,null,t,{kind:"method",name:"getInsensitiveAccountsData",static:!1,private:!1,access:{has:e=>"getInsensitiveAccountsData"in e,get:e=>e.getInsensitiveAccountsData},metadata:n},null,r),n&&Object.defineProperty(e,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:n})})(),e})();exports.ACCOUNTS_DATA_KEY=At,exports.ASI_BASE_UNIT=E,exports.ASI_CHAIN_PREFIX=b,exports.ASI_COIN_TYPE=60,exports.ASI_DECIMALS=8,exports.Account=lt,exports.AccountDataService=Ge,exports.AccountManager=Kt,exports.AccountsStorageRepository=bt,exports.ApiClientManager=Xe,exports.ApiServiceRegistry=ct,exports.Asset=ee,exports.AssetsService=qe,exports.BaseGraphQLClient=Oe,exports.BaseHttpClient=Ve,exports.BinaryWriter=rt,exports.Bip44Path=ae,exports.BlockService=Je,exports.BrowserStorage=ft,exports.Client=ar,exports.Crypto=_t,exports.DEFAULT_ASSET=te,exports.DEFAULT_BIP_44_PATH_OPTIONS=x,exports.DEFAULT_NODE_STORAGE_DIR=m,exports.DEFAULT_PHLO_LIMIT=f,exports.DEFAULT_PHLO_PRICE=1,exports.DEPLOY_STATUS_POLLING_TIMEOUT=v,exports.DeployService=Qe,exports.DeployStatusPoller=et,exports.DisposableItemManager=Jt,exports.FAULT_TOLERANCE_THRESHOLD=.99,exports.GasFee=I,exports.HEX_BYTE_PADDING=64,exports.HEX_RADIX=16,exports.INVALID_BLOCK_NUMBER=-1,exports.IndexerClient=Ke,exports.ItemManager=Ht,exports.KeyDerivation=Se,exports.KeysManager=Ne,exports.Mnemonic=ne,exports.NATIVE_TOKEN_DECIMALS_AMOUNT=8,exports.NetworkConfigProvider=Fe,exports.NodeStorage=It,exports.ObserverClient=We,exports.POWER_BASE=10,exports.PRIVATE_KEY_LENGTH=32,exports.RESERVATION_EXPIRATION_TIME=A,exports.ReservationAdapterManager=Zt,exports.SIGNERS_DATA_KEY=Wt,exports.SecretsProvider=zt,exports.Signer=it,exports.SignerService=nt,exports.SignersStorageRepository=Ut,exports.StorageManager=Xt,exports.TRANSACTION_RESERVATIONS_DATA_KEY=Ft,exports.TransactionReservationsStorageRepository=$t,exports.TransactionService=ot,exports.ValidatorClient=Ue,exports.Wallet=Vt,exports.WalletManager=Gt,exports.Wallets=Me,exports.arrayBufferToBase64=P,exports.base64ToArrayBuffer=k,exports.bigIntToBuffer=_,exports.bufferToBigInt=M,exports.buildUrl=F,exports.decodeBase16=D,exports.decodeBase58=C,exports.encodeBase16=N,exports.encodeBase58=S,exports.fromAtomicAmount=W,exports.fromAtomicAmountToNumber=(e,t)=>{const r=BigInt(10)**BigInt(t),n=e/r,a=e%r;return n>BigInt(Number.MAX_SAFE_INTEGER)?(console.warn("Integer part exceeds Number.MAX_SAFE_INTEGER; returning imprecise Number"),Number(V(e,t))):Number(n)+Number(a)/Number(r)},exports.genRandomHex=R,exports.generateRandomId=O,exports.isAddress=e=>Q(e).isValid,exports.normalizeAddress=$,exports.setupBufferPolyfill=T,exports.toAtomicAmount=K,exports.toUint8Array=U,exports.validateAccountName=(e,t=30)=>e&&0!==e.trim().length?e.length>t?{isValid:!1,error:`Account name must be ${t} characters or less`}:X.test(e)?{isValid:!1,error:"Account name contains invalid characters"}:{isValid:!0}:{isValid:!1,error:"Account name is required"},exports.validateAddress=Q;
3
4
  //# sourceMappingURL=index.cjs.map