vaults-multichain-sdk 1.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.
package/dist/index.cjs ADDED
@@ -0,0 +1,2 @@
1
+ 'use strict';Object.defineProperty(exports,'__esModule',{value:true});var web3_js=require('@solana/web3.js'),rt=require('bitcoinjs-lib'),cc=require('ecpair'),dc=require('tiny-secp256k1'),buffer=require('buffer'),shamirSecretSharing=require('shamir-secret-sharing'),Wr=require('xrpl'),ed25519=require('@noble/ed25519'),sha2_js=require('@noble/hashes/sha2.js'),ethers=require('ethers'),tronweb=require('tronweb'),ft=require('@sqds/multisig'),ao=require('@solana/spl-token'),splMemo=require('@solana/spl-memo'),viem=require('viem'),elliptic=require('elliptic'),Ao=require('hash.js');function _interopDefault(e){return e&&e.__esModule?e:{default:e}}function _interopNamespace(e){if(e&&e.__esModule)return e;var n=Object.create(null);if(e){Object.keys(e).forEach(function(k){if(k!=='default'){var d=Object.getOwnPropertyDescriptor(e,k);Object.defineProperty(n,k,d.get?d:{enumerable:true,get:function(){return e[k]}});}})}n.default=e;return Object.freeze(n)}var rt__namespace=/*#__PURE__*/_interopNamespace(rt);var cc__default=/*#__PURE__*/_interopDefault(cc);var dc__namespace=/*#__PURE__*/_interopNamespace(dc);var Wr__namespace=/*#__PURE__*/_interopNamespace(Wr);var ft__namespace=/*#__PURE__*/_interopNamespace(ft);var ao__namespace=/*#__PURE__*/_interopNamespace(ao);var Ao__namespace=/*#__PURE__*/_interopNamespace(Ao);var Ko=Object.create;var bn=Object.defineProperty;var Ho=Object.getOwnPropertyDescriptor;var Xo=Object.getOwnPropertyNames;var Vo=Object.getPrototypeOf,Go=Object.prototype.hasOwnProperty;var or=(c=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(c,{get:(e,t)=>(typeof require<"u"?require:e)[t]}):c)(function(c){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+c+'" is not supported')});var K=(c,e)=>()=>(c&&(e=c(c=0)),e);var $o=(c,e)=>()=>(e||c((e={exports:{}}).exports,e),e.exports),Y=(c,e)=>{for(var t in e)bn(c,t,{get:e[t],enumerable:true});},qo=(c,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of Xo(e))!Go.call(c,r)&&r!==t&&bn(c,r,{get:()=>e[r],enumerable:!(n=Ho(e,r))||n.enumerable});return c};var jo=(c,e,t)=>(t=c!=null?Ko(Vo(c)):{},qo(bn(t,"default",{value:c,enumerable:true}),c));function Ys(c){zs=c;}function zo(){return zs==="mainnet"?"BTC":"BTC_T3"}exports.EChainType=void 0;var zs;exports.MultisigStatus=void 0;exports.OrderStatus=void 0;exports.EAdaInstructionType=void 0;exports.EXrpOrderType=void 0;exports.StatusFilterEnum=void 0;exports.EAddressBookEntryType=void 0;exports.ORG_POLICY_CODES=void 0;var Q=K(()=>{exports.EChainType=(l=>(l.EVM="EVM",l.SOL="SOL",l.TRON="TRON",l.BTC="BTC",l.BTC_T3="BTC_T3",l.ADA="ADA",l.XRP="XRP",l))(exports.EChainType||{}),zs="mainnet";exports.MultisigStatus=(n=>(n.PENDING="pending",n.ACTIVE="active",n.INACTIVE="inactive",n))(exports.MultisigStatus||{}),exports.OrderStatus=(a=>(a.PENDING="pending",a.APPROVED="approved",a.EXECUTED="executed",a.REJECTED="rejected",a.CANCELLED="cancelled",a.FAILED="failed",a))(exports.OrderStatus||{}),exports.EAdaInstructionType=(t=>(t.native="native",t.token="token",t))(exports.EAdaInstructionType||{}),exports.EXrpOrderType=(l=>(l.native="native",l.asset="asset",l.setTrustLine="setTrustLine",l.removeTrustLine="removeTrustLine",l.changeThreshold="changeThreshold",l.updateOwners="updateOwners",l.updateOwnerThreshold="updateOwnerThreshold",l))(exports.EXrpOrderType||{}),exports.StatusFilterEnum=(r=>(r.ALL="all",r.PENDING="pending",r.EXECUTED="executed",r.REJECTED="rejected",r))(exports.StatusFilterEnum||{}),exports.EAddressBookEntryType=(t=>(t.CEX="CEX",t.Wallet="Wallet",t))(exports.EAddressBookEntryType||{}),exports.ORG_POLICY_CODES=["ERROR_KYC_REQUIRED","ERROR_BUSINESS_HOURS_VIOLATION","ERROR_ADDRESS_NOT_WHITELISTED","ERROR_DAILY_LIMIT_EXCEEDED"];});var si={};Y(si,{API_TIMEOUTS:()=>Qo,BTC_NETWORK_CONFIG:()=>nc,DEFAULT_CONFIG:()=>In,DEFAULT_RPC_ENDPOINTS:()=>ri,EVM_CHAIN_NAMES:()=>Yo,KEY_RECONSTRUCTION_CONFIG:()=>Zo,MINIMUM_BALANCE_FOR_TX:()=>ec,NATIVE_CURRENCY:()=>tc,SHAMIR_CONFIG:()=>Jo,SUPPORTED_CHAINS:()=>rc,TRON_FULL_HOST:()=>je,getRpcEndpoint:()=>Ye,normalizeSdkPathPrefix:()=>ni,resolveConfig:()=>Sn,resolveRpcEndpoints:()=>ut});function ni(c){if(c===void 0||c.trim()==="")return "/sdk";let e=c.trim(),n=(e.startsWith("/")?e:`/${e}`).replace(/\/+$/,"");return n===""?"/sdk":n}function Sn(c){if(!c.apiKey&&!c.accessToken)throw new Error("Either apiKey or accessToken must be provided");if(!c.network)throw new Error("network must be provided");let e=c.network==="mainnet"?"https://stage-api.trustodian.online":"https://afridax-backend-production.up.railway.app";return {apiKey:c.apiKey??"",accessToken:c.accessToken,network:c.network,apiBaseUrl:e,apiPathPrefix:ni(c.apiPathPrefix),rpcOverrides:c.rpcOverrides??In.rpcOverrides,timeout:c.timeout??In.timeout}}function ut(c,e={}){let t=ri[c],n={...t.evm};Object.keys(t.evm).forEach(S=>{let O=Number(S),C=O.toString();e[C]&&(n[O]=e[C]);}),Object.keys(e).forEach(S=>{isNaN(Number(S))||(n[Number(S)]=e[S]);});let s=e[c==="mainnet"?"sol_mainnet":"sol_devnet"]||t.solana,l=e[c==="mainnet"?"tron_mainnet":"tron_shasta"]||t.tron,m=e[c==="mainnet"?"btc":"BTC_T3"]||t.btc,T=e[c==="mainnet"?"ada_mainnet":"ada_preprod"]||t.ada,A=e[c==="mainnet"?"xrp_mainnet":"xrp_testnet"]||t.xrp;return {evm:n,solana:s,tron:l,btc:m,ada:T,xrp:A}}function Ye(c,e,t){switch(c){case "EVM":if(t===void 0)throw new Error("Chain ID is required for EVM chains");let n=e.evm[t];if(!n)throw new Error(`No RPC endpoint configured for EVM chain ID ${t}`);return n;case "SOL":return e.solana;case "TRON":return e.tron;case "BTC":case "BTC_T3":return e.btc;case "ADA":return e.ada;case "XRP":return e.xrp;default:throw new Error(`Unsupported chain type: ${c}`)}}var ri,je,Yo,In,Jo,Zo,Qo,ec,tc,rc,nc,it=K(()=>{ri={mainnet:{evm:{1:"https://ethereum-rpc.publicnode.com",137:"https://polygon-rpc.com",8453:"https://mainnet.base.org",42161:"https://arb1.arbitrum.io/rpc",10:"https://mainnet.optimism.io",56:"https://bsc-rpc.publicnode.com",43114:"https://api.avax.network/ext/bc/C/rpc"},solana:"https://public.rpc.solanavibestation.com/",tron:"https://api.trongrid.io",btc:"https://mempool.space/api",ada:"",xrp:"wss://xrplcluster.com"},testnet:{evm:{11155111:"https://ethereum-sepolia-rpc.publicnode.com",80002:"https://rpc-amoy.polygon.technology",84532:"https://sepolia.base.org",421614:"https://sepolia-rollup.arbitrum.io/rpc",11155420:"https://optimism-sepolia-rpc.publicnode.com",97:"https://bsc-testnet-rpc.publicnode.com",43113:"https://api.avax-test.network/ext/bc/C/rpc"},solana:"https://api.devnet.solana.com",tron:"https://api.shasta.trongrid.io",btc:"https://mempool.space/testnet/api",ada:"",xrp:"wss://s.altnet.rippletest.net:51233"}},je={mainnet:"https://api.trongrid.io",testnet:"https://api.shasta.trongrid.io"},Yo={1:"Ethereum",137:"Polygon",8453:"Base",42161:"Arbitrum One",10:"Optimism",56:"BNB Smart Chain",11155111:"Ethereum Sepolia",80002:"Polygon Amoy",84532:"Base Sepolia",421614:"Arbitrum Sepolia",11155420:"Optimism Sepolia",97:"BNB Smart Chain Testnet",43114:"Avalanche C-Chain",43113:"Avalanche Fuji"},In={network:"mainnet",apiBaseUrl:"",apiPathPrefix:"/sdk",rpcOverrides:{},timeout:3e4};Jo={THRESHOLD:2,TOTAL_SHARES:3},Zo={MAX_RETRIES:1,RETRY_ON_MISMATCH:true},Qo={DEFAULT:3e4,TRANSACTION:6e4,KEY_RECONSTRUCTION:45e3},ec={EVM:"0.001",SOL:"0.01",TRON:"1",BTC:"0.0001",BTC_T3:"0.0001",ADA:"1",XRP:"1"},tc={EVM:{symbol:"ETH",decimals:18},SOL:{symbol:"SOL",decimals:9},TRON:{symbol:"TRX",decimals:6},BTC:{symbol:"BTC",decimals:8},BTC_T3:{symbol:"BTC",decimals:8},ADA:{symbol:"ADA",decimals:6},XRP:{symbol:"XRP",decimals:6}},rc=["EVM","SOL","TRON","BTC","BTC_T3","ADA","XRP"],nc={mainnet:{name:"bitcoin",bech32:"bc",pubKeyHash:0,scriptHash:5,wif:128},testnet:{name:"testnet",bech32:"tb",pubKeyHash:111,scriptHash:196,wif:239}};});function ic(c){return c instanceof exports.AfridaxBaseError}exports.AfridaxBaseError=void 0;exports.ApiError=void 0;exports.KeyMismatchError=void 0;exports.InsufficientBalanceError=void 0;exports.ChainNotSupportedError=void 0;exports.NetworkError=void 0;var q,Ot;exports.InvalidInputError=void 0;exports.UnauthorizedError=void 0;exports.PermissionDeniedError=void 0;exports.OrgPolicyRejectedError=void 0;var $t,dr;exports.NotFoundError=void 0;var ht=K(()=>{Q();exports.AfridaxBaseError=class extends Error{code;chain;operation;details;cause;constructor(e,t,n){super(t),this.name=this.constructor.name,this.code=e,this.chain=n?.chain,this.operation=n?.operation,this.details=n?.details,this.cause=n?.cause,Object.setPrototypeOf(this,new.target.prototype),Error.captureStackTrace&&Error.captureStackTrace(this,this.constructor);}toJSON(){return {code:this.code,message:this.message,chain:this.chain,operation:this.operation,details:this.details,cause:this.cause}}toString(){let e=`[${this.code}] ${this.message}`;return this.chain&&(e+=` (chain: ${this.chain})`),this.operation&&(e+=` (operation: ${this.operation})`),e}},exports.ApiError=class extends exports.AfridaxBaseError{statusCode;responseBody;constructor(e,t){super("API_ERROR",e,t),this.statusCode=t?.statusCode,this.responseBody=t?.responseBody;}toJSON(){return {...super.toJSON(),statusCode:this.statusCode}}},exports.KeyMismatchError=class extends exports.AfridaxBaseError{expectedAddress;derivedAddress;constructor(e,t){super("KEY_MISMATCH",e,t),this.expectedAddress=t.expectedAddress,this.derivedAddress=t.derivedAddress;}toJSON(){return {...super.toJSON(),expectedAddress:this.expectedAddress,derivedAddress:this.derivedAddress}}},exports.InsufficientBalanceError=class extends exports.AfridaxBaseError{requiredAmount;availableAmount;currency;constructor(e,t){super("INSUFFICIENT_BALANCE",e,t),this.requiredAmount=t.requiredAmount,this.availableAmount=t.availableAmount,this.currency=t.currency;}toJSON(){return {...super.toJSON(),requiredAmount:this.requiredAmount,availableAmount:this.availableAmount,currency:this.currency}}},exports.ChainNotSupportedError=class extends exports.AfridaxBaseError{requestedChain;supportedChains;constructor(e,t){super("CHAIN_NOT_SUPPORTED",e,{operation:t.operation,details:t.details,cause:t.cause}),this.requestedChain=t.requestedChain,this.supportedChains=t.supportedChains;}toJSON(){return {...super.toJSON(),requestedChain:this.requestedChain,supportedChains:this.supportedChains}}},exports.NetworkError=class extends exports.AfridaxBaseError{endpoint;isTimeout;constructor(e,t){super("NETWORK_ERROR",e,t),this.endpoint=t?.endpoint,this.isTimeout=t?.isTimeout??false;}toJSON(){return {...super.toJSON(),endpoint:this.endpoint,isTimeout:this.isTimeout}}},q=class extends exports.AfridaxBaseError{txHash;constructor(e,t){super("TRANSACTION_FAILED",e,t),this.txHash=t?.txHash;}},Ot=class extends exports.AfridaxBaseError{signedTx;constructor(e,t){super("BROADCAST_FAILED",e,t),this.signedTx=t?.signedTx;}},exports.InvalidInputError=class extends exports.AfridaxBaseError{field;value;constructor(e,t){super("INVALID_INPUT",e,t),this.field=t?.field,this.value=t?.value;}},exports.UnauthorizedError=class extends exports.AfridaxBaseError{constructor(e,t){super("UNAUTHORIZED",e,t);}},exports.PermissionDeniedError=class extends exports.AfridaxBaseError{constructor(e,t){super("PERMISSION_DENIED",e,t);}},exports.OrgPolicyRejectedError=class extends exports.AfridaxBaseError{platformCode;statusCode;responseBody;constructor(e,t){super("ORG_POLICY_REJECTED",e,t),this.platformCode=t.platformCode,this.statusCode=t.statusCode,this.responseBody=t.responseBody;}toJSON(){return {...super.toJSON(),platformCode:this.platformCode,statusCode:this.statusCode}}};$t=class extends exports.AfridaxBaseError{retryAfter;constructor(e,t){super("RATE_LIMITED",e,t),this.retryAfter=t?.retryAfter;}},dr=class extends exports.AfridaxBaseError{timeoutMs;constructor(e,t){super("TIMEOUT",e,t),this.timeoutMs=t.timeoutMs;}},exports.NotFoundError=class extends exports.AfridaxBaseError{resourceType;resourceId;constructor(e,t){let n;switch(t.resourceType){case "order":n="ORDER_NOT_FOUND";break;case "multisig":n="MULTISIG_NOT_FOUND";break;case "wallet":n="WALLET_NOT_FOUND";break}super(n,e,t),this.resourceType=t.resourceType,this.resourceId=t.resourceId;}};});var ai={};Y(ai,{WalletApi:()=>qt});var qt,Pn=K(()=>{qt=class{client;constructor(e){this.client=e;}async createWallet(e){return this.client.post("/sdk/wallets/create",{wallets:[{chain:e}]})}async importWallet(e,t){return this.client.post("/sdk/wallets/create",{wallets:[{chain:e,key:t}]})}async getWallet(e){return this.client.get(`/sdk/wallets/${e}`)}async getWallets(){return this.client.get("/sdk/wallets/all")}async getPaginatedWallets(e,t=10){let n=1,r=t,s;typeof e=="object"&&e!==null?(n=e.page??1,r=e.limit??10,s=e.chainTypes):typeof e=="number"&&(n=e);let a={page:n,limit:r};return s?.length&&(a.chainTypes=s.join(",")),this.client.get("/sdk/wallets",{params:a})}async deleteWallet(e,t){return this.client.delete(`/sdk/wallets/${e}/${t}`)}async updateWalletName(e,t,n){return this.client.post("/sdk/wallets/update/name",{walletAddress:t,name:n,chainType:e})}async fetchServerShare(e,t){return (await this.client.get(`/sdk/wallets/share/c/${e}/${t}`)).share}async fetchRecoveryShare(e,t){return (await this.client.get(`/sdk/wallets/share/s/${e}/${t}`)).share}async fetchShares(e,t){let[n,r]=await Promise.all([this.fetchServerShare(e,t),this.fetchRecoveryShare(e,t)]);return {server:n,recovery:r}}async fetchPublicKey(){return (await this.client.get("/sdk/wallets/pubkey")).pubkey}async updateShares(e,t,n){await this.client.post("/sdk/wallets/update",{walletAddress:e,serverShare:t,encryptedRecoveryShare:n});}async getWalletsPortfolio(e){if(e.length===0)return [];let t={wallets:e};return await this.client.post("/sdk/wallets/portfolio",t)}async getSupportedTokens(e,t,n=1,r=50,s){return this.client.get(`/sdk/wallets/supported-tokens/${e}/${t}`,{params:{page:n,limit:r,search:s}})}async getTotalAssetValue(){return this.client.get("/sdk/wallets/total-asset-value")}async getHistory(e,t,n=1,r=20){return this.client.get(`/sdk/history/wallet/${e}/${t}`,{params:{page:n,limit:r}})}};});function ur(c){let e=new Uint8Array(c);if(typeof globalThis.crypto<"u"&&globalThis.crypto.getRandomValues)globalThis.crypto.getRandomValues(e);else if(typeof or<"u"){let n=or("crypto").randomBytes(c);e.set(new Uint8Array(n.buffer,n.byteOffset,n.byteLength));}else throw new Error("No cryptographically secure random number generator available");return e}async function pr(c,e){return lc(c,e)}async function lc(c,e){if(typeof globalThis.crypto>"u"||!globalThis.crypto||!globalThis.crypto.subtle)throw console.error("Crypto Error: Web Crypto API (crypto.subtle) is not supported in this environment."),new Error("BROWSER_NOT_SUPPORTED: Encryption failed because Web Crypto API is not available.");if(typeof TextEncoder>"u"||typeof atob>"u"||typeof btoa>"u")throw console.error("Crypto Error: Required global functions (TextEncoder, atob, btoa) are missing."),new Error("BROWSER_NOT_SUPPORTED: Encryption failed because required global functions are missing.");let t=c.replace(/-----BEGIN PUBLIC KEY-----/,"").replace(/-----END PUBLIC KEY-----/,"").replace(/\s+/g,"");try{let n=Uint8Array.from(atob(t),l=>l.charCodeAt(0)),r=await globalThis.crypto.subtle.importKey("spki",n.buffer,{name:"RSA-OAEP",hash:"SHA-256"},!1,["encrypt"]),s=new TextEncoder().encode(e),a=await globalThis.crypto.subtle.encrypt({name:"RSA-OAEP"},r,s);return btoa(String.fromCharCode(...new Uint8Array(a)))}catch(n){throw console.error("Crypto Error: Failed during key import or encryption step.",n),new Error("ENCRYPTION_FAILED: Could not securely encrypt data. Check key format or algorithm support.")}}function Rn(c,e=true){let t=Array.from(c).map(n=>n.toString(16).padStart(2,"0")).join("");return e?`0x${t}`:t}var jt=K(()=>{Q();cc__default.default(dc__namespace);});var gi={};Y(gi,{SHAMIR_SHARES_NUM:()=>ci,SHAMIR_THRESHOLD:()=>oi,bytesToHex:()=>Mn,combineShares:()=>re,createShares:()=>ui,fetchRecoveryShare:()=>pi,fetchServerShare:()=>hr,fetchShares:()=>hi,getReconstructionShares:()=>Ke,hexToBytes:()=>di,splitPrivateKey:()=>li,updateShares:()=>mi});function di(c){let e=c.startsWith("0x")?c.slice(2):c,t=new Uint8Array(e.length/2);for(let n=0;n<t.length;n++)t[n]=parseInt(e.slice(n*2,n*2+2),16);return t}function Mn(c){return "0x"+Array.from(c).map(e=>e.toString(16).padStart(2,"0")).join("")}function hc(c){if(c.length===0)return c;let e=c.map(n=>n.startsWith("0x")?n.slice(2):n),t=Math.max(...e.map(n=>n.length));return e.map(n=>n.padStart(t,"0"))}async function re(c){let t=hc(c).map(r=>di("0x"+r)),n=await shamirSecretSharing.combine(t);return new Uint8Array(n)}async function li(c){let e=await shamirSecretSharing.split(c,ci,oi),{ethers:t}=await import('ethers');return {serverShare:t.hexlify(e[1]),recoveryShare:t.hexlify(e[2])}}async function ui(c){if(!c||c.length===0)throw new Error("Cannot create shares from empty private key");return li(c)}async function hr(c,e,t){return (await c.get(`/sdk/wallets/share/c/${t}/${e}`)).share}async function pi(c,e,t){return (await c.get(`/sdk/wallets/share/s/${t}/${e}`)).share}async function hi(c,e,t){let[n,r]=await Promise.all([pi(c,e,t),hr(c,e,t)]);return {recovery:n,server:r}}async function mi(c,e,t,n){let r=await re([n,t]),s=await ui(r),a=await c.get("/sdk/wallets/pubkey"),l=await pr(a.pubkey,s.recoveryShare);return await c.post("/sdk/wallets/update",{walletAddress:e,serverShare:s.serverShare,encryptedRecoveryShare:l}),{recovery:s.recoveryShare,server:s.serverShare}}async function Ke(c,e,t){let n,r,s=await hi(c,e,t),a=await mi(c,e,s.server,s.recovery);if(n=a.recovery,r=a.server,!n||!r)throw new Error("Failed to retrieve key shares.");return {mainShare:n,additionalShare:r}}var oi,ci,Ze=K(()=>{jt();oi=2,ci=3;});var _n={};Y(_n,{getWalletFromPrivateKey:()=>at});async function at(c){let e=c.toUpperCase();if(e.startsWith("ED")){let p=e.slice(2),m=buffer.Buffer.from(p,"hex"),g=ed25519.getPublicKey(m),T="ED"+buffer.Buffer.from(g).toString("hex").toUpperCase();return new Wr__namespace.Wallet(T,e)}let t=e.startsWith("00")?e.slice(2):e,n=buffer.Buffer.from(t,"hex"),s=(await import('tiny-secp256k1')).pointFromScalar(n,true);if(!s)throw new Error("Failed to derive secp256k1 public key from private key");let a=buffer.Buffer.from(s).toString("hex").toUpperCase(),l=e.startsWith("00")?e:"00"+e;return new Wr__namespace.Wallet(a,l)}var Tt=K(()=>{ed25519.hashes.sha512=c=>sha2_js.sha512(c);});var ee,qe=K(()=>{Ze();it();Q();ee=class{apiClient;network;constructor(e,t="mainnet"){this.apiClient=e,this.network=t;}async reconstructEvmKey(e){let{mainShare:t,additionalShare:n}=await Ke(this.apiClient,e,"EVM"),r=await re([t,n]),s=Mn(r),a=new ethers.ethers.Wallet(s);if(a.address.toLowerCase()!==e.toLowerCase())throw new Error("KEY_MISMATCH");return {privateKey:s,signer:a}}async reconstructSolanaKey(e){let{mainShare:t,additionalShare:n}=await Ke(this.apiClient,e,"SOL"),r=await re([t,n]),s;try{s=web3_js.Keypair.fromSecretKey(r);}catch(a){throw console.error("Keypair reconstruction failed:",a.message),new Error("KEY_MISMATCH")}if(s.publicKey.toBase58()!==e)throw new Error("KEY_MISMATCH");return {secretKey:s.secretKey,keypair:s}}async reconstructBtcKey(e,t=false){let n=t?"BTC":"BTC_T3",{mainShare:r,additionalShare:s}=await Ke(this.apiClient,e,n),a=await re([r,s]),l=await import('bitcoinjs-lib'),p=await import('tiny-secp256k1'),{ECPairFactory:m}=await import('ecpair'),g=m(p),T=t?l.networks.bitcoin:l.networks.testnet,y=g.fromPrivateKey(buffer.Buffer.from(a),{network:T}),{address:A}=l.payments.p2wpkh({pubkey:buffer.Buffer.from(y.publicKey),network:T});if(A!==e)throw new Error("KEY_MISMATCH");return {privateKeyWif:y.toWIF(),privateKeyBuffer:a}}async reconstructTronKey(e){let{mainShare:t,additionalShare:n}=await Ke(this.apiClient,e,"TRON"),r=await re([t,n]),s=buffer.Buffer.from(r).toString("hex"),a=je[this.network];if(new tronweb.TronWeb({fullHost:a}).address.fromPrivateKey(s)!==e)throw new Error("KEY_MISMATCH");return {privateKey:s}}async reconstructAdaKey(e){let{mainShare:t,additionalShare:n}=await Ke(this.apiClient,e,"ADA"),r=await re([t,n]),s=await import('@emurgo/cardano-serialization-lib-browser'),a=r.length===64?s.PrivateKey.from_extended_bytes(r):s.PrivateKey.from_normal_bytes(r),p=a.to_public().hash(),m=s.Address.from_bech32(e),g,T=s.BaseAddress.from_address(m);if(T)g=T.payment_cred().to_keyhash();else {let S=s.EnterpriseAddress.from_address(m);if(S)g=S.payment_cred().to_keyhash();else {let O=s.PointerAddress.from_address(m);O&&(g=O.payment_cred().to_keyhash());}}if(!g)throw new Error("Could not extract payment key hash from address");let y=p.to_bytes(),A=g.to_bytes();if(y.length!==A.length||!y.every((S,O)=>S===A[O]))throw new Error("KEY_MISMATCH");return {privateKey:a,privateKeyHex:buffer.Buffer.from(r).toString("hex")}}async reconstructXrpKey(e){let{mainShare:t,additionalShare:n}=await Ke(this.apiClient,e,"XRP"),r=await re([t,n]),s=buffer.Buffer.from(r).toString("hex"),{getWalletFromPrivateKey:a}=await Promise.resolve().then(()=>(Tt(),_n));if((await a(s)).address!==e)throw new Error("KEY_MISMATCH");return {privateKey:s}}async reconstructWithRetry(e,t=1){try{return await e()}catch(n){if(n instanceof Error&&n.message==="KEY_MISMATCH"&&t>0)try{return await e()}catch{throw new Error("Wallet key verification failed, even after forcing a share update. The account may be corrupted.")}throw n}}async signTransaction(e){let{address:t,chainType:n,action:r,params:s}=e;if(n==="EVM")return this.signEvmTransaction(t,r,s);if(n==="SOL")return this.signSolanaTransaction(t,r,s);if(n==="TRON")return this.signTronTransaction(t,s);if(n==="BTC")return this.signBtcTransaction(t,s);if(n==="ADA")return this.signAdaTransaction(t,r,s);if(n==="XRP")return this.signXrpTransaction(t,r,s);throw new Error(`Unsupported chain type: ${n}`)}getChainConfig(e){return {[Number("1")]:{key:"ethereum",maxGwei:200},[Number("11155111")]:{key:"sepolia",maxGwei:200},[Number("137")]:{key:"polygon",maxGwei:500},[Number("8453")]:{key:"base",maxGwei:10},[Number("43114")]:{key:"avalanche",maxGwei:300},[Number("43113")]:{key:"avalanche-fuji",maxGwei:300}}[e]}async signEvmTransaction(e,t,n){let{signer:r}=await this.reconstructWithRetry(()=>this.reconstructEvmKey(e));if(t==="signEvmOrder"){let s=n.hashToSign;return {tx:await r.signMessage(ethers.ethers.getBytes(s))}}if(t==="signEvmTx"||t==="signTransaction"){let s=n.transaction||n.unsignedTx,a=n.expectedChainId,l=ethers.ethers.Transaction.from(s),p=BigInt(a);if(l.chainId!==p)throw console.error(`Chain ID mismatch. Expected: ${a}, Received: ${l.chainId}`),new Error("Transaction chain ID does not match the expected network.");let m=l.data&&l.data!=="0x",g=this.getChainConfig(a);if(!g)console.warn(`Unknown EVM chain ID: ${a}`);else {let y=m?2e5:5e5;l.gasLimit>BigInt(y)&&console.warn(`Gas limit (${l.gasLimit}) exceeds recommended maximum (${y})`);let A=ethers.ethers.parseUnits(String(g.maxGwei),"gwei");if(l.gasPrice&&l.gasPrice>A)throw console.error(`Gas price too high: ${l.gasPrice}`),new Error("Gas price exceeds safe limit.");if(l.maxFeePerGas&&l.maxFeePerGas>A)throw console.error(`Max Fee Per Gas too high for ${g.key}. Limit: ${g.maxGwei} Gwei`),new Error("Max Fee Per Gas exceeds safe limit.")}if(m)try{if(l.data.startsWith("0xa9059cbb")){let A=l.data.slice(10);if(A.length!==128)throw new Error("Invalid ERC20 transfer data length");let S="0x"+A.slice(24,64),O=ethers.ethers.getAddress(S);if(!ethers.ethers.isAddress(O))throw new Error("Invalid recipient address in transfer data")}}catch(y){throw console.error("Error validating ERC20 data:",y),new Error("Not standart transaction")}return {tx:await r.signTransaction(l)}}if(t==="signTypedData"){let s=n.domain,a=n.types,l=n.value;return {tx:await r.signTypedData(s,a,l)}}throw new Error(`Unknown EVM action: ${t}`)}async signSolanaTransaction(e,t,n){let{Transaction:r,VersionedTransaction:s,PublicKey:a,Connection:l}=await import('@solana/web3.js'),{keypair:p}=await this.reconstructWithRetry(()=>this.reconstructSolanaKey(e));if(t==="sol.executeOrder"){let y=n.multisigParams,A=n.method,S=await import('@sqds/multisig'),O=new l(y.rpcUrl,"confirmed"),C=new a(y.multisigPda),x=BigInt(y.transactionIndex),R=new r;if(A.toLowerCase()==="native"||A.toLowerCase()==="spl"){let _=await S.instructions.vaultTransactionExecute({connection:O,multisigPda:C,transactionIndex:x,member:p.publicKey});R.add(_.instruction);}else {let _=S.instructions.configTransactionExecute({multisigPda:C,transactionIndex:x,member:p.publicKey,rentPayer:p.publicKey});R.add(_);}let P=(await O.getLatestBlockhash()).blockhash;return R.feePayer=p.publicKey,R.recentBlockhash=P,R.partialSign(p),{tx:R.serialize().toString("base64")}}if(t==="sol.rejectOrder"){let y=n.multisigParams,A=await import('@sqds/multisig'),S=new l(y.rpcUrl,"confirmed"),O=new a(y.multisigPda),C=BigInt(y.transactionIndex),x=new r,R=A.instructions.proposalReject({member:p.publicKey,multisigPda:O,transactionIndex:C,memo:y.orderId});x.add(R),x.feePayer=p.publicKey;let P=(await S.getLatestBlockhash()).blockhash;return x.recentBlockhash=P,x.partialSign(p),{tx:x.serialize().toString("base64")}}let m=n.transaction,g=buffer.Buffer.from(m,"base64"),T;try{let y=r.from(g);y.partialSign(p),T=y.serialize({requireAllSignatures:!1}).toString("base64");}catch{let y=s.deserialize(g);y.sign([p]),T=buffer.Buffer.from(y.serialize()).toString("base64");}return {tx:T}}async signTronTransaction(e,t){let{privateKey:n}=await this.reconstructWithRetry(()=>this.reconstructTronKey(e)),r=je[this.network],s=new tronweb.TronWeb({fullHost:r,privateKey:n}),a=t.unsignedTx;return {tx:(await s.trx.sign(a,n)).signature?.[0]||""}}async signBtcTransaction(e,t){let n=await import('bitcoinjs-lib'),r=await import('tiny-secp256k1'),{ECPairFactory:s}=await import('ecpair'),a=s(r),l=t.isMainnet||false,{privateKeyBuffer:p}=await this.reconstructWithRetry(()=>this.reconstructBtcKey(e,l)),m=l?n.networks.bitcoin:n.networks.testnet,g=a.fromPrivateKey(buffer.Buffer.from(p),{network:m}),T=t.psbtHex,y=n.Psbt.fromHex(T,{network:m});return y.signAllInputs(g),y.finalizeAllInputs(),{tx:y.extractTransaction().toHex()}}async signAdaTransaction(e,t,n){let r=await import('@emurgo/cardano-serialization-lib-browser'),{privateKey:s}=await this.reconstructWithRetry(()=>this.reconstructAdaKey(e));if(t==="signAdaOrder"){let a=n.hashToSign,l=r.TransactionHash.from_bytes(buffer.Buffer.from(a,"hex")),p=r.make_vkey_witness(l,s);return {tx:buffer.Buffer.from(p.to_bytes()).toString("hex")}}throw new Error(`Unknown ADA action: ${t}`)}async signXrpTransaction(e,t,n){let{privateKey:r}=await this.reconstructWithRetry(()=>this.reconstructXrpKey(e)),{getWalletFromPrivateKey:s}=await Promise.resolve().then(()=>(Tt(),_n)),a=await import('xrpl'),l=await s(r);if(t==="signXrpOrder"){let p=n.transaction,m=l.sign(p,true),T=a.decode(m.tx_blob)?.Signers?.[0]?.Signer;if(!T)throw new Error("Failed to extract signer from XRP multisig blob");return {tx:JSON.stringify({signature:T.TxnSignature,signingPubKey:T.SigningPubKey})}}if(t==="sendXrpTransaction"){let p=n.transaction;return {tx:l.sign(p).tx_blob}}throw new Error(`Unknown XRP action: ${t}`)}};});var Fn={};Y(Fn,{EChainType:()=>J,ESolanaInstructionType:()=>Ve,TransactionEstimatingType:()=>exports.TransactionEstimatingType,TransactionExecutionType:()=>Ue});var J,Ve,Ue;exports.TransactionEstimatingType=void 0;var Ge=K(()=>{J={EVM:"EVM",SOL:"SOL",TRON:"TRON",BTC:"BTC",BTC_T3:"BTC_T3",ADA:"ADA",XRP:"XRP"},Ve={native:"native",spl:"spl",addOwner:"addOwner",removeOwner:"removeOwner",changeThreshold:"changeThreshold"},Ue={ExecOrder:"execOrder",Send:"send",ActivateMultisig:"activateMultisig",ActivateTrustLine:"activateTrustLine"},exports.TransactionEstimatingType={ExecOrder:"execOrder",Send:"send",ActivateMultisig:"activateMultisig",SignOrder:"SignOrder",CreateOrder:"CreateOrder",ChangeMultisig:"ChangeMultisig"};});var Ei={};Y(Ei,{MAINNET_CHAIN_IDS:()=>yi,MAX_GAS_LIMIT_ERC20:()=>vi,MAX_GAS_LIMIT_NATIVE:()=>Ti,SYMBOLIC_GWEI_LIMITS:()=>zt,TESTNET_CHAIN_IDS:()=>wi,getChainConfig:()=>gr,getNativeCurrency:()=>ze,validateEvmTransaction:()=>Tc});function gr(c){let e=String(c);for(let[t,n]of Object.entries(yi))if(n===e&&zt[t]!==void 0)return {key:t,chainId:e,maxGwei:zt[t]};for(let[t,n]of Object.entries(wi)){let r=t.replace(/_SEPOLIA|_FUJI/,"");if(n===e&&zt[r]!==void 0)return {key:r,chainId:e,maxGwei:zt[r]}}return null}function ze(c){return wc[String(c)]||"ETH"}function Tc(c,e){let t=BigInt(e);if(c.chainId!==t)throw new q(`Chain ID mismatch. Expected: ${e}, Received: ${c.chainId}`,{details:{expectedChainId:e,receivedChainId:c.chainId}});if(c.nonce===void 0||c.nonce===null)throw new q("Transaction nonce is missing");let n=c.data&&c.data!=="0x",r=gr(e);if(!r)throw new q(`Unsupported EVM chain ID: ${e}`);let s=n?vi:Ti;c.gasLimit&&c.gasLimit>BigInt(s)&&console.warn(`Gas limit (${c.gasLimit}) exceeds recommended maximum (${s})`);let a=ethers.ethers.parseUnits(String(r.maxGwei),"gwei");if(c.gasPrice&&c.gasPrice>a)throw new q(`Gas price exceeds safe limit for ${r.key}. Limit: ${r.maxGwei} Gwei`,{details:{gasPrice:c.gasPrice,maxGasPrice:a}});if(c.maxFeePerGas&&c.maxFeePerGas>a)throw new q(`Max Fee Per Gas exceeds safe limit for ${r.key}. Limit: ${r.maxGwei} Gwei`,{details:{maxFeePerGas:c.maxFeePerGas,maxGasPrice:a}});n&&vc(c),n&&c.value&&c.value>0n&&console.warn("ERC20 transfer includes native token value - this is unusual");}function vc(c){try{if(!c.data.startsWith("0xa9059cbb")){console.warn("Transaction contains data but not a standard ERC20 transfer");return}let t=c.data.slice(10);if(t.length!==128)throw new q("Invalid ERC20 transfer data length");let n="0x"+t.slice(24,64),r=ethers.ethers.getAddress(n);if(!ethers.ethers.isAddress(r))throw new q("Invalid recipient address in transfer data");let s="0x"+t.slice(64,128);if(BigInt(s)<=0n)throw new q("Invalid transfer amount")}catch(e){throw e instanceof q?e:(console.error("Error validating ERC20 data:",e),new q("Not standard transaction"))}}var zt,yi,wi,wc,Ti,vi,kt=K(()=>{ht();zt={ETH:100,POL:1e6,ARBITRUM:150,OPTIMISM:150,BASE:150,BNB:20,AVAX:300},yi={ETH:"1",POL:"137",ARBITRUM:"42161",OPTIMISM:"10",BASE:"8453",BNB:"56",AVAX:"43114"},wi={ETH_SEPOLIA:"11155111",POL:"80002",ARBITRUM_SEPOLIA:"421614",OPTIMISM_SEPOLIA:"11155420",BASE_SEPOLIA:"84532",BNB:"97",AVAX_FUJI:"43113"};wc={1:"ETH",11155111:"ETH",137:"POL",80002:"POL",43114:"AVAX",43113:"AVAX",56:"BNB",97:"BNB",42161:"ETH",421614:"ETH",10:"ETH",11155420:"ETH",8453:"ETH",84532:"ETH"};Ti=5e5,vi=2e5;});var bi={};Y(bi,{estimateEvmRegularFee:()=>bc});var Dn,xi,Un,Ac,xc,bc,Ii=K(()=>{kt();Dn="50000",xi="100000",Un="20000000000",Ac=["function transfer(address to, uint256 amount)"],xc=new ethers.Interface(Ac),bc=async({input:c,activeWallet:e,chainId:t,evmStrategy:n})=>{try{let{data:r}=c,{to:s,amount:a,isNativeToken:l,tokenAddress:p,decimals:m}=r;if(!n?.getProvider)throw new Error("getProvider function is missing");let g=n.getProvider(t);if(!g)throw new Error("Provider unavailable.");try{await g.getNetwork();}catch(x){throw new Error(`RPC Connection Error during setup: ${x.message||"Node connection failed."}`)}let T,y=Dn;if(l){let x;try{let R=await g.getBalance(e.address),P=ethers.ethers.parseEther(a.toString());P>R*99n/100n?x=R>ethers.ethers.parseEther("0.02")?ethers.ethers.parseEther("0.01"):R/2n:x=P;}catch(R){console.warn("Failed to fetch balance, using requested amount:",R),x=ethers.ethers.parseEther(a.toString());}T={from:e.address,to:s,value:x,data:"0x"},y=Dn;}else {if(!p)throw new Error("tokenAddress is required for ERC20 transfers.");if(m===void 0)throw new Error("decimals are required for ERC20 transfers.");let x=ethers.ethers.parseUnits(a.toString(),m),R=xc.encodeFunctionData("transfer",[s,x]);T={from:e.address,to:p,value:"0x0",data:R},y=xi;}let A,S;try{A=(await g.estimateGas(T)*115n/100n).toString();}catch(x){if(typeof x=="object"&&x!==null&&"code"in x&&(x.code==="UNPREDICTABLE_GAS_LIMIT"||x.code==="INSUFFICIENT_FUNDS"))console.warn(`Gas estimation failed (${x.code}), using fallback limit.`),A=y;else throw console.error("CRITICAL network error during gas estimation, skipping further attempts:",x),x}try{if(!n?.getFeeData)throw new Error("getFeeData function is missing");let x=await n.getFeeData(g),R=2000000000n,P=x.gasPrice||BigInt(Un);S=((P>R?P:R)*105n/100n).toString();}catch(x){throw console.error("Failed to fetch gas price, using fallback value:",x),x}let O=BigInt(A)*BigInt(S),C=ethers.formatUnits(O,18);return {gasLimit:A,gasPrice:S,estimatedFee:C,currency:ze(t)}}catch(r){console.error("Complete fee estimation failed, returning fallback values:",r);let s=c.data.isNativeToken?Dn:xi,a=BigInt(s)*BigInt(Un),l=ethers.formatUnits(a,18);return {gasLimit:s,gasPrice:Un,estimatedFee:l,currency:ze(t)}}};});var Sc,Ci,Oc,yr,Si,_t,wr,Oi,mt,Tr=K(()=>{qe();Ge();kt();Sc="0x0000000000000000000000000000000000000001",Ci=["function getOwners() view returns (address[])","function execTransaction(address to, uint256 value, bytes data, uint8 operation, uint256 safeTxGas, uint256 baseGas, uint256 gasPrice, address gasToken, address payable refundReceiver, bytes signatures) payable returns (bool)","function addOwnerWithThreshold(address owner, uint256 _threshold)","function removeOwner(address prevOwner, address owner, uint256 _threshold)","function changeThreshold(uint256 _threshold)","function nonce() view returns (uint256)","function getThreshold() view returns (uint256)"],Oc=["function transfer(address to, uint256 amount)"],yr="50000",Si="100000",_t="20000000000",wr=new ethers.ethers.Interface(Ci),Oi=new ethers.Interface(Oc),mt=class{apiClient;keyReconstructor;rpcConfig;constructor(e,t){this.apiClient=e,this.rpcConfig=t,this.keyReconstructor=new ee(e);}getProvider(e){if(!e)throw new Error("ChainId required to get provider");let t=Number(e),n=this.rpcConfig.evm[t];if(!n)throw new Error(`Unsupported EVM network ID: ${e}`);return new ethers.ethers.JsonRpcProvider(n)}async getFeeData(e){return await e.getFeeData()}async getBalance(e,t){let n=await t.getBalance(e);return ethers.ethers.formatEther(n)}async getTransactionHash(e){return ethers.ethers.keccak256(e)}async getSignedTransaction(e){return ethers.ethers.Transaction.from(e)}async getNonce(e,t){return await e.getTransactionCount(t)}async simulateTransaction(e,t){let n=t;return await e.call({to:n.to,from:n.from,data:n.data,value:n.value,gasLimit:n.gasLimit,gasPrice:n.gasPrice})}async broadcastTransaction(e,t){return await e.broadcastTransaction(t)}encodeExecTransaction(e,t,n,r,s){return wr.encodeFunctionData("execTransaction",[e,t,n,r,"0","0","0",ethers.ethers.ZeroAddress,ethers.ethers.ZeroAddress,s])}async getOwners(e,t){return await new ethers.ethers.Contract(e,Ci,t).getOwners()}encodeRemoveOwner(e,t,n){let r=e.findIndex(a=>a.toLowerCase()===t.toLowerCase());if(r===-1)throw new Error("Owner not found");if(e.length===1)throw new Error("Cannot remove the only owner");let s=r===0?Sc:e[r-1];return wr.encodeFunctionData("removeOwner",[s,t,n])}encodeChangeThreshold(e){return wr.encodeFunctionData("changeThreshold",[e])}encodeAddOwnerWithThreshold(e,t){return wr.encodeFunctionData("addOwnerWithThreshold",[e,t])}async signOrder(e){let{wallet:t,order:n}=e;if(!t)throw new Error("Wallet address missing");let r=n?.hashToSing||n?.params?.safeTxHash;if(!r)throw new Error("Order hash not found");let s;try{s=(await this.keyReconstructor.reconstructWithRetry(()=>this.keyReconstructor.reconstructEvmKey(t.address))).signer;}catch(a){throw new Error(a.message||"Order signing failed on EVM key reconstruction.")}try{let a=await s.signMessage(ethers.ethers.getBytes(r));return {tx:await this.gnosisAdjustVInSignature("eth_sign",a,r,s.address)}}catch(a){throw console.error("Error signing EVM order:",a),new Error(a.message||"Order signing failed on EVM.")}}async gnosisAdjustVInSignature(e,t,n,r){let s=[0,1,27,28],a=27,l=parseInt(t.slice(-2),16);if(!s.includes(l))throw new Error("Invalid signature");if(e==="eth_sign"){l<a&&(l+=a);let p=t.slice(0,-2)+l.toString(16);await this.isTxHashSignedWithPrefix(n,p,r)&&(l+=4),t=t.slice(0,-2)+l.toString(16);}return e==="eth_signTypedData"&&(l<a&&(l+=a),t=t.slice(0,-2)+l.toString(16)),t}async isTxHashSignedWithPrefix(e,t,n){try{return ethers.ethers.verifyMessage(ethers.ethers.getBytes(e),t).toLowerCase()===n.toLowerCase()}catch{return false}}async signEvmTransaction(e,t,n){let r=await this.keyReconstructor.reconstructWithRetry(()=>this.keyReconstructor.reconstructEvmKey(e)),{signer:s}=r,a=ethers.ethers.Transaction.from(t);if(a.chainId!==BigInt(n))throw new Error("Transaction chain ID does not match the expected network.");return {tx:await s.signTransaction(a)}}async createOrder(e){let{multisigId:t,wallet:n,method:r,instructions:s}=e,a=await this.apiClient.post("/sdk/order/create/evm",{multisigId:t,walletAddress:n.address,method:r,instructions:s});return {order:a.order,proposalHash:a.order.hashToSing||""}}async rejectOrder(e){let{orderId:t,multisigId:n,wallet:r}=e;if(!n)throw new Error("Vault id missing");return {rejectionHash:"",order:(await this.apiClient.post("/sdk/order/reject/evm",{orderId:t,multisigId:n,walletAddress:r.address})).order}}async executeTransaction(e){let{input:t,actualWallet:n,chainId:r}=e;if(!n)throw new Error("Wallet not connected");if(t.type===Ue.Send)return this.executeNativeSend(t.data,n,r);throw new Error(`Transaction type ${t.type} not yet implemented`)}async executeNativeSend(e,t,n){let r=this.getProvider(String(n)),{to:s,amount:a,estimatedFee:l,tokenAddress:p,isNativeToken:m}=e,g=l?.gasLimit?Math.floor(Number(l.gasLimit)*.9).toString():yr,T=l?.gasPrice?Math.floor(Number(l.gasPrice)*.9).toString():_t,y;if(m)y={to:s,value:ethers.ethers.parseEther(String(a)),data:"0x",gasLimit:BigInt(g),gasPrice:BigInt(T),chainId:n};else {if(!p)throw new Error("Token address is required for ERC20 transfers");let O=await new ethers.ethers.Contract(p,["function decimals() view returns (uint8)"],r).decimals(),C=ethers.ethers.parseUnits(String(a),O),x=Oi.encodeFunctionData("transfer",[s,C]);y={to:p,value:0n,data:x,gasLimit:BigInt(g),gasPrice:BigInt(T),chainId:n};}y.nonce=await this.getNonce(r,t.address);let{tx:A}=await this.signEvmTransaction(t.address,y,n);return await this.broadcastTransaction(r,A)}async estimateFee(e){let{input:t,actualWallet:n,chainId:r}=e;switch(t.type){case exports.TransactionEstimatingType.Send:let{estimateEvmRegularFee:s}=await Promise.resolve().then(()=>(Ii(),bi));return s({input:{data:t.data},activeWallet:n,chainId:r,evmStrategy:this});case exports.TransactionEstimatingType.ExecOrder:return this.estimateExecOrderFee(t.data,n,r);case exports.TransactionEstimatingType.ActivateMultisig:return this.estimateMultisigActivationFee(t.data,n,r);case exports.TransactionEstimatingType.CreateOrder:case exports.TransactionEstimatingType.SignOrder:case exports.TransactionEstimatingType.ChangeMultisig:return console.log(`Method ${t.type} does not require fee on EVM`),{estimatedFee:"0",gasLimit:"0",gasPrice:"0",currency:ze(r)};default:throw new Error(`Fee estimation not implemented for EVM type: ${t.type}`)}}async estimateEvmRegularFee(e,t,n){try{let{to:r,amount:s,isNativeToken:a,tokenAddress:l,decimals:p}=e,m=this.getProvider(n);try{await m.getNetwork();}catch(C){throw new Error(`RPC Connection Error during setup: ${C.message||"Node connection failed."}`)}let g,T=yr;if(a){let C;try{let x=await m.getBalance(t.address),R=ethers.ethers.parseEther(s.toString());R>x*99n/100n?C=x>ethers.ethers.parseEther("0.02")?ethers.ethers.parseEther("0.01"):x/2n:C=R;}catch(x){console.warn("Failed to fetch balance, using requested amount:",x),C=ethers.ethers.parseEther(s.toString());}g={from:t.address,to:r,value:C,data:"0x"},T=yr;}else {if(!l)throw new Error("tokenAddress is required for ERC20 transfers.");if(p===void 0)throw new Error("decimals are required for ERC20 transfers.");let C=ethers.ethers.parseUnits(s.toString(),p),x=Oi.encodeFunctionData("transfer",[r,C]);g={from:t.address,to:l,value:"0x0",data:x},T=Si;}let y,A;try{y=(await m.estimateGas(g)*115n/100n).toString();}catch(C){if(typeof C=="object"&&C!==null&&"code"in C&&(C.code==="UNPREDICTABLE_GAS_LIMIT"||C.code==="INSUFFICIENT_FUNDS"))console.warn(`Gas estimation failed (${C.code}), using fallback limit.`),y=T;else throw console.error("CRITICAL network error during gas estimation, skipping further attempts:",C),C}try{let C=await this.getFeeData(m),x=2000000000n,R=C.gasPrice||BigInt(_t);A=((R>x?R:x)*105n/100n).toString();}catch(C){throw console.error("Failed to fetch gas price, using fallback value:",C),C}let S=BigInt(y)*BigInt(A),O=ethers.formatUnits(S,18);return {gasLimit:y,gasPrice:A,estimatedFee:O,currency:ze(n)}}catch(r){console.error("Complete fee estimation failed, returning fallback values:",r);let s=e.isNativeToken?yr:Si,a=BigInt(s)*BigInt(_t),l=ethers.formatUnits(a,18);return {gasLimit:s,gasPrice:_t,estimatedFee:l,currency:ze(n)}}}async estimateExecOrderFee(e,t,n){let{order:r,multisigAddress:s}=e;if(!t?.address)throw new Error("Wallet not connected");let a=this.getProvider(n);try{await a.getNetwork();}catch(P){throw console.error("Failed to connect to RPC during initial check:",P),new Error(`RPC Connection Error: ${P.message||"Node connection failed."}`)}let{to:l,value:p,data:m,operation:g,signature:T}=r,y="1000000",A;try{A=await this.encodeExecTransaction(l,p,m,g,T.toString());}catch(P){throw console.error("Fail encoding data for order execution:",P),new Error("Fail encoding data")}let S={from:t.address,to:s,value:"0",data:A},O;try{O=(await this.getFeeData(a)).gasPrice?.toString()||_t;}catch(P){console.error("Fail to get gas price, using fallback:",P),O=_t;}let C;try{C=(await a.estimateGas(S)*120n/100n).toString();}catch(P){console.error("Failed to estimate gas for order execution, using fallback limit:",P),C=y;}let x=BigInt(C)*BigInt(O),R=ethers.formatUnits(x,18);return {gasLimit:C,gasPrice:O,estimatedFee:R,currency:ze(n)}}async estimateMultisigActivationFee(e,t,n){let{multisig:r}=e;if(!t?.address)throw new Error("Wallet not connected");let s=this.getProvider(n),a={from:t.address,to:r.factoryAddress,data:r.params.deployData,value:"0",chainId:Number(r.chainId)},p=(await this.getFeeData(s)).gasPrice?.toString()||"20000000000",m,g="800000";try{m=(await s.estimateGas(a)*120n/100n).toString();}catch(A){console.error("Failed to estimate gas, using fallback limit:",A),m=g;}let T=BigInt(m)*BigInt(p),y=ethers.formatUnits(T,18);return {gasLimit:m,gasPrice:p,estimatedFee:y,currency:ze(n)}}};});var vr,Wn=K(()=>{cc.ECPairFactory(dc__namespace),vr=async c=>{let e=c.map(n=>ethers.ethers.getBytes(n));return await shamirSecretSharing.combine(e)};});var Bc,Nc,Pi,Fc,Lc,Dc,Uc,Wc,Ri,Mi=K(()=>{jt();Bc=async(c,e,t,n)=>{let r=await fetch(`${n}/sdk/wallets/share/c/${t}/${e}`,{headers:{"X-API-KEY":c},credentials:"include"});if(!r.ok)throw new Error("Failed to fetch server share");return (await r.json()).share},Nc=async(c,e,t,n)=>{let r=await fetch(`${n}/sdk/wallets/share/s/${t}/${e}`,{headers:{"X-API-KEY":c},credentials:"include"});if(!r.ok)throw new Error("Failed to fetch recovery share");return (await r.json()).share},Pi=async(c,e,t,n)=>{let[r,s]=await Promise.all([Nc(c,e,t,n),Bc(c,e,t,n)]);return {recovery:r,server:s}},Fc=2,Lc=3,Dc=async c=>{let{combine:e}=await import('shamir-secret-sharing'),t=c.map(r=>ethers.ethers.getBytes(r));return await e(t)},Uc=async c=>{let{split:e}=await import('shamir-secret-sharing'),t=await e(c,Lc,Fc),{ethers:n}=await import('ethers'),r=n.hexlify(t[0]),s=n.hexlify(t[1]),a=n.hexlify(t[2]);return {deviceShare:r,serverShare:s,recoveryShare:a}},Wc=async c=>{if(!c)throw new Error("Cannot create shares");return await Uc(c)},Ri=async(c,e,t,n,r)=>{try{let s=await Dc([t,e]),a=await Wc(s),l=await fetch(`${r}/sdk/wallets/pubkey`,{method:"GET",headers:{"Content-Type":"application/json","X-API-KEY":n}});if(!l.ok)throw await l.text().catch(()=>"N/A"),console.error(`Critical Failure [${c}]: STEP 2 (Get Pubkey). Status: ${l.status}.`),new Error(`Failed to fetch public key. Status: ${l.status}`);let{pubkey:p}=await l.json(),m=await pr(p,a.recoveryShare),g=await fetch(`${r}/sdk/wallets/update`,{method:"POST",headers:{"Content-Type":"application/json","X-API-KEY":n},body:JSON.stringify({walletAddress:c,serverShare:a.serverShare,encryptedRecoveryShare:m})});if(!g.ok)throw await g.text().catch(()=>"N/A"),console.error(`Critical Failure [${c}]: STEP 4 (Update Shares). Status: ${g.status}.`),new Error(`Failed to update shares on server. Status: ${g.status}`);return {recovery:"",server:a.serverShare,device:a.deviceShare}}catch(s){throw console.error(`UpdateShares Critical Failure for ${c}:`,s),s}};});var Er,Kn=K(()=>{Mi();Er=async(c,e,t,n)=>{let r,s,a=await Pi(e,c,t,n),{device:l,server:p}=await Ri(c,a.server,a.recovery,e,n);return r=l,s=p,{mainShare:r,additionalShare:s}};});var ot,Ar=K(()=>{Wn();Kn();Q();ot=async(c,e,t)=>{let{mainShare:n,additionalShare:r}=await Er(c,e,"SOL",t),s=await vr([n,r]),a;try{a=web3_js.Keypair.fromSecretKey(s);}catch(l){throw console.error("Keypair reconstruction failed:",l.message),new Error("KEY_MISMATCH")}if(a.publicKey.toBase58()!==c)throw new Error("KEY_MISMATCH");return {signer:a}};});var _i={};Y(_i,{activateSolMultisig:()=>$c});async function $c(c){let{createKeyServerShare:e,multisigId:t,multisigPda:n,owners:r,threshold:s,vaultAddress:a,rpcUrl:l,recentBlockhash:p,walletAddress:m,apiClient:g}=c,T=await g.post("/sdk/multisig/share/sol",{multisigId:t,walletAddress:m}),y=await re([e,T.share]),A=y.length===32?web3_js.Keypair.fromSeed(y):web3_js.Keypair.fromSecretKey(y),[S]=ft__namespace.getMultisigPda({createKey:A.publicKey});if(S.toBase58()!==n)throw new Error(`PDA_MISMATCH: derived=${S.toBase58()}, expected=${n}`);let O;try{O=await hr(g,m,"SOL");}catch{throw new Error("Failed to fetch wallet server share")}let C;try{C=(await ot(m,g.getApiKey(),g.getBaseUrl())).signer;}catch(k){if(k.message!=="KEY_MISMATCH")throw k;try{C=(await ot(m,g.getApiKey(),g.getBaseUrl())).signer;}catch{throw new Error("Wallet key verification failed, even after forcing a share update. The account may be corrupted.")}}if(C.publicKey.toBase58()!==m)throw new Error("KEY_MISMATCH: wallet public key does not match address");let x=new web3_js.Connection(l,"confirmed"),[R]=ft__namespace.getProgramConfigPda({}),M=(await ft__namespace.accounts.ProgramConfig.fromAccountAddress(x,R)).treasury,_=r.map(k=>({key:new web3_js.PublicKey(k),permissions:ft__namespace.types.Permissions.all()})),B=new web3_js.PublicKey(n),U=ft__namespace.instructions.multisigCreateV2({treasury:M,creator:C.publicKey,multisigPda:B,configAuthority:null,threshold:s,members:_,timeLock:0,createKey:A.publicKey,rentCollector:null}),G=web3_js.SystemProgram.transfer({fromPubkey:C.publicKey,toPubkey:new web3_js.PublicKey(a),lamports:Gc}),W=new web3_js.Transaction;return W.add(U),W.add(G),W.feePayer=C.publicKey,W.recentBlockhash=p,W.partialSign(A),W.partialSign(C),{tx:W.serialize().toString("base64"),updatedDeviceShare:null}}var Gc,Bi=K(()=>{Ze();Ar();Gc=21e5;});var Xn={};Y(Xn,{activateXrpMultisig:()=>jc});async function jc(c){let{multisigId:e,multisigAddress:t,walletAddress:n,signers:r,threshold:s,apiClient:a,rpcUrl:l,deviceShare:p}=c,m=await a.post("/sdk/multisig/share/xrp",{multisigId:e,walletAddress:n}),g=await re([p,m.share]),T=buffer.Buffer.from(g).toString("hex"),y=await at(T);if(y.address!==t)throw y=null,new Error("Master wallet address does not match multisig address");let A=new Wr__namespace.Client(l);try{await A.connect();let O=(await A.request({command:"account_info",account:t,ledger_index:"current"})).result.account_data.Sequence,x=(await A.request({command:"ledger_current"})).result.ledger_current_index+150,R={TransactionType:"SignerListSet",Account:t,SignerQuorum:s,SignerEntries:r.map(G=>({SignerEntry:{Account:G.address,SignerWeight:G.weight}})),Sequence:O,LastLedgerSequence:x,Fee:"12"},P={TransactionType:"AccountSet",Account:t,SetFlag:Wr__namespace.AccountSetAsfFlags.asfDisableMaster,Sequence:O+1,LastLedgerSequence:x,Fee:"12"},M=await A.autofill(R),_=y.sign(M),B=await A.autofill(P),U=y.sign(B);y=null,await a.patch(`/sdk/multisig/execute/xrp/${e}`,{data:{type:"deploy",signerListSetTxBlob:_.tx_blob,disableMasterKeyTxBlob:U.tx_blob}});}finally{y=null,await A.disconnect();}}var Vn=K(()=>{Tt();Ze();});var Gn,Ui,Ir,Wi=K(()=>{Gn=[{inputs:[{internalType:"address",name:"owner",type:"address"},{internalType:"uint256",name:"_threshold",type:"uint256"}],name:"addOwnerWithThreshold",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"address",name:"prevOwner",type:"address"},{internalType:"address",name:"owner",type:"address"},{internalType:"uint256",name:"_threshold",type:"uint256"}],name:"removeOwner",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"address",name:"prevOwner",type:"address"},{internalType:"address",name:"oldOwner",type:"address"},{internalType:"address",name:"newOwner",type:"address"}],name:"swapOwner",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"uint256",name:"_threshold",type:"uint256"}],name:"changeThreshold",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[],name:"getOwners",outputs:[{internalType:"address[]",name:"",type:"address[]"}],stateMutability:"view",type:"function"}],Ui=[{inputs:[{internalType:"address",name:"to",type:"address"},{internalType:"uint256",name:"amount",type:"uint256"}],name:"transfer",outputs:[{internalType:"bool",name:"",type:"bool"}],stateMutability:"nonpayable",type:"function"}],Ir="0x0000000000000000000000000000000000000001";});var Zt={};Y(Zt,{createEvmActions:()=>td,createEvmSendAction:()=>rd,createSolanaInstructions:()=>nd,createTronInstruction:()=>sd,getChangeMethod:()=>ed,isSendOrder:()=>Hi,isSettingsOrder:()=>Qc});function Hi(c){return ["native","erc20","spl","trc20","trc","ada_native","ada_token","xrp_native","xrp_asset","native","asset","native","spl","native","trc20","trc"].includes(c)}function Qc(c){return !Hi(c)}function ed(c,e,t,n){let r=e>1||t>1,s=e>0&&n||t>0&&n||t>0&&e>0;if(r||s){if(c==="EVM")return "MultiSend";if(c==="SOL")return "MultiSend";if(c==="TRON")return "updateOwnerThreshold";if(c==="XRP")return "updateOwnerThreshold"}if(e===1){if(c==="EVM")return "AddOwner";if(c==="SOL")return "addOwner";if(c==="TRON")return "updateOwners";if(c==="XRP")return "updateOwners"}else if(t===1){if(c==="EVM")return "RemoveOwner";if(c==="SOL")return "removeOwner";if(c==="TRON")return "updateOwners";if(c==="XRP")return "updateOwners"}else if(n){if(c==="EVM")return "ChangeThreshold";if(c==="SOL")return "changeThreshold";if(c==="TRON")return "changeThreshold";if(c==="XRP")return "changeThreshold"}return null}async function td(c){let{method:e,multisigAddress:t,threshold:n,newThreshold:r=null,owners:s,ownersAdded:a,ownersRemoved:l,provider:p}=c,m=[],T=[...s];if(p&&t)try{T=(await new ethers.ethers.Contract(t,Gn,p).getOwners()).toArray();}catch{console.warn("Failed to fetch on-chain owners, using provided owners");}switch(e){case "AddOwner":case "addOwnerWithThreshold":if(!a||a.length===0)throw new Error("Missing parameters for addOwner");m.push({to:t,data:vt.encodeFunctionData("addOwnerWithThreshold",[a[0],r||n]),value:"0"});break;case "RemoveOwner":case "removeOwner":if(!l||l.length===0)throw new Error("Missing parameters for removeOwner");let y=l[0],A=y.toLowerCase(),S=T.findIndex(C=>C.toLowerCase()===A);if(S===-1)throw new Error("Owner not found");if(T.length===2)throw new Error("Multisig should have at least 2 owners");let O=S===0?Ir:T[S-1];m.push({to:t,data:vt.encodeFunctionData("removeOwner",[O,y,r||n]),value:"0"});break;case "ChangeThreshold":case "changeThreshold":if(r==null)throw new Error("Missing parameters for changeThreshold");m.push({to:t,data:vt.encodeFunctionData("changeThreshold",[r]),value:"0"});break;case "MultiSend":case "multiSend":{let C=[...a??[]],x=[...l??[]];if(C.length>0&&x.length>0){let R=Math.min(C.length,x.length);for(let P=0;P<R;P++){let M=x.shift(),_=C.shift(),B=M.toLowerCase(),U=T.findIndex(W=>W.toLowerCase()===B);if(U===-1)throw new Error(`Owner to remove (${M}) not found on-chain for swap.`);let G=U===0?Ir:T[U-1];m.push({to:t,data:vt.encodeFunctionData("swapOwner",[G,M,_]),value:"0"}),T.splice(U,1,_);}}if(C.length>0&&C.forEach(R=>{m.push({to:t,data:vt.encodeFunctionData("addOwnerWithThreshold",[R,r??n]),value:"0"}),T.push(R);}),x.length>0&&x.forEach(R=>{let P=R.toLowerCase(),M=T.findIndex(B=>B.toLowerCase()===P);if(M===-1)throw new Error(`Owner to remove (${R}) not found.`);let _=M===0?Ir:T[M-1];m.push({to:t,data:vt.encodeFunctionData("removeOwner",[_,R,r??n]),value:"0"}),T.splice(M,1);}),r!=null&&C.length===0&&x.length===0&&m.push({to:t,data:vt.encodeFunctionData("changeThreshold",[r]),value:"0"}),m.length===0)throw new Error("MultiSend method called with no actions to create.");break}default:throw new Error(`Unsupported EVM method: ${e}`)}return m}function rd(c,e,t,n,r){if(t){let s=ethers.ethers.parseUnits(e,18).toString();return {to:c,data:"0x",value:s}}else {if(!n||r===void 0)throw new Error("Token address and decimals required for ERC20 transfer");let s=ethers.ethers.parseUnits(e,r),a=Zc.encodeFunctionData("transfer",[c,s]);return {to:n,data:a,value:"0"}}}function nd(c,e,t,n){let r=[];switch(c){case "addOwner":case "addOwner":if(!e||e.length===0)throw new Error("Missing parameters for Solana addOwner instruction.");return [{type:c,newOwner:e[0]}];case "removeOwner":case "removeOwner":if(!t||t.length===0)throw new Error("Missing parameters for Solana removeOwner instruction.");return [{type:c,removeOwner:t[0]}];case "changeThreshold":case "changeThreshold":if(n===void 0)throw new Error("Missing parameters for Solana changeThreshold instruction.");return [{type:c,newThreshold:n}];case "MultiSend":case "MultiSend":if(e&&e.length>0&&e.forEach(s=>{r.push({type:"addOwner",newOwner:s});}),t&&t.length>0&&t.forEach(s=>{r.push({type:"removeOwner",removeOwner:s});}),n!==void 0&&r.push({type:"changeThreshold",newThreshold:n}),r.length===0)throw new Error("MultiSend method called with no actions to create.");return r;default:throw new Error(`Unsupported Solana instruction method: ${c}`)}}function sd(c,e,t){switch(c){case "updateOwners":case "updateOwners":if(!e)throw new Error("Owners are required for Tron updateOwners instruction.");return {type:c,owners:e};case "changeThreshold":case "changeThreshold":if(t===void 0)throw new Error("New threshold is required for Tron changeThreshold instruction.");return {type:c,newThreshold:t};case "updateOwnerThreshold":case "updateOwnerThreshold":if(!e||t===void 0)throw new Error("Both owners and newThreshold are required for Tron updateOwnerThreshold instruction.");return {type:c,owners:e,newThreshold:t};default:throw new Error("Unsupported Tron instruction method.")}}var vt,Zc,Qt=K(()=>{Wi();Q();vt=new ethers.ethers.Interface(Gn),Zc=new ethers.ethers.Interface(Ui);});var Gi,$i=K(()=>{Ge();Gi=c=>{let{instructions:e,threshold:t}=c;switch(e.type){case Ve.addOwner:{let n=e.newOwner;if(!n)throw new Error("Error: newMember doesn't exist");let r={__kind:"AddMember",newMember:{key:new web3_js.PublicKey(n),permissions:ft__namespace.types.Permissions.all()}};return t?[r,{__kind:"ChangeThreshold",newThreshold:t}]:[r]}case Ve.removeOwner:{let n=e.removeOwner;if(!n)throw new Error("Error: oldMember doesn't exist");let r={__kind:"RemoveMember",oldMember:new web3_js.PublicKey(n)};return t?[r,{__kind:"ChangeThreshold",newThreshold:t}]:[r]}case Ve.changeThreshold:return [{__kind:"ChangeThreshold",newThreshold:e.newThreshold}];case Ve.spl:throw new Error("SPL instructions are not yet supported.");default:throw new Error(`Unsupported method type: ${e?.type}`)}};});var er,$n=K(()=>{er=c=>{let e=String(c),t=/^\d+(\.\d{1,9})?$/,n;try{n=parseFloat(e);}catch{throw new Error("Invalid number format for SOL amount.")}if(isNaN(n)||n<0)throw new Error("Invalid or negative SOL amount provided.");let r=n.toFixed(9).replace(/\.?0+$/,"");if(!t.test(r))throw new Error("SOL amount must have up to 9 decimal places and contain only digits and a period.");let s=Math.floor(n*1e9);if(s===0&&n>0)throw new Error("Amount is too small to be represented in lamports (potential dust).");return BigInt(s)};});var zi,Yi=K(()=>{zi=async(c,e)=>{try{let t=await c.getAccountInfo(e);if(!t)throw new Error("Token mint account not found");return t.owner.equals(ao.TOKEN_2022_PROGRAM_ID)?(console.log("Detected Token-2022 (Token Extensions) program"),ao.TOKEN_2022_PROGRAM_ID):(console.log("Detected legacy Token program"),ao.TOKEN_PROGRAM_ID)}catch(t){return console.warn("Failed to detect token program, defaulting to TOKEN_PROGRAM_ID:",t),ao.TOKEN_PROGRAM_ID}};});var ea={};Y(ea,{createSolanaMultisigOrder:()=>qn});var ud,qn,jn=K(()=>{Ge();Ar();$i();$n();Yi();ud=(c,e)=>{let[t="0",n=""]=c.split("."),r=(n+"0".repeat(e)).slice(0,e),a=(t+(r||"0".repeat(e))).replace(/^0+(?=\d)/,"");return a===""?0n:BigInt(a)},qn=async c=>{let{address:e,apiKey:t,multisigPda:n,method:r,instructions:s,orderId:a,rpcUrl:l,vaultAddress:p,selectedToken:m,apiUrl:g,memo:T}=c,y;try{y=(await ot(e,t,g)).signer;}catch(_){if(_.message!=="KEY_MISMATCH")throw _;try{y=(await ot(e,t,g)).signer;}catch{throw new Error("Wallet key verification failed, even after forcing a share update. The account may be corrupted.")}}let A=new web3_js.Connection(l,"confirmed"),S=new web3_js.PublicKey(n),O=await ft__namespace.accounts.Multisig.fromAccountAddress(A,S),C=BigInt(O.transactionIndex.toString())+1n,x=new web3_js.Transaction,R=(await A.getLatestBlockhash()).blockhash;if(r===Ve.native){if(!s[0].toPubkey||!s[0].amount)throw new Error("Error: toPubkey or amount doesn't exist");let _=er(String(s[0].amount)),U=[web3_js.SystemProgram.transfer({fromPubkey:new web3_js.PublicKey(p),toPubkey:new web3_js.PublicKey(s[0].toPubkey),lamports:_})];T&&U.push(splMemo.createMemoInstruction(T));let G=new web3_js.TransactionMessage({payerKey:new web3_js.PublicKey(p),recentBlockhash:R,instructions:U}),W=ft__namespace.instructions.vaultTransactionCreate({multisigPda:S,transactionIndex:C,creator:y.publicKey,vaultIndex:0,ephemeralSigners:0,transactionMessage:G,memo:T||a});x.add(W);}else if(r===Ve.spl)try{let _=s[0];if(!_?.toPubkey||!_?.amount)throw new Error("SPL: missing toPubkey or amount");if(!m?.address||typeof m.decimals!="number")throw new Error("SPL: selectedToken info missing (mint/decimals)");let[B]=ft__namespace.getVaultPda({multisigPda:S,index:0}),U=new web3_js.PublicKey(m.address),G=new web3_js.PublicKey(_.toPubkey),W=await zi(A,U);console.log(`\u{1F50D} Using token program: ${W.toBase58()}`);let k=await A.getTokenAccountsByOwner(B,{mint:U,programId:W});if(k.value.length===0)throw new Error(`SPL: vault has no token account for mint ${m.address}`);let N=k.value[0].pubkey,X=await ao.getAssociatedTokenAddress(U,G,!0,W,ao.ASSOCIATED_TOKEN_PROGRAM_ID),E=[];await A.getAccountInfo(X)||E.push(ao.createAssociatedTokenAccountInstruction(y.publicKey,X,G,U,W,ao.ASSOCIATED_TOKEN_PROGRAM_ID));let d=ud(String(_.amount),m.decimals);if(d<=0n)throw new Error("SPL: amount must be > 0");E.push(ao.createTransferCheckedInstruction(N,U,X,B,d,m.decimals,[],W)),T&&E.push(splMemo.createMemoInstruction(T));let u=new web3_js.TransactionMessage({payerKey:B,recentBlockhash:R,instructions:E}),h=ft__namespace.instructions.vaultTransactionCreate({multisigPda:S,transactionIndex:C,creator:y.publicKey,vaultIndex:0,ephemeralSigners:0,transactionMessage:u,memo:T||a});x.add(h);}catch(_){throw console.error("createSolanaMultisigOrder (SPL) failed:",_),_}else {let _=c.instructions.map(U=>Gi({...c,instructions:U})).flat(),B=ft__namespace.instructions.configTransactionCreate({multisigPda:S,creator:y.publicKey,transactionIndex:C,actions:_,memo:a,rentPayer:y.publicKey});x.add(B);}let P=ft__namespace.instructions.proposalCreate({creator:y.publicKey,multisigPda:S,transactionIndex:C});x.add(P),x.feePayer=y.publicKey,x.recentBlockhash=R,x.partialSign(y);let M=x.serialize().toString("base64");return console.log("\u{1F680} ~ vaultTransaction:",M),{tx:M}};});var zn={};Y(zn,{signXrpMultisigOrder:()=>md});async function md(c){let{address:e,orderId:t,multisigId:n,apiClient:r}=c,{mainShare:s,additionalShare:a}=await Ke(r,e,"XRP"),l=await re([s,a]),p=buffer.Buffer.from(l).toString("hex"),m=await at(p);if(m.address!==e)throw new Error("KEY_MISMATCH");let g=null;for(let T=0;T<=ta;T++){T>0&&await new Promise(y=>setTimeout(y,hd*T));try{let y=await r.get(`/sdk/order/${t}/tx-xrp`),{transaction:A,version:S}=y;A?.DestinationTag&&typeof A?.DestinationTag=="string"&&(A.DestinationTag=+A.DestinationTag);let O=m.sign(A,!0),x=Wr__namespace.decode(O.tx_blob)?.Signers?.[0]?.Signer;if(!x)throw new Error("Failed to extract signer from decoded XRP multisig transaction");let{TxnSignature:R,SigningPubKey:P}=x;return await r.post("/sdk/order/sign/xrp",{orderId:t,multisigId:n,walletAddress:e,signature:R,signingPubKey:P,version:S}),{signature:R,version:S}}catch(y){if((y?.status||y?.statusCode||y?.response?.status)===409&&T<ta){g=y;continue}throw y}}throw g||new Error("XRP order signing failed after retries")}var ta,hd,Yn=K(()=>{Tt();Ze();Q();ta=3,hd=500;});var Zn={};Y(Zn,{signAdaMultisigOrder:()=>gd});var gd,Qn=K(()=>{qe();gd=async c=>{let{address:e,hashToSign:t,orderId:n,multisigId:r,apiClient:s}=c;if(!t)throw new Error("Order hash to sign is missing");let a=new ee(s),{privateKey:l}=await a.reconstructWithRetry(()=>a.reconstructAdaKey(e)),p=await import('@emurgo/cardano-serialization-lib-browser'),m=p.TransactionHash.from_bytes(buffer.Buffer.from(t,"hex")),g=p.make_vkey_witness(m,l),T=buffer.Buffer.from(g.to_bytes()).toString("hex"),A=l.to_public().hash(),S=buffer.Buffer.from(A.to_bytes()).toString("hex");return await s.post("/sdk/order/sign/ada",{orderId:n,multisigId:r,walletAddress:e,witnessHex:T,keyHashHex:S}),{witnessHex:T,keyHashHex:S}};});var oa,ca,da,Et,tt,tr=K(()=>{oa=async(c,e)=>{try{let t=await fetch(`${e}/address/${c}/utxo`);if(!t.ok)throw new Error(`Failed to fetch UTXOs: ${t.statusText}`);return await t.json()}catch(t){throw console.error("Error fetching UTXOs:",t),new Error("Failed to fetch UTXOs.")}},ca=async c=>{let e=`${c}/v1/fees/recommended`;try{let n=await(await fetch(e)).json();return n.halfHourFee||n.fastestFee||10}catch(t){throw console.error("Error fetching BTC fee:",t),new Error("Failed to fetch recommended fee.")}},da=async(c,e)=>{try{let t=await fetch(`${e}/tx`,{method:"POST",body:c});if(!t.ok){let n=await t.text();try{if(n.includes("RPC error: ")){let r=n.split("RPC error: ")[1],s=JSON.parse(r);if(s.message.includes("dust")||s.message.includes("non-standard"))throw new Error("The transaction amount is too small to be broadcasted. Please increase the amount.")}}catch{}throw new Error(`Error: Failed to broadcast transaction. Details: ${n}`)}return await t.text()}catch(t){throw console.error("Error broadcasting transaction:",t),t}},Et=(c,e)=>{try{c.addInput({...e,witnessUtxo:{script:e.witnessUtxo.script,value:BigInt(e.witnessUtxo.value)}});}catch(t){try{c.addInput({...e,witnessUtxo:{script:e.witnessUtxo.script,value:Number(e.witnessUtxo.value)}});}catch(n){throw console.error("Failed to add input with BigInt:",t),console.error("Failed to add input with Number:",n),t}}},tt=(c,e)=>{try{c.addOutput({address:e.address,value:BigInt(e.value)});}catch(t){try{c.addOutput({address:e.address,value:BigInt(e.value)});}catch(n){throw console.error("Failed to add output with BigInt:",t),console.error("Failed to add output with Number:",n),t}}};});var ss,xa=K(()=>{Q();Ze();ss=async(c,e)=>{let{mainShare:t,additionalShare:n}=await Ke(e,c,"EVM"),r=await re([t,n]),s;try{let a="0x"+Buffer.from(r).toString("hex");s=new ethers.ethers.Wallet(a);}catch(a){throw console.error("EVM Key reconstruction failed:",a.message),new Error("KEY_MISMATCH")}if(s.address.toLowerCase()!==c.toLowerCase())throw new Error("KEY_MISMATCH");return {signer:s}};});var ba,Ia=K(()=>{xa();kt();ba=async({address:c,apiClient:e,transaction:t,expectedChainId:n})=>{let r;try{r=(await ss(c,e)).signer;}catch(s){if(s.message!=="KEY_MISMATCH")throw s;try{r=(await ss(c,e)).signer;}catch{throw new Error("Wallet key verification failed, even after forcing a share update. The account may be corrupted.")}}try{let s=ethers.ethers.Transaction.from(t),a=BigInt(n);if(s.chainId!==a)throw console.error(`Chain ID mismatch. Expected: ${n}, Received: ${s.chainId}`),new Error("Transaction chain ID does not match the expected network.");if(s.nonce===void 0||s.nonce===null)throw new Error("Transaction nonce is missing.");let l=s.data&&s.data!=="0x",p=gr(n);if(!p)throw new Error(`Unsupported EVM chain ID: ${n}`);let m=l?2e5:5e5;s.gasLimit>BigInt(m)&&console.warn(`Gas limit (${s.gasLimit}) exceeds recommended maximum (${m})`);let g=ethers.ethers.parseUnits(String(p.maxGwei),"gwei");if(s.gasPrice&&s.gasPrice>g)throw console.error(`Gas price too high: ${s.gasPrice}`),new Error("Gas price exceeds safe limit.");if(s.maxFeePerGas&&s.maxFeePerGas>g)throw console.error(`Max Fee Per Gas too high for ${p.key}. Limit: ${p.maxGwei} Gwei`),new Error("Max Fee Per Gas exceeds safe limit.");if(l)try{if(s.data.startsWith("0xa9059cbb")){let A=s.data.slice(10);if(A.length!==128)throw new Error("Invalid ERC20 transfer data length");let S="0x"+A.slice(24,64),O=ethers.ethers.getAddress(S),C="0x"+A.slice(64,128);if(BigInt(C)<=0n)throw new Error("Invalid transfer amount");if(!ethers.ethers.isAddress(O))throw new Error("Invalid recipient address in transfer data")}else console.warn("Transaction contains data but not a standard ERC20 transfer");}catch(y){throw console.error("Error validating ERC20 data:",y),new Error("Not standart transaction")}return l&&s.value&&s.value>0n&&console.warn("ERC20 transfer includes native token value - this is unusual"),{tx:await r.signTransaction(s)}}catch(s){throw console.error("Failed to sign transaction:",s),new Error("Failed to sign transaction.")}};});var Sa={};Y(Sa,{evmSendTransaction:()=>qd});var $d,qd,Oa=K(()=>{Ia();Tr();kt();$d=["function transfer(address to, uint256 amount) returns (bool)","function decimals() view returns (uint8)"],qd=async({input:c,activeWallet:e,chainId:t,apiClient:n,rpcConfig:r})=>{let s=new mt(n,r),{to:a,amount:l,estimatedFee:p,tokenAddress:m,isNativeToken:g}=c.data;if(!s?.getProvider)throw new Error("getProvider function is missing");let T=s.getProvider(t);if(!T)throw new Error("Provider unavailable. Please try again later.");let y=p?.gasLimit?p.gasLimit:"50000",A=p?.gasPrice?p.gasPrice:"20000000000",S;if(g)S={to:a,value:ethers.ethers.parseEther(l.toString()).toString(),data:"0x",gasLimit:y,gasPrice:A,chainId:Number(t)};else {if(!m)throw new Error("Token address is required for ERC20 transfers");try{let O=new ethers.ethers.Contract(m,$d,T),C=await O.decimals(),x=ethers.ethers.parseUnits(l.toString(),C),R=O.interface.encodeFunctionData("transfer",[a,x]);S={to:m,value:"0",data:R,gasLimit:y,gasPrice:A,chainId:Number(t)};}catch(O){throw console.error("Error preparing ERC20 transfer:",O),new Error("Failed to prepare ERC20 transfer")}}if(!s?.getNonce)throw new Error("getNonce function is missing");S.nonce=await s.getNonce(T,e.address);try{let{tx:O}=await ba({address:e.address,apiClient:n,transaction:S,expectedChainId:Number(t)});if(!s?.broadcastTransaction)throw new Error("broadcastTransaction function is missing");let C=await s.broadcastTransaction(T,O),x=new Promise((R,P)=>setTimeout(()=>P(new Error("Confirmation timeout")),6e4));try{await Promise.race([C.wait(),x]);}catch(R){throw R}return {...C}}catch(O){let C=O,x=(C.message||C.reason||"").toLowerCase();throw C.code==="INSUFFICIENT_FUNDS"||x.includes("insufficien")?new Error(`Not enough ${ze(t)} to pay for gas or transaction value.`):x.includes("execution reverted")||x.includes("revert")?new Error("Transaction failed. Check inputs, wallet balance, or permissions."):x.includes("out of gas")?new Error("Transaction ran out of gas."):C}};});var as,Ca=K(()=>{Q();Ze();as=async(c,e)=>{let{mainShare:t,additionalShare:n}=await Ke(e,c,"SOL"),r=await re([t,n]),s;try{s=web3_js.Keypair.fromSecretKey(r);}catch(a){throw console.error("Keypair reconstruction failed:",a.message),new Error("KEY_MISMATCH")}if(s.publicKey.toBase58()!==c)throw new Error("KEY_MISMATCH");return {signer:s}};});var Pa,Ra=K(()=>{Pa=c=>{let e=String(c),t=/^\d+(\.\d{1,9})?$/,n;try{n=parseFloat(e);}catch{throw new Error("Invalid number format for SOL amount.")}if(isNaN(n)||n<0)throw new Error("Invalid or negative SOL amount provided.");let r=n.toFixed(9).replace(/\.?0+$/,"");if(!t.test(r))throw new Error("SOL amount must have up to 9 decimal places and contain only digits and a period.");let s=Math.floor(n*1e9);if(s===0&&n>0)throw new Error("Amount is too small to be represented in lamports (potential dust).");return BigInt(s)};});var _a,Ba=K(()=>{_a=async(c,e)=>{try{let t=await c.getAccountInfo(e);if(!t)throw new Error("Token mint account not found");return t.owner.equals(ao.TOKEN_2022_PROGRAM_ID)?(console.log("Detected Token-2022 (Token Extensions) program"),ao.TOKEN_2022_PROGRAM_ID):(console.log("Detected legacy Token program"),ao.TOKEN_PROGRAM_ID)}catch(t){return console.warn("Failed to detect token program, defaulting to TOKEN_PROGRAM_ID:",t),ao.TOKEN_PROGRAM_ID}};});var Da={};Y(Da,{sendSolanaTransaction:()=>sl});var nl,sl,Ua=K(()=>{Ca();Ra();Ba();nl=(c,e)=>{let[t="0",n=""]=c.split("."),r=(n+"0".repeat(e)).slice(0,e),s=t+r;return BigInt(s)},sl=async({address:c,apiClient:e,to:t,amount:n,rpcUrl:r,isNativeToken:s=true,tokenAddress:a,decimals:l=9,memo:p})=>{let m;try{m=(await as(c,e)).signer;}catch(g){if(g.message!=="KEY_MISMATCH")throw g;try{m=(await as(c,e)).signer;}catch{throw new Error("Wallet key verification failed, even after forcing a share update. The account may be corrupted.")}}try{if(!r.startsWith("https://"))throw new Error("Invalid or unsecure RPC URL provided.");let T;try{T=new web3_js.PublicKey(t);}catch{throw new Error("Recipient address is not a valid Solana Public Key.")}let y=String(n);if(!/^\d+(\.\d+)?$/.test(y))throw new Error(`Invalid amount format. Must be a number with up to ${l} decimal places.`);let A=new web3_js.Connection(r,"confirmed"),S=new web3_js.Transaction;if(s){let C=Pa(y);if(C<=0n)throw new Error("Transfer amount must be positive.");let x=await A.getBalance(m.publicKey,"confirmed");if(BigInt(x)<C+5000n)throw new Error("Insufficient balance to cover transfer amount and transaction fee.");let P=await A.getBalance(T,"confirmed"),M=await A.getMinimumBalanceForRentExemption(0);if(P+Number(C)<M)throw new Error(`Recipient account would have insufficient funds for rent exemption. Minimum transfer amount: ${(M-P)/1e9} SOL`);let _=web3_js.SystemProgram.transfer({fromPubkey:m.publicKey,toPubkey:T,lamports:C});S.add(_),p&&S.add(splMemo.createMemoInstruction(p));}else {if(!a)throw new Error("Token address is required for SPL token transfers.");let C;try{C=new web3_js.PublicKey(a);}catch(W){throw new Error(`Invalid SPL token mint address. ${W}`)}let x=await _a(A,C),R=nl(y,l);if(R<=0n)throw new Error("Transfer amount must be positive.");let P=await ao.getAssociatedTokenAddress(C,m.publicKey,!1,x,ao.ASSOCIATED_TOKEN_PROGRAM_ID);try{let W=await A.getTokenAccountBalance(P);if(BigInt(W.value.amount)<R)throw new Error(`Insufficient token balance. Available: ${W.value.uiAmount}, Required: ${n}`)}catch(W){throw W.message?.includes("could not find account")?new Error("Sender does not have an account for this token. Balance may be 0."):W}let M=await ao.getAssociatedTokenAddress(C,T,!0,x,ao.ASSOCIATED_TOKEN_PROGRAM_ID);if(!await A.getAccountInfo(M)){console.log("Recipient token account does not exist. Creating associated token account...");let W=ao.createAssociatedTokenAccountInstruction(m.publicKey,M,T,C,x,ao.ASSOCIATED_TOKEN_PROGRAM_ID);S.add(W);let k=await A.getBalance(m.publicKey,"confirmed"),N=await A.getMinimumBalanceForRentExemption(165),X=10000n;if(BigInt(k)<BigInt(N)+X)throw new Error(`Insufficient SOL to create recipient token account. Need approximately ${(Number(N)+Number(X))/1e9} SOL for rent and fees.`)}let B=x.equals(ao.TOKEN_2022_PROGRAM_ID)?ao.createTransferCheckedInstruction(P,C,M,m.publicKey,R,l,[],x):ao.createTransferInstruction(P,M,m.publicKey,R,[],x);S.add(B),p&&S.add(splMemo.createMemoInstruction(p));let U=await A.getBalance(m.publicKey,"confirmed");if(BigInt(U)<10000n)throw new Error("Insufficient SOL balance to pay for transaction fees.")}let O=await web3_js.sendAndConfirmTransaction(A,S,[m],{commitment:"confirmed",skipPreflight:!1,preflightCommitment:"confirmed"});return console.log(`Transaction successful. Signature: ${O}${s?" (Native SOL Transfer)":" (SPL Token Transfer)"}`),{tx:O}}catch(g){throw console.error("sendTransaction failed:",g),g.message?.includes("Insufficient")?g:g.message?.includes("blockhash")?new Error("Transaction failed: Network timeout. Please try again."):g.message?.includes("0x1")?new Error("Transaction failed: Insufficient funds for transaction fee."):g.message?.includes("custom program error")?new Error("Transaction failed: Token transfer rejected by program. Check token account status."):new Error(g.message||"Transaction failed. Please try again.")}};});var Ka={};Y(Ka,{sendBtcTransaction:()=>cl});var ol,cl,Ha=K(()=>{Q();it();qe();tr();ol=cc__default.default(dc__namespace);"toJSON"in BigInt.prototype||Object.defineProperty(BigInt.prototype,"toJSON",{get(){return function(){return this.toString()}}});cl=async({activeWallet:c,to:e,amount:t,apiClient:n,network:r})=>{let s=n.getNetwork(),a=s==="mainnet"?rt__namespace.networks.bitcoin:rt__namespace.networks.testnet;try{rt__namespace.address.toOutputScript(e,a);}catch{throw new Error("Recipient address is invalid for the current network.")}let l=n.getRpcConfig(),p=Ye("BTC",l),m=await oa(c.address,p);if(m.length===0)throw new Error("No funds found on your Bitcoin address.");let g=Number(t);if(isNaN(g)||g<=0)throw new Error("Invalid amount provided.");let T=Math.round(g*1e8),y=await ca(p),A=[...m].sort((b,f)=>f.value-b.value),S=0,O=[],C=2;for(let b of A){O.push(b),S+=b.value;let o=O.length*148+C*34+10,v=Math.ceil(y*o);if(S>=T+v)break}let R=O.length*148+C*34+10,P=Math.ceil(y*R);if(O.reduce((b,f)=>b+f.value,0)<T+P)throw new Error("Insufficient BTC balance to cover amount and fees.");let _=1e4;if(P>_||P<=0)throw new Error(`Estimated fee is outside the allowed range (1 - ${_} sats).`);let B=new ee(n),U=await B.reconstructWithRetry(()=>B.reconstructBtcKey(c.address,s==="mainnet")),{privateKeyWif:G}=U,W=ol.fromWIF(G,a),k=BigInt(T),N=new rt__namespace.Psbt({network:a}),X=0;for(let b of O)Et(N,{hash:b.txid,index:b.vout,witnessUtxo:{script:rt__namespace.address.toOutputScript(c.address,a),value:b.value}}),X+=b.value;tt(N,{address:e,value:k});let E=BigInt(Math.round(P)),i=BigInt(X)-k-E,d=BigInt(546);if(i<0n)throw new Error("Insufficient funds to cover amount and fee.");if(i>0n&&i<d&&(i=0n),i>0n&&tt(N,{address:c.address,value:i}),BigInt(X)>5000000000n)throw new Error("Total input amount exceeds safe limit (50 BTC).");let h={publicKey:buffer.Buffer.from(W.publicKey),sign:b=>buffer.Buffer.from(W.sign(b))};for(let b=0;b<O.length;b++)N.signInput(b,h);N.finalizeAllInputs();let w=N.extractTransaction().toHex();return {hash:await da(w,p),rawTransaction:w}};});var cs={};Y(cs,{sendAdaTransaction:()=>dl});function ll(c,e){if(e===0)return c;let t=c.split("."),n=t[0]||"0",r=(t[1]||"").padEnd(e,"0").slice(0,e);return (BigInt(n)*BigInt(10**e)+BigInt(r)).toString()}var dl,ds=K(()=>{qe();dl=async c=>{let{address:e,to:t,amount:n,isNativeToken:r,apiClient:s,chainId:a,policyId:l,assetName:p,decimals:m}=c,g=r!==false;if(!t||typeof t!="string"||!t.startsWith("addr"))throw new Error("Invalid Cardano address format.");if(g){let b=Number(n);if(isNaN(b)||b<=0)throw new Error("Invalid amount provided.")}else {if(!n)throw new Error("Missing token parameter: amount.");if(!p)throw new Error("Missing token parameters: assetName.");if(!l)throw new Error("Missing token parameters: policyId.");if(l.length!==56)throw new Error("Invalid policyId: must be 56 hex characters.")}let T=new ee(s),{privateKey:y}=await T.reconstructWithRetry(()=>T.reconstructAdaKey(e)),S=(await s.get("/sdk/order/utxos/ada",{params:{address:e,chainId:a}}))?.utxos||[];if(!S||S.length===0)throw new Error("No UTXOs found!");let O=g?S.filter(b=>!b.nativeAssets||b.nativeAssets.length===0):S;if(O.length===0)throw new Error(g?"No pure ADA UTXOs available. Your ADA is locked in UTXOs with tokens \u2014 send the tokens first to free it.":"No UTXOs found for this transaction.");if(!g&&S.filter(o=>!o.nativeAssets||o.nativeAssets.length===0).reduce((o,v)=>o+Number(v.value),0)<15e5)throw new Error("Insufficient free ADA to send tokens. All your ADA is locked in token UTXOs. Please send at least 1.5 ADA to your wallet address to enable token transfers.");let C=p??"";if(!g&&l){for(let b of S)if(b.nativeAssets&&b.nativeAssets.length>0){let f=b.nativeAssets.find(o=>o.policyId===l);if(f){C=f.assetName;break}}}let x=await import('@emurgo/cardano-serialization-lib-browser'),{blake2b:R}=await import('blakejs');try{x.Address.from_bech32(t);}catch{throw new Error("Recipient address is invalid for the current network.")}let P={minFeeA:44,minFeeB:155381,poolDeposit:5e8,keyDeposit:2e6,maxValueSize:5e3,maxTxSize:16384,coinsPerUtxoByte:4310},M=x.TransactionBuilderConfigBuilder.new().fee_algo(x.LinearFee.new(x.BigNum.from_str(P.minFeeA.toString()),x.BigNum.from_str(P.minFeeB.toString()))).pool_deposit(x.BigNum.from_str(P.poolDeposit.toString())).key_deposit(x.BigNum.from_str(P.keyDeposit.toString())).max_value_size(P.maxValueSize).max_tx_size(P.maxTxSize).coins_per_utxo_byte(x.BigNum.from_str(P.coinsPerUtxoByte.toString())).build(),_=x.TransactionBuilder.new(M),B=x.TransactionUnspentOutputs.new();for(let b of O){let f=x.TransactionHash.from_bytes(buffer.Buffer.from(b.txHash,"hex")),o=x.TransactionInput.new(f,b.index),v=x.Value.new(x.BigNum.from_str(b.value.toString()));if(b.nativeAssets&&b.nativeAssets.length>0){let L=x.MultiAsset.new();for(let D of b.nativeAssets){let V=x.ScriptHash.from_bytes(buffer.Buffer.from(D.policyId,"hex")),$=x.AssetName.new(buffer.Buffer.from(D.assetName,"hex")),z=L.get(V)??x.Assets.new();z.insert($,x.BigNum.from_str(D.value.toString())),L.insert(V,z);}v.set_multiasset(L);}let F=x.TransactionOutput.new(x.Address.from_bech32(e),v);B.add(x.TransactionUnspentOutput.new(o,F));}let U=x.Address.from_bech32(t);if(g){let b=Number(n)*1e6,f=x.Value.new(x.BigNum.from_str(Math.floor(b).toString()));_.add_output(x.TransactionOutput.new(U,f));}else {let b=x.ScriptHash.from_bytes(buffer.Buffer.from(l,"hex")),f=x.AssetName.new(buffer.Buffer.from(C,"hex")),o=ll(n.toString(),m??0),v=x.Assets.new();v.insert(f,x.BigNum.from_str(o));let F=x.MultiAsset.new();F.insert(b,v);let L;try{let V=x.Value.new(x.BigNum.from_str("0"));V.set_multiasset(F);let $=x.TransactionOutput.new(U,V),z=x.DataCost.new_coins_per_byte(x.BigNum.from_str(P.coinsPerUtxoByte.toString()));L=x.min_ada_for_output($,z);}catch{L=x.BigNum.from_str("1500000");}let D=x.Value.new(L);D.set_multiasset(F),_.add_output(x.TransactionOutput.new(U,D));}let G=g?x.CoinSelectionStrategyCIP2.LargestFirst:x.CoinSelectionStrategyCIP2.LargestFirstMultiAsset;_.add_inputs_from(B,G);let W=x.Address.from_bech32(e);_.add_change_if_needed(W);let k=_.build(),N=k.to_bytes(),X=R(N,void 0,32),E=x.TransactionHash.from_bytes(X),i=x.TransactionWitnessSet.new(),d=x.Vkeywitnesses.new(),u=x.make_vkey_witness(E,y);d.add(u),i.set_vkeys(d);let h=x.Transaction.new(k,i,void 0),w=buffer.Buffer.from(h.to_bytes()).toString("hex");return {hash:(await s.post("/sdk/order/send/ada",{txHex:w,chainId:a})).txHash||w}};});var Xr={};Y(Xr,{calculateMultisigFee:()=>dt,calculateReserveRequirement:()=>ul,checkExpiration:()=>yl,checkXrpAccountExists:()=>ml,dropsToXrp:()=>nt,fetchAccountTrustLines:()=>hl,fetchXrpAccountReserveInfo:()=>pl,formatTokenDisplay:()=>fl,hasTrustLine:()=>gl,parseTokenAddress:()=>ps,validateXrpAddress:()=>Kr,validateXrpAmount:()=>Hr,xrpToDrops:()=>us});function Kr(c){return /^r[1-9A-HJ-NP-Za-km-z]{24,34}$/.test(c)}function nt(c){return (Number(c)/ls).toString()}function us(c){return Math.floor(Number(c)*ls).toString()}function ps(c){let e=c.split(".");if(e.length<2)throw new Error(`Invalid XRP token address format: ${c}. Expected "currency.issuer"`);return {currency:e[0],issuer:e[1]}}function Hr(c){let e=Number(c);if(isNaN(e)||e<0)return false;let t=c.split(".");return !(t.length===2&&t[1].length>6)}function dt(c){return Math.ceil((1+c)*10*1.4).toString()}function ul(c=0,e=false){let n=.2*c,r=e?.2:0;return (1+n+r).toString()}async function pl(c,e){let t=new Wr__namespace.Client(e);try{await t.connect();let n;try{n=await t.request({command:"account_info",account:c,ledger_index:"validated"});}catch(x){throw x?.data?.error==="actNotFound"?new Error(`XRP account not found: ${c}`):x}let r=n.result.account_data,s=r.Balance,a=r.OwnerCount,p=(await t.request({command:"account_objects",account:c,ledger_index:"validated",limit:400})).result.account_objects||[],m=0,g=!1,T=0,y=0,A=0;for(let x of p)switch(x.LedgerEntryType){case "RippleState":m++;break;case "SignerList":g=!0;break;case "Offer":T++;break;case "Escrow":y++;break;default:A++;}let S=Number(s)/ls,O=1+.2*a,C=Math.max(0,S-O);return {address:c,totalBalance:S.toString(),availableBalance:C.toString(),totalReserve:O.toString(),baseReserve:"1",ownerCount:a,ownerReservePerObject:"0.2",objects:{trustLines:m,signerList:g,offers:T,escrows:y,otherObjects:A}}}finally{await t.disconnect();}}async function hl(c,e){let t=new Wr__namespace.Client(e);try{return await t.connect(),((await t.request({command:"account_lines",account:c,ledger_index:"validated"})).result.lines||[]).map(r=>({currency:r.currency,issuer:r.account,balance:r.balance,limit:r.limit}))}catch(n){let r=n?.data?.error;if(r==="actNotFound"||r==="actMalformed")return [];throw n}finally{await t.disconnect();}}async function ml(c,e){let t=new Wr__namespace.Client(e);try{return await t.connect(),await t.request({command:"account_info",account:c,ledger_index:"validated"}),!0}catch(n){if(n?.data?.error==="actNotFound")return false;throw n}finally{await t.disconnect();}}function gl(c,e,t){return c.some(n=>n.currency.toLowerCase()===e.toLowerCase()&&n.issuer.toLowerCase()===t.toLowerCase())}function fl(c,e){if(c.length<=3)return `${e} ${c}`;if(c.length===40)try{let t=c.replace(/0+$/,""),n=Buffer.from(t,"hex").toString("ascii");return n.length<=3&&/^[A-Z]+$/.test(n)?`${e} ${n}`:`${e} ${c.substring(0,8)}...`}catch{return `${e} ${c.substring(0,8)}...`}return `${e} ${c}`}function yl(c,e){let t=c-e;if(t<=0)return {expired:true,remaining:0};let n=t*4,r=Math.floor(n/3600),s=Math.floor(n%3600/60),a=n%60,l;return r>0?l=`${r}h ${s}m`:s>0?l=`${s}m ${a}s`:l=`${a}s`,{expired:false,remaining:t,remainingTime:l}}var ls,st=K(()=>{ls=1e6;});var hs={};Y(hs,{sendXrpTransaction:()=>Tl});async function Tl(c){let{address:e,to:t,amount:n,apiClient:r,rpcUrl:s,tokenAddress:a,isNativeToken:l=true,memo:p}=c;if(e===t)throw new Error("XRP Ledger does not allow sending a Payment to yourself (temREDUNDANT).");let{mainShare:m,additionalShare:g}=await Ke(r,e,"XRP"),T=await re([m,g]),y=Buffer.from(T).toString("hex"),A=await at(y);if(A.address!==e)throw new Error("KEY_MISMATCH");let S=new Wr__namespace.Client(s);try{await S.connect();let O;if(l||!a||a===viem.zeroAddress)O=us(n);else {let{currency:B,issuer:U}=ps(a);O={currency:B,value:n,issuer:U};}let C=p&&/^\d+$/.test(p)?parseInt(p,10):void 0,x={TransactionType:"Payment",Account:e,Destination:t,Amount:O,...C!==void 0&&{DestinationTag:C}},R=await S.autofill(x),P=A.sign(R),_=(await S.submitAndWait(P.tx_blob)).result.meta?.TransactionResult||"";if(!_.startsWith("tes"))throw new Error(`XRP transaction failed: ${_}. ${vl(_)}`);return {hash:P.hash,tx:P.tx_blob,result:_}}finally{await S.disconnect();}}function vl(c){return {tecUNFUNDED_PAYMENT:"Insufficient balance for this transaction.",tecNO_DST_INSUF_XRP:"Destination requires at least 1 XRP to activate.",tecPATH_DRY:"No trust line or insufficient liquidity for this token.",tefPAST_SEQ:"Transaction expired. Please try again.",tecNO_LINE_INSUF_RESERVE:"Insufficient XRP for trust line reserve. Need at least 0.2 XRP available.",tecNO_DST:"Token issuer account does not exist."}[c]||""}var ms=K(()=>{Tt();Ze();st();Q();});var gs,Va=K(()=>{Wn();Kn();it();Ge();gs=async(c,e,t,n)=>{let{mainShare:r,additionalShare:s}=await Er(c,e,J.TRON,t),a=await vr([r,s]),l=buffer.Buffer.from(a).toString("hex");if(new tronweb.TronWeb({fullHost:je[n]}).address.fromPrivateKey(l)!==c)throw new Error("KEY_MISMATCH");return {privateKey:l}};});var Ga={};Y(Ga,{sendTronTransaction:()=>bl});var bl,$a=K(()=>{it();Va();bl=async({address:c,apiClient:e,to:t,amount:n,network:r,isNativeToken:s=true,tokenAddress:a,decimals:l,memo:p})=>{let m=je[r],g=new tronweb.TronWeb({fullHost:m}),T;try{T=(await gs(c,e.getApiKey(),e.getBaseUrl(),r)).privateKey;}catch(A){if(A.message!=="KEY_MISMATCH")throw A;try{T=(await gs(c,e.getApiKey(),e.getBaseUrl(),r)).privateKey;}catch{throw new Error("Wallet key verification failed, even after forcing a share update. The account may be corrupted.")}}let y;if(s){let S=await g.trx.getBalance(c),O=Math.round(Number(n)*1e6);if(O+3e5>S)throw new Error(`Insufficient TRX for transaction. Please leave ~0.1 TRX for bandwidth costs. Available: ${S/1e6} TRX`);y=await g.transactionBuilder.sendTrx(t,O,c),p&&(y=await g.transactionBuilder.addUpdateData(y,p,"utf8"));}else {if(!a)throw new Error("Token address is required for TRC20 transfers.");if(l===void 0)throw new Error("Token decimals are required for TRC20 transfers.");try{if(!g.isAddress(a))throw new Error("Invalid TRC20 token contract address.");let S=Math.round(Number(n)*Math.pow(10,l));if(S<=0)throw new Error("Transfer amount must be positive.");let O=await g.contract().at(a);if(!O.transfer)throw new Error("Invalid TRC20 token: contract does not have transfer function.");try{let R=await O.balanceOf(c).call(),P=BigInt(R.toString()),M=BigInt(S);if(P<M)throw new Error(`Insufficient token balance. Available: ${Number(R)/Math.pow(10,l)}, Required: ${n}`)}catch(R){if(R.message?.includes("Insufficient token balance"))throw R;console.warn("Could not verify token balance:",R);}let C=[{type:"address",value:t},{type:"uint256",value:S.toString()}],x={feeLimit:1e8,callValue:0};if(y=await g.transactionBuilder.triggerSmartContract(a,"transfer(address,uint256)",x,C,c),!y||!y.transaction)throw new Error("Failed to build TRC20 transfer transaction.");y=y.transaction,p&&(y=await g.transactionBuilder.addUpdateData(y,p,"utf8"));}catch(A){throw console.error("TRC20 transfer preparation failed:",A),A.message?A:new Error("Failed to prepare TRC20 transfer.")}}try{let A=await g.trx.sign(y,T),S=await g.trx.sendRawTransaction(A);if(S&&S.txid)return console.log(s?"Transaction sent successfully.":"Token transfer sent successfully."),{hash:S.txid,rawTransaction:JSON.stringify(A)};{let O=S?.message||"Transaction failed.";throw new Error(O)}}catch(A){throw console.error("Tron transaction execution failed:",A),A}};});var Ya=$o((za,fs)=>{(function(c,e){function t(E,i){if(!E)throw new Error(i||"Assertion failed")}function n(E,i){E.super_=i;var d=function(){};d.prototype=i.prototype,E.prototype=new d,E.prototype.constructor=E;}function r(E,i,d){if(r.isBN(E))return E;this.negative=0,this.words=null,this.length=0,this.red=null,E!==null&&((i==="le"||i==="be")&&(d=i,i=10),this._init(E||0,i||10,d||"be"));}typeof c=="object"?c.exports=r:e.BN=r,r.BN=r,r.wordSize=26;var s;try{typeof window<"u"&&typeof window.Buffer<"u"?s=window.Buffer:s=or("buffer").Buffer;}catch{}r.isBN=function(i){return i instanceof r?true:i!==null&&typeof i=="object"&&i.constructor.wordSize===r.wordSize&&Array.isArray(i.words)},r.max=function(i,d){return i.cmp(d)>0?i:d},r.min=function(i,d){return i.cmp(d)<0?i:d},r.prototype._init=function(i,d,u){if(typeof i=="number")return this._initNumber(i,d,u);if(typeof i=="object")return this._initArray(i,d,u);d==="hex"&&(d=16),t(d===(d|0)&&d>=2&&d<=36),i=i.toString().replace(/\s+/g,"");var h=0;i[0]==="-"&&(h++,this.negative=1),h<i.length&&(d===16?this._parseHex(i,h,u):(this._parseBase(i,d,h),u==="le"&&this._initArray(this.toArray(),d,u)));},r.prototype._initNumber=function(i,d,u){i<0&&(this.negative=1,i=-i),i<67108864?(this.words=[i&67108863],this.length=1):i<4503599627370496?(this.words=[i&67108863,i/67108864&67108863],this.length=2):(t(i<9007199254740992),this.words=[i&67108863,i/67108864&67108863,1],this.length=3),u==="le"&&this._initArray(this.toArray(),d,u);},r.prototype._initArray=function(i,d,u){if(t(typeof i.length=="number"),i.length<=0)return this.words=[0],this.length=1,this;this.length=Math.ceil(i.length/3),this.words=new Array(this.length);for(var h=0;h<this.length;h++)this.words[h]=0;var w,I,b=0;if(u==="be")for(h=i.length-1,w=0;h>=0;h-=3)I=i[h]|i[h-1]<<8|i[h-2]<<16,this.words[w]|=I<<b&67108863,this.words[w+1]=I>>>26-b&67108863,b+=24,b>=26&&(b-=26,w++);else if(u==="le")for(h=0,w=0;h<i.length;h+=3)I=i[h]|i[h+1]<<8|i[h+2]<<16,this.words[w]|=I<<b&67108863,this.words[w+1]=I>>>26-b&67108863,b+=24,b>=26&&(b-=26,w++);return this._strip()};function a(E,i){var d=E.charCodeAt(i);if(d>=48&&d<=57)return d-48;if(d>=65&&d<=70)return d-55;if(d>=97&&d<=102)return d-87;t(false,"Invalid character in "+E);}function l(E,i,d){var u=a(E,d);return d-1>=i&&(u|=a(E,d-1)<<4),u}r.prototype._parseHex=function(i,d,u){this.length=Math.ceil((i.length-d)/6),this.words=new Array(this.length);for(var h=0;h<this.length;h++)this.words[h]=0;var w=0,I=0,b;if(u==="be")for(h=i.length-1;h>=d;h-=2)b=l(i,d,h)<<w,this.words[I]|=b&67108863,w>=18?(w-=18,I+=1,this.words[I]|=b>>>26):w+=8;else {var f=i.length-d;for(h=f%2===0?d+1:d;h<i.length;h+=2)b=l(i,d,h)<<w,this.words[I]|=b&67108863,w>=18?(w-=18,I+=1,this.words[I]|=b>>>26):w+=8;}this._strip();};function p(E,i,d,u){for(var h=0,w=0,I=Math.min(E.length,d),b=i;b<I;b++){var f=E.charCodeAt(b)-48;h*=u,f>=49?w=f-49+10:f>=17?w=f-17+10:w=f,t(f>=0&&w<u,"Invalid character"),h+=w;}return h}r.prototype._parseBase=function(i,d,u){this.words=[0],this.length=1;for(var h=0,w=1;w<=67108863;w*=d)h++;h--,w=w/d|0;for(var I=i.length-u,b=I%h,f=Math.min(I,I-b)+u,o=0,v=u;v<f;v+=h)o=p(i,v,v+h,d),this.imuln(w),this.words[0]+o<67108864?this.words[0]+=o:this._iaddn(o);if(b!==0){var F=1;for(o=p(i,v,i.length,d),v=0;v<b;v++)F*=d;this.imuln(F),this.words[0]+o<67108864?this.words[0]+=o:this._iaddn(o);}this._strip();},r.prototype.copy=function(i){i.words=new Array(this.length);for(var d=0;d<this.length;d++)i.words[d]=this.words[d];i.length=this.length,i.negative=this.negative,i.red=this.red;};function m(E,i){E.words=i.words,E.length=i.length,E.negative=i.negative,E.red=i.red;}if(r.prototype._move=function(i){m(i,this);},r.prototype.clone=function(){var i=new r(null);return this.copy(i),i},r.prototype._expand=function(i){for(;this.length<i;)this.words[this.length++]=0;return this},r.prototype._strip=function(){for(;this.length>1&&this.words[this.length-1]===0;)this.length--;return this._normSign()},r.prototype._normSign=function(){return this.length===1&&this.words[0]===0&&(this.negative=0),this},typeof Symbol<"u"&&typeof Symbol.for=="function")try{r.prototype[Symbol.for("nodejs.util.inspect.custom")]=g;}catch{r.prototype.inspect=g;}else r.prototype.inspect=g;function g(){return (this.red?"<BN-R: ":"<BN: ")+this.toString(16)+">"}var T=["","0","00","000","0000","00000","000000","0000000","00000000","000000000","0000000000","00000000000","000000000000","0000000000000","00000000000000","000000000000000","0000000000000000","00000000000000000","000000000000000000","0000000000000000000","00000000000000000000","000000000000000000000","0000000000000000000000","00000000000000000000000","000000000000000000000000","0000000000000000000000000"],y=[0,0,25,16,12,11,10,9,8,8,7,7,7,7,6,6,6,6,6,6,6,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5],A=[0,0,33554432,43046721,16777216,48828125,60466176,40353607,16777216,43046721,1e7,19487171,35831808,62748517,7529536,11390625,16777216,24137569,34012224,47045881,64e6,4084101,5153632,6436343,7962624,9765625,11881376,14348907,17210368,20511149,243e5,28629151,33554432,39135393,45435424,52521875,60466176];r.prototype.toString=function(i,d){i=i||10,d=d|0||1;var u;if(i===16||i==="hex"){u="";for(var h=0,w=0,I=0;I<this.length;I++){var b=this.words[I],f=((b<<h|w)&16777215).toString(16);w=b>>>24-h&16777215,h+=2,h>=26&&(h-=26,I--),w!==0||I!==this.length-1?u=T[6-f.length]+f+u:u=f+u;}for(w!==0&&(u=w.toString(16)+u);u.length%d!==0;)u="0"+u;return this.negative!==0&&(u="-"+u),u}if(i===(i|0)&&i>=2&&i<=36){var o=y[i],v=A[i];u="";var F=this.clone();for(F.negative=0;!F.isZero();){var L=F.modrn(v).toString(i);F=F.idivn(v),F.isZero()?u=L+u:u=T[o-L.length]+L+u;}for(this.isZero()&&(u="0"+u);u.length%d!==0;)u="0"+u;return this.negative!==0&&(u="-"+u),u}t(false,"Base should be between 2 and 36");},r.prototype.toNumber=function(){var i=this.words[0];return this.length===2?i+=this.words[1]*67108864:this.length===3&&this.words[2]===1?i+=4503599627370496+this.words[1]*67108864:this.length>2&&t(false,"Number can only safely store up to 53 bits"),this.negative!==0?-i:i},r.prototype.toJSON=function(){return this.toString(16,2)},s&&(r.prototype.toBuffer=function(i,d){return this.toArrayLike(s,i,d)}),r.prototype.toArray=function(i,d){return this.toArrayLike(Array,i,d)};var S=function(i,d){return i.allocUnsafe?i.allocUnsafe(d):new i(d)};r.prototype.toArrayLike=function(i,d,u){this._strip();var h=this.byteLength(),w=u||Math.max(1,h);t(h<=w,"byte array longer than desired length"),t(w>0,"Requested array length <= 0");var I=S(i,w),b=d==="le"?"LE":"BE";return this["_toArrayLike"+b](I,h),I},r.prototype._toArrayLikeLE=function(i,d){for(var u=0,h=0,w=0,I=0;w<this.length;w++){var b=this.words[w]<<I|h;i[u++]=b&255,u<i.length&&(i[u++]=b>>8&255),u<i.length&&(i[u++]=b>>16&255),I===6?(u<i.length&&(i[u++]=b>>24&255),h=0,I=0):(h=b>>>24,I+=2);}if(u<i.length)for(i[u++]=h;u<i.length;)i[u++]=0;},r.prototype._toArrayLikeBE=function(i,d){for(var u=i.length-1,h=0,w=0,I=0;w<this.length;w++){var b=this.words[w]<<I|h;i[u--]=b&255,u>=0&&(i[u--]=b>>8&255),u>=0&&(i[u--]=b>>16&255),I===6?(u>=0&&(i[u--]=b>>24&255),h=0,I=0):(h=b>>>24,I+=2);}if(u>=0)for(i[u--]=h;u>=0;)i[u--]=0;},Math.clz32?r.prototype._countBits=function(i){return 32-Math.clz32(i)}:r.prototype._countBits=function(i){var d=i,u=0;return d>=4096&&(u+=13,d>>>=13),d>=64&&(u+=7,d>>>=7),d>=8&&(u+=4,d>>>=4),d>=2&&(u+=2,d>>>=2),u+d},r.prototype._zeroBits=function(i){if(i===0)return 26;var d=i,u=0;return (d&8191)===0&&(u+=13,d>>>=13),(d&127)===0&&(u+=7,d>>>=7),(d&15)===0&&(u+=4,d>>>=4),(d&3)===0&&(u+=2,d>>>=2),(d&1)===0&&u++,u},r.prototype.bitLength=function(){var i=this.words[this.length-1],d=this._countBits(i);return (this.length-1)*26+d};function O(E){for(var i=new Array(E.bitLength()),d=0;d<i.length;d++){var u=d/26|0,h=d%26;i[d]=E.words[u]>>>h&1;}return i}r.prototype.zeroBits=function(){if(this.isZero())return 0;for(var i=0,d=0;d<this.length;d++){var u=this._zeroBits(this.words[d]);if(i+=u,u!==26)break}return i},r.prototype.byteLength=function(){return Math.ceil(this.bitLength()/8)},r.prototype.toTwos=function(i){return this.negative!==0?this.abs().inotn(i).iaddn(1):this.clone()},r.prototype.fromTwos=function(i){return this.testn(i-1)?this.notn(i).iaddn(1).ineg():this.clone()},r.prototype.isNeg=function(){return this.negative!==0},r.prototype.neg=function(){return this.clone().ineg()},r.prototype.ineg=function(){return this.isZero()||(this.negative^=1),this},r.prototype.iuor=function(i){for(;this.length<i.length;)this.words[this.length++]=0;for(var d=0;d<i.length;d++)this.words[d]=this.words[d]|i.words[d];return this._strip()},r.prototype.ior=function(i){return t((this.negative|i.negative)===0),this.iuor(i)},r.prototype.or=function(i){return this.length>i.length?this.clone().ior(i):i.clone().ior(this)},r.prototype.uor=function(i){return this.length>i.length?this.clone().iuor(i):i.clone().iuor(this)},r.prototype.iuand=function(i){var d;this.length>i.length?d=i:d=this;for(var u=0;u<d.length;u++)this.words[u]=this.words[u]&i.words[u];return this.length=d.length,this._strip()},r.prototype.iand=function(i){return t((this.negative|i.negative)===0),this.iuand(i)},r.prototype.and=function(i){return this.length>i.length?this.clone().iand(i):i.clone().iand(this)},r.prototype.uand=function(i){return this.length>i.length?this.clone().iuand(i):i.clone().iuand(this)},r.prototype.iuxor=function(i){var d,u;this.length>i.length?(d=this,u=i):(d=i,u=this);for(var h=0;h<u.length;h++)this.words[h]=d.words[h]^u.words[h];if(this!==d)for(;h<d.length;h++)this.words[h]=d.words[h];return this.length=d.length,this._strip()},r.prototype.ixor=function(i){return t((this.negative|i.negative)===0),this.iuxor(i)},r.prototype.xor=function(i){return this.length>i.length?this.clone().ixor(i):i.clone().ixor(this)},r.prototype.uxor=function(i){return this.length>i.length?this.clone().iuxor(i):i.clone().iuxor(this)},r.prototype.inotn=function(i){t(typeof i=="number"&&i>=0);var d=Math.ceil(i/26)|0,u=i%26;this._expand(d),u>0&&d--;for(var h=0;h<d;h++)this.words[h]=~this.words[h]&67108863;return u>0&&(this.words[h]=~this.words[h]&67108863>>26-u),this._strip()},r.prototype.notn=function(i){return this.clone().inotn(i)},r.prototype.setn=function(i,d){t(typeof i=="number"&&i>=0);var u=i/26|0,h=i%26;return this._expand(u+1),d?this.words[u]=this.words[u]|1<<h:this.words[u]=this.words[u]&~(1<<h),this._strip()},r.prototype.iadd=function(i){var d;if(this.negative!==0&&i.negative===0)return this.negative=0,d=this.isub(i),this.negative^=1,this._normSign();if(this.negative===0&&i.negative!==0)return i.negative=0,d=this.isub(i),i.negative=1,d._normSign();var u,h;this.length>i.length?(u=this,h=i):(u=i,h=this);for(var w=0,I=0;I<h.length;I++)d=(u.words[I]|0)+(h.words[I]|0)+w,this.words[I]=d&67108863,w=d>>>26;for(;w!==0&&I<u.length;I++)d=(u.words[I]|0)+w,this.words[I]=d&67108863,w=d>>>26;if(this.length=u.length,w!==0)this.words[this.length]=w,this.length++;else if(u!==this)for(;I<u.length;I++)this.words[I]=u.words[I];return this},r.prototype.add=function(i){var d;return i.negative!==0&&this.negative===0?(i.negative=0,d=this.sub(i),i.negative^=1,d):i.negative===0&&this.negative!==0?(this.negative=0,d=i.sub(this),this.negative=1,d):this.length>i.length?this.clone().iadd(i):i.clone().iadd(this)},r.prototype.isub=function(i){if(i.negative!==0){i.negative=0;var d=this.iadd(i);return i.negative=1,d._normSign()}else if(this.negative!==0)return this.negative=0,this.iadd(i),this.negative=1,this._normSign();var u=this.cmp(i);if(u===0)return this.negative=0,this.length=1,this.words[0]=0,this;var h,w;u>0?(h=this,w=i):(h=i,w=this);for(var I=0,b=0;b<w.length;b++)d=(h.words[b]|0)-(w.words[b]|0)+I,I=d>>26,this.words[b]=d&67108863;for(;I!==0&&b<h.length;b++)d=(h.words[b]|0)+I,I=d>>26,this.words[b]=d&67108863;if(I===0&&b<h.length&&h!==this)for(;b<h.length;b++)this.words[b]=h.words[b];return this.length=Math.max(this.length,b),h!==this&&(this.negative=1),this._strip()},r.prototype.sub=function(i){return this.clone().isub(i)};function C(E,i,d){d.negative=i.negative^E.negative;var u=E.length+i.length|0;d.length=u,u=u-1|0;var h=E.words[0]|0,w=i.words[0]|0,I=h*w,b=I&67108863,f=I/67108864|0;d.words[0]=b;for(var o=1;o<u;o++){for(var v=f>>>26,F=f&67108863,L=Math.min(o,i.length-1),D=Math.max(0,o-E.length+1);D<=L;D++){var V=o-D|0;h=E.words[V]|0,w=i.words[D]|0,I=h*w+F,v+=I/67108864|0,F=I&67108863;}d.words[o]=F|0,f=v|0;}return f!==0?d.words[o]=f|0:d.length--,d._strip()}var x=function(i,d,u){var h=i.words,w=d.words,I=u.words,b=0,f,o,v,F=h[0]|0,L=F&8191,D=F>>>13,V=h[1]|0,$=V&8191,z=V>>>13,lt=h[2]|0,Z=lt&8191,te=lt>>>13,ks=h[3]|0,se=ks&8191,ie=ks>>>13,_s=h[4]|0,ae=_s&8191,oe=_s>>>13,Bs=h[5]|0,ce=Bs&8191,de=Bs>>>13,Ns=h[6]|0,le=Ns&8191,ue=Ns>>>13,Fs=h[7]|0,pe=Fs&8191,he=Fs>>>13,Ls=h[8]|0,me=Ls&8191,ge=Ls>>>13,Ds=h[9]|0,fe=Ds&8191,ye=Ds>>>13,Us=w[0]|0,we=Us&8191,Te=Us>>>13,Ws=w[1]|0,ve=Ws&8191,Ee=Ws>>>13,Ks=w[2]|0,Ae=Ks&8191,xe=Ks>>>13,Hs=w[3]|0,be=Hs&8191,Ie=Hs>>>13,Xs=w[4]|0,Se=Xs&8191,Oe=Xs>>>13,Vs=w[5]|0,Ce=Vs&8191,Pe=Vs>>>13,Gs=w[6]|0,Re=Gs&8191,Me=Gs>>>13,$s=w[7]|0,ke=$s&8191,_e=$s>>>13,qs=w[8]|0,Be=qs&8191,Ne=qs>>>13,js=w[9]|0,Fe=js&8191,Le=js>>>13;u.negative=i.negative^d.negative,u.length=19,f=Math.imul(L,we),o=Math.imul(L,Te),o=o+Math.imul(D,we)|0,v=Math.imul(D,Te);var sn=(b+f|0)+((o&8191)<<13)|0;b=(v+(o>>>13)|0)+(sn>>>26)|0,sn&=67108863,f=Math.imul($,we),o=Math.imul($,Te),o=o+Math.imul(z,we)|0,v=Math.imul(z,Te),f=f+Math.imul(L,ve)|0,o=o+Math.imul(L,Ee)|0,o=o+Math.imul(D,ve)|0,v=v+Math.imul(D,Ee)|0;var an=(b+f|0)+((o&8191)<<13)|0;b=(v+(o>>>13)|0)+(an>>>26)|0,an&=67108863,f=Math.imul(Z,we),o=Math.imul(Z,Te),o=o+Math.imul(te,we)|0,v=Math.imul(te,Te),f=f+Math.imul($,ve)|0,o=o+Math.imul($,Ee)|0,o=o+Math.imul(z,ve)|0,v=v+Math.imul(z,Ee)|0,f=f+Math.imul(L,Ae)|0,o=o+Math.imul(L,xe)|0,o=o+Math.imul(D,Ae)|0,v=v+Math.imul(D,xe)|0;var on=(b+f|0)+((o&8191)<<13)|0;b=(v+(o>>>13)|0)+(on>>>26)|0,on&=67108863,f=Math.imul(se,we),o=Math.imul(se,Te),o=o+Math.imul(ie,we)|0,v=Math.imul(ie,Te),f=f+Math.imul(Z,ve)|0,o=o+Math.imul(Z,Ee)|0,o=o+Math.imul(te,ve)|0,v=v+Math.imul(te,Ee)|0,f=f+Math.imul($,Ae)|0,o=o+Math.imul($,xe)|0,o=o+Math.imul(z,Ae)|0,v=v+Math.imul(z,xe)|0,f=f+Math.imul(L,be)|0,o=o+Math.imul(L,Ie)|0,o=o+Math.imul(D,be)|0,v=v+Math.imul(D,Ie)|0;var cn=(b+f|0)+((o&8191)<<13)|0;b=(v+(o>>>13)|0)+(cn>>>26)|0,cn&=67108863,f=Math.imul(ae,we),o=Math.imul(ae,Te),o=o+Math.imul(oe,we)|0,v=Math.imul(oe,Te),f=f+Math.imul(se,ve)|0,o=o+Math.imul(se,Ee)|0,o=o+Math.imul(ie,ve)|0,v=v+Math.imul(ie,Ee)|0,f=f+Math.imul(Z,Ae)|0,o=o+Math.imul(Z,xe)|0,o=o+Math.imul(te,Ae)|0,v=v+Math.imul(te,xe)|0,f=f+Math.imul($,be)|0,o=o+Math.imul($,Ie)|0,o=o+Math.imul(z,be)|0,v=v+Math.imul(z,Ie)|0,f=f+Math.imul(L,Se)|0,o=o+Math.imul(L,Oe)|0,o=o+Math.imul(D,Se)|0,v=v+Math.imul(D,Oe)|0;var dn=(b+f|0)+((o&8191)<<13)|0;b=(v+(o>>>13)|0)+(dn>>>26)|0,dn&=67108863,f=Math.imul(ce,we),o=Math.imul(ce,Te),o=o+Math.imul(de,we)|0,v=Math.imul(de,Te),f=f+Math.imul(ae,ve)|0,o=o+Math.imul(ae,Ee)|0,o=o+Math.imul(oe,ve)|0,v=v+Math.imul(oe,Ee)|0,f=f+Math.imul(se,Ae)|0,o=o+Math.imul(se,xe)|0,o=o+Math.imul(ie,Ae)|0,v=v+Math.imul(ie,xe)|0,f=f+Math.imul(Z,be)|0,o=o+Math.imul(Z,Ie)|0,o=o+Math.imul(te,be)|0,v=v+Math.imul(te,Ie)|0,f=f+Math.imul($,Se)|0,o=o+Math.imul($,Oe)|0,o=o+Math.imul(z,Se)|0,v=v+Math.imul(z,Oe)|0,f=f+Math.imul(L,Ce)|0,o=o+Math.imul(L,Pe)|0,o=o+Math.imul(D,Ce)|0,v=v+Math.imul(D,Pe)|0;var ln=(b+f|0)+((o&8191)<<13)|0;b=(v+(o>>>13)|0)+(ln>>>26)|0,ln&=67108863,f=Math.imul(le,we),o=Math.imul(le,Te),o=o+Math.imul(ue,we)|0,v=Math.imul(ue,Te),f=f+Math.imul(ce,ve)|0,o=o+Math.imul(ce,Ee)|0,o=o+Math.imul(de,ve)|0,v=v+Math.imul(de,Ee)|0,f=f+Math.imul(ae,Ae)|0,o=o+Math.imul(ae,xe)|0,o=o+Math.imul(oe,Ae)|0,v=v+Math.imul(oe,xe)|0,f=f+Math.imul(se,be)|0,o=o+Math.imul(se,Ie)|0,o=o+Math.imul(ie,be)|0,v=v+Math.imul(ie,Ie)|0,f=f+Math.imul(Z,Se)|0,o=o+Math.imul(Z,Oe)|0,o=o+Math.imul(te,Se)|0,v=v+Math.imul(te,Oe)|0,f=f+Math.imul($,Ce)|0,o=o+Math.imul($,Pe)|0,o=o+Math.imul(z,Ce)|0,v=v+Math.imul(z,Pe)|0,f=f+Math.imul(L,Re)|0,o=o+Math.imul(L,Me)|0,o=o+Math.imul(D,Re)|0,v=v+Math.imul(D,Me)|0;var un=(b+f|0)+((o&8191)<<13)|0;b=(v+(o>>>13)|0)+(un>>>26)|0,un&=67108863,f=Math.imul(pe,we),o=Math.imul(pe,Te),o=o+Math.imul(he,we)|0,v=Math.imul(he,Te),f=f+Math.imul(le,ve)|0,o=o+Math.imul(le,Ee)|0,o=o+Math.imul(ue,ve)|0,v=v+Math.imul(ue,Ee)|0,f=f+Math.imul(ce,Ae)|0,o=o+Math.imul(ce,xe)|0,o=o+Math.imul(de,Ae)|0,v=v+Math.imul(de,xe)|0,f=f+Math.imul(ae,be)|0,o=o+Math.imul(ae,Ie)|0,o=o+Math.imul(oe,be)|0,v=v+Math.imul(oe,Ie)|0,f=f+Math.imul(se,Se)|0,o=o+Math.imul(se,Oe)|0,o=o+Math.imul(ie,Se)|0,v=v+Math.imul(ie,Oe)|0,f=f+Math.imul(Z,Ce)|0,o=o+Math.imul(Z,Pe)|0,o=o+Math.imul(te,Ce)|0,v=v+Math.imul(te,Pe)|0,f=f+Math.imul($,Re)|0,o=o+Math.imul($,Me)|0,o=o+Math.imul(z,Re)|0,v=v+Math.imul(z,Me)|0,f=f+Math.imul(L,ke)|0,o=o+Math.imul(L,_e)|0,o=o+Math.imul(D,ke)|0,v=v+Math.imul(D,_e)|0;var pn=(b+f|0)+((o&8191)<<13)|0;b=(v+(o>>>13)|0)+(pn>>>26)|0,pn&=67108863,f=Math.imul(me,we),o=Math.imul(me,Te),o=o+Math.imul(ge,we)|0,v=Math.imul(ge,Te),f=f+Math.imul(pe,ve)|0,o=o+Math.imul(pe,Ee)|0,o=o+Math.imul(he,ve)|0,v=v+Math.imul(he,Ee)|0,f=f+Math.imul(le,Ae)|0,o=o+Math.imul(le,xe)|0,o=o+Math.imul(ue,Ae)|0,v=v+Math.imul(ue,xe)|0,f=f+Math.imul(ce,be)|0,o=o+Math.imul(ce,Ie)|0,o=o+Math.imul(de,be)|0,v=v+Math.imul(de,Ie)|0,f=f+Math.imul(ae,Se)|0,o=o+Math.imul(ae,Oe)|0,o=o+Math.imul(oe,Se)|0,v=v+Math.imul(oe,Oe)|0,f=f+Math.imul(se,Ce)|0,o=o+Math.imul(se,Pe)|0,o=o+Math.imul(ie,Ce)|0,v=v+Math.imul(ie,Pe)|0,f=f+Math.imul(Z,Re)|0,o=o+Math.imul(Z,Me)|0,o=o+Math.imul(te,Re)|0,v=v+Math.imul(te,Me)|0,f=f+Math.imul($,ke)|0,o=o+Math.imul($,_e)|0,o=o+Math.imul(z,ke)|0,v=v+Math.imul(z,_e)|0,f=f+Math.imul(L,Be)|0,o=o+Math.imul(L,Ne)|0,o=o+Math.imul(D,Be)|0,v=v+Math.imul(D,Ne)|0;var hn=(b+f|0)+((o&8191)<<13)|0;b=(v+(o>>>13)|0)+(hn>>>26)|0,hn&=67108863,f=Math.imul(fe,we),o=Math.imul(fe,Te),o=o+Math.imul(ye,we)|0,v=Math.imul(ye,Te),f=f+Math.imul(me,ve)|0,o=o+Math.imul(me,Ee)|0,o=o+Math.imul(ge,ve)|0,v=v+Math.imul(ge,Ee)|0,f=f+Math.imul(pe,Ae)|0,o=o+Math.imul(pe,xe)|0,o=o+Math.imul(he,Ae)|0,v=v+Math.imul(he,xe)|0,f=f+Math.imul(le,be)|0,o=o+Math.imul(le,Ie)|0,o=o+Math.imul(ue,be)|0,v=v+Math.imul(ue,Ie)|0,f=f+Math.imul(ce,Se)|0,o=o+Math.imul(ce,Oe)|0,o=o+Math.imul(de,Se)|0,v=v+Math.imul(de,Oe)|0,f=f+Math.imul(ae,Ce)|0,o=o+Math.imul(ae,Pe)|0,o=o+Math.imul(oe,Ce)|0,v=v+Math.imul(oe,Pe)|0,f=f+Math.imul(se,Re)|0,o=o+Math.imul(se,Me)|0,o=o+Math.imul(ie,Re)|0,v=v+Math.imul(ie,Me)|0,f=f+Math.imul(Z,ke)|0,o=o+Math.imul(Z,_e)|0,o=o+Math.imul(te,ke)|0,v=v+Math.imul(te,_e)|0,f=f+Math.imul($,Be)|0,o=o+Math.imul($,Ne)|0,o=o+Math.imul(z,Be)|0,v=v+Math.imul(z,Ne)|0,f=f+Math.imul(L,Fe)|0,o=o+Math.imul(L,Le)|0,o=o+Math.imul(D,Fe)|0,v=v+Math.imul(D,Le)|0;var mn=(b+f|0)+((o&8191)<<13)|0;b=(v+(o>>>13)|0)+(mn>>>26)|0,mn&=67108863,f=Math.imul(fe,ve),o=Math.imul(fe,Ee),o=o+Math.imul(ye,ve)|0,v=Math.imul(ye,Ee),f=f+Math.imul(me,Ae)|0,o=o+Math.imul(me,xe)|0,o=o+Math.imul(ge,Ae)|0,v=v+Math.imul(ge,xe)|0,f=f+Math.imul(pe,be)|0,o=o+Math.imul(pe,Ie)|0,o=o+Math.imul(he,be)|0,v=v+Math.imul(he,Ie)|0,f=f+Math.imul(le,Se)|0,o=o+Math.imul(le,Oe)|0,o=o+Math.imul(ue,Se)|0,v=v+Math.imul(ue,Oe)|0,f=f+Math.imul(ce,Ce)|0,o=o+Math.imul(ce,Pe)|0,o=o+Math.imul(de,Ce)|0,v=v+Math.imul(de,Pe)|0,f=f+Math.imul(ae,Re)|0,o=o+Math.imul(ae,Me)|0,o=o+Math.imul(oe,Re)|0,v=v+Math.imul(oe,Me)|0,f=f+Math.imul(se,ke)|0,o=o+Math.imul(se,_e)|0,o=o+Math.imul(ie,ke)|0,v=v+Math.imul(ie,_e)|0,f=f+Math.imul(Z,Be)|0,o=o+Math.imul(Z,Ne)|0,o=o+Math.imul(te,Be)|0,v=v+Math.imul(te,Ne)|0,f=f+Math.imul($,Fe)|0,o=o+Math.imul($,Le)|0,o=o+Math.imul(z,Fe)|0,v=v+Math.imul(z,Le)|0;var gn=(b+f|0)+((o&8191)<<13)|0;b=(v+(o>>>13)|0)+(gn>>>26)|0,gn&=67108863,f=Math.imul(fe,Ae),o=Math.imul(fe,xe),o=o+Math.imul(ye,Ae)|0,v=Math.imul(ye,xe),f=f+Math.imul(me,be)|0,o=o+Math.imul(me,Ie)|0,o=o+Math.imul(ge,be)|0,v=v+Math.imul(ge,Ie)|0,f=f+Math.imul(pe,Se)|0,o=o+Math.imul(pe,Oe)|0,o=o+Math.imul(he,Se)|0,v=v+Math.imul(he,Oe)|0,f=f+Math.imul(le,Ce)|0,o=o+Math.imul(le,Pe)|0,o=o+Math.imul(ue,Ce)|0,v=v+Math.imul(ue,Pe)|0,f=f+Math.imul(ce,Re)|0,o=o+Math.imul(ce,Me)|0,o=o+Math.imul(de,Re)|0,v=v+Math.imul(de,Me)|0,f=f+Math.imul(ae,ke)|0,o=o+Math.imul(ae,_e)|0,o=o+Math.imul(oe,ke)|0,v=v+Math.imul(oe,_e)|0,f=f+Math.imul(se,Be)|0,o=o+Math.imul(se,Ne)|0,o=o+Math.imul(ie,Be)|0,v=v+Math.imul(ie,Ne)|0,f=f+Math.imul(Z,Fe)|0,o=o+Math.imul(Z,Le)|0,o=o+Math.imul(te,Fe)|0,v=v+Math.imul(te,Le)|0;var fn=(b+f|0)+((o&8191)<<13)|0;b=(v+(o>>>13)|0)+(fn>>>26)|0,fn&=67108863,f=Math.imul(fe,be),o=Math.imul(fe,Ie),o=o+Math.imul(ye,be)|0,v=Math.imul(ye,Ie),f=f+Math.imul(me,Se)|0,o=o+Math.imul(me,Oe)|0,o=o+Math.imul(ge,Se)|0,v=v+Math.imul(ge,Oe)|0,f=f+Math.imul(pe,Ce)|0,o=o+Math.imul(pe,Pe)|0,o=o+Math.imul(he,Ce)|0,v=v+Math.imul(he,Pe)|0,f=f+Math.imul(le,Re)|0,o=o+Math.imul(le,Me)|0,o=o+Math.imul(ue,Re)|0,v=v+Math.imul(ue,Me)|0,f=f+Math.imul(ce,ke)|0,o=o+Math.imul(ce,_e)|0,o=o+Math.imul(de,ke)|0,v=v+Math.imul(de,_e)|0,f=f+Math.imul(ae,Be)|0,o=o+Math.imul(ae,Ne)|0,o=o+Math.imul(oe,Be)|0,v=v+Math.imul(oe,Ne)|0,f=f+Math.imul(se,Fe)|0,o=o+Math.imul(se,Le)|0,o=o+Math.imul(ie,Fe)|0,v=v+Math.imul(ie,Le)|0;var yn=(b+f|0)+((o&8191)<<13)|0;b=(v+(o>>>13)|0)+(yn>>>26)|0,yn&=67108863,f=Math.imul(fe,Se),o=Math.imul(fe,Oe),o=o+Math.imul(ye,Se)|0,v=Math.imul(ye,Oe),f=f+Math.imul(me,Ce)|0,o=o+Math.imul(me,Pe)|0,o=o+Math.imul(ge,Ce)|0,v=v+Math.imul(ge,Pe)|0,f=f+Math.imul(pe,Re)|0,o=o+Math.imul(pe,Me)|0,o=o+Math.imul(he,Re)|0,v=v+Math.imul(he,Me)|0,f=f+Math.imul(le,ke)|0,o=o+Math.imul(le,_e)|0,o=o+Math.imul(ue,ke)|0,v=v+Math.imul(ue,_e)|0,f=f+Math.imul(ce,Be)|0,o=o+Math.imul(ce,Ne)|0,o=o+Math.imul(de,Be)|0,v=v+Math.imul(de,Ne)|0,f=f+Math.imul(ae,Fe)|0,o=o+Math.imul(ae,Le)|0,o=o+Math.imul(oe,Fe)|0,v=v+Math.imul(oe,Le)|0;var wn=(b+f|0)+((o&8191)<<13)|0;b=(v+(o>>>13)|0)+(wn>>>26)|0,wn&=67108863,f=Math.imul(fe,Ce),o=Math.imul(fe,Pe),o=o+Math.imul(ye,Ce)|0,v=Math.imul(ye,Pe),f=f+Math.imul(me,Re)|0,o=o+Math.imul(me,Me)|0,o=o+Math.imul(ge,Re)|0,v=v+Math.imul(ge,Me)|0,f=f+Math.imul(pe,ke)|0,o=o+Math.imul(pe,_e)|0,o=o+Math.imul(he,ke)|0,v=v+Math.imul(he,_e)|0,f=f+Math.imul(le,Be)|0,o=o+Math.imul(le,Ne)|0,o=o+Math.imul(ue,Be)|0,v=v+Math.imul(ue,Ne)|0,f=f+Math.imul(ce,Fe)|0,o=o+Math.imul(ce,Le)|0,o=o+Math.imul(de,Fe)|0,v=v+Math.imul(de,Le)|0;var Tn=(b+f|0)+((o&8191)<<13)|0;b=(v+(o>>>13)|0)+(Tn>>>26)|0,Tn&=67108863,f=Math.imul(fe,Re),o=Math.imul(fe,Me),o=o+Math.imul(ye,Re)|0,v=Math.imul(ye,Me),f=f+Math.imul(me,ke)|0,o=o+Math.imul(me,_e)|0,o=o+Math.imul(ge,ke)|0,v=v+Math.imul(ge,_e)|0,f=f+Math.imul(pe,Be)|0,o=o+Math.imul(pe,Ne)|0,o=o+Math.imul(he,Be)|0,v=v+Math.imul(he,Ne)|0,f=f+Math.imul(le,Fe)|0,o=o+Math.imul(le,Le)|0,o=o+Math.imul(ue,Fe)|0,v=v+Math.imul(ue,Le)|0;var vn=(b+f|0)+((o&8191)<<13)|0;b=(v+(o>>>13)|0)+(vn>>>26)|0,vn&=67108863,f=Math.imul(fe,ke),o=Math.imul(fe,_e),o=o+Math.imul(ye,ke)|0,v=Math.imul(ye,_e),f=f+Math.imul(me,Be)|0,o=o+Math.imul(me,Ne)|0,o=o+Math.imul(ge,Be)|0,v=v+Math.imul(ge,Ne)|0,f=f+Math.imul(pe,Fe)|0,o=o+Math.imul(pe,Le)|0,o=o+Math.imul(he,Fe)|0,v=v+Math.imul(he,Le)|0;var En=(b+f|0)+((o&8191)<<13)|0;b=(v+(o>>>13)|0)+(En>>>26)|0,En&=67108863,f=Math.imul(fe,Be),o=Math.imul(fe,Ne),o=o+Math.imul(ye,Be)|0,v=Math.imul(ye,Ne),f=f+Math.imul(me,Fe)|0,o=o+Math.imul(me,Le)|0,o=o+Math.imul(ge,Fe)|0,v=v+Math.imul(ge,Le)|0;var An=(b+f|0)+((o&8191)<<13)|0;b=(v+(o>>>13)|0)+(An>>>26)|0,An&=67108863,f=Math.imul(fe,Fe),o=Math.imul(fe,Le),o=o+Math.imul(ye,Fe)|0,v=Math.imul(ye,Le);var xn=(b+f|0)+((o&8191)<<13)|0;return b=(v+(o>>>13)|0)+(xn>>>26)|0,xn&=67108863,I[0]=sn,I[1]=an,I[2]=on,I[3]=cn,I[4]=dn,I[5]=ln,I[6]=un,I[7]=pn,I[8]=hn,I[9]=mn,I[10]=gn,I[11]=fn,I[12]=yn,I[13]=wn,I[14]=Tn,I[15]=vn,I[16]=En,I[17]=An,I[18]=xn,b!==0&&(I[19]=b,u.length++),u};Math.imul||(x=C);function R(E,i,d){d.negative=i.negative^E.negative,d.length=E.length+i.length;for(var u=0,h=0,w=0;w<d.length-1;w++){var I=h;h=0;for(var b=u&67108863,f=Math.min(w,i.length-1),o=Math.max(0,w-E.length+1);o<=f;o++){var v=w-o,F=E.words[v]|0,L=i.words[o]|0,D=F*L,V=D&67108863;I=I+(D/67108864|0)|0,V=V+b|0,b=V&67108863,I=I+(V>>>26)|0,h+=I>>>26,I&=67108863;}d.words[w]=b,u=I,I=h;}return u!==0?d.words[w]=u:d.length--,d._strip()}function P(E,i,d){return R(E,i,d)}r.prototype.mulTo=function(i,d){var u,h=this.length+i.length;return this.length===10&&i.length===10?u=x(this,i,d):h<63?u=C(this,i,d):h<1024?u=R(this,i,d):u=P(this,i,d),u};r.prototype.mul=function(i){var d=new r(null);return d.words=new Array(this.length+i.length),this.mulTo(i,d)},r.prototype.mulf=function(i){var d=new r(null);return d.words=new Array(this.length+i.length),P(this,i,d)},r.prototype.imul=function(i){return this.clone().mulTo(i,this)},r.prototype.imuln=function(i){var d=i<0;d&&(i=-i),t(typeof i=="number"),t(i<67108864);for(var u=0,h=0;h<this.length;h++){var w=(this.words[h]|0)*i,I=(w&67108863)+(u&67108863);u>>=26,u+=w/67108864|0,u+=I>>>26,this.words[h]=I&67108863;}return u!==0&&(this.words[h]=u,this.length++),this.length=i===0?1:this.length,d?this.ineg():this},r.prototype.muln=function(i){return this.clone().imuln(i)},r.prototype.sqr=function(){return this.mul(this)},r.prototype.isqr=function(){return this.imul(this.clone())},r.prototype.pow=function(i){var d=O(i);if(d.length===0)return new r(1);for(var u=this,h=0;h<d.length&&d[h]===0;h++,u=u.sqr());if(++h<d.length)for(var w=u.sqr();h<d.length;h++,w=w.sqr())d[h]!==0&&(u=u.mul(w));return u},r.prototype.iushln=function(i){t(typeof i=="number"&&i>=0);var d=i%26,u=(i-d)/26,h=67108863>>>26-d<<26-d,w;if(d!==0){var I=0;for(w=0;w<this.length;w++){var b=this.words[w]&h,f=(this.words[w]|0)-b<<d;this.words[w]=f|I,I=b>>>26-d;}I&&(this.words[w]=I,this.length++);}if(u!==0){for(w=this.length-1;w>=0;w--)this.words[w+u]=this.words[w];for(w=0;w<u;w++)this.words[w]=0;this.length+=u;}return this._strip()},r.prototype.ishln=function(i){return t(this.negative===0),this.iushln(i)},r.prototype.iushrn=function(i,d,u){t(typeof i=="number"&&i>=0);var h;d?h=(d-d%26)/26:h=0;var w=i%26,I=Math.min((i-w)/26,this.length),b=67108863^67108863>>>w<<w,f=u;if(h-=I,h=Math.max(0,h),f){for(var o=0;o<I;o++)f.words[o]=this.words[o];f.length=I;}if(I!==0)if(this.length>I)for(this.length-=I,o=0;o<this.length;o++)this.words[o]=this.words[o+I];else this.words[0]=0,this.length=1;var v=0;for(o=this.length-1;o>=0&&(v!==0||o>=h);o--){var F=this.words[o]|0;this.words[o]=v<<26-w|F>>>w,v=F&b;}return f&&v!==0&&(f.words[f.length++]=v),this.length===0&&(this.words[0]=0,this.length=1),this._strip()},r.prototype.ishrn=function(i,d,u){return t(this.negative===0),this.iushrn(i,d,u)},r.prototype.shln=function(i){return this.clone().ishln(i)},r.prototype.ushln=function(i){return this.clone().iushln(i)},r.prototype.shrn=function(i){return this.clone().ishrn(i)},r.prototype.ushrn=function(i){return this.clone().iushrn(i)},r.prototype.testn=function(i){t(typeof i=="number"&&i>=0);var d=i%26,u=(i-d)/26,h=1<<d;if(this.length<=u)return false;var w=this.words[u];return !!(w&h)},r.prototype.imaskn=function(i){t(typeof i=="number"&&i>=0);var d=i%26,u=(i-d)/26;if(t(this.negative===0,"imaskn works only with positive numbers"),this.length<=u)return this;if(d!==0&&u++,this.length=Math.min(u,this.length),d!==0){var h=67108863^67108863>>>d<<d;this.words[this.length-1]&=h;}return this._strip()},r.prototype.maskn=function(i){return this.clone().imaskn(i)},r.prototype.iaddn=function(i){return t(typeof i=="number"),t(i<67108864),i<0?this.isubn(-i):this.negative!==0?this.length===1&&(this.words[0]|0)<=i?(this.words[0]=i-(this.words[0]|0),this.negative=0,this):(this.negative=0,this.isubn(i),this.negative=1,this):this._iaddn(i)},r.prototype._iaddn=function(i){this.words[0]+=i;for(var d=0;d<this.length&&this.words[d]>=67108864;d++)this.words[d]-=67108864,d===this.length-1?this.words[d+1]=1:this.words[d+1]++;return this.length=Math.max(this.length,d+1),this},r.prototype.isubn=function(i){if(t(typeof i=="number"),t(i<67108864),i<0)return this.iaddn(-i);if(this.negative!==0)return this.negative=0,this.iaddn(i),this.negative=1,this;if(this.words[0]-=i,this.length===1&&this.words[0]<0)this.words[0]=-this.words[0],this.negative=1;else for(var d=0;d<this.length&&this.words[d]<0;d++)this.words[d]+=67108864,this.words[d+1]-=1;return this._strip()},r.prototype.addn=function(i){return this.clone().iaddn(i)},r.prototype.subn=function(i){return this.clone().isubn(i)},r.prototype.iabs=function(){return this.negative=0,this},r.prototype.abs=function(){return this.clone().iabs()},r.prototype._ishlnsubmul=function(i,d,u){var h=i.length+u,w;this._expand(h);var I,b=0;for(w=0;w<i.length;w++){I=(this.words[w+u]|0)+b;var f=(i.words[w]|0)*d;I-=f&67108863,b=(I>>26)-(f/67108864|0),this.words[w+u]=I&67108863;}for(;w<this.length-u;w++)I=(this.words[w+u]|0)+b,b=I>>26,this.words[w+u]=I&67108863;if(b===0)return this._strip();for(t(b===-1),b=0,w=0;w<this.length;w++)I=-(this.words[w]|0)+b,b=I>>26,this.words[w]=I&67108863;return this.negative=1,this._strip()},r.prototype._wordDiv=function(i,d){var u=this.length-i.length,h=this.clone(),w=i,I=w.words[w.length-1]|0,b=this._countBits(I);u=26-b,u!==0&&(w=w.ushln(u),h.iushln(u),I=w.words[w.length-1]|0);var f=h.length-w.length,o;if(d!=="mod"){o=new r(null),o.length=f+1,o.words=new Array(o.length);for(var v=0;v<o.length;v++)o.words[v]=0;}var F=h.clone()._ishlnsubmul(w,1,f);F.negative===0&&(h=F,o&&(o.words[f]=1));for(var L=f-1;L>=0;L--){var D=(h.words[w.length+L]|0)*67108864+(h.words[w.length+L-1]|0);for(D=Math.min(D/I|0,67108863),h._ishlnsubmul(w,D,L);h.negative!==0;)D--,h.negative=0,h._ishlnsubmul(w,1,L),h.isZero()||(h.negative^=1);o&&(o.words[L]=D);}return o&&o._strip(),h._strip(),d!=="div"&&u!==0&&h.iushrn(u),{div:o||null,mod:h}},r.prototype.divmod=function(i,d,u){if(t(!i.isZero()),this.isZero())return {div:new r(0),mod:new r(0)};var h,w,I;return this.negative!==0&&i.negative===0?(I=this.neg().divmod(i,d),d!=="mod"&&(h=I.div.neg()),d!=="div"&&(w=I.mod.neg(),u&&w.negative!==0&&w.iadd(i)),{div:h,mod:w}):this.negative===0&&i.negative!==0?(I=this.divmod(i.neg(),d),d!=="mod"&&(h=I.div.neg()),{div:h,mod:I.mod}):(this.negative&i.negative)!==0?(I=this.neg().divmod(i.neg(),d),d!=="div"&&(w=I.mod.neg(),u&&w.negative!==0&&w.isub(i)),{div:I.div,mod:w}):i.length>this.length||this.cmp(i)<0?{div:new r(0),mod:this}:i.length===1?d==="div"?{div:this.divn(i.words[0]),mod:null}:d==="mod"?{div:null,mod:new r(this.modrn(i.words[0]))}:{div:this.divn(i.words[0]),mod:new r(this.modrn(i.words[0]))}:this._wordDiv(i,d)},r.prototype.div=function(i){return this.divmod(i,"div",false).div},r.prototype.mod=function(i){return this.divmod(i,"mod",false).mod},r.prototype.umod=function(i){return this.divmod(i,"mod",true).mod},r.prototype.divRound=function(i){var d=this.divmod(i);if(d.mod.isZero())return d.div;var u=d.div.negative!==0?d.mod.isub(i):d.mod,h=i.ushrn(1),w=i.andln(1),I=u.cmp(h);return I<0||w===1&&I===0?d.div:d.div.negative!==0?d.div.isubn(1):d.div.iaddn(1)},r.prototype.modrn=function(i){var d=i<0;d&&(i=-i),t(i<=67108863);for(var u=(1<<26)%i,h=0,w=this.length-1;w>=0;w--)h=(u*h+(this.words[w]|0))%i;return d?-h:h},r.prototype.modn=function(i){return this.modrn(i)},r.prototype.idivn=function(i){var d=i<0;d&&(i=-i),t(i<=67108863);for(var u=0,h=this.length-1;h>=0;h--){var w=(this.words[h]|0)+u*67108864;this.words[h]=w/i|0,u=w%i;}return this._strip(),d?this.ineg():this},r.prototype.divn=function(i){return this.clone().idivn(i)},r.prototype.egcd=function(i){t(i.negative===0),t(!i.isZero());var d=this,u=i.clone();d.negative!==0?d=d.umod(i):d=d.clone();for(var h=new r(1),w=new r(0),I=new r(0),b=new r(1),f=0;d.isEven()&&u.isEven();)d.iushrn(1),u.iushrn(1),++f;for(var o=u.clone(),v=d.clone();!d.isZero();){for(var F=0,L=1;(d.words[0]&L)===0&&F<26;++F,L<<=1);if(F>0)for(d.iushrn(F);F-- >0;)(h.isOdd()||w.isOdd())&&(h.iadd(o),w.isub(v)),h.iushrn(1),w.iushrn(1);for(var D=0,V=1;(u.words[0]&V)===0&&D<26;++D,V<<=1);if(D>0)for(u.iushrn(D);D-- >0;)(I.isOdd()||b.isOdd())&&(I.iadd(o),b.isub(v)),I.iushrn(1),b.iushrn(1);d.cmp(u)>=0?(d.isub(u),h.isub(I),w.isub(b)):(u.isub(d),I.isub(h),b.isub(w));}return {a:I,b,gcd:u.iushln(f)}},r.prototype._invmp=function(i){t(i.negative===0),t(!i.isZero());var d=this,u=i.clone();d.negative!==0?d=d.umod(i):d=d.clone();for(var h=new r(1),w=new r(0),I=u.clone();d.cmpn(1)>0&&u.cmpn(1)>0;){for(var b=0,f=1;(d.words[0]&f)===0&&b<26;++b,f<<=1);if(b>0)for(d.iushrn(b);b-- >0;)h.isOdd()&&h.iadd(I),h.iushrn(1);for(var o=0,v=1;(u.words[0]&v)===0&&o<26;++o,v<<=1);if(o>0)for(u.iushrn(o);o-- >0;)w.isOdd()&&w.iadd(I),w.iushrn(1);d.cmp(u)>=0?(d.isub(u),h.isub(w)):(u.isub(d),w.isub(h));}var F;return d.cmpn(1)===0?F=h:F=w,F.cmpn(0)<0&&F.iadd(i),F},r.prototype.gcd=function(i){if(this.isZero())return i.abs();if(i.isZero())return this.abs();var d=this.clone(),u=i.clone();d.negative=0,u.negative=0;for(var h=0;d.isEven()&&u.isEven();h++)d.iushrn(1),u.iushrn(1);do{for(;d.isEven();)d.iushrn(1);for(;u.isEven();)u.iushrn(1);var w=d.cmp(u);if(w<0){var I=d;d=u,u=I;}else if(w===0||u.cmpn(1)===0)break;d.isub(u);}while(true);return u.iushln(h)},r.prototype.invm=function(i){return this.egcd(i).a.umod(i)},r.prototype.isEven=function(){return (this.words[0]&1)===0},r.prototype.isOdd=function(){return (this.words[0]&1)===1},r.prototype.andln=function(i){return this.words[0]&i},r.prototype.bincn=function(i){t(typeof i=="number");var d=i%26,u=(i-d)/26,h=1<<d;if(this.length<=u)return this._expand(u+1),this.words[u]|=h,this;for(var w=h,I=u;w!==0&&I<this.length;I++){var b=this.words[I]|0;b+=w,w=b>>>26,b&=67108863,this.words[I]=b;}return w!==0&&(this.words[I]=w,this.length++),this},r.prototype.isZero=function(){return this.length===1&&this.words[0]===0},r.prototype.cmpn=function(i){var d=i<0;if(this.negative!==0&&!d)return -1;if(this.negative===0&&d)return 1;this._strip();var u;if(this.length>1)u=1;else {d&&(i=-i),t(i<=67108863,"Number is too big");var h=this.words[0]|0;u=h===i?0:h<i?-1:1;}return this.negative!==0?-u|0:u},r.prototype.cmp=function(i){if(this.negative!==0&&i.negative===0)return -1;if(this.negative===0&&i.negative!==0)return 1;var d=this.ucmp(i);return this.negative!==0?-d|0:d},r.prototype.ucmp=function(i){if(this.length>i.length)return 1;if(this.length<i.length)return -1;for(var d=0,u=this.length-1;u>=0;u--){var h=this.words[u]|0,w=i.words[u]|0;if(h!==w){h<w?d=-1:h>w&&(d=1);break}}return d},r.prototype.gtn=function(i){return this.cmpn(i)===1},r.prototype.gt=function(i){return this.cmp(i)===1},r.prototype.gten=function(i){return this.cmpn(i)>=0},r.prototype.gte=function(i){return this.cmp(i)>=0},r.prototype.ltn=function(i){return this.cmpn(i)===-1},r.prototype.lt=function(i){return this.cmp(i)===-1},r.prototype.lten=function(i){return this.cmpn(i)<=0},r.prototype.lte=function(i){return this.cmp(i)<=0},r.prototype.eqn=function(i){return this.cmpn(i)===0},r.prototype.eq=function(i){return this.cmp(i)===0},r.red=function(i){return new N(i)},r.prototype.toRed=function(i){return t(!this.red,"Already a number in reduction context"),t(this.negative===0,"red works only with positives"),i.convertTo(this)._forceRed(i)},r.prototype.fromRed=function(){return t(this.red,"fromRed works only with numbers in reduction context"),this.red.convertFrom(this)},r.prototype._forceRed=function(i){return this.red=i,this},r.prototype.forceRed=function(i){return t(!this.red,"Already a number in reduction context"),this._forceRed(i)},r.prototype.redAdd=function(i){return t(this.red,"redAdd works only with red numbers"),this.red.add(this,i)},r.prototype.redIAdd=function(i){return t(this.red,"redIAdd works only with red numbers"),this.red.iadd(this,i)},r.prototype.redSub=function(i){return t(this.red,"redSub works only with red numbers"),this.red.sub(this,i)},r.prototype.redISub=function(i){return t(this.red,"redISub works only with red numbers"),this.red.isub(this,i)},r.prototype.redShl=function(i){return t(this.red,"redShl works only with red numbers"),this.red.shl(this,i)},r.prototype.redMul=function(i){return t(this.red,"redMul works only with red numbers"),this.red._verify2(this,i),this.red.mul(this,i)},r.prototype.redIMul=function(i){return t(this.red,"redMul works only with red numbers"),this.red._verify2(this,i),this.red.imul(this,i)},r.prototype.redSqr=function(){return t(this.red,"redSqr works only with red numbers"),this.red._verify1(this),this.red.sqr(this)},r.prototype.redISqr=function(){return t(this.red,"redISqr works only with red numbers"),this.red._verify1(this),this.red.isqr(this)},r.prototype.redSqrt=function(){return t(this.red,"redSqrt works only with red numbers"),this.red._verify1(this),this.red.sqrt(this)},r.prototype.redInvm=function(){return t(this.red,"redInvm works only with red numbers"),this.red._verify1(this),this.red.invm(this)},r.prototype.redNeg=function(){return t(this.red,"redNeg works only with red numbers"),this.red._verify1(this),this.red.neg(this)},r.prototype.redPow=function(i){return t(this.red&&!i.red,"redPow(normalNum)"),this.red._verify1(this),this.red.pow(this,i)};var _={k256:null,p224:null,p192:null,p25519:null};function B(E,i){this.name=E,this.p=new r(i,16),this.n=this.p.bitLength(),this.k=new r(1).iushln(this.n).isub(this.p),this.tmp=this._tmp();}B.prototype._tmp=function(){var i=new r(null);return i.words=new Array(Math.ceil(this.n/13)),i},B.prototype.ireduce=function(i){var d=i,u;do this.split(d,this.tmp),d=this.imulK(d),d=d.iadd(this.tmp),u=d.bitLength();while(u>this.n);var h=u<this.n?-1:d.ucmp(this.p);return h===0?(d.words[0]=0,d.length=1):h>0?d.isub(this.p):d.strip!==void 0?d.strip():d._strip(),d},B.prototype.split=function(i,d){i.iushrn(this.n,0,d);},B.prototype.imulK=function(i){return i.imul(this.k)};function U(){B.call(this,"k256","ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f");}n(U,B),U.prototype.split=function(i,d){for(var u=4194303,h=Math.min(i.length,9),w=0;w<h;w++)d.words[w]=i.words[w];if(d.length=h,i.length<=9){i.words[0]=0,i.length=1;return}var I=i.words[9];for(d.words[d.length++]=I&u,w=10;w<i.length;w++){var b=i.words[w]|0;i.words[w-10]=(b&u)<<4|I>>>22,I=b;}I>>>=22,i.words[w-10]=I,I===0&&i.length>10?i.length-=10:i.length-=9;},U.prototype.imulK=function(i){i.words[i.length]=0,i.words[i.length+1]=0,i.length+=2;for(var d=0,u=0;u<i.length;u++){var h=i.words[u]|0;d+=h*977,i.words[u]=d&67108863,d=h*64+(d/67108864|0);}return i.words[i.length-1]===0&&(i.length--,i.words[i.length-1]===0&&i.length--),i};function G(){B.call(this,"p224","ffffffff ffffffff ffffffff ffffffff 00000000 00000000 00000001");}n(G,B);function W(){B.call(this,"p192","ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff");}n(W,B);function k(){B.call(this,"25519","7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed");}n(k,B),k.prototype.imulK=function(i){for(var d=0,u=0;u<i.length;u++){var h=(i.words[u]|0)*19+d,w=h&67108863;h>>>=26,i.words[u]=w,d=h;}return d!==0&&(i.words[i.length++]=d),i},r._prime=function(i){if(_[i])return _[i];var d;if(i==="k256")d=new U;else if(i==="p224")d=new G;else if(i==="p192")d=new W;else if(i==="p25519")d=new k;else throw new Error("Unknown prime "+i);return _[i]=d,d};function N(E){if(typeof E=="string"){var i=r._prime(E);this.m=i.p,this.prime=i;}else t(E.gtn(1),"modulus must be greater than 1"),this.m=E,this.prime=null;}N.prototype._verify1=function(i){t(i.negative===0,"red works only with positives"),t(i.red,"red works only with red numbers");},N.prototype._verify2=function(i,d){t((i.negative|d.negative)===0,"red works only with positives"),t(i.red&&i.red===d.red,"red works only with red numbers");},N.prototype.imod=function(i){return this.prime?this.prime.ireduce(i)._forceRed(this):(m(i,i.umod(this.m)._forceRed(this)),i)},N.prototype.neg=function(i){return i.isZero()?i.clone():this.m.sub(i)._forceRed(this)},N.prototype.add=function(i,d){this._verify2(i,d);var u=i.add(d);return u.cmp(this.m)>=0&&u.isub(this.m),u._forceRed(this)},N.prototype.iadd=function(i,d){this._verify2(i,d);var u=i.iadd(d);return u.cmp(this.m)>=0&&u.isub(this.m),u},N.prototype.sub=function(i,d){this._verify2(i,d);var u=i.sub(d);return u.cmpn(0)<0&&u.iadd(this.m),u._forceRed(this)},N.prototype.isub=function(i,d){this._verify2(i,d);var u=i.isub(d);return u.cmpn(0)<0&&u.iadd(this.m),u},N.prototype.shl=function(i,d){return this._verify1(i),this.imod(i.ushln(d))},N.prototype.imul=function(i,d){return this._verify2(i,d),this.imod(i.imul(d))},N.prototype.mul=function(i,d){return this._verify2(i,d),this.imod(i.mul(d))},N.prototype.isqr=function(i){return this.imul(i,i.clone())},N.prototype.sqr=function(i){return this.mul(i,i)},N.prototype.sqrt=function(i){if(i.isZero())return i.clone();var d=this.m.andln(3);if(t(d%2===1),d===3){var u=this.m.add(new r(1)).iushrn(2);return this.pow(i,u)}for(var h=this.m.subn(1),w=0;!h.isZero()&&h.andln(1)===0;)w++,h.iushrn(1);t(!h.isZero());var I=new r(1).toRed(this),b=I.redNeg(),f=this.m.subn(1).iushrn(1),o=this.m.bitLength();for(o=new r(2*o*o).toRed(this);this.pow(o,f).cmp(b)!==0;)o.redIAdd(b);for(var v=this.pow(o,h),F=this.pow(i,h.addn(1).iushrn(1)),L=this.pow(i,h),D=w;L.cmp(I)!==0;){for(var V=L,$=0;V.cmp(I)!==0;$++)V=V.redSqr();t($<D);var z=this.pow(v,new r(1).iushln(D-$-1));F=F.redMul(z),v=z.redSqr(),L=L.redMul(v),D=$;}return F},N.prototype.invm=function(i){var d=i._invmp(this.m);return d.negative!==0?(d.negative=0,this.imod(d).redNeg()):this.imod(d)},N.prototype.pow=function(i,d){if(d.isZero())return new r(1).toRed(this);if(d.cmpn(1)===0)return i.clone();var u=4,h=new Array(1<<u);h[0]=new r(1).toRed(this),h[1]=i;for(var w=2;w<h.length;w++)h[w]=this.mul(h[w-1],i);var I=h[0],b=0,f=0,o=d.bitLength()%26;for(o===0&&(o=26),w=d.length-1;w>=0;w--){for(var v=d.words[w],F=o-1;F>=0;F--){var L=v>>F&1;if(I!==h[0]&&(I=this.sqr(I)),L===0&&b===0){f=0;continue}b<<=1,b|=L,f++,!(f!==u&&(w!==0||F!==0))&&(I=this.mul(I,h[b]),f=0,b=0);}o=26;}return I},N.prototype.convertTo=function(i){var d=i.umod(this.m);return d===i?d.clone():d},N.prototype.convertFrom=function(i){var d=i.clone();return d.red=null,d},r.mont=function(i){return new X(i)};function X(E){N.call(this,E),this.shift=this.m.bitLength(),this.shift%26!==0&&(this.shift+=26-this.shift%26),this.r=new r(1).iushln(this.shift),this.r2=this.imod(this.r.sqr()),this.rinv=this.r._invmp(this.m),this.minv=this.rinv.mul(this.r).isubn(1).div(this.m),this.minv=this.minv.umod(this.r),this.minv=this.r.sub(this.minv);}n(X,N),X.prototype.convertTo=function(i){return this.imod(i.ushln(this.shift))},X.prototype.convertFrom=function(i){var d=this.imod(i.mul(this.rinv));return d.red=null,d},X.prototype.imul=function(i,d){if(i.isZero()||d.isZero())return i.words[0]=0,i.length=1,i;var u=i.imul(d),h=u.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m),w=u.isub(h).iushrn(this.shift),I=w;return w.cmp(this.m)>=0?I=w.isub(this.m):w.cmpn(0)<0&&(I=w.iadd(this.m)),I._forceRed(this)},X.prototype.mul=function(i,d){if(i.isZero()||d.isZero())return new r(0)._forceRed(this);var u=i.mul(d),h=u.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m),w=u.isub(h).iushrn(this.shift),I=w;return w.cmp(this.m)>=0?I=w.isub(this.m):w.cmpn(0)<0&&(I=w.iadd(this.m)),I._forceRed(this)},X.prototype.invm=function(i){var d=this.imod(i._invmp(this.m).mul(this.r2));return d._forceRed(this)};})(typeof fs>"u"||fs,za);});var po={};Y(po,{estimateTronRegularFee:()=>ql});var oo,zr,co,lo,uo,Gl,$l,ql,ho=K(()=>{oo=1e3,zr=1e6,co=.3,lo=3.5,uo=1.1,Gl=420,$l=14e3,ql=async({input:c,activeWallet:e,tronWeb:t})=>{let{to:n,amount:r,tokenAddress:s,isNativeToken:a=true,decimals:l=6}=c.data;if(!t)throw new Error("TronWeb instance unavailable.");let p=e.address,m=a?co:lo;try{if(a){let g=Math.ceil(Number(r)*zr),T=0;try{let B=await t.trx.getAccount(n);(!B||!B.address)&&(T=uo);}catch{T=uo;}let S=(await t.transactionBuilder.sendTrx(n,g,p)).raw_data_hex.length/2,O=await t.trx.getAccountResources(p),C=O.NetLimit||0,x=O.NetUsed||0,R=O.freeNetLimit||0,P=O.freeNetUsed||0,M=C-x+(R-P),_=0;if(M>=S)_=0;else {let B=S-M;B>0&&(_=B*oo/zr);}m=_+T;}else {if(!s)throw new Error("Token address is required for TRC20 transfers.");let g=await t.trx.getAccountResources(p),T=g.EnergyLimit||0,y=g.EnergyUsed||0,A=T-y,S=Math.round(Number(r)*Math.pow(10,l)),O=[{type:"address",value:n},{type:"uint256",value:S.toString()}],C={feeLimit:1e8,callValue:0},x;try{if(x=(await t.transactionBuilder.triggerSmartContract(s,"transfer(address,uint256)",C,O,p)).transaction,!x)throw new Error("Failed to build TRC20 transaction for estimation.")}catch(X){throw console.error("Failed to build TRC20 transaction:",X),new Error("Unable to estimate TRC20 transfer fee.")}let P=x.raw_data_hex.length/2,M=g.NetLimit||0,_=g.NetUsed||0,B=g.freeNetLimit||0,U=g.freeNetUsed||0,G=M-_+(B-U),W=0;G<P&&(W=(P-G)*oo/zr);let k=0,N=$l;try{let X=await t.transactionBuilder.triggerConstantContract(s,"transfer(address,uint256)",{},O,p);X&&X.energy_used&&(N=X.energy_used);}catch(X){console.warn("Could not get actual energy consumption, using default:",X);}A<N&&(k=(N-A)*Gl/zr),m=W+k,m=m*1.1;}}catch(g){console.error("Tron fee estimation error:",g),m=a?co:lo;}return {gasLimit:"N/A",gasPrice:"N/A",estimatedFee:m.toFixed(6)}};});var yo={};Y(yo,{estimateOrderExecutionFee:()=>Zl});var mo,xt,go,Kt,Yr,jl,zl,Yl,fo,Jl,Zl,wo=K(()=>{Q();mo=(c,e)=>c.toFixed(e),xt=c=>typeof c=="string"?Number(c):c||0,go="0x0000000000000000000000000000000000000000",Kt=1e6,Yr=5,jl=5e3,zl=100,Yl=1e3,fo=420,Jl=async(c,e)=>{try{return !!(await c.trx.getAccount(e)).create_time}catch{return false}},Zl=async(c,e,t,n)=>{let r=Yl,s=fo;if(!t||!c?.params||c.params.chainType!=="TRON"||!c.params.transaction?.raw_data_hex)return {gasLimit:"0",gasPrice:String(s),estimatedFee:Yr.toFixed(6),nativeFeeLamports:Math.round(Yr*Kt)};let{raw_data_hex:a}=c.params.transaction,l=c.method;try{let p=await t.trx.getAccountResources(e),m=xt(p.freeNetLimit)||jl,g=xt(p.freeNetUsed)||0,T=xt(p.NetLimit)||0,y=xt(p.NetUsed)||0,A=xt(p.EnergyLimit)||0,S=xt(p.EnergyUsed)||0,O=Math.max(0,m-g),C=Math.max(0,T-y),x=O+C,R=Math.max(0,A-S),P=Math.ceil(a.length/2),M=0,_=0,B=0,U=!1;if(l==="Send"&&c.params.token&&c.params.instructions?.[0]&&"tokenAddress"in c.params.instructions[0]&&c.params.instructions[0].tokenAddress&&c.params.instructions[0].tokenAddress!==go){P=Math.max(350,P);let X=c.to;try{let E=c.params.instructions[0].tokenAddress,i=await t.transactionBuilder.estimateEnergy(E,"transfer(address,uint256)",{feeLimit:1e8},[{type:"address",value:X},{type:"uint256",value:1}],e);i&&typeof i.energy_required<"u"?(M=xt(i.energy_required),M<1e3&&(M=6e3),M>5e5&&(M=5e5)):M=85e3;}catch(E){console.warn("estimateEnergy failed, fallback to conservative energy:",E),M=85e3;}X&&!await Jl(t,X)&&(_=1);}else l==="Send"?(P=Math.max(270,P),M=0):(l==="Change threshold"||l.includes("owner"))&&(M=15e4,P=Math.max(480,P),B=zl,U=!0);let W=Math.max(0,P-x)*r/Kt,k=W;if(!U&&M>0){let E=Math.max(0,M-R)*s/Kt;k+=E;}else U&&(k+=B);k+=_;let N=l==="Send"&&!c.params.token?1.02:1.05;return k=k*N,l==="Send"&&c.params.instructions?.[0]&&(!("tokenAddress"in c.params.instructions[0])||!c.params.instructions[0].tokenAddress||c.params.instructions[0].tokenAddress===go)?k=Math.max(.27,k):l==="Send"&&c.params.token&&(k=Math.max(2,k)),{gasLimit:String(M),gasPrice:String(s),estimatedFee:mo(k,6),nativeFeeLamports:Math.round(k*Kt),breakdown:{bandwidthCost:W,energyCost:U?0:Math.max(0,M-R)*s/Kt,activationFee:_,systemFee:B,requiredBandwidth:P,availableBandwidth:x,requiredEnergy:M,availableEnergy:R}}}catch(p){return console.error("TRON fee estimation error:",p),{gasLimit:"0",gasPrice:String(s),estimatedFee:mo(Yr,6),nativeFeeLamports:Math.round(Yr*Kt)}}};});var To={};Y(To,{estimateTronMultisigActivationFee:()=>tu});var eu,tu,vo=K(()=>{eu=c=>buffer.Buffer.byteLength(c,"utf8"),tu=async({multisig:c,tronWeb:e})=>{if(!c.address||!c.owners||!c.threshold)throw new Error("Missing multisig data for fee estimation.");if(!e)throw new Error("TronWeb instance unavailable.");let t={type:0,permission_name:"owner",threshold:Number(c.threshold),keys:c.owners.map(r=>({address:e.address.toHex(r.walletAddress),weight:1}))},n={type:2,permission_name:"active",threshold:Number(c.threshold),operations:"7fff1fc0037e0000000000000000000000000000000000000000000000000000",keys:c.owners.map(r=>({address:e.address.toHex(r.walletAddress),weight:1}))};try{let r=await e.transactionBuilder.updateAccountPermissions(c.address,t,null,[n]),a=(await e.trx.getAccountResources(c.address)).EnergyLimit||0,l=1e5,p=JSON.stringify(r.raw_data),m=eu(p),g=1e3,T=m*g,y=T,A=0;if(a<l){let x=(l-a)*1e3;A=x/1e6,y+=x;}let S=y/1e6;return {gasLimit:String(m),gasPrice:String(g),estimatedFee:S.toFixed(6),nativeFeeLamports:y,breakdown:{bandwidthFee:T/1e6,energyFee:A,energyRequired:l,energyAvailable:a}}}catch(r){console.error("TRON fee estimation error:",r);let s=100,a=s*1e6;return {gasLimit:"800",gasPrice:"1000",estimatedFee:s.toFixed(6),nativeFeeLamports:a}}};});function Xt(c){return BigInt(wt.minFeeA*c+wt.minFeeB)}function Vt(c,e,t,n,r){let l=t?80:50,p=n*100+r+20,m=10+c*43+e*l+p;return Math.ceil(m*1.2)}function Zr(c,e,t){let n=e+t,r=c.reduce((p,m)=>p+BigInt(m.value),0n);if(r<n)throw new Error(`Insufficient balance. Available: ${Number(r)/1e6} ADA, Required: ${Number(e)/1e6} ADA + Fee`);let s=[...c].sort((p,m)=>Number(BigInt(p.value)-BigInt(m.value))),a=0n,l=[];for(let p of s)if(l.push(p),a+=BigInt(p.value),a>=n)return {selected:l,total:a};throw new Error("Failed to select UTXOs")}async function Qr(c,e,t){return c.get("/sdk/order/utxos/ada",{params:{address:e,chainId:t}})}var wt,Es=K(()=>{wt={minFeeA:44,minFeeB:155381,maxTxSize:16384,coinsPerUtxoByte:4310,minUtxoValue:1e6};});var Mo={};Y(Mo,{estimateAdaNativeFee:()=>gu});var gu,ko=K(()=>{Es();gu=async c=>{try{let{address:e,amount:t,isNativeToken:n,apiClient:r,chainId:s}=c,a=parseFloat(t.toString()),l=BigInt(Math.floor(a*1e6)),p=!n,{utxos:m}=await Qr(r,e,s),g=Vt(2,2,p,1,0),T=Xt(g),{selected:y}=Zr(m,l,T),A=Vt(y.length,2,p,1,0),S=Xt(A),O=Number(S)/1e6;return {gasLimit:A.toString(),gasPrice:wt.minFeeA.toString(),estimatedFee:O.toFixed(6)}}catch(e){return console.error("Error estimating Cardano native fee:",e),{gasLimit:"500",gasPrice:wt.minFeeA.toString(),estimatedFee:"0.200000"}}};});var _o={};Y(_o,{estimateAdaOrderCreationFee:()=>fu});var fu,Bo=K(()=>{Es();fu=async c=>{try{let{amount:e,tokenAddress:t,multisig:n,apiClient:r,chainId:s}=c,{address:a,threshold:l,params:p}=n,m=parseInt(l)||1,g=p?.nativeScriptCbor?p.nativeScriptCbor.length/2:0,T=!!(t&&t!=="0x0000000000000000000000000000000000000000"),y=parseFloat(e),A=BigInt(Math.floor(y*1e6));if(!a)throw new Error("Multisig address is missing");let{utxos:S}=await Qr(r,a,s),O=Vt(2,2,T,m,g),C=Xt(O),{selected:x}=Zr(S,A,C),R=Vt(x.length,2,T,m,g),P=Xt(R),M=Number(P)/1e6;return {gasLimit:R.toString(),gasPrice:wt.minFeeA.toString(),estimatedFee:M.toFixed(6)}}catch(e){return console.error("Error estimating Cardano order creation fee:",e),{gasLimit:"1000",gasPrice:wt.minFeeA.toString(),estimatedFee:"0.300000"}}};});var Fo={};Y(Fo,{activateTrustLine:()=>wu});async function wu(c){let{address:e,currency:t,issuer:n,limit:r="1000000000",apiClient:s,rpcUrl:a}=c,{mainShare:l,additionalShare:p}=await Ke(s,e,"XRP"),m=await re([l,p]),g=buffer.Buffer.from(m).toString("hex"),T=await at(g);if(T.address!==e)throw new Error("KEY_MISMATCH");let y=new Wr__namespace.Client(a);try{await y.connect();try{await y.request({command:"account_info",account:n,ledger_index:"validated"});}catch(R){throw R?.data?.error==="actNotFound"?new Error("Token issuer account does not exist."):R}let A={TransactionType:"TrustSet",Account:e,LimitAmount:{currency:t,issuer:n,value:r}},S=await y.autofill(A),O=T.sign(S),x=(await y.submitAndWait(O.tx_blob)).result.meta?.TransactionResult||"";if(x==="tecNO_LINE_INSUF_RESERVE")throw new Error("Insufficient XRP for trust line reserve. Need at least 0.2 XRP available.");if(x==="tecNO_DST")throw new Error("Token issuer account does not exist in this network.");if(!x.startsWith("tes"))throw new Error(`XRP TrustSet transaction failed: ${x}`);return {hash:O.hash,tx:O.tx_blob,result:x}}finally{await y.disconnect();}}var Lo=K(()=>{Tt();Ze();Q();});var As={};Y(As,{estimateXrpNativeFee:()=>Tu});async function Tu(c=1){let e=dt(c),t=nt(e);return {gasLimit:"1",gasPrice:e,estimatedFee:t,currency:"XRP"}}var xs=K(()=>{st();});var bs={};Y(bs,{estimateXrpAssetFee:()=>vu});async function vu(c=1){let e=dt(c),t=nt(e);return {gasLimit:"1",gasPrice:e,estimatedFee:t,currency:"XRP"}}var Is=K(()=>{st();});var Ss={};Y(Ss,{estimateXrpMultisigConfigFee:()=>Eu});async function Eu(c,e){if(e==="activate"){let n=Math.ceil(14),r=(n*2).toString();return {gasLimit:"2",gasPrice:n.toString(),estimatedFee:nt(r),currency:"XRP"}}let t=dt(c);return {gasLimit:"1",gasPrice:t,estimatedFee:nt(t),currency:"XRP"}}var Os=K(()=>{st();});var Do={};Y(Do,{estimateXrpTrustLineFee:()=>Au});async function Au(c=1){let e=dt(c),t=nt(e);return {gasLimit:"1",gasPrice:e,estimatedFee:t,currency:"XRP"}}var Uo=K(()=>{st();});Q();it();ht();it();var lr=class{baseUrl;apiKey;accessToken;apiPathPrefix;defaultTimeout;config;constructor(e){this.config=e,this.baseUrl=e.apiBaseUrl.replace(/\/$/,""),this.apiKey=e.apiKey,this.accessToken=e.accessToken,this.apiPathPrefix=e.apiPathPrefix,this.defaultTimeout=e.timeout;}getApiKey(){return this.apiKey}getBaseUrl(){return this.baseUrl}getRpcConfig(){return ut(this.config.network,this.config.rpcOverrides)}getNetwork(){return this.config.network}getRpcConfigForNetwork(e){return ut(e,this.config.rpcOverrides)}async _request(e){let{method:t,path:n,data:r,headers:s,timeout:a,params:l}=e,p=this._resolveApiPath(n),m=this._buildUrl(p,l),g=a??this.defaultTimeout,T=new AbortController,y=setTimeout(()=>T.abort(),g),A={"Content-Type":"application/json",...s};this.apiKey&&(A["x-api-key"]=this.apiKey),this.accessToken&&(A.Authorization=`Bearer ${this.accessToken}`);let S={method:t,headers:A,signal:T.signal};r!==void 0&&t!=="GET"&&(S.body=JSON.stringify(r));try{let O=await fetch(m,S);return clearTimeout(y),await this._handleResponse(O,t,p)}catch(O){throw clearTimeout(y),O instanceof exports.ApiError||O instanceof exports.UnauthorizedError||O instanceof exports.PermissionDeniedError||O instanceof exports.OrgPolicyRejectedError||O instanceof $t?O:O instanceof Error?O.name==="AbortError"?new dr(`Request timed out after ${g}ms`,{timeoutMs:g,operation:`${t} ${p}`}):new exports.NetworkError(`Network request failed: ${O.message}`,{endpoint:m,isTimeout:false,operation:`${t} ${p}`,cause:O}):new exports.NetworkError("An unknown network error occurred",{endpoint:m,isTimeout:false,operation:`${t} ${p}`})}}_resolveApiPath(e){let t=this.apiPathPrefix;if(e==="/sdk"||e.startsWith("/sdk/")){let n=e==="/sdk"?"/":e.slice(4);return `${t}${n}`}return e}_buildUrl(e,t){let n=e.startsWith("/")?e:`/${e}`,r=new URL(`${this.baseUrl}${n}`);return t&&Object.entries(t).forEach(([s,a])=>{a!==void 0&&(Array.isArray(a)?a.forEach(l=>{l!==void 0&&l!==""&&r.searchParams.append(s,String(l));}):r.searchParams.append(s,String(a)));}),r.toString()}async _handleResponse(e,t,n){let r;try{e.headers.get("content-type")?.includes("application/json")?r=await e.json():r=await e.text();}catch{r=null;}if(e.ok)return r;let s=this._extractErrorMessage(r)||e.statusText;if(e.status===401)throw new exports.UnauthorizedError(s,{operation:`${t} ${n}`,details:{statusCode:401,responseBody:r}});if(e.status===403)throw new exports.PermissionDeniedError(s,{operation:`${t} ${n}`,details:{statusCode:403,responseBody:r}});if(e.status===429){let a=e.headers.get("Retry-After");throw new $t(s,{retryAfter:a?parseInt(a,10):void 0,operation:`${t} ${n}`,details:{statusCode:429,responseBody:r}})}throw new exports.ApiError(s,{statusCode:e.status,responseBody:r,operation:`${t} ${n}`})}_extractErrorMessage(e){if(!e)return null;if(typeof e=="string")return e;if(typeof e=="object"){let t=e;if(typeof t.message=="string")return t.message;if(Array.isArray(t.message)&&t.message.length>0){let n=t.message[0];if(typeof n=="string")return n;if(typeof n=="object"&&n!==null){let r=n;return r.constraints&&typeof r.constraints=="object"?Object.values(r.constraints).join("; "):JSON.stringify(n)}}if(typeof t.error=="string")return t.error;if(Array.isArray(t.errors)&&t.errors.length>0)return String(t.errors[0])}return null}async get(e,t){return this._request({method:"GET",path:e,...t})}async post(e,t,n){return this._request({method:"POST",path:e,data:t,...n})}async put(e,t,n){return this._request({method:"PUT",path:e,data:t,...n})}async patch(e,t,n){return this._request({method:"PATCH",path:e,data:t,...n})}async delete(e,t){return this._request({method:"DELETE",path:e,...t})}};Pn();Q();ht();Tr();var br=class{client;keyReconstructor;constructor(e,t){this.client=e,this.keyReconstructor=t;}async createMultisig(e){let{chain:t,owners:n,threshold:r,chainIds:s}=e,a=this.client.getNetwork()==="mainnet";switch(t){case "EVM":let l=a?"1":"11155111";return this.createEvmMultisig(n,r,s||[l]);case "SOL":let p=a?"sol_mainnet":"sol_devnet",m=s&&s.length>0?s[0]:p;return this.createSolanaMultisig(m,n[0],n,r);case "TRON":let g=a?"tron_mainnet":"tron_shasta",T=s&&s.length>0?s:[g];return this.createTronMultisig(n,r,T);case "BTC":case "BTC_T3":let y=a?"BTC":"BTC_T3",A=s&&s.length>0?s[0]:y;return this.createBtcMultisig(A,n[0],n,r);case "ADA":{let S=a?"ada_mainnet":"ada_preprod",O=s&&s.length>0?s[0]:S;return this.createAdaMultisig(O,n[0],n,r)}case "XRP":{let S=a?"xrp_mainnet":"xrp_testnet",O=s&&s.length>0?s[0]:S;return this.createXrpMultisig(O,n[0],n,r)}default:throw new exports.InvalidInputError(`Chain '${t}' is not supported for createMultisig`)}}async getMultisig(e){return this.getMultisigById(e.chain,e.address)}async getMultisigs(e){return this.getMultisigsByChain(e.chain,e.walletAddress)}async getPaginatedMultisigs(e){let t=e?.page??1,n=e?.limit??10,r={page:t,limit:n};return e?.chainTypes?.length&&(r.chainTypes=e.chainTypes.join(",")),this.client.get("/sdk/multisig",{params:r})}async updateMultisig(e){return this.updateMultisigName(e.multisigId,e.name,e.walletAddress)}async deleteMultisig(e){return this.deleteMultisigById(e.multisigId)}async activateMultisig(e){let{chain:t,multisigId:n,walletAddress:r}=e;switch(t){case "EVM":{if(!e.multisig)throw new exports.InvalidInputError("Multisig object is required for EVM activation");return {txHash:(await this.activateEvmMultisig(e.multisig,r,e.gasLimit,e.gasPrice)).txHash}}case "SOL":{if(!e.multisig)throw new exports.InvalidInputError("Multisig object is required for Solana activation");let s=e.multisig,a=s.params?.share;if(!a)throw new exports.InvalidInputError("Multisig share (params.share) is required for Solana multisig activation");let l=s.params?.vaultAddress;if(!l)throw new exports.InvalidInputError("Vault address (params.vaultAddress) is required for Solana multisig activation");let p=await this.client.post("/sdk/multisig/sol/tx/deploy",{multisigId:n,walletAddress:r});if(!p.blockhash)throw new exports.InvalidInputError("Failed to get blockhash from backend for Solana activation");let m=this.client.getNetwork(),g=this.client.getRpcConfigForNetwork(m),{activateSolMultisig:T}=await Promise.resolve().then(()=>(Bi(),_i)),{tx:y}=await T({createKeyServerShare:a,multisigId:n,multisigPda:s.address,owners:s.owners.map(S=>S.walletAddress),threshold:Number(s.threshold),vaultAddress:l,rpcUrl:g.solana,recentBlockhash:p.blockhash,walletAddress:r,apiClient:this.client});return {txHash:(await this.client.post("/sdk/multisig/sol/deploy",{multisigId:n,walletAddress:r,transaction:y})).txHash||"Transaction submitted"}}case "TRON":{if(!e.multisig)throw new exports.InvalidInputError("Multisig object is required for Tron activation");let s=e.multisig;if(!s.address)throw new exports.InvalidInputError("Multisig address is required for Tron activation");let a=s.params?.share;if(!a)throw new exports.InvalidInputError("Multisig share (params.share) is required for Tron multisig activation");let l=await this.fetchTronServerShare(n,r),{combineShares:p}=await Promise.resolve().then(()=>(Ze(),gi)),m=await p([a,l]),g=buffer.Buffer.from(m).toString("hex"),{TronWeb:T}=await import('tronweb'),{TRON_FULL_HOST:y}=await Promise.resolve().then(()=>(it(),si)),S=s.chainId==="tron_mainnet"?"mainnet":"testnet",O=new T({fullHost:y[S],privateKey:g}),C={type:0,permission_name:"owner",threshold:Number(s.threshold),keys:s.owners.map(_=>({address:O.address.toHex(_.walletAddress),weight:1}))},x={type:2,permission_name:"active",threshold:Number(s.threshold),operations:"7fff1fc0037e0000000000000000000000000000000000000000000000000000",keys:s.owners.map(_=>({address:O.address.toHex(_.walletAddress),weight:1}))},R=await O.transactionBuilder.updateAccountPermissions(s.address,C,null,[x]),P=await O.trx.sign(R,g);if(!P)throw new exports.InvalidInputError("Failed to sign Tron activation transaction");let M=await this.client.patch(`/sdk/multisig/execute/tron/${n}`,{transaction:P});if(!M||!M.multisig)throw new exports.InvalidInputError("Failed to execute Tron activation transaction");return {txHash:M.txHash||M.transactionHash||M.multisig?.id||"Transaction submitted"}}case "BTC":case "BTC_T3":throw new exports.InvalidInputError("BTC multisig activation is handled differently");case "XRP":{if(!e.multisig)throw new exports.InvalidInputError("Multisig object is required for XRP activation");let s=e.multisig;if(!s.address)throw new exports.InvalidInputError("Multisig address is required for XRP activation");let a=s.params?.share;if(!a)throw new exports.InvalidInputError("Multisig share (params.share) is required for XRP multisig activation");let l=s.owners.map(y=>({address:y.walletAddress,weight:1})),p=parseInt(s.threshold||"1",10),m=this.client.getNetwork(),g=this.client.getRpcConfigForNetwork(m).xrp,{activateXrpMultisig:T}=await Promise.resolve().then(()=>(Vn(),Xn));return await T({multisigId:n,multisigAddress:s.address,walletAddress:r,signers:l,threshold:p,apiClient:this.client,rpcUrl:g,deviceShare:a}),{txHash:""}}default:throw new exports.InvalidInputError(`Chain '${t}' is not supported for activateMultisig`)}}async getMultisigHistory(e){return this.getHistory(e.multisigId,e.page,e.limit)}async fetchMultisigServerShare(e){return this.fetchTronServerShare(e.multisigId,e.walletAddress)}async createEvmMultisig(e,t,n){let r=this.client.getNetwork()==="mainnet",s=Number(r?"1":"11155111"),a=n.map(p=>typeof p=="number"?p:parseInt(String(p),10)||s);return (await this.client.post("/sdk/multisig/create/evm",{owners:e,threshold:t,chains:a})).multisigs}async createSolanaMultisig(e,t,n,r){return (await this.client.post(`/sdk/multisig/create/sol/${e}/${t}`,{owners:n,threshold:r})).multisig}async createTronMultisig(e,t,n=["tron_shasta"]){return (await this.client.post("/sdk/multisig/create/tron",{owners:e,threshold:t,chains:n})).multisig}async createBtcMultisig(e,t,n,r){return (await this.client.post(`/sdk/multisig/create/btc/${e}/${t}`,{owners:n,threshold:r})).multisig}async createAdaMultisig(e,t,n,r){return (await this.client.post(`/sdk/multisig/create/ada/${e}/${t}`,{chains:[e],creatorAddress:t,owners:n,threshold:r})).multisig}async createXrpMultisig(e,t,n,r){return (await this.client.post("/sdk/multisig/create/xrp",{chains:[e],creatorAddress:t,owners:n,threshold:r})).multisig}async getMultisigsByChain(e,t){let n=t?`/sdk/multisig/${e}/${t}`:`/sdk/multisig/${e}`;return (await this.client.get(n)).multisigs}async getMultisigById(e,t){return (await this.client.get(`/sdk/multisig/id/${e}/${t.toLowerCase()}`)).multisig}async activateEvmMultisig(e,t,n,r){if(!this.keyReconstructor)throw new exports.InvalidInputError("KeyReconstructor is required for EVM multisig activation");if(!e.factoryAddress||!e.params?.deployData)throw new exports.InvalidInputError("Multisig is missing deployment data (factoryAddress or deployData)");let{id:s,chainId:a,factoryAddress:l,params:{deployData:p}}=e,m=new mt(this.client,this.client.getRpcConfig()),g=m.getProvider(String(a)),T={to:l,data:p,value:"0",chainId:Number(a)};if(T.nonce=await m.getNonce(g,t),n?T.gasLimit=BigInt(n):T.gasLimit=500000n,r)T.gasPrice=BigInt(r);else try{let C=await m.getFeeData(g);C.gasPrice&&(T.gasPrice=C.gasPrice);}catch{console.warn("Failed to fetch fee data for activation default.");}let{tx:y}=await this.keyReconstructor.signTransaction({address:t,chainType:"EVM",action:"signEvmTx",params:{transaction:T,expectedChainId:Number(a)}}),A=y,S=await m.getSignedTransaction(A);if(!S.hash)throw new Error("Missing transaction hash after signing");return await m.simulateTransaction(g,S),{txHash:(await this.client.post(`/sdk/multisig/execute/evm/${s}`,{signedTransaction:A})).transactionHash}}async updateMultisigName(e,t,n){return (await this.client.post("/sdk/multisig/update/name",{multisigId:e,name:t,walletAddress:n})).multisig}async deleteMultisigById(e){return this.client.delete(`/sdk/multisig/${e}`)}async getHistory(e,t=1,n=10){return this.client.get(`/sdk/history/${e}`,{params:{page:t,limit:n}})}async fetchSolMultisigShare(e,t){return (await this.client.post("/sdk/multisig/share/sol",{multisigId:e,walletAddress:t})).share}async fetchTronServerShare(e,t){return (await this.client.post("/sdk/multisig/share/tron",{multisigId:e,walletAddress:t})).share}};Q();ht();qe();var Ni=[{inputs:[{internalType:"address",name:"owner",type:"address"},{internalType:"uint256",name:"_threshold",type:"uint256"}],name:"addOwnerWithThreshold",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"address",name:"prevOwner",type:"address"},{internalType:"address",name:"owner",type:"address"},{internalType:"uint256",name:"_threshold",type:"uint256"}],name:"removeOwner",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"uint256",name:"_threshold",type:"uint256"}],name:"changeThreshold",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"address",name:"prevOwner",type:"address"},{internalType:"address",name:"oldOwner",type:"address"},{internalType:"address",name:"newOwner",type:"address"}],name:"swapOwner",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[],name:"getOwners",outputs:[{internalType:"address[]",name:"",type:"address[]"}],stateMutability:"view",type:"function"},{inputs:[],name:"getThreshold",outputs:[{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"address",name:"to",type:"address"},{internalType:"uint256",name:"value",type:"uint256"},{internalType:"bytes",name:"data",type:"bytes"},{internalType:"uint8",name:"operation",type:"uint8"},{internalType:"uint256",name:"safeTxGas",type:"uint256"},{internalType:"uint256",name:"baseGas",type:"uint256"},{internalType:"uint256",name:"gasPrice",type:"uint256"},{internalType:"address",name:"gasToken",type:"address"},{internalType:"address",name:"refundReceiver",type:"address"},{internalType:"bytes",name:"signatures",type:"bytes"}],name:"execTransaction",outputs:[{internalType:"bool",name:"success",type:"bool"}],stateMutability:"payable",type:"function"},{inputs:[{internalType:"address",name:"to",type:"address"},{internalType:"uint256",name:"value",type:"uint256"},{internalType:"bytes",name:"data",type:"bytes"},{internalType:"uint8",name:"operation",type:"uint8"},{internalType:"uint256",name:"safeTxGas",type:"uint256"},{internalType:"uint256",name:"baseGas",type:"uint256"},{internalType:"uint256",name:"gasPrice",type:"uint256"},{internalType:"address",name:"gasToken",type:"address"},{internalType:"address payable",name:"refundReceiver",type:"address"},{internalType:"uint256",name:"_nonce",type:"uint256"}],name:"getTransactionHash",outputs:[{internalType:"bytes32",name:"",type:"bytes32"}],stateMutability:"view",type:"function"},{inputs:[],name:"nonce",outputs:[{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"view",type:"function"}];var Fi=c=>{let[e="0",t=""]=c.split("."),n=(t+"000000000").slice(0,9),r=e+n;return BigInt(r)},Li=.001;var Yc="0014df10",Di=c=>{let e=Array.from(c).map(t=>t.charCodeAt(0).toString(16).padStart(2,"0")).join("");return Yc+e};var Sr=class{client;keyReconstructor;constructor(e){this.client=e,this.keyReconstructor=new ee(e);}async createOrder(e){let{chain:t,multisigId:n,walletAddress:r,method:s,instructions:a}=e;switch(t){case "EVM":return {order:(await this.createEvmOrder(n,r,a,s,e)).order};case "SOL":{let l=await this.createSolanaOrder(n,r,a,s,e);return {order:l.order,proposalHash:l.params?.multisigPda}}case "TRON":return {order:(await this.createTronOrder(n,r,a,s,e)).order};case "BTC":case "BTC_T3":return {order:(await this.createBtcOrder(n,r,a)).order};case "ADA":return {order:(await this.createAdaOrder(n,r,a)).order};case "XRP":return {order:(await this.createXrpOrder(n,r,a,s,e)).order};default:throw new exports.InvalidInputError(`Chain '${t}' is not supported for createOrder`)}}async createSendOrder(e){let n=(await this.client.get(`/sdk/multisig/${e.multisigId}`)).multisig,r=this.detectSendMethod(n.chainType,e.token),s=this.buildSendInstructions(e.to,e.amount,e.token,e.memo);return this.createOrder({chain:n.chainType,multisigId:e.multisigId,walletAddress:e.walletAddress,method:r,instructions:s,token:e.token,selectedToken:e.token,chainId:e.chainId})}async createSettingsOrder(e){let t=e.multisig.params.chainType,n=e.multisig.owners.map(T=>T.walletAddress),r=+e.multisig.threshold,s=e.newOwners.filter(T=>!n.includes(T)),a=n.filter(T=>!e.newOwners.includes(T)),l=e.newThreshold??r,p=l!==r,{getChangeMethod:m}=await Promise.resolve().then(()=>(Qt(),Zt)),g=m(t,s.length,a.length,p);if(!g)throw new exports.InvalidInputError("No changes detected in multisig configuration");return this.createOrder({chain:t,multisigId:e.multisigId,multisigAddress:e.multisig.address||void 0,walletAddress:e.walletAddress,method:g,instructions:[],multisig:e.multisig,owners:n,newOwners:s,ownersToRemove:a,multisigThreshold:r,newThreshold:l,chainId:e.multisig.chainId})}detectSendMethod(e,t){if(!t)return "native";if(e==="EVM")return "erc20";if(e==="SOL")return "spl";if(e==="TRON")return t.address.startsWith("T")?"trc20":"trc";if(e==="XRP")return "asset";throw new exports.InvalidInputError(`Unsupported chain for token transfer: ${e}`)}buildSendInstructions(e,t,n,r){return [{to:e,toPubkey:e,amount:t,tokenAddress:n?.address,decimals:n?.decimals,memo:r}]}async getOrder(e){return this.getOrderById(e.orderId)}async getOrders(e){return this.getOrdersByMultisigId(e.multisigId,e.page,e.limit)}async getPaginatedOrders(e){return this.getOrders(e)}async signOrder(e){let{chain:t,orderId:n,walletAddress:r,transaction:s,multisigId:a}=e;switch(t){case "EVM":{if(!s)throw new exports.InvalidInputError("Transaction is required for EVM orders");let l=await this.signEvmOrder(n,r,s,a);return {signature:s,order:l.order}}case "SOL":{if(!s)throw new exports.InvalidInputError("Transaction is required for Solana orders");let l=await this.signSolanaOrder(n,r,s,a);return {signature:s,order:l.order}}case "TRON":{if(!s)throw new exports.InvalidInputError("Transaction is required for Tron orders");let l=await this.signTronOrder(n,r,s,a,e?.version);return {signature:s,order:l.order}}case "BTC":case "BTC_T3":{if(!s)throw new exports.InvalidInputError("Transaction is required for Btc orders");let l=await this.signBtcOrder(n,r,s,a);return {signature:s,order:l.order}}case "ADA":{let l=await this.signAdaOrderWithReconstruction(n,r,a);return {signature:l.witnessHex,order:l.order}}case "XRP":{let l=await this.signXrpOrder(n,r,a);return {signature:l.signature,order:l.order}}default:throw new exports.InvalidInputError(`Chain '${t}' is not supported for signOrder`)}}async executeOrder(e){let{chain:t,order:n,multisig:r,walletAddress:s,feeQuote:a,chainId:l}=e;switch(t){case "EVM":{let p=r.address||n.multisigAddress||n.vault?.address,m=await this.executeEvmOrder({orderId:n.id,order:n,multisigAddress:p,walletAddress:s,chainId:l||n.chainId||r.chainId||"1",gasLimit:a?.gasLimit,gasPrice:a?.gasPrice});return {txHash:m.txHash||"",order:m.order}}case "SOL":{let p=n.params?.instructions?.[0]?.type||"native",m=await this.executeSolanaOrder({orderId:n.id,walletAddress:s,chainId:l||r.chainId||"sol_mainnet",method:p});return {txHash:m.txHash||"",order:m.order}}case "TRON":{let p=await this.executeTronOrder(n.id,s);return {txHash:p.txHash||"",order:p.order}}case "BTC":case "BTC_T3":{let p=await this.executeBtcOrder(n.id,s);return {txHash:p.txHash||"",order:p.order}}case "ADA":{let p=await this.executeAdaOrder(n.id,s,r?.id);return {txHash:p.txHash||"",order:p.order}}case "XRP":{let p=await this.executeXrpOrder(n.id,s,r?.id);return {txHash:p.txHash||"",order:p.order}}default:throw new exports.InvalidInputError(`Chain '${t}' is not supported for executeOrder`)}}async rejectOrder(e){let{chain:t,order:n,multisig:r,walletAddress:s}=e;switch(t){case "EVM":return {order:await this.rejectEvmOrder(n,s,r)};case "SOL":return {order:(await this.rejectSolanaOrder(n.id,s,r.id)).order};case "TRON":return {order:await this.rejectTronOrder(n?.id,s,r.id)};case "BTC":case "BTC_T3":return {order:await this.rejectBtcOrder(n?.id,s,r.id)};case "ADA":return {order:await this.rejectAdaOrder(n?.id,s,r.id)};case "XRP":return {order:await this.rejectXrpOrder(n?.id,s,r.id)};default:throw new exports.InvalidInputError(`Chain '${t}' is not supported for rejectOrder`)}}async cancelOrder(e){return this.deleteOrder(e.orderId)}async createEvmOrder(e,t,n,r,s){let{isSendOrder:a,createEvmSendAction:l,createEvmActions:p}=await Promise.resolve().then(()=>(Qt(),Zt)),m;if(a(r)){let g=n[0];if(!g||!g.to)throw new exports.InvalidInputError("Send order requires 'to' address");if(!g.amount)throw new exports.InvalidInputError("Send order requires 'amount'");let T=r==="native",y=s.selectedToken||s.token;m=[l(g.to,g.amount,T,y?.address,y?.decimals)];}else {if(!s.multisigAddress&&!s.multisig?.address)throw new exports.InvalidInputError("Settings order requires multisigAddress or multisig object");let g=s.multisigAddress||s.multisig.address,T=s.owners||(s.multisig?s.multisig.owners.map(C=>C.walletAddress):[]),y=s.multisigThreshold||s.threshold||(s.multisig?.threshold?parseInt(s.multisig.threshold):1),A=this.client.getNetwork(),S=this.client.getRpcConfigForNetwork(A).evm[Number(s.chainId||"1")],O=S?new ethers.ethers.JsonRpcProvider(S):void 0;m=await p({chainId:s.chainId||"1",method:r,multisigAddress:g,threshold:y,newThreshold:s.newThreshold,owners:T,ownersAdded:s.newOwners,ownersRemoved:s.ownersToRemove,provider:O});}return this.client.post("/sdk/order/create/evm",{multisigId:e,walletAddress:t,actions:m})}async createSolanaOrder(e,t,n,r,s){let{isSendOrder:a,createSolanaInstructions:l}=await Promise.resolve().then(()=>(Qt(),Zt)),p;if(a(r)){let x=n[0];if(!x)throw new exports.InvalidInputError("Send order requires instruction");let R=x.to||x.toPubkey;if(!R)throw new exports.InvalidInputError("Send order requires 'to' or 'toPubkey' address");if(!x.amount)throw new exports.InvalidInputError("Send order requires 'amount'");let P=r==="spl"||r==="spl"?s.selectedToken?.address||s.token?.address||x.tokenAddress:void 0;p=[{type:r,toPubkey:R,amount:x.amount,tokenAddress:P,memo:x.memo}];}else {let x=s.newOwners||n.map(M=>M.newOwner).flat()||[],R=s.ownersToRemove||n.map(M=>M.removeOwner).flat()||[],P=s.newThreshold||n[0]?.newThreshold;p=l(r,x.filter(M=>M),R.filter(M=>M),P);}let m,g;if(s.orderIdToActivate){let{order:x}=await this.getOrderById(s.orderIdToActivate),{params:R}=await this.getSolanaOrderParams(s.orderIdToActivate);m=x,g=R;}else {let x=await this.client.post("/sdk/order/create/sol",{multisigId:e,walletAddress:t,actions:p});m=x.order,g=x.params;}if(!g?.vaultAddress||!g?.multisigPda)throw new exports.InvalidInputError("Backend response missing multisig params");let{createSolanaMultisigOrder:T}=await Promise.resolve().then(()=>(jn(),ea)),y=this.client.getNetwork(),A=this.client.getRpcConfigForNetwork(y).solana,S=n[0]?.memo,{tx:O}=await T({address:t,apiKey:this.client.getApiKey(),multisigPda:g.multisigPda,method:r,instructions:p,orderId:m.id,rpcUrl:A,vaultAddress:g.vaultAddress,selectedToken:s.selectedToken||s.token,apiUrl:this.client.getBaseUrl(),memo:S});return {order:(await this.client.post("/sdk/order/activate/sol",{transaction:O,multisigId:e,orderId:m.id,walletAddress:t})).order,params:g}}async createTronOrder(e,t,n,r,s){let{isSendOrder:a,createTronInstruction:l}=await Promise.resolve().then(()=>(Qt(),Zt)),p;if(a(r)){let m=n[0];if(!m)throw new exports.InvalidInputError("Send order requires instruction");let g=m.to||m.toPubkey;if(!g)throw new exports.InvalidInputError("Send order requires 'to' or 'toPubkey' address");if(!m.amount)throw new exports.InvalidInputError("Send order requires 'amount'");let T=r==="trc20"||r==="trc"||r==="trc20"||r==="trc"?s.selectedToken?.address||s.token?.address||m.tokenAddress:void 0;p=[{amount:m.amount,to:g,type:r,tokenAddress:T,memo:m.memo}];}else {let m=s.owners||s.multisig?.owners.map(S=>S.walletAddress)||[],g=s.newOwners||[],T=s.ownersToRemove||[],y=[...new Set([...g,...m])].filter(S=>!T.length||!T.includes(S));p=[l(r,y,s.newThreshold)];}return this.client.post("/sdk/order/create/tron",{multisigId:e,walletAddress:t,actions:p})}async createBtcOrder(e,t,n){let r=n[0]||{};return this.client.post("/sdk/order/create/btc",{multisigId:e,walletAddress:t,instructions:{amount:r.amount||r.value,to:r.to||r.toPubkey,type:r.type||"transfer"}})}async createAdaOrder(e,t,n){let r=n[0]||{},s={amount:r.amount||r.value,to:r.to||r.toPubkey,type:r.type||"native"};if(r.tokenAddress&&r.tokenAddress!=="0x0000000000000000000000000000000000000000"){if(s.policyId=r.tokenAddress,!r.symbol)throw new Error("Symbol is required for ADA token transfers");s.assetName=Di(r.symbol),s.type="token";}return this.client.post("/sdk/order/create/ada",{multisigId:e,walletAddress:t,instructions:s})}async createXrpOrder(e,t,n,r,s){let a=n[0]||{},l=r.replace(/^xrp_/,""),p;switch(l){case "native":{p=[{type:l,to:a.to||a.toPubkey,amount:a.amount,memo:a.memo}];break}case "asset":{let[m="",g=""]=a.tokenAddress.indexOf(".")?a.tokenAddress.split("."):[a.tokenAddress,a.issuer];p=[{type:l,to:a.to||a.toPubkey,amount:a.amount,tokenAddress:m,issuer:g,memo:a.memo}];break}case "setTrustLine":{p=[{type:l,tokenAddress:a.tokenAddress,issuer:a.issuer,limit:a.limit||"1000000000"}];break}case "removeTrustLine":{p=[{type:l,currency:a.tokenAddress||a.currency,issuer:a.issuer}];break}case "changeThreshold":{p=[{type:l,newThreshold:a.newThreshold??s.newThreshold}];break}case "updateOwners":{let m=a.newOwners||a.owners||s.newOwners;if(m&&m.length>8)throw new exports.InvalidInputError("XRP multisig supports maximum 8 signers");p=[{type:l,owners:m}];break}case "updateOwnerThreshold":{let m=a.newOwners||a.owners||s.newOwners;if(m&&m.length>8)throw new exports.InvalidInputError("XRP multisig supports maximum 8 signers");p=[{type:l,owners:m,newThreshold:a.newThreshold??s.newThreshold}];break}default:throw new exports.InvalidInputError(`Unsupported XRP order type: ${l}`)}return this.client.post("/sdk/order/create/xrp",{multisigId:e,walletAddress:t,actions:p})}async signXrpOrder(e,t,n){let{signXrpMultisigOrder:r}=await Promise.resolve().then(()=>(Yn(),zn)),s=await r({address:t,orderId:e,multisigId:n||"",apiClient:this.client}),{order:a}=await this.getOrderById(e);return {signature:s.signature,order:a}}async executeXrpOrder(e,t,n){let r=await this.client.patch("/sdk/order/execute/xrp",{orderId:e,multisigId:n,walletAddress:t});return {txHash:r.txHash||r.data?.txHash||"",order:r.order||r.data?.order}}async rejectXrpOrder(e,t,n){if(!t)throw new Error("Wallet address missing");if(!n)throw new Error("Vault id missing");try{return (await this.client.post("/sdk/order/reject/xrp",{orderId:e,multisigId:n,walletAddress:t})).order}catch(r){throw console.error("rejectXrpOrder failed:",r),new Error(r.response?.data?.message||r?.message||"Order rejection failed")}}async signAdaOrder(e,t,n,r,s){return this.client.post("/sdk/order/sign/ada",{orderId:e,walletAddress:t,witnessHex:n,keyHashHex:r,multisigId:s})}async signAdaOrderWithReconstruction(e,t,n){let{order:r}=await this.getOrderById(e),s=r?.hashToSing||r?.hashToSign;if(!s)throw new exports.InvalidInputError("Order hash to sign is missing for ADA order");let{signAdaMultisigOrder:a}=await Promise.resolve().then(()=>(Qn(),Zn)),l=await a({address:t,hashToSign:s,orderId:e,multisigId:n||r.multisigId||"",apiClient:this.client}),{order:p}=await this.getOrderById(e);return {witnessHex:l.witnessHex,keyHashHex:l.keyHashHex,order:p}}async rejectAdaOrder(e,t,n){if(!t)throw new Error("Wallet address missing");if(!n)throw new Error("Vault id missing");try{return (await this.client.post("/sdk/order/reject/ada",{orderId:e,multisigId:n,walletAddress:t})).order}catch(r){throw console.error("rejectAdaOrder failed:",r),new Error(r.response?.data?.message||r?.message||"Order rejection failed")}}async executeAdaOrder(e,t,n){let r=await this.client.patch("/sdk/order/execute/ada",{orderId:e,walletAddress:t,multisigId:n});return {txHash:r.txHash||r.data?.order?.txHash||"",order:r.order||r.data?.order}}async signEvmOrder(e,t,n,r){return this.client.post("/sdk/order/sign/evm",{orderId:e,walletAddress:t,signedHash:n,multisigId:r})}async signSolanaOrder(e,t,n,r){return this.client.post("/sdk/order/sign/sol",{orderId:e,walletAddress:t,transaction:n,multisigId:r})}async signTronOrder(e,t,n,r,s){return this.client.post("/sdk/order/sign/tron",{orderId:e,walletAddress:t,signature:n,multisigId:r,version:s})}async signBtcOrder(e,t,n,r){return this.client.post("/sdk/order/sign/btc",{orderId:e,walletAddress:t,signedData:n,multisigId:r})}async rejectEvmOrder(e,t,n){return (await this.client.post("/sdk/order/create/evm",{multisigId:n?.id,walletAddress:t,nonce:e?.nonce,actions:[{to:n?.address,data:"0x",value:"0"}]})).order}async rejectSolanaOrder(e,t,n){let r=await this.client.get(`/sdk/order/params/sol/${e}`),{order:s,params:a}=r;if(!a?.multisigPda||!a?.transactionIndex)throw new Error("Missing Vault params from backend response");let l=this.client.getNetwork(),p=this.client.getRpcConfigForNetwork(l).solana,{tx:m}=await this.keyReconstructor.signTransaction({address:t,chainType:"SOL",action:"sol.rejectOrder",params:{multisigParams:{multisigPda:a.multisigPda,transactionIndex:s.nonce.toString(),orderId:e,rpcUrl:p}}});return {order:(await this.client.post("/sdk/order/reject/sol",{transaction:m,orderId:e,multisigId:s.multisigId||n,walletAddress:t})).order}}async rejectTronOrder(e,t,n){if(!t)throw new Error("Wallet address missing");if(!n)throw new Error("Vault id missing");try{return (await this.client.post("/sdk/order/reject/tron",{orderId:e,multisigId:n,walletAddress:t})).order}catch(r){throw console.error("rejectOrder failed:",r),new Error(r?.message||"Order rejection failed")}}async rejectBtcOrder(e,t,n){if(!t)throw new Error("Wallet address missing");if(!n)throw new Error("Vault id missing");try{return (await this.client.post("/sdk/order/reject/btc",{orderId:e,multisigId:n,walletAddress:t})).order}catch(r){throw console.error("rejectOrder failed:",r),new Error(r.response?.data?.message||r?.message||"Order rejection failed")}}async executeEvmOrder(e){let{orderId:t,order:n,multisigAddress:r,walletAddress:s,chainId:a,gasLimit:l,gasPrice:p}=e;if(!s)throw new Error("Wallet not connected");if(!r)throw new Error("Multisig address is required for EVM order execution");let m=new ethers.ethers.Interface(Ni),g;try{let{to:T,value:y,data:A,operation:S,signature:O}=n,C=m.encodeFunctionData("execTransaction",[T,y||"0",A||"0x",S||0,0,0,0,ethers.ethers.ZeroAddress,ethers.ethers.ZeroAddress,O||"0x"]);g={to:r,value:"0",gasLimit:l||"500000",data:C,chainId:+a,gasPrice:p};}catch(T){throw console.error("Error encoding EVM transaction:",T),new Error("Fail encoding EVM data")}try{let T=this.client.getNetwork(),y=this.client.getRpcConfigForNetwork(T).evm[Number(a)];if(!y)throw new Error(`No RPC endpoint configured for chain ID ${a}`);let A=new ethers.ethers.JsonRpcProvider(y);g.nonce=await A.getTransactionCount(s,"pending"),g.chainId=Number(a);}catch(T){throw console.error("Failed to fetch nonce:",T),new Error("Failed to fetch nonce from provider")}try{let{tx:T}=await this.keyReconstructor.signTransaction({address:s,chainType:"EVM",action:"signTransaction",params:{transaction:g,expectedChainId:Number(a)}}),y=ethers.ethers.Transaction.from(T);if(!y.hash)throw new Error("Missing transaction hash after signing");let A=await this.client.post(`/sdk/order/execute/evm/${t}`,{signedTransaction:T});return {txHash:y.hash,order:A.order}}catch(T){let y=T,A=(y.message||y.reason||"").toLowerCase();throw console.error("EVM order execution failed:",T),y.code==="INSUFFICIENT_FUNDS"||A.includes("insufficient funds")||A.includes("insufficiend")||A.includes("insuffitiend")?new Error("Not enough ETH to pay for gas or transaction value."):y.code==="CALL_EXCEPTION"||A.includes("execution reverted")||A.includes("revert")||A.includes("failed")?new Error("Transaction failed. Check inputs, wallet balance, or permissions."):A.includes("gas required exceeds")||A.includes("out of gas")?new Error("Transaction ran out of gas. Try increasing gas limit."):new Error(y.message||"Unexpected error occurred.")}}async executeSolanaOrder(e){let{orderId:t,walletAddress:n,method:r}=e,s=this.client.getNetwork(),a=this.client.getRpcConfigForNetwork(s).solana,l=new web3_js.Connection(a,"confirmed"),p=new web3_js.PublicKey(n);if(await l.getBalance(p)<Number(Fi(Li.toString())))throw new Error("Insufficient SOL balance");let g=await this.client.get(`/sdk/order/params/sol/${t}`),{params:T,order:y}=g;if(!T?.multisigPda||!T?.transactionIndex)throw new Error("Missing Vault params from backend response");try{let{tx:A}=await this.keyReconstructor.signTransaction({address:n,chainType:"SOL",action:"sol.executeOrder",params:{multisigParams:{multisigPda:T.multisigPda,transactionIndex:y.nonce,orderId:t,rpcUrl:a},method:r}});return {txHash:"",order:(await this.client.patch("/sdk/order/execute/sol",{transaction:A,orderId:t,walletAddress:n})).order}}catch(A){console.error("Solana order execution failed:",A);let S="Transaction failed";throw typeof A?.message=="string"&&(A.message.includes("insufficient funds")||A.message.includes("Insufficient")||A.message.includes("insufficient")||A.message.includes("does not have enough balance")||A.message.includes("blockhash not found")||A.message.includes("failed to send transaction:")&&A.message.includes("Insufficient"))&&(S="Transaction failed: insufficient balance"),new Error(S)}}async executeTronOrder(e,t){let n=await this.client.patch("/sdk/order/execute/tron",{orderId:e,walletAddress:t});return {txHash:n.txHash||n.data?.txHash||"",order:n.order||n.data?.order}}async executeBtcOrder(e,t){let n=await this.client.patch("/sdk/order/execute/btc",{orderId:e,walletAddress:t});return {txHash:n.txHash||n.data?.order?.txHash||"",order:n.order||n.data?.order}}async getOrdersByMultisigId(e,t=1,n=20){return this.client.get(`/sdk/order/${e}`,{params:{page:t,limit:n}})}async getOrderById(e){return this.client.get(`/sdk/order/data/${e}`)}async deleteOrder(e){return this.client.delete(`/sdk/order/${e}`)}async getSolanaOrderParams(e){return this.client.get(`/sdk/order/params/sol/${e}`)}async getTronOrderTransaction(e){return this.client.get(`/sdk/order/tx/tron/${e}`)}};var Or=class{client;constructor(e){this.client=e;}async createEntry(e){return this.client.post("/sdk/address-book",e)}async getEntries(e){return this.client.get("/sdk/address-book",{params:{chainType:e?.chainType,type:e?.type}})}async updateEntry(e,t){return this.client.patch(`/sdk/address-book/${e}`,t)}async deleteEntry(e){await this.client.delete(`/sdk/address-book/${e}`);}async getAddressType(e,t){return this.client.get(`/sdk/address-book/type/${e}/${t}`)}};var Cr=class{client;constructor(e){this.client=e;}async getTeam(){return this.client.get("/sdk/organization/team")}async inviteMember(e){return this.client.post("/sdk/organization/team/invite",{email:e.email})}async removeMember(e){await this.client.delete(`/sdk/organization/team/${encodeURIComponent(e.memberId)}`);}async listAssignedMemberWallets(e){return this.client.get(`/sdk/organization/team/${encodeURIComponent(e.memberId)}/wallets`)}async assignWallet(e){return this.client.post(`/sdk/organization/team/${encodeURIComponent(e.memberId)}/wallets`,{walletId:e.walletId})}async unassignWallet(e){let t=encodeURIComponent(e.memberId),n=encodeURIComponent(e.walletId);await this.client.delete(`/sdk/organization/team/${t}/wallets/${n}`);}async listOrganizationWallets(){return this.client.get("/sdk/organization/wallets")}async getPolicies(){return this.client.get("/sdk/organization/policies")}async updatePolicies(e){return this.client.patch("/sdk/organization/policies",e)}async listAddresses(){return this.client.get("/sdk/organization/address-book")}async addAddress(e){return this.client.post("/sdk/organization/address-book",e)}async updateAddress(e,t){return this.client.patch(`/sdk/organization/address-book/${encodeURIComponent(e)}`,t)}async deleteAddress(e){await this.client.delete(`/sdk/organization/address-book/${encodeURIComponent(e)}`);}async getAuditLogs(e){let t={};return e?.page!=null&&(t.page=e.page),e?.limit!=null&&(t.limit=e.limit),e?.dateFrom&&(t.dateFrom=e.dateFrom),e?.dateTo&&(t.dateTo=e.dateTo),e?.actorId&&(t.actorId=e.actorId),e?.eventTypes?.length&&(t.eventTypes=e.eventTypes),this.client.get("/sdk/organization/audit-logs",{params:t})}};jt();jt();var wd=283,Rr=new Uint8Array(512),Ft=new Uint8Array(256);function Td(){let c=1;for(let e=0;e<255;e++)Rr[e]=c,Rr[e+255]=c,Ft[c]=e,c=c^c<<1,c&256&&(c^=wd);Ft[0]=0;}Td();function Pr(c,e){return c===0||e===0?0:Rr[Ft[c]+Ft[e]]}function vd(c,e){if(e===0)throw new Error("Division by zero in GF(2^8)");if(c===0)return 0;let t=Ft[c]-Ft[e];return t<0&&(t+=255),Rr[t]}function na(c,e){return c^e}function Ed(c,e){return c^e}function Ad(c,e){if(e===0)return c[0];let t=0;for(let n=c.length-1;n>=0;n--)t=na(Pr(t,e),c[n]);return t}function xd(c,e){let t=c.length,n=0;for(let r=0;r<t;r++){let s=1,a=1;for(let p=0;p<t;p++)r!==p&&(s=Pr(s,c[p]),a=Pr(a,Ed(c[p],c[r])));let l=vd(s,a);n=na(n,Pr(e[r],l));}return n}var sa=2,ia=3;function bd(c,e=sa,t=ia){if(e<2)throw new Error("Threshold must be at least 2");if(e>t)throw new Error("Threshold cannot exceed total shares");if(t>255)throw new Error("Cannot generate more than 255 shares");if(c.length===0)throw new Error("Secret cannot be empty");let n=c.length,r=[];for(let s=0;s<t;s++)r.push(new Uint8Array(n+1)),r[s][0]=s+1;for(let s=0;s<n;s++){let a=new Uint8Array(e);a[0]=c[s];let l=ur(e-1);for(let p=1;p<e;p++)a[p]=l[p-1],a[p]===0&&(a[p]=1);for(let p=0;p<t;p++){let m=p+1,g=Ad(a,m);r[p][s+1]=g;}}return r}function Id(c){if(c.length<2)throw new Error("Need at least 2 shares to reconstruct");if(c.some(a=>a.length===0))throw new Error("All shares must be non-empty");let e=c[0].length;if(c.some(a=>a.length!==e))throw new Error("All shares must have the same length");if(e<2)throw new Error("Share length must be at least 2 bytes (1 ID + 1 data)");let t=c.map(a=>a[0]);if(new Set(t).size!==t.length)throw new Error("Duplicate share IDs detected");if(t.some(a=>a===0))throw new Error("Share ID cannot be 0");let r=e-1,s=new Uint8Array(r);for(let a=0;a<r;a++){let l=c.map(p=>p[a+1]);s[a]=xd(t,l);}return s}var Mr=class c{static THRESHOLD=sa;static TOTAL_SHARES=ia;static split(e,t=c.THRESHOLD,n=c.TOTAL_SHARES){return bd(e,t,n)}static combine(e){return Id(e)}static validateShares(e,t=c.THRESHOLD){if(!Array.isArray(e)||e.length<t||e.some(a=>!(a instanceof Uint8Array))||e.some(a=>a.length<2))return false;let n=e[0].length;if(e.some(a=>a.length!==n))return false;let r=e.map(a=>a[0]);return !(new Set(r).size!==r.length||r.some(a=>a===0||a>255))}static getShareIndex(e){if(e.length===0)throw new Error("Share cannot be empty");return e[0]}static getShareData(e){if(e.length<2)throw new Error("Share must have at least 2 bytes");return e.slice(1)}static createShare(e,t){if(e<1||e>255)throw new Error("Share ID must be between 1 and 255");let n=new Uint8Array(t.length+1);return n[0]=e,n.set(t,1),n}};var Sd=32,aa={SERVER:0,RECOVERY:2},kr=class{shareApi;config;constructor(e,t){this.shareApi=e,this.config=t;}async generateAndSplitShares(e){let t=ur(Sd),n=Mr.split(t,2,3),r=Rn(n[aa.SERVER]),s=Rn(n[aa.RECOVERY]);return {privateKey:t,serverShare:r,recoveryShare:s}}};tr();Q();it();ht();var Md=cc__default.default(dc__namespace),ya="50000",wa="100000",Nr="20000000000",kd=5e-6,_d=1e-5,Bd=.00203928,Nd=1e3,Fr=1e6,Ta=.3,va=3.5,Ea=1.1,Fd=420,Aa=14e3,Ld=57.5,Dd=148,Ud=74,Wd=10,Kd=31,Lr=1e8,Hd=20,Xd=["function transfer(address to, uint256 amount)"],Vd=new ethers.Interface(Xd),Dr=class{config;rpcConfig;constructor(e){this.config=e,this.rpcConfig=ut(e.network,e.rpcOverrides);}async getEstimatedFee(e,t){switch(this.validateChain(e),e){case "EVM":return this.estimateEvmFee(t);case "SOL":return this.estimateSolanaFee(t);case "TRON":return this.estimateTronFee(t);case "BTC":case "BTC_T3":return this.estimateBtcFee(t);case "ADA":return this.estimateAdaFee(t);default:throw new exports.ChainNotSupportedError(`Unsupported chain: ${e}`,{requestedChain:e,supportedChains:["EVM","SOL","TRON","BTC","ADA"]})}}async estimateEvmFee(e){try{let t=Ye("EVM",this.rpcConfig,e.chainId),n=new ethers.ethers.JsonRpcProvider(t),r=!e.tokenAddress,s,a=ya;if(r)s={from:e.from,to:e.to,value:ethers.ethers.parseEther(e.value||"0"),data:"0x"};else {let T=ethers.ethers.parseUnits(e.value||"0",e.decimals||18),y=Vd.encodeFunctionData("transfer",[e.to,T]);s={from:e.from,to:e.tokenAddress,value:"0x0",data:y},a=wa;}let l,p;try{l=(await n.estimateGas(s)*115n/100n).toString();}catch{l=a;}try{p=(((await n.getFeeData()).gasPrice||BigInt(Nr))*105n/100n).toString();}catch{p=Nr;}let m=BigInt(l)*BigInt(p),g=ethers.formatUnits(m,18);return {estimatedFee:g,gasLimit:l,gasPrice:p,totalFee:g,currency:"ETH"}}catch{let n=e.tokenAddress?wa:ya,r=BigInt(n)*BigInt(Nr);return {estimatedFee:ethers.formatUnits(r,18),gasLimit:n,gasPrice:Nr,totalFee:ethers.formatUnits(r,18),currency:"ETH"}}}async estimateSolanaFee(e){try{let t=Ye("SOL",this.rpcConfig),n=new web3_js.Connection(t,"confirmed"),r=new web3_js.PublicKey(e.from),s=new web3_js.PublicKey(e.to),a=!e.tokenAddress,l=0n,{blockhash:p}=await n.getLatestBlockhash("confirmed"),m=[];if(a){let S=Math.ceil(Number(e.value)*web3_js.LAMPORTS_PER_SOL);m.push(web3_js.SystemProgram.transfer({fromPubkey:r,toPubkey:s,lamports:BigInt(S)}));}else {let S=new web3_js.PublicKey(e.tokenAddress),O=await this.detectTokenProgram(n,S),C=await ao.getAssociatedTokenAddress(S,r,!1,O,ao.ASSOCIATED_TOKEN_PROGRAM_ID),x=await ao.getAssociatedTokenAddress(S,s,!1,O,ao.ASSOCIATED_TOKEN_PROGRAM_ID);if(!await n.getAccountInfo(x)){let M=await n.getMinimumBalanceForRentExemption(165);l=BigInt(M),m.push(ao.createAssociatedTokenAccountInstruction(r,x,s,S,O,ao.ASSOCIATED_TOKEN_PROGRAM_ID));}let P=BigInt(Math.round(Number(e.value)*Math.pow(10,e.decimals||9)));O.equals(ao.TOKEN_2022_PROGRAM_ID)?m.push(ao.createTransferCheckedInstruction(C,S,x,r,P,e.decimals||9,[],O)):m.push(ao.createTransferInstruction(C,x,r,P,[],O));}let g=new web3_js.TransactionMessage({payerKey:r,recentBlockhash:p,instructions:m}).compileToLegacyMessage(),T=await n.getFeeForMessage(g,"confirmed"),y=BigInt(T.value||5e3),A=Number(y+l)/web3_js.LAMPORTS_PER_SOL;return {estimatedFee:A.toString(),gasLimit:"N/A",gasPrice:"N/A",totalFee:A.toString(),currency:"SOL"}}catch{let t=e.tokenAddress?_d+Bd:kd;return {estimatedFee:t.toString(),gasLimit:"N/A",gasPrice:"N/A",totalFee:t.toString(),currency:"SOL"}}}async estimateTronFee(e){try{let t=new tronweb.TronWeb({fullHost:je[this.config.network]}),n=!e.tokenAddress,r=n?Ta:va;if(n){let s=Math.ceil(Number(e.value)*Fr),a=0;try{let A=await t.trx.getAccount(e.to);(!A||!A.address)&&(a=Ea);}catch{a=Ea;}let m=(await t.transactionBuilder.sendTrx(e.to,s,e.from)).raw_data_hex.length/2,g=await t.trx.getAccountResources(e.from),T=(g.NetLimit||0)-(g.NetUsed||0)+(g.freeNetLimit||0)-(g.freeNetUsed||0),y=0;T<m&&(y=(m-T)*Nd/Fr),r=y+a;}else {let s=await t.trx.getAccountResources(e.from),a=(s.EnergyLimit||0)-(s.EnergyUsed||0),l=0;a<Aa&&(l=(Aa-a)*Fd/Fr),r=l*1.1;}return {estimatedFee:r.toFixed(6),gasLimit:"N/A",gasPrice:"N/A",totalFee:r.toFixed(6),currency:"TRX"}}catch{let t=e.tokenAddress?va.toString():Ta.toString();return {estimatedFee:t,gasLimit:"N/A",gasPrice:"N/A",totalFee:t,currency:"TRX"}}}async estimateBtcFee(e){let t=e.feeRate||Hd,n=e.from||"",r=Ld;n.startsWith("1")?r=Dd:n.startsWith("3")&&(r=Ud);let l=Wd+1*r+2*Kd,m=Math.ceil(l*t)/Lr;return {estimatedFee:m.toFixed(8),gasLimit:l.toFixed(2),gasPrice:t.toString(),totalFee:m.toFixed(8),currency:"BTC"}}async estimateAdaFee(e){let r=!!e.tokenAddress,s=10,a=43,l=r?80:50,m=Math.ceil((s+2*a+2*l+120)*1.2),T=(44*m+155381)/1e6;return {estimatedFee:T.toFixed(6),gasLimit:m.toString(),gasPrice:"44",totalFee:T.toFixed(6),currency:"ADA"}}async signTransaction(e,t,n){switch(this.validateChain(t),this.validatePrivateKey(e),t){case "EVM":return this.signEvmTransaction(e,n);case "SOL":return this.signSolanaTransaction(e,n);case "TRON":return this.signTronTransaction(e,n);case "BTC":case "BTC_T3":return this.signBtcTransaction(e,n);default:throw new exports.ChainNotSupportedError(`Unsupported chain: ${t}`,{requestedChain:t,supportedChains:["EVM","SOL","TRON","BTC"]})}}async signEvmTransaction(e,t){if(!t.chainId)throw new q("Chain ID is required for EVM transactions",{chain:"EVM"});let n="0x"+buffer.Buffer.from(e).toString("hex"),r=new ethers.ethers.Wallet(n),s=Ye("EVM",this.rpcConfig,t.chainId),a=new ethers.ethers.JsonRpcProvider(s),l=t.gasLimit;if(!l)try{l=(await a.estimateGas({from:t.from,to:t.to,value:t.value?ethers.ethers.parseEther(t.value):0n,data:t.data||"0x"})*120n/100n).toString();}catch{l=t.data&&t.data!=="0x"?"100000":"21000";}let p=t.gasPrice;if(!p&&!t.maxFeePerGas)try{let A=await a.getFeeData();A.gasPrice&&(p=A.gasPrice.toString());}catch{p="20000000000";}let m=t.nonce;if(m===void 0)try{m=await a.getTransactionCount(t.from,"pending");}catch(A){throw console.error("Failed to fetch nonce from provider:",A),new q("Failed to fetch nonce from provider",{chain:"EVM",details:{error:String(A)}})}let g=ethers.ethers.Transaction.from({chainId:t.chainId,to:t.to,value:t.value?ethers.ethers.parseEther(t.value):0n,data:t.data||"0x",nonce:m,gasLimit:BigInt(l),gasPrice:p?BigInt(p):void 0,maxFeePerGas:t.maxFeePerGas?BigInt(t.maxFeePerGas):void 0,maxPriorityFeePerGas:t.maxPriorityFeePerGas?BigInt(t.maxPriorityFeePerGas):void 0}),{validateEvmTransaction:T}=await Promise.resolve().then(()=>(kt(),Ei));try{T(g,t.chainId);}catch(A){if(A instanceof q)throw A;let S=A instanceof Error?{message:A.message,name:A.name}:{error:String(A)};throw new q("Transaction validation failed",{chain:"EVM",details:S})}let y=await r.signTransaction(g);return {rawTransaction:y,hash:ethers.ethers.keccak256(y),chain:"EVM"}}async signSolanaTransaction(e,t){let n;if(e.length===64)n=web3_js.Keypair.fromSecretKey(e);else if(e.length===32)n=web3_js.Keypair.fromSeed(e);else throw new q("Solana private key must be 32 or 64 bytes",{chain:"SOL"});let r=Ye("SOL",this.rpcConfig),s=new web3_js.Connection(r,"confirmed"),a=new web3_js.Transaction;if(t.tokenAddress){let m=new web3_js.PublicKey(t.tokenAddress),g=await this.detectTokenProgram(s,m),T=t.decimals||9,y=BigInt(Math.round(Number(t.value)*Math.pow(10,T))),A=await ao.getAssociatedTokenAddress(m,n.publicKey,false,g,ao.ASSOCIATED_TOKEN_PROGRAM_ID),S=await ao.getAssociatedTokenAddress(m,new web3_js.PublicKey(t.to),true,g,ao.ASSOCIATED_TOKEN_PROGRAM_ID);await s.getAccountInfo(S)||a.add(ao.createAssociatedTokenAccountInstruction(n.publicKey,S,new web3_js.PublicKey(t.to),m,g,ao.ASSOCIATED_TOKEN_PROGRAM_ID)),g.equals(ao.TOKEN_2022_PROGRAM_ID)?a.add(ao.createTransferCheckedInstruction(A,m,S,n.publicKey,y,T,[],g)):a.add(ao.createTransferInstruction(A,S,n.publicKey,y,[],g));}else {let m=BigInt(Math.ceil(Number(t.value)*web3_js.LAMPORTS_PER_SOL));a.add(web3_js.SystemProgram.transfer({fromPubkey:n.publicKey,toPubkey:new web3_js.PublicKey(t.to),lamports:m}));}let{blockhash:l}=await s.getLatestBlockhash("confirmed");return a.recentBlockhash=l,a.feePayer=n.publicKey,a.sign(n),{rawTransaction:a.serialize().toString("base64"),chain:"SOL"}}async signTronTransaction(e,t){try{let n=buffer.Buffer.from(e).toString("hex"),r=new tronweb.TronWeb({fullHost:je[this.config.network]}),s;if(t.tokenAddress){let l=t.decimals||6,p=Math.round(Number(t.value)*Math.pow(10,l)),m=[{type:"address",value:t.to},{type:"uint256",value:p.toString()}],g=await r.transactionBuilder.triggerSmartContract(t.tokenAddress,"transfer(address,uint256)",{feeLimit:1e8,callValue:0},m,t.from);if(!g||!g.transaction)throw new q("Failed to build TRC20 transfer transaction",{chain:"TRON",details:g});s=g.transaction;}else {let l=Math.ceil(Number(t.value)*Fr);if(!t.from)throw new q("From address is required for TRON transactions",{chain:"TRON"});s=await r.transactionBuilder.sendTrx(t.to,l,t.from);}if(!s)throw new q("Failed to build TRON transaction",{chain:"TRON"});let a=await r.trx.sign(s,n);if(!a||!a.txID)throw new q("Failed to sign TRON transaction",{chain:"TRON"});return {rawTransaction:JSON.stringify(a),hash:a.txID,chain:"TRON"}}catch(n){if(n instanceof q)throw n;let r=n?.message||n?.error||JSON.stringify(n)||"Unknown TRON transaction error";throw new q(`TRON transaction failed: ${r}`,{chain:"TRON",details:n})}}async getBtcUtxos(e){let t=this.rpcConfig.btc;try{let n=await fetch(`${t}/address/${e}/utxo`);if(!n.ok)throw new Error(`Failed to fetch UTXOs: ${n.statusText}`);return await n.json()}catch(n){throw console.error("Error fetching UTXOs:",n),new q("Failed to fetch UTXOs",{chain:"BTC"})}}async fetchBtcFee(){let e=`${this.rpcConfig.btc}/v1/fees/recommended`;try{let t=await fetch(e);if(!t.ok)throw new Error(`Failed to fetch BTC fee: ${t.statusText}`);let n=await t.json();return this.config.network!=="mainnet"?n.fastestFee:n.hourFee}catch(t){throw console.error("Error fetching BTC fee:",t),new Error("Failed to fetch recommended fee.")}}async signBtcTransaction(e,t){let n=this.config.network==="mainnet"?rt__namespace.networks.bitcoin:rt__namespace.networks.testnet;try{rt__namespace.address.toOutputScript(t.to,n);}catch{throw new q("Recipient address is invalid for the current network.",{chain:"BTC",details:{to:t.to,network:this.config.network}})}let r=Md.fromPrivateKey(buffer.Buffer.from(e),{network:n}),{address:s}=rt__namespace.payments.p2wpkh({pubkey:buffer.Buffer.from(r.publicKey),network:n});if(!s)throw new q("Could not derive sender address",{chain:"BTC"});let a=await this.getBtcUtxos(s);if(a.length===0)throw new exports.InsufficientBalanceError("No funds found on your Bitcoin address",{requiredAmount:t.value||"0",availableAmount:"0",currency:"BTC",chain:"BTC"});let l=await this.fetchBtcFee(),p=BigInt(Math.round(Number(t.value)*Lr)),m=[...a].sort((k,N)=>N.value-k.value),g=0,T=[],y=2;for(let k of m){T.push(k),g+=k.value;let X=T.length*148+y*34+10,E=Math.ceil(l*X);if(g>=Number(p)+E)break}let S=T.length*148+y*34+10,O=Math.ceil(l*S),C=1e4;if(O>C||O<=0)throw new q(`Estimated fee is outside the allowed range (1 - ${C} sats).`,{chain:"BTC",details:{estimatedFee:O}});let x=T.reduce((k,N)=>k+N.value,0);if(x<Number(p)+O)throw new exports.InsufficientBalanceError("Insufficient BTC balance to cover amount and fees",{requiredAmount:((Number(p)+O)/Lr).toString(),availableAmount:(x/Lr).toString(),currency:"BTC",chain:"BTC"});if(BigInt(x)>5000000000n)throw new q("Total input amount exceeds safe limit (50 BTC).",{chain:"BTC"});let P=new rt__namespace.Psbt({network:n}),M=0;for(let k of T)Et(P,{hash:k.txid,index:k.vout,witnessUtxo:{script:rt__namespace.address.toOutputScript(s,n),value:k.value}}),M+=k.value;tt(P,{address:t.to,value:p});let _=BigInt(Math.round(O)),B=BigInt(M)-p-_,U=546n;if(B<0n)throw new q("Insufficient funds to cover amount and fee.",{chain:"BTC"});B>0n&&B<U&&(B=0n),B>0n&&tt(P,{address:s,value:B});for(let k=0;k<T.length;k++)P.signInput(k,r);P.finalizeAllInputs();let G=P.extractTransaction().toHex(),W=P.extractTransaction().getId();return {rawTransaction:G,hash:W,chain:"BTC"}}async broadcastTransaction(e,t){if(this.validateChain(e),!t.rawTransaction)throw new Ot("Signed transaction data is missing",{chain:e});switch(e){case "EVM":return this.broadcastEvmTransaction(t);case "SOL":return this.broadcastSolanaTransaction(t);case "TRON":return this.broadcastTronTransaction(t);case "BTC":case "BTC_T3":return this.broadcastBtcTransaction(t);default:throw new exports.ChainNotSupportedError(`Unsupported chain: ${e}`,{requestedChain:e,supportedChains:["EVM","SOL","TRON","BTC"]})}}async broadcastEvmTransaction(e){let t=ethers.ethers.Transaction.from(e.rawTransaction),n=Number(t.chainId),r=Ye("EVM",this.rpcConfig,n),s=new ethers.ethers.JsonRpcProvider(r);return await s.getNetwork(),{txHash:(await s.broadcastTransaction(e.rawTransaction)).hash,chain:"EVM"}}async broadcastSolanaTransaction(e){let t=Ye("SOL",this.rpcConfig),n=new web3_js.Connection(t,"confirmed"),r=buffer.Buffer.from(e.rawTransaction,"base64"),s=web3_js.Transaction.from(r);return {txHash:await n.sendRawTransaction(s.serialize(),{skipPreflight:false,preflightCommitment:"confirmed"}),chain:"SOL"}}async broadcastTronTransaction(e){let t=new tronweb.TronWeb({fullHost:je[this.config.network]}),n=JSON.parse(e.rawTransaction),r=await t.trx.sendRawTransaction(n);if(!r.result)throw new Ot("Tron broadcast failed",{chain:"TRON",details:{result:r}});return {txHash:r.txid,chain:"TRON"}}async broadcastBtcTransaction(e){let t=this.rpcConfig.btc,n=await fetch(`${t}/tx`,{method:"POST",body:e.rawTransaction});if(!n.ok){let s=await n.text();throw new Ot(`BTC broadcast failed: ${s}`,{chain:"BTC"})}return {txHash:await n.text(),chain:"BTC"}}async detectTokenProgram(e,t){try{let n=await e.getAccountInfo(t);return n&&n.owner.equals(ao.TOKEN_2022_PROGRAM_ID)?ao.TOKEN_2022_PROGRAM_ID:ao.TOKEN_PROGRAM_ID}catch{return ao.TOKEN_PROGRAM_ID}}getRpcEndpointUrl(e,t){return Ye(e,this.rpcConfig,t)}validateChain(e){let t=["EVM","SOL","TRON","BTC","BTC_T3","ADA"];if(!t.includes(e))throw new exports.ChainNotSupportedError(`Chain '${e}' is not supported`,{requestedChain:e,supportedChains:t})}validatePrivateKey(e){if(!e||e.length===0)throw new q("Private key is required for signing");if(e.length!==32&&e.length!==64)throw new q("Private key must be 32 or 64 bytes",{details:{keyLength:e.length}})}};Q();qe();var Gr=class{client;keyManager;txService;config;keyReconstructor;constructor(e,t,n,r){this.client=e,this.keyManager=t,this.txService=n,this.config=r,this.keyReconstructor=new ee(e,r.network);}async createWallet(e){await this.keyManager.generateAndSplitShares(e);return {...await this.client.post("/sdk/wallets/create",{wallets:[{chain:e}]})}}async importWallet(e,t){return this.client.post("/sdk/wallets/create",{wallets:[{chain:e,key:t}]})}async getWallet(e){return await this.client.get(`/sdk/wallets/${e}`)}async getWallets(){return this.client.get("/sdk/wallets/all")}async getPaginatedWallets(e,t=10){if(typeof e=="object"&&e!==null)return this.client.get("/sdk/wallets",{params:{page:e.page??1,limit:e.limit??10,...e.chainTypes?.length?{chainTypes:e.chainTypes.join(",")}:{}}});let n=typeof e=="number"?e:1;return this.client.get("/sdk/wallets",{params:{page:n,limit:t}})}async deleteWallet(e,t){return this.client.delete(`/sdk/wallets/${e}/${t}`)}async updateWalletName(e,t,n){return this.client.post("/sdk/wallets/update/name",{walletAddress:t,name:n,chainType:e})}async fetchServerShare(e,t){return (await this.client.get(`/sdk/wallets/share/c/${e}/${t}`)).share}async fetchRecoveryShare(e,t){return (await this.client.get(`/sdk/wallets/share/s/${e}/${t}`)).share}async fetchShares(e,t){let[n,r]=await Promise.all([this.fetchServerShare(e,t),this.fetchRecoveryShare(e,t)]);return {server:n,recovery:r}}async fetchPublicKey(){return (await this.client.get("/sdk/wallets/pubkey")).pubkey}async updateShares(e,t,n){await this.client.post("/sdk/wallets/update",{walletAddress:e,serverShare:t,encryptedRecoveryShare:n});}async getPortfolio(e,t,n){let r=this.toApiChainType(e);return this.client.get(`/sdk/wallets/portfolio/${r}/${t}/${n}`)}toApiChainType(e){return {EVM:"EVM",SOL:"SOL",TRON:"TRON",BTC:"BTC",BTC_T3:"BTC_T3",ADA:"ADA",XRP:"XRP"}[e]||e.toUpperCase()}async getSupportedTokens(e,t,n=1,r=50,s){return this.client.get(`/sdk/wallets/supported-tokens/${e}/${t}`,{params:{page:n,limit:r,search:s}})}async getTotalAssetValue(){return this.client.get("/sdk/wallets/total-asset-value")}async getHistory(e,t,n=1,r=20){return this.client.get(`/sdk/history/wallet/${e}/${t}`,{params:{page:n,limit:r}})}async signTransaction(e){let t;if(e.chain==="EVM"){let r=await this.keyReconstructor.reconstructWithRetry(()=>this.keyReconstructor.reconstructEvmKey(e.address)),s=r.privateKey.startsWith("0x")?r.privateKey.slice(2):r.privateKey;t=buffer.Buffer.from(s,"hex");}else if(e.chain==="SOL")t=(await this.keyReconstructor.reconstructWithRetry(()=>this.keyReconstructor.reconstructSolanaKey(e.address))).secretKey;else if(e.chain==="TRON"){let r=await this.keyReconstructor.reconstructWithRetry(()=>this.keyReconstructor.reconstructTronKey(e.address)),s=r.privateKey.startsWith("0x")?r.privateKey.slice(2):r.privateKey;t=buffer.Buffer.from(s,"hex");}else if(e.chain==="BTC"||e.chain==="BTC_T3"){let r=e.chain==="BTC";t=(await this.keyReconstructor.reconstructWithRetry(()=>this.keyReconstructor.reconstructBtcKey(e.address,r))).privateKeyBuffer;}else throw e.chain==="ADA"||e.chain==="XRP"?new Error(`${e.chain} personal wallet signing is handled via the dedicated sendTransaction path`):new Error(`Unsupported chain: ${e.chain}`);return await this.txService.signTransaction(t,e.chain,e.txParams)}async sendTransaction(e){if(e.chain==="EVM"){let{evmSendTransaction:r}=await Promise.resolve().then(()=>(Oa(),Sa)),s={chain:e.chain,address:e.address,share:"",name:"",isImported:false},a={to:e.txParams.to,amount:e.txParams.value||"0",tokenAddress:e.txParams.tokenAddress,decimals:e.txParams.decimals,isNativeToken:e.txParams.isNativeToken,estimatedFee:e.txParams.feeHint},p=await r({input:{data:a},activeWallet:s,chainId:e.txParams.chainId||1,apiClient:this.client,rpcConfig:this.txService.rpcConfig});return {hash:p.hash,rawTransaction:p.from}}if(e.chain==="SOL"){let{sendSolanaTransaction:r}=await Promise.resolve().then(()=>(Ua(),Da)),s=await r({address:e.address,apiClient:this.client,to:e.txParams.to,amount:e.txParams.value||"0",rpcUrl:this.txService.rpcConfig.solana,isNativeToken:e.txParams.isNativeToken,tokenAddress:e.txParams.tokenAddress,decimals:e.txParams.decimals,memo:e.txParams.memo});return {hash:s.tx,rawTransaction:s.tx}}if(e.chain==="BTC"||e.chain==="BTC_T3"){let{sendBtcTransaction:r}=await Promise.resolve().then(()=>(Ha(),Ka)),s={chain:e.chain,address:e.address,share:"",name:"",isImported:false},a=await r({activeWallet:s,to:e.txParams.to,amount:e.txParams.value||"0",apiClient:this.client,network:this.config.network});return {hash:a.hash,rawTransaction:a.rawTransaction}}if(e.chain==="ADA"){let{sendAdaTransaction:r}=await Promise.resolve().then(()=>(ds(),cs)),s=this.config.network==="mainnet"?"ada_mainnet":"ada_preprod",a=await r({address:e.address,to:e.txParams.to,amount:e.txParams.value||"0",isNativeToken:e.txParams.isNativeToken!==false,apiClient:this.client,chainId:s,policyId:e.txParams.tokenAddress,assetName:e.txParams.symbol,decimals:e.txParams.decimals});return {hash:a.hash,rawTransaction:a.hash}}if(e.chain==="XRP"){let{sendXrpTransaction:r}=await Promise.resolve().then(()=>(ms(),hs)),s=this.txService.rpcConfig.xrp,a=await r({address:e.address,to:e.txParams.to,amount:e.txParams.value||"0",isNativeToken:e.txParams.isNativeToken!==false,apiClient:this.client,rpcUrl:s,tokenAddress:e.txParams.tokenAddress,memo:e.txParams.memo,decimals:e.txParams.decimals});return {hash:a.hash,rawTransaction:a.hash}}if(e.chain==="TRON"){let{sendTronTransaction:r}=await Promise.resolve().then(()=>($a(),Ga)),s=this.config.network==="mainnet"?"mainnet":"testnet",a=await r({address:e.address,apiClient:this.client,to:e.txParams.to,amount:e.txParams.value||"0",network:s,isNativeToken:e.txParams.isNativeToken,tokenAddress:e.txParams.tokenAddress,decimals:e.txParams.decimals,memo:e.txParams.memo});return {hash:a.hash,rawTransaction:a.rawTransaction}}let t=await this.signTransaction(e);return {hash:(await this.txService.broadcastTransaction(e.chain,t)).txHash,rawTransaction:t.rawTransaction}}async estimateFee(e,t){return this.txService.getEstimatedFee(e,t)}async exportWallet(e,t){this.config.network==="mainnet";switch(e){case "EVM":return {privateKey:(await this.keyReconstructor.reconstructWithRetry(()=>this.keyReconstructor.reconstructEvmKey(t))).privateKey};case "SOL":{let r=await this.keyReconstructor.reconstructWithRetry(()=>this.keyReconstructor.reconstructSolanaKey(t));return {privateKey:buffer.Buffer.from(r.secretKey).toString("hex")}}case "TRON":return {privateKey:(await this.keyReconstructor.reconstructWithRetry(()=>this.keyReconstructor.reconstructTronKey(t))).privateKey};case "BTC":case "BTC_T3":{let r=e==="BTC",s=await this.keyReconstructor.reconstructWithRetry(()=>this.keyReconstructor.reconstructBtcKey(t,r));return {privateKey:buffer.Buffer.from(s.privateKeyBuffer).toString("hex")}}case "ADA":return {privateKey:(await this.keyReconstructor.reconstructWithRetry(()=>this.keyReconstructor.reconstructAdaKey(t))).privateKeyHex};case "XRP":return {privateKey:(await this.keyReconstructor.reconstructWithRetry(()=>this.keyReconstructor.reconstructXrpKey(t))).privateKey};default:throw new Error(`Unsupported chain type: ${e}`)}}};qe();Tr();qe();jn();Ar();var ja=async({address:c,apiKey:e,multisigParams:t,apiUrl:n})=>{let r;try{r=(await ot(c,e,n)).signer;}catch(s){if(s.message!=="KEY_MISMATCH")throw s;try{r=(await ot(c,e,n)).signer;}catch{throw new Error("Wallet key verification failed, even after forcing a share update. The account may be corrupted.")}}try{if(!t.rpcUrl.startsWith("https://"))throw new Error("Invalid or unsecure RPC URL provided.");let a;try{a=new web3_js.PublicKey(t.multisigPda);}catch{throw new Error("Invalid Multisig PDA format.")}let l;try{if(l=BigInt(t.index),l<0n)throw new Error("Transaction index cannot be negative.")}catch{throw new Error("Invalid transaction index format.")}let p=new web3_js.Connection(t.rpcUrl,"confirmed"),m=new web3_js.Transaction,g=ft__namespace.instructions.proposalApprove({member:r.publicKey,multisigPda:a,transactionIndex:l,memo:t.orderId});m.add(g),m.feePayer=r.publicKey;let T=(await p.getLatestBlockhash()).blockhash;m.recentBlockhash=T,m.partialSign(r);let y=m.serialize().toString("base64");return console.log("\u{1F680} ~ approve:",y),{tx:y}}catch(s){throw console.error("signSolanaMultisigOrder failed:",s),s}};$n();Ge();Q();var $e=jo(Ya());Q();async function Za({multisigPda:c,transactionIndex:e,rpcUrl:t,method:n,feePayerAddress:r}){let s=new web3_js.Connection(t,"confirmed"),a=new web3_js.PublicKey(c),l=BigInt(e),p=new web3_js.PublicKey(r),m=p,g=new web3_js.Transaction;if(n.toLowerCase()==="native".toLowerCase()){let y=await ft__namespace.instructions.vaultTransactionExecute({connection:s,multisigPda:a,transactionIndex:l,member:m});g.add(y.instruction);}else if(n.toLowerCase()!=="spl".toLowerCase()&&n.toLowerCase()!=="native".toLowerCase()){let y=ft__namespace.instructions.configTransactionExecute({multisigPda:a,transactionIndex:l,member:m,rentPayer:m});g.add(y);}else if(n.toLowerCase()==="spl".toLowerCase())try{let y=await ft__namespace.instructions.vaultTransactionExecute({connection:s,multisigPda:a,transactionIndex:l,member:m});g.add(y.instruction);}catch(y){throw console.error("buildUnsignedExecuteTx (SPL) failed to get instruction:",y),new Error(`SPL instruction building failed: ${y}`)}else throw new Error("Unsupported method type for execution");g.feePayer=p;let T=(await s.getLatestBlockhash("confirmed")).blockhash;return g.recentBlockhash=T,g}var Qa=c=>{let e=atob(c);return Uint8Array.from(e,t=>t.charCodeAt(0))};var Ll=5e3,Dl=1e-5,Ul=5e-6,no=.00203928,Wl=1378,Kl=.002,Wt=1e4,nr=2039280,qr=15e5,sr=400,Hl=300,Xl=(c,e)=>{let[t="0",n=""]=c.split("."),r=(n+"0".repeat(e)).slice(0,e),a=(t+(r||"0".repeat(e))).replace(/^0+(?=\d)/,"");return a===""?0n:BigInt(a)},Vl=async(c,e)=>{try{let t=await c.getAccountInfo(e);if(!t)throw new Error("Token mint account not found");return t.owner.equals(ao.TOKEN_2022_PROGRAM_ID)?ao.TOKEN_2022_PROGRAM_ID:ao.TOKEN_PROGRAM_ID}catch(t){return console.warn("Failed to detect token program, defaulting to TOKEN_PROGRAM_ID:",t),ao.TOKEN_PROGRAM_ID}},so=(c,e)=>ao.getAssociatedTokenAddressSync(e,c),jr=class{apiClient;keyReconstructor;isMainnet;rpcConfig;constructor(e,t,n){this.isMainnet=t,this.apiClient=e,this.keyReconstructor=new ee(e),this.rpcConfig=n;}getProvider(){return new web3_js.Connection(this.rpcConfig.solana,"confirmed")}async getBalance(e,t){let n=new web3_js.PublicKey(e);return (await t.getBalance(n)/web3_js.LAMPORTS_PER_SOL).toString()}getTransactionHash(e){if(typeof e=="string")return e;let t=e.signature?.toString("base64");if(!t)throw new Error("Missing signature in transaction.");return t}async broadcastTransaction(e,t){let n=buffer.Buffer.from(t,"base64"),r=await e.sendRawTransaction(n,{skipPreflight:false,preflightCommitment:"confirmed"}),{blockhash:s,lastValidBlockHeight:a}=await e.getLatestBlockhash();return await e.confirmTransaction({signature:r,blockhash:s,lastValidBlockHeight:a},"confirmed"),{hash:r}}async signOrder(e){let{orderId:t,wallet:n,multisigId:r}=e,s=this.getProvider(),a=await this.apiClient.get(`/sdk/order/params/sol/${t}`),{order:l,params:p}=a;if(!p?.multisigPda||!p?.transactionIndex)throw new Error("Missing Vault params from backend response");try{let{tx:m}=await ja({address:n.address,apiKey:this.apiClient.getApiKey(),multisigParams:{multisigPda:p.multisigPda,orderId:t,rpcUrl:s.rpcEndpoint,index:l.nonce},apiUrl:this.apiClient.getBaseUrl()});return {tx:m}}catch(m){console.error(m);let g=m?.response?.data?.message||m.message||"";throw g?.includes("insufficient funds")||g?.includes("does not have enough balance")?new Error("Transaction failed: insufficient SOL in wallet."):g?.includes("Proposal is stale")?new Error("Transaction failed: Vault can not be changed acording this transaction"):new Error(`Transaction failed: ${g}`)}}async createOrder(e){let{multisigId:t,wallet:n,method:r,instructions:s,selectedToken:a,threshold:l,orderToActivate:p}=e,m=this.getProvider(),g=new web3_js.PublicKey(n.address),T=await m.getBalance(g),y=r===Ve.native,A=r===Ve.spl,S;if(p?.order?.params?.chainType==="SOL"){let P=p.order.params.instructions[0];P.type===Ve.spl&&(S=P.tokenAddress);}let O=p?{...p.order.params?.token,address:S}:a,C=er(Kl.toString());if(T<Number(C))throw new Error("Insufficient SOL balance for transaction fees");if(y){if(!s[0].amount)throw new Error("Amount is not provided");let P=er(String(s[0].amount));if(P<1n)throw new Error("Amount is too small to transfer");if(T<Number(P))throw new Error("Insufficient SOL balance for transaction")}else if(A&&s[0].amount){if(!s[0].amount)throw new Error("Amount is not provided");if(!O||!O?.decimals)throw console.error("Decimals is not provided"),new Error("Decimals is not provided");if(Xl(String(s[0].amount),O.decimals)<1n)throw new Error("Amount is too small to transfer")}let x,R;if(p)x=p.params,R=p.order;else {let P=await this.apiClient.post("/sdk/order/create/sol",{multisigId:t,walletAddress:n.address,actions:s});x=P.params,R=P.order;}if(!x?.vaultAddress||!x?.multisigPda)throw new Error("Missing data from backend response");try{let P=s[0]?.memo,{tx:M}=await qn({address:n.address,apiKey:this.apiClient.getApiKey(),multisigPda:x.multisigPda,method:r,instructions:s,orderId:R.id,rpcUrl:m.rpcEndpoint,threshold:l,vaultAddress:x.vaultAddress,selectedToken:O,apiUrl:this.apiClient.getBaseUrl(),memo:P});return {order:(await this.apiClient.post("/sdk/order/activate/sol",{transaction:M,multisigId:t,orderId:R.id,walletAddress:n.address})).order,proposalHash:""}}catch(P){throw console.error(P),P}}async rejectOrder(e){let{orderId:t,wallet:n}=e,r=await this.keyReconstructor.reconstructWithRetry(()=>this.keyReconstructor.reconstructSolanaKey(n.address)),{keypair:s}=r,a=await this.apiClient.get(`/order/${t}`),{multisigPda:l,transactionIndex:p}=a.order.params||{};if(!l||!p)throw new Error("Order missing multisig parameters");let m=this.getProvider(),g=new web3_js.PublicKey(l),T=BigInt(p),y=new web3_js.Transaction,A=ft__namespace.instructions.proposalReject({member:s.publicKey,multisigPda:g,transactionIndex:T,memo:t});y.add(A),y.feePayer=s.publicKey;let S=(await m.getLatestBlockhash()).blockhash;y.recentBlockhash=S,y.partialSign(s);let O=y.serialize().toString("base64"),C=await this.apiClient.post("/sdk/order/reject/sol",{orderId:t,walletAddress:n.address,transaction:O});return {rejectionHash:O,order:C.order}}async executeTransaction(e){let{input:t,actualWallet:n,networkType:r}=e;if(!n)throw new Error("Wallet is not connected.");if(t.type===Ue.Send)return this.executeSolSend(t.data,n,r);throw new Error(`Transaction type ${t.type} not yet implemented for Solana`)}async executeSolSend(e,t,n){let r=await this.keyReconstructor.reconstructWithRetry(()=>this.keyReconstructor.reconstructSolanaKey(t.address)),{keypair:s}=r,a=this.getProvider(),{to:l,amount:p,isNativeToken:m,memo:g}=e;if(!m)throw new Error("SPL token transfers not yet implemented");let T=BigInt(Math.round(parseFloat(String(p))*web3_js.LAMPORTS_PER_SOL)),y=new web3_js.Transaction().add(web3_js.SystemProgram.transfer({fromPubkey:s.publicKey,toPubkey:new web3_js.PublicKey(l),lamports:T}));g&&y.add(splMemo.createMemoInstruction(g)),y.feePayer=s.publicKey;let{blockhash:A}=await a.getLatestBlockhash();y.recentBlockhash=A,y.sign(s);let S=y.serialize().toString("base64");return this.broadcastTransaction(a,S)}async estimateFee(e){let{input:t,actualWallet:n,chainId:r}=e;switch(t.type){case exports.TransactionEstimatingType.Send:return this.estimateSolanaRegularFee(t.data,n,r);case exports.TransactionEstimatingType.SignOrder:return this.estimateSolanaApprovalFee(t.data,n);case exports.TransactionEstimatingType.CreateOrder:return this.estimateSolanaCreateOrderFee(t.data,n,r);case exports.TransactionEstimatingType.ChangeMultisig:return this.estimateSolanaChangeMultisigFee(t.data,n,r);case exports.TransactionEstimatingType.ActivateMultisig:return this.estimateSolanaActivationFee(t.data,n.address);case exports.TransactionEstimatingType.ExecOrder:return this.estimateSolanaOrderExecuteFee(t.data,n,r);default:throw new Error(`Fee estimation not implemented for Solana type: ${t.type}`)}}async estimateSolanaRegularFee(e,t,n){let{to:r,amount:s,tokenAddress:a,isNativeToken:l=true,decimals:p=9}=e,m=this.getProvider(),g=new web3_js.PublicKey(t.address),T=new web3_js.PublicKey(r),y,A=0n;try{let{blockhash:O}=await m.getLatestBlockhash("confirmed"),C=[];if(l){let P=Math.ceil(Number(s)*web3_js.LAMPORTS_PER_SOL);if(P<=0)throw new Error("Amount must be greater than zero.");C.push(web3_js.SystemProgram.transfer({fromPubkey:g,toPubkey:T,lamports:BigInt(P)}));}else {if(!a)throw new Error("Token address is required for SPL token transfers.");let P=new web3_js.PublicKey(a),M=await Vl(m,P),_=await ao.getAssociatedTokenAddress(P,g,!1,M,ao.ASSOCIATED_TOKEN_PROGRAM_ID),B=await ao.getAssociatedTokenAddress(P,T,!1,M,ao.ASSOCIATED_TOKEN_PROGRAM_ID);if(!await m.getAccountInfo(B)){console.log("Recipient token account does not exist. Including creation fee in estimate.");try{let W=await m.getMinimumBalanceForRentExemption(165);A=BigInt(W);}catch(W){console.warn("Failed to get rent exemption, using fallback:",W),A=BigInt(Math.ceil(no*web3_js.LAMPORTS_PER_SOL));}C.push(ao.createAssociatedTokenAccountInstruction(g,B,T,P,M,ao.ASSOCIATED_TOKEN_PROGRAM_ID));}let G=BigInt(Math.round(Number(s)*Math.pow(10,p)));if(G<=0n)throw new Error("Token amount must be greater than zero.");M.equals(ao.TOKEN_2022_PROGRAM_ID)?C.push(ao.createTransferCheckedInstruction(_,P,B,g,G,p,[],M)):C.push(ao.createTransferInstruction(_,B,g,G,[],M));}let x=new web3_js.TransactionMessage({payerKey:g,recentBlockhash:O,instructions:C}).compileToLegacyMessage(),R=await m.getFeeForMessage(x,"confirmed");if(R.value===null)throw new Error("Fee calculation returned null.");y=BigInt(R.value);}catch(O){console.error("Fee estimation error:",O),y=BigInt(Math.ceil((l?Ul:Dl)*web3_js.LAMPORTS_PER_SOL)),!l&&A===0n&&(A=BigInt(Math.ceil(no*web3_js.LAMPORTS_PER_SOL)));}return {gasLimit:"N/A",gasPrice:"N/A",estimatedFee:(Number(y+A)/web3_js.LAMPORTS_PER_SOL).toString(),...A>0n&&{metadata:{transactionFee:(Number(y)/web3_js.LAMPORTS_PER_SOL).toString(),accountCreationFee:(Number(A)/web3_js.LAMPORTS_PER_SOL).toString(),needsAccountCreation:true}}}}async estimateSolanaApprovalFee(e,t){try{let n=await this.apiClient.get(`/sdk/order/params/sol/${e.order.id}`),{order:r,params:s}=n;if(!s?.multisigPda||!s?.transactionIndex)throw new Error("Missing Vault params from backend response");let a=this.getProvider(),l=new web3_js.PublicKey(s.multisigPda),p=BigInt(r.nonce),m=new web3_js.PublicKey(t.address),g=await ft__namespace.instructions.proposalApprove({multisigPda:l,transactionIndex:p,member:m}),T=new web3_js.Transaction().add(g);T.feePayer=m;let y=await a.getLatestBlockhash("confirmed");T.recentBlockhash=y.blockhash;let A=await a.getFeeForMessage(T.compileMessage(),"confirmed");if(!A.value)throw new Error("Solana network failed to return a fee estimate for approval (fee value is null).");let S=A.value,O=S/web3_js.LAMPORTS_PER_SOL;return {gasLimit:String(T.serializeMessage().length),gasPrice:String(S),estimatedFee:String(O),nativeFeeLamports:S}}catch(n){throw console.error("Failed client-side Solana approval fee estimation:",n),new Error(n.message||"Failed to estimate approval transaction fee on Solana.")}}async estimateSolanaCreateOrderFee(e,t,n){let r={gasLimit:String(sr),gasPrice:String(Wt+nr+qr),estimatedFee:String((Wt+nr+qr)/web3_js.LAMPORTS_PER_SOL),nativeFeeLamports:Wt+nr+qr};try{let s=this.getProvider(),a=new web3_js.PublicKey(t.address),l=new web3_js.PublicKey(e.multisig.address),p=new web3_js.PublicKey(e.to),m=e.amount,g=e.tokenDecimals,T=Wt,y=nr,A=qr,S=sr,O;if(e.method===Ve.native||!e.tokenAddress){let X=new $e.BN(new $e.BN(m.split(".")[0]||0).mul(new $e.BN(web3_js.LAMPORTS_PER_SOL)).add(new $e.BN(m.split(".")[1]||0).mul(new $e.BN(web3_js.LAMPORTS_PER_SOL).div(new $e.BN(Math.pow(10,(m.split(".")[1]||"").length)))))).toNumber();O=web3_js.SystemProgram.transfer({fromPubkey:l,toPubkey:p,lamports:X});}else if(e.method===Ve.spl&&e.tokenAddress){let X=new web3_js.PublicKey(e.tokenAddress),E=so(l,X),i=so(p,X),[d,u]=m.split("."),h=new $e.BN(10).pow(new $e.BN(g)),w=new $e.BN(0);if(d&&(w=w.add(new $e.BN(d).mul(h))),u){let I=u.padEnd(g,"0");w=w.add(new $e.BN(I).mul(h).div(new $e.BN(10).pow(new $e.BN(g))));}O=ao__namespace.createTransferCheckedInstruction(E,X,i,l,w.toNumber(),g);}else return console.error(`estimateSolanaCreateOrderFee: Unsupported instruction type or missing token address: ${e.method}`),r;let C=BigInt(0),x=await s.getLatestBlockhash("confirmed"),R=new web3_js.TransactionMessage({payerKey:l,recentBlockhash:x.blockhash,instructions:[O]}),P=ft__namespace.instructions.vaultTransactionCreate({multisigPda:l,transactionIndex:C,creator:a,rentPayer:a,vaultIndex:0,ephemeralSigners:0,transactionMessage:R}),M=ft__namespace.instructions.proposalCreate({multisigPda:l,creator:a,transactionIndex:C,rentPayer:a}),_=new web3_js.Transaction().add(P).add(M);_.feePayer=a,_.recentBlockhash=x.blockhash;let B=await s.getFeeForMessage(_.compileMessage(),"confirmed");B.value!==null?T=B.value:(console.warn("estimateSolanaCreateOrderFee: Fee calculation returned null, using fallback"),T=Wt);let U=O.data.length,G=sr+U,W=Hl+U;y=await s.getMinimumBalanceForRentExemption(G),A=await s.getMinimumBalanceForRentExemption(W),S=_.serializeMessage().length;let k=T+y+A,N=k/web3_js.LAMPORTS_PER_SOL;return {gasLimit:String(S),gasPrice:String(k),estimatedFee:String(N),nativeFeeLamports:k}}catch(s){return console.error("estimateSolanaCreateOrderFee: Error during fee estimation:",s),r}}async estimateSolanaChangeMultisigFee(e,t,n){let r=this.getProvider(),s=new web3_js.PublicKey(t.address),a=Wt,l=nr,p=sr;if(!e.multisig.address)throw new Error("Multisig address is required for fee estimation.");let m=new web3_js.PublicKey(e.multisig.address),g=m,T=s,y=255,A=e.newOwners.map(k=>new web3_js.PublicKey(k)),S=e.multisig.owners.map(k=>new web3_js.PublicKey(k.walletAddress)),O=[],C=A.filter(k=>!S.some(N=>N.equals(k))),x=S.filter(k=>!A.some(N=>N.equals(k)));for(let k of C){let N={key:k,permissions:y};O.push(ft__namespace.instructions.multisigAddMember({multisigPda:m,configAuthority:g,rentPayer:T,newMember:N}));}for(let k of x)O.push(ft__namespace.instructions.multisigRemoveMember({multisigPda:m,configAuthority:g,oldMember:k}));let R=Number(e.multisig.threshold);if(e.newThreshold!==R&&O.push(ft__namespace.instructions.multisigChangeThreshold({multisigPda:m,configAuthority:g,rentPayer:T,newThreshold:e.newThreshold})),O.length===0)throw new Error("No changes detected. Fee estimation requires changes in owners or threshold.");let P=BigInt(0),M=await ft__namespace.instructions.proposalCreate({multisigPda:m,creator:s,transactionIndex:P,rentPayer:T}),_=new web3_js.Transaction().add(M);_.feePayer=s;let B=O.reduce((k,N)=>k+N.data.length,0),U=sr+B;try{let k=await r.getLatestBlockhash("confirmed");_.recentBlockhash=k.blockhash;let N=await r.getFeeForMessage(_.compileMessage(),"confirmed");if(N.value!==null)a=N.value;else throw new Error("Fee calculation returned null.");l=await r.getMinimumBalanceForRentExemption(U),p=_.serializeMessage().length;}catch(k){console.error("Failed Solana network estimation, using fallbacks:",k);}let G=a+l,W=G/web3_js.LAMPORTS_PER_SOL;return {gasLimit:String(p),gasPrice:String(G),estimatedFee:String(W),nativeFeeLamports:G}}async estimateSolanaActivationFee(e,t){let n=Ll,r=0,s=0;try{let m=(await this.apiClient.post("/sdk/multisig/sol/tx/deploy",{walletAddress:t,multisigId:e.multisig.id})).transaction,g=this.getProvider(),T=web3_js.Transaction.from(Qa(m));s=T.serializeMessage().length;let y=await g.getLatestBlockhash("confirmed");T.recentBlockhash=y.blockhash;let A=await g.getFeeForMessage(T.compileMessage(),"confirmed");if(A.value===null)throw new Error("Solana network returned a null fee estimate.");n=A.value,r=await g.getMinimumBalanceForRentExemption(Wl,"confirmed");}catch(p){console.error("Failed network-side Solana fee estimation, using fallback fee:",p),r=23e5;}let a=n+r,l=a/web3_js.LAMPORTS_PER_SOL;return {gasLimit:String(s),gasPrice:String(n),estimatedFee:String(l),nativeFeeLamports:a}}async estimateSolanaOrderExecuteFee(e,t,n){try{let r=await this.apiClient.get(`/sdk/order/params/sol/${e.order.id}`),{params:s,order:a}=r;if(!s?.multisigPda||!s?.transactionIndex)throw new Error("Missing Vault params from backend response");let l=this.getProvider(),p=await Za({multisigPda:s.multisigPda,transactionIndex:a.nonce.toString(),rpcUrl:l.rpcEndpoint,method:a.method||"native",feePayerAddress:t.address}),m=await l.getFeeForMessage(p.compileMessage(),"confirmed");if(!m.value)throw new Error("Solana network failed to return a fee estimate (fee value is null).");let g=m.value,T=g/web3_js.LAMPORTS_PER_SOL;return {gasLimit:String(p.serializeMessage().length),gasPrice:String(g),estimatedFee:String(T),nativeFeeLamports:g}}catch(r){throw console.error("Failed client-side Solana order execution fee estimation:",r),new Error(r.message||"Failed to estimate order execution transaction fee on Solana.")}}};qe();Ge();var Eo=1e6,su=new elliptic.ec("secp256k1");function iu(c,e){let t=buffer.Buffer.from(Ao__namespace.sha256().update(c).digest()),r=su.keyFromPrivate(e,"hex").sign(t,{canonical:true}),s=r.r.toArrayLike(buffer.Buffer,"be",32),a=r.s.toArrayLike(buffer.Buffer,"be",32),l=buffer.Buffer.from([r.recoveryParam]);return buffer.Buffer.concat([s,a,l]).toString("hex")}var Jr=class{apiClient;keyReconstructor;isMainnet;rpcConfig;constructor(e,t=false,n){this.apiClient=e,this.keyReconstructor=new ee(e,t?"mainnet":"testnet"),this.isMainnet=t,this.rpcConfig=n;}getProvider(){return new tronweb.TronWeb({fullHost:this.rpcConfig.tron})}async getBalance(e,t){let n=await t.trx.getBalance(e);return (Number(n)/Eo).toString()}async signOrder(e){let{order:t,wallet:n}=e;if(!t)throw new Error("Order data is missing.");let r=await this.apiClient.get(`/sdk/order/tx/tron/${t.id}`),{transaction:s,version:a,order:l}=r;if(!s)throw new Error("No transaction found in the response.");let p=await this.keyReconstructor.reconstructWithRetry(()=>this.keyReconstructor.reconstructTronKey(n.address)),{privateKey:m}=p,g=this.getProvider(),T=(t.method||"").toLowerCase(),y=T!=="native"&&T!=="trc",A;y?A=await this.signMultisigTxManually(g,s,m):A=await g.trx.multiSign(s,m,2);let S=A.signature[A.signature.length-1];if(!S)throw new Error("Failed to extract signature from signed transaction.");return {tx:S,version:a}}async signMultisigTxManually(e,t,n){let r=JSON.parse(JSON.stringify(t)),s=e.utils.transaction.txJsonToPb(r),a=s.getRawData().serializeBinary(),l=iu(a,n);return r.signature||(r.signature=[]),r.signature.push(l),r.txID=e.utils.transaction.txPbToTxID(s),r.raw_data_hex=buffer.Buffer.from(a).toString("hex"),r}async createOrder(e){let{multisigId:t,wallet:n,method:r,instructions:s}=e,a=r==="native"||r==="trc"?[{amount:s[0]?.amount,to:s[0]?.toPubkey,type:s[0]?.type,tokenAddress:s[0]?.tokenAddress,memo:s[0]?.memo}]:s,l=await this.apiClient.post("/sdk/order/create/tron",{multisigId:t,walletAddress:n.address,actions:a});return {order:l.order,proposalHash:l.order.hashToSing||""}}async rejectOrder(e){let{orderId:t,multisigId:n,wallet:r}=e;if(!n)throw new Error("Vault id missing");return {rejectionHash:"",order:(await this.apiClient.post("/sdk/order/reject/tron",{orderId:t,multisigId:n,walletAddress:r.address})).order}}async executeTransaction(e){let{input:t,actualWallet:n}=e;if(!n)throw new Error("Wallet is not connected.");if(t.type===Ue.Send)return this.executeTronSend(t.data,n);if(t.type===Ue.ExecOrder){let{order:r}=t.data;return this.executeTronOrder(r,n)}throw new Error(`Transaction type ${t.type} not yet implemented for Tron`)}async executeTronSend(e,t){let n=await this.keyReconstructor.reconstructWithRetry(()=>this.keyReconstructor.reconstructTronKey(t.address)),{privateKey:r}=n,s=this.getProvider(),{to:a,amount:l,isNativeToken:p,tokenAddress:m,decimals:g,memo:T}=e,y;if(p){let O=Math.round(Number(l)*Eo);y=await s.transactionBuilder.sendTrx(a,O,t.address),T&&(y=await s.transactionBuilder.addUpdateData(y,T,"utf8"));}else {if(!m)throw new Error("Token address is required for TRC20 transfers.");if(g===void 0)throw new Error("Token decimals are required for TRC20 transfers.");let O=Math.round(Number(l)*Math.pow(10,g)),C=[{type:"address",value:a},{type:"uint256",value:O.toString()}],x={feeLimit:1e8,callValue:0};y=(await s.transactionBuilder.triggerSmartContract(m,"transfer(address,uint256)",x,C,t.address)).transaction,T&&(y=await s.transactionBuilder.addUpdateData(y,T,"utf8"));}let A=await s.trx.sign(y,r),S=await s.trx.sendRawTransaction(A);if(S.result===false||S.code)throw new Error(S.message||"Transaction failed");return {hash:S.txid}}async executeTronOrder(e,t){return {order:(await this.apiClient.patch("/sdk/order/execute/tron",{orderId:e.id,walletAddress:t.address})).order}}async estimateFee(e){let{input:t,actualWallet:n,chainId:r}=e,s=this.getProvider();switch(t.type){case exports.TransactionEstimatingType.Send:let{estimateTronRegularFee:a}=await Promise.resolve().then(()=>(ho(),po));return a({input:{data:t.data},activeWallet:n,tronWeb:s});case exports.TransactionEstimatingType.ExecOrder:let{estimateOrderExecutionFee:l}=await Promise.resolve().then(()=>(wo(),yo));return l(t.data.order,t.data.multisigAddress,s,this.isMainnet);case exports.TransactionEstimatingType.ActivateMultisig:let{estimateTronMultisigActivationFee:p}=await Promise.resolve().then(()=>(vo(),To));return p({multisig:t.data.multisig,tronWeb:s});case exports.TransactionEstimatingType.CreateOrder:case exports.TransactionEstimatingType.SignOrder:case exports.TransactionEstimatingType.ChangeMultisig:return console.log(`Method ${t.type} does not require fee on Tron`),{estimatedFee:"0",gasLimit:"0",gasPrice:"0",currency:"TRX"};default:throw new Error(`Fee estimation not implemented for Tron type: ${t.type}`)}}};qe();tr();tr();cc__default.default(dc__namespace);async function xo(c,e){try{let t=await fetch(`${e}/address/${c}/utxo`);if(!t.ok)throw new Error(`Failed to fetch UTXOs: ${t.statusText}`);return t.json()}catch(t){throw console.error("Error fetching UTXOs:",t),new Error("Failed to fetch UTXOs.")}}var bo=148,Io=34,So=10,Oo=2,Co=1e8,Po=20,du=1.1;async function lu(c){try{let e=await fetch(`${c}/v1/fees/recommended`);if(!e.ok)throw new Error("Failed to fetch fee rates");return (await e.json()).halfHourFee||Po}catch(e){return console.error("Error fetching fee rate:",e),Po}}var Ro=async({input:c,activeWallet:e,rpcUrl:t})=>{let n=c.currentFeeRateSatVB||await lu(t),r=1;try{let m=await xo(e.address,t);if(m.length>0){let g=Math.round(Number(c.data.amount)*Co),T=[...m].sort((A,S)=>S.value-A.value),y=0;r=0;for(let A of T){r++,y+=A.value;let S=r*bo+Oo*Io+So,O=Math.ceil(n*S);if(y>=g+O)break}r===0&&(r=1);}}catch(m){console.error("Error fetching UTXOs for fee estimation:",m),r=1;}let s=r*bo+Oo*Io+So,a=Math.ceil(s*n),p=Math.ceil(a*du)/Co;return {gasLimit:s.toFixed(2),gasPrice:n.toString(),estimatedFee:p.toFixed(8)}};Ge();Q();var uu=57.5,pu=10,hu=31;var vs=1e8,mu=20,ir=class{apiClient;keyReconstructor;isMainnet;rpcConfig;constructor(e,t=false,n){this.apiClient=e,this.keyReconstructor=new ee(e),this.isMainnet=t,this.rpcConfig=n;}getProvider(){}getMempoolApiUrl(){return this.rpcConfig.btc}detectScriptType(e){return e.startsWith("1")?"p2pkh":e.startsWith("3")||e.startsWith("2")?"p2sh":e.startsWith("bc1q")||e.startsWith("tb1q")?"p2wpkh":e.startsWith("bc1p")||e.startsWith("tb1p")?"p2tr":"p2wpkh"}async getBalance(e){let n=await(await fetch(`${this.getMempoolApiUrl()}/address/${e}`)).json();return ((n.chain_stats.funded_txo_sum-n.chain_stats.spent_txo_sum)/vs).toString()}async signOrder(e){let{wallet:t,order:n}=e;if(!t)throw new Error("Wallet address missing");if(!n)throw new Error("There is no order");if(!n?.data)throw new Error("Order missing PSBT data");if(!n?.to)throw new Error("Order missing recipient address");if(!n?.value)throw new Error("Order missing value");if(!n.params||n.params.chainType!=="BTC"&&n.params.chainType!=="BTC_T3")throw new Error("Invalid chain params for BTC");if(!n.params.feeSats)throw new Error("Order missing fee");let r=await this.keyReconstructor.reconstructWithRetry(()=>this.keyReconstructor.reconstructBtcKey(t.address,this.isMainnet)),{privateKeyWif:s}=r,a=n.data,l=await import('bitcoinjs-lib'),p=await import('tiny-secp256k1'),{ECPairFactory:m}=await import('ecpair');m(p);let T=this.isMainnet?l.networks.bitcoin:l.networks.testnet,y;try{y=l.Psbt.fromBase64(a,{network:T});}catch(R){throw console.error("PSBT parsing failed:",R),new Error("Invalid PSBT format or Base64 encoding.")}let A=Math.round(parseFloat(n?.value)*vs),S=false;for(let R of y.txOutputs)if(l.address.fromOutputScript(R.script,T)===n.to&&Number(R.value)===A){S=true;break}if(!S)throw console.error(`PSBT Output verification failed. Expected TO: ${n.to}, Value: ${n.value} BTC`),new Error("Transaction outputs do not match expected recipient or amount.");if(!n.params||n.params.chainType!=="BTC"&&n.params.chainType!=="BTC_T3")throw new Error("Invalid chain params for BTC");let O=parseInt(n.params.feeSats,10);if(O>1e4||O<=0)throw console.error(`Fee sanity check failed. Received fee: ${O} sats.`),new Error("Transaction fee is outside the allowed range.");return {tx:await this.signBtcBase64TX(a,s,T)}}async signBtcBase64TX(e,t,n){let r=await import('bitcoinjs-lib'),{ECPairFactory:s}=await import('ecpair'),a=await import('tiny-secp256k1'),l=s(a),p=r.Psbt.fromBase64(e,{network:n}),m=l.fromWIF(t,n),g={publicKey:buffer.Buffer.from(m.publicKey),sign:T=>buffer.Buffer.from(m.sign(T))};return p.data.inputs.forEach((T,y)=>{try{p.signInput(y,g);}catch(A){console.warn(`Cannot sign input #${y}:`,A);}}),p.toBase64()}async createOrder(e){let{multisigId:t,wallet:n,instructions:r}=e,s=await this.apiClient.post("/sdk/order/create/btc",{multisigId:t,walletAddress:n.address,instructions:{amount:r[0]?.amount,to:r[0]?.toPubkey,type:r[0]?.type}});return {order:s.order,proposalHash:s.order.hashToSing||""}}async rejectOrder(e){let{orderId:t,multisigId:n,wallet:r}=e;if(!n)throw new Error("Vault id missing");return {rejectionHash:"",order:(await this.apiClient.post("/sdk/order/reject/btc",{orderId:t,multisigId:n,walletAddress:r.address})).order}}async executeTransaction(e){let{input:t,actualWallet:n}=e;if(!n?.address||!n.share)throw new Error("Wallet not connected or share missing");if(t.type===Ue.Send)return this.executeBtcSend(t.data,n);if(t.type===Ue.ExecOrder){let{order:r}=t.data;return this.executeBtcOrder(r,n)}throw new Error("Unsupported transaction execution type")}async executeBtcSend(e,t){let{to:n,amount:r,utxos:s,estimatedFee:a}=e;if(!s||s.length===0)throw new Error("UTXOs required for BTC transaction");let l=await this.keyReconstructor.reconstructWithRetry(()=>this.keyReconstructor.reconstructBtcKey(t.address,this.isMainnet)),{privateKeyWif:p}=l,m=await import('bitcoinjs-lib'),g=await import('tiny-secp256k1'),{ECPairFactory:T}=await import('ecpair'),y=T(g),A=this.isMainnet?m.networks.bitcoin:m.networks.testnet,S=y.fromWIF(p,A),O=BigInt(Math.round(parseFloat(String(r))*vs)),C=a?.feeRate||mu,x=new m.Psbt({network:A}),R=0n;for(let k of s){let N={hash:k.txid,index:k.vout},X=k.scriptType||this.detectScriptType(t.address);if(X==="p2pkh")k.nonWitnessUtxo?N.nonWitnessUtxo=buffer.Buffer.from(k.nonWitnessUtxo,"hex"):N.witnessUtxo={script:k.script?buffer.Buffer.from(k.script,"hex"):m.address.toOutputScript(t.address,A),value:k.value};else if(X==="p2sh"){let E=buffer.Buffer.from(S.publicKey),i=m.payments.p2wpkh({pubkey:E,network:A}),d=m.payments.p2sh({redeem:i,network:A});N.witnessUtxo={script:d.output,value:k.value},N.redeemScript=i.output;}else N.witnessUtxo={script:k.script?buffer.Buffer.from(k.script,"hex"):m.address.toOutputScript(t.address,A),value:k.value};Et(x,N),R+=BigInt(k.value);}tt(x,{address:n,value:O});let P=pu+s.length*uu+2*hu,M=BigInt(Math.ceil(P*C)),_=R-O-M,B=546n;if(_<0n)throw new Error("Insufficient funds to cover amount and fee.");if(_>0n&&_<B)throw new Error("Change amount is below the dust limit.");_>0n&&tt(x,{address:t.address,value:_});let U=buffer.Buffer.from(S.publicKey);for(let k=0;k<s.length;k++)x.signInput(k,{publicKey:U,sign:N=>buffer.Buffer.from(S.sign(N))});x.finalizeAllInputs();let G=x.extractTransaction().toHex();return {hash:await this.broadcastBtcTransaction(G)}}async executeBtcOrder(e,t){return {order:(await this.apiClient.patch("/sdk/order/execute/btc",{orderId:e.id,walletAddress:t.address})).order}}async broadcastBtcTransaction(e){let t=await fetch(`${this.getMempoolApiUrl()}/tx`,{method:"POST",body:e});if(!t.ok){let n=await t.text();throw new Error(`Failed to broadcast BTC transaction: ${n}`)}return await t.text()}async estimateFee(e){let{input:t,actualWallet:n}=e;if(t.type===exports.TransactionEstimatingType.Send)return Ro({input:{data:t.data},activeWallet:n,rpcUrl:this.getMempoolApiUrl()});throw new Error(`Fee estimation not implemented for type: ${t.type}`)}};qe();Ge();var en=class{apiClient;keyReconstructor;isMainnet;constructor(e,t,n){this.apiClient=e,this.keyReconstructor=new ee(e),this.isMainnet=t;}getProvider(){}async signOrder(e){let{wallet:t,order:n,orderId:r,multisigId:s}=e;if(!t)throw new Error("Wallet is required for ADA signOrder");let a=n?.hashToSing||n?.hashToSign;if(!a)throw new Error("Order hash to sign is missing");let{signAdaMultisigOrder:l}=await Promise.resolve().then(()=>(Qn(),Zn));return {tx:(await l({address:t.address,hashToSign:a,orderId:r,multisigId:s,apiClient:this.apiClient})).witnessHex}}async createOrder(e){let{multisigId:t,wallet:n,instructions:r}=e;if(!n)throw new Error("Wallet is required for ADA createOrder");let s=r[0]||{},a={amount:s.amount||s.value,to:s.to||s.toPubkey,type:s.type||"native"};s.tokenAddress&&s.tokenAddress!=="0x0000000000000000000000000000000000000000"&&(a.policyId=s.tokenAddress,a.assetName=s.assetName,a.type="token");let l=await this.apiClient.post("/sdk/order/create/ada",{multisigId:t,walletAddress:n.address,instructions:a});return {order:l.order,proposalHash:l.order.hashToSing||""}}async rejectOrder(e){let{orderId:t,wallet:n,multisigId:r}=e;if(!n)throw new Error("Wallet is required for ADA rejectOrder");return {rejectionHash:"",order:(await this.apiClient.post("/sdk/order/reject/ada",{orderId:t,multisigId:r,walletAddress:n.address})).order}}async executeTransaction(e){let{input:t,actualWallet:n,chainId:r}=e;if(t.type===Ue.Send){let s=t.data;if(!n)throw new Error("Wallet is required for ADA send");let{sendAdaTransaction:a}=await Promise.resolve().then(()=>(ds(),cs)),l=s.isNativeToken!==false;return a({address:n.address,to:s.to,amount:s.amount,isNativeToken:l,apiClient:this.apiClient,chainId:r,policyId:s.policyId,assetName:s.assetName,decimals:s.decimals})}if(t.type===Ue.ExecOrder){let s=t.data;if(!n)throw new Error("Wallet is required for ADA execOrder");return {order:(await this.apiClient.patch("/sdk/order/execute/ada",{orderId:s.order.id,multisigId:s.multisigId,walletAddress:n.address})).order}}throw new Error(`Unsupported ADA transaction type: ${t.type}`)}async estimateFee(e){let{input:t,actualWallet:n,chainId:r}=e;if(t.type===exports.TransactionEstimatingType.Send){let s=t.data,{estimateAdaNativeFee:a}=await Promise.resolve().then(()=>(ko(),Mo));return a({address:n.address,amount:s.amount,isNativeToken:s.isNativeToken!==false,apiClient:this.apiClient,chainId:r})}if(t.type===exports.TransactionEstimatingType.CreateOrder){let s=t.data,{estimateAdaOrderCreationFee:a}=await Promise.resolve().then(()=>(Bo(),_o));return a({amount:s.amount,tokenAddress:s.tokenAddress,multisig:s.multisig,apiClient:this.apiClient,chainId:r})}return {gasLimit:"500",gasPrice:"44",estimatedFee:"0.200000"}}};qe();Ge();Q();st();var tn=class{apiClient;keyReconstructor;isMainnet;rpcUrl;constructor(e,t,n){this.apiClient=e,this.keyReconstructor=new ee(e),this.isMainnet=t,this.rpcUrl=n.xrp;}getProvider(){return new Wr__namespace.Client(this.rpcUrl)}async getBalance(e){let t=new Wr__namespace.Client(this.rpcUrl);try{await t.connect();let r=(await t.request({command:"account_info",account:e,ledger_index:"validated"})).result.account_data.Balance;return Wr__namespace.dropsToXrp(r).toString()}catch(n){if(n?.data?.error==="actNotFound"||n?.message?.includes("actNotFound"))return "0";throw n}finally{await t.disconnect();}}async signOrder(e){let{wallet:t,orderId:n,multisigId:r}=e;if(!t)throw new Error("Wallet is required for XRP signOrder");let{signXrpMultisigOrder:s}=await Promise.resolve().then(()=>(Yn(),zn)),a=await s({address:t.address,orderId:n,multisigId:r,apiClient:this.apiClient});return {tx:a.signature,version:a.version.toString()}}async createOrder(e){let{multisigId:t,wallet:n,instructions:r}=e;if(!n)throw new Error("Wallet is required for XRP createOrder");let s=r[0]||{},a=e.method?String(e.method):"",l=s.type?String(s.type):"",p=a||l||"native";p==="trc"&&(p="asset");let m=p,g;switch(m){case "native":{let y=s.to||s.toPubkey;if(y&&!Kr(y))throw new Error(`Invalid recipient address: ${y}`);if(s.amount&&!Hr(s.amount))throw new Error(`Invalid amount: ${s.amount}`);g=[{type:"native",to:y,amount:s.amount,memo:s.memo}];break}case "asset":{let y=s.to||s.toPubkey;if(y&&!Kr(y))throw new Error(`Invalid recipient address: ${y}`);if(s.amount&&!Hr(s.amount))throw new Error(`Invalid amount: ${s.amount}`);if(!s.tokenAddress)throw new Error(`Invalid token address: ${s.tokenAddress}`);let[A="",S=""]=s.tokenAddress.indexOf(".")?s.tokenAddress.split("."):[s.tokenAddress,s.issuer];g=[{type:"asset",to:y,amount:s.amount,tokenAddress:A,issuer:S,memo:s.memo}];break}case "setTrustLine":g=[{type:"setTrustLine",tokenAddress:s.tokenAddress,issuer:s.issuer,limit:s.limit||"1000000000"}];break;case "removeTrustLine":g=[{type:"removeTrustLine",currency:s.currency||s.tokenAddress,issuer:s.issuer}];break;case "changeThreshold":g=[{type:"changeThreshold",newThreshold:s.newThreshold}];break;case "updateOwners":{let y=s.newOwners||s.owners;if(y&&y.length>8)throw new Error("XRP multisig supports maximum 8 signers");g=[{type:"updateOwners",owners:y}];break}case "updateOwnerThreshold":{let y=s.newOwners||s.owners;if(y&&y.length>8)throw new Error("XRP multisig supports maximum 8 signers");g=[{type:"updateOwnerThreshold",owners:y,newThreshold:s.newThreshold}];break}default:throw new Error(`Unsupported XRP order type: ${m}`)}let T=await this.apiClient.post("/sdk/order/create/xrp",{multisigId:t,walletAddress:n.address,actions:g});return {order:T.order,proposalHash:T.hashToSign||T.order.hashToSing||""}}async rejectOrder(e){let{orderId:t,wallet:n,multisigId:r}=e;if(!n)throw new Error("Wallet is required for XRP rejectOrder");let s=await this.apiClient.post("/sdk/order/reject/xrp",{orderId:t,multisigId:r,walletAddress:n.address});return {rejectionHash:s.rejectionHash||t,order:s.order}}async executeTransaction(e){let{input:t,actualWallet:n,chainId:r}=e;if(t.type===Ue.Send){let s=t.data;if(!n)throw new Error("Wallet is required for XRP send");let{sendXrpTransaction:a}=await Promise.resolve().then(()=>(ms(),hs)),l=s.isNativeToken!==false;return a({address:n.address,to:s.to,amount:s.amount.toString(),isNativeToken:l,apiClient:this.apiClient,rpcUrl:this.rpcUrl,tokenAddress:s.tokenAddress,memo:s.memo,decimals:s.decimals})}if(t.type===Ue.ExecOrder){let s=t.data;if(!n)throw new Error("Wallet is required for XRP execOrder");let a=await this.apiClient.patch("/sdk/order/execute/xrp",{orderId:s.order.id,multisigId:s.multisigId,walletAddress:n.address});return {order:a.order,txHash:a.txHash}}if(t.type===Ue.ActivateMultisig){let s=t.data;if(!n)throw new Error("Wallet is required for XRP activateMultisig");let a=s.multisig,l=(a.owners||[]).map(T=>({address:T.walletAddress||T.address,weight:1})),p=parseInt(a.threshold||"1",10),m=n.share,{activateXrpMultisig:g}=await Promise.resolve().then(()=>(Vn(),Xn));return await g({multisigId:a.id,multisigAddress:a.address||"",walletAddress:n.address,signers:l,threshold:p,apiClient:this.apiClient,rpcUrl:this.rpcUrl,deviceShare:m}),{success:true}}if(t.type===Ue.ActivateTrustLine){let s=t.data;if(!n)throw new Error("Wallet is required for XRP activateTrustLine");let{activateTrustLine:a}=await Promise.resolve().then(()=>(Lo(),Fo));return a({address:n.address,currency:s.currency,issuer:s.issuer,limit:s.limit,apiClient:this.apiClient,rpcUrl:this.rpcUrl})}throw new Error(`Unsupported XRP transaction type: ${t.type}`)}async estimateFee(e){let{input:t}=e;if(t.type===exports.TransactionEstimatingType.Send)if(t.data.isNativeToken!==false){let{estimateXrpNativeFee:s}=await Promise.resolve().then(()=>(xs(),As));return s(1)}else {let{estimateXrpAssetFee:s}=await Promise.resolve().then(()=>(Is(),bs));return s(1)}if(t.type===exports.TransactionEstimatingType.CreateOrder)return {gasLimit:"0",gasPrice:"0",estimatedFee:"0",currency:"XRP"};if(t.type===exports.TransactionEstimatingType.ActivateMultisig){let{estimateXrpMultisigConfigFee:n}=await Promise.resolve().then(()=>(Os(),Ss)),r=t.data.multisig?.owners?.length||1;return n(r,"activate")}if(t.type===exports.TransactionEstimatingType.ExecOrder){let n=t.data.order,r=n?.params?.instructions?.type||n?.actions?.[0]?.type||"native",s=n?.multisig?.owners?.length||2;if(r==="setTrustLine"||r==="removeTrustLine"){let{estimateXrpTrustLineFee:l}=await Promise.resolve().then(()=>(Uo(),Do));return l(s)}if(r==="changeThreshold"||r==="updateOwners"||r==="updateOwnerThreshold"){let{estimateXrpMultisigConfigFee:l}=await Promise.resolve().then(()=>(Os(),Ss));return l(s,r)}if(r==="asset"){let{estimateXrpAssetFee:l}=await Promise.resolve().then(()=>(Is(),bs));return l(s)}let{estimateXrpNativeFee:a}=await Promise.resolve().then(()=>(xs(),As));return a(s)}return {gasLimit:"1",gasPrice:"14",estimatedFee:"0.000014",currency:"XRP"}}};Ge();Q();var xu=[{name:"Ethereum",type:J.EVM,mainnetId:"1",testnetId:"11155111",mainnetAliases:["ethereum","eth","evm"],testnetAliases:["sepolia"]},{name:"Polygon",type:J.EVM,mainnetId:"137",testnetId:"80002",mainnetAliases:["polygon","matic"],testnetAliases:["pol-test"]},{name:"Base",type:J.EVM,mainnetId:"8453",testnetId:"84532",mainnetAliases:["base"],testnetAliases:["base-sepolia"]},{name:"Arbitrum",type:J.EVM,mainnetId:"42161",testnetId:"421614",mainnetAliases:["arbitrum","arb"],testnetAliases:["arb-sepolia"]},{name:"Optimism",type:J.EVM,mainnetId:"10",testnetId:"11155420",mainnetAliases:["optimism","op"],testnetAliases:["op-sepolia"]},{name:"BNB",type:J.EVM,mainnetId:"56",testnetId:"97",mainnetAliases:["bsc","bnb"],testnetAliases:["bnb-test"]},{name:"Avalanche",type:J.EVM,mainnetId:"43114",testnetId:"43113",mainnetAliases:["avalanche","avax"],testnetAliases:["avax-fuji","fuji"]},{name:"Solana",type:J.SOL,mainnetId:"sol_mainnet",testnetId:"sol_devnet",mainnetAliases:["solana","sol","mainnet-beta"],testnetAliases:["solana-devnet","devnet"]},{name:"Tron",type:J.TRON,mainnetId:"tron_mainnet",testnetId:"tron_shasta",mainnetAliases:["tron","trx","tron-mainnet"],testnetAliases:["shasta","tron-shasta"]},{name:"Bitcoin",type:J.BTC,mainnetId:"BTC",testnetId:"BTC_T3",mainnetAliases:["bitcoin","btc","btc-mainnet"],testnetAliases:["bitcoin_testnet","btc_testnet","btc_t3","testnet"]},{name:"Cardano",type:J.ADA,mainnetId:"ada_mainnet",testnetId:"ada_preprod",mainnetAliases:["cardano","ada","ada-mainnet"],testnetAliases:["ada-preprod","preprod"]},{name:"XRP",type:J.XRP,mainnetId:"xrp_mainnet",testnetId:"xrp_testnet",mainnetAliases:["xrp","ripple","xrp-mainnet"],testnetAliases:["xrp-testnet","xrp_testnet"]}],bu=()=>{let c={};for(let e of xu){let t={chainId:e.mainnetId,type:e.type,networkType:"mainnet"},n={chainId:e.testnetId,type:e.type,networkType:e.type===J.BTC&&e.testnetId==="BTC_T3"?"testnet":e.testnetId.replace(/_/g,"-").split("-")[1]||"testnet"};e.name==="Bitcoin"&&e.testnetId==="BTC_T3"&&(n.type=J.BTC_T3),c[e.mainnetId]=t;for(let r of e.mainnetAliases)c[r]=t;c[e.testnetId]=n;for(let r of e.testnetAliases)c[r]=n;}return c},Iu=bu(),rn=class{apiClient;strategies;chainConfigs;isMainnet;constructor(e,t=false,n){this.apiClient=e,this.isMainnet=t,this.strategies=new Map,this.chainConfigs=new Map(Object.entries(Iu)),this.initializeStrategies(n);}initializeStrategies(e){this.strategies.set(J.EVM,new mt(this.apiClient,e)),this.strategies.set(J.SOL,new jr(this.apiClient,this.isMainnet,e)),this.strategies.set(J.TRON,new Jr(this.apiClient,this.isMainnet,e)),this.strategies.set(J.BTC,new ir(this.apiClient,this.isMainnet,e)),this.strategies.set(J.BTC_T3,new ir(this.apiClient,false,e)),this.strategies.set(J.ADA,new en(this.apiClient,this.isMainnet,e)),this.strategies.set(J.XRP,new tn(this.apiClient,this.isMainnet,e));}getStrategy(e){let t=this.getChainConfig(e);return t?this.strategies.get(t.type)||null:(console.warn(`BlockchainAdapter: unsupported chainId ${e}`),null)}getChainConfig(e){let t=String(e).toLowerCase();return this.chainConfigs.get(t)||null}getNetworkInfo(e){let t=this.getChainConfig(e);return t?{type:t.type,networkType:t.networkType,chainId:t.chainId}:null}registerChain(e,t){this.chainConfigs.set(e.toLowerCase(),t);}async getBalance(e,t){let n=this.getStrategy(e);if(!n?.getBalance)throw new Error(`getBalance not supported for chain ${e}`);let r=this.getChainConfig(e),s=n.getProvider?.(r?.type===J.EVM?r?.chainId:r?.networkType);return n.getBalance(t,s)}async estimateFee(e,t){let n=this.getStrategy(e);if(!n?.estimateFee)throw new Error(`estimateFee not supported for chain ${e}`);return n.estimateFee({...t,chainId:e})}async createOrder(e,t){let n=this.getStrategy(e);if(!n?.createOrder)throw new Error(`createOrder not supported for chain ${e}`);let r=this.getChainConfig(e);return n.createOrder({...t,networkType:r?.networkType||""})}async signOrder(e,t){let n=this.getStrategy(e);if(!n?.signOrder)throw new Error(`signOrder not supported for chain ${e}`);let r=this.getChainConfig(e);return n.signOrder({...t,networkType:r?.networkType||""})}async rejectOrder(e,t){let n=this.getStrategy(e);if(!n?.rejectOrder)throw new Error(`rejectOrder not supported for chain ${e}`);let r=this.getChainConfig(e);return n.rejectOrder({...t,networkType:r?.networkType||""})}async executeTransaction(e,t){let n=this.getStrategy(e);if(!n?.executeTransaction)throw new Error(`executeTransaction not supported for chain ${e}`);let r=this.getChainConfig(e);return n.executeTransaction({...t,networkType:r?.networkType||"",chainId:e})}async broadcastTransaction(e,t){let n=this.getStrategy(e);if(!n?.broadcastTransaction)throw new Error(`broadcastTransaction not supported for chain ${e}`);let r=this.getChainConfig(e),s=n.getProvider?.(r?.type===J.EVM?r?.chainId:r?.networkType);return n.broadcastTransaction(s,t)}async getTransactionHash(e,t){let n=this.getStrategy(e);if(!n?.getTransactionHash)throw new Error(`getTransactionHash not supported for chain ${e}`);return n.getTransactionHash(t)}async getOwners(e,t){let n=this.getStrategy(e);if(!n?.getOwners)throw new Error(`getOwners not supported for chain ${e}`);let r=this.getChainConfig(e),s=n.getProvider?.(r?.type===J.EVM?r?.chainId:r?.networkType);return n.getOwners(t,s)}encodeRemoveOwner(e,t,n,r){let s=this.getStrategy(e);if(!s?.encodeRemoveOwner)throw new Error(`encodeRemoveOwner not supported for chain ${e}`);return s.encodeRemoveOwner(t,n,r)}encodeChangeThreshold(e,t){let n=this.getStrategy(e);if(!n?.encodeChangeThreshold)throw new Error(`encodeChangeThreshold not supported for chain ${e}`);return n.encodeChangeThreshold(t)}encodeAddOwnerWithThreshold(e,t,n){let r=this.getStrategy(e);if(!r?.encodeAddOwnerWithThreshold)throw new Error(`encodeAddOwnerWithThreshold not supported for chain ${e}`);return r.encodeAddOwnerWithThreshold(t,n)}encodeExecTransaction(e,t,n,r,s,a){let l=this.getStrategy(e);if(!l?.encodeExecTransaction)throw new Error(`encodeExecTransaction not supported for chain ${e}`);return l.encodeExecTransaction(t,n,r,s,a)}};Q();var Cs=200,Ps=4294967295,Wo=["XRP","SOL","TRON"];function Rs(c){return Wo.includes(c)}function Ms(c,e){return c?e==="XRP"?/^\d+$/.test(c)?Number(c)>Ps?{isValid:false,error:`XRP memo (Destination Tag) must be between 0 and ${Ps}`}:{isValid:true}:{isValid:false,error:"XRP memo (Destination Tag) must contain only digits"}:e==="SOL"||e==="TRON"?/\s/.test(c)?{isValid:false,error:"Memo must not contain spaces"}:c.length>Cs?{isValid:false,error:`Memo must be at most ${Cs} characters`}:{isValid:true}:{isValid:true}:{isValid:true}}function Su(c){return c==="XRP"?"Destination Tag (numeric)":c==="SOL"||c==="TRON"?"Memo (up to 200 characters, no spaces)":""}ht();var nn=class{resolvedConfig;rpcConfig;client;walletService;multisigApi;orderApi;blockchainAdapter;keyManager;txService;addressBookApi;organizationApi;constructor(e){this.resolvedConfig=Sn(e),Ys(this.resolvedConfig.network),this.client=new lr(this.resolvedConfig);let t=new qt(this.client);this.keyManager=new kr(t,this.resolvedConfig),this.txService=new Dr(this.resolvedConfig),this.walletService=new Gr(this.client,this.keyManager,this.txService,this.resolvedConfig);let n=new ee(this.client);this.multisigApi=new br(this.client,n),this.orderApi=new Sr(this.client),this.addressBookApi=new Or(this.client),this.organizationApi=new Cr(this.client),this.rpcConfig=ut(this.resolvedConfig.network,this.resolvedConfig.rpcOverrides),this.blockchainAdapter=new rn(this.client,this.resolvedConfig.network==="mainnet",this.rpcConfig);}async createWallet(e){return {wallets:(await this.walletService.createWallet(e.chain)).wallets}}async importWallet(e){return this.walletService.importWallet(e.chain,e.privateKey)}async deleteWallet(e){return this.walletService.deleteWallet(e.chain,e.address)}async getWallet(e){return this.walletService.getWallet(e.address)}async getWallets(e){if(e?.page!=null||e?.limit!=null||e?.chainTypes!=null&&e.chainTypes.length>0||e?.chain!=null){let n=e?.chainTypes?.length?e.chainTypes:e?.chain!=null?[e.chain]:void 0;return this.walletService.getPaginatedWallets({page:e?.page,limit:e?.limit,chainTypes:n})}return this.walletService.getWallets()}async getWalletsPortfolio(e){return new(await Promise.resolve().then(()=>(Pn(),ai))).WalletApi(this.client).getWalletsPortfolio(e)}async getPortfolio(e){let t=[{walletAddress:e.address,chainType:e.chain,chain:e.chainId.toString()}];return (await this.getWalletsPortfolio(t))[0]}async sendTransaction(e){if(e.memo&&Rs(e.chain)){let r=Ms(e.memo,e.chain);if(!r.isValid)throw new exports.InvalidInputError(r.error||"Invalid memo")}let t={chain:e.chain,from:e.from,to:e.to,value:e.amount,chainId:e.chainId,isNativeToken:e.isNativeToken,tokenAddress:e.tokenAddress,symbol:e.symbol,decimals:e.decimals,feeHint:e.feeHint,memo:e.memo};return {txHash:(await this.walletService.sendTransaction({chain:e.chain,address:e.from,txParams:t})).hash}}async estimateFee(e){let{chain:t,txType:n,payload:r,chainId:s}=e,{TransactionEstimatingType:a}=await Promise.resolve().then(()=>(Ge(),Fn)),l;switch(n){case a.Send:{l={type:a.Send,data:{to:r.to||"",amount:r.amount||"0",tokenAddress:r.tokenAddress,isNativeToken:!r.tokenAddress,decimals:r.decimals}};break}case a.ExecOrder:{if(!r.order)throw new Error("Order object is required for ExecOrder fee estimation");l={type:a.ExecOrder,data:{order:r.order,multisigAddress:r.multisig?.address||""}};break}case a.ActivateMultisig:{if(!r.multisig)throw new Error("Multisig object is required for ActivateMultisig fee estimation");l={type:a.ActivateMultisig,data:{multisig:r.multisig}};break}case a.SignOrder:{if(!r.order)throw new Error("Order object is required for SignOrder fee estimation");l={type:a.SignOrder,data:{order:r.order}};break}case a.CreateOrder:{if(!r.multisig)throw new Error("Multisig object is required for CreateOrder fee estimation");l={type:a.CreateOrder,data:{to:r.to||"",amount:r.amount||"0",tokenAddress:r.tokenAddress,tokenDecimals:r.decimals||0,multisig:r.multisig,method:r.method}};break}case a.ChangeMultisig:{if(!r.multisig||!r.owners||!r.threshold)throw new Error("Multisig, owners, and threshold are required for ChangeMultisig fee estimation");l={type:a.ChangeMultisig,data:{multisig:r.multisig,newOwners:r.owners,newThreshold:r.threshold}};break}default:l={type:a.Send,data:{to:r.to||"",amount:r.amount||"0",tokenAddress:r.tokenAddress,isNativeToken:!r.tokenAddress,decimals:r.decimals}};}let p=this.getChainIdForEstimation(t,s);return this.blockchainAdapter.estimateFee(p,{input:l,actualWallet:{address:r.from||"",chain:t,name:null,share:"",isImported:false},chainId:p})}getChainIdForEstimation(e,t){if(t)return t;let n=this.resolvedConfig.network==="mainnet";switch(e){case "EVM":return n?"1":"11155111";case "SOL":return n?"sol_mainnet":"sol_devnet";case "TRON":return n?"tron_mainnet":"tron_shasta";case "BTC":case "BTC_T3":return n?"BTC":"BTC_T3";case "ADA":return n?"ada_mainnet":"ada_preprod";case "XRP":return n?"xrp_mainnet":"xrp_testnet";default:return n?"1":"11155111"}}async exportWallet(e){return {privateKey:(await this.walletService.exportWallet(e.chain,e.address)).privateKey}}async updateWalletName(e){return this.walletService.updateWalletName(e.chain,e.address,e.name)}async createMultisig(e){return this.multisigApi.createMultisig({chain:e.chain,owners:e.owners,threshold:e.threshold,chainIds:e.chainIds})}async getMultisigs(e){return this.multisigApi.getMultisigs({chain:e.chain,walletAddress:e.walletAddress})}async getPaginatedMultisigs(e){return this.multisigApi.getPaginatedMultisigs(e)}async getMultisigById(e){return this.multisigApi.getMultisig({chain:e.chain,address:e.address})}async activateMultisig(e){return {txHash:(await this.multisigApi.activateMultisig({chain:e.chain,multisigId:e.multisigId,multisig:e.multisig,multisigAddress:e.multisigAddress,walletAddress:e.walletAddress,feeQuote:e.feeQuote})).txHash||""}}async estimateActivationFee(e){return {estimatedFee:"0.001",currency:e.chain==="EVM"?"ETH":e.chain==="SOL"?"SOL":e.chain==="TRON"?"TRX":e.chain==="ADA"?"ADA":e.chain==="XRP"?"XRP":"BTC"}}async updateMultisigName(e){return this.multisigApi.updateMultisig({chain:e.chain,multisigId:e.multisigId,name:e.name,walletAddress:e.walletAddress})}async deleteMultisig(e){return this.multisigApi.deleteMultisig({chain:e.chain,multisigId:e.multisigId})}async createOrder(e){let t=await this.orderApi.createOrder({chain:e.chain,multisigId:e.multisigId,walletAddress:e.walletAddress,method:e.method,instructions:e.instructions,threshold:e.threshold,token:e.token,orderIdToActivate:e.orderIdToActivate});return {order:t.order,proposalHash:t.proposalHash}}async createSendOrder(e){return this.orderApi.createSendOrder(e)}async createSettingsOrder(e){return this.orderApi.createSettingsOrder(e)}async signOrder(e){let{order:t}=e;if(e.chain==="XRP")return this.orderApi.signOrder({chain:e.chain,orderId:t.id,walletAddress:e.walletAddress,multisigId:e.multisigId});let n=this.getChainIdForSignOrder(e.chain,t),r=await this.blockchainAdapter.signOrder(n,{orderId:t.id,multisigId:e.multisigId||"",wallet:{address:e.walletAddress},networkType:n,order:t}),s=await this.orderApi.signOrder({chain:e.chain,orderId:t.id,walletAddress:e.walletAddress,transaction:r.tx,multisigId:e.multisigId,version:r?.version});return {signature:r.tx||"",order:s.order}}getChainIdForSignOrder(e,t){let n=this.resolvedConfig.network==="mainnet";return e==="EVM"?t?.chainId?.toString()||(n?"1":"11155111"):e==="SOL"?n?"sol_mainnet":"sol_devnet":e==="TRON"?n?"tron_mainnet":"tron_shasta":e==="BTC"||e==="BTC_T3"?n?"BTC":"BTC_T3":e==="ADA"?n?"ada_mainnet":"ada_preprod":e==="XRP"?n?"xrp_mainnet":"xrp_testnet":"1"}async rejectOrder(e){return (await this.orderApi.rejectOrder({chain:e.chain,order:e.order,multisig:e.multisig,walletAddress:e.walletAddress})).order}async executeOrder(e){let t=await this.orderApi.executeOrder({chain:e.chain,order:e.order,multisig:e.multisig,walletAddress:e.walletAddress,feeQuote:e.feeQuote});return {txHash:t.txHash||"",order:t.order}}async estimateOrderExecutionFee(e){return {estimatedFee:"0.001",currency:e.chain==="EVM"?"ETH":e.chain==="SOL"?"SOL":e.chain==="TRON"?"TRX":e.chain==="ADA"?"ADA":e.chain==="XRP"?"XRP":"BTC"}}async getOrders(e){return this.orderApi.getOrders({chain:e.chain,multisigId:e.multisigId,page:e.page,limit:e.limit})}async getOrderById(e){return this.orderApi.getOrder({chain:e.chain,orderId:e.orderId})}async deleteOrder(e){return this.orderApi.cancelOrder({chain:e.chain,orderId:e.orderId})}async getSupportedTokens(e){return this.walletService.getSupportedTokens(e.chain,e.chainId,e.page,e.limit,e.search)}async getTotalAssetValue(){return this.walletService.getTotalAssetValue()}async getWalletHistory(e){return this.walletService.getHistory(e.chain,e.walletAddress,e.page,e.limit)}async getMultisigTxHistory(e){return this.multisigApi.getMultisigHistory({multisigId:e.multisigId,page:e.page,limit:e.limit})}async activateXrpTrustLine(e){let{validateXrpAddress:t}=await Promise.resolve().then(()=>(st(),Xr));if(!t(e.address))throw new Error(`Invalid XRP address: ${e.address}`);if(!t(e.issuer))throw new Error(`Invalid XRP issuer address: ${e.issuer}`);let{TransactionExecutionType:n}=await Promise.resolve().then(()=>(Ge(),Fn)),s=this.resolvedConfig.network==="mainnet"?"xrp_mainnet":"xrp_testnet";return await this.blockchainAdapter.executeTransaction(s,{input:{type:n.ActivateTrustLine,data:{currency:e.currency,issuer:e.issuer,limit:e.limit}},actualWallet:{address:e.address,chain:"XRP",name:null,share:"",isImported:false},networkType:s,chainId:s})}async getXrpAccountReserve(e){let{validateXrpAddress:t,fetchXrpAccountReserveInfo:n}=await Promise.resolve().then(()=>(st(),Xr));if(!t(e.address))throw new Error(`Invalid XRP address: ${e.address}`);return n(e.address,this.rpcConfig.xrp)}async getXrpTrustLines(e){let{validateXrpAddress:t,fetchAccountTrustLines:n}=await Promise.resolve().then(()=>(st(),Xr));if(!t(e.address))throw new Error(`Invalid XRP address: ${e.address}`);return n(e.address,this.rpcConfig.xrp)}async createAddressBookEntry(e){return this.addressBookApi.createEntry({name:e.name,address:e.address,chainType:e.chainType,type:e.type,memo:e.memo})}async getAddressBookEntries(e){return this.addressBookApi.getEntries({chainType:e?.chainType,type:e?.type})}async updateAddressBookEntry(e){return this.addressBookApi.updateEntry(e.id,{name:e.name,memo:e.memo})}async deleteAddressBookEntry(e){return this.addressBookApi.deleteEntry(e.id)}async getAddressType(e){return this.addressBookApi.getAddressType(e.chainType,e.address)}async getOrgTeam(){return this.organizationApi.getTeam()}async inviteOrgMember(e){return this.organizationApi.inviteMember(e)}async removeOrgMember(e){return this.organizationApi.removeMember(e)}async listOrgMemberWallets(e){return this.organizationApi.listAssignedMemberWallets(e)}async assignOrgWallet(e){return this.organizationApi.assignWallet(e)}async unassignOrgWallet(e){return this.organizationApi.unassignWallet(e)}async listOrgWallets(){return this.organizationApi.listOrganizationWallets()}async getOrgPolicies(){return this.organizationApi.getPolicies()}async updateOrgPolicies(e){return this.organizationApi.updatePolicies(e)}async listOrgAddresses(){return this.organizationApi.listAddresses()}async addOrgAddress(e){return this.organizationApi.addAddress(e)}async updateOrgAddress(e){let{addressId:t,...n}=e;return this.organizationApi.updateAddress(t,n)}async deleteOrgAddress(e){return this.organizationApi.deleteAddress(e.addressId)}async getOrgAuditLogs(e){return this.organizationApi.getAuditLogs(e)}};Q();Ge();ht();Q();var p0=nn;
2
+ exports.AfridaxSDK=nn;exports.MEMO_MAX_LENGTH=Cs;exports.MEMO_SUPPORTED_CHAINS=Wo;exports.XRP_MAX_DESTINATION_TAG=Ps;exports.default=p0;exports.getBtcChainType=zo;exports.getMemoPlaceholder=Su;exports.isAfridaxError=ic;exports.isMemoSupported=Rs;exports.validateMemo=Ms;