@asichain/asi-wallet-sdk 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (43) hide show
  1. package/LICENSE +201 -0
  2. package/README.md +330 -0
  3. package/dist/config/index.d.ts +15 -0
  4. package/dist/domains/Asset/index.d.ts +12 -0
  5. package/dist/domains/BlockchainGateway/index.d.ts +48 -0
  6. package/dist/domains/BrowserStorage/index.d.ts +21 -0
  7. package/dist/domains/Client/index.d.ts +16 -0
  8. package/dist/domains/Deploy/factory/index.d.ts +4 -0
  9. package/dist/domains/Deploy/index.d.ts +8 -0
  10. package/dist/domains/EncryptedRecord/index.d.ts +10 -0
  11. package/dist/domains/Error/DeploymentErrorHandler.d.ts +8 -0
  12. package/dist/domains/Error/index.d.ts +2 -0
  13. package/dist/domains/Error/meta.d.ts +21 -0
  14. package/dist/domains/HttpClient/index.d.ts +13 -0
  15. package/dist/domains/Signer/index.d.ts +12 -0
  16. package/dist/domains/Vault/index.d.ts +41 -0
  17. package/dist/domains/Wallet/index.d.ts +58 -0
  18. package/dist/domains/index.d.ts +15 -0
  19. package/dist/index.cjs.js +1 -0
  20. package/dist/index.d.ts +504 -0
  21. package/dist/index.esm.js +1 -0
  22. package/dist/services/AssetsService/index.d.ts +6 -0
  23. package/dist/services/BinaryWriter/index.d.ts +8 -0
  24. package/dist/services/Crypto/index.d.ts +29 -0
  25. package/dist/services/Fee/index.d.ts +5 -0
  26. package/dist/services/KeyDerivation/index.d.ts +15 -0
  27. package/dist/services/KeysManager/index.d.ts +14 -0
  28. package/dist/services/Mnemonic/index.d.ts +11 -0
  29. package/dist/services/Resubmit/DeployResubmitter.d.ts +22 -0
  30. package/dist/services/Resubmit/NodeManager.d.ts +22 -0
  31. package/dist/services/Resubmit/index.d.ts +3 -0
  32. package/dist/services/Resubmit/types.d.ts +32 -0
  33. package/dist/services/Signer/index.d.ts +5 -0
  34. package/dist/services/Transfer/index.d.ts +11 -0
  35. package/dist/services/Wallets/index.d.ts +16 -0
  36. package/dist/services/index.d.ts +19 -0
  37. package/dist/utils/codec/index.d.ts +6 -0
  38. package/dist/utils/constants/index.d.ts +24 -0
  39. package/dist/utils/functions/index.d.ts +5 -0
  40. package/dist/utils/index.d.ts +5 -0
  41. package/dist/utils/polyfills/index.d.ts +1 -0
  42. package/dist/utils/validators/index.d.ts +21 -0
  43. package/package.json +53 -0
@@ -0,0 +1,10 @@
1
+ import { type EncryptedData } from "@services/Crypto";
2
+ export default class EncryptedRecord {
3
+ private encryptedSeedData;
4
+ static createAndEncrypt(data: string, password: string): Promise<EncryptedRecord>;
5
+ static createFromEncryptedData(encryptedData: EncryptedData): EncryptedRecord;
6
+ static createFromStringifiedEncryptedData(data: string): EncryptedRecord;
7
+ private constructor();
8
+ decrypt(password: string): Promise<string>;
9
+ toString(): string;
10
+ }
@@ -0,0 +1,8 @@
1
+ import { DeploymentErrorType } from "./meta";
2
+ export default class DeploymentErrorHandler {
3
+ parseDeploymentError(errorMessage: string): DeploymentErrorType;
4
+ isDeploymentErrorRecoverable(errorType: DeploymentErrorType): boolean;
5
+ isDeploymentErrorFatal(errorType: DeploymentErrorType): boolean;
6
+ isPollingErrorRecoverable(errorMessage: string): boolean;
7
+ getErrorMessageByErrorType(errorType: DeploymentErrorType): string;
8
+ }
@@ -0,0 +1,2 @@
1
+ export { default as DeploymentErrorHandler } from "./DeploymentErrorHandler";
2
+ export * from "./meta";
@@ -0,0 +1,21 @@
1
+ export declare enum RecoverableDeployErrors {
2
+ READ_ONLY_NODE = "READ_ONLY_NODE",
3
+ CASPER_INSTANCE_UNAVAILABLE = "CASPER_INSTANCE_UNAVAILABLE",
4
+ INVALID_DEPLOY_ID = "INVALID_DEPLOY_ID",
5
+ INVALID_BLOCK_NUMBER = "INVALID_BLOCK_NUMBER"
6
+ }
7
+ export declare enum FatalDeployErrors {
8
+ INSUFFICIENT_BALANCE = "INSUFFICIENT_BALANCE",
9
+ WRONG_NETWORK = "WRONG_NETWORK",
10
+ PARSING_ERROR = "PARSING_ERROR",
11
+ LOW_PHLO_PRICE = "LOW_PHLO_PRICE",
12
+ SIGNATURE_ERROR = "SIGNATURE_ERROR",
13
+ STORAGE_RETRIEVAL_ERROR = "STORAGE_RETRIEVAL_ERROR",
14
+ UNKNOWN_ERROR = "UNKNOWN_ERROR",
15
+ DEPLOY_SUBMIT_TIMEOUT = "DEPLOY_SUBMIT_TIMEOUT",
16
+ BLOCK_INCLUSION_TIMEOUT = "BLOCK_INCLUSION_TIMEOUT",
17
+ FINALIZATION_TIMEOUT = "FINALIZATION_TIMEOUT"
18
+ }
19
+ export type DeploymentErrorType = RecoverableDeployErrors | FatalDeployErrors;
20
+ export declare const deploymentErrorMessages: Record<DeploymentErrorType, string>;
21
+ export declare function getDeploymentErrorMessage(errorType: DeploymentErrorType): string;
@@ -0,0 +1,13 @@
1
+ import type { AxiosInstance, AxiosRequestConfig } from "axios";
2
+ export interface HttpClient {
3
+ get<T = any>(url: string, config?: AxiosRequestConfig): Promise<T>;
4
+ post<T = any>(url: string, data?: any, config?: AxiosRequestConfig): Promise<T>;
5
+ getBaseUrl(): string | undefined;
6
+ }
7
+ export default class AxiosHttpClient implements HttpClient {
8
+ private readonly client;
9
+ constructor(client: AxiosInstance);
10
+ get<T>(url: string): Promise<T>;
11
+ post<T>(url: string, data?: any): Promise<T>;
12
+ getBaseUrl(): string | undefined;
13
+ }
@@ -0,0 +1,12 @@
1
+ import Wallet from "@domains/Wallet";
2
+ export interface SigningRequest {
3
+ wallet: Wallet;
4
+ data: any;
5
+ }
6
+ export interface SignedResult {
7
+ data: any;
8
+ deployer: string;
9
+ signature: string;
10
+ sigAlgorithm: string;
11
+ }
12
+ export type PasswordProvider = () => Promise<string>;
@@ -0,0 +1,41 @@
1
+ import EncryptedRecord from "@domains//EncryptedRecord";
2
+ import Wallet, { type StringifiedWalletMeta, type Address } from "@domains/Wallet";
3
+ export type Wallets = Map<Address, Wallet>;
4
+ export type Seeds = Map<string, EncryptedRecord>;
5
+ export type VaultRawData = string;
6
+ export type StoredWalletsMetaRecords = Record<Address, StringifiedWalletMeta>;
7
+ export type StoredSeedsMetaRecords = Record<string, string>;
8
+ export declare const DEFAULT_STORAGE_KEY = "0";
9
+ export default class Vault {
10
+ private static vaultPrefix;
11
+ private isLocked;
12
+ private wallets;
13
+ private seeds;
14
+ private encryptedVaultData;
15
+ constructor(VaultData?: VaultRawData);
16
+ static getSavedVaultKeys(): string[];
17
+ static getVaultDataFromStorage(vaultKey: string): VaultRawData | null;
18
+ isVaultLocked(): boolean;
19
+ save(vaultKey?: string): void;
20
+ lock(password: string): Promise<void>;
21
+ unlock(password: string): Promise<void>;
22
+ isEmpty(): boolean;
23
+ getWallets(): Wallet[];
24
+ getWalletsCount(): number;
25
+ getWalletAddresses(): Address[];
26
+ addWallet(wallet: Wallet): void;
27
+ removeWallet(address: Address): void;
28
+ getWallet(address: Address): Wallet | undefined;
29
+ hasWallet(address: Address): boolean;
30
+ hasSeed(seedId: string): boolean;
31
+ private metaToWallets;
32
+ private metaToSeeds;
33
+ getSeeds(): EncryptedRecord[];
34
+ getSeed(id: string): EncryptedRecord | undefined;
35
+ addSeed(id: string, seed: EncryptedRecord): void;
36
+ removeSeed(id: string): void;
37
+ getSeedsIds(): string[];
38
+ toString(): string;
39
+ private ensureUnlocked;
40
+ private static ensureBrowserEnvironment;
41
+ }
@@ -0,0 +1,58 @@
1
+ import Asset, { Assets } from "@domains/Asset";
2
+ import { EncryptedData } from "@services/Crypto";
3
+ type AddressBrand = {
4
+ readonly __brand: unique symbol;
5
+ };
6
+ export type Address = `1111${string & AddressBrand}`;
7
+ export interface StoredWalletMeta {
8
+ name: string;
9
+ address: Address;
10
+ encryptedPrivateKey: string;
11
+ masterNodeId: string | null;
12
+ index: string | null;
13
+ }
14
+ export type StringifiedWalletMeta = string;
15
+ export type WalletMemory = Map<string, string>;
16
+ export declare enum WalletMemoryKeys {
17
+ PRIVATE_KEY = "private_key",
18
+ CRYPTO_SALT = "crypto_salt",
19
+ CRYPTO_IV = "crypto_iv",
20
+ CRYPTO_VERSION = "crypto version"
21
+ }
22
+ export interface SigningCapability {
23
+ signDigest(digest: Uint8Array): Promise<Uint8Array>;
24
+ getPublicKey(): Uint8Array;
25
+ }
26
+ export default class Wallet {
27
+ private static unsafeRawKeyExportEnabled;
28
+ private name;
29
+ private address;
30
+ private privateKey;
31
+ private isLocked;
32
+ private assets;
33
+ private masterNodeId;
34
+ private index;
35
+ private constructor();
36
+ static fromPrivateKey(name: string, privateKey: Uint8Array, password: string, masterNodeId?: string | null, index?: number | null): Promise<Wallet>;
37
+ static fromEncryptedData(name: string, address: Address, encryptedPrivateKey: EncryptedData, masterNodeId: string | null, index: number | null): Wallet;
38
+ /**
39
+ * @deprecated Raw key export is disabled by default. Prefer `withSigningCapability()`.
40
+ * Enable only for legacy migration by calling `Wallet.enableUnsafeRawKeyExportForLegacyInterop()`.
41
+ */
42
+ decrypt(password: string): Promise<Uint8Array>;
43
+ static enableUnsafeRawKeyExportForLegacyInterop(): void;
44
+ static disableUnsafeRawKeyExport(): void;
45
+ static isUnsafeRawKeyExportEnabled(): boolean;
46
+ private decryptPrivateKey;
47
+ withSigningCapability<T>(password: string, callback: (signingCapability: SigningCapability) => Promise<T> | T): Promise<T>;
48
+ getEncryptedPrivateKey(): EncryptedData;
49
+ registerAsset(asset: Asset): void;
50
+ getAddress(): Address;
51
+ getName(): string;
52
+ getIndex(): number | null;
53
+ getAssets(): Assets;
54
+ isWalletLocked(): boolean;
55
+ toString(): StringifiedWalletMeta;
56
+ private static encryptPrivateKey;
57
+ }
58
+ export {};
@@ -0,0 +1,15 @@
1
+ export * from "./Asset";
2
+ export * from "./Vault";
3
+ export * from "./Wallet";
4
+ export * from "./Signer";
5
+ export * from "./HttpClient";
6
+ export * from "./BrowserStorage";
7
+ export * from "./BlockchainGateway";
8
+ export * from "./Error";
9
+ export { default as BlockchainGateway } from "./BlockchainGateway";
10
+ export { default as EncryptedRecord } from "./EncryptedRecord";
11
+ export { default as SecureStorage } from "./BrowserStorage";
12
+ export { default as AxiosHttpClient } from "./HttpClient";
13
+ export { default as Wallet } from "./Wallet";
14
+ export { default as Vault } from "./Vault";
15
+ export { default as Asset } from "./Asset";
@@ -0,0 +1 @@
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 I=t=>{const r=w(t);return e.encode(r)},f=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},S=2,D=12,R=16,b=256,x="AES-GCM",_="SHA-256",L="raw",O="PBKDF2",C=1e5;class T{static async encryptWithPassword(e,t){const r=crypto.getRandomValues(new Uint8Array(R)),s=crypto.getRandomValues(new Uint8Array(D)),o=await this.deriveKey(t,r),a=await crypto.subtle.encrypt({name:x,iv:s},o,(new TextEncoder).encode(e));return{data:A(a),salt:A(r.buffer),iv:A(s.buffer),version:S}}static async decryptWithPassword(e,t){if(e.version!==S)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:x,iv:s},o,v(e.data));return(new TextDecoder).decode(a)}static async deriveKey(e,t){const r=await crypto.subtle.importKey(L,(new TextEncoder).encode(e),O,!1,["deriveKey"]);return crypto.subtle.deriveKey({name:O,salt:new Uint8Array(t),iterations:C,hash:_},r,{name:x,length:b},!1,["encrypt","decrypt"])}}const P=()=>{"undefined"==typeof window||window.Buffer||(window.Buffer=r.Buffer)};var U;P(),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 K{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(" ")}}P();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(K.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:V,bytesToHex:M}=a.utils;class B{static generateRandomKey(e=32){if(!e||e<0||!Number.isInteger(e))throw new Error("PrivateKeyLength must be a positive integer");return V(e)}static generateKeyPair(e=32){if(!e||e<0||!Number.isInteger(e))throw new Error("PrivateKeyLength must be a positive integer");const t=V(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:F}=n,{keccak256:W}=i;class G{static createWallet(e,t){let r;r=e?B.getKeyPairFromPrivateKey(e):B.generateKeyPair();return{address:this.deriveAddressFromPublicKey(r.publicKey),publicKey:r.publicKey,privateKey:r.privateKey}}static async createWalletFromMnemonic(e,t){const r=e?K.mnemonicToWordArray(e):K.generateMnemonicArray(),s=K.wordArrayToMnemonic(r);if(!s||!K.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=B.getKeyPairFromPrivateKey(e);return this.deriveAddressFromPublicKey(t.publicKey)}static deriveAddressFromPublicKey(e){const t=W(e.slice(1)),r=w(t.slice(-40)),s=W(r),o=`${p.coinId}${p.version}${s}`,a=w(o),n=F(a,void 0,32).slice(0,8);return I(`${o}${n}`)}}function H(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}var $,z;"function"==typeof SuppressedError&&SuppressedError,exports.RecoverableDeployErrors=void 0,($=exports.RecoverableDeployErrors||(exports.RecoverableDeployErrors={})).READ_ONLY_NODE="READ_ONLY_NODE",$.CASPER_INSTANCE_UNAVAILABLE="CASPER_INSTANCE_UNAVAILABLE",$.INVALID_DEPLOY_ID="INVALID_DEPLOY_ID",$.INVALID_BLOCK_NUMBER="INVALID_BLOCK_NUMBER",exports.FatalDeployErrors=void 0,(z=exports.FatalDeployErrors||(exports.FatalDeployErrors={})).INSUFFICIENT_BALANCE="INSUFFICIENT_BALANCE",z.WRONG_NETWORK="WRONG_NETWORK",z.PARSING_ERROR="PARSING_ERROR",z.LOW_PHLO_PRICE="LOW_PHLO_PRICE",z.SIGNATURE_ERROR="SIGNATURE_ERROR",z.STORAGE_RETRIEVAL_ERROR="STORAGE_RETRIEVAL_ERROR",z.UNKNOWN_ERROR="UNKNOWN_ERROR",z.DEPLOY_SUBMIT_TIMEOUT="DEPLOY_SUBMIT_TIMEOUT",z.BLOCK_INCLUSION_TIMEOUT="BLOCK_INCLUSION_TIMEOUT",z.FINALIZATION_TIMEOUT="FINALIZATION_TIMEOUT";const Y={[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 X=(()=>{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 Y[e]??Y[exports.FatalDeployErrors.UNKNOWN_ERROR]}constructor(){!function(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)}(this,s)}},(()=>{const o="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;t=[j],r=[j],H(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),H(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 J{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,Z;exports.DeployStatus=void 0,(q=exports.DeployStatus||(exports.DeployStatus={})).DEPLOYING="Deploying",q.INCLUDED_IN_BLOCK="IncludedInBlock",q.FINALIZED="Finalized",q.CHECK_ERROR="CheckingError";class Q{constructor(e,t){this.validatorClient=e,this.indexerClient=t}static createHttpClient(e){const t=l.create({baseURL:e.baseUrl,...e.axiosConfig});return new J(t)}changeValidator(e){return this.validatorClient=Q.createHttpClient(e),this}changeIndexer(e){return this.indexerClient=Q.createHttpClient(e),this}static init(e){return Q.instance=new Q(this.createHttpClient(e.validator),this.createHttpClient(e.indexer)),Q.instance}static isInitialized(){return void 0!==Q?.instance}static getInstance(){if(!Q.isInitialized())throw new Error("BlockchainGateway is not initialized. Call BlockchainGateway.init() first.");return Q.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,(Z=exports.WalletClientModes||(exports.WalletClientModes={})).LOCAL="local",Z.MPC="mpc";const ee={mode:exports.WalletClientModes.LOCAL},te=5e5,re={phloPrice:1,useRandomNode:!0,deployValiditySeconds:80,nodeSelectionAttempts:3,deployRetries:3,deployIntervalSeconds:5,pollingIntervalSeconds:3};class se{constructor(e,t,r){if(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(e,t=re.nodeSelectionAttempts,r=re.useRandomNode){const s=r?Math.max(1,t):0,o=new se(e,s,r);return se.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){Q.getInstance().getValidatorClientUrl()!==e&&Q.getInstance().changeValidator({baseUrl:e});if(!await Q.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(!se.instance)throw new Error("NodeManager is not initialized. Call NodeManager.initialize() first.");return se.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 oe=127;class ae{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>oe;)this.buffer.push(e&oe|128),e>>>=7;this.buffer.push(e)}writeInteger64(e){for(;e>oe;)this.buffer.push(e&oe|128),e=Math.floor(e/128);this.buffer.push(e)}getResultBuffer(){return new Uint8Array(this.buffer)}}const{blake2bHex:ne}=n;class ie{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=ne(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)}}}ie.deployDataProtobufSerialize=e=>{const{term:t,timestamp:r,phloPrice:s,phloLimit:o,validAfterBlockNumber:a,shardId:n=""}=e,i=new ae;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 le=/[,\s]+/g,ce=/^\d+(?:\.\d+)?$/,de=/(\.\d*?[1-9])0+$/,ue=/\.0+$/,pe=e=>{const t=e/h,r=e%h,s=h.toString().length-1,o=r.toString().padStart(s,"0");return`${t.toString()}.${o}`.replace(de,"$1").replace(ue,"")},ye=pe,{blake2bHex:he}=n,Ee=/[<>:"/\\|?*]/,ge=/^[a-zA-Z0-9]+$/,me=/^[1-9A-HJ-NP-Za-km-z]+$/,Ie=`${p.coinId}${p.version}`;var fe;exports.AddressValidationErrorCode=void 0,(fe=exports.AddressValidationErrorCode||(exports.AddressValidationErrorCode={})).INVALID_PREFIX="INVALID_PREFIX",fe.INVALID_LENGTH="INVALID_LENGTH",fe.INVALID_ALPHABET="INVALID_ALPHABET",fe.INVALID_BASE58="INVALID_BASE58",fe.INVALID_HEX_LENGTH="INVALID_HEX_LENGTH",fe.INVALID_CHAIN_PREFIX="INVALID_CHAIN_PREFIX",fe.INVALID_CHECKSUM="INVALID_CHECKSUM",fe.NON_CANONICAL="NON_CANONICAL";const we=e=>({isValid:!1,errorCode:e}),Ne=e=>{if(!e.startsWith("1111"))return we(exports.AddressValidationErrorCode.INVALID_PREFIX);if(e.length<50||e.length>54)return we(exports.AddressValidationErrorCode.INVALID_LENGTH);if(!ge.test(e))return we(exports.AddressValidationErrorCode.INVALID_ALPHABET);if(!me.test(e))return we(exports.AddressValidationErrorCode.INVALID_BASE58);const t=N(f(e));if(80!==t.length)return we(exports.AddressValidationErrorCode.INVALID_HEX_LENGTH);if(I(t)!==e)return we(exports.AddressValidationErrorCode.NON_CANONICAL);const r=t.slice(0,72),s=t.slice(72);if(!r.startsWith(Ie))return we(exports.AddressValidationErrorCode.INVALID_CHAIN_PREFIX);const o=he(w(r),void 0,32).slice(0,8);return 8!==s.length||s!==o?we(exports.AddressValidationErrorCode.INVALID_CHECKSUM):{isValid:!0}};const Ae=e=>e.replace(/\\/g,"\\\\").replace(/"/g,'\\"').replace(/\n/g,"\\n").replace(/\r/g,"\\r").replace(/\t/g,"\\t");class ve{static async createAndEncrypt(e,t){const r=await T.encryptWithPassword(e,t);return new ve(r)}static createFromEncryptedData(e){return new ve(e)}static createFromStringifiedEncryptedData(e){return new ve(JSON.parse(e))}constructor(e){this.encryptedSeedData=e}async decrypt(e){return await T.decryptWithPassword(this.encryptedSeedData,e)}toString(){return JSON.stringify(this.encryptedSeedData)}}var Se;exports.WalletMemoryKeys=void 0,(Se=exports.WalletMemoryKeys||(exports.WalletMemoryKeys={})).PRIVATE_KEY="private_key",Se.CRYPTO_SALT="crypto_salt",Se.CRYPTO_IV="crypto_iv",Se.CRYPTO_VERSION="crypto version";class De{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=G.deriveAddressFromPrivateKey(t),n=await this.encryptPrivateKey(t,r);return new De(e,a,n,s,o)}static fromEncryptedData(e,t,r,s,o){const a=Ne(t);if(!a.isValid)throw new Error(`Invalid address format: ${a.errorCode??"UNKNOWN"}`);return new De(e,t,r,s,o)}async decrypt(e){if(!De.unsafeRawKeyExportEnabled)throw new Error("Wallet.decrypt is disabled by default for security. Use withSigningCapability() instead.");return await this.decryptPrivateKey(e)}static enableUnsafeRawKeyExportForLegacyInterop(){De.unsafeRawKeyExportEnabled=!0}static disableUnsafeRawKeyExport(){De.unsafeRawKeyExportEnabled=!1}static isUnsafeRawKeyExportEnabled(){return De.unsafeRawKeyExportEnabled}async decryptPrivateKey(e){try{const t=await T.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 B.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 T.encryptWithPassword(JSON.stringify(e),t)}}De.unsafeRawKeyExportEnabled=!1;class Re{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(Re.ensureBrowserEnvironment(),!this.isLocked)throw new Error("Cannot save an unlocked vault");const t=`${Re.vaultPrefix}_${e}`;localStorage.setItem(t,JSON.stringify(this.encryptedVaultData))}async lock(e){this.ensureUnlocked();const t=this.toString();this.encryptedVaultData=await T.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 T.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=De.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=ve.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")}}Re.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=class{async transfer(e,t,r,s,o,a=5e5){try{const n=Ne(e);if(!n.isValid)throw new Error(`AssetsService.transfer: Invalid 'fromAddress': ${n.errorCode??"UNKNOWN"}`);const i=Ne(t);if(!i.isValid)throw new Error(`AssetsService.transfer: Invalid 'toAddress': ${i.errorCode??"UNKNOWN"}`);if(r<=0n)throw new Error("AssetsService.transfer: Transfer amount must be greater than zero");const l=Q.getInstance(),c=((e,t,r)=>{if(r<=0n)throw new Error("Transfer amount must be greater than zero");const s=Ae(e),o=Ae(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 ie.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=Ne(e);if(!t.isValid)throw new Error(`AssetsService.getASIBalance: Invalid address: ${t.errorCode??"UNKNOWN"}`);const r=Q.getInstance(),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", "${Ae(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)}}},exports.AxiosHttpClient=J,exports.BinaryWriter=ae,exports.BlockchainGateway=Q,exports.CryptoService=T,exports.DEFAULT_AXIOS_TIMEOUT_MS=3e4,exports.DEFAULT_BIP_44_PATH_OPTIONS=E,exports.DEFAULT_CLIENT_CONFIG=ee,exports.DEFAULT_DECIMALS_AMOUNT=8,exports.DEFAULT_PHLO_LIMIT=te,exports.DEFAULT_RESUBMIT_CONFIG=re,exports.DEFAULT_STORAGE_KEY="0",exports.DeployResubmitter=class{constructor(e,t){if(this.startSubmissionTime=0,this.config=e,this.nodeManager=se.initialize(t,e.nodeSelectionAttempts,e.useRandomNode),this.errorHandler=new X,!Q.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=Q.getInstance(),n=await o.getLatestBlockNumber();if(-1===n)throw new Error("DeployResubmitter.retryDeployToOneNode: Invalid block number");const i={term:e,phloLimit:s||te,phloPrice:1,validAfterBlockNumber:n-1,timestamp:Date.now(),shardId:"root"},l=await ie.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 Q.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=X,exports.EncryptedRecord=ve,exports.FAULT_TOLERANCE_THRESHOLD=.99,exports.FeeService=m,exports.GasFee=y,exports.INVALID_BLOCK_NUMBER=-1,exports.KeyDerivationService=k,exports.KeysManager=B,exports.MAX_WALLETS_PER_ACCOUNT=20,exports.MnemonicService=K,exports.POWER_BASE=10,exports.PRIVATE_KEY_LENGTH=32,exports.ResubmitNodeManager=se,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=ie,exports.Vault=Re,exports.Wallet=De,exports.WalletsService=G,exports.arrayBufferToBase64=A,exports.base64ToArrayBuffer=v,exports.decodeBase16=w,exports.decodeBase58=f,exports.deploymentErrorMessages=Y,exports.encodeBase16=N,exports.encodeBase58=I,exports.fromAtomicAmount=ye,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(pe(e))):Number(t)+Number(r)/Number(h)},exports.fromAtomicAmountToString=pe,exports.genRandomHex=e=>[...Array(e)].map(()=>Math.floor(16*Math.random()).toString(16)).join(""),exports.getDeploymentErrorMessage=function(e){return Y[e]??"An unknown error occurred. Please try again."},exports.isAddress=e=>Ne(e).isValid,exports.setupBufferPolyfill=P,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(le,""),!ce.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`}:Ee.test(e)?{isValid:!1,error:"Account name contains invalid characters"}:{isValid:!0}:{isValid:!1,error:"Account name is required"},exports.validateAddress=Ne;