@asichain/asi-wallet-sdk 0.1.4 → 0.1.6

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 CHANGED
@@ -311,7 +311,6 @@ Playground available at `http://localhost:5173`. See [docs/PLAYGROUND.md](docs/P
311
311
  | [@noble/hashes](https://github.com/paulmillr/noble-hashes) | 1.6.0 | Cryptographic hash helpers |
312
312
  | [@noble/secp256k1](https://github.com/paulmillr/noble-secp256k1) | 1.7.0 | secp256k1 key generation and signing |
313
313
  | [js-sha3](https://github.com/nicknisi/js-sha3) | 0.9.3 | keccak256 hashing |
314
- | [tiny-secp256k1](https://github.com/nicknisi/tiny-secp256k1) | 2.2.4 | secp256k1 for BIP-32 derivation |
315
314
 
316
315
  **Playground** ([playground/package.json](playground/package.json)):
317
316
 
package/dist/index.cjs CHANGED
@@ -1,2 +1,3 @@
1
- "use strict";var e=require("bs58"),t=require("bip39"),r=require("buffer"),s=require("tiny-secp256k1"),o=require("bip32"),a=require("@noble/secp256k1"),n=require("blakejs"),i=require("js-sha3"),l=require("axios");function c(e){var t=Object.create(null);return e&&Object.keys(e).forEach(function(r){if("default"!==r){var s=Object.getOwnPropertyDescriptor(e,r);Object.defineProperty(t,r,s.get?s:{enumerable:!0,get:function(){return e[r]}})}}),t.default=e,Object.freeze(t)}var d=c(t),u=c(s);const p={coinId:"000000",version:"00"},y={BASE_FEE:.0025,VARIATION_RANGE:.1,LABEL:"ASI",TRANSFER:"0.0025",DEPLOY:"0.0025"},h=BigInt(10)**BigInt(8),E={coinType:60,account:0,change:0,index:0};var g;class m{}g=m,m.generateRandomGasFee=()=>{const e=2*(Math.random()-.5)*y.VARIATION_RANGE;return(y.BASE_FEE*(1+e)).toFixed(4)},m.getGasFeeAsNumber=()=>y.BASE_FEE,m.formatGasFee=e=>`${e||g.generateRandomGasFee()} ${y.LABEL}`;const f=t=>{const r=w(t);return e.encode(r)},I=t=>e.decode(t),w=e=>{const t=new Uint8Array(e.length/2);for(let r=0;r<e.length;r+=2)t[r/2]=parseInt(e.substr(r,2),16);return t},N=e=>Array.from(e,e=>e.toString(16).padStart(2,"0")).join(""),A=e=>{const t=new Uint8Array(e);let r="";for(let e=0;e<t.byteLength;e++)r+=String.fromCharCode(t[e]);return btoa(r)},v=e=>{const t=atob(e),r=new Uint8Array(t.length);for(let e=0;e<t.length;e++)r[e]=t.charCodeAt(e);return r.buffer};var S;!function(e){e.ENCRYPT="encrypt",e.DECRYPT="decrypt",e.DERIVATION="deriveKey"}(S||(S={}));const D=2,R=12,b=16,x=256,_="AES-GCM",L="SHA-256",O="raw",C="PBKDF2",T=1e5;S.ENCRYPT,S.DECRYPT;class P{static async encryptWithPassword(e,t){const r=crypto.getRandomValues(new Uint8Array(b)),s=crypto.getRandomValues(new Uint8Array(R)),o=await this.deriveKey(t,r),a=await crypto.subtle.encrypt({name:_,iv:s},o,(new TextEncoder).encode(e));return{data:A(a),salt:A(r.buffer),iv:A(s.buffer),version:D}}static async decryptWithPassword(e,t){if(e.version!==D)throw new Error(`Unsupported version ${e.version}`);const r=new Uint8Array(v(e.salt)),s=new Uint8Array(v(e.iv)),o=await this.deriveKey(t,r),a=await crypto.subtle.decrypt({name:_,iv:s},o,v(e.data));return(new TextDecoder).decode(a)}static async deriveKey(e,t){const r=await crypto.subtle.importKey(O,(new TextEncoder).encode(e),C,!1,[S.DERIVATION]);return crypto.subtle.deriveKey({name:C,salt:new Uint8Array(t),iterations:T,hash:L},r,{name:_,length:x},!1,[S.ENCRYPT,S.DECRYPT])}}const k=()=>{"undefined"==typeof window||window.Buffer||(window.Buffer=r.Buffer)};var U;k(),exports.MnemonicStrength=void 0,(U=exports.MnemonicStrength||(exports.MnemonicStrength={}))[U.TWELVE_WORDS=128]="TWELVE_WORDS",U[U.TWENTY_FOUR_WORDS=256]="TWENTY_FOUR_WORDS";class V{static generateMnemonic(e=exports.MnemonicStrength.TWELVE_WORDS){return d.generateMnemonic(e)}static generateMnemonicArray(e=exports.MnemonicStrength.TWELVE_WORDS){return this.mnemonicToWordArray(this.generateMnemonic(e))}static isMnemonicValid(e){return d.validateMnemonic(e)}static mnemonicToWordArray(e){return e.trim().split(" ")}static wordArrayToMnemonic(e){return e.join(" ")}}k();class K{static buildBip44Path({coinType:e=60,account:t=0,change:r=0,index:s=0}){return`m/44'/${e}'/${t}'/${r}/${s}`}static derivePrivateKey(e,t){const r=e.derivePath(t);if(!r.privateKey)throw new Error("No private key at derived node");return new Uint8Array(r.privateKey)}static async mnemonicToSeed(e,r=""){return"string"==typeof e?await t.mnemonicToSeed(e,r):await t.mnemonicToSeed(V.wordArrayToMnemonic(e),r)}static seedToMasterNode(e){return o.BIP32Factory(u).fromSeed(e)}static async deriveKeyFromMnemonic(e,t=E){const r=this.buildBip44Path(t),s=await K.mnemonicToSeed(e),o=K.seedToMasterNode(s);return K.derivePrivateKey(o,r)}static async deriveNextKeyFromMnemonic(e,t,r=E){const s=t+1;return await this.deriveKeyFromMnemonic(e,{...r,index:s})}}const{randomBytes:B,bytesToHex:M}=a.utils;class F{static generateRandomKey(e=32){if(!e||e<0||!Number.isInteger(e))throw new Error("PrivateKeyLength must be a positive integer");return B(e)}static generateKeyPair(e=32){if(!e||e<0||!Number.isInteger(e))throw new Error("PrivateKeyLength must be a positive integer");const t=B(e);return{privateKey:t,publicKey:a.getPublicKey(t)}}static getKeyPairFromPrivateKey(e){return{privateKey:e,publicKey:a.getPublicKey(e)}}static getPublicKeyFromPrivateKey(e){return a.getPublicKey(e)}static convertKeyToHex(e){return M(e)}static async deriveKeyFromMnemonic(e,t){return await K.deriveKeyFromMnemonic(e,t)}static generateMpcKeyPair(){throw new Error("MPC key generation is not implemented yet.")}}const{blake2bHex:W}=n,{keccak256:G}=i;class H{static createWallet(e,t){let r;r=e?F.getKeyPairFromPrivateKey(e):F.generateKeyPair();return{address:this.deriveAddressFromPublicKey(r.publicKey),publicKey:r.publicKey,privateKey:r.privateKey}}static async createWalletFromMnemonic(e,t){const r=e?V.mnemonicToWordArray(e):V.generateMnemonicArray(),s=V.wordArrayToMnemonic(r);if(!s||!V.isMnemonicValid(s))throw new Error("WalletsService.createWalletFromMnemonic: Recovery mnemonic is missing or invalid");const o=await K.mnemonicToSeed(r),a=K.seedToMasterNode(o),n=K.buildBip44Path({coinType:60,account:0,change:0,index:t||0}),i=K.derivePrivateKey(a,n);return{...this.createWallet(i),mnemonic:s}}static deriveAddressFromPrivateKey(e){const t=F.getKeyPairFromPrivateKey(e);return this.deriveAddressFromPublicKey(t.publicKey)}static deriveAddressFromPublicKey(e){const t=G(e.slice(1)),r=w(t.slice(-40)),s=G(r),o=`${p.coinId}${p.version}${s}`,a=w(o),n=W(a,void 0,32).slice(0,8);return f(`${o}${n}`)}}function $(e,t,r,s,o,a){function n(e){if(void 0!==e&&"function"!=typeof e)throw new TypeError("Function expected");return e}for(var i,l=s.kind,c="getter"===l?"get":"setter"===l?"set":"value",d=!t&&e?s.static?e:e.prototype:null,u=t||(d?Object.getOwnPropertyDescriptor(d,s.name):{}),p=!1,y=r.length-1;y>=0;y--){var h={};for(var E in s)h[E]="access"===E?{}:s[E];for(var E in s.access)h.access[E]=s.access[E];h.addInitializer=function(e){if(p)throw new TypeError("Cannot add initializers after decoration has completed");a.push(n(e||null))};var g=(0,r[y])("accessor"===l?{get:u.get,set:u.set}:u[c],h);if("accessor"===l){if(void 0===g)continue;if(null===g||"object"!=typeof g)throw new TypeError("Object expected");(i=n(g.get))&&(u.get=i),(i=n(g.set))&&(u.set=i),(i=n(g.init))&&o.unshift(i)}else(i=n(g))&&("field"===l?o.unshift(i):u[c]=i)}d&&Object.defineProperty(d,s.name,u),p=!0}function Y(e,t,r){for(var s=arguments.length>2,o=0;o<t.length;o++)r=s?t[o].call(e,r):t[o].call(e);return s?r:void 0}var z,j;"function"==typeof SuppressedError&&SuppressedError,exports.RecoverableDeployErrors=void 0,(z=exports.RecoverableDeployErrors||(exports.RecoverableDeployErrors={})).READ_ONLY_NODE="READ_ONLY_NODE",z.CASPER_INSTANCE_UNAVAILABLE="CASPER_INSTANCE_UNAVAILABLE",z.INVALID_DEPLOY_ID="INVALID_DEPLOY_ID",z.INVALID_BLOCK_NUMBER="INVALID_BLOCK_NUMBER",exports.FatalDeployErrors=void 0,(j=exports.FatalDeployErrors||(exports.FatalDeployErrors={})).INSUFFICIENT_BALANCE="INSUFFICIENT_BALANCE",j.WRONG_NETWORK="WRONG_NETWORK",j.PARSING_ERROR="PARSING_ERROR",j.LOW_PHLO_PRICE="LOW_PHLO_PRICE",j.SIGNATURE_ERROR="SIGNATURE_ERROR",j.STORAGE_RETRIEVAL_ERROR="STORAGE_RETRIEVAL_ERROR",j.UNKNOWN_ERROR="UNKNOWN_ERROR",j.DEPLOY_SUBMIT_TIMEOUT="DEPLOY_SUBMIT_TIMEOUT",j.BLOCK_INCLUSION_TIMEOUT="BLOCK_INCLUSION_TIMEOUT",j.FINALIZATION_TIMEOUT="FINALIZATION_TIMEOUT";const X={[exports.RecoverableDeployErrors.READ_ONLY_NODE]:"Node is read-only. Trying another node...",[exports.RecoverableDeployErrors.CASPER_INSTANCE_UNAVAILABLE]:"Casper instance not available. Trying another node...",[exports.RecoverableDeployErrors.INVALID_DEPLOY_ID]:"Invalid deploy ID. Please try again.",[exports.RecoverableDeployErrors.INVALID_BLOCK_NUMBER]:"Invalid block number. Please try again.",[exports.FatalDeployErrors.INSUFFICIENT_BALANCE]:"Insufficient balance. Please top up your account.",[exports.FatalDeployErrors.WRONG_NETWORK]:"Wrong network. Please contact technical support.",[exports.FatalDeployErrors.PARSING_ERROR]:"Parsing error. Please contact technical support.",[exports.FatalDeployErrors.LOW_PHLO_PRICE]:"Phlo price too low. Please rebuild the transaction with a higher phlo price.",[exports.FatalDeployErrors.SIGNATURE_ERROR]:"Signature verification failed. Please try again.",[exports.FatalDeployErrors.STORAGE_RETRIEVAL_ERROR]:"Storage retrieval error. Please try again later.",[exports.FatalDeployErrors.UNKNOWN_ERROR]:"An unknown error occurred. Please try again.",[exports.FatalDeployErrors.DEPLOY_SUBMIT_TIMEOUT]:"Deploy submission timed out. Please try again.",[exports.FatalDeployErrors.BLOCK_INCLUSION_TIMEOUT]:"Deploy was not included in a block within the expected time.",[exports.FatalDeployErrors.FINALIZATION_TIMEOUT]:"Block finalization polling timed out."};function J(e,t){return function(...t){return"string"==typeof t[0]&&(t[0]=t[0].toLowerCase()),e.apply(this,t)}}let q=(()=>{var e;let t,r,s=[];return e=class{parseDeploymentError(e){return e.includes("read only")?exports.RecoverableDeployErrors.READ_ONLY_NODE:e.includes("casper instance")?exports.RecoverableDeployErrors.CASPER_INSTANCE_UNAVAILABLE:e.includes("invalid deploy ID")?exports.RecoverableDeployErrors.INVALID_DEPLOY_ID:e.includes("invalid block number")?exports.RecoverableDeployErrors.INVALID_BLOCK_NUMBER:e.includes("insufficient balance")?exports.FatalDeployErrors.INSUFFICIENT_BALANCE:e.includes("wrong network")?exports.FatalDeployErrors.WRONG_NETWORK:e.includes("parsing error")?exports.FatalDeployErrors.PARSING_ERROR:e.includes("low")&&e.includes("phlo")?exports.FatalDeployErrors.LOW_PHLO_PRICE:e.includes("signature")||e.includes("sign")||e.includes("invalid signature")?exports.FatalDeployErrors.SIGNATURE_ERROR:e.includes("storage")||e.includes("retrieval")?exports.FatalDeployErrors.STORAGE_RETRIEVAL_ERROR:exports.FatalDeployErrors.UNKNOWN_ERROR}isDeploymentErrorRecoverable(e){return Object.values(exports.RecoverableDeployErrors).includes(e)}isDeploymentErrorFatal(e){return Object.values(exports.FatalDeployErrors).includes(e)}isPollingErrorRecoverable(e){return e.includes("casper instance")||e.includes("storage")||e.includes("parsing")}getErrorMessageByErrorType(e){return X[e]??X[exports.FatalDeployErrors.UNKNOWN_ERROR]}constructor(){Y(this,s)}},(()=>{const o="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;t=[J],r=[J],$(e,null,t,{kind:"method",name:"parseDeploymentError",static:!1,private:!1,access:{has:e=>"parseDeploymentError"in e,get:e=>e.parseDeploymentError},metadata:o},null,s),$(e,null,r,{kind:"method",name:"isPollingErrorRecoverable",static:!1,private:!1,access:{has:e=>"isPollingErrorRecoverable"in e,get:e=>e.isPollingErrorRecoverable},metadata:o},null,s),o&&Object.defineProperty(e,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:o})})(),e})();class Z{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 Q,ee;exports.DeployStatus=void 0,(Q=exports.DeployStatus||(exports.DeployStatus={})).DEPLOYING="Deploying",Q.INCLUDED_IN_BLOCK="IncludedInBlock",Q.FINALIZED="Finalized",Q.CHECK_ERROR="CheckingError";class te{constructor(e,t){this.validatorClient=e,this.indexerClient=t}static createHttpClient(e){const t=l.create({baseURL:e.baseUrl,...e.axiosConfig});return new Z(t)}changeValidator(e){return this.validatorClient=te.createHttpClient(e),this}changeIndexer(e){return this.indexerClient=te.createHttpClient(e),this}static init(e){return te.instance=new te(this.createHttpClient(e.validator),this.createHttpClient(e.indexer)),te.instance}static isInitialized(){return void 0!==te?.instance}static getInstance(){if(!te.isInitialized())throw new Error("BlockchainGateway is not initialized. Call BlockchainGateway.init() first.");return te.instance}getValidatorClientUrl(){return this.validatorClient.getBaseUrl()??""}async submitDeploy(e){try{const t=await this.validatorClient.post("/api/deploy",e,{headers:{"Content-Type":"application/json"}});if(console.log("BlockchainGateway.submitDeploy: Deploy result:",t),"string"==typeof t){const e=/DeployId is:\s*([a-fA-F0-9]+)/.exec(t);return e?e[1]:t}return t.signature||t.deployId||t}catch(e){const t="BlockchainGateway.submitDeploy: "+this.getGatewayErrorMessage(e);throw new Error(t)}}async submitExploratoryDeploy(e){try{return await this.indexerClient.post("/api/explore-deploy",e)}catch(e){const t="BlockchainGateway.submitExploratoryDeploy: "+this.getGatewayErrorMessage(e);throw new Error(t)}}async exploreDeployData(e){try{return(await this.submitExploratoryDeploy(e)).expr}catch(e){const t="BlockchainGateway.exploreDeployData: "+this.getGatewayErrorMessage(e);throw console.error(t),new Error(t)}}async getDeploy(e){return await this.indexerClient.get(`/api/deploy/${e}`)}async isDeployFinalized(e){return e.faultTolerance>=.99}async getDeployStatus(e){try{let t;if(t=await this.getDeploy(e),!t?.blockHash)return{status:exports.DeployStatus.DEPLOYING};return{status:await this.isDeployFinalized(t)?exports.DeployStatus.FINALIZED:exports.DeployStatus.INCLUDED_IN_BLOCK}}catch(e){const t="BlockchainGateway.getDeployStatus: "+this.getGatewayErrorMessage(e);return{status:exports.DeployStatus.CHECK_ERROR,errorMessage:t}}}async getBlock(e){const t=await this.indexerClient.get(`/api/block/${e}`);return t?.blockInfo}async getLatestBlockNumber(){try{const e=await this.getLatestBlock();return e?.blockNumber??-1}catch(e){const t="BlockchainGateway.getLatestBlockNumber: "+this.getGatewayErrorMessage(e);return console.error(t),-1}}async isValidatorActive(){try{return await this.validatorClient.get("/status"),!0}catch(e){return console.error("BlockchainGateway.isValidatorActive: Node health check failed:",e),!1}}getGatewayErrorMessage(e){if(l.isAxiosError(e)){const t=e.response?.status??e.code,r=e.response?.statusText??"";return`Axios error while requesting "${e.config?.url??""}": [${t}] ${r} - ${e.message}`}return e instanceof Error?e.message:String(e)}validateBlocksResponse(e){if(!e?.length){throw new Error("BlockchainGateway.validateBlocksResponse: No blocks returned from /api/blocks endpoint")}}async getLatestBlock(){const e=await this.indexerClient.get("/api/blocks/1");return this.validateBlocksResponse(e),e[0]}}exports.WalletClientModes=void 0,(ee=exports.WalletClientModes||(exports.WalletClientModes={})).LOCAL="local",ee.MPC="mpc";const re={mode:exports.WalletClientModes.LOCAL},se=5e5,oe={phloPrice:1,useRandomNode:!0,deployValiditySeconds:80,nodeSelectionAttempts:3,deployRetries:3,deployIntervalSeconds:5,pollingIntervalSeconds:3};function ae(e,t){return function(...r){if(!te.isInitialized())throw new Error(`${t.kind} ${String(t.name)}: BlockchainGateway is not initialized. Call BlockchainGateway.init() first.`);return e.apply(this,r)}}let ne=(()=>{var e;let t,r,s=[];return e=class{constructor(e,t,r){if(this.retriesLeft=Y(this,s),this.inactiveNodesUrls=new Set,this.currentNodeUrl="",!e?.length)throw new Error("At least one node URL must be provided");this.availableNodesUrls=e,this.useRandomNode=r,this.retriesLeft=t}static initialize(t,r=oe.nodeSelectionAttempts,s=oe.useRandomNode){const o=s?Math.max(1,r):0,a=new e(t,o,s);return e.instance=a,a}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){te.getInstance().getValidatorClientUrl()!==e&&te.getInstance().changeValidator({baseUrl:e});if(!await te.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 o="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;t=[ae],r=[ae],$(e,null,t,{kind:"method",name:"connectDefaultNode",static:!1,private:!1,access:{has:e=>"connectDefaultNode"in e,get:e=>e.connectDefaultNode},metadata:o},null,s),$(e,null,r,{kind:"method",name:"connectActiveRandomNode",static:!1,private:!1,access:{has:e=>"connectActiveRandomNode"in e,get:e=>e.connectActiveRandomNode},metadata:o},null,s),o&&Object.defineProperty(e,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:o})})(),e})();const ie=127;class le{constructor(){this.buffer=[]}writeString(e,t){if(!t)return;const r=e<<3|2;this.writeInteger(r);const s=(new TextEncoder).encode(t);this.writeInteger(s.length),this.buffer.push(...Array.from(s))}writeInt64(e,t){if(!t)return;const r=e<<3;this.writeInteger(r),this.writeInteger64(t)}writeInteger(e){for(;e>ie;)this.buffer.push(e&ie|128),e>>>=7;this.buffer.push(e)}writeInteger64(e){for(;e>ie;)this.buffer.push(e&ie|128),e=Math.floor(e/128);this.buffer.push(e)}getResultBuffer(){return new Uint8Array(this.buffer)}}const{blake2bHex:ce}=n;class de{static async sign(e,t){const{wallet:r,data:s}=e;try{const e=await t();return await r.withSigningCapability(e,async e=>{const t=this.deployDataProtobufSerialize(s),r=ce(t,void 0,32),o=Uint8Array.from(Buffer.from(r,"hex")),a=await e.signDigest(o),n=e.getPublicKey();return{data:{term:s.term,timestamp:s.timestamp,phloPrice:s.phloPrice,phloLimit:s.phloLimit,validAfterBlockNumber:s.validAfterBlockNumber,shardId:s.shardId},deployer:N(n),signature:N(a),sigAlgorithm:"secp256k1"}})}catch(e){const t=`SignerService.sign: ${e.message}`;throw new Error(t)}}}de.deployDataProtobufSerialize=e=>{const{term:t,timestamp:r,phloPrice:s,phloLimit:o,validAfterBlockNumber:a,shardId:n=""}=e,i=new le;return i.writeString(2,t),i.writeInt64(3,r),i.writeInt64(7,s),i.writeInt64(8,o),i.writeInt64(10,a),i.writeString(11,n),i.getResultBuffer()};const ue=/[,\s]+/g,pe=/^\d+(?:\.\d+)?$/,ye=/(\.\d*?[1-9])0+$/,he=/\.0+$/,Ee=e=>{const t=e/h,r=e%h,s=h.toString().length-1,o=r.toString().padStart(s,"0");return`${t.toString()}.${o}`.replace(ye,"$1").replace(he,"")},ge=Ee,{blake2bHex:me}=n,fe=/[<>:"/\\|?*]/,Ie=/^[a-zA-Z0-9]+$/,we=/^[1-9A-HJ-NP-Za-km-z]+$/,Ne=`${p.coinId}${p.version}`;var Ae;exports.AddressValidationErrorCode=void 0,(Ae=exports.AddressValidationErrorCode||(exports.AddressValidationErrorCode={})).INVALID_PREFIX="INVALID_PREFIX",Ae.INVALID_LENGTH="INVALID_LENGTH",Ae.INVALID_ALPHABET="INVALID_ALPHABET",Ae.INVALID_BASE58="INVALID_BASE58",Ae.INVALID_HEX_LENGTH="INVALID_HEX_LENGTH",Ae.INVALID_CHAIN_PREFIX="INVALID_CHAIN_PREFIX",Ae.INVALID_CHECKSUM="INVALID_CHECKSUM",Ae.NON_CANONICAL="NON_CANONICAL";const ve=e=>({isValid:!1,errorCode:e}),Se=e=>{if(!e.startsWith("1111"))return ve(exports.AddressValidationErrorCode.INVALID_PREFIX);if(e.length<50||e.length>54)return ve(exports.AddressValidationErrorCode.INVALID_LENGTH);if(!Ie.test(e))return ve(exports.AddressValidationErrorCode.INVALID_ALPHABET);if(!we.test(e))return ve(exports.AddressValidationErrorCode.INVALID_BASE58);const t=N(I(e));if(80!==t.length)return ve(exports.AddressValidationErrorCode.INVALID_HEX_LENGTH);if(f(t)!==e)return ve(exports.AddressValidationErrorCode.NON_CANONICAL);const r=t.slice(0,72),s=t.slice(72);if(!r.startsWith(Ne))return ve(exports.AddressValidationErrorCode.INVALID_CHAIN_PREFIX);const o=me(w(r),void 0,32).slice(0,8);return 8!==s.length||s!==o?ve(exports.AddressValidationErrorCode.INVALID_CHECKSUM):{isValid:!0}};const De=e=>e.replace(/\\/g,"\\\\").replace(/"/g,'\\"').replace(/\n/g,"\\n").replace(/\r/g,"\\r").replace(/\t/g,"\\t");let Re=(()=>{var e;let t,r,s=[];return e=class{getBlockchainGateway(){return te.getInstance()}async transfer(e,t,r,s,o,a=5e5){try{const n=Se(e);if(!n.isValid)throw new Error(`AssetsService.transfer: Invalid 'fromAddress': ${n.errorCode??"UNKNOWN"}`);const i=Se(t);if(!i.isValid)throw new Error(`AssetsService.transfer: Invalid 'toAddress': ${i.errorCode??"UNKNOWN"}`);if(e===t)throw new Error("AssetsService.transfer: Sender and recipient addresses cannot be the same");if(r<=0n)throw new Error("AssetsService.transfer: Transfer amount must be greater than zero");const l=this.getBlockchainGateway(),c=((e,t,r)=>{if(r<=0n)throw new Error("Transfer amount must be greater than zero");const s=De(e),o=De(t),a=r.toString();return`\n new \n deployerId(\`rho:rchain:deployerId\`),\n stdout(\`rho:io:stdout\`),\n rl(\`rho:registry:lookup\`),\n ASIVaultCh,\n vaultCh,\n toVaultCh,\n asiVaultkeyCh,\n resultCh\n in {\n rl!(\`rho:rchain:asiVault\`, *ASIVaultCh) |\n for (@(_, ASIVault) <- ASIVaultCh) {\n @ASIVault!("findOrCreate", "${s}", *vaultCh) |\n @ASIVault!("findOrCreate", "${o}", *toVaultCh) |\n @ASIVault!("deployerAuthKey", *deployerId, *asiVaultkeyCh) |\n for (@(true, vault) <- vaultCh; key <- asiVaultkeyCh; @(true, toVault) <- toVaultCh) {\n @vault!("transfer", "${o}", ${a}, *key, *resultCh) |\n for (@result <- resultCh) {\n match result {\n (true, Nil) => {\n stdout!(("Transfer successful:", ${a}, "ASI"))\n }\n (false, reason) => {\n stdout!(("Transfer failed:", reason))\n }\n }\n }\n } |\n for (@(false, errorMsg) <- vaultCh) {\n stdout!(("Sender vault error:", errorMsg))\n } |\n for (@(false, errorMsg) <- toVaultCh) {\n stdout!(("Destination vault error:", errorMsg))\n }\n }\n }\n `})(e,t,r),d=await l.getLatestBlockNumber();if(-1===d)throw new Error("AssetsService.transfer: Invalid block number");const u={term:c,phloLimit:a,phloPrice:1,validAfterBlockNumber:d-1,timestamp:Date.now(),shardId:"root"},p=await de.sign({wallet:s,data:u},o);return await l.submitDeploy(p)}catch(e){const t="AssetsService.transfer: "+e.message;throw new Error(t)}}async getASIBalance(e){const t=Se(e);if(!t.isValid)throw new Error(`AssetsService.getASIBalance: Invalid address: ${t.errorCode??"UNKNOWN"}`);const r=this.getBlockchainGateway(),s=(e=>`\n new return, rl(\`rho:registry:lookup\`), ASIVaultCh, vaultCh in {\n rl!(\`rho:rchain:asiVault\`, *ASIVaultCh) |\n for (@(_, ASIVault) <- ASIVaultCh) {\n @ASIVault!("findOrCreate", "${De(e)}", *vaultCh) |\n for (@maybeVault <- vaultCh) {\n match maybeVault {\n (true, vault) => @vault!("balance", *return)\n (false, err) => return!(err)\n }\n }\n }\n }\n`)(e);try{const e=await r.exploreDeployData(s);if(e&&e.length>0){const t=e[0];if(t?.ExprInt?.data)return BigInt(t.ExprInt.data);if(t?.ExprString?.data)throw new Error("Balance check error:")}return BigInt(0)}catch(e){return BigInt(0)}}constructor(){Y(this,s)}},(()=>{const o="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;t=[ae],r=[ae],$(e,null,t,{kind:"method",name:"transfer",static:!1,private:!1,access:{has:e=>"transfer"in e,get:e=>e.transfer},metadata:o},null,s),$(e,null,r,{kind:"method",name:"getASIBalance",static:!1,private:!1,access:{has:e=>"getASIBalance"in e,get:e=>e.getASIBalance},metadata:o},null,s),o&&Object.defineProperty(e,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:o})})(),e})();class be{static async createAndEncrypt(e,t){const r=await P.encryptWithPassword(e,t);return new be(r)}static createFromEncryptedData(e){return new be(e)}static createFromStringifiedEncryptedData(e){return new be(JSON.parse(e))}constructor(e){this.encryptedSeedData=e}async decrypt(e){return await P.decryptWithPassword(this.encryptedSeedData,e)}toString(){return JSON.stringify(this.encryptedSeedData)}}var xe;exports.WalletMemoryKeys=void 0,(xe=exports.WalletMemoryKeys||(exports.WalletMemoryKeys={})).PRIVATE_KEY="private_key",xe.CRYPTO_SALT="crypto_salt",xe.CRYPTO_IV="crypto_iv",xe.CRYPTO_VERSION="crypto version";class _e{constructor(e,t,r,s,o){this.name=e,this.index=o,this.masterNodeId=s,this.address=t,this.privateKey=r,this.assets=new Map,this.isLocked=!0}static async fromPrivateKey(e,t,r,s=null,o=null){const a=H.deriveAddressFromPrivateKey(t),n=await this.encryptPrivateKey(t,r);return new _e(e,a,n,s,o)}static fromEncryptedData(e,t,r,s,o){const a=Se(t);if(!a.isValid)throw new Error(`Invalid address format: ${a.errorCode??"UNKNOWN"}`);return new _e(e,t,r,s,o)}async decrypt(e){if(!_e.unsafeRawKeyExportEnabled)throw new Error("Wallet.decrypt is disabled by default for security. Use withSigningCapability() instead.");return await this.decryptPrivateKey(e)}static enableUnsafeRawKeyExportForLegacyInterop(){_e.unsafeRawKeyExportEnabled=!0}static disableUnsafeRawKeyExport(){_e.unsafeRawKeyExportEnabled=!1}static isUnsafeRawKeyExportEnabled(){return _e.unsafeRawKeyExportEnabled}async decryptPrivateKey(e){try{const t=await P.decryptWithPassword(this.privateKey,e),r=JSON.parse(t);if(r&&"object"==typeof r&&!Array.isArray(r)){const e=Object.keys(r).sort((e,t)=>Number(e)-Number(t)).map(e=>{const t=r[e],s="string"==typeof t?Number(t):t;return"number"!=typeof s||isNaN(s)?0:s});return new Uint8Array(e)}return new Uint8Array(r)}catch(e){throw new Error("Unlock Failed: "+e?.message)}}async withSigningCapability(e,t){const r=await this.decryptPrivateKey(e);let s=!1;const o={signDigest:async e=>{if(s)throw new Error("Signing capability has expired");return await a.sign(e,r)},getPublicKey:()=>{if(s)throw new Error("Signing capability has expired");return F.getPublicKeyFromPrivateKey(r)}};try{return await t(o)}finally{s=!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 P.encryptWithPassword(JSON.stringify(e),t)}}_e.unsafeRawKeyExportEnabled=!1;class Le{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(Le.ensureBrowserEnvironment(),!this.isLocked)throw new Error("Cannot save an unlocked vault");const t=`${Le.vaultPrefix}_${e}`;localStorage.setItem(t,JSON.stringify(this.encryptedVaultData))}async lock(e){this.ensureUnlocked();const t=this.toString();this.encryptedVaultData=await P.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 P.decryptWithPassword(this.encryptedVaultData,e),{wallets:r,seeds:s}=JSON.parse(t);this.metaToWallets(r),this.metaToSeeds(s),this.isLocked=!1}isEmpty(){return this.ensureUnlocked(),0===this.wallets.size}getWallets(){return Array.from(this.wallets.values())}getWalletsCount(){return this.ensureUnlocked(),this.wallets.size}getWalletAddresses(){return this.ensureUnlocked(),Array.from(this.wallets.keys())}addWallet(e){this.ensureUnlocked(),this.wallets.set(e.getAddress(),e)}removeWallet(e){this.ensureUnlocked(),this.wallets.delete(e)}getWallet(e){return this.ensureUnlocked(),this.wallets.get(e)}hasWallet(e){return this.ensureUnlocked(),this.wallets.has(e)}hasSeed(e){return this.ensureUnlocked(),this.seeds.has(e)}metaToWallets(e){const t=new Map;Object.keys(e).forEach(r=>{const s=JSON.parse(e[r]),o=_e.fromEncryptedData(s.name,s.address,JSON.parse(s.encryptedPrivateKey),s.masterNodeId,s.index?+s.index:null);t.set(r,o)}),this.wallets=t}metaToSeeds(e){const t=new Map;Object.keys(e).forEach(r=>{const s=be.createFromStringifiedEncryptedData(e[r]);t.set(r,s)}),this.seeds=t}getSeeds(){return this.ensureUnlocked(),Array.from(this.seeds.values())}getSeed(e){return this.ensureUnlocked(),this.seeds.get(e)}addSeed(e,t){this.ensureUnlocked(),this.seeds.set(e,t)}removeSeed(e){this.ensureUnlocked(),this.seeds.delete(e)}getSeedsIds(){return this.ensureUnlocked(),Array.from(this.seeds.keys())}toString(){const e={},t={};this.ensureUnlocked();const r=this.getWalletAddresses(),s=this.getSeedsIds();return r.forEach(e=>{const r=this.getWallet(e);r&&(t[e]=r.toString())}),s.forEach(t=>{const r=this.getSeed(t);r&&(e[t]=r.toString())}),JSON.stringify({wallets:t,seeds:e})}ensureUnlocked(){if(this.isLocked)throw new Error("Attempted to access locked vault")}static ensureBrowserEnvironment(){if("undefined"==typeof window)throw new Error("getVault can only be called in a browser environment")}}Le.vaultPrefix="ASI_WALLETS_VAULT";exports.ASI_BASE_UNIT=h,exports.ASI_CHAIN_PREFIX=p,exports.ASI_COIN_TYPE=60,exports.ASI_DECIMALS=8,exports.Asset=class{constructor(e,t,r=8){this.id=e,this.name=t,this.decimals=r}getId(){return this.id}getName(){return this.name}getDecimals(){return this.decimals}},exports.AssetsService=Re,exports.AxiosHttpClient=Z,exports.BinaryWriter=le,exports.BlockchainGateway=te,exports.CryptoService=P,exports.DEFAULT_AXIOS_TIMEOUT_MS=3e4,exports.DEFAULT_BIP_44_PATH_OPTIONS=E,exports.DEFAULT_CLIENT_CONFIG=re,exports.DEFAULT_DECIMALS_AMOUNT=8,exports.DEFAULT_PHLO_LIMIT=se,exports.DEFAULT_RESUBMIT_CONFIG=oe,exports.DEFAULT_STORAGE_KEY="0",exports.DeployResubmitter=class{constructor(e,t){if(this.startSubmissionTime=0,this.config=e,this.nodeManager=ne.initialize(t,e.nodeSelectionAttempts,e.useRandomNode),this.errorHandler=new q,!te.isInitialized())throw new Error("BlockchainGateway is not initialized")}isDeployExpired(){return Date.now()-this.startSubmissionTime>=1e3*this.config.deployValiditySeconds}sleep(e){return new Promise(t=>setTimeout(t,1e3*e))}async retryDeployToOneNode(e,t,r,s){let o=this.config.deployRetries,a={success:!1};for(;o>0&&!this.isDeployExpired();){try{const o=te.getInstance(),n=await o.getLatestBlockNumber();if(-1===n)throw new Error("DeployResubmitter.retryDeployToOneNode: Invalid block number");const i={term:e,phloLimit:s||se,phloPrice:1,validAfterBlockNumber:n-1,timestamp:Date.now(),shardId:"root"},l=await de.sign({wallet:t,data:i},r),c=await o.submitDeploy(l);if("string"!=typeof c){throw new Error("Invalid deploy ID received: "+c)}return a={success:!0,deployId:c},a}catch(e){const t="DeployResubmitter.retryDeployToOneNode:"+e.message,r=this.errorHandler.parseDeploymentError(t);if(console.error(t),a.error={blockchainError:{type:r,message:t}},this.errorHandler.isDeploymentErrorFatal(r))break;o--}await this.sleep(this.config.deployIntervalSeconds)}return this.isDeployExpired()&&(a.error=a?.error||{},a.error.exceededTimeout=exports.FatalDeployErrors.DEPLOY_SUBMIT_TIMEOUT),{success:!1,error:a.error}}async retryDeployToRandomNodes(e,t,r,s){let o={success:!1};for(;!this.isDeployExpired()&&this.nodeManager.getRetriesLeft()>0&&(await this.nodeManager.connectActiveRandomNode(),o=await this.retryDeployToOneNode(e,t,r,s),!o.success)&&(this.nodeManager.deactivateCurrentNode(),o.error?.blockchainError?.type)&&!this.errorHandler.isDeploymentErrorFatal(o.error?.blockchainError?.type););return o}async pollDeployStatus(e){let t;for(;!this.isDeployExpired();){const r=await te.getInstance().getDeployStatus(e),s=r.status;if(s===exports.DeployStatus.CHECK_ERROR){const e=`DeployResubmitter.pollDeployStatus: ${"errorMessage"in r?r.errorMessage:"Unknown error"}`,s=this.errorHandler.parseDeploymentError(e);console.error(e);const o={type:s,message:e};if(this.errorHandler.isDeploymentErrorFatal(s)&&!e.includes("Bad Request"))return{success:!1,deployStatus:exports.DeployStatus.CHECK_ERROR,error:{blockchainError:o}};t=o}if(console.log("DeployResubmitter.pollDeployStatus: current deploy status:",s),s==exports.DeployStatus.INCLUDED_IN_BLOCK||s==exports.DeployStatus.FINALIZED)return{success:!0,deployStatus:r.status};await this.sleep(this.config.pollingIntervalSeconds)}return{success:!1,deployStatus:t?exports.DeployStatus.CHECK_ERROR:exports.DeployStatus.DEPLOYING,error:{...t,exceededTimeout:exports.FatalDeployErrors.BLOCK_INCLUSION_TIMEOUT}}}async resubmit(e,t,r,s){let o;if(console.log("DeployResubmitter: starting deploy submission with resubmission logic"),this.startSubmissionTime=Date.now(),this.config.useRandomNode?o=await this.retryDeployToRandomNodes(e,t,r,s):(await this.nodeManager.connectDefaultNode(),o=await this.retryDeployToOneNode(e,t,r,s)),!o.success||!o?.deployId)return o;console.log(`DeployResubmitter: deploy submitted successfully with ID: ${o.deployId}. Starting to poll for status...`);const a=await this.pollDeployStatus(o.deployId);return console.log(`DeployResubmitter: finished polling deploy status. Final status: ${a.deployStatus}, success: ${a.success}`),a}},exports.DeploymentErrorHandler=q,exports.EncryptedRecord=be,exports.FAULT_TOLERANCE_THRESHOLD=.99,exports.FeeService=m,exports.GasFee=y,exports.INVALID_BLOCK_NUMBER=-1,exports.KeyDerivationService=K,exports.KeysManager=F,exports.MAX_WALLETS_PER_ACCOUNT=20,exports.MnemonicService=V,exports.POWER_BASE=10,exports.PRIVATE_KEY_LENGTH=32,exports.ResubmitNodeManager=ne,exports.SecureStorage=class{constructor(e="storage_prefix"){if("undefined"==typeof localStorage)throw new Error("localStorage is not supported in this environment.");this.prefix=e}write(e,t){localStorage.setItem(this.createKey(e),t)}read(e){return localStorage.getItem(this.createKey(e))}delete(e){localStorage.removeItem(this.createKey(e))}has(e){return!!localStorage.getItem(this.createKey(e))}isEmpty(){return!this.getIds().length}clear(){this.getIds().forEach(e=>localStorage.removeItem(e))}getIds(){const e=[];for(let t=0;t<localStorage.length;t++){const r=localStorage.key(t);if(!r)break;r.startsWith(`${this.prefix}`)&&e.push(r)}return e}createKey(e){return`${this.prefix}_${e}`}},exports.SignerService=de,exports.Vault=Le,exports.Wallet=_e,exports.WalletsService=H,exports.arrayBufferToBase64=A,exports.base64ToArrayBuffer=v,exports.decodeBase16=w,exports.decodeBase58=I,exports.deploymentErrorMessages=X,exports.encodeBase16=N,exports.encodeBase58=f,exports.fromAtomicAmount=ge,exports.fromAtomicAmountToNumber=e=>{const t=e/h,r=e%h;return t>BigInt(Number.MAX_SAFE_INTEGER)?(console.warn("Integer part exceeds Number.MAX_SAFE_INTEGER; returning imprecise Number"),Number(Ee(e))):Number(t)+Number(r)/Number(h)},exports.fromAtomicAmountToString=Ee,exports.genRandomHex=e=>[...Array(e)].map(()=>Math.floor(16*Math.random()).toString(16)).join(""),exports.getDeploymentErrorMessage=function(e){return X[e]??"An unknown error occurred. Please try again."},exports.isAddress=e=>Se(e).isValid,exports.setupBufferPolyfill=k,exports.toAtomicAmount=e=>{const t=h.toString().length-1;if("number"==typeof e){if(!Number.isFinite(e))throw new Error("Invalid number");e=String(e)}let r=String(e).trim();if(!r.length)throw new Error("Cannot process empty amount");let s=!1;if(r.startsWith("-")&&(s=!0,r=r.slice(1)),r=r.replace(ue,""),!pe.test(r))throw new Error("Invalid amount format");const[o,a=""]=r.split("."),n=o||"0";let i=a;i.length>t&&(console.warn(`Fraction ${i} has more than allowed decimals; truncating`),i=i.slice(0,t)),i=i.padEnd(t,"0");const l=BigInt(n)*h+BigInt(i||"0");return s?-l:l},exports.validateAccountName=(e,t=30)=>e&&0!==e.trim().length?e.length>t?{isValid:!1,error:`Account name must be ${t} characters or less`}:fe.test(e)?{isValid:!1,error:"Account name contains invalid characters"}:{isValid:!0}:{isValid:!1,error:"Account name is required"},exports.validateAddress=Se;
1
+ "use strict";var e=require("bs58"),t=require("bip39"),r=require("buffer"),s=require("@noble/secp256k1"),n=require("bip32"),o=require("blakejs"),a=require("js-sha3"),i=require("axios");function l(e){return e&&e.__esModule?e:{default:e}}function c(e){if(e&&e.__esModule)return e;var t=Object.create(null);return e&&Object.keys(e).forEach(function(r){if("default"!==r){var s=Object.getOwnPropertyDescriptor(e,r);Object.defineProperty(t,r,s.get?s:{enumerable:!0,get:function(){return e[r]}})}}),t.default=e,Object.freeze(t)}var d=l(e),u=c(t),h=l(o),p=l(a),y=l(i);const f={coinId:"000000",version:"00"},g={BASE_FEE:.0025,VARIATION_RANGE:.1,LABEL:"ASI",TRANSFER:"0.0025",DEPLOY:"0.0025"},E=BigInt(10)**BigInt(8),m={coinType:60,account:0,change:0,index:0};var w;class I{}w=I,I.generateRandomGasFee=()=>{const e=2*(Math.random()-.5)*g.VARIATION_RANGE;return(g.BASE_FEE*(1+e)).toFixed(4)},I.getGasFeeAsNumber=()=>g.BASE_FEE,I.formatGasFee=e=>`${e||w.generateRandomGasFee()} ${g.LABEL}`;const A=e=>{const t=v(e);return d.default.encode(t)},N=e=>d.default.decode(e),v=e=>{const t=new Uint8Array(e.length/2);for(let r=0;r<e.length;r+=2)t[r/2]=parseInt(e.substr(r,2),16);return t},b=e=>Array.from(e,e=>e.toString(16).padStart(2,"0")).join(""),S=e=>{const t=new Uint8Array(e);let r="";for(let e=0;e<t.byteLength;e++)r+=String.fromCharCode(t[e]);return btoa(r)},D=e=>{const t=atob(e),r=new Uint8Array(t.length);for(let e=0;e<t.length;e++)r[e]=t.charCodeAt(e);return r.buffer},R=e=>BigInt("0x"+Buffer.from(e).toString("hex")),x=e=>Uint8Array.from(Buffer.from(e.toString(16).padStart(64,"0"),"hex"));var L;!function(e){e.ENCRYPT="encrypt",e.DECRYPT="decrypt",e.DERIVATION="deriveKey"}(L||(L={}));const _=2,O=12,C=16,T=256,P="AES-GCM",U="SHA-256",k="raw",B="PBKDF2",V=1e5;L.ENCRYPT,L.DECRYPT;class K{static async encryptWithPassword(e,t){const r=crypto.getRandomValues(new Uint8Array(C)),s=crypto.getRandomValues(new Uint8Array(O)),n=await this.deriveKey(t,r),o=await crypto.subtle.encrypt({name:P,iv:s},n,(new TextEncoder).encode(e));return{data:S(o),salt:S(r.buffer),iv:S(s.buffer),version:_}}static async decryptWithPassword(e,t){if(e.version!==_)throw new Error(`Unsupported version ${e.version}`);const r=new Uint8Array(D(e.salt)),s=new Uint8Array(D(e.iv)),n=await this.deriveKey(t,r),o=await crypto.subtle.decrypt({name:P,iv:s},n,D(e.data));return(new TextDecoder).decode(o)}static async deriveKey(e,t){const r=await crypto.subtle.importKey(k,(new TextEncoder).encode(e),B,!1,[L.DERIVATION]);return crypto.subtle.deriveKey({name:B,salt:new Uint8Array(t),iterations:V,hash:U},r,{name:P,length:T},!1,[L.ENCRYPT,L.DECRYPT])}}const M=()=>{"undefined"==typeof window||window.Buffer||(window.Buffer=r.Buffer)};var F;M(),exports.MnemonicStrength=void 0,(F=exports.MnemonicStrength||(exports.MnemonicStrength={}))[F.TWELVE_WORDS=128]="TWELVE_WORDS",F[F.TWENTY_FOUR_WORDS=256]="TWENTY_FOUR_WORDS";class W{static generateMnemonic(e=exports.MnemonicStrength.TWELVE_WORDS){return u.generateMnemonic(e)}static generateMnemonicArray(e=exports.MnemonicStrength.TWELVE_WORDS){return this.mnemonicToWordArray(this.generateMnemonic(e))}static isMnemonicValid(e){return u.validateMnemonic(e)}static mnemonicToWordArray(e){return e.trim().split(" ")}static wordArrayToMnemonic(e){return e.join(" ")}}
2
+ /*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */function H(e){if(!Number.isSafeInteger(e)||e<0)throw new Error("positive integer expected, got "+e)}function G(e,...t){if(!((r=e)instanceof Uint8Array||ArrayBuffer.isView(r)&&"Uint8Array"===r.constructor.name))throw new Error("Uint8Array expected");var r;if(t.length>0&&!t.includes(e.length))throw new Error("Uint8Array expected of length "+t+", got length="+e.length)}function $(e,t=!0){if(e.destroyed)throw new Error("Hash instance has been destroyed");if(t&&e.finished)throw new Error("Hash#digest() has already been called")}function Y(...e){for(let t=0;t<e.length;t++)e[t].fill(0)}function j(e){return new DataView(e.buffer,e.byteOffset,e.byteLength)}function z(e,t){return e<<32-t|e>>>t}function X(e){return"string"==typeof e&&(e=function(e){if("string"!=typeof e)throw new Error("string expected");return new Uint8Array((new TextEncoder).encode(e))}(e)),G(e),e}class J{}function q(e){const t=t=>e().update(X(t)).digest(),r=e();return t.outputLen=r.outputLen,t.blockLen=r.blockLen,t.create=()=>e(),t}function Z(e,t,r){return e&t^~e&r}function Q(e,t,r){return e&t^e&r^t&r}class ee extends J{constructor(e,t,r,s){super(),this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.blockLen=e,this.outputLen=t,this.padOffset=r,this.isLE=s,this.buffer=new Uint8Array(e),this.view=j(this.buffer)}update(e){$(this),G(e=X(e));const{view:t,buffer:r,blockLen:s}=this,n=e.length;for(let o=0;o<n;){const a=Math.min(s-this.pos,n-o);if(a===s){const t=j(e);for(;s<=n-o;o+=s)this.process(t,o);continue}r.set(e.subarray(o,o+a),this.pos),this.pos+=a,o+=a,this.pos===s&&(this.process(t,0),this.pos=0)}return this.length+=e.length,this.roundClean(),this}digestInto(e){$(this),function(e,t){G(e);const r=t.outputLen;if(e.length<r)throw new Error("digestInto() expects output buffer of length at least "+r)}(e,this),this.finished=!0;const{buffer:t,view:r,blockLen:s,isLE:n}=this;let{pos:o}=this;t[o++]=128,Y(this.buffer.subarray(o)),this.padOffset>s-o&&(this.process(r,0),o=0);for(let e=o;e<s;e++)t[e]=0;!function(e,t,r,s){if("function"==typeof e.setBigUint64)return e.setBigUint64(t,r,s);const n=BigInt(32),o=BigInt(4294967295),a=Number(r>>n&o),i=Number(r&o),l=s?4:0,c=s?0:4;e.setUint32(t+l,a,s),e.setUint32(t+c,i,s)}(r,s-8,BigInt(8*this.length),n),this.process(r,0);const a=j(e),i=this.outputLen;if(i%4)throw new Error("_sha2: outputLen should be aligned to 32bit");const l=i/4,c=this.get();if(l>c.length)throw new Error("_sha2: outputLen bigger than state");for(let e=0;e<l;e++)a.setUint32(4*e,c[e],n)}digest(){const{buffer:e,outputLen:t}=this;this.digestInto(e);const r=e.slice(0,t);return this.destroy(),r}_cloneInto(e){e||(e=new this.constructor),e.set(...this.get());const{blockLen:t,buffer:r,length:s,finished:n,destroyed:o,pos:a}=this;return e.destroyed=o,e.finished=n,e.length=s,e.pos=a,s%t&&e.buffer.set(r),e}clone(){return this._cloneInto()}}const te=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),re=Uint32Array.from([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),se=new Uint32Array(64);class ne extends ee{constructor(e=32){super(64,e,8,!1),this.A=0|te[0],this.B=0|te[1],this.C=0|te[2],this.D=0|te[3],this.E=0|te[4],this.F=0|te[5],this.G=0|te[6],this.H=0|te[7]}get(){const{A:e,B:t,C:r,D:s,E:n,F:o,G:a,H:i}=this;return[e,t,r,s,n,o,a,i]}set(e,t,r,s,n,o,a,i){this.A=0|e,this.B=0|t,this.C=0|r,this.D=0|s,this.E=0|n,this.F=0|o,this.G=0|a,this.H=0|i}process(e,t){for(let r=0;r<16;r++,t+=4)se[r]=e.getUint32(t,!1);for(let e=16;e<64;e++){const t=se[e-15],r=se[e-2],s=z(t,7)^z(t,18)^t>>>3,n=z(r,17)^z(r,19)^r>>>10;se[e]=n+se[e-7]+s+se[e-16]|0}let{A:r,B:s,C:n,D:o,E:a,F:i,G:l,H:c}=this;for(let e=0;e<64;e++){const t=c+(z(a,6)^z(a,11)^z(a,25))+Z(a,i,l)+re[e]+se[e]|0,d=(z(r,2)^z(r,13)^z(r,22))+Q(r,s,n)|0;c=l,l=i,i=a,a=o+t|0,o=n,n=s,s=r,r=t+d|0}r=r+this.A|0,s=s+this.B|0,n=n+this.C|0,o=o+this.D|0,a=a+this.E|0,i=i+this.F|0,l=l+this.G|0,c=c+this.H|0,this.set(r,s,n,o,a,i,l,c)}roundClean(){Y(se)}destroy(){this.set(0,0,0,0,0,0,0,0),Y(this.buffer)}}const oe=q(()=>new ne);class ae extends J{constructor(e,t){super(),this.finished=!1,this.destroyed=!1,function(e){if("function"!=typeof e||"function"!=typeof e.create)throw new Error("Hash should be wrapped by utils.createHasher");H(e.outputLen),H(e.blockLen)}(e);const r=X(t);if(this.iHash=e.create(),"function"!=typeof this.iHash.update)throw new Error("Expected instance of class which extends utils.Hash");this.blockLen=this.iHash.blockLen,this.outputLen=this.iHash.outputLen;const s=this.blockLen,n=new Uint8Array(s);n.set(r.length>s?e.create().update(r).digest():r);for(let e=0;e<n.length;e++)n[e]^=54;this.iHash.update(n),this.oHash=e.create();for(let e=0;e<n.length;e++)n[e]^=106;this.oHash.update(n),Y(n)}update(e){return $(this),this.iHash.update(e),this}digestInto(e){$(this),G(e,this.outputLen),this.finished=!0,this.iHash.digestInto(e),this.oHash.update(e),this.oHash.digestInto(e),this.destroy()}digest(){const e=new Uint8Array(this.oHash.outputLen);return this.digestInto(e),e}_cloneInto(e){e||(e=Object.create(Object.getPrototypeOf(this),{}));const{oHash:t,iHash:r,finished:s,destroyed:n,blockLen:o,outputLen:a}=this;return e.finished=s,e.destroyed=n,e.blockLen=o,e.outputLen=a,e.oHash=t._cloneInto(e.oHash),e.iHash=r._cloneInto(e.iHash),e}clone(){return this._cloneInto()}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}}const ie=(e,t,r)=>new ae(e,t).update(r).digest();ie.create=(e,t)=>new ae(e,t),s.utils.hmacSha256Sync=(e,...t)=>ie(oe,e,s.utils.concatBytes(...t));const le=s.CURVE.n,ce={isPoint(e){try{return s.Point.fromHex(e),!0}catch{return!1}},isPrivate(e){if(32!==e.length)return!1;const t=R(e);return t>0n&&t<le},pointFromScalar(e,t=!0){try{return s.getPublicKey(e,t)}catch{return null}},pointAddScalar(e,t,r=!0){try{const n=s.Point.fromHex(e),o=R(t),a=s.Point.BASE.multiply(o);return n.add(a).toRawBytes(r)}catch{return null}},privateAdd(e,t){const r=(R(e)+R(t))%le;return 0n===r?null:x(r)},privateNegate(e){const t=R(e);return x((le-t)%le)},sign:(e,t)=>s.signSync(e,t,{der:!1}),verify:(e,t,r)=>s.verify(r,e,t)};M();class de{static buildBip44Path({coinType:e=60,account:t=0,change:r=0,index:s=0}){return`m/44'/${e}'/${t}'/${r}/${s}`}static derivePrivateKey(e,t){const r=e.derivePath(t);if(!r.privateKey)throw new Error("No private key at derived node");return new Uint8Array(r.privateKey)}static async mnemonicToSeed(e,r=""){return"string"==typeof e?await t.mnemonicToSeed(e,r):await t.mnemonicToSeed(W.wordArrayToMnemonic(e),r)}static seedToMasterNode(e){return n.BIP32Factory(ce).fromSeed(e)}static async deriveKeyFromMnemonic(e,t=m){const r=this.buildBip44Path(t),s=await de.mnemonicToSeed(e),n=de.seedToMasterNode(s);return de.derivePrivateKey(n,r)}static async deriveNextKeyFromMnemonic(e,t,r=m){const s=t+1;return await this.deriveKeyFromMnemonic(e,{...r,index:s})}}const{randomBytes:ue,bytesToHex:he}=s.utils;class pe{static generateRandomKey(e=32){if(!e||e<0||!Number.isInteger(e))throw new Error("PrivateKeyLength must be a positive integer");return ue(e)}static generateKeyPair(e=32){if(!e||e<0||!Number.isInteger(e))throw new Error("PrivateKeyLength must be a positive integer");const t=ue(e);return{privateKey:t,publicKey:s.getPublicKey(t)}}static getKeyPairFromPrivateKey(e){return{privateKey:e,publicKey:s.getPublicKey(e)}}static getPublicKeyFromPrivateKey(e){return s.getPublicKey(e)}static convertKeyToHex(e){return he(e)}static async deriveKeyFromMnemonic(e,t){return await de.deriveKeyFromMnemonic(e,t)}static generateMpcKeyPair(){throw new Error("MPC key generation is not implemented yet.")}}const{blake2bHex:ye}=h.default,{keccak256:fe}=p.default;class ge{static createWallet(e,t){let r;r=e?pe.getKeyPairFromPrivateKey(e):pe.generateKeyPair();return{address:this.deriveAddressFromPublicKey(r.publicKey),publicKey:r.publicKey,privateKey:r.privateKey}}static async createWalletFromMnemonic(e,t){const r=e?W.mnemonicToWordArray(e):W.generateMnemonicArray(),s=W.wordArrayToMnemonic(r);if(!s||!W.isMnemonicValid(s))throw new Error("WalletsService.createWalletFromMnemonic: Recovery mnemonic is missing or invalid");const n=await de.mnemonicToSeed(r),o=de.seedToMasterNode(n),a=de.buildBip44Path({coinType:60,account:0,change:0,index:t||0}),i=de.derivePrivateKey(o,a);return{...this.createWallet(i),mnemonic:s}}static deriveAddressFromPrivateKey(e){const t=pe.getKeyPairFromPrivateKey(e);return this.deriveAddressFromPublicKey(t.publicKey)}static deriveAddressFromPublicKey(e){const t=fe(e.slice(1)),r=v(t.slice(-40)),s=fe(r),n=`${f.coinId}${f.version}${s}`,o=v(n),a=ye(o,void 0,32).slice(0,8);return A(`${n}${a}`)}}function Ee(e,t,r,s,n,o){function a(e){if(void 0!==e&&"function"!=typeof e)throw new TypeError("Function expected");return e}for(var i,l=s.kind,c="getter"===l?"get":"setter"===l?"set":"value",d=!t&&e?s.static?e:e.prototype:null,u=t||(d?Object.getOwnPropertyDescriptor(d,s.name):{}),h=!1,p=r.length-1;p>=0;p--){var y={};for(var f in s)y[f]="access"===f?{}:s[f];for(var f in s.access)y.access[f]=s.access[f];y.addInitializer=function(e){if(h)throw new TypeError("Cannot add initializers after decoration has completed");o.push(a(e||null))};var g=(0,r[p])("accessor"===l?{get:u.get,set:u.set}:u[c],y);if("accessor"===l){if(void 0===g)continue;if(null===g||"object"!=typeof g)throw new TypeError("Object expected");(i=a(g.get))&&(u.get=i),(i=a(g.set))&&(u.set=i),(i=a(g.init))&&n.unshift(i)}else(i=a(g))&&("field"===l?n.unshift(i):u[c]=i)}d&&Object.defineProperty(d,s.name,u),h=!0}function me(e,t,r){for(var s=arguments.length>2,n=0;n<t.length;n++)r=s?t[n].call(e,r):t[n].call(e);return s?r:void 0}var we,Ie;"function"==typeof SuppressedError&&SuppressedError,exports.RecoverableDeployErrors=void 0,(we=exports.RecoverableDeployErrors||(exports.RecoverableDeployErrors={})).READ_ONLY_NODE="READ_ONLY_NODE",we.CASPER_INSTANCE_UNAVAILABLE="CASPER_INSTANCE_UNAVAILABLE",we.INVALID_DEPLOY_ID="INVALID_DEPLOY_ID",we.INVALID_BLOCK_NUMBER="INVALID_BLOCK_NUMBER",exports.FatalDeployErrors=void 0,(Ie=exports.FatalDeployErrors||(exports.FatalDeployErrors={})).INSUFFICIENT_BALANCE="INSUFFICIENT_BALANCE",Ie.WRONG_NETWORK="WRONG_NETWORK",Ie.PARSING_ERROR="PARSING_ERROR",Ie.LOW_PHLO_PRICE="LOW_PHLO_PRICE",Ie.SIGNATURE_ERROR="SIGNATURE_ERROR",Ie.STORAGE_RETRIEVAL_ERROR="STORAGE_RETRIEVAL_ERROR",Ie.UNKNOWN_ERROR="UNKNOWN_ERROR",Ie.DEPLOY_SUBMIT_TIMEOUT="DEPLOY_SUBMIT_TIMEOUT",Ie.BLOCK_INCLUSION_TIMEOUT="BLOCK_INCLUSION_TIMEOUT",Ie.FINALIZATION_TIMEOUT="FINALIZATION_TIMEOUT";const Ae={[exports.RecoverableDeployErrors.READ_ONLY_NODE]:"Node is read-only. Trying another node...",[exports.RecoverableDeployErrors.CASPER_INSTANCE_UNAVAILABLE]:"Casper instance not available. Trying another node...",[exports.RecoverableDeployErrors.INVALID_DEPLOY_ID]:"Invalid deploy ID. Please try again.",[exports.RecoverableDeployErrors.INVALID_BLOCK_NUMBER]:"Invalid block number. Please try again.",[exports.FatalDeployErrors.INSUFFICIENT_BALANCE]:"Insufficient balance. Please top up your account.",[exports.FatalDeployErrors.WRONG_NETWORK]:"Wrong network. Please contact technical support.",[exports.FatalDeployErrors.PARSING_ERROR]:"Parsing error. Please contact technical support.",[exports.FatalDeployErrors.LOW_PHLO_PRICE]:"Phlo price too low. Please rebuild the transaction with a higher phlo price.",[exports.FatalDeployErrors.SIGNATURE_ERROR]:"Signature verification failed. Please try again.",[exports.FatalDeployErrors.STORAGE_RETRIEVAL_ERROR]:"Storage retrieval error. Please try again later.",[exports.FatalDeployErrors.UNKNOWN_ERROR]:"An unknown error occurred. Please try again.",[exports.FatalDeployErrors.DEPLOY_SUBMIT_TIMEOUT]:"Deploy submission timed out. Please try again.",[exports.FatalDeployErrors.BLOCK_INCLUSION_TIMEOUT]:"Deploy was not included in a block within the expected time.",[exports.FatalDeployErrors.FINALIZATION_TIMEOUT]:"Block finalization polling timed out."};function Ne(e,t){return function(...t){return"string"==typeof t[0]&&(t[0]=t[0].toLowerCase()),e.apply(this,t)}}let ve=(()=>{var e;let t,r,s=[];return e=class{parseDeploymentError(e){return e.includes("read only")?exports.RecoverableDeployErrors.READ_ONLY_NODE:e.includes("casper instance")?exports.RecoverableDeployErrors.CASPER_INSTANCE_UNAVAILABLE:e.includes("invalid deploy ID")?exports.RecoverableDeployErrors.INVALID_DEPLOY_ID:e.includes("invalid block number")?exports.RecoverableDeployErrors.INVALID_BLOCK_NUMBER:e.includes("insufficient balance")?exports.FatalDeployErrors.INSUFFICIENT_BALANCE:e.includes("wrong network")?exports.FatalDeployErrors.WRONG_NETWORK:e.includes("parsing error")?exports.FatalDeployErrors.PARSING_ERROR:e.includes("low")&&e.includes("phlo")?exports.FatalDeployErrors.LOW_PHLO_PRICE:e.includes("signature")||e.includes("sign")||e.includes("invalid signature")?exports.FatalDeployErrors.SIGNATURE_ERROR:e.includes("storage")||e.includes("retrieval")?exports.FatalDeployErrors.STORAGE_RETRIEVAL_ERROR:exports.FatalDeployErrors.UNKNOWN_ERROR}isDeploymentErrorRecoverable(e){return Object.values(exports.RecoverableDeployErrors).includes(e)}isDeploymentErrorFatal(e){return Object.values(exports.FatalDeployErrors).includes(e)}isPollingErrorRecoverable(e){return e.includes("casper instance")||e.includes("storage")||e.includes("parsing")}getErrorMessageByErrorType(e){return Ae[e]??Ae[exports.FatalDeployErrors.UNKNOWN_ERROR]}constructor(){me(this,s)}},(()=>{const n="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;t=[Ne],r=[Ne],Ee(e,null,t,{kind:"method",name:"parseDeploymentError",static:!1,private:!1,access:{has:e=>"parseDeploymentError"in e,get:e=>e.parseDeploymentError},metadata:n},null,s),Ee(e,null,r,{kind:"method",name:"isPollingErrorRecoverable",static:!1,private:!1,access:{has:e=>"isPollingErrorRecoverable"in e,get:e=>e.isPollingErrorRecoverable},metadata:n},null,s),n&&Object.defineProperty(e,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:n})})(),e})();class be{constructor(e){this.client=e}async get(e){return(await this.client.get(e)).data}async post(e,t){return(await this.client.post(e,t)).data}getBaseUrl(){return this.client.defaults.baseURL}}var Se,De;exports.DeployStatus=void 0,(Se=exports.DeployStatus||(exports.DeployStatus={})).DEPLOYING="Deploying",Se.INCLUDED_IN_BLOCK="IncludedInBlock",Se.FINALIZED="Finalized",Se.CHECK_ERROR="CheckingError";class Re{constructor(e,t){this.validatorClient=e,this.indexerClient=t}static createHttpClient(e){const t=y.default.create({baseURL:e.baseUrl,...e.axiosConfig});return new be(t)}changeValidator(e){return this.validatorClient=Re.createHttpClient(e),this}changeIndexer(e){return this.indexerClient=Re.createHttpClient(e),this}static init(e){return Re.instance=new Re(this.createHttpClient(e.validator),this.createHttpClient(e.indexer)),Re.instance}static isInitialized(){return void 0!==Re?.instance}static getInstance(){if(!Re.isInitialized())throw new Error("BlockchainGateway is not initialized. Call BlockchainGateway.init() first.");return Re.instance}getValidatorClientUrl(){return this.validatorClient.getBaseUrl()??""}async submitDeploy(e){try{const t=await this.validatorClient.post("/api/deploy",e,{headers:{"Content-Type":"application/json"}});if(console.log("BlockchainGateway.submitDeploy: Deploy result:",t),"string"==typeof t){const e=/DeployId is:\s*([a-fA-F0-9]+)/.exec(t);return e?e[1]:t}return t.signature||t.deployId||t}catch(e){const t="BlockchainGateway.submitDeploy: "+this.getGatewayErrorMessage(e);throw new Error(t)}}async submitExploratoryDeploy(e){try{return await this.indexerClient.post("/api/explore-deploy",e)}catch(e){const t="BlockchainGateway.submitExploratoryDeploy: "+this.getGatewayErrorMessage(e);throw new Error(t)}}async exploreDeployData(e){try{return(await this.submitExploratoryDeploy(e)).expr}catch(e){const t="BlockchainGateway.exploreDeployData: "+this.getGatewayErrorMessage(e);throw console.error(t),new Error(t)}}async getDeploy(e){return await this.indexerClient.get(`/api/deploy/${e}`)}async isDeployFinalized(e){return e.faultTolerance>=.99}async getDeployStatus(e){try{let t;if(t=await this.getDeploy(e),!t?.blockHash)return{status:exports.DeployStatus.DEPLOYING};return{status:await this.isDeployFinalized(t)?exports.DeployStatus.FINALIZED:exports.DeployStatus.INCLUDED_IN_BLOCK}}catch(e){const t="BlockchainGateway.getDeployStatus: "+this.getGatewayErrorMessage(e);return{status:exports.DeployStatus.CHECK_ERROR,errorMessage:t}}}async getBlock(e){const t=await this.indexerClient.get(`/api/block/${e}`);return t?.blockInfo}async getLatestBlockNumber(){try{const e=await this.getLatestBlock();return e?.blockNumber??-1}catch(e){const t="BlockchainGateway.getLatestBlockNumber: "+this.getGatewayErrorMessage(e);return console.error(t),-1}}async isValidatorActive(){try{return await this.validatorClient.get("/status"),!0}catch(e){return console.error("BlockchainGateway.isValidatorActive: Node health check failed:",e),!1}}getGatewayErrorMessage(e){if(y.default.isAxiosError(e)){const t=e.response?.status??e.code,r=e.response?.statusText??"";return`Axios error while requesting "${e.config?.url??""}": [${t}] ${r} - ${e.message}`}return e instanceof Error?e.message:String(e)}validateBlocksResponse(e){if(!e?.length){throw new Error("BlockchainGateway.validateBlocksResponse: No blocks returned from /api/blocks endpoint")}}async getLatestBlock(){const e=await this.indexerClient.get("/api/blocks/1");return this.validateBlocksResponse(e),e[0]}}exports.WalletClientModes=void 0,(De=exports.WalletClientModes||(exports.WalletClientModes={})).LOCAL="local",De.MPC="mpc";const xe={mode:exports.WalletClientModes.LOCAL},Le=5e5,_e={phloPrice:1,useRandomNode:!0,deployValiditySeconds:80,nodeSelectionAttempts:3,deployRetries:3,deployIntervalSeconds:5,pollingIntervalSeconds:3};function Oe(e,t){return function(...r){if(!Re.isInitialized())throw new Error(`${t.kind} ${String(t.name)}: BlockchainGateway is not initialized. Call BlockchainGateway.init() first.`);return e.apply(this,r)}}let Ce=(()=>{var e;let t,r,s=[];return e=class{constructor(e,t,r){if(this.retriesLeft=me(this,s),this.inactiveNodesUrls=new Set,this.currentNodeUrl="",!e?.length)throw new Error("At least one node URL must be provided");this.availableNodesUrls=e,this.useRandomNode=r,this.retriesLeft=t}static initialize(t,r=_e.nodeSelectionAttempts,s=_e.useRandomNode){const n=s?Math.max(1,r):0,o=new e(t,n,s);return e.instance=o,o}async connectDefaultNode(){if(this.useRandomNode)throw new Error("NodeManager.connectDefaultNode: Random node selection is enabled, cannot connect to default node");await this.connectNode(this.availableNodesUrls[0])}async connectNode(e){Re.getInstance().getValidatorClientUrl()!==e&&Re.getInstance().changeValidator({baseUrl:e});if(!await Re.getInstance().isValidatorActive()){this.deactivateNode(e);const t=`NodeManager.connectNode: Node ${e} is not active`;throw console.error(t),new Error(t)}this.currentNodeUrl=e}static getInstance(){if(!e.instance)throw new Error("NodeManager is not initialized. Call NodeManager.initialize() first.");return e.instance}isInitialized(){return!!this.currentNodeUrl}markNodeInactive(e){this.inactiveNodesUrls.add(e)}deactivateCurrentNode(){this.isInitialized()&&this.deactivateNode(this.currentNodeUrl)}deactivateNode(e){this.retriesLeft--,this.markNodeInactive(e),this.currentNodeUrl===e&&(this.currentNodeUrl="")}getAvailableNodesUrls(){return this.availableNodesUrls.filter(e=>!this.inactiveNodesUrls.has(e))}getRetriesLeft(){return this.retriesLeft}getRandomAvailableNodeUrl(){const e=this.getAvailableNodesUrls();if(!e?.length)throw console.error("NodeManager.getRandomAvailableNodeUrl: No available node URLs to select"),new Error("NodeManager: no available node URLs");return e[Math.floor(Math.random()*e.length)]}async connectActiveRandomNode(){if(!this.useRandomNode)throw new Error("NodeManager.connectActiveRandomNode: Random node selection is disabled, connect to default node");for(;this.retriesLeft>0;){const e=this.getRandomAvailableNodeUrl();if(console.log(`NodeManager.connectActiveRandomNode: Attempting to connect to node ${e}. Retries left: ${this.retriesLeft}`),e){try{await this.connectNode(e)}catch(e){continue}return}}throw new Error("NodeManager.connectActiveRandomNode: No active node URL found after all attempts")}},(()=>{const n="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;t=[Oe],r=[Oe],Ee(e,null,t,{kind:"method",name:"connectDefaultNode",static:!1,private:!1,access:{has:e=>"connectDefaultNode"in e,get:e=>e.connectDefaultNode},metadata:n},null,s),Ee(e,null,r,{kind:"method",name:"connectActiveRandomNode",static:!1,private:!1,access:{has:e=>"connectActiveRandomNode"in e,get:e=>e.connectActiveRandomNode},metadata:n},null,s),n&&Object.defineProperty(e,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:n})})(),e})();const Te=127;class Pe{constructor(){this.buffer=[]}writeString(e,t){if(!t)return;const r=e<<3|2;this.writeInteger(r);const s=(new TextEncoder).encode(t);this.writeInteger(s.length),this.buffer.push(...Array.from(s))}writeInt64(e,t){if(!t)return;const r=e<<3;this.writeInteger(r),this.writeInteger64(t)}writeInteger(e){for(;e>Te;)this.buffer.push(e&Te|128),e>>>=7;this.buffer.push(e)}writeInteger64(e){for(;e>Te;)this.buffer.push(e&Te|128),e=Math.floor(e/128);this.buffer.push(e)}getResultBuffer(){return new Uint8Array(this.buffer)}}const{blake2bHex:Ue}=h.default;class ke{static async sign(e,t){const{wallet:r,data:s}=e;try{const e=await t();return await r.withSigningCapability(e,async e=>{const t=this.deployDataProtobufSerialize(s),r=Ue(t,void 0,32),n=Uint8Array.from(Buffer.from(r,"hex")),o=await e.signDigest(n),a=e.getPublicKey();return{data:{term:s.term,timestamp:s.timestamp,phloPrice:s.phloPrice,phloLimit:s.phloLimit,validAfterBlockNumber:s.validAfterBlockNumber,shardId:s.shardId},deployer:b(a),signature:b(o),sigAlgorithm:"secp256k1"}})}catch(e){const t=`SignerService.sign: ${e.message}`;throw new Error(t)}}}ke.deployDataProtobufSerialize=e=>{const{term:t,timestamp:r,phloPrice:s,phloLimit:n,validAfterBlockNumber:o,shardId:a=""}=e,i=new Pe;return i.writeString(2,t),i.writeInt64(3,r),i.writeInt64(7,s),i.writeInt64(8,n),i.writeInt64(10,o),i.writeString(11,a),i.getResultBuffer()};const Be=/[,\s]+/g,Ve=/^\d+(?:\.\d+)?$/,Ke=/(\.\d*?[1-9])0+$/,Me=/\.0+$/,Fe=e=>{const t=e/E,r=e%E,s=E.toString().length-1,n=r.toString().padStart(s,"0");return`${t.toString()}.${n}`.replace(Ke,"$1").replace(Me,"")},We=Fe,{blake2bHex:He}=h.default,Ge=/[<>:"/\\|?*]/,$e=/^[a-zA-Z0-9]+$/,Ye=/^[1-9A-HJ-NP-Za-km-z]+$/,je=`${f.coinId}${f.version}`;var ze;exports.AddressValidationErrorCode=void 0,(ze=exports.AddressValidationErrorCode||(exports.AddressValidationErrorCode={})).INVALID_PREFIX="INVALID_PREFIX",ze.INVALID_LENGTH="INVALID_LENGTH",ze.INVALID_ALPHABET="INVALID_ALPHABET",ze.INVALID_BASE58="INVALID_BASE58",ze.INVALID_HEX_LENGTH="INVALID_HEX_LENGTH",ze.INVALID_CHAIN_PREFIX="INVALID_CHAIN_PREFIX",ze.INVALID_CHECKSUM="INVALID_CHECKSUM",ze.NON_CANONICAL="NON_CANONICAL";const Xe=e=>({isValid:!1,errorCode:e}),Je=e=>{if(!e.startsWith("1111"))return Xe(exports.AddressValidationErrorCode.INVALID_PREFIX);if(e.length<50||e.length>54)return Xe(exports.AddressValidationErrorCode.INVALID_LENGTH);if(!$e.test(e))return Xe(exports.AddressValidationErrorCode.INVALID_ALPHABET);if(!Ye.test(e))return Xe(exports.AddressValidationErrorCode.INVALID_BASE58);const t=b(N(e));if(80!==t.length)return Xe(exports.AddressValidationErrorCode.INVALID_HEX_LENGTH);if(A(t)!==e)return Xe(exports.AddressValidationErrorCode.NON_CANONICAL);const r=t.slice(0,72),s=t.slice(72);if(!r.startsWith(je))return Xe(exports.AddressValidationErrorCode.INVALID_CHAIN_PREFIX);const n=He(v(r),void 0,32).slice(0,8);return 8!==s.length||s!==n?Xe(exports.AddressValidationErrorCode.INVALID_CHECKSUM):{isValid:!0}};const qe=e=>e.replace(/\\/g,"\\\\").replace(/"/g,'\\"').replace(/\n/g,"\\n").replace(/\r/g,"\\r").replace(/\t/g,"\\t");let Ze=(()=>{var e;let t,r,s=[];return e=class{getBlockchainGateway(){return Re.getInstance()}async transfer(e,t,r,s,n,o=5e5){try{const a=Je(e);if(!a.isValid)throw new Error(`AssetsService.transfer: Invalid 'fromAddress': ${a.errorCode??"UNKNOWN"}`);const i=Je(t);if(!i.isValid)throw new Error(`AssetsService.transfer: Invalid 'toAddress': ${i.errorCode??"UNKNOWN"}`);if(e===t)throw new Error("AssetsService.transfer: Sender and recipient addresses cannot be the same");if(r<=0n)throw new Error("AssetsService.transfer: Transfer amount must be greater than zero");const l=this.getBlockchainGateway(),c=((e,t,r)=>{if(r<=0n)throw new Error("Transfer amount must be greater than zero");const s=qe(e),n=qe(t),o=r.toString();return`\n new \n deployerId(\`rho:rchain:deployerId\`),\n stdout(\`rho:io:stdout\`),\n rl(\`rho:registry:lookup\`),\n ASIVaultCh,\n vaultCh,\n toVaultCh,\n asiVaultkeyCh,\n resultCh\n in {\n rl!(\`rho:rchain:asiVault\`, *ASIVaultCh) |\n for (@(_, ASIVault) <- ASIVaultCh) {\n @ASIVault!("findOrCreate", "${s}", *vaultCh) |\n @ASIVault!("findOrCreate", "${n}", *toVaultCh) |\n @ASIVault!("deployerAuthKey", *deployerId, *asiVaultkeyCh) |\n for (@(true, vault) <- vaultCh; key <- asiVaultkeyCh; @(true, toVault) <- toVaultCh) {\n @vault!("transfer", "${n}", ${o}, *key, *resultCh) |\n for (@result <- resultCh) {\n match result {\n (true, Nil) => {\n stdout!(("Transfer successful:", ${o}, "ASI"))\n }\n (false, reason) => {\n stdout!(("Transfer failed:", reason))\n }\n }\n }\n } |\n for (@(false, errorMsg) <- vaultCh) {\n stdout!(("Sender vault error:", errorMsg))\n } |\n for (@(false, errorMsg) <- toVaultCh) {\n stdout!(("Destination vault error:", errorMsg))\n }\n }\n }\n `})(e,t,r),d=await l.getLatestBlockNumber();if(-1===d)throw new Error("AssetsService.transfer: Invalid block number");const u={term:c,phloLimit:o,phloPrice:1,validAfterBlockNumber:d-1,timestamp:Date.now(),shardId:"root"},h=await ke.sign({wallet:s,data:u},n);return await l.submitDeploy(h)}catch(e){const t="AssetsService.transfer: "+e.message;throw new Error(t)}}async getASIBalance(e){const t=Je(e);if(!t.isValid)throw new Error(`AssetsService.getASIBalance: Invalid address: ${t.errorCode??"UNKNOWN"}`);const r=this.getBlockchainGateway(),s=(e=>`\n new return, rl(\`rho:registry:lookup\`), ASIVaultCh, vaultCh in {\n rl!(\`rho:rchain:asiVault\`, *ASIVaultCh) |\n for (@(_, ASIVault) <- ASIVaultCh) {\n @ASIVault!("findOrCreate", "${qe(e)}", *vaultCh) |\n for (@maybeVault <- vaultCh) {\n match maybeVault {\n (true, vault) => @vault!("balance", *return)\n (false, err) => return!(err)\n }\n }\n }\n }\n`)(e);try{const e=await r.exploreDeployData(s);if(e&&e.length>0){const t=e[0];if(t?.ExprInt?.data)return BigInt(t.ExprInt.data);if(t?.ExprString?.data)throw new Error("Balance check error:")}return BigInt(0)}catch(e){return BigInt(0)}}constructor(){me(this,s)}},(()=>{const n="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;t=[Oe],r=[Oe],Ee(e,null,t,{kind:"method",name:"transfer",static:!1,private:!1,access:{has:e=>"transfer"in e,get:e=>e.transfer},metadata:n},null,s),Ee(e,null,r,{kind:"method",name:"getASIBalance",static:!1,private:!1,access:{has:e=>"getASIBalance"in e,get:e=>e.getASIBalance},metadata:n},null,s),n&&Object.defineProperty(e,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:n})})(),e})();class Qe{static async createAndEncrypt(e,t){const r=await K.encryptWithPassword(e,t);return new Qe(r)}static createFromEncryptedData(e){return new Qe(e)}static createFromStringifiedEncryptedData(e){return new Qe(JSON.parse(e))}constructor(e){this.encryptedSeedData=e}async decrypt(e){return await K.decryptWithPassword(this.encryptedSeedData,e)}toString(){return JSON.stringify(this.encryptedSeedData)}}var et;exports.WalletMemoryKeys=void 0,(et=exports.WalletMemoryKeys||(exports.WalletMemoryKeys={})).PRIVATE_KEY="private_key",et.CRYPTO_SALT="crypto_salt",et.CRYPTO_IV="crypto_iv",et.CRYPTO_VERSION="crypto version";class tt{constructor(e,t,r,s,n){this.name=e,this.index=n,this.masterNodeId=s,this.address=t,this.privateKey=r,this.assets=new Map,this.isLocked=!0}static async fromPrivateKey(e,t,r,s=null,n=null){const o=ge.deriveAddressFromPrivateKey(t),a=await this.encryptPrivateKey(t,r);return new tt(e,o,a,s,n)}static fromEncryptedData(e,t,r,s,n){const o=Je(t);if(!o.isValid)throw new Error(`Invalid address format: ${o.errorCode??"UNKNOWN"}`);return new tt(e,t,r,s,n)}async decrypt(e){if(!tt.unsafeRawKeyExportEnabled)throw new Error("Wallet.decrypt is disabled by default for security. Use withSigningCapability() instead.");return await this.decryptPrivateKey(e)}static enableUnsafeRawKeyExportForLegacyInterop(){tt.unsafeRawKeyExportEnabled=!0}static disableUnsafeRawKeyExport(){tt.unsafeRawKeyExportEnabled=!1}static isUnsafeRawKeyExportEnabled(){return tt.unsafeRawKeyExportEnabled}async decryptPrivateKey(e){try{const t=await K.decryptWithPassword(this.privateKey,e),r=JSON.parse(t);if(r&&"object"==typeof r&&!Array.isArray(r)){const e=Object.keys(r).sort((e,t)=>Number(e)-Number(t)).map(e=>{const t=r[e],s="string"==typeof t?Number(t):t;return"number"!=typeof s||isNaN(s)?0:s});return new Uint8Array(e)}return new Uint8Array(r)}catch(e){throw new Error("Unlock Failed: "+e?.message)}}async withSigningCapability(e,t){const r=await this.decryptPrivateKey(e);let n=!1;const o={signDigest:async e=>{if(n)throw new Error("Signing capability has expired");return await s.sign(e,r)},getPublicKey:()=>{if(n)throw new Error("Signing capability has expired");return pe.getPublicKeyFromPrivateKey(r)}};try{return await t(o)}finally{n=!0,r.fill(0)}}getEncryptedPrivateKey(){return this.privateKey}registerAsset(e){this.assets.set(e.getId(),e)}getAddress(){return this.address}getName(){return this.name}getIndex(){return this.index}getAssets(){return this.assets}isWalletLocked(){return this.isLocked}toString(){const e={name:this.name,address:this.address,encryptedPrivateKey:JSON.stringify(this.privateKey),masterNodeId:this.masterNodeId??"",index:this.index?.toString()??""};return JSON.stringify(e)}static async encryptPrivateKey(e,t){return await K.encryptWithPassword(JSON.stringify(e),t)}}tt.unsafeRawKeyExportEnabled=!1;class rt{constructor(e){if("undefined"==typeof window)throw new Error("getVault can only be called in a browser environment");if(this.isLocked=!1,this.wallets=new Map,this.seeds=new Map,this.encryptedVaultData=null,!e)return;const t=JSON.parse(e);this.encryptedVaultData=t,this.isLocked=!0}static getSavedVaultKeys(){this.ensureBrowserEnvironment();const e=[];for(let t=0;t<localStorage.length;t++){const r=localStorage.key(t);r&&r.startsWith(this.vaultPrefix)&&e.push(r)}return e}static getVaultDataFromStorage(e){return this.ensureBrowserEnvironment(),localStorage.getItem(e)}isVaultLocked(){return this.isLocked}save(e="0"){if(rt.ensureBrowserEnvironment(),!this.isLocked)throw new Error("Cannot save an unlocked vault");const t=`${rt.vaultPrefix}_${e}`;localStorage.setItem(t,JSON.stringify(this.encryptedVaultData))}async lock(e){this.ensureUnlocked();const t=this.toString();this.encryptedVaultData=await K.encryptWithPassword(t,e),this.wallets=new Map,this.seeds=new Map,this.isLocked=!0}async unlock(e){if(!this.isLocked)return;if(!this.encryptedVaultData)throw new Error("Vault was unlocked on undefined encryptedVaultData");const t=await K.decryptWithPassword(this.encryptedVaultData,e),{wallets:r,seeds:s}=JSON.parse(t);this.metaToWallets(r),this.metaToSeeds(s),this.isLocked=!1}isEmpty(){return this.ensureUnlocked(),0===this.wallets.size}getWallets(){return Array.from(this.wallets.values())}getWalletsCount(){return this.ensureUnlocked(),this.wallets.size}getWalletAddresses(){return this.ensureUnlocked(),Array.from(this.wallets.keys())}addWallet(e){this.ensureUnlocked(),this.wallets.set(e.getAddress(),e)}removeWallet(e){this.ensureUnlocked(),this.wallets.delete(e)}getWallet(e){return this.ensureUnlocked(),this.wallets.get(e)}hasWallet(e){return this.ensureUnlocked(),this.wallets.has(e)}hasSeed(e){return this.ensureUnlocked(),this.seeds.has(e)}metaToWallets(e){const t=new Map;Object.keys(e).forEach(r=>{const s=JSON.parse(e[r]),n=tt.fromEncryptedData(s.name,s.address,JSON.parse(s.encryptedPrivateKey),s.masterNodeId,s.index?+s.index:null);t.set(r,n)}),this.wallets=t}metaToSeeds(e){const t=new Map;Object.keys(e).forEach(r=>{const s=Qe.createFromStringifiedEncryptedData(e[r]);t.set(r,s)}),this.seeds=t}getSeeds(){return this.ensureUnlocked(),Array.from(this.seeds.values())}getSeed(e){return this.ensureUnlocked(),this.seeds.get(e)}addSeed(e,t){this.ensureUnlocked(),this.seeds.set(e,t)}removeSeed(e){this.ensureUnlocked(),this.seeds.delete(e)}getSeedsIds(){return this.ensureUnlocked(),Array.from(this.seeds.keys())}toString(){const e={},t={};this.ensureUnlocked();const r=this.getWalletAddresses(),s=this.getSeedsIds();return r.forEach(e=>{const r=this.getWallet(e);r&&(t[e]=r.toString())}),s.forEach(t=>{const r=this.getSeed(t);r&&(e[t]=r.toString())}),JSON.stringify({wallets:t,seeds:e})}ensureUnlocked(){if(this.isLocked)throw new Error("Attempted to access locked vault")}static ensureBrowserEnvironment(){if("undefined"==typeof window)throw new Error("getVault can only be called in a browser environment")}}rt.vaultPrefix="ASI_WALLETS_VAULT";class st{constructor(e){this.vault=e}static async create(e={}){const t=e.vault||new rt;if(t.isVaultLocked()){if(!e.password)throw new Error("Vault is locked. Please provide a password to unlock it.");await t.unlock(e.password)}return new st(t)}async createWallet(e,t,r){const s=await tt.fromPrivateKey(e,t,r);return this.vault.addWallet(s),s}selectActiveWallet(e){return!!this.vault.hasWallet(e)&&(this.activeWalletAddress=e,!0)}getActiveWallet(){if(this.activeWalletAddress)return this.vault.getWallet(this.activeWalletAddress)}getWallets(){return this.vault.getWallets()}}exports.ASI_BASE_UNIT=E,exports.ASI_CHAIN_PREFIX=f,exports.ASI_COIN_TYPE=60,exports.ASI_DECIMALS=8,exports.Asset=class{constructor(e,t,r=8){this.id=e,this.name=t,this.decimals=r}getId(){return this.id}getName(){return this.name}getDecimals(){return this.decimals}},exports.AssetsService=Ze,exports.AxiosHttpClient=be,exports.BinaryWriter=Pe,exports.BlockchainGateway=Re,exports.Client=st,exports.CryptoService=K,exports.DEFAULT_AXIOS_TIMEOUT_MS=3e4,exports.DEFAULT_BIP_44_PATH_OPTIONS=m,exports.DEFAULT_CLIENT_CONFIG=xe,exports.DEFAULT_DECIMALS_AMOUNT=8,exports.DEFAULT_PHLO_LIMIT=Le,exports.DEFAULT_RESUBMIT_CONFIG=_e,exports.DEFAULT_STORAGE_KEY="0",exports.DeployResubmitter=class{constructor(e,t){if(this.startSubmissionTime=0,this.config=e,this.nodeManager=Ce.initialize(t,e.nodeSelectionAttempts,e.useRandomNode),this.errorHandler=new ve,!Re.isInitialized())throw new Error("BlockchainGateway is not initialized")}isDeployExpired(){return Date.now()-this.startSubmissionTime>=1e3*this.config.deployValiditySeconds}sleep(e){return new Promise(t=>setTimeout(t,1e3*e))}async retryDeployToOneNode(e,t,r,s){let n=this.config.deployRetries,o={success:!1};for(;n>0&&!this.isDeployExpired();){try{const n=Re.getInstance(),a=await n.getLatestBlockNumber();if(-1===a)throw new Error("DeployResubmitter.retryDeployToOneNode: Invalid block number");const i={term:e,phloLimit:s||Le,phloPrice:1,validAfterBlockNumber:a-1,timestamp:Date.now(),shardId:"root"},l=await ke.sign({wallet:t,data:i},r),c=await n.submitDeploy(l);if("string"!=typeof c){throw new Error("Invalid deploy ID received: "+c)}return o={success:!0,deployId:c},o}catch(e){const t="DeployResubmitter.retryDeployToOneNode:"+e.message,r=this.errorHandler.parseDeploymentError(t);if(console.error(t),o.error={blockchainError:{type:r,message:t}},this.errorHandler.isDeploymentErrorFatal(r))break;n--}await this.sleep(this.config.deployIntervalSeconds)}return this.isDeployExpired()&&(o.error=o?.error||{},o.error.exceededTimeout=exports.FatalDeployErrors.DEPLOY_SUBMIT_TIMEOUT),{success:!1,error:o.error}}async retryDeployToRandomNodes(e,t,r,s){let n={success:!1};for(;!this.isDeployExpired()&&this.nodeManager.getRetriesLeft()>0&&(await this.nodeManager.connectActiveRandomNode(),n=await this.retryDeployToOneNode(e,t,r,s),!n.success)&&(this.nodeManager.deactivateCurrentNode(),n.error?.blockchainError?.type)&&!this.errorHandler.isDeploymentErrorFatal(n.error?.blockchainError?.type););return n}async pollDeployStatus(e){let t;for(;!this.isDeployExpired();){const r=await Re.getInstance().getDeployStatus(e),s=r.status;if(s===exports.DeployStatus.CHECK_ERROR){const e=`DeployResubmitter.pollDeployStatus: ${"errorMessage"in r?r.errorMessage:"Unknown error"}`,s=this.errorHandler.parseDeploymentError(e);console.error(e);const n={type:s,message:e};if(this.errorHandler.isDeploymentErrorFatal(s)&&!e.includes("Bad Request"))return{success:!1,deployStatus:exports.DeployStatus.CHECK_ERROR,error:{blockchainError:n}};t=n}if(console.log("DeployResubmitter.pollDeployStatus: current deploy status:",s),s==exports.DeployStatus.INCLUDED_IN_BLOCK||s==exports.DeployStatus.FINALIZED)return{success:!0,deployStatus:r.status};await this.sleep(this.config.pollingIntervalSeconds)}return{success:!1,deployStatus:t?exports.DeployStatus.CHECK_ERROR:exports.DeployStatus.DEPLOYING,error:{...t,exceededTimeout:exports.FatalDeployErrors.BLOCK_INCLUSION_TIMEOUT}}}async resubmit(e,t,r,s){let n;if(console.log("DeployResubmitter: starting deploy submission with resubmission logic"),this.startSubmissionTime=Date.now(),this.config.useRandomNode?n=await this.retryDeployToRandomNodes(e,t,r,s):(await this.nodeManager.connectDefaultNode(),n=await this.retryDeployToOneNode(e,t,r,s)),!n.success||!n?.deployId)return n;console.log(`DeployResubmitter: deploy submitted successfully with ID: ${n.deployId}. Starting to poll for status...`);const o=await this.pollDeployStatus(n.deployId);return console.log(`DeployResubmitter: finished polling deploy status. Final status: ${o.deployStatus}, success: ${o.success}`),o}},exports.DeploymentErrorHandler=ve,exports.EncryptedRecord=Qe,exports.FAULT_TOLERANCE_THRESHOLD=.99,exports.FeeService=I,exports.GasFee=g,exports.HEX_BYTE_PADDING=64,exports.HEX_RADIX=16,exports.INVALID_BLOCK_NUMBER=-1,exports.KeyDerivationService=de,exports.KeysManager=pe,exports.MAX_WALLETS_PER_ACCOUNT=20,exports.MnemonicService=W,exports.POWER_BASE=10,exports.PRIVATE_KEY_LENGTH=32,exports.ResubmitNodeManager=Ce,exports.SecureStorage=class{constructor(e="storage_prefix"){if("undefined"==typeof localStorage)throw new Error("localStorage is not supported in this environment.");this.prefix=e}write(e,t){localStorage.setItem(this.createKey(e),t)}read(e){return localStorage.getItem(this.createKey(e))}delete(e){localStorage.removeItem(this.createKey(e))}has(e){return!!localStorage.getItem(this.createKey(e))}isEmpty(){return!this.getIds().length}clear(){this.getIds().forEach(e=>localStorage.removeItem(e))}getIds(){const e=[];for(let t=0;t<localStorage.length;t++){const r=localStorage.key(t);if(!r)break;r.startsWith(`${this.prefix}`)&&e.push(r)}return e}createKey(e){return`${this.prefix}_${e}`}},exports.SignerService=ke,exports.Vault=rt,exports.Wallet=tt,exports.WalletsService=ge,exports.arrayBufferToBase64=S,exports.base64ToArrayBuffer=D,exports.bigIntToBuffer=x,exports.bufferToBigInt=R,exports.decodeBase16=v,exports.decodeBase58=N,exports.deploymentErrorMessages=Ae,exports.encodeBase16=b,exports.encodeBase58=A,exports.fromAtomicAmount=We,exports.fromAtomicAmountToNumber=e=>{const t=e/E,r=e%E;return t>BigInt(Number.MAX_SAFE_INTEGER)?(console.warn("Integer part exceeds Number.MAX_SAFE_INTEGER; returning imprecise Number"),Number(Fe(e))):Number(t)+Number(r)/Number(E)},exports.fromAtomicAmountToString=Fe,exports.genRandomHex=e=>[...Array(e)].map(()=>Math.floor(16*Math.random()).toString(16)).join(""),exports.getDeploymentErrorMessage=function(e){return Ae[e]??"An unknown error occurred. Please try again."},exports.isAddress=e=>Je(e).isValid,exports.setupBufferPolyfill=M,exports.toAtomicAmount=e=>{const t=E.toString().length-1;if("number"==typeof e){if(!Number.isFinite(e))throw new Error("Invalid number");e=String(e)}let r=String(e).trim();if(!r.length)throw new Error("Cannot process empty amount");let s=!1;if(r.startsWith("-")&&(s=!0,r=r.slice(1)),r=r.replace(Be,""),!Ve.test(r))throw new Error("Invalid amount format");const[n,o=""]=r.split("."),a=n||"0";let i=o;i.length>t&&(console.warn(`Fraction ${i} has more than allowed decimals; truncating`),i=i.slice(0,t)),i=i.padEnd(t,"0");const l=BigInt(a)*E+BigInt(i||"0");return s?-l:l},exports.validateAccountName=(e,t=30)=>e&&0!==e.trim().length?e.length>t?{isValid:!1,error:`Account name must be ${t} characters or less`}:Ge.test(e)?{isValid:!1,error:"Account name contains invalid characters"}:{isValid:!0}:{isValid:!1,error:"Account name is required"},exports.validateAddress=Je;
2
3
  //# sourceMappingURL=index.cjs.map