@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/README.md +148 -121
- package/dist/index.cjs +3 -2
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.ts +950 -368
- package/dist/index.esm.js +3 -2
- package/dist/index.esm.js.map +1 -1
- package/package.json +8 -2
package/dist/index.esm.js
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
-
import e from"bs58";import
|
|
2
|
-
/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */function Z(e){if(!Number.isSafeInteger(e)||e<0)throw new Error("positive integer expected, got "+e)}function q(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 Q(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 ee(...e){for(let t=0;t<e.length;t++)e[t].fill(0)}function te(e){return new DataView(e.buffer,e.byteOffset,e.byteLength)}function re(e,t){return e<<32-t|e>>>t}function ne(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)),q(e),e}class se{}function ie(e){const t=t=>e().update(ne(t)).digest(),r=e();return t.outputLen=r.outputLen,t.blockLen=r.blockLen,t.create=()=>e(),t}function ae(e,t,r){return e&t^~e&r}function oe(e,t,r){return e&t^e&r^t&r}class ce extends se{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=te(this.buffer)}update(e){Q(this),q(e=ne(e));const{view:t,buffer:r,blockLen:n}=this,s=e.length;for(let i=0;i<s;){const a=Math.min(n-this.pos,s-i);if(a===n){const t=te(e);for(;n<=s-i;i+=n)this.process(t,i);continue}r.set(e.subarray(i,i+a),this.pos),this.pos+=a,i+=a,this.pos===n&&(this.process(t,0),this.pos=0)}return this.length+=e.length,this.roundClean(),this}digestInto(e){Q(this),function(e,t){q(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:s}=this;let{pos:i}=this;t[i++]=128,ee(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 s=BigInt(32),i=BigInt(4294967295),a=Number(r>>s&i),o=Number(r&i),c=n?4:0,l=n?0:4;e.setUint32(t+c,a,n),e.setUint32(t+l,o,n)}(r,n-8,BigInt(8*this.length),s),this.process(r,0);const a=te(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++)a.setUint32(4*e,l[e],s)}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:s,destroyed:i,pos:a}=this;return e.destroyed=i,e.finished=s,e.length=n,e.pos=a,n%t&&e.buffer.set(r),e}clone(){return this._cloneInto()}}const le=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),de=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]),ue=new Uint32Array(64);class he extends ce{constructor(e=32){super(64,e,8,!1),this.A=0|le[0],this.B=0|le[1],this.C=0|le[2],this.D=0|le[3],this.E=0|le[4],this.F=0|le[5],this.G=0|le[6],this.H=0|le[7]}get(){const{A:e,B:t,C:r,D:n,E:s,F:i,G:a,H:o}=this;return[e,t,r,n,s,i,a,o]}set(e,t,r,n,s,i,a,o){this.A=0|e,this.B=0|t,this.C=0|r,this.D=0|n,this.E=0|s,this.F=0|i,this.G=0|a,this.H=0|o}process(e,t){for(let r=0;r<16;r++,t+=4)ue[r]=e.getUint32(t,!1);for(let e=16;e<64;e++){const t=ue[e-15],r=ue[e-2],n=re(t,7)^re(t,18)^t>>>3,s=re(r,17)^re(r,19)^r>>>10;ue[e]=s+ue[e-7]+n+ue[e-16]|0}let{A:r,B:n,C:s,D:i,E:a,F:o,G:c,H:l}=this;for(let e=0;e<64;e++){const t=l+(re(a,6)^re(a,11)^re(a,25))+ae(a,o,c)+de[e]+ue[e]|0,d=(re(r,2)^re(r,13)^re(r,22))+oe(r,n,s)|0;l=c,c=o,o=a,a=i+t|0,i=s,s=n,n=r,r=t+d|0}r=r+this.A|0,n=n+this.B|0,s=s+this.C|0,i=i+this.D|0,a=a+this.E|0,o=o+this.F|0,c=c+this.G|0,l=l+this.H|0,this.set(r,n,s,i,a,o,c,l)}roundClean(){ee(ue)}destroy(){this.set(0,0,0,0,0,0,0,0),ee(this.buffer)}}const ye=ie(()=>new he);class pe extends se{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");Z(e.outputLen),Z(e.blockLen)}(e);const r=ne(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,s=new Uint8Array(n);s.set(r.length>n?e.create().update(r).digest():r);for(let e=0;e<s.length;e++)s[e]^=54;this.iHash.update(s),this.oHash=e.create();for(let e=0;e<s.length;e++)s[e]^=106;this.oHash.update(s),ee(s)}update(e){return Q(this),this.iHash.update(e),this}digestInto(e){Q(this),q(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:s,blockLen:i,outputLen:a}=this;return e.finished=n,e.destroyed=s,e.blockLen=i,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 fe=(e,t,r)=>new pe(e,t).update(r).digest();fe.create=(e,t)=>new pe(e,t),s.hmacSha256Sync=(e,...t)=>fe(ye,e,s.concatBytes(...t));const ge=i.n,me={isPoint(e){try{return a.fromHex(e),!0}catch{return!1}},isPrivate(e){if(32!==e.length)return!1;const t=U(e);return t>0n&&t<ge},pointFromScalar(e,t=!0){try{return o(e,t)}catch{return null}},pointAddScalar(e,t,r=!0){try{const n=a.fromHex(e),s=U(t),i=a.BASE.multiply(s);return n.add(i).toRawBytes(r)}catch{return null}},privateAdd(e,t){const r=(U(e)+U(t))%ge;return 0n===r?null:B(r)},privateNegate(e){const t=U(e);return B((ge-t)%ge)},sign:(e,t)=>c(e,t,{der:!1}),verify:(e,t,r)=>l(r,e,t)};j();class we{static buildBip44Path({coinType:e=60,account:t=0,change:r=0,index:n=0}){return`m/44'/${e}'/${t}'/${r}/${n}`}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,t=""){return"string"==typeof e?await r(e,t):await r(X.wordArrayToMnemonic(e),t)}static seedToMasterNode(e){return u(me).fromSeed(e)}static async deriveKeyFromMnemonic(e,t=R){const r=this.buildBip44Path(t),n=await we.mnemonicToSeed(e),s=we.seedToMasterNode(n);return we.derivePrivateKey(s,r)}static async deriveNextKeyFromMnemonic(e,t,r=R){const n=t+1;return await this.deriveKeyFromMnemonic(e,{...r,index:n})}}const{randomBytes:Ee,bytesToHex:Ie}=s;class Ne{static generateRandomKey(e=32){if(!e||e<0||!Number.isInteger(e))throw new Error("PrivateKeyLength must be a positive integer");return Ee(e)}static generateKeyPair(e=32){if(!e||e<0||!Number.isInteger(e))throw new Error("PrivateKeyLength must be a positive integer");const t=Ee(e);return{privateKey:t,publicKey:o(t)}}static getKeyPairFromPrivateKey(e){return{privateKey:e,publicKey:o(e)}}static getPublicKeyFromPrivateKey(e){return o(e)}static convertKeyToHex(e){return Ie(e)}static async deriveKeyFromMnemonic(e,t){return await we.deriveKeyFromMnemonic(e,t)}static generateMpcKeyPair(){throw new Error("MPC key generation is not implemented yet.")}}const{blake2bHex:Ae}=h,{keccak256:ve}=y;class be{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 createWalletFromMnemonic(e,t){const r=e?X.mnemonicToWordArray(e):X.generateMnemonicArray(),n=X.wordArrayToMnemonic(r);if(!n||!X.isMnemonicValid(n))throw new Error("WalletsService.createWalletFromMnemonic: Recovery mnemonic is missing or invalid");const s=await we.mnemonicToSeed(r),i=we.seedToMasterNode(s),a=we.buildBip44Path({coinType:60,account:0,change:0,index:t||0}),o=we.derivePrivateKey(i,a);return{...this.createWallet(o),mnemonic:n}}static deriveAddressFromPrivateKey(e){const t=Ne.getKeyPairFromPrivateKey(e);return this.deriveAddressFromPublicKey(t.publicKey)}static deriveAddressFromPublicKey(e){const t=ve(e.slice(1)),r=C(t.slice(-40)),n=ve(r),s=`${g.coinId}${g.version}${n}`,i=C(s),a=Ae(i,void 0,32).slice(0,8);return _(`${s}${a}`)}}function Se(e,t,r,n,s,i){function a(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,y=r.length-1;y>=0;y--){var p={};for(var f in n)p[f]="access"===f?{}:n[f];for(var f in n.access)p.access[f]=n.access[f];p.addInitializer=function(e){if(h)throw new TypeError("Cannot add initializers after decoration has completed");i.push(a(e||null))};var g=(0,r[y])("accessor"===c?{get:u.get,set:u.set}:u[l],p);if("accessor"===c){if(void 0===g)continue;if(null===g||"object"!=typeof g)throw new TypeError("Object expected");(o=a(g.get))&&(u.get=o),(o=a(g.set))&&(u.set=o),(o=a(g.init))&&s.unshift(o)}else(o=a(g))&&("field"===c?s.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,s=0;s<t.length;s++)r=n?t[s].call(e,r):t[s].call(e);return n?r:void 0}var Le,De;"function"==typeof SuppressedError&&SuppressedError,function(e){e.READ_ONLY_NODE="READ_ONLY_NODE",e.CASPER_INSTANCE_UNAVAILABLE="CASPER_INSTANCE_UNAVAILABLE",e.INVALID_DEPLOY_ID="INVALID_DEPLOY_ID",e.INVALID_BLOCK_NUMBER="INVALID_BLOCK_NUMBER"}(Le||(Le={})),function(e){e.INSUFFICIENT_BALANCE="INSUFFICIENT_BALANCE",e.WRONG_NETWORK="WRONG_NETWORK",e.PARSING_ERROR="PARSING_ERROR",e.LOW_PHLO_PRICE="LOW_PHLO_PRICE",e.SIGNATURE_ERROR="SIGNATURE_ERROR",e.STORAGE_RETRIEVAL_ERROR="STORAGE_RETRIEVAL_ERROR",e.UNKNOWN_ERROR="UNKNOWN_ERROR",e.DEPLOY_SUBMIT_TIMEOUT="DEPLOY_SUBMIT_TIMEOUT",e.BLOCK_INCLUSION_TIMEOUT="BLOCK_INCLUSION_TIMEOUT",e.FINALIZATION_TIMEOUT="FINALIZATION_TIMEOUT"}(De||(De={}));const _e={[Le.READ_ONLY_NODE]:"Node is read-only. Trying another node...",[Le.CASPER_INSTANCE_UNAVAILABLE]:"Casper instance not available. Trying another node...",[Le.INVALID_DEPLOY_ID]:"Invalid deploy ID. Please try again.",[Le.INVALID_BLOCK_NUMBER]:"Invalid block number. Please try again.",[De.INSUFFICIENT_BALANCE]:"Insufficient balance. Please top up your account.",[De.WRONG_NETWORK]:"Wrong network. Please contact technical support.",[De.PARSING_ERROR]:"Parsing error. Please contact technical support.",[De.LOW_PHLO_PRICE]:"Phlo price too low. Please rebuild the transaction with a higher phlo price.",[De.SIGNATURE_ERROR]:"Signature verification failed. Please try again.",[De.STORAGE_RETRIEVAL_ERROR]:"Storage retrieval error. Please try again later.",[De.UNKNOWN_ERROR]:"An unknown error occurred. Please try again.",[De.DEPLOY_SUBMIT_TIMEOUT]:"Deploy submission timed out. Please try again.",[De.BLOCK_INCLUSION_TIMEOUT]:"Deploy was not included in a block within the expected time.",[De.FINALIZATION_TIMEOUT]:"Block finalization polling timed out."};function Oe(e){return _e[e]??"An unknown error occurred. Please try again."}function Ce(e,t){return function(...t){return"string"==typeof t[0]&&(t[0]=t[0].toLowerCase()),e.apply(this,t)}}let ke=(()=>{var e;let t,r,n=[];return e=class{parseDeploymentError(e){return e.includes("read only")?Le.READ_ONLY_NODE:e.includes("casper instance")?Le.CASPER_INSTANCE_UNAVAILABLE:e.includes("invalid deploy ID")?Le.INVALID_DEPLOY_ID:e.includes("invalid block number")?Le.INVALID_BLOCK_NUMBER:e.includes("insufficient balance")?De.INSUFFICIENT_BALANCE:e.includes("wrong network")?De.WRONG_NETWORK:e.includes("parsing error")?De.PARSING_ERROR:e.includes("low")&&e.includes("phlo")?De.LOW_PHLO_PRICE:e.includes("signature")||e.includes("sign")||e.includes("invalid signature")?De.SIGNATURE_ERROR:e.includes("storage")||e.includes("retrieval")?De.STORAGE_RETRIEVAL_ERROR:De.UNKNOWN_ERROR}isDeploymentErrorRecoverable(e){return Object.values(Le).includes(e)}isDeploymentErrorFatal(e){return Object.values(De).includes(e)}isPollingErrorRecoverable(e){return e.includes("casper instance")||e.includes("storage")||e.includes("parsing")}getErrorMessageByErrorType(e){return _e[e]??_e[De.UNKNOWN_ERROR]}constructor(){Re(this,n)}},(()=>{const s="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;t=[Ce],r=[Ce],Se(e,null,t,{kind:"method",name:"parseDeploymentError",static:!1,private:!1,access:{has:e=>"parseDeploymentError"in e,get:e=>e.parseDeploymentError},metadata:s},null,n),Se(e,null,r,{kind:"method",name:"isPollingErrorRecoverable",static:!1,private:!1,access:{has:e=>"isPollingErrorRecoverable"in e,get:e=>e.isPollingErrorRecoverable},metadata:s},null,n),s&&Object.defineProperty(e,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:s})})(),e})();class Te{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 Pe,Ue;!function(e){e.DEPLOYING="Deploying",e.INCLUDED_IN_BLOCK="IncludedInBlock",e.FINALIZED="Finalized",e.CHECK_ERROR="CheckingError"}(Pe||(Pe={}));class Be{constructor(e,t){this.validatorClient=e,this.indexerClient=t}static createHttpClient(e){const t=p.create({baseURL:e.baseUrl,...e.axiosConfig});return new Te(t)}changeValidator(e){return this.validatorClient=Be.createHttpClient(e),this}changeIndexer(e){return this.indexerClient=Be.createHttpClient(e),this}static init(e){return Be.instance=new Be(this.createHttpClient(e.validator),this.createHttpClient(e.indexer)),Be.instance}static isInitialized(){return void 0!==Be?.instance}static getInstance(){if(!Be.isInitialized())throw new Error("BlockchainGateway is not initialized. Call BlockchainGateway.init() first.");return Be.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:Pe.DEPLOYING};return{status:await this.isDeployFinalized(t)?Pe.FINALIZED:Pe.INCLUDED_IN_BLOCK}}catch(e){const t="BlockchainGateway.getDeployStatus: "+this.getGatewayErrorMessage(e);return{status:Pe.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(p.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]}}!function(e){e.LOCAL="local",e.MPC="mpc"}(Ue||(Ue={}));const Ve={mode:Ue.LOCAL},Ke=3e4,xe=20,Me=8,We=5e5,He={phloPrice:1,useRandomNode:!0,deployValiditySeconds:80,nodeSelectionAttempts:3,deployRetries:3,deployIntervalSeconds:5,pollingIntervalSeconds:3};function Fe(e,t){return function(...r){if(!Be.isInitialized())throw new Error(`${t.kind} ${String(t.name)}: BlockchainGateway is not initialized. Call BlockchainGateway.init() first.`);return e.apply(this,r)}}let Ge=(()=>{var e;let t,r,n=[];return e=class{constructor(e,t,r){if(this.retriesLeft=Re(this,n),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=He.nodeSelectionAttempts,n=He.useRandomNode){const s=n?Math.max(1,r):0,i=new e(t,s,n);return e.instance=i,i}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){Be.getInstance().getValidatorClientUrl()!==e&&Be.getInstance().changeValidator({baseUrl:e});if(!await Be.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 s="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;t=[Fe],r=[Fe],Se(e,null,t,{kind:"method",name:"connectDefaultNode",static:!1,private:!1,access:{has:e=>"connectDefaultNode"in e,get:e=>e.connectDefaultNode},metadata:s},null,n),Se(e,null,r,{kind:"method",name:"connectActiveRandomNode",static:!1,private:!1,access:{has:e=>"connectActiveRandomNode"in e,get:e=>e.connectActiveRandomNode},metadata:s},null,n),s&&Object.defineProperty(e,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:s})})(),e})();const $e=127;class Ye{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>$e;)this.buffer.push(e&$e|128),e>>>=7;this.buffer.push(e)}writeInteger64(e){for(;e>$e;)this.buffer.push(e&$e|128),e=Math.floor(e/128);this.buffer.push(e)}getResultBuffer(){return new Uint8Array(this.buffer)}}const{blake2bHex:ze}=h;class je{static async sign(e,t){const{wallet:r,data:n}=e;try{const e=await t();return await r.withSigningCapability(e,async e=>{const t=this.deployDataProtobufSerialize(n),r=ze(t,void 0,32),s=Uint8Array.from(Buffer.from(r,"hex")),i=await e.signDigest(s),a=e.getPublicKey();return{data:{term:n.term,timestamp:n.timestamp,phloPrice:n.phloPrice,phloLimit:n.phloLimit,validAfterBlockNumber:n.validAfterBlockNumber,shardId:n.shardId},deployer:k(a),signature:k(i),sigAlgorithm:"secp256k1"}})}catch(e){const t=`SignerService.sign: ${e.message}`;throw new Error(t)}}}je.deployDataProtobufSerialize=e=>{const{term:t,timestamp:r,phloPrice:n,phloLimit:s,validAfterBlockNumber:i,shardId:a=""}=e,o=new Ye;return o.writeString(2,t),o.writeInt64(3,r),o.writeInt64(7,n),o.writeInt64(8,s),o.writeInt64(10,i),o.writeString(11,a),o.getResultBuffer()};const Je=/[,\s]+/g,Xe=/^\d+(?:\.\d+)?$/,Ze=/(\.\d*?[1-9])0+$/,qe=/\.0+$/,Qe=e=>{const t=v.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 n=!1;if(r.startsWith("-")&&(n=!0,r=r.slice(1)),r=r.replace(Je,""),!Xe.test(r))throw new Error("Invalid amount format");const[s,i=""]=r.split("."),a=s||"0";let o=i;o.length>t&&(console.warn(`Fraction ${o} has more than allowed decimals; truncating`),o=o.slice(0,t)),o=o.padEnd(t,"0");const c=BigInt(a)*v+BigInt(o||"0");return n?-c:c},et=e=>{const t=e/v,r=e%v,n=v.toString().length-1,s=r.toString().padStart(n,"0");return`${t.toString()}.${s}`.replace(Ze,"$1").replace(qe,"")},tt=e=>{const t=e/v,r=e%v;return t>BigInt(Number.MAX_SAFE_INTEGER)?(console.warn("Integer part exceeds Number.MAX_SAFE_INTEGER; returning imprecise Number"),Number(et(e))):Number(t)+Number(r)/Number(v)},rt=et,nt=e=>[...Array(e)].map(()=>Math.floor(16*Math.random()).toString(16)).join(""),{blake2bHex:st}=h,it=/[<>:"/\\|?*]/,at=(e,t=30)=>e&&0!==e.trim().length?e.length>t?{isValid:!1,error:`Account name must be ${t} characters or less`}:it.test(e)?{isValid:!1,error:"Account name contains invalid characters"}:{isValid:!0}:{isValid:!1,error:"Account name is required"},ot=/^[a-zA-Z0-9]+$/,ct=/^[1-9A-HJ-NP-Za-km-z]+$/,lt=`${g.coinId}${g.version}`;var dt;!function(e){e.INVALID_PREFIX="INVALID_PREFIX",e.INVALID_LENGTH="INVALID_LENGTH",e.INVALID_ALPHABET="INVALID_ALPHABET",e.INVALID_BASE58="INVALID_BASE58",e.INVALID_HEX_LENGTH="INVALID_HEX_LENGTH",e.INVALID_CHAIN_PREFIX="INVALID_CHAIN_PREFIX",e.INVALID_CHECKSUM="INVALID_CHECKSUM",e.NON_CANONICAL="NON_CANONICAL"}(dt||(dt={}));const ut=e=>({isValid:!1,errorCode:e}),ht=e=>{if(!e.startsWith("1111"))return ut(dt.INVALID_PREFIX);if(e.length<50||e.length>54)return ut(dt.INVALID_LENGTH);if(!ot.test(e))return ut(dt.INVALID_ALPHABET);if(!ct.test(e))return ut(dt.INVALID_BASE58);const t=k(O(e));if(80!==t.length)return ut(dt.INVALID_HEX_LENGTH);if(_(t)!==e)return ut(dt.NON_CANONICAL);const r=t.slice(0,72),n=t.slice(72);if(!r.startsWith(lt))return ut(dt.INVALID_CHAIN_PREFIX);const s=st(C(r),void 0,32).slice(0,8);return 8!==n.length||n!==s?ut(dt.INVALID_CHECKSUM):{isValid:!0}},yt=e=>ht(e).isValid;class pt{constructor(e,t){if(this.startSubmissionTime=0,this.config=e,this.nodeManager=Ge.initialize(t,e.nodeSelectionAttempts,e.useRandomNode),this.errorHandler=new ke,!Be.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,n){let s=this.config.deployRetries,i={success:!1};for(;s>0&&!this.isDeployExpired();){try{const s=Be.getInstance(),a=await s.getLatestBlockNumber();if(-1===a)throw new Error("DeployResubmitter.retryDeployToOneNode: Invalid block number");const o={term:e,phloLimit:n||We,phloPrice:1,validAfterBlockNumber:a-1,timestamp:Date.now(),shardId:"root"},c=await je.sign({wallet:t,data:o},r),l=await s.submitDeploy(c);if("string"!=typeof l){throw new Error("Invalid deploy ID received: "+l)}return i={success:!0,deployId:l},i}catch(e){const t="DeployResubmitter.retryDeployToOneNode:"+e.message,r=this.errorHandler.parseDeploymentError(t);if(console.error(t),i.error={blockchainError:{type:r,message:t}},this.errorHandler.isDeploymentErrorFatal(r))break;s--}await this.sleep(this.config.deployIntervalSeconds)}return this.isDeployExpired()&&(i.error=i?.error||{},i.error.exceededTimeout=De.DEPLOY_SUBMIT_TIMEOUT),{success:!1,error:i.error}}async retryDeployToRandomNodes(e,t,r,n){let s={success:!1};for(;!this.isDeployExpired()&&this.nodeManager.getRetriesLeft()>0&&(await this.nodeManager.connectActiveRandomNode(),s=await this.retryDeployToOneNode(e,t,r,n),!s.success)&&(this.nodeManager.deactivateCurrentNode(),s.error?.blockchainError?.type)&&!this.errorHandler.isDeploymentErrorFatal(s.error?.blockchainError?.type););return s}async pollDeployStatus(e){let t;for(;!this.isDeployExpired();){const r=await Be.getInstance().getDeployStatus(e),n=r.status;if(n===Pe.CHECK_ERROR){const e=`DeployResubmitter.pollDeployStatus: ${"errorMessage"in r?r.errorMessage:"Unknown error"}`,n=this.errorHandler.parseDeploymentError(e);console.error(e);const s={type:n,message:e};if(this.errorHandler.isDeploymentErrorFatal(n)&&!e.includes("Bad Request"))return{success:!1,deployStatus:Pe.CHECK_ERROR,error:{blockchainError:s}};t=s}if(console.log("DeployResubmitter.pollDeployStatus: current deploy status:",n),n==Pe.INCLUDED_IN_BLOCK||n==Pe.FINALIZED)return{success:!0,deployStatus:r.status};await this.sleep(this.config.pollingIntervalSeconds)}return{success:!1,deployStatus:t?Pe.CHECK_ERROR:Pe.DEPLOYING,error:{...t,exceededTimeout:De.BLOCK_INCLUSION_TIMEOUT}}}async resubmit(e,t,r,n){let s;if(console.log("DeployResubmitter: starting deploy submission with resubmission logic"),this.startSubmissionTime=Date.now(),this.config.useRandomNode?s=await this.retryDeployToRandomNodes(e,t,r,n):(await this.nodeManager.connectDefaultNode(),s=await this.retryDeployToOneNode(e,t,r,n)),!s.success||!s?.deployId)return s;console.log(`DeployResubmitter: deploy submitted successfully with ID: ${s.deployId}. Starting to poll for status...`);const i=await this.pollDeployStatus(s.deployId);return console.log(`DeployResubmitter: finished polling deploy status. Final status: ${i.deployStatus}, success: ${i.success}`),i}}const ft=e=>e.replace(/\\/g,"\\\\").replace(/"/g,'\\"').replace(/\n/g,"\\n").replace(/\r/g,"\\r").replace(/\t/g,"\\t");let gt=(()=>{var e;let t,r,n=[];return e=class{getBlockchainGateway(){return Be.getInstance()}async transfer(e,t,r,n,s,i=5e5){try{const a=ht(e);if(!a.isValid)throw new Error(`AssetsService.transfer: Invalid 'fromAddress': ${a.errorCode??"UNKNOWN"}`);const o=ht(t);if(!o.isValid)throw new Error(`AssetsService.transfer: Invalid 'toAddress': ${o.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 c=this.getBlockchainGateway(),l=((e,t,r)=>{if(r<=0n)throw new Error("Transfer amount must be greater than zero");const n=ft(e),s=ft(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", "${s}", *toVaultCh) |\n @ASIVault!("deployerAuthKey", *deployerId, *asiVaultkeyCh) |\n for (@(true, vault) <- vaultCh; key <- asiVaultkeyCh; @(true, toVault) <- toVaultCh) {\n @vault!("transfer", "${s}", ${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 `})(e,t,r),d=await c.getLatestBlockNumber();if(-1===d)throw new Error("AssetsService.transfer: Invalid block number");const u={term:l,phloLimit:i,phloPrice:1,validAfterBlockNumber:d-1,timestamp:Date.now(),shardId:"root"},h=await je.sign({wallet:n,data:u},s);return await c.submitDeploy(h)}catch(e){const t="AssetsService.transfer: "+e.message;throw new Error(t)}}async getASIBalance(e){const t=ht(e);if(!t.isValid)throw new Error(`AssetsService.getASIBalance: Invalid address: ${t.errorCode??"UNKNOWN"}`);const r=this.getBlockchainGateway(),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", "${ft(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(n);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(){Re(this,n)}},(()=>{const s="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;t=[Fe],r=[Fe],Se(e,null,t,{kind:"method",name:"transfer",static:!1,private:!1,access:{has:e=>"transfer"in e,get:e=>e.transfer},metadata:s},null,n),Se(e,null,r,{kind:"method",name:"getASIBalance",static:!1,private:!1,access:{has:e=>"getASIBalance"in e,get:e=>e.getASIBalance},metadata:s},null,n),s&&Object.defineProperty(e,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:s})})(),e})();class mt{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}}class wt{static async createAndEncrypt(e,t){const r=await z.encryptWithPassword(e,t);return new wt(r)}static createFromEncryptedData(e){return new wt(e)}static createFromStringifiedEncryptedData(e){return new wt(JSON.parse(e))}constructor(e){this.encryptedSeedData=e}async decrypt(e){return await z.decryptWithPassword(this.encryptedSeedData,e)}toString(){return JSON.stringify(this.encryptedSeedData)}}var Et;!function(e){e.PRIVATE_KEY="private_key",e.CRYPTO_SALT="crypto_salt",e.CRYPTO_IV="crypto_iv",e.CRYPTO_VERSION="crypto version"}(Et||(Et={}));class It{constructor(e,t,r,n,s){this.name=e,this.index=s,this.masterNodeId=n,this.address=t,this.privateKey=r,this.assets=new Map,this.isLocked=!0}static async fromPrivateKey(e,t,r,n=null,s=null){const i=be.deriveAddressFromPrivateKey(t),a=await this.encryptPrivateKey(t,r);return new It(e,i,a,n,s)}static fromEncryptedData(e,t,r,n,s){const i=ht(t);if(!i.isValid)throw new Error(`Invalid address format: ${i.errorCode??"UNKNOWN"}`);return new It(e,t,r,n,s)}async decrypt(e){if(!It.unsafeRawKeyExportEnabled)throw new Error("Wallet.decrypt is disabled by default for security. Use withSigningCapability() instead.");return await this.decryptPrivateKey(e)}static enableUnsafeRawKeyExportForLegacyInterop(){It.unsafeRawKeyExportEnabled=!0}static disableUnsafeRawKeyExport(){It.unsafeRawKeyExportEnabled=!1}static isUnsafeRawKeyExportEnabled(){return It.unsafeRawKeyExportEnabled}async decryptPrivateKey(e){try{const t=await z.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],n="string"==typeof t?Number(t):t;return"number"!=typeof n||isNaN(n)?0:n});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 s={signDigest:async e=>{if(n)throw new Error("Signing capability has expired");return await d(e,r)},getPublicKey:()=>{if(n)throw new Error("Signing capability has expired");return Ne.getPublicKeyFromPrivateKey(r)}};try{return await t(s)}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 z.encryptWithPassword(JSON.stringify(e),t)}}It.unsafeRawKeyExportEnabled=!1;const Nt="0";class At{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(At.ensureBrowserEnvironment(),!this.isLocked)throw new Error("Cannot save an unlocked vault");const t=`${At.vaultPrefix}_${e}`;localStorage.setItem(t,JSON.stringify(this.encryptedVaultData))}async lock(e){this.ensureUnlocked();const t=this.toString();this.encryptedVaultData=await z.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 z.decryptWithPassword(this.encryptedVaultData,e),{wallets:r,seeds:n}=JSON.parse(t);this.metaToWallets(r),this.metaToSeeds(n),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 n=JSON.parse(e[r]),s=It.fromEncryptedData(n.name,n.address,JSON.parse(n.encryptedPrivateKey),n.masterNodeId,n.index?+n.index:null);t.set(r,s)}),this.wallets=t}metaToSeeds(e){const t=new Map;Object.keys(e).forEach(r=>{const n=wt.createFromStringifiedEncryptedData(e[r]);t.set(r,n)}),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(),n=this.getSeedsIds();return r.forEach(e=>{const r=this.getWallet(e);r&&(t[e]=r.toString())}),n.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")}}At.vaultPrefix="ASI_WALLETS_VAULT";class vt{constructor(e){this.vault=e}static async create(e={}){const t=e.vault||new At;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 vt(t)}async createWallet(e,t,r){const n=await It.fromPrivateKey(e,t,r);return this.vault.addWallet(n),n}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()}}class bt{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}`}}export{v as ASI_BASE_UNIT,g as ASI_CHAIN_PREFIX,m as ASI_COIN_TYPE,w as ASI_DECIMALS,dt as AddressValidationErrorCode,mt as Asset,gt as AssetsService,Te as AxiosHttpClient,Ye as BinaryWriter,Be as BlockchainGateway,vt as Client,z as CryptoService,Ke as DEFAULT_AXIOS_TIMEOUT_MS,R as DEFAULT_BIP_44_PATH_OPTIONS,Ve as DEFAULT_CLIENT_CONFIG,Me as DEFAULT_DECIMALS_AMOUNT,We as DEFAULT_PHLO_LIMIT,He as DEFAULT_RESUBMIT_CONFIG,Nt as DEFAULT_STORAGE_KEY,pt as DeployResubmitter,Pe as DeployStatus,ke as DeploymentErrorHandler,wt as EncryptedRecord,b as FAULT_TOLERANCE_THRESHOLD,De as FatalDeployErrors,D as FeeService,E as GasFee,N as HEX_BYTE_PADDING,I as HEX_RADIX,S as INVALID_BLOCK_NUMBER,we as KeyDerivationService,Ne as KeysManager,xe as MAX_WALLETS_PER_ACCOUNT,X as MnemonicService,J as MnemonicStrength,A as POWER_BASE,f as PRIVATE_KEY_LENGTH,Le as RecoverableDeployErrors,Ge as ResubmitNodeManager,bt as SecureStorage,je as SignerService,At as Vault,It as Wallet,Ue as WalletClientModes,Et as WalletMemoryKeys,be as WalletsService,T as arrayBufferToBase64,P as base64ToArrayBuffer,B as bigIntToBuffer,U as bufferToBigInt,C as decodeBase16,O as decodeBase58,_e as deploymentErrorMessages,k as encodeBase16,_ as encodeBase58,rt as fromAtomicAmount,tt as fromAtomicAmountToNumber,et as fromAtomicAmountToString,nt as genRandomHex,Oe as getDeploymentErrorMessage,yt as isAddress,j as setupBufferPolyfill,Qe as toAtomicAmount,at as validateAccountName,ht as validateAddress};
|
|
1
|
+
import{Buffer as e}from"buffer";import t from"bs58";import n from"blakejs";import a from"js-sha3";import*as r from"bip39";import{mnemonicToSeed as i}from"bip39";import{utils as s,CURVE as o,Point as c,getPublicKey as l,signSync as d,verify as u,sign as h}from"@noble/secp256k1";import{BIP32Factory as g}from"bip32";import w from"axios";import p from"node-persist";const y=8,f=5e5,m=1,I="./storage",v={MIN:170000n,MAX:250000n},A=18e4,b=3e5,E=32,T={coinId:"000000",version:"00"},S=60,C=8,N=16,D=64,x=10,P=BigInt(10)**BigInt(8),k=.99,M=-1,R={coinType:60,account:0,change:0,index:0},_=()=>{"undefined"==typeof window||window.Buffer||(window.Buffer=e)},z=e=>{const n=L(e);return t.encode(n)},H=e=>t.decode(e),L=e=>{const t=new Uint8Array(e.length/2);for(let n=0;n<e.length;n+=2)t[n/2]=parseInt(e.substr(n,2),16);return t},O=e=>Array.from(e,e=>e.toString(16).padStart(2,"0")).join(""),B=e=>{const t=new Uint8Array(e);let n="";for(let e=0;e<t.byteLength;e++)n+=String.fromCharCode(t[e]);return btoa(n)},K=e=>{const t=atob(e),n=new Uint8Array(t.length);for(let e=0;e<t.length;e++)n[e]=t.charCodeAt(e);return n.buffer},V=e=>BigInt("0x"+Buffer.from(e).toString("hex")),W=e=>Uint8Array.from(Buffer.from(e.toString(16).padStart(64,"0"),"hex")),U=e=>[...Array(e)].map(()=>Math.floor(16*Math.random()).toString(16)).join(""),$=()=>`res_${Date.now()}_${U(8)}`,F=/[,\s]+/g,j=/^\d+(?:\.\d+)?$/,X=/(\.\d*?[1-9])0+$/,G=/\.0+$/,Y=(e,t)=>{const n=(BigInt(10)**BigInt(t)).toString().length-1;if("number"==typeof e){if(!Number.isFinite(e))throw new Error("Invalid number");e=String(e)}let a=String(e).trim();if(!a.length)throw new Error("Cannot process empty amount");let r=!1;if(a.startsWith("-")&&(r=!0,a=a.slice(1)),a=a.replace(F,""),!j.test(a))throw new Error("Invalid amount format");const[i,s=""]=a.split("."),o=i||"0";let c=s;c.length>n&&(console.warn(`Fraction ${c} has more than allowed decimals; truncating`),c=c.slice(0,n)),c=c.padEnd(n,"0");const l=BigInt(o)*P+BigInt(c||"0");return r?-l:l},q=(e,t)=>{const n=e<0n,a=n?-e:e,r=BigInt(10)**BigInt(t),i=a/r,s=a%r,o=r.toString().length-1,c=s.toString().padStart(o,"0");return`${n?"-":""}${i.toString()}.${c}`.replace(X,"$1").replace(G,"")},J=(e,t)=>{const n=BigInt(10)**BigInt(t),a=e/n,r=e%n;return a>BigInt(Number.MAX_SAFE_INTEGER)?(console.warn("Integer part exceeds Number.MAX_SAFE_INTEGER; returning imprecise Number"),Number(q(e,t))):Number(a)+Number(r)/Number(n)},Z=q,Q=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")},ee=(e,t={})=>{let n=e;Object.entries(t.path??{}).forEach(([e,t])=>{void 0!==t&&(n=n.replace(`:${e}`,encodeURIComponent(String(t))))});const a=new URLSearchParams;Object.entries(t.query??{}).forEach(([e,t])=>{null!=t&&a.append(e,String(t))});const r=a.toString();return r?`${n}?${r}`:n};function te(e){return e?.trim().toLowerCase()??""}const{blake2bHex:ne}=n,ae=/[<>:"/\\|?*]/,re=(e,t=30)=>e&&0!==e.trim().length?e.length>t?{isValid:!1,error:`Account name must be ${t} characters or less`}:ae.test(e)?{isValid:!1,error:"Account name contains invalid characters"}:{isValid:!0}:{isValid:!1,error:"Account name is required"},ie=/^[a-zA-Z0-9]+$/,se=/^[1-9A-HJ-NP-Za-km-z]+$/,oe=`${T.coinId}${T.version}`;var ce;!function(e){e.INVALID_PREFIX="INVALID_PREFIX",e.INVALID_LENGTH="INVALID_LENGTH",e.INVALID_ALPHABET="INVALID_ALPHABET",e.INVALID_BASE58="INVALID_BASE58",e.INVALID_HEX_LENGTH="INVALID_HEX_LENGTH",e.INVALID_CHAIN_PREFIX="INVALID_CHAIN_PREFIX",e.INVALID_CHECKSUM="INVALID_CHECKSUM",e.NON_CANONICAL="NON_CANONICAL"}(ce||(ce={}));const le=e=>({isValid:!1,errorCode:e}),de=e=>{if(!e.startsWith("1111"))return le(ce.INVALID_PREFIX);if(e.length<50||e.length>54)return le(ce.INVALID_LENGTH);if(!ie.test(e))return le(ce.INVALID_ALPHABET);if(!se.test(e))return le(ce.INVALID_BASE58);const t=O(H(e));if(80!==t.length)return le(ce.INVALID_HEX_LENGTH);if(z(t)!==e)return le(ce.NON_CANONICAL);const n=t.slice(0,72),a=t.slice(72);if(!n.startsWith(oe))return le(ce.INVALID_CHAIN_PREFIX);const r=ne(L(n),void 0,32).slice(0,8);return 8!==a.length||a!==r?le(ce.INVALID_CHECKSUM):{isValid:!0}},ue=e=>de(e).isValid;class he{constructor({id:e,name:t,decimals:n,contractAddress:a}){this.id=e,this.name=t,this.decimals=n??8,this.contractAddress=a??null}getId(){return this.id}getName(){return this.name}getDecimals(){return this.decimals}getContractAddress(){return this.contractAddress}}const ge=new he({id:$(),name:"ASI"});var we;_(),function(e){e[e.TWELVE_WORDS=128]="TWELVE_WORDS",e[e.TWENTY_FOUR_WORDS=256]="TWENTY_FOUR_WORDS"}(we||(we={}));class pe{static generateMnemonic(e=we.TWELVE_WORDS){return r.generateMnemonic(e)}static generateMnemonicArray(e=we.TWELVE_WORDS){return this.mnemonicToWordArray(this.generateMnemonic(e))}static isMnemonicValid(e){return r.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 r.mnemonicToSeed(e,t):await r.mnemonicToSeed(this.wordArrayToMnemonic(e),t)}}class ye{constructor({coinType:e,account:t=0,change:n=0,index:a=0}){if(e<0)throw new Error("coinType must be non-negative");if(t<0)throw new Error("account must be non-negative");if(n<ye.MIN_CHANGE||n>ye.MAX_CHANGE)throw new Error("change must be 0 or 1");if(a<0)throw new Error("index must be non-negative");this.coinType=e,this.account=t,this.change=n,this.index=a}static parse(e){const t=e.split("/");if("m"!==t[0])throw new Error("Path must start with 'm'");if(t.length!==ye.PATH_COMPONENTS_COUNT)throw new Error("Invalid BIP-44 path: expected 6 components (m/44'/coinType'/account'/change/index)");const n=t[ye.COIN_TYPE_INDEX].replace("'",""),a=t[ye.ACCOUNT_INDEX].replace("'",""),r=t[ye.CHANGE_INDEX],i=t[ye.INDEX_COMPONENT_INDEX],s=parseInt(n,ye.DECIMAL_RADIX),o=parseInt(a,ye.DECIMAL_RADIX),c=parseInt(r,ye.DECIMAL_RADIX),l=parseInt(i,ye.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[ye.PURPOSE_INDEX]!==`${ye.BIP44_PURPOSE}'`)throw new Error("BIP-44 path must use 44' as the purpose");return new ye({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<ye.MIN_CHANGE||e>ye.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 ye({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 ye({coinType:this.coinType,account:this.account,change:this.change,index:this.index})}nextIndex(){return new ye({coinType:this.coinType,account:this.account,change:this.change,index:this.index+1})}}function fe(e){if(!Number.isSafeInteger(e)||e<0)throw new Error("positive integer expected, got "+e)}function me(e,...t){if(!((n=e)instanceof Uint8Array||ArrayBuffer.isView(n)&&"Uint8Array"===n.constructor.name))throw new Error("Uint8Array expected");
|
|
2
|
+
/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */
|
|
3
|
+
var n;if(t.length>0&&!t.includes(e.length))throw new Error("Uint8Array expected of length "+t+", got length="+e.length)}function Ie(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 ve(...e){for(let t=0;t<e.length;t++)e[t].fill(0)}function Ae(e){return new DataView(e.buffer,e.byteOffset,e.byteLength)}function be(e,t){return e<<32-t|e>>>t}function Ee(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)),me(e),e}ye.BIP44_PURPOSE=44,ye.MIN_CHANGE=0,ye.MAX_CHANGE=1,ye.PATH_COMPONENTS_COUNT=6,ye.PURPOSE_INDEX=1,ye.COIN_TYPE_INDEX=2,ye.ACCOUNT_INDEX=3,ye.CHANGE_INDEX=4,ye.INDEX_COMPONENT_INDEX=5,ye.DECIMAL_RADIX=10;class Te{}function Se(e){const t=t=>e().update(Ee(t)).digest(),n=e();return t.outputLen=n.outputLen,t.blockLen=n.blockLen,t.create=()=>e(),t}function Ce(e,t,n){return e&t^~e&n}function Ne(e,t,n){return e&t^e&n^t&n}class De extends Te{constructor(e,t,n,a){super(),this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.blockLen=e,this.outputLen=t,this.padOffset=n,this.isLE=a,this.buffer=new Uint8Array(e),this.view=Ae(this.buffer)}update(e){Ie(this),me(e=Ee(e));const{view:t,buffer:n,blockLen:a}=this,r=e.length;for(let i=0;i<r;){const s=Math.min(a-this.pos,r-i);if(s===a){const t=Ae(e);for(;a<=r-i;i+=a)this.process(t,i);continue}n.set(e.subarray(i,i+s),this.pos),this.pos+=s,i+=s,this.pos===a&&(this.process(t,0),this.pos=0)}return this.length+=e.length,this.roundClean(),this}digestInto(e){Ie(this),function(e,t){me(e);const n=t.outputLen;if(e.length<n)throw new Error("digestInto() expects output buffer of length at least "+n)}(e,this),this.finished=!0;const{buffer:t,view:n,blockLen:a,isLE:r}=this;let{pos:i}=this;t[i++]=128,ve(this.buffer.subarray(i)),this.padOffset>a-i&&(this.process(n,0),i=0);for(let e=i;e<a;e++)t[e]=0;!function(e,t,n,a){if("function"==typeof e.setBigUint64)return e.setBigUint64(t,n,a);const r=BigInt(32),i=BigInt(4294967295),s=Number(n>>r&i),o=Number(n&i),c=a?4:0,l=a?0:4;e.setUint32(t+c,s,a),e.setUint32(t+l,o,a)}(n,a-8,BigInt(8*this.length),r),this.process(n,0);const s=Ae(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],r)}digest(){const{buffer:e,outputLen:t}=this;this.digestInto(e);const n=e.slice(0,t);return this.destroy(),n}_cloneInto(e){e||(e=new this.constructor),e.set(...this.get());const{blockLen:t,buffer:n,length:a,finished:r,destroyed:i,pos:s}=this;return e.destroyed=i,e.finished=r,e.length=a,e.pos=s,a%t&&e.buffer.set(n),e}clone(){return this._cloneInto()}}const xe=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),Pe=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]),ke=new Uint32Array(64);class Me extends De{constructor(e=32){super(64,e,8,!1),this.A=0|xe[0],this.B=0|xe[1],this.C=0|xe[2],this.D=0|xe[3],this.E=0|xe[4],this.F=0|xe[5],this.G=0|xe[6],this.H=0|xe[7]}get(){const{A:e,B:t,C:n,D:a,E:r,F:i,G:s,H:o}=this;return[e,t,n,a,r,i,s,o]}set(e,t,n,a,r,i,s,o){this.A=0|e,this.B=0|t,this.C=0|n,this.D=0|a,this.E=0|r,this.F=0|i,this.G=0|s,this.H=0|o}process(e,t){for(let n=0;n<16;n++,t+=4)ke[n]=e.getUint32(t,!1);for(let e=16;e<64;e++){const t=ke[e-15],n=ke[e-2],a=be(t,7)^be(t,18)^t>>>3,r=be(n,17)^be(n,19)^n>>>10;ke[e]=r+ke[e-7]+a+ke[e-16]|0}let{A:n,B:a,C:r,D:i,E:s,F:o,G:c,H:l}=this;for(let e=0;e<64;e++){const t=l+(be(s,6)^be(s,11)^be(s,25))+Ce(s,o,c)+Pe[e]+ke[e]|0,d=(be(n,2)^be(n,13)^be(n,22))+Ne(n,a,r)|0;l=c,c=o,o=s,s=i+t|0,i=r,r=a,a=n,n=t+d|0}n=n+this.A|0,a=a+this.B|0,r=r+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(n,a,r,i,s,o,c,l)}roundClean(){ve(ke)}destroy(){this.set(0,0,0,0,0,0,0,0),ve(this.buffer)}}const Re=Se(()=>new Me);class _e extends Te{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");fe(e.outputLen),fe(e.blockLen)}(e);const n=Ee(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 a=this.blockLen,r=new Uint8Array(a);r.set(n.length>a?e.create().update(n).digest():n);for(let e=0;e<r.length;e++)r[e]^=54;this.iHash.update(r),this.oHash=e.create();for(let e=0;e<r.length;e++)r[e]^=106;this.oHash.update(r),ve(r)}update(e){return Ie(this),this.iHash.update(e),this}digestInto(e){Ie(this),me(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:n,finished:a,destroyed:r,blockLen:i,outputLen:s}=this;return e.finished=a,e.destroyed=r,e.blockLen=i,e.outputLen=s,e.oHash=t._cloneInto(e.oHash),e.iHash=n._cloneInto(e.iHash),e}clone(){return this._cloneInto()}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}}const ze=(e,t,n)=>new _e(e,t).update(n).digest();ze.create=(e,t)=>new _e(e,t),s.hmacSha256Sync=(e,...t)=>ze(Re,e,s.concatBytes(...t));const He=o.n,Le={isPoint(e){try{return c.fromHex(e),!0}catch{return!1}},isPrivate(e){if(32!==e.length)return!1;const t=V(e);return t>0n&&t<He},pointFromScalar(e,t=!0){try{return l(e,t)}catch{return null}},pointAddScalar(e,t,n=!0){try{const a=c.fromHex(e),r=V(t),i=c.BASE.multiply(r);return a.add(i).toRawBytes(n)}catch{return null}},privateAdd(e,t){const n=(V(e)+V(t))%He;return 0n===n?null:W(n)},privateNegate(e){const t=V(e);return W((He-t)%He)},sign:(e,t)=>d(e,t,{der:!1}),verify:(e,t,n)=>u(n,e,t)};_();class Oe{static async deriveKeyFromMnemonic(e,t){const n="string"==typeof t?t:t.toString(),a=await pe.mnemonicToSeed(e),r=g(Le).fromSeed(Buffer.from(a));a.fill(0);const i=r.derivePath(n);if(!i.privateKey)throw new Error("No private key at derived node");return new Uint8Array(i.privateKey)}static derivePrivateKey(e,t){const n=e.derivePath(t.toString());if(!n.privateKey)throw new Error("No private key at derived node");return new Uint8Array(n.privateKey)}static async mnemonicToSeed(e,t=""){return"string"==typeof e?await i(e,t):await i(pe.wordArrayToMnemonic(e),t)}static seedToMasterNode(e){return g(Le).fromSeed(Buffer.from(e))}static async deriveNextKeyFromMnemonic(e,t,n=R){const a=new ye({...n,index:t+1});return await this.deriveKeyFromMnemonic(e,a)}}const{randomBytes:Be,bytesToHex:Ke}=s;class Ve{static generateRandomKey(e=32){if(!e||e<0||!Number.isInteger(e))throw new Error("PrivateKeyLength must be a positive integer");return Be(e)}static generateKeyPair(e=32){const t=this.generateRandomKey(e);return{privateKey:t,publicKey:l(t)}}static getKeyPairFromPrivateKey(e){return{privateKey:e,publicKey:l(e)}}static getPublicKeyFromPrivateKey(e){return l(e)}static convertKeyToHex(e){return Ke(e)}static async getInitialHDPathFromOptions(e){return"customHDPath"in e?e.customHDPath:new ye({coinType:60,account:0,change:0,index:e.index})}static async getPrivateDataFromSeed(e,t){const n=Oe.seedToMasterNode(e);return{privateKey:Oe.derivePrivateKey(n,t),path:t,index:t.getIndex()}}}const{blake2bHex:We}=n,{keccak256:Ue}=a;class $e{static createWallet(e,t){let n;n=e?Ve.getKeyPairFromPrivateKey(e):Ve.generateKeyPair();return{address:this.deriveAddressFromPublicKey(n.publicKey),publicKey:n.publicKey,privateKey:n.privateKey}}static async createFirstWalletWithMnemonic(e,t){const n=e?pe.mnemonicToWordArray(e):pe.generateMnemonicArray(),a=pe.wordArrayToMnemonic(n);if(!a||!pe.isMnemonicValid(a))throw new Error("WalletsService.createFirstWalletWithMnemonic: Recovery mnemonic is missing or invalid");const r=await Oe.mnemonicToSeed(n),i=Oe.seedToMasterNode(r),s=new ye({coinType:60,account:0,change:0,index:t||0}),o=Oe.derivePrivateKey(i,s);return{...this.createWallet(o),mnemonic:a}}static deriveAddressFromPrivateKey(e){const t=Ve.getKeyPairFromPrivateKey(e);return this.deriveAddressFromPublicKey(t.publicKey)}static deriveAddressFromPublicKey(e){const t=Ue(e.slice(1)),n=L(t.slice(-40)),a=Ue(n),r=`${T.coinId}${T.version}${a}`,i=L(r),s=We(i,void 0,32).slice(0,8);return z(`${r}${s}`)}}function Fe(e,t,n,a,r,i){function s(e){if(void 0!==e&&"function"!=typeof e)throw new TypeError("Function expected");return e}for(var o,c=a.kind,l="getter"===c?"get":"setter"===c?"set":"value",d=!t&&e?a.static?e:e.prototype:null,u=t||(d?Object.getOwnPropertyDescriptor(d,a.name):{}),h=!1,g=n.length-1;g>=0;g--){var w={};for(var p in a)w[p]="access"===p?{}:a[p];for(var p in a.access)w.access[p]=a.access[p];w.addInitializer=function(e){if(h)throw new TypeError("Cannot add initializers after decoration has completed");i.push(s(e||null))};var y=(0,n[g])("accessor"===c?{get:u.get,set:u.set}:u[l],w);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))&&r.unshift(o)}else(o=s(y))&&("field"===c?r.unshift(o):u[l]=o)}d&&Object.defineProperty(d,a.name,u),h=!0}function je(e,t,n){for(var a=arguments.length>2,r=0;r<t.length;r++)n=a?t[r].call(e,n):t[r].call(e);return a?n:void 0}"function"==typeof SuppressedError&&SuppressedError;class Xe{constructor(e){this.client=w.create({baseURL:e.baseUrl,headers:{"Content-Type":"application/json"},...e.axiosConfig})}async query(e,t){const n=await this.client.post("",{query:e,variables:t},{headers:{"Content-Type":"application/json"}});if(n.data.errors?.length)throw new Error(JSON.stringify(n.data.errors));return n.data.data}}function Ge(e,t,n){const a=te(n);return te(e)===a?"send":"receive"}function Ye(e){if(void 0===e||""===e)return new Date(0);if("number"==typeof e)return qe(e);const t=e.trim();if(/^\d+$/.test(t))return qe(Number(t));const n=Date.parse(t);return Number.isFinite(n)?new Date(n):new Date(0)}function qe(e){return new Date(e<1e10?1e3*e:e)}class Je{static isRecord(e){return"object"==typeof e&&null!==e}static isDefined(e){return void 0!==e}static createTransactionHistoryRequest(e,t={}){const n={address:e.trim(),offset:t.offset??0};return void 0!==t.limit&&(n.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:n}}static mapTransactionHistory(e,t,n){return e&&e.transfers?e.transfers.map(e=>function(e,t){const n=e.from_address?.trim(),a=e.to_address?.trim();var r;if(e.deploy_id&&n&&a)return{id:e.deploy_id,timestamp:Ye(e.timestamp),type:Ge(n,0,t.accountAddress),from:n,to:a,amount:(r=e.amount_asi,void 0===r?void 0:String(r)),deployId:e.deploy_id,blockHash:e.block_hash,status:"confirmed",networkName:t.networkName,detectedBy:"auto"}}(e,{accountAddress:t,networkName:n})).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 Ze extends Xe{async getTransactionHistory(e,t={}){const{query:n,variables:a}=Je.createTransactionHistoryRequest(e,t);return this.query(n,a)}}class Qe{constructor(e){this.client=w.create({baseURL:e.baseUrl,...e.axiosConfig})}async get(e,t){return(await this.client.get(e,t)).data}async post(e,t,n){return(await this.client.post(e,t,n)).data}}class et extends Qe{getDeploy(e){return this.get(`/api/deploy/${e}`)}getBlock(e){return this.get(`/api/block/${e}`)}getBlocks(e={}){const{start:t,end:n,view:a}=e,r=ee("api/blocks",{path:{start:t,end:n,view:a}});return this.get(r,a?{params:{view:a}}:void 0)}}class tt extends Qe{submitDeploy(e){return this.post("/api/deploy",e)}submitExploratoryDeploy(e){return this.post("/api/explore-deploy",e)}getStatus(){return this.get("/status")}}class nt{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 at(e,t){return function(...t){if(!this.isReady())throw new Error("ApiClientManager is not initialized");return e.apply(this,t)}}function rt(e,t){return function(...t){if(!this.networkConfigProvider.isReady())throw new Error("ApiClientManager config is not initialized");return e.apply(this,t)}}let it=(()=>{var e;let t,n,a,r,i,s,o,c=[];return e=class{constructor(){this.networkConfigProvider=je(this,c),this.validatorClient=null,this.observerClient=null,this.indexerClient=null,this.currentNetwork=null,this.isInitialized=!1,this.networkConfigProvider=new nt}static getInstance(){return e.instance||(e.instance=new e),e.instance}initialize(e,t){if(this.isInitialized)return;this.networkConfigProvider.initialize(e);const n=t??Object.keys(e)[0];this.switchNetwork(n),this.isInitialized=!0}switchNetwork(e){const t=this.networkConfigProvider.get(e);this.validatorClient=new tt({baseUrl:t.ValidatorURL}),this.observerClient=new et({baseUrl:t.ReadOnlyURL}),this.indexerClient=new Ze({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=[rt],n=[at],a=[at],r=[at],i=[at],s=[at],o=[at,rt],Fe(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),Fe(e,null,n,{kind:"method",name:"getValidatorClient",static:!1,private:!1,access:{has:e=>"getValidatorClient"in e,get:e=>e.getValidatorClient},metadata:l},null,c),Fe(e,null,a,{kind:"method",name:"getObserverClient",static:!1,private:!1,access:{has:e=>"getObserverClient"in e,get:e=>e.getObserverClient},metadata:l},null,c),Fe(e,null,r,{kind:"method",name:"getIndexerClient",static:!1,private:!1,access:{has:e=>"getIndexerClient"in e,get:e=>e.getIndexerClient},metadata:l},null,c),Fe(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),Fe(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),Fe(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 st{constructor(e){this.apiClientManager=e??it.getInstance()}async getTransactionHistory(e,t,n={}){try{const a=t??it.getInstance().getNetwork(),r=await this.apiClientManager.getIndexerClient().getTransactionHistory(e,n);return Je.mapTransactionHistory(r,e,a)}catch(e){return Je.isRecoverableNetworkError(e)?(console.warn("[GraphQL] Network error while loading transaction history. Returning an empty history."),[]):(console.error("AccountDataService.getTransactionHistory:",e),[])}}}const ot=e=>e.replace(/\\/g,"\\\\").replace(/"/g,'\\"').replace(/\n/g,"\\n").replace(/\r/g,"\\r").replace(/\t/g,"\\t");class ct{constructor(e){this.deployService=e}async getBalance(e,t){const n=de(e);if(!n.isValid)throw new Error(`AssetsService.getBalance: Invalid address: ${n.errorCode??"UNKNOWN"}`);const a=(e=>`\n new return, rl(\`rho:registry:lookup\`), ASIVaultCh, vaultCh in {\n rl!(\`rho:rchain:asiVault\`, *ASIVaultCh) |\n for (@(_, ASIVault) <- ASIVaultCh) {\n @ASIVault!("findOrCreate", "${ot(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(a);if(e?.length>0){const n=e[0];if(void 0!==n?.ExprInt?.data)return{amount:BigInt(n.ExprInt.data),asset:t};if(void 0!==n?.ExprString?.data)throw new Error("Balance check error")}return{amount:0n,asset:t}}catch{return{amount:0n,asset:t}}}}class lt{constructor(e){this.apiClientManager=e??it.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 dt;!function(e){e.DEPLOYING="Deploying",e.INCLUDED_IN_BLOCK="IncludedInBlock",e.FINALIZED="Finalized",e.CHECK_ERROR="CheckingError"}(dt||(dt={}));class ut{constructor(e){this.apiClientManager=e??it.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:dt.DEPLOYING};return{status:await this.isDeployFinalized(t)?dt.FINALIZED:dt.INCLUDED_IN_BLOCK}}catch(e){return{status:dt.CHECK_ERROR,errorMessage:e instanceof Error?e.message:String(e)}}}}class ht{constructor(e){this.deployService=e}watch(e,t={},{intervalMs:n=5e3,timeoutMs:a=18e4}={}){const r=Date.now()+a;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 a=await this.deployService.getDeployStatus(e);if(t.onStatus?.(a,e),a.status===dt.FINALIZED)return n={deployId:e},u(),t.onConfirmed?.(n),void s(n);Date.now()>r&&h(new Error(`DeployStatusPoller: timeout for ${e}`))}catch(e){h(e instanceof Error?e:new Error(String(e)))}finally{c=!1}var n}};return i=setInterval(g,n),g(),d.catch(()=>{}),{cancel:u,done:d}}waitFor(e,t){return this.watch(e,{},t).done}}const gt=127;class wt{constructor(){this.buffer=[]}writeString(e,t){if(!t)return;const n=e<<3|2;this.writeInteger(n);const a=(new TextEncoder).encode(t);this.writeInteger(a.length),this.buffer.push(...Array.from(a))}writeInt64(e,t){if(!t)return;const n=e<<3;this.writeInteger(n),this.writeInteger64(t)}writeInteger(e){for(;e>gt;)this.buffer.push(e>|128),e>>>=7;this.buffer.push(e)}writeInteger64(e){for(;e>gt;)this.buffer.push(e>|128),e=Math.floor(e/128);this.buffer.push(e)}getResultBuffer(){return new Uint8Array(this.buffer)}}class pt{}var yt;pt.deployDataProtobufSerialize=e=>{const{term:t,timestamp:n,phloPrice:a,phloLimit:r,validAfterBlockNumber:i,shardId:s=""}=e,o=new wt;return o.writeString(2,t),o.writeInt64(3,n),o.writeInt64(7,a),o.writeInt64(8,r),o.writeInt64(10,i),o.writeString(11,s),o.getResultBuffer()},function(e){e.PRIVATE_KEY="private-key",e.HD="hd"}(yt||(yt={}));class ft{constructor({id:e,encryptedSecret:t}){this.id=e,this.encryptedSecret=t}getId(){return this.id}getEncryptedSecret(){return this.encryptedSecret}}const{blake2bHex:mt}=n;class It{constructor(e,t){this.deployService=e,this.blockService=t}async signDeploy(e,t,n){const a=pt.deployDataProtobufSerialize(t),r=mt(a,void 0,32),i=await e.sign(r,n);return{data:t,deployer:O(i.publicKey),signature:O(i.signature),sigAlgorithm:"secp256k1"}}async transfer({walletType:e,account:t,signer:n,details:a,passwordProvider:r}){if(!t)throw new Error("Wallet has no active account");const i=t.getAddress(),s=de(a.to);if(!s.isValid)throw new Error(`Invalid recipient address: ${s.errorCode}`);if(a.amount<=0n)throw new Error("Amount must be greater than zero");if(a.phloLimit&&a.phloLimit<=0n)throw new Error("Phlo limit must be greater than zero");if(a.phloPrice&&a.phloPrice<=0n)throw new Error("Phlo price must be greater than zero");const o=((e,t,n)=>{if(n<=0n)throw new Error("Transfer amount must be greater than zero");const a=ot(e),r=ot(t),i=n.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", "${a}", *vaultCh) |\n @ASIVault!("findOrCreate", "${r}", *toVaultCh) |\n @ASIVault!("deployerAuthKey", *deployerId, *asiVaultkeyCh) |\n for (@(true, vault) <- vaultCh; key <- asiVaultkeyCh; @(true, toVault) <- toVaultCh) {\n @vault!("transfer", "${r}", ${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,a.to,a.amount),c=await this.blockService.getLatestBlockNumber();if(-1===c)throw new Error("TransactionService.transfer: Invalid block number");const l=e!==yt.HD?{passwordProvider:r}:{passwordProvider:r,index:t.getIndex()},d=await this.signDeploy(n,{term:o,phloLimit:a.phloLimit??f,phloPrice:a.phloPrice??1,validAfterBlockNumber:c-1,timestamp:Date.now(),shardId:a.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 vt{constructor(e){this.deploy=new ut(e),this.blocks=new lt(e),this.accountData=new st(e),this.assets=new ct(this.deploy),this.transactions=new It(this.deploy,this.blocks),this.poller=new ht(this.deploy)}static getInstance(e){return vt.instance||(vt.instance=new vt(e??it.getInstance())),vt.instance}}class At{constructor({id:e,name:t,index:n,portfolioOptions:a,address:r}){this.id=e??$(),this.name=t,this.index=n,this.address=r,this.assets=a?.assets??new Map([[ge.getId(),ge]]),this.primaryAsset=a?.primaryAsset??ge}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 n=t.getSecret();if((e=>"privateKey"in e)(n)){const t=$e.deriveAddressFromPrivateKey(n.privateKey);return new At({...e,index:null,address:t})}void 0!==e.index&&n.rootHDPath.setIndex(e.index);const a=await Oe.deriveKeyFromMnemonic(n.seed,n.rootHDPath),r=$e.deriveAddressFromPrivateKey(a);return a.fill(0),new At({...e,index:n.rootHDPath.getIndex(),address:r})}update(e){e.name&&(this.name=e.name)}async getBalance(){return vt.getInstance().assets.getBalance(this.address,this.primaryAsset)}async getTransactionsHistory(e,t){return vt.getInstance().accountData.getTransactionHistory(this.address,e,t)}}function bt(e,t){return async function(...t){return await this.init(),await e.apply(this,t)}}function Et(e,t){return async function(...t){const n=t[0];if("string"!=typeof n)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(n))throw new Error(`Table '${n}' does not exist. Use createTable() first.`);return await e.apply(this,t)}}function Tt(e,t){return async function(...t){if(this.isInitialized())return await e.apply(this,t)}}function St(e,t){return async function(...t){const n=t[0];if("string"!=typeof n)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(n))return await e.apply(this,t)}}function Ct(e,t){return async function(...t){if(this.getType()!==yt.HD)throw new Error("This operation is available only for HD wallets");return await e.apply(this,t)}}function Nt(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 Dt(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 xt=(()=>{var e;let t,n,a,r,i=[];return e=class{constructor(e="AppDatabase"){this.name=je(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 n=indexedDB.open(this.name);n.onsuccess=()=>{this.storageInterface=n.result,this.storageInterface.onclose=()=>{this.storageInterface=null},this.storageInterface.onversionchange=()=>{this.storageInterface?.close(),this.storageInterface=null},e(this.storageInterface)},n.onerror=()=>{t(new Error(`Failed to open database: ${n.error?.message}`))}})}async createTable(e,t="id"){const n=this.storageInterface.version+1;return await this.close(),new Promise((a,r)=>{const i=indexedDB.open(this.name,n);i.onupgradeneeded=n=>{const a=i.result;if(!a.objectStoreNames.contains(e)){a.createObjectStore(e,{keyPath:t}).createIndex("createdAt","createdAt",{unique:!1})}},i.onsuccess=()=>{this.storageInterface=i.result,a()},i.onerror=()=>{r(new Error(`Failed to create table: ${i.error?.message}`))}})}async insert(e,t){const n={...t,createdAt:t.createdAt||Date.now(),updatedAt:Date.now()};await this.executeTransaction(e,"readwrite",e=>e.add(n))}async insertMany(e,t){const n=t.map(e=>({...e,createdAt:e.createdAt||Date.now(),updatedAt:Date.now()}));await this.executeTransaction(e,"readwrite",e=>{for(const t of n)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,n){const a=await this.getById(e,t);if(!a)throw new Error(`Record with id '${t}' not found in table '${e}'`);const r={...a,...n,id:a.id,updatedAt:Date.now()};await this.executeTransaction(e,"readwrite",e=>e.put(r))}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 n of t)e.delete(n)})}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((n,a)=>{const r=indexedDB.open(this.name,t);r.onupgradeneeded=t=>{const n=r.result;n.objectStoreNames.contains(e)&&n.deleteObjectStore(e)},r.onsuccess=()=>{this.storageInterface=r.result,n()},r.onerror=()=>{a(new Error(`Failed to drop table: ${r.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,n){return new Promise((a,r)=>{if(!this.storageInterface)return void r(new Error("Database not initialized"));const i=this.storageInterface.transaction(e,t),s=i.objectStore(e),o=n(s);i.oncomplete=()=>{a(o&&"result"in o?o.result:void 0)},i.onerror=()=>{r(new Error(`Transaction failed: ${i.error?.message}`))},i.onabort=()=>{r(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=[bt],n=[bt,Et],a=[bt],r=[bt,Et],Fe(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),Fe(e,null,n,{kind:"method",name:"dropTable",static:!1,private:!1,access:{has:e=>"dropTable"in e,get:e=>e.dropTable},metadata:s},null,i),Fe(e,null,a,{kind:"method",name:"tableExists",static:!1,private:!1,access:{has:e=>"tableExists"in e,get:e=>e.tableExists},metadata:s},null,i),Fe(e,null,r,{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 Pt="__tables__";let kt=(()=>{var e;let t,n,a,r,i,s,o,c,l=[];return e=class{constructor(e=I){this.storageDir=je(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=p.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 n=await this.storageInterface.getItem(Pt)??[];n.push(e),await this.storageInterface.setItem(Pt,n)}async insert(e,t){const n=await this.getTable(e);if(n[String(t.id)])throw new Error(`Record with id '${t.id}' already exists`);n[String(t.id)]={...t,createdAt:t.createdAt||Date.now(),updatedAt:Date.now()},await this.saveTable(e,n)}async insertMany(e,t){const n=await this.getTable(e);for(const e of t)n[String(e.id)]={...e,createdAt:e.createdAt||Date.now(),updatedAt:Date.now()};await this.saveTable(e,n)}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,n){const a=await this.getTable(e),r=a[String(t)];if(!r)throw new Error(`Record with id '${t}' not found in table '${e}'`);a[String(t)]={...r,...n,id:r.id,updatedAt:Date.now()},await this.saveTable(e,a)}async delete(e,t){const n=await this.getTable(e);delete n[String(t)],await this.saveTable(e,n)}async deleteMany(e,t){const n=await this.getTable(e);for(const e of t)delete n[String(e)];await this.saveTable(e,n)}async clearTable(e){await this.saveTable(e,{})}async dropTable(e){await this.storageInterface.removeItem(this.getTableKey(e));const t=await this.storageInterface.getItem(Pt);await this.storageInterface.setItem(Pt,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=[bt,Et],n=[bt],a=[bt,St],r=[Et],i=[bt,Et],s=[bt],o=[bt],c=[Tt],Fe(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),Fe(e,null,n,{kind:"method",name:"saveTable",static:!1,private:!1,access:{has:e=>"saveTable"in e,get:e=>e.saveTable},metadata:d},null,l),Fe(e,null,a,{kind:"method",name:"createTable",static:!1,private:!1,access:{has:e=>"createTable"in e,get:e=>e.createTable},metadata:d},null,l),Fe(e,null,r,{kind:"method",name:"clearTable",static:!1,private:!1,access:{has:e=>"clearTable"in e,get:e=>e.clearTable},metadata:d},null,l),Fe(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),Fe(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),Fe(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),Fe(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 Mt=e=>"undefined"!=typeof window?xt.getInstance():kt.getInstance(e?.nodeStorageDir),Rt="ACCOUNTS";class _t{constructor(e){this.isInitialized=!1,this.initPromise=null,this.storageInterface=Mt(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(){try{await this.storageInterface.tableExists(Rt)||await this.storageInterface.createTable(Rt,"id"),this.isInitialized=!0}catch(e){throw e}}async ensureInitialized(){this.isInitialized||await this.initialize()}getRawDB(){return this.storageInterface}async saveAccount(e,t,n,a){await this.ensureInitialized(),await this.storageInterface.insert(Rt,{id:e,signerId:t,name:n,index:a,createdAt:Date.now()})}async saveAccounts(e){await this.ensureInitialized(),await this.storageInterface.insertMany(Rt,e)}async getAccount(e){return await this.ensureInitialized(),this.storageInterface.getById(Rt,e)}async getAllAccounts(){return await this.ensureInitialized(),this.storageInterface.getAll(Rt)}async updateAccount(e,t){await this.ensureInitialized(),await this.storageInterface.update(Rt,e,t)}async deleteAccount(e){await this.ensureInitialized(),await this.storageInterface.delete(Rt,e)}async deleteMultipleAccounts(e){await this.ensureInitialized(),await this.storageInterface.deleteMany(Rt,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(Rt)}async clearTable(e){if(await this.ensureInitialized(),![Rt].includes(e))throw new Error(`Invalid table name: ${e}`);await this.storageInterface.clearTable(e)}isReady(){return this.isInitialized}async getTablesList(){return await this.ensureInitialized(),[Rt]}close(){this.storageInterface.close(),this.isInitialized=!1}}var zt;!function(e){e.ENCRYPT="encrypt",e.DECRYPT="decrypt",e.DERIVATION="deriveKey"}(zt||(zt={}));const Ht=2,Lt=12,Ot=16,Bt=256,Kt="AES-GCM",Vt="SHA-256",Wt="raw",Ut="PBKDF2",$t=1e5;zt.ENCRYPT,zt.DECRYPT;class Ft{static async encryptWithPassword(e,t){const n=crypto.getRandomValues(new Uint8Array(Ot)),a=crypto.getRandomValues(new Uint8Array(Lt)),r=await this.deriveKey(t,n),i=await crypto.subtle.encrypt({name:Kt,iv:a},r,(new TextEncoder).encode(e));return{data:B(i),salt:B(n.buffer),iv:B(a.buffer),version:Ht}}static async decryptWithPassword(e,t){if(e.version!==Ht)throw new Error(`Unsupported version ${e.version}`);const n=new Uint8Array(K(e.salt)),a=new Uint8Array(K(e.iv)),r=await this.deriveKey(t,n),i=await crypto.subtle.decrypt({name:Kt,iv:a},r,K(e.data));return(new TextDecoder).decode(i)}static async decryptSignerData(e,t){const n=await Ft.decryptWithPassword(e,t.getSecret().password),a=JSON.parse(n);if("privateKey"in a){return{privateKey:Q(a.privateKey)}}const r=ye.parse(a.rootHDPath);return{seed:a.seed,rootHDPath:r}}static async deriveKey(e,t){const n=await crypto.subtle.importKey(Wt,(new TextEncoder).encode(e),Ut,!1,[zt.DERIVATION]);return crypto.subtle.deriveKey({name:Ut,salt:new Uint8Array(t),iterations:$t,hash:Vt},n,{name:Kt,length:Bt},!1,[zt.ENCRYPT,zt.DECRYPT])}}class jt extends ft{async sign(e,t){const n=await Ft.decryptWithPassword(this.encryptedSecret,t.passwordProvider.getSecret().password),a=JSON.parse(n),r=ye.parse(a.rootHDPath);r.setIndex(t.index);const i=await Oe.deriveKeyFromMnemonic(a.seed,r),s=Ve.getPublicKeyFromPrivateKey(i);try{return{signature:await h(e,i),publicKey:s}}finally{i.fill(0)}}}class Xt extends ft{async sign(e,t){const{privateKey:n}=await Ft.decryptSignerData(this.encryptedSecret,t.passwordProvider),a=Ve.getPublicKeyFromPrivateKey(n);try{return{signature:await h(e,n),publicKey:a}}finally{n.fill(0)}}}const Gt=async e=>{const{password:t,secret:n}=e.secretProvider.getSecret(),a=await Ft.encryptWithPassword(JSON.stringify(n),t);switch(e.type){case yt.PRIVATE_KEY:return new Xt({id:e.id,encryptedSecret:a});case yt.HD:return new jt({id:e.id,encryptedSecret:a})}};var Yt;class qt{constructor(e){Yt.set(this,void 0),function(e,t,n,a,r){if("m"===a)throw new TypeError("Private method is not writable");if("a"===a&&!r)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");"a"===a?r.call(e,n):r?r.value=n:t.set(e,n)}(this,Yt,e,"f")}getSecret(){return function(e,t,n,a){if("a"===n&&!a)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!a:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===n?a:"a"===n?a.call(e):a?a.value:t.get(e)}(this,Yt,"f").call(this)}}Yt=new WeakMap;class Jt{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 Zt extends Jt{constructor(e=new Map,t=null){super(e),this.activeAccount=t??e.values().next().value??null}async create(e,t){const n=$(),a=await At.create({id:n,...e},t);return this.add(n,a),this.activeAccount||(this.activeAccount=a),{account:a,accountId:n}}remove(e){const t=super.remove(e);return this.activeAccount=this.items.values().next().value??null,t}update(e,t){const n=this.get(e);n?n.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 Qt=(()=>{var e;let t,n,a=[];return e=class{constructor({id:e,type:t,signer:n,accounts:r,activeAccount:i}){this.id=je(this,a),this.id=e??$(),this.type=t,this.signer=n,this.accountManager=new Zt(r,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(),n=this.getAccounts().map(e=>e.getIndex()).filter(e=>null!==e).sort((e,t)=>e-t);if(!n.length)return t;let a=t+1;for(const e of n)if(e!==a){if(e>a)return a}else a++;return a}async deriveAccount(e,t){const n=await Ft.decryptSignerData(this.signer.getEncryptedSecret(),t),a=new qt(()=>n),r=this.getDerivationIndex(n.rootHDPath);return this.accountManager.create({...e,index:r??void 0},a)}removeAccount(e){return this.accountManager.remove(e)}updateAccount(e,t){this.accountManager.update(e,t)}static async createPk(t,n){const a=await Gt({id:$(),type:yt.PRIVATE_KEY,secretProvider:n}),r=await At.create(t,new qt(()=>n.getSecret().secret)),i=new Map([[r.getId(),r]]);return new e({type:yt.PRIVATE_KEY,signer:a,accounts:i,activeAccount:r})}static async createHD(t,n){const a=await Ve.getInitialHDPathFromOptions(t.pathOptions),r=new qt(()=>({secret:{rootHDPath:a.toString(),seed:t.mnemonic},password:n.getSecret().password})),i=await Gt({id:$(),type:yt.HD,secretProvider:r}),s=new qt(()=>({rootHDPath:a,seed:t.mnemonic})),o=await At.create(t.accountOptions,s),c=new Map([[o.getId(),o]]);return new e({type:yt.HD,signer:i,accounts:c,activeAccount:o})}static async restore(t,n){const{signerRecord:a,accountRecords:r}=t,i=(({id:e,type:t,encryptedData:n})=>{switch(t){case yt.PRIVATE_KEY:return new Xt({id:e,encryptedSecret:n});case yt.HD:return new jt({id:e,encryptedSecret:n})}})(a),s=await Ft.decryptSignerData(i.getEncryptedSecret(),n),o=new qt(()=>s),c=new Map;for(const e of r){const t=await At.create({id:e.id,name:e.name,index:e.index??void 0},o);c.set(t.getId(),t)}return new e({type:a.type,signer:i,accounts:c})}async transfer(e,t){return vt.getInstance().transactions.transfer({walletType:this.type,account:this.getActiveAccount(),signer:this.signer,details:e,passwordProvider:t})}},(()=>{const r="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;t=[Ct],n=[Nt],Fe(e,null,t,{kind:"method",name:"deriveAccount",static:!1,private:!1,access:{has:e=>"deriveAccount"in e,get:e=>e.deriveAccount},metadata:r},null,a),Fe(e,null,n,{kind:"method",name:"transfer",static:!1,private:!1,access:{has:e=>"transfer"in e,get:e=>e.transfer},metadata:r},null,a),r&&Object.defineProperty(e,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:r})})(),e})();const en="SIGNERS";class tn{constructor(e){this.isInitialized=!1,this.initPromise=null,this.storageInterface=Mt(e)}static getInstance(e){return tn.instance||(tn.instance=new tn(e)),tn.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(en)||await this.storageInterface.createTable(en,"id"),this.isInitialized=!0}catch(e){throw e}}async ensureInitialized(){this.isInitialized||await this.initialize()}getRawDB(){return this.storageInterface}async saveSigner(e,t,n){await this.ensureInitialized(),await this.storageInterface.insert(en,{id:e,type:t,encryptedData:n,createdAt:Date.now()})}async getSigner(e){return await this.ensureInitialized(),this.storageInterface.getById(en,e)}async getAllSigners(){return await this.ensureInitialized(),this.storageInterface.getAll(en)}async updateSigner(e,t){await this.ensureInitialized(),await this.storageInterface.update(en,e,t)}async deleteSigner(e){await this.ensureInitialized(),await this.storageInterface.delete(en,e)}async deleteMultipleSigners(e){await this.ensureInitialized(),await this.storageInterface.deleteMany(en,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(en)}async clearTable(e){if(await this.ensureInitialized(),e!==en)throw new Error(`Invalid table name: ${e}`);await this.storageInterface.clearTable(e)}isReady(){return this.isInitialized}async getTablesList(){return await this.ensureInitialized(),[en]}close(){this.storageInterface.close(),this.isInitialized=!1}}const nn="TRANSACTION_RESERVATIONS";class an{constructor(e){this.isInitialized=!1,this.initPromise=null,this.storageInterface=Mt(e)}static getInstance(e){return an.instance||(an.instance=new an(e)),an.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(nn)||await this.storageInterface.createTable(nn,"id"),this.isInitialized=!0}async ensureInitialized(){this.isInitialized||await this.initialize()}getRawDB(){return this.storageInterface}async saveTransactionReservation(e,t,n,a){await this.ensureInitialized(),await this.storageInterface.insert(nn,{id:e,networkName:t,signerId:n,encryptedData:a,createdAt:Date.now()})}async getTransactionReservations(e){return await this.ensureInitialized(),this.storageInterface.getById(nn,e)}async getAllTransactionReservations(){return await this.ensureInitialized(),this.storageInterface.getAll(nn)}async updateTransactionReservation(e,t){await this.ensureInitialized(),await this.storageInterface.update(nn,e,t)}async deleteTransactionReservation(e){await this.ensureInitialized(),await this.storageInterface.delete(nn,e)}async deleteMultipleTransactionReservations(e){await this.ensureInitialized(),await this.storageInterface.deleteMany(nn,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(nn)}async clearTable(e){if(await this.ensureInitialized(),e!==nn)throw new Error(`Invalid table name: ${e}`);await this.storageInterface.clearTable(e)}isReady(){return this.isInitialized}async getTablesList(){return await this.ensureInitialized(),[nn]}close(){this.storageInterface.close(),this.isInitialized=!1}}var rn;class sn{}rn=sn,sn.init=async e=>{await tn.getInstance(e).initialize(),await _t.getInstance(e).initialize(),await an.getInstance(e).initialize()},sn.saveSigner=async({id:e,type:t,signer:n})=>{await tn.getInstance().saveSigner(e,t,n.getEncryptedSecret())},sn.saveSigners=async e=>Promise.all(e.map(e=>tn.getInstance().saveSigner(e.id,e.type,e.signer.getEncryptedSecret()))),sn.getSigner=async e=>{const t=await tn.getInstance().getSigner(e);if(!t)throw new Error("Signer with this id not found");return{id:t.id,type:t.type,encryptedData:t.encryptedData}},sn.getSigners=async()=>tn.getInstance().getAllSigners(),sn.updateSigner=async(e,t)=>{await tn.getInstance().updateSigner(e,t)},sn.deleteSigner=async e=>{await tn.getInstance().deleteSigner(e)},sn.deleteMultipleSigners=async e=>{await tn.getInstance().deleteMultipleSigners(e)},sn.saveAccount=async({id:e,account:t,signerId:n})=>{await _t.getInstance().saveAccount(e,n,t.getName(),t.getIndex())},sn.saveAccounts=async e=>{const t=e.map(({id:e,account:t,signerId:n})=>({id:e,signerId:n,name:t.getName(),index:t.getIndex(),createdAt:Date.now()}));await _t.getInstance().saveAccounts(t)},sn.getAccount=async e=>{const t=await _t.getInstance().getAccount(e);if(!t)throw new Error("Account with this id not found");return t},sn.getAccounts=async()=>_t.getInstance().getAllAccounts(),sn.updateAccount=async(e,t)=>{await _t.getInstance().updateAccount(e,t)},sn.deleteAccount=async e=>{await _t.getInstance().deleteAccount(e)},sn.deleteMultipleAccounts=async e=>{await _t.getInstance().deleteMultipleAccounts(e)},sn.saveWallet=async({signerId:e,wallet:t})=>{const n=t.getSigner();await rn.saveSigner({id:e,type:t.getType(),signer:n}),await rn.saveAccounts(Array.from(t.getAccountsMap()).map(([t,n])=>({id:t,account:n,signerId:e})))},sn.saveWallets=async e=>Promise.all(e.map(e=>rn.saveWallet(e))),sn.getWallet=async({signerId:e,passwordProvider:t})=>{const n=await rn.getSigner(e),a=(await rn.getAccounts()).filter(t=>t.signerId===e);return Qt.restore({signerRecord:n,accountRecords:a},t)},sn.getWallets=async()=>{const e=await rn.getSigners(),t=await rn.getAccounts();return e.map(e=>({signer:e,accounts:t.filter(t=>t.signerId===e.id)}))},sn.saveTransactionReservation=async({id:e,networkName:t,signerId:n,encryptedData:a})=>{await an.getInstance().saveTransactionReservation(e,t,n,a)},sn.getTransactionReservationsBySignerId=async(e,t)=>(await an.getInstance().getAllTransactionReservations()).filter(n=>n.signerId===e&&n.networkName===t),sn.updateTransactionReservation=async(e,t)=>{await an.getInstance().updateTransactionReservation(e,t)},sn.deleteTransactionReservation=async e=>{await an.getInstance().deleteTransactionReservation(e)},sn.deleteMultipleTransactionReservations=async e=>{await an.getInstance().deleteMultipleTransactionReservations(e)},sn.clear=async()=>{await tn.getInstance().clearAllData(),await _t.getInstance().clearAllData(),await an.getInstance().clearAllData()},sn.close=()=>{tn.getInstance().close(),_t.getInstance().close(),an.getInstance().close()};class on extends Jt{async createHD({mnemonic:e,accountName:t,index:n},a){const r=await Qt.createHD({mnemonic:e,pathOptions:{index:n??0},accountOptions:{name:t}},a);return await this.persist(r),r}async createPrivateKey(e,t){const n=await Qt.createPk({name:e},t);return await this.persist(n),n}async unlock(e,t){const n=await sn.getWallet({signerId:e,passwordProvider:t});return this.add(n.getId(),n),n}async delete(e){const t=super.remove(e),n=Array.from(t.getAccountsMap().keys());return n.length&&await sn.deleteMultipleAccounts(n),await sn.deleteSigner(t.getSigner().getId()),t}async deriveAccount(e,t,n){const a=this.get(e);if(!a)throw new Error("WalletManager.deriveAccount: unknown wallet id");const r=a.getSigner().getId(),{account:i,accountId:s}=await a.deriveAccount({name:t},n);return await sn.saveAccount({id:s,account:i,signerId:r}),{accountId:s,account:i}}async removeAccount(e,t){const n=this.get(e);if(!n)throw new Error("WalletManager.removeAccount: unknown wallet id");const a=n.removeAccount(t);return await sn.deleteAccount(t),a}async renameAccount(e,t,n){const a=this.get(e);if(!a)throw new Error("WalletManager.renameAccount: unknown wallet id");a.updateAccount(t,{name:n}),await sn.updateAccount(t,{name:n})}setActiveAccount(e,t){const n=this.get(e);if(!n)throw new Error("WalletManager.setActiveAccount: unknown wallet id");n.setActiveAccount(t)}async getPublicWalletsMetadata(){return(await sn.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 sn.getSigners()).length}async persist(e){await sn.saveWallet({signerId:e.getSigner().getId(),wallet:e}),this.add(e.getId(),e)}}class cn{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??A};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=vt.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 n=setTimeout(()=>this.handleExpired(e),t);this.expirationTimers.set(e.id,n)}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 ln{constructor(e,t){const n=e=>{sn.deleteTransactionReservation(e.id).catch(e=>console.error("ReservationAdapter: failed to delete released reservation:",e))};this.reservationsManager=new cn(e,{onConfirmed:n,onExpired:n,...t})}static async create(e,t,n){const a=it.getInstance().getNetwork(),r=e.getSigner().getId(),i=await sn.getTransactionReservationsBySignerId(r,a),s=t.getSecret().password,o=[];for(const e of i){const t=await Ft.decryptWithPassword(e.encryptedData,s),n=JSON.parse(t);n.expirationTime<=Date.now()?await sn.deleteTransactionReservation(e.id):o.push({id:e.id,networkName:e.networkName,timestamp:new Date(n.timestamp),accountAddress:n.accountAddress,pendingAmount:n.pendingAmount,deployId:n.deployId,expirationTime:n.expirationTime})}return new ln(o,n)}getReservedAmount(e){const t=this.reservationsManager.getByAccountAddress(e);return t.reduce((e,t)=>e+BigInt(t.pendingAmount),0n)+BigInt(t.length)*v.MAX}async getBalance(e){const t=await e.getBalance(),n=this.getReservedAmount(e.getAddress());return{...t,amount:t.amount-n}}getReservations(){return this.reservationsManager.getAll()}dispose(){this.reservationsManager.dispose()}async persistReservation(e,t,n){const a=n.getSecret().password,r={timestamp:e.timestamp,accountAddress:e.accountAddress,pendingAmount:e.pendingAmount,deployId:e.deployId,expirationTime:e.expirationTime},i=await Ft.encryptWithPassword(JSON.stringify(r),a);await sn.saveTransactionReservation({id:e.id,networkName:e.networkName,signerId:t.getSigner().getId(),encryptedData:i})}async validateSufficientBalance(e,t){const n=this.getReservedAmount(e.getAddress())+t;return(await e.getBalance()).amount-n>0n}async transfer(e,t,n){const a=e.getActiveAccount();if(!await this.validateSufficientBalance(a,t.amount))throw new Error("ReservationAdapter.transfer: Insufficient balance");const r=await e.transfer(t,n),i={id:$(),deployId:r,timestamp:new Date,accountAddress:a.getAddress(),pendingAmount:t.amount.toString(),networkName:it.getInstance().getNetwork(),expirationTime:Date.now()+b};return await this.persistReservation(i,e,n),this.reservationsManager.add(i),r}}class dn extends Jt{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 un extends dn{async create(e,t){const n=await ln.create(e,t);return super.add(e.getId(),n),n}}const hn="INSENSITIVE_CACHE";class gn{constructor(){this.isInitialized=!1,this.initPromise=null,this.storageInterface=Mt()}static getInstance(){return gn.instance||(gn.instance=new gn),gn.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(hn)||await this.storageInterface.createTable(hn,"id"),this.isInitialized=!0}async ensureInitialized(){this.isInitialized||await this.initialize()}async saveRecord(e){await this.ensureInitialized(),await this.storageInterface.insert(hn,e)}async getRecord(e){return await this.ensureInitialized(),this.storageInterface.getById(hn,e)}async getAllRecords(){return await this.ensureInitialized(),this.storageInterface.getAll(hn)}async updateRecord(e,t){await this.ensureInitialized(),await this.storageInterface.update(hn,e,t)}async deleteRecord(e){await this.ensureInitialized(),await this.storageInterface.delete(hn,e)}async clear(){await this.ensureInitialized(),await this.storageInterface.clearTable(hn)}close(){this.storageInterface.close(),this.isInitialized=!1}}var wn;class pn{}wn=pn,pn.init=async()=>{await gn.getInstance().initialize()},pn.save=async e=>{await gn.getInstance().saveRecord(e)},pn.get=async e=>gn.getInstance().getRecord(e),pn.getAll=async()=>gn.getInstance().getAllRecords(),pn.update=async(e,t)=>{await gn.getInstance().updateRecord(e,t)},pn.delete=async e=>{await gn.getInstance().deleteRecord(e)},pn.deleteAll=async e=>{for(const t of e)await wn.delete(t)},pn.clear=async()=>{await gn.getInstance().clear()},pn.close=()=>{gn.getInstance().close()};class yn{}yn.serialize=e=>({id:e.getId(),address:e.getAddress()});let fn=(()=>{var e;let t,n=[];return e=class{constructor({walletsMap:e,reservationAdaptersMap:t,eventDispatcher:a,flags:r}){this.walletManager=je(this,n),this.walletManager=new on(e),this.reservationAdapterManager=new un(t),this.eventDispatcher=a,this.flags=r}static async create({networksConfig:t,defaultNetwork:n,storageOptions:a,eventDispatcher:r,flags:i}){return await sn.init(a),it.getInstance().initialize(t,n),vt.getInstance(),i?.withInsensitiveCacheStorage&&await pn.init(),new e({eventDispatcher:r,flags:i})}getWalletManager(){return this.walletManager}getInsensitiveAccountsData(){return pn.getAll()}async clearPersistence(){this.walletManager.clear(),this.reservationAdapterManager.clear(),await sn.clear(),await this.emitWalletsChanged()}close(){this.walletManager.clear(),this.reservationAdapterManager.clear(),sn.close(),it.getInstance().close()}generateMnemonic(e=we.TWELVE_WORDS){return pe.generateMnemonic(e)}generatePrivateKey(){return Ve.generateKeyPair().privateKey}async createHDWallet({mnemonic:e,accountName:t,index:n},a){const r=this.createPasswordProvider(a),i=await this.walletManager.createHD({mnemonic:e,accountName:t,index:n},r);return await this.reservationAdapterManager.create(i,r),await this.emitWalletsChanged(),this.flags?.withInsensitiveCacheStorage&&pn.save(yn.serialize(i.getActiveAccount())),i}async createPrivateKeyWallet({privateKey:e,accountName:t},n){const a=new qt(()=>({password:n,secret:{privateKey:e}})),r=await this.walletManager.createPrivateKey(t,a);return await this.reservationAdapterManager.create(r,a),await this.emitWalletsChanged(),this.flags?.withInsensitiveCacheStorage&&pn.save(yn.serialize(r.getActiveAccount())),r}async removeWallet(e){const t=await this.walletManager.delete(e);this.reservationAdapterManager.remove(e),this.flags?.withInsensitiveCacheStorage&&pn.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 n=this.createPasswordProvider(t),a=await this.walletManager.unlock(e,n);return await this.reservationAdapterManager.create(a,n),a}async deriveAccount(e,t,n){const a=this.createPasswordProvider(n),r=await this.walletManager.deriveAccount(e,t,a);return this.emitAccountsChanged(e),this.flags?.withInsensitiveCacheStorage&&pn.save(yn.serialize(r.account)),r}async removeAccount(e,t){const n=await this.walletManager.removeAccount(e,t);this.flags?.withInsensitiveCacheStorage&&pn.delete(n.getId()),this.emitAccountsChanged(e)}async renameAccount(e,t,n){await this.walletManager.renameAccount(e,t,n),this.emitAccountsChanged(e)}setActiveAccount(e,t){this.walletManager.setActiveAccount(e,t)}getNetworksNames(){return it.getInstance().getNetworkNames()}getCurrentNetwork(){return it.getInstance().getNetwork()}setNetwork(e){it.getInstance().switchNetwork(e),this.eventDispatcher?.onNetworkChanged?.(e)}async getBalance(e){return(await vt.getInstance().assets.getBalance(e,ge)).amount}async getAvailableBalance(e,t){const n=this.getUnlockedWallet(e),a=this.getAccount(n,t),r=this.reservationAdapterManager.get(e);if(!r)throw new Error("Client.getAvailableBalance: Not found reservation adapter");return(await r.getBalance(a)).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:n,amount:a},r){const i=this.getUnlockedWallet(e);i.setActiveAccount(t);const s=this.createPasswordProvider(r),o=this.reservationAdapterManager.get(e);if(!o)throw new Error("Client.transfer: Not found reservation adapter");const c=await o.transfer(i,{to:n,amount:a,asset:ge},s);return this.eventDispatcher?.onReservationsChanged?.(e,o.getReservations()),c}toDisplayAmount(e){return Z(e,8)}toAtomicAmount(e){return Y(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 n=e.getAccountsMap().get(t);if(!n)throw new Error(`Account ${t} not found`);return n}createPasswordProvider(e){return new qt(()=>({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 a="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;t=[Dt],Fe(e,null,t,{kind:"method",name:"getInsensitiveAccountsData",static:!1,private:!1,access:{has:e=>"getInsensitiveAccountsData"in e,get:e=>e.getInsensitiveAccountsData},metadata:a},null,n),a&&Object.defineProperty(e,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:a})})(),e})();export{Rt as ACCOUNTS_DATA_KEY,P as ASI_BASE_UNIT,T as ASI_CHAIN_PREFIX,S as ASI_COIN_TYPE,C as ASI_DECIMALS,At as Account,st as AccountDataService,Zt as AccountManager,_t as AccountsStorageRepository,ce as AddressValidationErrorCode,it as ApiClientManager,vt as ApiServiceRegistry,he as Asset,ct as AssetsService,Xe as BaseGraphQLClient,Qe as BaseHttpClient,wt as BinaryWriter,ye as Bip44Path,lt as BlockService,xt as BrowserStorage,fn as Client,Ft as Crypto,ge as DEFAULT_ASSET,R as DEFAULT_BIP_44_PATH_OPTIONS,I as DEFAULT_NODE_STORAGE_DIR,f as DEFAULT_PHLO_LIMIT,m as DEFAULT_PHLO_PRICE,A as DEPLOY_STATUS_POLLING_TIMEOUT,ut as DeployService,dt as DeployStatus,ht as DeployStatusPoller,dn as DisposableItemManager,k as FAULT_TOLERANCE_THRESHOLD,v as GasFee,D as HEX_BYTE_PADDING,N as HEX_RADIX,M as INVALID_BLOCK_NUMBER,Ze as IndexerClient,Jt as ItemManager,Oe as KeyDerivation,Ve as KeysManager,pe as Mnemonic,we as MnemonicStrength,y as NATIVE_TOKEN_DECIMALS_AMOUNT,nt as NetworkConfigProvider,kt as NodeStorage,et as ObserverClient,x as POWER_BASE,E as PRIVATE_KEY_LENGTH,b as RESERVATION_EXPIRATION_TIME,un as ReservationAdapterManager,en as SIGNERS_DATA_KEY,qt as SecretsProvider,ft as Signer,pt as SignerService,tn as SignersStorageRepository,sn as StorageManager,nn as TRANSACTION_RESERVATIONS_DATA_KEY,an as TransactionReservationsStorageRepository,It as TransactionService,tt as ValidatorClient,Qt as Wallet,on as WalletManager,yt as WalletTypes,$e as Wallets,B as arrayBufferToBase64,K as base64ToArrayBuffer,W as bigIntToBuffer,V as bufferToBigInt,ee as buildUrl,L as decodeBase16,H as decodeBase58,O as encodeBase16,z as encodeBase58,Z as fromAtomicAmount,J as fromAtomicAmountToNumber,U as genRandomHex,$ as generateRandomId,ue as isAddress,te as normalizeAddress,_ as setupBufferPolyfill,Y as toAtomicAmount,Q as toUint8Array,re as validateAccountName,de as validateAddress};
|
|
3
4
|
//# sourceMappingURL=index.esm.js.map
|