@asichain/asi-wallet-sdk 0.1.3 → 0.1.5
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 +0 -1
- package/dist/index.cjs +3 -0
- package/dist/index.cjs.map +1 -0
- package/dist/index.d.ts +21 -2
- package/dist/index.esm.js +2 -1
- package/dist/index.esm.js.map +1 -1
- package/package.json +12 -10
- package/dist/config/index.d.ts +0 -15
- package/dist/domains/Asset/index.d.ts +0 -12
- package/dist/domains/BlockchainGateway/index.d.ts +0 -48
- package/dist/domains/BrowserStorage/index.d.ts +0 -21
- package/dist/domains/Client/index.d.ts +0 -16
- package/dist/domains/Deploy/factory/index.d.ts +0 -4
- package/dist/domains/Deploy/index.d.ts +0 -8
- package/dist/domains/EncryptedRecord/index.d.ts +0 -10
- package/dist/domains/Error/DeploymentErrorHandler.d.ts +0 -8
- package/dist/domains/Error/index.d.ts +0 -2
- package/dist/domains/Error/meta.d.ts +0 -21
- package/dist/domains/HttpClient/index.d.ts +0 -13
- package/dist/domains/Signer/index.d.ts +0 -12
- package/dist/domains/Vault/index.d.ts +0 -41
- package/dist/domains/Wallet/index.d.ts +0 -58
- package/dist/domains/index.d.ts +0 -15
- package/dist/index.cjs.js +0 -2
- package/dist/index.cjs.js.map +0 -1
- package/dist/services/AssetsService/index.d.ts +0 -7
- package/dist/services/BinaryWriter/index.d.ts +0 -8
- package/dist/services/Crypto/index.d.ts +0 -29
- package/dist/services/Fee/index.d.ts +0 -5
- package/dist/services/KeyDerivation/index.d.ts +0 -15
- package/dist/services/KeysManager/index.d.ts +0 -14
- package/dist/services/Mnemonic/index.d.ts +0 -11
- package/dist/services/Resubmit/DeployResubmitter.d.ts +0 -22
- package/dist/services/Resubmit/NodeManager.d.ts +0 -22
- package/dist/services/Resubmit/index.d.ts +0 -3
- package/dist/services/Resubmit/types.d.ts +0 -32
- package/dist/services/Signer/index.d.ts +0 -5
- package/dist/services/Transfer/index.d.ts +0 -11
- package/dist/services/Wallets/index.d.ts +0 -16
- package/dist/services/index.d.ts +0 -19
- package/dist/utils/codec/index.d.ts +0 -6
- package/dist/utils/constants/index.d.ts +0 -24
- package/dist/utils/decorators/index.d.ts +0 -5
- package/dist/utils/functions/index.d.ts +0 -5
- package/dist/utils/index.d.ts +0 -5
- package/dist/utils/polyfills/index.d.ts +0 -1
- package/dist/utils/validators/index.d.ts +0 -21
package/dist/index.esm.js
CHANGED
|
@@ -1,2 +1,3 @@
|
|
|
1
|
-
import e from"bs58";import*as t from"bip39";import{mnemonicToSeed as r}from"bip39";import{Buffer as n}from"buffer";import*as a from"tiny-secp256k1";import{BIP32Factory as i}from"bip32";import{getPublicKey as s,utils as o,sign as c}from"@noble/secp256k1";import l from"blakejs";import d from"js-sha3";import u from"axios";const h=32,y={coinId:"000000",version:"00"},p=60,g=8,m={BASE_FEE:.0025,VARIATION_RANGE:.1,LABEL:"ASI",TRANSFER:"0.0025",DEPLOY:"0.0025"},f=10,w=BigInt(10)**BigInt(8),E=.99,I=-1,N={coinType:60,account:0,change:0,index:0};var A;class v{}A=v,v.generateRandomGasFee=()=>{const e=2*(Math.random()-.5)*m.VARIATION_RANGE;return(m.BASE_FEE*(1+e)).toFixed(4)},v.getGasFeeAsNumber=()=>m.BASE_FEE,v.formatGasFee=e=>`${e||A.generateRandomGasFee()} ${m.LABEL}`;const b=t=>{const r=R(t);return e.encode(r)},S=t=>e.decode(t),R=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},D=e=>Array.from(e,e=>e.toString(16).padStart(2,"0")).join(""),L=e=>{const t=new Uint8Array(e);let r="";for(let e=0;e<t.byteLength;e++)r+=String.fromCharCode(t[e]);return btoa(r)},_=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},O=2,C=12,T=16,k=256,P="AES-GCM",U="SHA-256",K="raw",V="PBKDF2",B=1e5;class M{static async encryptWithPassword(e,t){const r=crypto.getRandomValues(new Uint8Array(T)),n=crypto.getRandomValues(new Uint8Array(C)),a=await this.deriveKey(t,r),i=await crypto.subtle.encrypt({name:P,iv:n},a,(new TextEncoder).encode(e));return{data:L(i),salt:L(r.buffer),iv:L(n.buffer),version:O}}static async decryptWithPassword(e,t){if(e.version!==O)throw new Error(`Unsupported version ${e.version}`);const r=new Uint8Array(_(e.salt)),n=new Uint8Array(_(e.iv)),a=await this.deriveKey(t,r),i=await crypto.subtle.decrypt({name:P,iv:n},a,_(e.data));return(new TextDecoder).decode(i)}static async deriveKey(e,t){const r=await crypto.subtle.importKey(K,(new TextEncoder).encode(e),V,!1,["deriveKey"]);return crypto.subtle.deriveKey({name:V,salt:new Uint8Array(t),iterations:B,hash:U},r,{name:P,length:k},!1,["encrypt","decrypt"])}}const x=()=>{"undefined"==typeof window||window.Buffer||(window.Buffer=n)};var W;x(),function(e){e[e.TWELVE_WORDS=128]="TWELVE_WORDS",e[e.TWENTY_FOUR_WORDS=256]="TWENTY_FOUR_WORDS"}(W||(W={}));class F{static generateMnemonic(e=W.TWELVE_WORDS){return t.generateMnemonic(e)}static generateMnemonicArray(e=W.TWELVE_WORDS){return this.mnemonicToWordArray(this.generateMnemonic(e))}static isMnemonicValid(e){return t.validateMnemonic(e)}static mnemonicToWordArray(e){return e.trim().split(" ")}static wordArrayToMnemonic(e){return e.join(" ")}}x();class G{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(F.wordArrayToMnemonic(e),t)}static seedToMasterNode(e){return i(a).fromSeed(e)}static async deriveKeyFromMnemonic(e,t=N){const r=this.buildBip44Path(t),n=await G.mnemonicToSeed(e),a=G.seedToMasterNode(n);return G.derivePrivateKey(a,r)}static async deriveNextKeyFromMnemonic(e,t,r=N){const n=t+1;return await this.deriveKeyFromMnemonic(e,{...r,index:n})}}const{randomBytes:$,bytesToHex:H}=o;class z{static generateRandomKey(e=32){if(!e||e<0||!Number.isInteger(e))throw new Error("PrivateKeyLength must be a positive integer");return $(e)}static generateKeyPair(e=32){if(!e||e<0||!Number.isInteger(e))throw new Error("PrivateKeyLength must be a positive integer");const t=$(e);return{privateKey:t,publicKey:s(t)}}static getKeyPairFromPrivateKey(e){return{privateKey:e,publicKey:s(e)}}static getPublicKeyFromPrivateKey(e){return s(e)}static convertKeyToHex(e){return H(e)}static async deriveKeyFromMnemonic(e,t){return await G.deriveKeyFromMnemonic(e,t)}static generateMpcKeyPair(){throw new Error("MPC key generation is not implemented yet.")}}const{blake2bHex:j}=l,{keccak256:Y}=d;class J{static createWallet(e,t){let r;r=e?z.getKeyPairFromPrivateKey(e):z.generateKeyPair();return{address:this.deriveAddressFromPublicKey(r.publicKey),publicKey:r.publicKey,privateKey:r.privateKey}}static async createWalletFromMnemonic(e,t){const r=e?F.mnemonicToWordArray(e):F.generateMnemonicArray(),n=F.wordArrayToMnemonic(r);if(!n||!F.isMnemonicValid(n))throw new Error("WalletsService.createWalletFromMnemonic: Recovery mnemonic is missing or invalid");const a=await G.mnemonicToSeed(r),i=G.seedToMasterNode(a),s=G.buildBip44Path({coinType:60,account:0,change:0,index:t||0}),o=G.derivePrivateKey(i,s);return{...this.createWallet(o),mnemonic:n}}static deriveAddressFromPrivateKey(e){const t=z.getKeyPairFromPrivateKey(e);return this.deriveAddressFromPublicKey(t.publicKey)}static deriveAddressFromPublicKey(e){const t=Y(e.slice(1)),r=R(t.slice(-40)),n=Y(r),a=`${y.coinId}${y.version}${n}`,i=R(a),s=j(i,void 0,32).slice(0,8);return b(`${a}${s}`)}}function X(e,t,r,n,a,i){function s(e){if(void 0!==e&&"function"!=typeof e)throw new TypeError("Function expected");return e}for(var o,c=n.kind,l="getter"===c?"get":"setter"===c?"set":"value",d=!t&&e?n.static?e:e.prototype:null,u=t||(d?Object.getOwnPropertyDescriptor(d,n.name):{}),h=!1,y=r.length-1;y>=0;y--){var p={};for(var g in n)p[g]="access"===g?{}:n[g];for(var g in n.access)p.access[g]=n.access[g];p.addInitializer=function(e){if(h)throw new TypeError("Cannot add initializers after decoration has completed");i.push(s(e||null))};var m=(0,r[y])("accessor"===c?{get:u.get,set:u.set}:u[l],p);if("accessor"===c){if(void 0===m)continue;if(null===m||"object"!=typeof m)throw new TypeError("Object expected");(o=s(m.get))&&(u.get=o),(o=s(m.set))&&(u.set=o),(o=s(m.init))&&a.unshift(o)}else(o=s(m))&&("field"===c?a.unshift(o):u[l]=o)}d&&Object.defineProperty(d,n.name,u),h=!0}function Z(e,t,r){for(var n=arguments.length>2,a=0;a<t.length;a++)r=n?t[a].call(e,r):t[a].call(e);return n?r:void 0}var q,Q;"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"}(q||(q={})),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"}(Q||(Q={}));const ee={[q.READ_ONLY_NODE]:"Node is read-only. Trying another node...",[q.CASPER_INSTANCE_UNAVAILABLE]:"Casper instance not available. Trying another node...",[q.INVALID_DEPLOY_ID]:"Invalid deploy ID. Please try again.",[q.INVALID_BLOCK_NUMBER]:"Invalid block number. Please try again.",[Q.INSUFFICIENT_BALANCE]:"Insufficient balance. Please top up your account.",[Q.WRONG_NETWORK]:"Wrong network. Please contact technical support.",[Q.PARSING_ERROR]:"Parsing error. Please contact technical support.",[Q.LOW_PHLO_PRICE]:"Phlo price too low. Please rebuild the transaction with a higher phlo price.",[Q.SIGNATURE_ERROR]:"Signature verification failed. Please try again.",[Q.STORAGE_RETRIEVAL_ERROR]:"Storage retrieval error. Please try again later.",[Q.UNKNOWN_ERROR]:"An unknown error occurred. Please try again.",[Q.DEPLOY_SUBMIT_TIMEOUT]:"Deploy submission timed out. Please try again.",[Q.BLOCK_INCLUSION_TIMEOUT]:"Deploy was not included in a block within the expected time.",[Q.FINALIZATION_TIMEOUT]:"Block finalization polling timed out."};function te(e){return ee[e]??"An unknown error occurred. Please try again."}function re(e,t){return function(...t){return"string"==typeof t[0]&&(t[0]=t[0].toLowerCase()),e.apply(this,t)}}let ne=(()=>{var e;let t,r,n=[];return e=class{parseDeploymentError(e){return e.includes("read only")?q.READ_ONLY_NODE:e.includes("casper instance")?q.CASPER_INSTANCE_UNAVAILABLE:e.includes("invalid deploy ID")?q.INVALID_DEPLOY_ID:e.includes("invalid block number")?q.INVALID_BLOCK_NUMBER:e.includes("insufficient balance")?Q.INSUFFICIENT_BALANCE:e.includes("wrong network")?Q.WRONG_NETWORK:e.includes("parsing error")?Q.PARSING_ERROR:e.includes("low")&&e.includes("phlo")?Q.LOW_PHLO_PRICE:e.includes("signature")||e.includes("sign")||e.includes("invalid signature")?Q.SIGNATURE_ERROR:e.includes("storage")||e.includes("retrieval")?Q.STORAGE_RETRIEVAL_ERROR:Q.UNKNOWN_ERROR}isDeploymentErrorRecoverable(e){return Object.values(q).includes(e)}isDeploymentErrorFatal(e){return Object.values(Q).includes(e)}isPollingErrorRecoverable(e){return e.includes("casper instance")||e.includes("storage")||e.includes("parsing")}getErrorMessageByErrorType(e){return ee[e]??ee[Q.UNKNOWN_ERROR]}constructor(){Z(this,n)}},(()=>{const a="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;t=[re],r=[re],X(e,null,t,{kind:"method",name:"parseDeploymentError",static:!1,private:!1,access:{has:e=>"parseDeploymentError"in e,get:e=>e.parseDeploymentError},metadata:a},null,n),X(e,null,r,{kind:"method",name:"isPollingErrorRecoverable",static:!1,private:!1,access:{has:e=>"isPollingErrorRecoverable"in e,get:e=>e.isPollingErrorRecoverable},metadata:a},null,n),a&&Object.defineProperty(e,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:a})})(),e})();class ae{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 ie,se;!function(e){e.DEPLOYING="Deploying",e.INCLUDED_IN_BLOCK="IncludedInBlock",e.FINALIZED="Finalized",e.CHECK_ERROR="CheckingError"}(ie||(ie={}));class oe{constructor(e,t){this.validatorClient=e,this.indexerClient=t}static createHttpClient(e){const t=u.create({baseURL:e.baseUrl,...e.axiosConfig});return new ae(t)}changeValidator(e){return this.validatorClient=oe.createHttpClient(e),this}changeIndexer(e){return this.indexerClient=oe.createHttpClient(e),this}static init(e){return oe.instance=new oe(this.createHttpClient(e.validator),this.createHttpClient(e.indexer)),oe.instance}static isInitialized(){return void 0!==oe?.instance}static getInstance(){if(!oe.isInitialized())throw new Error("BlockchainGateway is not initialized. Call BlockchainGateway.init() first.");return oe.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:ie.DEPLOYING};return{status:await this.isDeployFinalized(t)?ie.FINALIZED:ie.INCLUDED_IN_BLOCK}}catch(e){const t="BlockchainGateway.getDeployStatus: "+this.getGatewayErrorMessage(e);return{status:ie.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(u.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"}(se||(se={}));const ce={mode:se.LOCAL},le=3e4,de=20,ue=8,he=5e5,ye={phloPrice:1,useRandomNode:!0,deployValiditySeconds:80,nodeSelectionAttempts:3,deployRetries:3,deployIntervalSeconds:5,pollingIntervalSeconds:3};function pe(e,t){return function(...r){if(!oe.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=Z(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=ye.nodeSelectionAttempts,n=ye.useRandomNode){const a=n?Math.max(1,r):0,i=new e(t,a,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){oe.getInstance().getValidatorClientUrl()!==e&&oe.getInstance().changeValidator({baseUrl:e});if(!await oe.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 a="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;t=[pe],r=[pe],X(e,null,t,{kind:"method",name:"connectDefaultNode",static:!1,private:!1,access:{has:e=>"connectDefaultNode"in e,get:e=>e.connectDefaultNode},metadata:a},null,n),X(e,null,r,{kind:"method",name:"connectActiveRandomNode",static:!1,private:!1,access:{has:e=>"connectActiveRandomNode"in e,get:e=>e.connectActiveRandomNode},metadata:a},null,n),a&&Object.defineProperty(e,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:a})})(),e})();const me=127;class fe{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>me;)this.buffer.push(e&me|128),e>>>=7;this.buffer.push(e)}writeInteger64(e){for(;e>me;)this.buffer.push(e&me|128),e=Math.floor(e/128);this.buffer.push(e)}getResultBuffer(){return new Uint8Array(this.buffer)}}const{blake2bHex:we}=l;class Ee{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=we(t,void 0,32),a=Uint8Array.from(Buffer.from(r,"hex")),i=await e.signDigest(a),s=e.getPublicKey();return{data:{term:n.term,timestamp:n.timestamp,phloPrice:n.phloPrice,phloLimit:n.phloLimit,validAfterBlockNumber:n.validAfterBlockNumber,shardId:n.shardId},deployer:D(s),signature:D(i),sigAlgorithm:"secp256k1"}})}catch(e){const t=`SignerService.sign: ${e.message}`;throw new Error(t)}}}Ee.deployDataProtobufSerialize=e=>{const{term:t,timestamp:r,phloPrice:n,phloLimit:a,validAfterBlockNumber:i,shardId:s=""}=e,o=new fe;return o.writeString(2,t),o.writeInt64(3,r),o.writeInt64(7,n),o.writeInt64(8,a),o.writeInt64(10,i),o.writeString(11,s),o.getResultBuffer()};const Ie=/[,\s]+/g,Ne=/^\d+(?:\.\d+)?$/,Ae=/(\.\d*?[1-9])0+$/,ve=/\.0+$/,be=e=>{const t=w.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(Ie,""),!Ne.test(r))throw new Error("Invalid amount format");const[a,i=""]=r.split("."),s=a||"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(s)*w+BigInt(o||"0");return n?-c:c},Se=e=>{const t=e/w,r=e%w,n=w.toString().length-1,a=r.toString().padStart(n,"0");return`${t.toString()}.${a}`.replace(Ae,"$1").replace(ve,"")},Re=e=>{const t=e/w,r=e%w;return t>BigInt(Number.MAX_SAFE_INTEGER)?(console.warn("Integer part exceeds Number.MAX_SAFE_INTEGER; returning imprecise Number"),Number(Se(e))):Number(t)+Number(r)/Number(w)},De=Se,Le=e=>[...Array(e)].map(()=>Math.floor(16*Math.random()).toString(16)).join(""),{blake2bHex:_e}=l,Oe=/[<>:"/\\|?*]/,Ce=(e,t=30)=>e&&0!==e.trim().length?e.length>t?{isValid:!1,error:`Account name must be ${t} characters or less`}:Oe.test(e)?{isValid:!1,error:"Account name contains invalid characters"}:{isValid:!0}:{isValid:!1,error:"Account name is required"},Te=/^[a-zA-Z0-9]+$/,ke=/^[1-9A-HJ-NP-Za-km-z]+$/,Pe=`${y.coinId}${y.version}`;var Ue;!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"}(Ue||(Ue={}));const Ke=e=>({isValid:!1,errorCode:e}),Ve=e=>{if(!e.startsWith("1111"))return Ke(Ue.INVALID_PREFIX);if(e.length<50||e.length>54)return Ke(Ue.INVALID_LENGTH);if(!Te.test(e))return Ke(Ue.INVALID_ALPHABET);if(!ke.test(e))return Ke(Ue.INVALID_BASE58);const t=D(S(e));if(80!==t.length)return Ke(Ue.INVALID_HEX_LENGTH);if(b(t)!==e)return Ke(Ue.NON_CANONICAL);const r=t.slice(0,72),n=t.slice(72);if(!r.startsWith(Pe))return Ke(Ue.INVALID_CHAIN_PREFIX);const a=_e(R(r),void 0,32).slice(0,8);return 8!==n.length||n!==a?Ke(Ue.INVALID_CHECKSUM):{isValid:!0}},Be=e=>Ve(e).isValid;class Me{constructor(e,t){if(this.startSubmissionTime=0,this.config=e,this.nodeManager=ge.initialize(t,e.nodeSelectionAttempts,e.useRandomNode),this.errorHandler=new ne,!oe.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 a=this.config.deployRetries,i={success:!1};for(;a>0&&!this.isDeployExpired();){try{const a=oe.getInstance(),s=await a.getLatestBlockNumber();if(-1===s)throw new Error("DeployResubmitter.retryDeployToOneNode: Invalid block number");const o={term:e,phloLimit:n||he,phloPrice:1,validAfterBlockNumber:s-1,timestamp:Date.now(),shardId:"root"},c=await Ee.sign({wallet:t,data:o},r),l=await a.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;a--}await this.sleep(this.config.deployIntervalSeconds)}return this.isDeployExpired()&&(i.error=i?.error||{},i.error.exceededTimeout=Q.DEPLOY_SUBMIT_TIMEOUT),{success:!1,error:i.error}}async retryDeployToRandomNodes(e,t,r,n){let a={success:!1};for(;!this.isDeployExpired()&&this.nodeManager.getRetriesLeft()>0&&(await this.nodeManager.connectActiveRandomNode(),a=await this.retryDeployToOneNode(e,t,r,n),!a.success)&&(this.nodeManager.deactivateCurrentNode(),a.error?.blockchainError?.type)&&!this.errorHandler.isDeploymentErrorFatal(a.error?.blockchainError?.type););return a}async pollDeployStatus(e){let t;for(;!this.isDeployExpired();){const r=await oe.getInstance().getDeployStatus(e),n=r.status;if(n===ie.CHECK_ERROR){const e=`DeployResubmitter.pollDeployStatus: ${"errorMessage"in r?r.errorMessage:"Unknown error"}`,n=this.errorHandler.parseDeploymentError(e);console.error(e);const a={type:n,message:e};if(this.errorHandler.isDeploymentErrorFatal(n)&&!e.includes("Bad Request"))return{success:!1,deployStatus:ie.CHECK_ERROR,error:{blockchainError:a}};t=a}if(console.log("DeployResubmitter.pollDeployStatus: current deploy status:",n),n==ie.INCLUDED_IN_BLOCK||n==ie.FINALIZED)return{success:!0,deployStatus:r.status};await this.sleep(this.config.pollingIntervalSeconds)}return{success:!1,deployStatus:t?ie.CHECK_ERROR:ie.DEPLOYING,error:{...t,exceededTimeout:Q.BLOCK_INCLUSION_TIMEOUT}}}async resubmit(e,t,r,n){let a;if(console.log("DeployResubmitter: starting deploy submission with resubmission logic"),this.startSubmissionTime=Date.now(),this.config.useRandomNode?a=await this.retryDeployToRandomNodes(e,t,r,n):(await this.nodeManager.connectDefaultNode(),a=await this.retryDeployToOneNode(e,t,r,n)),!a.success||!a?.deployId)return a;console.log(`DeployResubmitter: deploy submitted successfully with ID: ${a.deployId}. Starting to poll for status...`);const i=await this.pollDeployStatus(a.deployId);return console.log(`DeployResubmitter: finished polling deploy status. Final status: ${i.deployStatus}, success: ${i.success}`),i}}const xe=e=>e.replace(/\\/g,"\\\\").replace(/"/g,'\\"').replace(/\n/g,"\\n").replace(/\r/g,"\\r").replace(/\t/g,"\\t");let We=(()=>{var e;let t,r,n=[];return e=class{getBlockchainGateway(){return oe.getInstance()}async transfer(e,t,r,n,a,i=5e5){try{const s=Ve(e);if(!s.isValid)throw new Error(`AssetsService.transfer: Invalid 'fromAddress': ${s.errorCode??"UNKNOWN"}`);const o=Ve(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");if(e===t)throw new Error("AssetsService.transfer: Sender and recipient addresses cannot be the same");const c=this.getBlockchainGateway(),l=((e,t,r)=>{if(r<=0n)throw new Error("Transfer amount must be greater than zero");const n=xe(e),a=xe(t),i=r.toString();return`\n new \n deployerId(\`rho:rchain:deployerId\`),\n stdout(\`rho:io:stdout\`),\n rl(\`rho:registry:lookup\`),\n ASIVaultCh,\n vaultCh,\n toVaultCh,\n asiVaultkeyCh,\n resultCh\n in {\n rl!(\`rho:rchain:asiVault\`, *ASIVaultCh) |\n for (@(_, ASIVault) <- ASIVaultCh) {\n @ASIVault!("findOrCreate", "${n}", *vaultCh) |\n @ASIVault!("findOrCreate", "${a}", *toVaultCh) |\n @ASIVault!("deployerAuthKey", *deployerId, *asiVaultkeyCh) |\n for (@(true, vault) <- vaultCh; key <- asiVaultkeyCh; @(true, toVault) <- toVaultCh) {\n @vault!("transfer", "${a}", ${i}, *key, *resultCh) |\n for (@result <- resultCh) {\n match result {\n (true, Nil) => {\n stdout!(("Transfer successful:", ${i}, "ASI"))\n }\n (false, reason) => {\n stdout!(("Transfer failed:", reason))\n }\n }\n }\n } |\n for (@(false, errorMsg) <- vaultCh) {\n stdout!(("Sender vault error:", errorMsg))\n } |\n for (@(false, errorMsg) <- toVaultCh) {\n stdout!(("Destination vault error:", errorMsg))\n }\n }\n }\n `})(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 Ee.sign({wallet:n,data:u},a);return await c.submitDeploy(h)}catch(e){const t="AssetsService.transfer: "+e.message;throw new Error(t)}}async getASIBalance(e){const t=Ve(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", "${xe(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(){Z(this,n)}},(()=>{const a="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;t=[pe],r=[pe],X(e,null,t,{kind:"method",name:"transfer",static:!1,private:!1,access:{has:e=>"transfer"in e,get:e=>e.transfer},metadata:a},null,n),X(e,null,r,{kind:"method",name:"getASIBalance",static:!1,private:!1,access:{has:e=>"getASIBalance"in e,get:e=>e.getASIBalance},metadata:a},null,n),a&&Object.defineProperty(e,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:a})})(),e})();class Fe{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 Ge{static async createAndEncrypt(e,t){const r=await M.encryptWithPassword(e,t);return new Ge(r)}static createFromEncryptedData(e){return new Ge(e)}static createFromStringifiedEncryptedData(e){return new Ge(JSON.parse(e))}constructor(e){this.encryptedSeedData=e}async decrypt(e){return await M.decryptWithPassword(this.encryptedSeedData,e)}toString(){return JSON.stringify(this.encryptedSeedData)}}var $e;!function(e){e.PRIVATE_KEY="private_key",e.CRYPTO_SALT="crypto_salt",e.CRYPTO_IV="crypto_iv",e.CRYPTO_VERSION="crypto version"}($e||($e={}));class He{constructor(e,t,r,n,a){this.name=e,this.index=a,this.masterNodeId=n,this.address=t,this.privateKey=r,this.assets=new Map,this.isLocked=!0}static async fromPrivateKey(e,t,r,n=null,a=null){const i=J.deriveAddressFromPrivateKey(t),s=await this.encryptPrivateKey(t,r);return new He(e,i,s,n,a)}static fromEncryptedData(e,t,r,n,a){const i=Ve(t);if(!i.isValid)throw new Error(`Invalid address format: ${i.errorCode??"UNKNOWN"}`);return new He(e,t,r,n,a)}async decrypt(e){if(!He.unsafeRawKeyExportEnabled)throw new Error("Wallet.decrypt is disabled by default for security. Use withSigningCapability() instead.");return await this.decryptPrivateKey(e)}static enableUnsafeRawKeyExportForLegacyInterop(){He.unsafeRawKeyExportEnabled=!0}static disableUnsafeRawKeyExport(){He.unsafeRawKeyExportEnabled=!1}static isUnsafeRawKeyExportEnabled(){return He.unsafeRawKeyExportEnabled}async decryptPrivateKey(e){try{const t=await M.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 a={signDigest:async e=>{if(n)throw new Error("Signing capability has expired");return await c(e,r)},getPublicKey:()=>{if(n)throw new Error("Signing capability has expired");return z.getPublicKeyFromPrivateKey(r)}};try{return await t(a)}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 M.encryptWithPassword(JSON.stringify(e),t)}}He.unsafeRawKeyExportEnabled=!1;const ze="0";class je{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(je.ensureBrowserEnvironment(),!this.isLocked)throw new Error("Cannot save an unlocked vault");const t=`${je.vaultPrefix}_${e}`;localStorage.setItem(t,JSON.stringify(this.encryptedVaultData))}async lock(e){this.ensureUnlocked();const t=this.toString();this.encryptedVaultData=await M.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 M.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]),a=He.fromEncryptedData(n.name,n.address,JSON.parse(n.encryptedPrivateKey),n.masterNodeId,n.index?+n.index:null);t.set(r,a)}),this.wallets=t}metaToSeeds(e){const t=new Map;Object.keys(e).forEach(r=>{const n=Ge.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")}}je.vaultPrefix="ASI_WALLETS_VAULT";class Ye{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{w as ASI_BASE_UNIT,y as ASI_CHAIN_PREFIX,p as ASI_COIN_TYPE,g as ASI_DECIMALS,Ue as AddressValidationErrorCode,Fe as Asset,We as AssetsService,ae as AxiosHttpClient,fe as BinaryWriter,oe as BlockchainGateway,M as CryptoService,le as DEFAULT_AXIOS_TIMEOUT_MS,N as DEFAULT_BIP_44_PATH_OPTIONS,ce as DEFAULT_CLIENT_CONFIG,ue as DEFAULT_DECIMALS_AMOUNT,he as DEFAULT_PHLO_LIMIT,ye as DEFAULT_RESUBMIT_CONFIG,ze as DEFAULT_STORAGE_KEY,Me as DeployResubmitter,ie as DeployStatus,ne as DeploymentErrorHandler,Ge as EncryptedRecord,E as FAULT_TOLERANCE_THRESHOLD,Q as FatalDeployErrors,v as FeeService,m as GasFee,I as INVALID_BLOCK_NUMBER,G as KeyDerivationService,z as KeysManager,de as MAX_WALLETS_PER_ACCOUNT,F as MnemonicService,W as MnemonicStrength,f as POWER_BASE,h as PRIVATE_KEY_LENGTH,q as RecoverableDeployErrors,ge as ResubmitNodeManager,Ye as SecureStorage,Ee as SignerService,je as Vault,He as Wallet,se as WalletClientModes,$e as WalletMemoryKeys,J as WalletsService,L as arrayBufferToBase64,_ as base64ToArrayBuffer,R as decodeBase16,S as decodeBase58,ee as deploymentErrorMessages,D as encodeBase16,b as encodeBase58,De as fromAtomicAmount,Re as fromAtomicAmountToNumber,Se as fromAtomicAmountToString,Le as genRandomHex,te as getDeploymentErrorMessage,Be as isAddress,x as setupBufferPolyfill,be as toAtomicAmount,Ce as validateAccountName,Ve as validateAddress};
|
|
1
|
+
import e from"bs58";import*as t from"bip39";import{mnemonicToSeed as r}from"bip39";import{Buffer as n}from"buffer";import{utils as s,CURVE as i,Point as a,getPublicKey as o,signSync as c,verify as l,sign as d}from"@noble/secp256k1";import{BIP32Factory as u}from"bip32";import h from"blakejs";import y from"js-sha3";import p from"axios";const f=32,g={coinId:"000000",version:"00"},m=60,w=8,E={BASE_FEE:.0025,VARIATION_RANGE:.1,LABEL:"ASI",TRANSFER:"0.0025",DEPLOY:"0.0025"},I=16,N=64,A=10,v=BigInt(10)**BigInt(8),b=.99,S=-1,R={coinType:60,account:0,change:0,index:0};var L;class D{}L=D,D.generateRandomGasFee=()=>{const e=2*(Math.random()-.5)*E.VARIATION_RANGE;return(E.BASE_FEE*(1+e)).toFixed(4)},D.getGasFeeAsNumber=()=>E.BASE_FEE,D.formatGasFee=e=>`${e||L.generateRandomGasFee()} ${E.LABEL}`;const _=t=>{const r=C(t);return e.encode(r)},O=t=>e.decode(t),C=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},k=e=>Array.from(e,e=>e.toString(16).padStart(2,"0")).join(""),T=e=>{const t=new Uint8Array(e);let r="";for(let e=0;e<t.byteLength;e++)r+=String.fromCharCode(t[e]);return btoa(r)},P=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},U=e=>BigInt("0x"+Buffer.from(e).toString("hex")),B=e=>Uint8Array.from(Buffer.from(e.toString(16).padStart(64,"0"),"hex"));var V;!function(e){e.ENCRYPT="encrypt",e.DECRYPT="decrypt",e.DERIVATION="deriveKey"}(V||(V={}));const K=2,x=12,M=16,W=256,H="AES-GCM",F="SHA-256",G="raw",$="PBKDF2",Y=1e5;V.ENCRYPT,V.DECRYPT;class z{static async encryptWithPassword(e,t){const r=crypto.getRandomValues(new Uint8Array(M)),n=crypto.getRandomValues(new Uint8Array(x)),s=await this.deriveKey(t,r),i=await crypto.subtle.encrypt({name:H,iv:n},s,(new TextEncoder).encode(e));return{data:T(i),salt:T(r.buffer),iv:T(n.buffer),version:K}}static async decryptWithPassword(e,t){if(e.version!==K)throw new Error(`Unsupported version ${e.version}`);const r=new Uint8Array(P(e.salt)),n=new Uint8Array(P(e.iv)),s=await this.deriveKey(t,r),i=await crypto.subtle.decrypt({name:H,iv:n},s,P(e.data));return(new TextDecoder).decode(i)}static async deriveKey(e,t){const r=await crypto.subtle.importKey(G,(new TextEncoder).encode(e),$,!1,[V.DERIVATION]);return crypto.subtle.deriveKey({name:$,salt:new Uint8Array(t),iterations:Y,hash:F},r,{name:H,length:W},!1,[V.ENCRYPT,V.DECRYPT])}}const j=()=>{"undefined"==typeof window||window.Buffer||(window.Buffer=n)};var J;j(),function(e){e[e.TWELVE_WORDS=128]="TWELVE_WORDS",e[e.TWENTY_FOUR_WORDS=256]="TWENTY_FOUR_WORDS"}(J||(J={}));class X{static generateMnemonic(e=J.TWELVE_WORDS){return t.generateMnemonic(e)}static generateMnemonicArray(e=J.TWELVE_WORDS){return this.mnemonicToWordArray(this.generateMnemonic(e))}static isMnemonicValid(e){return t.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 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};
|
|
2
3
|
//# sourceMappingURL=index.esm.js.map
|