@swapkit/toolboxes 6.6.0 → 6.6.2

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/CHANGELOG.md CHANGED
@@ -1,5 +1,21 @@
1
1
  # @swapkit/toolboxes
2
2
 
3
+ ## 6.6.2
4
+
5
+ ### Patch Changes
6
+
7
+ - [#489](https://github.com/swapkit/sdk/pull/489) [`3fb0f51`](https://github.com/swapkit/sdk/commit/3fb0f511c3c1a460bcc768f4dd05689786cc1a9d) Thanks [@hippocampusSK](https://github.com/hippocampusSK)! - `helpers_chain_rpc_connection_failed` now says which chain failed and why each configured RPC endpoint was rejected in its message and `info`. The reason is always one of a fixed set (an HTTP status, `timeout`, `invalid_url`, `dns_error`, `connection_refused` or `network_error`), never the raw error text, so the error stays small and carries nothing from upstream. Before, the details were passed as the error's cause, so the message only showed the error key. Endpoints are reported by origin only, so API keys in RPC URLs never reach the logs. `helpers_chain_no_public_or_set_rpc_url` also carries the chain in its message now.
8
+ - [#490](https://github.com/swapkit/sdk/pull/490) [`4da7435`](https://github.com/swapkit/sdk/commit/4da7435524265403abdc4f07d32a6fdf19b4d64d) Thanks [@hippocampusSK](https://github.com/hippocampusSK)! - Fix three Substrate toolbox (Polkadot, Chainflip) signing bugs:
9
+ - [#486](https://github.com/swapkit/sdk/pull/486) [`8b15231`](https://github.com/swapkit/sdk/commit/8b15231a8af87f7cdbbd6c40e308cb01e80e6186) Thanks [@hippocampusSK](https://github.com/hippocampusSK)! - Allow quote and swap requests to opt into selling the full balance of a native asset, and expose whether a route was adjusted for it (via @swapkit/helpers@6.5.0)
10
+ - [#484](https://github.com/swapkit/sdk/pull/484) [`c03235b`](https://github.com/swapkit/sdk/commit/c03235b7a06fc3c71c67c0407a2c8c5159b4cb17) Thanks [@github-actions](https://github.com/apps/github-actions)! - Update generated token lists. (via @swapkit/helpers@6.5.0)
11
+
12
+ ## 6.6.1
13
+
14
+ ### Patch Changes
15
+
16
+ - [#487](https://github.com/swapkit/sdk/pull/487) [`4c192c9`](https://github.com/swapkit/sdk/commit/4c192c939cb142989c13048f31fe681a15312020) Thanks [@hippocampusSK](https://github.com/hippocampusSK)! - Zcash transactions now pay the ZIP-317 conventional fee instead of a per-byte rate. Coin selection, fee estimation and sweeps price inputs per logical action, so UTXOs worth more than their marginal cost are no longer dropped as uneconomical and payable wallets are no longer rejected. The marginal fee switches from 5,000 to 1,000 zats at mainnet height 3,590,000 (ZIP 2009). `accumulative` takes an optional `marginalFee` for Zcash and `calculateZcashFee` is exported so the API can share the same fee. `feeRate` and `FeeOption` have no effect on Zcash because ZIP-317 has no fee market; the conventional fee for the expected mining height is always paid. Other UTXO chains are unchanged.
17
+ - [#484](https://github.com/swapkit/sdk/pull/484) [`c03235b`](https://github.com/swapkit/sdk/commit/c03235b7a06fc3c71c67c0407a2c8c5159b4cb17) Thanks [@github-actions](https://github.com/apps/github-actions)! - Update generated token lists. (via @swapkit/helpers@6.4.3)
18
+
3
19
  ## 6.6.0
4
20
 
5
21
  ### Minor Changes
@@ -1 +1 @@
1
- import{$ as M,A as l,B as m,C as n,D as o,E as p,F as q,G as r,H as s,I as t,J as u,K as v,L as w,M as x,N as y,O as z,P as A,Q as B,R as C,S as D,T as E,U as F,V as G,W as H,X as I,Y as J,Z as K,_ as L,aa as N,ba as O,ca as P,da as Q,ea as R,fa as S,ga as T,ha as U,p as a,q as b,r as c,s as d,t as e,u as f,v as g,w as h,x as i,y as j,z as k}from"./chunk-2q4pxsyg.js";import"./chunk-qk8kg62t.js";import"./chunk-pz8xe0qj.js";export{w as ADIToolbox,x as ARBToolbox,y as ARCToolbox,z as AURORAToolbox,A as AVAXToolbox,B as BASEToolbox,C as BERAToolbox,D as BSCToolbox,b as BaseEVMToolbox,E as BotanixToolbox,F as COREToolbox,G as CORNToolbox,H as CROToolbox,k as ContractAddress,v as ETHToolbox,I as GNOToolbox,J as HOODToolbox,K as HYPEREVMToolbox,L as LINEAToolbox,M as MATICToolbox,a as MAX_APPROVAL,N as MEGAETHToolbox,O as MONADToolbox,u as OPToolbox,P as PLASMAToolbox,Q as SONICToolbox,R as UNIToolbox,S as XLayerToolbox,e as createContract,t as createOPStackToolbox,j as getChecksumAddressFromAsset,f as getCreateContract,m as getCreateContractTxObject,i as getEIP1193SendTransaction,q as getEVMTxType,n as getEstimateGasPrices,T as getEvmToolbox,U as getEvmToolboxAsync,l as getTokenAddress,d as isBrowserProvider,p as isEIP1559Transaction,o as isEIP7702Transaction,g as isStateChangingCall,r as maxBigInt,s as scaleEIP1559Fees,h as toChecksumAddress,c as validateEVMAddress};
1
+ import{$ as M,A as l,B as m,C as n,D as o,E as p,F as q,G as r,H as s,I as t,J as u,K as v,L as w,M as x,N as y,O as z,P as A,Q as B,R as C,S as D,T as E,U as F,V as G,W as H,X as I,Y as J,Z as K,_ as L,aa as N,ba as O,ca as P,da as Q,ea as R,fa as S,ga as T,ha as U,p as a,q as b,r as c,s as d,t as e,u as f,v as g,w as h,x as i,y as j,z as k}from"./chunk-6fcz98xe.js";import"./chunk-qk8kg62t.js";import"./chunk-pz8xe0qj.js";export{w as ADIToolbox,x as ARBToolbox,y as ARCToolbox,z as AURORAToolbox,A as AVAXToolbox,B as BASEToolbox,C as BERAToolbox,D as BSCToolbox,b as BaseEVMToolbox,E as BotanixToolbox,F as COREToolbox,G as CORNToolbox,H as CROToolbox,k as ContractAddress,v as ETHToolbox,I as GNOToolbox,J as HOODToolbox,K as HYPEREVMToolbox,L as LINEAToolbox,M as MATICToolbox,a as MAX_APPROVAL,N as MEGAETHToolbox,O as MONADToolbox,u as OPToolbox,P as PLASMAToolbox,Q as SONICToolbox,R as UNIToolbox,S as XLayerToolbox,e as createContract,t as createOPStackToolbox,j as getChecksumAddressFromAsset,f as getCreateContract,m as getCreateContractTxObject,i as getEIP1193SendTransaction,q as getEVMTxType,n as getEstimateGasPrices,T as getEvmToolbox,U as getEvmToolboxAsync,l as getTokenAddress,d as isBrowserProvider,p as isEIP1559Transaction,o as isEIP7702Transaction,g as isStateChangingCall,r as maxBigInt,s as scaleEIP1559Fees,h as toChecksumAddress,c as validateEVMAddress};
@@ -0,0 +1,2 @@
1
+ import{ja as Ve}from"./chunk-qk8kg62t.js";import{ka as de}from"./chunk-pz8xe0qj.js";import{Chain as x}from"@swapkit/helpers";import{match as In}from"ts-pattern";import{Chain as g,getChainConfig as J,getRPCUrl as At,SKConfig as Mt,SwapKitError as U}from"@swapkit/helpers";import{FallbackProvider as Gt,getAddress as Ee,Interface as Ot,JsonRpcProvider as se,Network as Bt}from"ethers";import{match as _e}from"ts-pattern";function It(e){return new se(e)}async function Nn(e,t){return It(t||await At(e))}function Ce(e){let t=Mt.get("rpcUrls")[e]?.filter(Boolean)??[];if(t.length===0)throw new U({errorKey:"helpers_chain_no_public_or_set_rpc_url",info:{chain:e}});let{chainId:n}=J(e),o=Bt.from(Number(n)),[a]=t;if(t.length===1)return new se(a,o,{staticNetwork:o});return new Gt(t.map((r,i)=>({priority:i+1,provider:new se(r,o,{staticNetwork:o}),stallTimeout:2000})),o,{quorum:1})}function O(e){return e>0n?`0x${e.toString(16)}`:"0x0"}function Fe(e){let{explorerUrl:t,chainIdHex:n,rpcUrls:o}=J(e);return function(){return e!==g.Ethereum?{...Vt({chain:e}),blockExplorerUrls:[t],chainId:n,rpcUrls:o}:void 0}}function Ae(e){return![g.Adi,g.Arbitrum,g.BinanceSmartChain,g.Robinhood].includes(e)}function Vt({chain:e}){let{name:t,nativeCurrency:n,baseDecimal:o}=J(e);return _e(e).with(g.Arbitrum,()=>({chainName:"Arbitrum One",nativeCurrency:{decimals:o,name:"Ethereum",symbol:g.Ethereum}})).with(g.Aurora,()=>({chainName:"Aurora Mainnet",nativeCurrency:{decimals:o,name:"Ethereum",symbol:g.Ethereum}})).with(g.Avalanche,()=>({chainName:"Avalanche Network",nativeCurrency:{decimals:o,name:"Avalanche",symbol:e}})).with(g.Base,()=>({chainName:"Base Mainnet",nativeCurrency:{decimals:o,name:"Ethereum",symbol:g.Ethereum}})).with(g.Berachain,()=>({chainName:"Berachain",nativeCurrency:{decimals:o,name:"Berachain",symbol:"BERA"}})).with(g.XLayer,()=>({chainName:"X Layer",nativeCurrency:{decimals:o,name:"OKB",symbol:"OKB"}})).with(g.BinanceSmartChain,()=>({chainName:"BNB Smart Chain Mainnet",nativeCurrency:{decimals:o,name:"Binance Coin",symbol:"BNB"}})).with(g.Gnosis,()=>({chainName:"Gnosis",nativeCurrency:{decimals:o,name:"xDAI",symbol:"XDAI"}})).with(g.Optimism,()=>({chainName:"OP Mainnet",nativeCurrency:{decimals:o,name:"Ethereum",symbol:g.Ethereum}})).with(g.Polygon,()=>({chainName:"Polygon Mainnet",nativeCurrency:{decimals:o,name:"Polygon",symbol:g.Polygon}})).with(g.Robinhood,()=>({chainName:"Robinhood Chain",nativeCurrency:{decimals:o,name:"Ethereum",symbol:g.Ethereum}})).otherwise(()=>({chainName:t,nativeCurrency:{decimals:o,name:n,symbol:n}}))}async function Me(e,t){if(!("authorize"in e))throw Error("Signer does not support EIP-7702 authorization. Requires ethers.js v6.14+");let n={...t,nonce:t.nonce!==void 0?BigInt(t.nonce):void 0};return await e.authorize(n)}var ve=(e)=>typeof e==="string"&&/^0x[a-fA-F0-9]{64}$/.test(e),Rt=(e)=>{try{return typeof e==="string"&&!!Ee(e)}catch{return!1}};function St(e,t){let n=t!==void 0?`index ${t}: `:"",o=(a,r)=>{throw new U({errorKey:"toolbox_evm_invalid_eip7702_authorization",info:{field:a,message:`${n}${r}`}})};_e(e).when(({chainId:a})=>typeof a!=="bigint",()=>o("chainId","chainId must be a bigint")).when(({address:a})=>!Rt(a),()=>o("address","address must be a valid checksummed address")).when(({nonce:a})=>typeof a!=="bigint"||a<0n,()=>o("nonce","nonce must be a non-negative bigint")).when(({signature:a})=>!a,()=>o("signature","signature is required")).when(({signature:a})=>typeof a?.yParity!=="number"||![0,1].includes(a.yParity),()=>o("signature.yParity","yParity must be 0 or 1")).when(({signature:a})=>!ve(a?.r),()=>o("signature.r","r must be a 32-byte hex string")).when(({signature:a})=>!ve(a?.s),()=>o("signature.s","s must be a 32-byte hex string")).otherwise(()=>{})}function Ge(e){return[{key:"name",type:"string"},{key:"version",type:"string"},{key:"chainId",type:"uint256"},{key:"verifyingContract",type:"address"},{key:"salt",type:"bytes32"}].filter(({key:t})=>e[t]!=null).map(({key:t,type:n})=>({name:t,type:n}))}function Oe(e){if(!("EIP712Domain"in e.types))return e;let{EIP712Domain:t,...n}=e.types,o=Ge(e.domain);if(!(Array.isArray(t)&&t.length===o.length&&o.every(({name:r,type:i},s)=>t[s]?.name===r&&t[s]?.type===i)))throw new U({errorKey:"toolbox_evm_typed_data_domain_mismatch",info:{declared:t,expected:o}});return{...e,types:n}}function ce(e){return e.charAt(0).toUpperCase()+e.slice(1)}function ue(e,t){if(e.isTuple()&&e.components){let n=ce(e.name);return t[n]=e.components.map((o)=>({name:o.name,type:ue(o,t)})),n}if(e.isArray()){let n=e.arrayChildren;if(n?.isTuple()&&n.components){let o=ce(e.name.replace(/s$/,""));return t[o]=n.components.map((a)=>({name:a.name,type:ue(a,t)})),`${o}[]`}return`${n?.type??"bytes"}[]`}return e.type}function le(e,t){if(typeof e==="bigint")return e;if(t?.isTuple()&&typeof e?.toObject==="function"){let n=e.toObject(),o={};for(let[a,r]of(t.components??[]).entries())o[r.name]=le(n[r.name]??e[a],r);return o}if(Array.isArray(e)){let n=t?.arrayChildren;return e.map((o)=>le(o,n??void 0))}return e}function Ln({chain:e,abi:t,data:n,to:o}){let r=new Ot(t).parseTransaction({data:n});if(!r)throw new U({errorKey:"toolbox_evm_invalid_params",info:{error:"Could not decode calldata"}});let i={},s=ce(r.name);i[s]=r.fragment.inputs.map((p)=>({name:p.name,type:ue(p,i)}));let c={};for(let[p,b]of r.fragment.inputs.entries())c[b.name]=le(r.args[p],b);let{chainId:l}=J(e),u={chainId:Number(l),verifyingContract:Ee(o)},d=Ge(u);return{domain:u,message:c,primaryType:s,types:{EIP712Domain:d,...i}}}function Be(e,t){if(!Array.isArray(e)||e.length===0)throw new U({errorKey:"toolbox_evm_invalid_eip7702_authorization",info:{message:"EIP-7702 transactions require at least one authorization"}});for(let[n,o]of e.entries())if(St(o,n),t!==void 0&&o.chainId!==t)throw new U({errorKey:"toolbox_evm_invalid_eip7702_authorization",info:{field:"chainId",message:`index ${n}: authorization chainId (${o.chainId}) does not match transaction chainId (${t})`}})}import{Chain as T,derivationPathToString as Fn,FeeOption as An,resolveDerivationPath as Mn}from"@swapkit/helpers";import{HDNodeWallet as Gn}from"ethers";import{match as On,P as ot}from"ts-pattern";var Ie=[{inputs:[{components:[{internalType:"address",name:"target",type:"address"},{internalType:"bytes",name:"callData",type:"bytes"}],internalType:"struct Multicall2.Call[]",name:"calls",type:"tuple[]"}],name:"aggregate",outputs:[{internalType:"uint256",name:"blockNumber",type:"uint256"},{internalType:"bytes[]",name:"returnData",type:"bytes[]"}],stateMutability:"nonpayable",type:"function"},{inputs:[{components:[{internalType:"address",name:"target",type:"address"},{internalType:"bytes",name:"callData",type:"bytes"}],internalType:"struct Multicall2.Call[]",name:"calls",type:"tuple[]"}],name:"blockAndAggregate",outputs:[{internalType:"uint256",name:"blockNumber",type:"uint256"},{internalType:"bytes32",name:"blockHash",type:"bytes32"},{components:[{internalType:"bool",name:"success",type:"bool"},{internalType:"bytes",name:"returnData",type:"bytes"}],internalType:"struct Multicall2.Result[]",name:"returnData",type:"tuple[]"}],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"uint256",name:"blockNumber",type:"uint256"}],name:"getBlockHash",outputs:[{internalType:"bytes32",name:"blockHash",type:"bytes32"}],stateMutability:"view",type:"function"},{inputs:[],name:"getBlockNumber",outputs:[{internalType:"uint256",name:"blockNumber",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[],name:"getCurrentBlockCoinbase",outputs:[{internalType:"address",name:"coinbase",type:"address"}],stateMutability:"view",type:"function"},{inputs:[],name:"getCurrentBlockDifficulty",outputs:[{internalType:"uint256",name:"difficulty",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[],name:"getCurrentBlockGasLimit",outputs:[{internalType:"uint256",name:"gaslimit",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[],name:"getCurrentBlockTimestamp",outputs:[{internalType:"uint256",name:"timestamp",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"address",name:"addr",type:"address"}],name:"getEthBalance",outputs:[{internalType:"uint256",name:"balance",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[],name:"getLastBlockHash",outputs:[{internalType:"bytes32",name:"blockHash",type:"bytes32"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"bool",name:"requireSuccess",type:"bool"},{components:[{internalType:"address",name:"target",type:"address"},{internalType:"bytes",name:"callData",type:"bytes"}],internalType:"struct Multicall2.Call[]",name:"calls",type:"tuple[]"}],name:"tryAggregate",outputs:[{components:[{internalType:"bool",name:"success",type:"bool"},{internalType:"bytes",name:"returnData",type:"bytes"}],internalType:"struct Multicall2.Result[]",name:"returnData",type:"tuple[]"}],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"bool",name:"requireSuccess",type:"bool"},{components:[{internalType:"address",name:"target",type:"address"},{internalType:"bytes",name:"callData",type:"bytes"}],internalType:"struct Multicall2.Call[]",name:"calls",type:"tuple[]"}],name:"tryBlockAndAggregate",outputs:[{internalType:"uint256",name:"blockNumber",type:"uint256"},{internalType:"bytes32",name:"blockHash",type:"bytes32"},{components:[{internalType:"bool",name:"success",type:"bool"},{internalType:"bytes",name:"returnData",type:"bytes"}],internalType:"struct Multicall2.Result[]",name:"returnData",type:"tuple[]"}],stateMutability:"nonpayable",type:"function"}];import{AssetValue as kt,applyFeeMultiplierToBigInt as M,Chain as j,EVMChains as Nt,FeeOption as y,isGasAsset as ke,SwapKitError as m,SwapKitNumber as Q}from"@swapkit/helpers";import{erc20ABI as K}from"@swapkit/helpers/contracts";import{BrowserProvider as Lt,Contract as Ne,getAddress as ee,getBytes as Dt,Interface as Le,isError as D,resolveAddress as zt,Transaction as pe}from"ethers";import{match as De}from"ts-pattern";function Y(e){return{getBalance:Ve(e)}}function Kn(e){return e}var be=BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff");function te({chain:e=j.Ethereum,provider:t,signer:n,isEIP1559Compatible:o=!0,estimateGasPrices:a,estimateAdditionalFee:r}){let i=a??X({chain:e,isEIP1559Compatible:o,provider:t}),s=$e({chain:e,estimateAdditionalFee:r,estimateGasPrices:i,isEIP1559Compatible:o,provider:t,signer:n});return{approve:tn({chain:e,isEIP1559Compatible:o,provider:t,signer:n}),approvedAmount:qe({chain:e,provider:t}),broadcastTransaction:(c)=>t.broadcastTransaction(c),call:ae({chain:e,isEIP1559Compatible:o,provider:t,signer:n}),createApprovalTx:yn({chain:e,provider:t,signer:n}),createContract:Kt({chain:e,provider:t}),createContractTxObject:W({chain:e,provider:t}),createTransaction:s,createTransferTx:s,EIP1193SendTransaction:oe(t),estimateCall:je({provider:t,signer:n}),estimateGasLimit:on({chain:e,provider:t,signer:n}),estimateGasPrices:i,estimateTransactionFee:dn({chain:e,isEIP1559Compatible:o,provider:t}),getAddress:()=>n?n.getAddress():void 0,getBalance:Y(e).getBalance,getNetworkParams:Fe(e),isApproved:en({chain:e,provider:t}),sendTransaction:Xe({chain:e,estimateGasPrices:i,isEIP1559Compatible:o,provider:t,signer:n}),signAuthorization:an({signer:n}),signMessage:n?(c)=>n.signMessage(c):void 0,signTypedData:n?async(c)=>{let{domain:l,types:u,value:d}=Oe(c);return await n.signTypedData(l,u,d)}:void 0,transfer:nn({chain:e,estimateAdditionalFee:r,estimateGasPrices:i,isEIP1559Compatible:o,provider:t,signer:n}),validateAddress:Ut}}function Ut(e){try{return ee(e),!0}catch{return!1}}function ne(e){return e instanceof Lt}function ge(e,t,n){return new Ne(e,Le.from(t),n)}function Kt({provider:e}){return function(n,o){return new Ne(n,Le.from(o),e)}}var Ht=["payable","nonpayable"];function qt({abi:e,funcName:t}){let n=e.find((o)=>o.name===t);if(!n)throw new m("toolbox_evm_no_abi_fragment",{funcName:t});return n.stateMutability&&Ht.includes(n.stateMutability)}function Yn(e){return ee(e)}var jt=30000,Re=new WeakMap,Se=()=>{};function Wt(e,t,n){let o=Date.now();for(let[r,i]of e)if(i.held===0&&o-i.at>jt)e.delete(r);let a=e.get(t);if(!a||n>=a.next){let r={at:o,held:1,next:n+1,released:new Set};return e.set(t,r),{floor:r,nonce:n}}a.held+=1;for(let r of[...a.released].sort((i,s)=>i-s))if(a.released.delete(r),r>=n)return{floor:a,nonce:r};return{floor:a,nonce:a.next++}}async function ze({address:e,nonce:t,provider:n}){if(t!==void 0&&t!==null)return{nonce:t,release:Se,settle:Se};let{chainId:o}=await n.getNetwork(),a=Re.get(n)??new Map;Re.set(n,a);let r=`${o}:${e.toLowerCase()}`,i=await n.getTransactionCount(e,"pending"),{floor:s,nonce:c}=Wt(a,r,i),l=!1,u=(d)=>{if(l)return;if(l=!0,s.held-=1,s.at=Date.now(),d)s.released.add(c)};return{nonce:c,release:()=>u(!0),settle:()=>u(!1)}}function Z(e,t=0){if(!e||t>3)return"";if(typeof e==="string")return e.toLowerCase();if(typeof e!=="object")return"";let{error:n,info:o,message:a,shortMessage:r}=e;return[(typeof r==="string"?r:typeof a==="string"?a:"").toLowerCase(),Z(n,t+1),Z(o?.error,t+1)].filter(Boolean).join(" ")}function fe(e){if(D(e,"NONCE_EXPIRED")||D(e,"REPLACEMENT_UNDERPRICED"))return!0;let t=Z(e);return/nonce (?:is )?too low/.test(t)||t.includes("replacement transaction underpriced")}function ye(e){let t=Z(e);return t.includes("already known")||t.includes("known transaction")||t.includes("already imported")}function Ue(e){return D(e,"NETWORK_ERROR")||D(e,"SERVER_ERROR")||D(e,"TIMEOUT")}function Xt(e){return Ue(e)||D(e,"UNSUPPORTED_OPERATION")}function Ke(e){return Ue(e)||ye(e)}function He(e,t){return e.getTransaction(t).then((n)=>n!==null,()=>!1)}async function $t({provider:e,signer:t,txObject:n}){try{let o=pe.from(await t.signTransaction(n)).hash;return o&&await He(e,o)?o:null}catch{return null}}function oe(e,t=!1){return function({value:o,...a}){if(!ne(e))throw new m("toolbox_evm_provider_not_eip1193_compatible");let r={...a,gasPrice:"gasPrice"in a?a.gasPrice:void 0,maxFeePerGas:"maxFeePerGas"in a?a.maxFeePerGas:void 0,maxPriorityFeePerGas:"maxPriorityFeePerGas"in a?a.maxPriorityFeePerGas:void 0},{gasLimit:i,gasPrice:s,maxFeePerGas:c,maxPriorityFeePerGas:l,...u}=r,d={...u,...t&&i!==void 0&&{gas:O(BigInt(i))},...t&&s!==void 0&&{gasPrice:O(BigInt(s))},...t&&c!==void 0&&{maxFeePerGas:O(BigInt(c))},...t&&l!==void 0&&{maxPriorityFeePerGas:O(BigInt(l))},value:O(BigInt(o||0))};return e.send("eth_sendTransaction",[d])}}function Qn(e,t){let n=xe(e,t);if(n)return ee(n.toLowerCase());throw new m("toolbox_evm_invalid_gas_asset_address")}var Jt=Nt.reduce((e,t)=>(e[t]="0x0000000000000000000000000000000000000000",e),{}),Yt={...Jt,[j.Polygon]:"0x0000000000000000000000000000000000001010"},Qt="0x4200000000000000000000000000000000000042";function xe({chain:e,symbol:t,ticker:n},o){try{if(ke({chain:e,symbol:t}))return Yt[o];if(e===j.Optimism&&t==="OP")return Qt;return ee(t.slice(n.length+1).replace(/^0X/,""))}catch{return null}}function W({provider:e}){return async({contractAddress:t,abi:n,funcName:o,funcParams:a=[],txOverrides:r})=>{let i=await ge(t,n,e).getFunction(o).populateTransaction(...a.concat(r).filter((s)=>typeof s<"u"));return{...i,value:O(BigInt(i.value||0))}}}function X({chain:e,provider:t,isEIP1559Compatible:n=!0}){return De(e).with(j.Gnosis,()=>async function(){try{let{gasPrice:a,maxPriorityFeePerGas:r}=await t.getFeeData();if(!a||r===null)throw new m("toolbox_evm_no_fee_data");return{[y.Average]:{maxFeePerGas:M(a,y.Average),maxPriorityFeePerGas:M(r,y.Average)},[y.Fast]:{maxFeePerGas:M(a,y.Fast),maxPriorityFeePerGas:M(r,y.Fast)},[y.Fastest]:{maxFeePerGas:M(a,y.Fastest),maxPriorityFeePerGas:M(r,y.Fastest)}}}catch(a){throw new m("toolbox_evm_gas_estimation_error",{error:a.msg??a.toString()})}}).with(j.Arbitrum,()=>async function(){try{let{gasPrice:a}=await t.getFeeData();if(!a)throw new m("toolbox_evm_no_fee_data");let r=a*12n/10n;return{[y.Average]:{gasPrice:r},[y.Fast]:{gasPrice:M(r,y.Fast)},[y.Fastest]:{gasPrice:M(r,y.Fastest)}}}catch(a){throw new m("toolbox_evm_gas_estimation_error",{error:a.msg??a.toString()})}}).otherwise(()=>async function(){try{let{maxFeePerGas:a,maxPriorityFeePerGas:r,gasPrice:i}=await t.getFeeData();if(n){if(a===null||r===null)throw new m("toolbox_evm_no_fee_data");return{[y.Average]:{maxFeePerGas:a,maxPriorityFeePerGas:r},[y.Fast]:{maxFeePerGas:M(a,y.Fast),maxPriorityFeePerGas:M(r,y.Fast)},[y.Fastest]:{maxFeePerGas:M(a,y.Fastest),maxPriorityFeePerGas:M(r,y.Fastest)}}}if(!i)throw new m("toolbox_evm_no_gas_price");return{[y.Average]:{gasPrice:i},[y.Fast]:{gasPrice:M(i,y.Fast)},[y.Fastest]:{gasPrice:M(i,y.Fastest)}}}catch(a){throw new m("toolbox_evm_gas_estimation_error",{error:a.msg??a.toString()})}})}async function Zt({chain:e,contract:t,contractProvider:n,feeOption:o,funcName:a,funcParams:r,isEIP1559Compatible:i,provider:s,signer:c,txOverrides:l}){let u=l?.from||await c.getAddress();if(!u)throw new m("toolbox_evm_no_signer_address");let d=t.connect(c),p=X({chain:e,isEIP1559Compatible:i,provider:s}),[{maxFeePerGas:b,maxPriorityFeePerGas:f,gasPrice:P},A]=await Promise.all([p().then((_)=>_[o]),t.getFunction(a).estimateGas(...r,l)]),C=typeof u==="string"?u:await zt(u,n),{nonce:G,release:R,settle:k}=await ze({address:C,nonce:l?.nonce,provider:c.provider??s});try{let _=await d[a](...r,{...l,gasLimit:A,gasPrice:P,maxFeePerGas:b,maxPriorityFeePerGas:f,nonce:G});return typeof _?.hash==="string"?_?.hash:_}catch(_){if(fe(_)){let E=l?.nonce!=null?"caller":"pending",w={address:C,error:_,nonce:G,nonceSource:E};throw new m({errorKey:"toolbox_evm_nonce_conflict",info:w},w)}if(!Ke(_))R();throw _}finally{k()}}function ae({provider:e,isEIP1559Compatible:t,signer:n,chain:o}){return async function({callProvider:r,contractAddress:i,abi:s,funcName:c,funcParams:l=[],txOverrides:u={},feeOption:d=y.Fast}){let p=r||e;if(!i)throw new m("toolbox_evm_invalid_params",{error:"contractAddress must be provided"});let b=qt({abi:s,funcName:c});if(b&&ne(p)&&n){let A=W({chain:o,provider:p}),C=u?.from||await n?.getAddress(),G=await A({abi:s,contractAddress:i,funcName:c,funcParams:l,txOverrides:{...u,from:C}});return oe(p)(G)}let f=ge(i,s,p);if(b){if(!n)throw new m("toolbox_evm_no_signer");return Zt({chain:o,contract:f,contractProvider:p,feeOption:d,funcName:c,funcParams:l,isEIP1559Compatible:t,provider:e,signer:n,txOverrides:u})}let P=await f[c]?.(...l);return typeof P?.hash==="string"?P?.hash:P}}function qe({provider:e,chain:t}){return function({assetAddress:o,spenderAddress:a,from:r}){return ae({chain:t,isEIP1559Compatible:!0,provider:e})({abi:K,contractAddress:o,funcName:"allowance",funcParams:[r,a]})}}function en({provider:e,chain:t}){return async function({assetAddress:o,spenderAddress:a,from:r,amount:i=be}){let s=await qe({chain:t,provider:e})({assetAddress:o,from:r,spenderAddress:a});return Q.fromBigInt(s).gte(Q.fromBigInt(BigInt(i)))}}function tn({signer:e,isEIP1559Compatible:t=!0,provider:n,chain:o}){return async function({assetAddress:r,spenderAddress:i,feeOptionKey:s=y.Fast,amount:c,gasLimitFallback:l,from:u,nonce:d}){let p=[i,BigInt(c||be)],b=await e?.getAddress()||u,f={abi:K,contractAddress:r,funcName:"approve",funcParams:p,signer:e,txOverrides:{from:b}};if(ne(n)){let A=W({chain:o,provider:n}),C=oe(n),G=await A(f);return C(G)}return ae({chain:o,isEIP1559Compatible:t,provider:n,signer:e})({...f,feeOption:s,funcParams:p,txOverrides:{from:b,gasLimit:l?BigInt(l.toString()):void 0,nonce:d}})}}function nn({chain:e,estimateGasPrices:t,estimateAdditionalFee:n,signer:o,isEIP1559Compatible:a=!0,provider:r}){return async function({assetValue:s,memo:c,recipient:l,feeOptionKey:u=y.Fast,sender:d,sweep:p,...b}){let f=d||await o?.getAddress(),P=Xe({chain:e,estimateGasPrices:t,isEIP1559Compatible:a,provider:r,signer:o});if(!f)throw new m("toolbox_evm_no_from_address");let A=await $e({chain:e,estimateAdditionalFee:n,estimateGasPrices:t,isEIP1559Compatible:a,provider:r,signer:o})({assetValue:s,feeOptionKey:u,memo:c,recipient:l,sender:f,sweep:p,...b});return P({...A,feeOptionKey:u,sweep:p})}}function je({provider:e,signer:t}){return function({contractAddress:o,abi:a,funcName:r,funcParams:i=[],txOverrides:s}){if(!o)throw new m("toolbox_evm_no_contract_address");let c=ge(o,a,e);return t?c.connect(t).getFunction(r).estimateGas(...i,s):c.getFunction(r).estimateGas(...i,s)}}function on({provider:e,signer:t}){return async function({assetValue:o,recipient:a,memo:r,data:i,sender:s,funcName:c,funcParams:l,txOverrides:u}){let d=o.bigIntValue,p=o.isGasAsset?null:xe(o,o.chain);if(p&&c)return je({provider:e,signer:t})({abi:K,contractAddress:p,funcName:c,funcParams:l,txOverrides:u});let{hexlify:b,toUtf8Bytes:f}=await import("ethers");return e.estimateGas({data:i?i:r?b(f(r)):void 0,from:s,to:a,value:d})}}function an({signer:e}){if(!e)return;return(t)=>Me(e,t)}var We=(e)=>e.type===4||(e.authorizations?.length??0)>0,rn=(e)=>!We(e)&&(e.type===2||!!e.maxFeePerGas||!!e.maxPriorityFeePerGas),sn=(e,t=!0)=>{if(We(e))return"eip7702";if(rn(e))return"eip1559";if(e.gasPrice!=null)return"legacy";return t?"eip1559":"legacy"};function cn(e,t){if(e==="legacy"){if(t.gasPrice===void 0)throw new m("toolbox_evm_no_fee_data");return{gasPrice:O(t.gasPrice)}}if(t.maxFeePerGas===void 0||t.maxPriorityFeePerGas===void 0)throw new m("toolbox_evm_no_fee_data");return{maxFeePerGas:O(t.maxFeePerGas),maxPriorityFeePerGas:O(t.maxPriorityFeePerGas)}}function Xe({chain:e,estimateGasPrices:t,provider:n,signer:o,isEIP1559Compatible:a=!0}){return async function({feeOptionKey:i=y.Fast,sweep:s,...c}){let{from:l,to:u,data:d,value:p,...b}=c;if(!o)throw new m("toolbox_evm_no_signer");if(!u)throw new m("toolbox_evm_no_to_address");let f={...b,data:d||"0x",from:l,to:u,value:BigInt(p||0)};if(ne(n))return oe(n,s)(f);let P=l||await o.getAddress(),{chainId:A}=await n.getNetwork(),C=o.provider??n,{nonce:G,release:R,settle:k}=await ze({address:P,nonce:c.nonce,provider:C}),_=async()=>{let E=sn(f,a);if(E==="eip7702")Be(f.authorizations||[],A);let w=De(E).with("eip7702",()=>4).with("eip1559",()=>2).otherwise(()=>0),I={...f,chainId:A,nonce:G,type:w,...E==="eip7702"&&{authorizationList:f.authorizations}},F=t??X({chain:e,isEIP1559Compatible:a,provider:n}),V=(E==="legacy"?f.gasPrice!==void 0:f.maxFeePerGas!==void 0&&f.maxPriorityFeePerGas!==void 0)?{}:cn(E,(await F())[i]),h;try{h=O(f.gasLimit?BigInt(f.gasLimit):await n.estimateGas(I)*11n/10n)}catch(B){throw new m("toolbox_evm_error_estimating_gas_limit",{error:B})}return{...I,gasLimit:h,...V}};try{let E=await _().catch((w)=>{throw R(),w});try{return(await o.sendTransaction(E)).hash}catch(w){let I=c.nonce!=null?"caller":"pending",F={address:P,error:w,nonce:G,nonceSource:I};if(fe(w))throw new m({errorKey:"toolbox_evm_nonce_conflict",info:F},F);if(ye(w)){let h=await $t({provider:C,signer:o,txObject:{...E,from:P}});if(h)return h;throw new m({errorKey:"toolbox_evm_tx_already_known",info:F},F)}if(!Xt(w))throw R(),new m({errorKey:"toolbox_evm_error_sending_transaction",info:F},F);let N=D(w,"UNSUPPORTED_OPERATION"),V;try{V=await o.signTransaction({...E,from:P})}catch(h){if(N)R();let B={...F,fallbackError:h};throw new m({errorKey:"toolbox_evm_error_sending_transaction",info:B},B)}try{return(await C.broadcastTransaction(V)).hash}catch(h){let B={...F,fallbackError:h};if(ye(h)){let z=pe.from(V).hash;if(z)return z}if(fe(h)){let z=pe.from(V).hash;if(z&&await He(C,z))return z;throw new m({errorKey:"toolbox_evm_nonce_conflict",info:B},B)}if(N&&!Ke(h))R();throw new m({errorKey:"toolbox_evm_error_sending_transaction",info:B},B)}}}finally{k()}}}function L(e,t){throw new m({errorKey:"toolbox_sweep_amount_too_low",info:{balance:e.toString(),fee:t.toString()}})}function un(e,t){if(t){if(e.maxFeePerGas===void 0||e.maxPriorityFeePerGas===void 0)throw new m("toolbox_evm_no_fee_data");return{feeFields:{maxFeePerGas:e.maxFeePerGas,maxPriorityFeePerGas:e.maxPriorityFeePerGas},feePerGas:e.maxFeePerGas}}if(e.gasPrice===void 0)throw new m("toolbox_evm_no_fee_data");return{feeFields:{gasPrice:e.gasPrice},feePerGas:e.gasPrice}}function Pe(e,t){if(e>t)return e;return t}function ln(e){return Dt(e).reduce((t,n)=>t+(n===0?4n:16n),21000n)}function me(e){let n=(e instanceof Error?e.message:String(e)).toLowerCase();return n.includes("insufficient funds")||n.includes("insufficient balance")||n.includes("gas required exceeds allowance")}async function mn({balance:e,estimateAdditionalFee:t,feeOptionKey:n,l2Reserve:o,sweepTx:a,valueBeforeL1Fee:r}){if(!t)return 0n;let i=await t({...a,value:r})??0n,s=M(i,n),c=r-s;if(c<=0n)L(e,o+s);let l=await t({...a,value:c})??i;return M(Pe(i,l),n)}async function pn({chain:e,data:t,estimateGasPrices:n,estimateAdditionalFee:o,feeOptionKey:a,from:r,isEIP1559Compatible:i,provider:s,recipient:c,transaction:l}){let u=await s.getBalance(r),d=n??X({chain:e,isEIP1559Compatible:i,provider:s}),{feeFields:p,feePerGas:b}=un((await d())[a],i),f={...l,...p,data:t,from:r,to:c},P=ln(t)*b;if(u-P<=0n)L(u,P);let A=(u-P)/2n,C;try{C=await s.estimateGas({...f,value:A})}catch(h){if(!me(h))throw h;try{C=await s.estimateGas({...f,value:0n})}catch(B){if(me(B))L(u,P);throw B}}let G=C*b;if(u-G<=0n)L(u,G);let _=C*11n/10n*b,E=u>_?u-_:0n,w;try{w=await s.estimateGas({...f,value:E})}catch(h){if(!me(h))throw h;L(u,_)}let I=w*b,F=u-I;if(F<=0n)L(u,I);let N=await mn({balance:u,estimateAdditionalFee:o,feeOptionKey:a,l2Reserve:I,sweepTx:{...f,gasLimit:w},valueBeforeL1Fee:F}),V=F-N;if(V<=0n)L(u,I+N);return{...f,gasLimit:w,value:O(V)}}async function fn({chain:e,contractAddress:t,from:n,provider:o}){let a=await ae({chain:e,provider:o})({abi:K,contractAddress:t,funcName:"balanceOf",funcParams:[n]});if(typeof a!=="bigint")throw new m({errorKey:"toolbox_evm_invalid_transaction",info:{error:"Invalid ERC20 balance"}});return a}function $e({chain:e,estimateAdditionalFee:t,estimateGasPrices:n,isEIP1559Compatible:o=!0,provider:a,signer:r}){return async function({assetValue:s,authorizations:c,memo:l,recipient:u,data:d,feeOptionKey:p=y.Fast,gasLimit:b,sender:f,sweep:P,type:A,maxFeePerGas:C,maxPriorityFeePerGas:G,gasPrice:R,...k}){let _=s.getBaseValue("bigint"),E=f||await r?.getAddress();if(!E)throw new m("toolbox_evm_no_from_address");if(P&&(A===4||(c?.length??0)>0))throw new m({errorKey:"toolbox_not_supported",info:{chain:e,reason:"EIP-7702 sweep transactions are not supported"}});if(ke(s)){let{hexlify:N,toUtf8Bytes:V}=await import("ethers"),h=d||N(V(l||""));if(!P)return{...k,...c!==void 0&&{authorizations:c},data:h,from:E,...b!==void 0&&{gasLimit:b},to:u,...A!==void 0&&{type:A},value:O(_)};return pn({chain:e,data:h,estimateAdditionalFee:t,estimateGasPrices:n,feeOptionKey:p,from:E,isEIP1559Compatible:o,provider:a,recipient:u,transaction:{nonce:k.nonce,type:A}})}let w=xe(s,e);if(!w)throw new m("toolbox_evm_no_contract_address");let I=W({chain:e,provider:a}),F=P?await fn({chain:e,contractAddress:w,from:E,provider:a}):_;if(P&&F<=0n)throw new m({errorKey:"toolbox_sweep_amount_too_low",info:{asset:s.toString(),balance:F.toString()}});return I({abi:K,contractAddress:w,funcName:"transfer",funcParams:[u,F],txOverrides:{from:E,gasLimit:b,gasPrice:R,maxFeePerGas:C,maxPriorityFeePerGas:G,nonce:k.nonce}})}}function yn({provider:e,signer:t,chain:n}){return async function({assetAddress:a,spenderAddress:r,amount:i,from:s,nonce:c}){let l=await t?.getAddress()||s,u=W({chain:n,provider:e}),d=["bigint","number"].includes(typeof i)?i:i||be;return await u({abi:K,contractAddress:a,funcName:"approve",funcParams:[r,BigInt(d)],txOverrides:{from:l,nonce:c}})}}function dn({provider:e,isEIP1559Compatible:t=!0,chain:n}){return async function({feeOption:a=y.Fast,...r}){let s=await X({chain:n,isEIP1559Compatible:t,provider:e})(),c=await e.estimateGas(r),l=kt.from({chain:n}),{gasPrice:u,maxFeePerGas:d,maxPriorityFeePerGas:p}=s[a];if(!t&&u)return l.set(Q.fromBigInt(u*c,l.decimal));if(d&&p){let b=(d+p)*c;return l.set(Q.fromBigInt(b,l.decimal))}throw new m("toolbox_evm_no_gas_price")}}import{applyFeeMultiplierToBigInt as H,Chain as Qe,derivationPathToString as bn,FeeOption as S,getChainConfig as gn,resolveDerivationPath as xn,SwapKitError as q}from"@swapkit/helpers";import{Contract as Pn,HDNodeWallet as Tn}from"ethers";import{match as wn,P as Ye}from"ts-pattern";var Je=[{inputs:[{internalType:"address",name:"_owner",type:"address"}],stateMutability:"nonpayable",type:"constructor"},{anonymous:!1,inputs:[{indexed:!1,internalType:"uint256",name:"",type:"uint256"}],name:"DecimalsUpdated",type:"event"},{anonymous:!1,inputs:[{indexed:!1,internalType:"uint256",name:"",type:"uint256"}],name:"GasPriceUpdated",type:"event"},{anonymous:!1,inputs:[{indexed:!1,internalType:"uint256",name:"",type:"uint256"}],name:"L1BaseFeeUpdated",type:"event"},{anonymous:!1,inputs:[{indexed:!1,internalType:"uint256",name:"",type:"uint256"}],name:"OverheadUpdated",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"previousOwner",type:"address"},{indexed:!0,internalType:"address",name:"newOwner",type:"address"}],name:"OwnershipTransferred",type:"event"},{anonymous:!1,inputs:[{indexed:!1,internalType:"uint256",name:"",type:"uint256"}],name:"ScalarUpdated",type:"event"},{inputs:[],name:"decimals",outputs:[{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[],name:"gasPrice",outputs:[{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"bytes",name:"_data",type:"bytes"}],name:"getL1Fee",outputs:[{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"bytes",name:"_data",type:"bytes"}],name:"getL1GasUsed",outputs:[{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"uint256",name:"_gasUsed",type:"uint256"}],name:"getOperatorFee",outputs:[{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[],name:"l1BaseFee",outputs:[{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[],name:"overhead",outputs:[{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[],name:"owner",outputs:[{internalType:"address",name:"",type:"address"}],stateMutability:"view",type:"function"},{inputs:[],name:"renounceOwnership",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[],name:"scalar",outputs:[{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"uint256",name:"_decimals",type:"uint256"}],name:"setDecimals",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"uint256",name:"_gasPrice",type:"uint256"}],name:"setGasPrice",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"uint256",name:"_baseFee",type:"uint256"}],name:"setL1BaseFee",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"uint256",name:"_overhead",type:"uint256"}],name:"setOverhead",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"uint256",name:"_scalar",type:"uint256"}],name:"setScalar",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"address",name:"newOwner",type:"address"}],name:"transferOwnership",outputs:[],stateMutability:"nonpayable",type:"function"}];var hn="0x420000000000000000000000000000000000000f";function re(e){return new Pn(hn,Je,e)}function Ze(e){return async function(){let n=re(e);if(n&&"l1BaseFee"in n)return await n?.l1BaseFee();return}}function et(e){return async function({from:n,to:o,nonce:a,...r}){let{Transaction:i}=await import("ethers");if(!o)throw new q("toolbox_evm_invalid_transaction",{error:"Missing to address"});return i.from({...r,authorizationList:r.authorizationList,nonce:a??(n?await e.getTransactionCount(n,"pending"):0),to:o}).unsignedSerialized}}function we(e,t){return async function(o){let a=re(e),r=o.chainId??t??(await e.getNetwork()).chainId,i=await et(e)({...o,chainId:r});if(a&&"getL1Fee"in a){let s=await a.getL1Fee(i);if(typeof s!=="bigint")throw new q({errorKey:"toolbox_evm_invalid_transaction",info:{error:"Invalid OP-stack L1 fee"}});return s}return}}function he(e){return async function(n){let o=re(e);if(o&&"getOperatorFee"in o){let a=await o.getOperatorFee(n);if(typeof a!=="bigint")throw new q({errorKey:"toolbox_evm_invalid_transaction",info:{error:"Invalid OP-stack operator fee"}});return a}return 0n}}function vn(e,t){let n=we(e,t),o=he(e);return async function(r){if(r.gasLimit===void 0||r.gasLimit===null)throw new q({errorKey:"toolbox_evm_invalid_transaction",info:{error:"Missing gas limit for OP-stack fee estimation"}});let[i,s]=await Promise.all([n(r),o(BigInt(r.gasLimit.toString()))]);return(i??0n)+s}}function tt(e){return async function(n){let a=(await e.getFeeData()).gasPrice??0n,r=await e.estimateGas(n);return a*r}}function En(e){return async function(n){let o=await we(e)(n)??0n,a=await tt(e)(n),r=n.gasLimit??await e.estimateGas(n),i=await he(e)(BigInt(r.toString()));return o+a+i}}function _n(e){return async function(n){let o=re(e),a=await et(e)(n);if(o&&"getL1GasUsed"in o)return o.getL1GasUsed(a)}}function Te({feeOption:e,maxFeePerGas:t,maxPriorityFeePerGas:n}){let o=H(t,e),a=H(n,e);return{maxFeePerGas:Pe(o,a),maxPriorityFeePerGas:a}}function Cn(e){return async function(){try{let{maxFeePerGas:n,maxPriorityFeePerGas:o,gasPrice:a}=await e.getFeeData(),r=await Ze(e)(),i=a;if(!(n&&o))throw new q("toolbox_evm_no_fee_data");return{[S.Average]:{gasPrice:i,l1GasPrice:r,...Te({feeOption:S.Average,maxFeePerGas:n,maxPriorityFeePerGas:o})},[S.Fast]:{gasPrice:H(i,S.Fast),l1GasPrice:H(r||0n,S.Fast),...Te({feeOption:S.Fast,maxFeePerGas:n,maxPriorityFeePerGas:o})},[S.Fastest]:{gasPrice:H(i,S.Fastest),l1GasPrice:H(r||0n,S.Fastest),...Te({feeOption:S.Fastest,maxFeePerGas:n,maxPriorityFeePerGas:o})}}}catch(n){throw new q("toolbox_evm_gas_estimation_error",{error:n.msg??n.toString()})}}}function ie(e){return function({provider:n,...o}){let a=wn(o).with({phrase:Ye.string},({phrase:p,derivationPath:b,index:f=0})=>Tn.fromPhrase(p,void 0,bn(xn({chain:e,derivationPath:b,index:f}))).connect(n)).with({signer:Ye.any},({signer:p})=>p).otherwise(()=>{return}),r=Ze(n),i=BigInt(gn(e).chainId),s=we(n,i),c=vn(n,i),l=he(n),u=e===Qe.Optimism?Cn(n):void 0;return{...te({chain:e,estimateAdditionalFee:c,estimateGasPrices:u,provider:n,signer:a}),estimateL1Gas:_n(n),estimateL1GasCost:s,estimateL2GasCost:tt(n),estimateOperatorFee:l,estimateTotalGasCost:En(n),getBalance:Y(e).getBalance,getL1GasPrice:r}}}var nt=ie(Qe.Optimism);function at(e){let t=v(T.Ethereum)(e);async function n(o,a="0x5ba1e12693dc8f9c48aad8770482f4739beed696",r="aggregate",i=An.Fast){let s=await t.createContractTxObject({abi:Ie,contractAddress:a,funcName:r,funcParams:[o]});return t.sendTransaction({...s,feeOptionKey:i})}return{...t,multicall:n}}var rt=v(T.Adi),it=v(T.Arbitrum),st=v(T.Arc),ct=v(T.Aurora),ut=v(T.Avalanche),lt=ie(T.Base),mt=v(T.Berachain),pt=v(T.BinanceSmartChain),ft=v(T.Botanix),yt=v(T.Core),dt=v(T.Corn),bt=v(T.Cronos),gt=v(T.Gnosis),xt=v(T.Robinhood),Pt=v(T.Hyperevm),Tt=v(T.Linea),wt=v(T.Polygon),ht=v(T.MegaETH),vt=v(T.Monad),Et=v(T.Plasma),_t=v(T.Sonic),Ct=ie(T.Unichain),Ft=v(T.XLayer);function v(e){return function({provider:n,...o}){let a=Ae(e),r=On(o).with({phrase:ot.string},({phrase:s,derivationPath:c,index:l=0})=>Gn.fromPhrase(s,void 0,Fn(Mn({chain:e,derivationPath:c,index:l}))).connect(n)).with({signer:ot.any},({signer:s})=>s).otherwise(()=>{return});return te({chain:e,isEIP1559Compatible:a,provider:n,signer:r})}}function Vn(e,t){return In(e).with(x.Adi,()=>rt(t)).with(x.Arbitrum,()=>it(t)).with(x.Arc,()=>st(t)).with(x.Aurora,()=>ct(t)).with(x.Avalanche,()=>ut(t)).with(x.Base,()=>lt(t)).with(x.Berachain,()=>mt(t)).with(x.BinanceSmartChain,()=>pt(t)).with(x.Botanix,()=>ft(t)).with(x.Core,()=>yt(t)).with(x.Corn,()=>dt(t)).with(x.Cronos,()=>bt(t)).with(x.Ethereum,()=>at(t)).with(x.Gnosis,()=>gt(t)).with(x.Hyperevm,()=>Pt(t)).with(x.Linea,()=>Tt(t)).with(x.MegaETH,()=>ht(t)).with(x.Monad,()=>vt(t)).with(x.Optimism,()=>nt(t)).with(x.Plasma,()=>Et(t)).with(x.Polygon,()=>wt(t)).with(x.Robinhood,()=>xt(t)).with(x.Sonic,()=>_t(t)).with(x.Unichain,()=>Ct(t)).with(x.XLayer,()=>Ft(t)).exhaustive()}async function To(e,t){let n={...t,provider:t?.provider||Ce(e)};return Vn(e,n)}
2
+ export{Y as b,Kn as c,It as d,Nn as e,Ce as f,O as g,Fe as h,Ae as i,Me as j,St as k,Ge as l,Oe as m,Ln as n,Be as o,be as p,te as q,Ut as r,ne as s,ge as t,Kt as u,qt as v,Yn as w,oe as x,Qn as y,Yt as z,xe as A,W as B,X as C,We as D,rn as E,sn as F,Pe as G,Te as H,ie as I,nt as J,at as K,rt as L,it as M,st as N,ct as O,ut as P,lt as Q,mt as R,pt as S,ft as T,yt as U,dt as V,bt as W,gt as X,xt as Y,Pt as Z,Tt as _,wt as $,ht as aa,vt as ba,Et as ca,_t as da,Ct as ea,Ft as fa,Vn as ga,To as ha};
@@ -1 +1 @@
1
- import{a as ia}from"../../chunk-qsbf0z90.js";import{$ as _,A as z,B as A,C as B,D as C,E as D,F as E,G as F,H as G,I as H,J as I,K as J,L as K,M as L,N as M,O as N,P as O,Q as P,R as Q,S as R,T as S,U as T,V as U,W as V,X as W,Y as X,Z as Y,_ as Z,aa,b as a,ba,c as b,ca,d as c,da,e as d,ea,f as e,fa,g as f,ga,h as g,ha,i as h,j as i,k as j,l as k,m as l,n as m,o as n,p as o,q as p,r as q,s as r,t as s,u as t,v as u,w as v,x as w,y as x,z as y}from"../../chunk-2q4pxsyg.js";import"../../chunk-qk8kg62t.js";import"../../chunk-pz8xe0qj.js";export{K as ADIToolbox,L as ARBToolbox,M as ARCToolbox,N as AURORAToolbox,O as AVAXToolbox,P as BASEToolbox,Q as BERAToolbox,R as BSCToolbox,p as BaseEVMToolbox,S as BotanixToolbox,T as COREToolbox,U as CORNToolbox,V as CROToolbox,y as ContractAddress,J as ETHToolbox,ia as EthNetwork,W as GNOToolbox,X as HOODToolbox,Y as HYPEREVMToolbox,Z as LINEAToolbox,_ as MATICToolbox,o as MAX_APPROVAL,aa as MEGAETHToolbox,ba as MONADToolbox,I as OPToolbox,ca as PLASMAToolbox,da as SONICToolbox,ea as UNIToolbox,fa as XLayerToolbox,k as buildEIP712DomainType,s as createContract,b as createCustomEvmApi,H as createOPStackToolbox,x as getChecksumAddressFromAsset,t as getCreateContract,A as getCreateContractTxObject,w as getEIP1193SendTransaction,E as getEVMTxType,B as getEstimateGasPrices,a as getEvmApi,ga as getEvmToolbox,ha as getEvmToolboxAsync,e as getFallbackProvider,h as getIsEIP1559Compatible,g as getNetworkParams,d as getProvider,c as getProviderSync,z as getTokenAddress,r as isBrowserProvider,D as isEIP1559Transaction,C as isEIP7702Transaction,u as isStateChangingCall,F as maxBigInt,l as normalizeTypedDataForSigner,m as parseEIP712FromEVMTx,G as scaleEIP1559Fees,i as signAuthorization,v as toChecksumAddress,f as toHexString,j as validateAuthorization,n as validateAuthorizations,q as validateEVMAddress};
1
+ import{a as ia}from"../../chunk-qsbf0z90.js";import{$ as _,A as z,B as A,C as B,D as C,E as D,F as E,G as F,H as G,I as H,J as I,K as J,L as K,M as L,N as M,O as N,P as O,Q as P,R as Q,S as R,T as S,U as T,V as U,W as V,X as W,Y as X,Z as Y,_ as Z,aa,b as a,ba,c as b,ca,d as c,da,e as d,ea,f as e,fa,g as f,ga,h as g,ha,i as h,j as i,k as j,l as k,m as l,n as m,o as n,p as o,q as p,r as q,s as r,t as s,u as t,v as u,w as v,x as w,y as x,z as y}from"../../chunk-6fcz98xe.js";import"../../chunk-qk8kg62t.js";import"../../chunk-pz8xe0qj.js";export{K as ADIToolbox,L as ARBToolbox,M as ARCToolbox,N as AURORAToolbox,O as AVAXToolbox,P as BASEToolbox,Q as BERAToolbox,R as BSCToolbox,p as BaseEVMToolbox,S as BotanixToolbox,T as COREToolbox,U as CORNToolbox,V as CROToolbox,y as ContractAddress,J as ETHToolbox,ia as EthNetwork,W as GNOToolbox,X as HOODToolbox,Y as HYPEREVMToolbox,Z as LINEAToolbox,_ as MATICToolbox,o as MAX_APPROVAL,aa as MEGAETHToolbox,ba as MONADToolbox,I as OPToolbox,ca as PLASMAToolbox,da as SONICToolbox,ea as UNIToolbox,fa as XLayerToolbox,k as buildEIP712DomainType,s as createContract,b as createCustomEvmApi,H as createOPStackToolbox,x as getChecksumAddressFromAsset,t as getCreateContract,A as getCreateContractTxObject,w as getEIP1193SendTransaction,E as getEVMTxType,B as getEstimateGasPrices,a as getEvmApi,ga as getEvmToolbox,ha as getEvmToolboxAsync,e as getFallbackProvider,h as getIsEIP1559Compatible,g as getNetworkParams,d as getProvider,c as getProviderSync,z as getTokenAddress,r as isBrowserProvider,D as isEIP1559Transaction,C as isEIP7702Transaction,u as isStateChangingCall,F as maxBigInt,l as normalizeTypedDataForSigner,m as parseEIP712FromEVMTx,G as scaleEIP1559Fees,i as signAuthorization,v as toChecksumAddress,f as toHexString,j as validateAuthorization,n as validateAuthorizations,q as validateEVMAddress};
@@ -1 +1 @@
1
- import"../../chunk-qsbf0z90.js";import{m as we,r as Ue}from"../../chunk-2q4pxsyg.js";import"../../chunk-qk8kg62t.js";import"../../chunk-pz8xe0qj.js";function St({builder:e,grouping:t="na",orders:n}){return{builder:e,grouping:t,orders:n,type:"order"}}function Tt({cancels:e}){return{cancels:e,type:"cancel"}}function wt({cancels:e}){return{cancels:e,type:"cancelByCloid"}}function Ut({oid:e,order:t}){return{oid:e,order:t,type:"modify"}}function _t({modifies:e}){return{modifies:e,type:"batchModify"}}function Dt({asset:e,isCross:t,leverage:n}){return{asset:e,isCross:t,leverage:n,type:"updateLeverage"}}function Ot({asset:e,isBuy:t,ntli:n}){return{asset:e,isBuy:t,ntli:n,type:"updateIsolatedMargin"}}function kt({asset:e,leverage:t}){return{asset:e,leverage:t,type:"topUpIsolatedOnlyMargin"}}function Pt({time:e}){return{time:e,type:"scheduleCancel"}}function vt({amount:e,hyperliquidChain:t,nonce:n,signatureChainId:r,toPerp:i}){return{amount:e,hyperliquidChain:t,nonce:n,signatureChainId:r,toPerp:i,type:"usdClassTransfer"}}function se({amount:e,destination:t,destinationDex:n,fromSubAccount:r,hyperliquidChain:i,nonce:o,signatureChainId:s,sourceDex:p,token:u}){return{amount:e,destination:t,destinationDex:n,fromSubAccount:r,hyperliquidChain:i,nonce:o,signatureChainId:s,sourceDex:p,token:u,type:"sendAsset"}}function Rt({agentAddress:e,agentName:t,hyperliquidChain:n,nonce:r,signatureChainId:i}){return{agentAddress:e,agentName:t,hyperliquidChain:n,nonce:r,signatureChainId:i,type:"approveAgent"}}function It({builder:e,hyperliquidChain:t,maxFeeRate:n,nonce:r,signatureChainId:i}){return{builder:e,hyperliquidChain:t,maxFeeRate:n,nonce:r,signatureChainId:i,type:"approveBuilderFee"}}function qt({hyperliquidChain:e,isUndelegate:t,nonce:n,signatureChainId:r,validator:i,wei:o}){return{hyperliquidChain:e,isUndelegate:t,nonce:n,signatureChainId:r,type:"tokenDelegate",validator:i,wei:o}}import{SwapKitError as Ve,SwapKitNumber as Qe}from"@swapkit/helpers";import{HYPERCORE_USDC_TOKEN_ID as B}from"@swapkit/helpers/api";import{SwapKitError as V}from"@swapkit/helpers";import{keccak256 as Me,Signature as Fe}from"ethers";var I="0x0000000000000000000000000000000000000000",D="0xa4b1",q={name:"HyperliquidSignTransaction",verifyingContract:I,version:"1"},Le={chainId:1337,name:"Exchange",verifyingContract:I,version:"1"},je={Agent:[{name:"source",type:"string"},{name:"connectionId",type:"bytes32"}]},pe="Mainnet",Q={approveAgent:[{name:"hyperliquidChain",type:"string"},{name:"agentAddress",type:"address"},{name:"agentName",type:"string"},{name:"nonce",type:"uint64"}],approveBuilderFee:[{name:"hyperliquidChain",type:"string"},{name:"maxFeeRate",type:"string"},{name:"builder",type:"address"},{name:"nonce",type:"uint64"}],sendAsset:[{name:"hyperliquidChain",type:"string"},{name:"destination",type:"string"},{name:"sourceDex",type:"string"},{name:"destinationDex",type:"string"},{name:"token",type:"string"},{name:"amount",type:"string"},{name:"fromSubAccount",type:"string"},{name:"nonce",type:"uint64"}],tokenDelegate:[{name:"hyperliquidChain",type:"string"},{name:"validator",type:"address"},{name:"wei",type:"uint64"},{name:"isUndelegate",type:"bool"},{name:"nonce",type:"uint64"}],usdClassTransfer:[{name:"hyperliquidChain",type:"string"},{name:"amount",type:"string"},{name:"toPerp",type:"bool"},{name:"nonce",type:"uint64"}]},G={approveAgent:"HyperliquidTransaction:ApproveAgent",approveBuilderFee:"HyperliquidTransaction:ApproveBuilderFee",sendAsset:"HyperliquidTransaction:SendAsset",tokenDelegate:"HyperliquidTransaction:TokenDelegate",usdClassTransfer:"HyperliquidTransaction:UsdClassTransfer"},Ee=new TextEncoder;function b(...e){let t=e.reduce((i,o)=>i+o.length,0),n=new Uint8Array(t),r=0;for(let i of e)n.set(i,r),r+=i.length;return n}function Je(e,t,n){if(n<t)return new Uint8Array([e+n]);if(n<=255)return new Uint8Array([e+t,n]);if(n<=65535)return new Uint8Array([e+t+1,n>>8,n&255]);return new Uint8Array([e+t+2,n>>>24&255,n>>>16&255,n>>>8&255,n&255])}function v(e,t){let n=new Uint8Array(t),r=e;for(let i=t-1;i>=0;i-=1)n[i]=Number(r&0xffn),r>>=8n;return n}function ae(e){if(e>=0n){if(e<=0x7fn)return new Uint8Array([Number(e)]);if(e<=0xffn)return new Uint8Array([204,Number(e)]);if(e<=0xffffn)return b(new Uint8Array([205]),v(e,2));if(e<=0xffffffffn)return b(new Uint8Array([206]),v(e,4));return b(new Uint8Array([207]),v(e,8))}if(e>=-32n)return new Uint8Array([256+Number(e)]);if(e>=-128n)return new Uint8Array([208,256+Number(e)]);if(e>=-32768n)return b(new Uint8Array([209]),v(BigInt.asUintN(16,e),2));if(e>=-2147483648n)return b(new Uint8Array([210]),v(BigInt.asUintN(32,e),4));return b(new Uint8Array([211]),v(BigInt.asUintN(64,e),8))}function ce(e){let t=Ee.encode(e);if(t.length<32)return b(new Uint8Array([160+t.length]),t);return b(Je(217,0,t.length),t)}function ze(e){let t=e.map((r)=>Y(r)),n=e.length<16?new Uint8Array([144+e.length]):e.length<=65535?new Uint8Array([220,e.length>>8,e.length&255]):new Uint8Array([221,e.length>>>24&255,e.length>>>16&255,e.length>>>8&255,e.length&255]);return b(n,...t)}function Ke(e){let t=Object.entries(e).filter(([,r])=>typeof r<"u"),n=t.length<16?new Uint8Array([128+t.length]):t.length<=65535?new Uint8Array([222,t.length>>8,t.length&255]):new Uint8Array([223,t.length>>>24&255,t.length>>>16&255,t.length>>>8&255,t.length&255]);return b(n,...t.flatMap(([r,i])=>[ce(r),Y(i)]))}function Y(e){if(e===null)return new Uint8Array([192]);if(typeof e==="boolean")return new Uint8Array([e?195:194]);if(typeof e==="string")return ce(e);if(typeof e==="number"){if(!Number.isFinite(e)||!Number.isInteger(e))throw new V("helpers_invalid_params",{message:"Hyperliquid msgpack only supports integers"});return ae(BigInt(e))}if(typeof e==="bigint")return ae(e);if(e instanceof Uint8Array){let t=e.length<=255?new Uint8Array([196,e.length]):e.length<=65535?new Uint8Array([197,e.length>>8,e.length&255]):new Uint8Array([198,e.length>>>24&255,e.length>>>16&255,e.length>>>8&255,e.length&255]);return b(t,e)}if(Array.isArray(e))return ze(e);if(typeof e==="object")return Ke(e);throw new V("helpers_invalid_params",{message:`Unsupported Hyperliquid msgpack value: ${String(e)}`})}function We(e){let t=e.startsWith("0x")?e.slice(2):e;if(t.length%2!==0||/[^a-fA-F0-9]/u.test(t))throw new V("helpers_invalid_params",{hexValue:e});let n=new Uint8Array(t.length/2);for(let r=0;r<t.length;r+=2)n[r/2]=Number.parseInt(t.slice(r,r+2),16);return n}function de(e){return{domain:Le,message:{connectionId:e,source:"a"},primaryType:"Agent",types:{Agent:[...je.Agent]}}}function ye(e){let t=G[e.type],n=Q[e.type],{signatureChainId:r,type:i,...o}=e,s=Number.parseInt(r||D,16);return{domain:{...q,chainId:s},message:{...o,hyperliquidChain:o.hyperliquidChain||pe},primaryType:t,types:{[t]:n}}}function ue(e){let t=Fe.from(e);return{r:t.r,s:t.s,v:t.v}}function le(e,t,{expiresAfter:n,vaultAddress:r}={}){let i=Y(e),o=v(BigInt(t),8),s=r?b(new Uint8Array([1]),We(r.toLowerCase())):new Uint8Array([0]),p=typeof n==="number"?b(new Uint8Array([0]),v(BigInt(n),8)):new Uint8Array;return Me(b(i,o,s,p))}function ge(e){let t=e.hyperliquidChain||pe;switch(e.type){case"approveAgent":return{...e,agentAddress:e.agentAddress.toLowerCase(),hyperliquidChain:t};case"approveBuilderFee":return{...e,builder:e.builder.toLowerCase(),hyperliquidChain:t};case"sendAsset":return{...e,destination:e.destination.toLowerCase(),fromSubAccount:e.fromSubAccount.toLowerCase(),hyperliquidChain:t};case"tokenDelegate":return{...e,hyperliquidChain:t,validator:e.validator.toLowerCase()};case"usdClassTransfer":return{...e,hyperliquidChain:t};default:return e}}var fe=Number.parseInt(D,16),Ge=new Set(["chainId","name","verifyingContract","version"]),me=/^0x[0-9a-fA-F]{40}$/,X=Q.sendAsset;var c=(e)=>{throw new Ve("toolbox_hypercore_payload_mismatch",{problems:[e]})};function Ce(e){try{return new URL(e)}catch{return}}function Ae({action:e,allowedEndpoints:t,expectedAmount:n,expectedDestination:r,expectedDestinationDex:i,expectedFromSubAccount:o,expectedSourceDex:s,expectedToken:p,submitTo:u,typedData:S}){let{domain:h,message:m,primaryType:H,types:a}=S,d=G.sendAsset;if(H!==d)c(`primaryType is ${JSON.stringify(H)}, expected "${d}"`);if(e.type!=="sendAsset")c(`action.type is ${JSON.stringify(e.type)}, expected "sendAsset"`);let f=X.map(({name:y})=>y),x=new Set([...f,"signatureChainId","type"]),C=Object.keys(e).filter((y)=>!x.has(y));if(C.length)c(`action carries unexpected keys: ${C.join(", ")}`);for(let{name:y}of X)if(m[y]!==e[y])c(`${y}: signed ${JSON.stringify(m[y])} != submitted ${JSON.stringify(e[y])}`);let g=Object.keys(m),T=g.filter((y)=>!f.includes(y)),_=f.filter((y)=>!g.includes(y));if(T.length||_.length){let y=[T.length?`declares undeclared keys [${T.join(",")}]`:"",_.length?`is missing keys [${_.join(",")}]`:""].filter(Boolean).join(" / ");c(`message ${y}`)}let w=X.map(({name:y,type:W})=>`${y}:${W}`).join(","),R=(a[d]??[]).map(({name:y,type:W})=>`${y}:${W}`).join(",");if(R!==w)c(`types.${d} is [${R}], expected [${w}]`);let P=Object.keys(a).filter((y)=>y!==d&&y!=="EIP712Domain");if(P.length)c(`types carries unexpected entries: ${P.join(", ")}`);if(Number(h.chainId)!==fe)c(`domain.chainId is ${h.chainId}, expected ${fe} (Arbitrum)`);if(h.name!==q.name)c(`domain.name is ${JSON.stringify(h.name)}, expected "${q.name}"`);if(h.version!==q.version)c(`domain.version is ${JSON.stringify(h.version)}, expected "${q.version}"`);if(h.verifyingContract!==I)c(`domain.verifyingContract is ${h.verifyingContract}, expected the zero address`);let L=Object.keys(h).filter((y)=>!Ge.has(y));if(L.length)c(`domain carries unexpected keys: ${L.join(", ")}`);if(typeof e.signatureChainId!=="string"||e.signatureChainId.toLowerCase()!==D)c(`action.signatureChainId is ${JSON.stringify(e.signatureChainId)}, expected "${D}"`);if(e.hyperliquidChain!=="Mainnet")c(`action.hyperliquidChain is ${JSON.stringify(e.hyperliquidChain)}, expected "Mainnet"`);if(typeof e.nonce!=="number"||!Number.isSafeInteger(e.nonce)||e.nonce<=0)c(`action.nonce is ${JSON.stringify(e.nonce)}, expected a positive safe integer`);if(i!==""&&i!=="spot")c(`expectedDestinationDex ${JSON.stringify(i)} is not "" or "spot"`);if(e.destinationDex!==i)c(`action.destinationDex is ${JSON.stringify(e.destinationDex)}, expected ${JSON.stringify(i)}`);if(p!==B)c(`route sell token is ${JSON.stringify(p)}, expected "${B}"`);if(e.token!==p)c(`action.token is ${JSON.stringify(e.token)}, expected route sell token "${p}"`);if(e.sourceDex!==""&&e.sourceDex!=="spot")c(`action.sourceDex is ${JSON.stringify(e.sourceDex)}, expected "" or "spot"`);if(typeof e.sourceDex!=="string"||e.sourceDex!==s)c(`action.sourceDex is ${JSON.stringify(e.sourceDex)}, expected route sourceDex ${JSON.stringify(s)}`);let j=e.fromSubAccount;if(typeof j!=="string"||typeof o!=="string"||j.toLowerCase()!==o.toLowerCase())c(`action.fromSubAccount is ${JSON.stringify(e.fromSubAccount)}, expected ${JSON.stringify(o)}`);if(o&&!me.test(o))c(`expectedFromSubAccount ${JSON.stringify(o)} is not a well-formed 0x address`);if(!n)c("expectedAmount is missing — cannot verify action.amount");let re=!1;try{re=new Qe(String(e.amount)).eqValue(n)}catch{c(`action.amount ${JSON.stringify(e.amount)} is not comparable to ${n}`)}if(!re)c(`action.amount ${JSON.stringify(e.amount)} != route sell amount ${n}`);let z=typeof e.destination==="string"?e.destination:"";if(!me.test(z))c(`action.destination ${JSON.stringify(e.destination)} is not a well-formed 0x address`);if(!r)c("expectedDestination is missing — cannot verify action.destination");if(z.toLowerCase()!==r.toLowerCase())c(`action.destination ${z} != expected destination ${r}`);let ie=Ce(u),K=ie?.origin,oe=t.flatMap((y)=>Ce(y)?.origin??[]);if(ie?.protocol!=="https:")c(`submitTo ${JSON.stringify(u)} must be an https URL`);if(!K||!oe.includes(K))c(`submitTo origin ${K} is not one of the allowed exchange origins [${oe.join(", ")}]`)}import{AssetValue as M,Chain as Ye,derivationPathToString as Xe,getChainConfig as _e,getRPCUrl as Ze,NetworkDerivationPath as et,RequestClient as N,SwapKitError as l,SwapKitNumber as O,updateDerivationPath as tt}from"@swapkit/helpers";import{SwapKitApi as nt}from"@swapkit/helpers/api";import{HDNodeWallet as rt}from"ethers";import{match as it,P as Z}from"ts-pattern";var U=Ye.Hype,{baseDecimal:ee,rpcUrls:he}=_e(U),ot=he[0]?`${he[0]}/exchange`:void 0,st={HYPE:ee,USDC:6,USDT:6},De="Mainnet",at=/^\d+(?:\.\d+)?$/,pt=/^[^:]+:0x[0-9a-fA-F]+$/,ct={spotSend:[{name:"hyperliquidChain",type:"string"},{name:"destination",type:"string"},{name:"token",type:"string"},{name:"amount",type:"string"},{name:"time",type:"uint64"}]},dt={spotSend:"HyperliquidTransaction:SpotSend"};function A(e,t){if(!Ne(e))throw new l(t,{address:e});return e.toLowerCase()}function F(e){if(e===void 0)return;try{return new O(e)}catch{return}}var Oe={retry:{maxRetries:0},timeoutMs:5000};async function k({requestOptions:e,...t}){let n=await E();return N.post(`${n}/info`,{json:t,...e})}function te({dex:e,user:t}){return k({...e?{dex:e}:{},type:"clearinghouseState",user:A(t,"helpers_invalid_params")})}function ke({user:e}){return k({type:"spotClearinghouseState",user:A(e,"helpers_invalid_params")})}function yt({destination:e,sender:t}){let n=A(t,"helpers_invalid_params"),r=A(e,"helpers_invalid_params");return k({requestOptions:Oe,source:n,type:"preTransferCheck",user:r})}function ut({dex:e,user:t}){return k({...e?{dex:e}:{},type:"openOrders",user:A(t,"helpers_invalid_params")})}function lt({dex:e,user:t}){return k({...e?{dex:e}:{},type:"frontendOpenOrders",user:A(t,"helpers_invalid_params")})}function gt({oidOrCloid:e,user:t}){return k({oid:e,type:"orderStatus",user:A(t,"helpers_invalid_params")})}function ft({aggregateByTime:e,user:t}){return k({...typeof e==="boolean"?{aggregateByTime:e}:{},type:"userFills",user:A(t,"helpers_invalid_params")})}function mt({aggregateByTime:e,endTime:t,startTime:n,user:r}){return k({...typeof e==="boolean"?{aggregateByTime:e}:{},...typeof t==="number"?{endTime:t}:{},startTime:n,type:"userFillsByTime",user:A(r,"helpers_invalid_params")})}function He({coin:e,token:t,value:n,spotMeta:r}){if(!n||Number(n)<=0)return null;let i=e?.toUpperCase()||`TOKEN-${t||"UNKNOWN"}`,o=r?.tokens?.find((u)=>u.name===e||t!==void 0&&u.index===Number(t)),s=o?.weiDecimals??st[i]??ee,p=o?`${U}.${i}-${o.name}:${o.tokenId}`:`${U}.${i}`;return new M({decimal:s,identifier:p,value:n})}function Ct(e){let t=new Map;for(let n of e){let r=n.toString({includeSynthProtocol:!0}),i=t.get(r);t.set(r,i?i.add(n):n)}if(![...t.values()].some((n)=>n.isGasAsset||n.ticker==="HYPE")){let n=M.from({chain:U,value:0});t.set(n.toString({includeSynthProtocol:!0}),n)}return[...t.values()]}async function E(){try{return await Ze(U)}catch{let[e]=_e(U).rpcUrls;if(!e)throw new l("helpers_chain_no_public_or_set_rpc_url",{chain:U});return e}}async function J(){return`${await E()}/exchange`}function At(e){let t=dt[e.type],{type:n,...r}=e;return{domain:{chainId:Number.parseInt(e.signatureChainId,16),name:"HyperliquidSignTransaction",verifyingContract:I,version:"1"},message:r,primaryType:t,types:{[t]:ct[n]}}}async function ht({action:e,expiresAfter:t,nonce:n,vaultAddress:r}){let i=n||Date.now(),o=r?A(r,"helpers_invalid_params"):void 0,s=await J(),p=le(e,i,{expiresAfter:t,vaultAddress:o});return{action:e,endpoint:s,expiresAfter:t,nonce:i,typedData:de(p),vaultAddress:o}}async function Pe({action:e,endpoint:t,nonce:n,signatureChainId:r}){let i=n||e.nonce||Date.now(),o=r||e.signatureChainId||D,s=ge({...e,nonce:i,signatureChainId:o});return{action:s,endpoint:t??await J(),nonce:i,typedData:ye(s)}}async function ne({token:e,user:t}){let n=await ke({user:t}),i=(n.spotState?.balances||n.balances||[]).find(({coin:p})=>p&&e.startsWith(`${p}:`)),o=F(i?.total||0),s=F(i?.hold||0);return o&&s?o.sub(s):void 0}async function ve({assetValue:e,sender:t,token:n}){let r=(await ne({token:n,user:t}))?.getValue("string");if(!r||Number(r)<=0)throw new l("toolbox_sweep_amount_too_low",{asset:e.toString(),balance:r||"0"});return r}async function Ht(e){if(e.address&&pt.test(e.address))return e.address;let n=(await k({type:"spotMeta"}))?.tokens?.find(({name:r})=>r?.toUpperCase()===e.ticker.toUpperCase());if(n)return`${n.name}:${n.tokenId}`;throw new l("helpers_invalid_params",{asset:e.toString(),message:"Unable to resolve the HyperCore spot token id"})}async function Re({destination:e,sender:t}){let n;try{n=await yt({destination:e,sender:t})}catch(o){throw new l("toolbox_hypercore_pre_transfer_check_failed",o)}if(typeof n?.isSanctioned!=="boolean"||typeof n.userExists!=="boolean")throw new l("toolbox_hypercore_pre_transfer_check_failed",{response:n});let{fee:r}=n,i=typeof r==="string"&&at.test(r)?Number(r):Number.NaN;if(!Number.isFinite(i))throw new l("toolbox_hypercore_pre_transfer_check_failed",{response:n});if(n.isSanctioned)throw new l("toolbox_hypercore_destination_sanctioned",{destination:e,sender:t});return i}function Ie(e){return e.toUpperCase().startsWith("USDC:")}async function qe({activationFee:e,token:t,user:n}){if(e<=0)return;let[r,i]=await Promise.all([te({user:n}),ne({token:B,user:n})]),o=F(r.withdrawable||"0")??new O(0),s=i??new O(0);if(new O(e).lte(o)||new O(e).lte(s))return;throw new l("toolbox_hypercore_insufficient_balance",{activationFee:e,feeToken:B,perpsWithdrawable:o.getValue("string"),spotAvailable:s.getValue("string"),token:t})}async function $e({activationFee:e,amount:t,sourceDex:n,token:r,user:i}){let o=Ie(r),s=o?new O(t).add(e):new O(t);if(n!==void 0&&n!==""&&n!=="spot")throw new l("helpers_invalid_params",{message:"Unsupported HyperCore sourceDex",sourceDex:n});if(!o&&n==="")throw new l("helpers_invalid_params",{message:"Only a collateral token can be sent from a perp DEX",sourceDex:n,token:r});let p="0";if(o&&n!=="spot"){if(p=(await te({user:i})).withdrawable||"0",s.lte(F(p)??0))return"";if(n==="")throw new l("toolbox_hypercore_insufficient_balance",{amountRequired:s.getValue("string"),perpsWithdrawable:p,spotAvailable:"0",token:r})}let u=await ne({token:r,user:i})??new O(0);if(u.gte(s)){if(!o)await qe({activationFee:e,token:r,user:i});return"spot"}throw new l("toolbox_hypercore_insufficient_balance",{amountRequired:s.getValue("string"),perpsWithdrawable:p,spotAvailable:u.getValue("string"),token:r})}async function xt({amount:e,destination:t,sender:n,sourceDex:r,sweep:i,token:o}){if(i&&r!==void 0&&r!=="spot")throw new l("helpers_invalid_params",{message:"HyperCore sweep drains spot and requires sourceDex spot",sourceDex:r});let s=await Re({destination:t,sender:n});if(!i){let u=await $e({activationFee:s,amount:e,sourceDex:r,token:o,user:n});return{amount:e,sourceDex:u}}if(!Ie(o))return await qe({activationFee:s,token:o,user:n}),{amount:e,sourceDex:"spot"};if(s<=0)return{amount:e,sourceDex:"spot"};let p=new O(e).sub(s);if(p.lte(0))throw new l("toolbox_hypercore_insufficient_balance",{activationFee:s,spotAvailable:e,token:o});return{amount:p.getValue("string"),sourceDex:"spot"}}async function bt({assetValue:e,recipient:t,sender:n,signatureChainId:r,sweep:i,time:o,endpoint:s}){let p=A(t,"core_transaction_invalid_recipient_address"),u=A(n,"core_transaction_invalid_sender_address"),S=e.address;if(!S)throw new l("helpers_invalid_params",{asset:e.toString(),from:u});let h=i?await ve({assetValue:e,sender:u,token:S}):e.getValue("string"),m=s??await J(),H=o||Date.now(),a={amount:h,destination:p,hyperliquidChain:De,signatureChainId:r||D,time:H,token:S,type:"spotSend"};return{action:a,endpoint:m,nonce:H,typedData:At(a)}}async function xe({assetValue:e,destinationDex:t,endpoint:n,fromSubAccount:r,recipient:i,sender:o,signatureChainId:s,sourceDex:p,sweep:u,time:S}){let h=A(i,"core_transaction_invalid_recipient_address"),m=A(o,"core_transaction_invalid_sender_address"),H=r?A(r,"helpers_invalid_params"):"",a=H||m,d=await Ht(e),f=u?await ve({assetValue:e,sender:a,token:d}):e.getValue("string"),{amount:x,sourceDex:C}=await xt({amount:f,destination:h,sender:a,sourceDex:p,sweep:u,token:d}),g=se({amount:x,destination:h,destinationDex:t??"spot",fromSubAccount:H,hyperliquidChain:De,nonce:S||Date.now(),signatureChainId:s||D,sourceDex:C,token:d});return Pe({action:g,endpoint:n})}async function Be(e){let t=await N.post(e.endpoint,{json:{action:e.action,...typeof e.expiresAfter==="number"?{expiresAfter:e.expiresAfter}:{},nonce:e.nonce,signature:e.signature,vaultAddress:e.vaultAddress??null},retry:{maxRetries:0}});if(t?.status!=="ok")throw new l("core_transaction_failed",{definitive:t?.status==="err",response:t});return t}async function be({amount:e,destination:t,nonce:n,token:r,user:i}){let o=A(i,"helpers_invalid_params"),s=await E(),p=n-5000,u=t?.toLowerCase(),S=r?.toUpperCase(),h=({delta:m,time:H})=>{if(!(H&&H>=p&&m?.type==="send"&&m.nonce===n))return!1;if(u&&m?.destination?.toLowerCase()!==u)return!1;let a=F(m?.amount);if(e!==void 0&&!a?.eqValue(e))return!1;if(S!==void 0){if(!m?.token)return!1;let d=m.token.toUpperCase();if(d!==S&&!S.startsWith(`${d}:`))return!1}return!0};for(let m=0;m<8;m++){if(m>0)await new Promise((H)=>setTimeout(H,1500));try{let H=await N.post(`${s}/info`,{json:{startTime:p,type:"userNonFundingLedgerUpdates",user:o},...Oe}),a=Array.isArray(H)?H.find(h):void 0;if(a?.hash)return a.hash}catch{}}return""}async function Se({kind:e,lookup:t,signed:n}){try{await Be(n)}catch(i){if(i instanceof l&&i.errorKey==="core_transaction_failed"&&i.cause?.definitive===!0)throw i;let s=await be(t);if(s)return s;throw new l("toolbox_hypercore_transfer_hash_not_found",{broadcast:"unknown",guidance:"Delivery of this broadcast is unknown and the nonce is single-use — do not retry or re-sign; check the account ledger for the transfer first.",nonce:t.nonce,transportError:String(i)})}let r=await be(t);if(!r)throw new l("toolbox_hypercore_transfer_hash_not_found",{broadcast:"accepted",guidance:`Do not retry or re-sign — the exchange accepted this nonce, so re-submitting risks a duplicate ${e}. Check the account ledger for the transfer first.`,nonce:t.nonce});return r}function Te({action:e,nonce:t,user:n}){return{amount:e.amount,destination:e.destination,nonce:t,token:e.token,user:n}}function Ne(e){return e.startsWith("0x")&&Ue(e)}function Xt(e){let t=e&&"index"in e?e.index||0:0,n=Xe(e&&"derivationPath"in e&&e.derivationPath?e.derivationPath:tt(et[U],{index:t})),r,i=!1;function o(){if(i)return r;return r=it(e).with({phrase:Z.string},({phrase:a})=>rt.fromPhrase(a,void 0,n)).with({signer:Z.not(Z.nullish)},({signer:a})=>a).otherwise(()=>{return}),i=!0,r}async function s(){let a=o();return a?await a.getAddress():""}async function p(a){let d=o();if(!d)throw new l("toolbox_hypercore_no_signer");let f=we(a.typedData),x=await d.signTypedData(f.domain,f.types,f.message);return{action:a.action,endpoint:a.endpoint,nonce:a.nonce,signature:ue(x),..."expiresAfter"in a?{expiresAfter:a.expiresAfter}:{},..."vaultAddress"in a?{vaultAddress:a.vaultAddress}:{}}}async function u(a){let d=A(a,"helpers_invalid_params"),f=await E(),[x,C,g]=await Promise.all([N.post(`${f}/info`,{json:{type:"spotClearinghouseState",user:d}}),N.post(`${f}/info`,{json:{type:"clearinghouseState",user:d}}),N.post(`${f}/info`,{json:{type:"spotMeta"}})]),T=(x.spotState?.balances||x.balances||[]).map(({coin:w,token:R,total:P})=>He({coin:w,spotMeta:g,token:R,value:P})).filter((w)=>!!w),_=He({coin:"USDC",spotMeta:g,value:C.withdrawable||C.marginSummary?.accountValue||C.marginSummary?.totalRawUsd});return Ct(_?[...T,_]:T)}async function S(a,d=!0){let f=A(a,"helpers_invalid_params");try{let x=await nt.getChainBalance({address:f,chain:U,scamFilter:d});if(x.length){let C=x.map(({identifier:T,value:_,decimal:w})=>new M({decimal:w||ee,identifier:T,value:_}));return C.some((T)=>T.isGasAsset)?C:[M.from({chain:U}),...C]}}catch{}return u(f)}async function h({sweep:a,...d}){let f=o();if(!f)throw new l("toolbox_hypercore_no_signer");let x=d.sender||await f.getAddress(),C=await xe({...d,feeRate:0,sender:x,sweep:a}),g=await p(C);return Se({kind:"transfer",lookup:Te({action:C.action,nonce:C.nonce,user:C.action.fromSubAccount||x}),signed:g})}async function m(a){let d=o();if(!d)throw new l("toolbox_hypercore_no_signer");let{action:f,typedData:x,...C}=a,g=structuredClone(f),T=structuredClone(x),_=await d.getAddress(),w=await J(),R=[...new Set([w,ot??w])];Ae({...C,action:g,allowedEndpoints:R,typedData:T});let P=g.fromSubAccount?A(g.fromSubAccount,"helpers_invalid_params"):_,L=await Re({destination:g.destination,sender:P});await $e({activationFee:L,amount:g.amount,sourceDex:g.sourceDex,token:g.token,user:P});let j=await p({action:g,endpoint:w,nonce:g.nonce,typedData:T});return Se({kind:"payin",lookup:Te({action:g,nonce:g.nonce,user:P}),signed:j})}function H(){return M.from({chain:U,value:0})}return{broadcastTransaction:Be,createL1ActionRequest:ht,createSendAssetTransaction:xe,createTransaction:bt,createUserSignedActionRequest:Pe,estimateTransactionFee:H,getAddress:s,getBalance:S,getBalanceFromChain:u,getState:{clearinghouse:te,frontendOpenOrders:lt,openOrders:ut,orderStatus:gt,spotClearinghouse:ke,userFills:ft,userFillsByTime:mt},signAndBroadcastSendAsset:m,signTransaction:p,transfer:h,validateAddress:Ne}}export{B as HYPERCORE_USDC_TOKEN_ID,Rt as buildApproveAgentAction,It as buildApproveBuilderFeeAction,_t as buildBatchModifyAction,Tt as buildCancelAction,wt as buildCancelByCloidAction,Ut as buildModifyAction,St as buildOrderAction,Pt as buildScheduleCancelAction,se as buildSendAssetAction,qt as buildTokenDelegateAction,kt as buildTopUpIsolatedOnlyMarginAction,Ot as buildUpdateIsolatedMarginAction,Dt as buildUpdateLeverageAction,vt as buildUsdClassTransferAction,ht as createL1ActionRequest,xe as createSendAssetTransaction,bt as createTransaction,Pe as createUserSignedActionRequest,Xt as getHyperCoreToolbox,Ne as validateHyperCoreAddress};
1
+ import"../../chunk-qsbf0z90.js";import{m as we,r as Ue}from"../../chunk-6fcz98xe.js";import"../../chunk-qk8kg62t.js";import"../../chunk-pz8xe0qj.js";function St({builder:e,grouping:t="na",orders:n}){return{builder:e,grouping:t,orders:n,type:"order"}}function Tt({cancels:e}){return{cancels:e,type:"cancel"}}function wt({cancels:e}){return{cancels:e,type:"cancelByCloid"}}function Ut({oid:e,order:t}){return{oid:e,order:t,type:"modify"}}function _t({modifies:e}){return{modifies:e,type:"batchModify"}}function Dt({asset:e,isCross:t,leverage:n}){return{asset:e,isCross:t,leverage:n,type:"updateLeverage"}}function Ot({asset:e,isBuy:t,ntli:n}){return{asset:e,isBuy:t,ntli:n,type:"updateIsolatedMargin"}}function kt({asset:e,leverage:t}){return{asset:e,leverage:t,type:"topUpIsolatedOnlyMargin"}}function Pt({time:e}){return{time:e,type:"scheduleCancel"}}function vt({amount:e,hyperliquidChain:t,nonce:n,signatureChainId:r,toPerp:i}){return{amount:e,hyperliquidChain:t,nonce:n,signatureChainId:r,toPerp:i,type:"usdClassTransfer"}}function se({amount:e,destination:t,destinationDex:n,fromSubAccount:r,hyperliquidChain:i,nonce:o,signatureChainId:s,sourceDex:p,token:u}){return{amount:e,destination:t,destinationDex:n,fromSubAccount:r,hyperliquidChain:i,nonce:o,signatureChainId:s,sourceDex:p,token:u,type:"sendAsset"}}function Rt({agentAddress:e,agentName:t,hyperliquidChain:n,nonce:r,signatureChainId:i}){return{agentAddress:e,agentName:t,hyperliquidChain:n,nonce:r,signatureChainId:i,type:"approveAgent"}}function It({builder:e,hyperliquidChain:t,maxFeeRate:n,nonce:r,signatureChainId:i}){return{builder:e,hyperliquidChain:t,maxFeeRate:n,nonce:r,signatureChainId:i,type:"approveBuilderFee"}}function qt({hyperliquidChain:e,isUndelegate:t,nonce:n,signatureChainId:r,validator:i,wei:o}){return{hyperliquidChain:e,isUndelegate:t,nonce:n,signatureChainId:r,type:"tokenDelegate",validator:i,wei:o}}import{SwapKitError as Ve,SwapKitNumber as Qe}from"@swapkit/helpers";import{HYPERCORE_USDC_TOKEN_ID as B}from"@swapkit/helpers/api";import{SwapKitError as V}from"@swapkit/helpers";import{keccak256 as Me,Signature as Fe}from"ethers";var I="0x0000000000000000000000000000000000000000",D="0xa4b1",q={name:"HyperliquidSignTransaction",verifyingContract:I,version:"1"},Le={chainId:1337,name:"Exchange",verifyingContract:I,version:"1"},je={Agent:[{name:"source",type:"string"},{name:"connectionId",type:"bytes32"}]},pe="Mainnet",Q={approveAgent:[{name:"hyperliquidChain",type:"string"},{name:"agentAddress",type:"address"},{name:"agentName",type:"string"},{name:"nonce",type:"uint64"}],approveBuilderFee:[{name:"hyperliquidChain",type:"string"},{name:"maxFeeRate",type:"string"},{name:"builder",type:"address"},{name:"nonce",type:"uint64"}],sendAsset:[{name:"hyperliquidChain",type:"string"},{name:"destination",type:"string"},{name:"sourceDex",type:"string"},{name:"destinationDex",type:"string"},{name:"token",type:"string"},{name:"amount",type:"string"},{name:"fromSubAccount",type:"string"},{name:"nonce",type:"uint64"}],tokenDelegate:[{name:"hyperliquidChain",type:"string"},{name:"validator",type:"address"},{name:"wei",type:"uint64"},{name:"isUndelegate",type:"bool"},{name:"nonce",type:"uint64"}],usdClassTransfer:[{name:"hyperliquidChain",type:"string"},{name:"amount",type:"string"},{name:"toPerp",type:"bool"},{name:"nonce",type:"uint64"}]},G={approveAgent:"HyperliquidTransaction:ApproveAgent",approveBuilderFee:"HyperliquidTransaction:ApproveBuilderFee",sendAsset:"HyperliquidTransaction:SendAsset",tokenDelegate:"HyperliquidTransaction:TokenDelegate",usdClassTransfer:"HyperliquidTransaction:UsdClassTransfer"},Ee=new TextEncoder;function b(...e){let t=e.reduce((i,o)=>i+o.length,0),n=new Uint8Array(t),r=0;for(let i of e)n.set(i,r),r+=i.length;return n}function Je(e,t,n){if(n<t)return new Uint8Array([e+n]);if(n<=255)return new Uint8Array([e+t,n]);if(n<=65535)return new Uint8Array([e+t+1,n>>8,n&255]);return new Uint8Array([e+t+2,n>>>24&255,n>>>16&255,n>>>8&255,n&255])}function v(e,t){let n=new Uint8Array(t),r=e;for(let i=t-1;i>=0;i-=1)n[i]=Number(r&0xffn),r>>=8n;return n}function ae(e){if(e>=0n){if(e<=0x7fn)return new Uint8Array([Number(e)]);if(e<=0xffn)return new Uint8Array([204,Number(e)]);if(e<=0xffffn)return b(new Uint8Array([205]),v(e,2));if(e<=0xffffffffn)return b(new Uint8Array([206]),v(e,4));return b(new Uint8Array([207]),v(e,8))}if(e>=-32n)return new Uint8Array([256+Number(e)]);if(e>=-128n)return new Uint8Array([208,256+Number(e)]);if(e>=-32768n)return b(new Uint8Array([209]),v(BigInt.asUintN(16,e),2));if(e>=-2147483648n)return b(new Uint8Array([210]),v(BigInt.asUintN(32,e),4));return b(new Uint8Array([211]),v(BigInt.asUintN(64,e),8))}function ce(e){let t=Ee.encode(e);if(t.length<32)return b(new Uint8Array([160+t.length]),t);return b(Je(217,0,t.length),t)}function Ke(e){let t=e.map((r)=>Y(r)),n=e.length<16?new Uint8Array([144+e.length]):e.length<=65535?new Uint8Array([220,e.length>>8,e.length&255]):new Uint8Array([221,e.length>>>24&255,e.length>>>16&255,e.length>>>8&255,e.length&255]);return b(n,...t)}function ze(e){let t=Object.entries(e).filter(([,r])=>typeof r<"u"),n=t.length<16?new Uint8Array([128+t.length]):t.length<=65535?new Uint8Array([222,t.length>>8,t.length&255]):new Uint8Array([223,t.length>>>24&255,t.length>>>16&255,t.length>>>8&255,t.length&255]);return b(n,...t.flatMap(([r,i])=>[ce(r),Y(i)]))}function Y(e){if(e===null)return new Uint8Array([192]);if(typeof e==="boolean")return new Uint8Array([e?195:194]);if(typeof e==="string")return ce(e);if(typeof e==="number"){if(!Number.isFinite(e)||!Number.isInteger(e))throw new V("helpers_invalid_params",{message:"Hyperliquid msgpack only supports integers"});return ae(BigInt(e))}if(typeof e==="bigint")return ae(e);if(e instanceof Uint8Array){let t=e.length<=255?new Uint8Array([196,e.length]):e.length<=65535?new Uint8Array([197,e.length>>8,e.length&255]):new Uint8Array([198,e.length>>>24&255,e.length>>>16&255,e.length>>>8&255,e.length&255]);return b(t,e)}if(Array.isArray(e))return Ke(e);if(typeof e==="object")return ze(e);throw new V("helpers_invalid_params",{message:`Unsupported Hyperliquid msgpack value: ${String(e)}`})}function We(e){let t=e.startsWith("0x")?e.slice(2):e;if(t.length%2!==0||/[^a-fA-F0-9]/u.test(t))throw new V("helpers_invalid_params",{hexValue:e});let n=new Uint8Array(t.length/2);for(let r=0;r<t.length;r+=2)n[r/2]=Number.parseInt(t.slice(r,r+2),16);return n}function de(e){return{domain:Le,message:{connectionId:e,source:"a"},primaryType:"Agent",types:{Agent:[...je.Agent]}}}function ye(e){let t=G[e.type],n=Q[e.type],{signatureChainId:r,type:i,...o}=e,s=Number.parseInt(r||D,16);return{domain:{...q,chainId:s},message:{...o,hyperliquidChain:o.hyperliquidChain||pe},primaryType:t,types:{[t]:n}}}function ue(e){let t=Fe.from(e);return{r:t.r,s:t.s,v:t.v}}function le(e,t,{expiresAfter:n,vaultAddress:r}={}){let i=Y(e),o=v(BigInt(t),8),s=r?b(new Uint8Array([1]),We(r.toLowerCase())):new Uint8Array([0]),p=typeof n==="number"?b(new Uint8Array([0]),v(BigInt(n),8)):new Uint8Array;return Me(b(i,o,s,p))}function ge(e){let t=e.hyperliquidChain||pe;switch(e.type){case"approveAgent":return{...e,agentAddress:e.agentAddress.toLowerCase(),hyperliquidChain:t};case"approveBuilderFee":return{...e,builder:e.builder.toLowerCase(),hyperliquidChain:t};case"sendAsset":return{...e,destination:e.destination.toLowerCase(),fromSubAccount:e.fromSubAccount.toLowerCase(),hyperliquidChain:t};case"tokenDelegate":return{...e,hyperliquidChain:t,validator:e.validator.toLowerCase()};case"usdClassTransfer":return{...e,hyperliquidChain:t};default:return e}}var fe=Number.parseInt(D,16),Ge=new Set(["chainId","name","verifyingContract","version"]),me=/^0x[0-9a-fA-F]{40}$/,X=Q.sendAsset;var c=(e)=>{throw new Ve("toolbox_hypercore_payload_mismatch",{problems:[e]})};function Ce(e){try{return new URL(e)}catch{return}}function Ae({action:e,allowedEndpoints:t,expectedAmount:n,expectedDestination:r,expectedDestinationDex:i,expectedFromSubAccount:o,expectedSourceDex:s,expectedToken:p,submitTo:u,typedData:S}){let{domain:h,message:m,primaryType:H,types:a}=S,d=G.sendAsset;if(H!==d)c(`primaryType is ${JSON.stringify(H)}, expected "${d}"`);if(e.type!=="sendAsset")c(`action.type is ${JSON.stringify(e.type)}, expected "sendAsset"`);let f=X.map(({name:y})=>y),x=new Set([...f,"signatureChainId","type"]),C=Object.keys(e).filter((y)=>!x.has(y));if(C.length)c(`action carries unexpected keys: ${C.join(", ")}`);for(let{name:y}of X)if(m[y]!==e[y])c(`${y}: signed ${JSON.stringify(m[y])} != submitted ${JSON.stringify(e[y])}`);let g=Object.keys(m),T=g.filter((y)=>!f.includes(y)),_=f.filter((y)=>!g.includes(y));if(T.length||_.length){let y=[T.length?`declares undeclared keys [${T.join(",")}]`:"",_.length?`is missing keys [${_.join(",")}]`:""].filter(Boolean).join(" / ");c(`message ${y}`)}let w=X.map(({name:y,type:W})=>`${y}:${W}`).join(","),R=(a[d]??[]).map(({name:y,type:W})=>`${y}:${W}`).join(",");if(R!==w)c(`types.${d} is [${R}], expected [${w}]`);let P=Object.keys(a).filter((y)=>y!==d&&y!=="EIP712Domain");if(P.length)c(`types carries unexpected entries: ${P.join(", ")}`);if(Number(h.chainId)!==fe)c(`domain.chainId is ${h.chainId}, expected ${fe} (Arbitrum)`);if(h.name!==q.name)c(`domain.name is ${JSON.stringify(h.name)}, expected "${q.name}"`);if(h.version!==q.version)c(`domain.version is ${JSON.stringify(h.version)}, expected "${q.version}"`);if(h.verifyingContract!==I)c(`domain.verifyingContract is ${h.verifyingContract}, expected the zero address`);let L=Object.keys(h).filter((y)=>!Ge.has(y));if(L.length)c(`domain carries unexpected keys: ${L.join(", ")}`);if(typeof e.signatureChainId!=="string"||e.signatureChainId.toLowerCase()!==D)c(`action.signatureChainId is ${JSON.stringify(e.signatureChainId)}, expected "${D}"`);if(e.hyperliquidChain!=="Mainnet")c(`action.hyperliquidChain is ${JSON.stringify(e.hyperliquidChain)}, expected "Mainnet"`);if(typeof e.nonce!=="number"||!Number.isSafeInteger(e.nonce)||e.nonce<=0)c(`action.nonce is ${JSON.stringify(e.nonce)}, expected a positive safe integer`);if(i!==""&&i!=="spot")c(`expectedDestinationDex ${JSON.stringify(i)} is not "" or "spot"`);if(e.destinationDex!==i)c(`action.destinationDex is ${JSON.stringify(e.destinationDex)}, expected ${JSON.stringify(i)}`);if(p!==B)c(`route sell token is ${JSON.stringify(p)}, expected "${B}"`);if(e.token!==p)c(`action.token is ${JSON.stringify(e.token)}, expected route sell token "${p}"`);if(e.sourceDex!==""&&e.sourceDex!=="spot")c(`action.sourceDex is ${JSON.stringify(e.sourceDex)}, expected "" or "spot"`);if(typeof e.sourceDex!=="string"||e.sourceDex!==s)c(`action.sourceDex is ${JSON.stringify(e.sourceDex)}, expected route sourceDex ${JSON.stringify(s)}`);let j=e.fromSubAccount;if(typeof j!=="string"||typeof o!=="string"||j.toLowerCase()!==o.toLowerCase())c(`action.fromSubAccount is ${JSON.stringify(e.fromSubAccount)}, expected ${JSON.stringify(o)}`);if(o&&!me.test(o))c(`expectedFromSubAccount ${JSON.stringify(o)} is not a well-formed 0x address`);if(!n)c("expectedAmount is missing — cannot verify action.amount");let re=!1;try{re=new Qe(String(e.amount)).eqValue(n)}catch{c(`action.amount ${JSON.stringify(e.amount)} is not comparable to ${n}`)}if(!re)c(`action.amount ${JSON.stringify(e.amount)} != route sell amount ${n}`);let K=typeof e.destination==="string"?e.destination:"";if(!me.test(K))c(`action.destination ${JSON.stringify(e.destination)} is not a well-formed 0x address`);if(!r)c("expectedDestination is missing — cannot verify action.destination");if(K.toLowerCase()!==r.toLowerCase())c(`action.destination ${K} != expected destination ${r}`);let ie=Ce(u),z=ie?.origin,oe=t.flatMap((y)=>Ce(y)?.origin??[]);if(ie?.protocol!=="https:")c(`submitTo ${JSON.stringify(u)} must be an https URL`);if(!z||!oe.includes(z))c(`submitTo origin ${z} is not one of the allowed exchange origins [${oe.join(", ")}]`)}import{AssetValue as M,Chain as Ye,derivationPathToString as Xe,getChainConfig as _e,getRPCUrl as Ze,NetworkDerivationPath as et,RequestClient as N,SwapKitError as l,SwapKitNumber as O,updateDerivationPath as tt}from"@swapkit/helpers";import{SwapKitApi as nt}from"@swapkit/helpers/api";import{HDNodeWallet as rt}from"ethers";import{match as it,P as Z}from"ts-pattern";var U=Ye.Hype,{baseDecimal:ee,rpcUrls:he}=_e(U),ot=he[0]?`${he[0]}/exchange`:void 0,st={HYPE:ee,USDC:6,USDT:6},De="Mainnet",at=/^\d+(?:\.\d+)?$/,pt=/^[^:]+:0x[0-9a-fA-F]+$/,ct={spotSend:[{name:"hyperliquidChain",type:"string"},{name:"destination",type:"string"},{name:"token",type:"string"},{name:"amount",type:"string"},{name:"time",type:"uint64"}]},dt={spotSend:"HyperliquidTransaction:SpotSend"};function A(e,t){if(!Ne(e))throw new l(t,{address:e});return e.toLowerCase()}function F(e){if(e===void 0)return;try{return new O(e)}catch{return}}var Oe={retry:{maxRetries:0},timeoutMs:5000};async function k({requestOptions:e,...t}){let n=await E();return N.post(`${n}/info`,{json:t,...e})}function te({dex:e,user:t}){return k({...e?{dex:e}:{},type:"clearinghouseState",user:A(t,"helpers_invalid_params")})}function ke({user:e}){return k({type:"spotClearinghouseState",user:A(e,"helpers_invalid_params")})}function yt({destination:e,sender:t}){let n=A(t,"helpers_invalid_params"),r=A(e,"helpers_invalid_params");return k({requestOptions:Oe,source:n,type:"preTransferCheck",user:r})}function ut({dex:e,user:t}){return k({...e?{dex:e}:{},type:"openOrders",user:A(t,"helpers_invalid_params")})}function lt({dex:e,user:t}){return k({...e?{dex:e}:{},type:"frontendOpenOrders",user:A(t,"helpers_invalid_params")})}function gt({oidOrCloid:e,user:t}){return k({oid:e,type:"orderStatus",user:A(t,"helpers_invalid_params")})}function ft({aggregateByTime:e,user:t}){return k({...typeof e==="boolean"?{aggregateByTime:e}:{},type:"userFills",user:A(t,"helpers_invalid_params")})}function mt({aggregateByTime:e,endTime:t,startTime:n,user:r}){return k({...typeof e==="boolean"?{aggregateByTime:e}:{},...typeof t==="number"?{endTime:t}:{},startTime:n,type:"userFillsByTime",user:A(r,"helpers_invalid_params")})}function He({coin:e,token:t,value:n,spotMeta:r}){if(!n||Number(n)<=0)return null;let i=e?.toUpperCase()||`TOKEN-${t||"UNKNOWN"}`,o=r?.tokens?.find((u)=>u.name===e||t!==void 0&&u.index===Number(t)),s=o?.weiDecimals??st[i]??ee,p=o?`${U}.${i}-${o.name}:${o.tokenId}`:`${U}.${i}`;return new M({decimal:s,identifier:p,value:n})}function Ct(e){let t=new Map;for(let n of e){let r=n.toString({includeSynthProtocol:!0}),i=t.get(r);t.set(r,i?i.add(n):n)}if(![...t.values()].some((n)=>n.isGasAsset||n.ticker==="HYPE")){let n=M.from({chain:U,value:0});t.set(n.toString({includeSynthProtocol:!0}),n)}return[...t.values()]}async function E(){try{return await Ze(U)}catch{let[e]=_e(U).rpcUrls;if(!e)throw new l({errorKey:"helpers_chain_no_public_or_set_rpc_url",info:{chain:U}});return e}}async function J(){return`${await E()}/exchange`}function At(e){let t=dt[e.type],{type:n,...r}=e;return{domain:{chainId:Number.parseInt(e.signatureChainId,16),name:"HyperliquidSignTransaction",verifyingContract:I,version:"1"},message:r,primaryType:t,types:{[t]:ct[n]}}}async function ht({action:e,expiresAfter:t,nonce:n,vaultAddress:r}){let i=n||Date.now(),o=r?A(r,"helpers_invalid_params"):void 0,s=await J(),p=le(e,i,{expiresAfter:t,vaultAddress:o});return{action:e,endpoint:s,expiresAfter:t,nonce:i,typedData:de(p),vaultAddress:o}}async function Pe({action:e,endpoint:t,nonce:n,signatureChainId:r}){let i=n||e.nonce||Date.now(),o=r||e.signatureChainId||D,s=ge({...e,nonce:i,signatureChainId:o});return{action:s,endpoint:t??await J(),nonce:i,typedData:ye(s)}}async function ne({token:e,user:t}){let n=await ke({user:t}),i=(n.spotState?.balances||n.balances||[]).find(({coin:p})=>p&&e.startsWith(`${p}:`)),o=F(i?.total||0),s=F(i?.hold||0);return o&&s?o.sub(s):void 0}async function ve({assetValue:e,sender:t,token:n}){let r=(await ne({token:n,user:t}))?.getValue("string");if(!r||Number(r)<=0)throw new l("toolbox_sweep_amount_too_low",{asset:e.toString(),balance:r||"0"});return r}async function Ht(e){if(e.address&&pt.test(e.address))return e.address;let n=(await k({type:"spotMeta"}))?.tokens?.find(({name:r})=>r?.toUpperCase()===e.ticker.toUpperCase());if(n)return`${n.name}:${n.tokenId}`;throw new l("helpers_invalid_params",{asset:e.toString(),message:"Unable to resolve the HyperCore spot token id"})}async function Re({destination:e,sender:t}){let n;try{n=await yt({destination:e,sender:t})}catch(o){throw new l("toolbox_hypercore_pre_transfer_check_failed",o)}if(typeof n?.isSanctioned!=="boolean"||typeof n.userExists!=="boolean")throw new l("toolbox_hypercore_pre_transfer_check_failed",{response:n});let{fee:r}=n,i=typeof r==="string"&&at.test(r)?Number(r):Number.NaN;if(!Number.isFinite(i))throw new l("toolbox_hypercore_pre_transfer_check_failed",{response:n});if(n.isSanctioned)throw new l("toolbox_hypercore_destination_sanctioned",{destination:e,sender:t});return i}function Ie(e){return e.toUpperCase().startsWith("USDC:")}async function qe({activationFee:e,token:t,user:n}){if(e<=0)return;let[r,i]=await Promise.all([te({user:n}),ne({token:B,user:n})]),o=F(r.withdrawable||"0")??new O(0),s=i??new O(0);if(new O(e).lte(o)||new O(e).lte(s))return;throw new l("toolbox_hypercore_insufficient_balance",{activationFee:e,feeToken:B,perpsWithdrawable:o.getValue("string"),spotAvailable:s.getValue("string"),token:t})}async function $e({activationFee:e,amount:t,sourceDex:n,token:r,user:i}){let o=Ie(r),s=o?new O(t).add(e):new O(t);if(n!==void 0&&n!==""&&n!=="spot")throw new l("helpers_invalid_params",{message:"Unsupported HyperCore sourceDex",sourceDex:n});if(!o&&n==="")throw new l("helpers_invalid_params",{message:"Only a collateral token can be sent from a perp DEX",sourceDex:n,token:r});let p="0";if(o&&n!=="spot"){if(p=(await te({user:i})).withdrawable||"0",s.lte(F(p)??0))return"";if(n==="")throw new l("toolbox_hypercore_insufficient_balance",{amountRequired:s.getValue("string"),perpsWithdrawable:p,spotAvailable:"0",token:r})}let u=await ne({token:r,user:i})??new O(0);if(u.gte(s)){if(!o)await qe({activationFee:e,token:r,user:i});return"spot"}throw new l("toolbox_hypercore_insufficient_balance",{amountRequired:s.getValue("string"),perpsWithdrawable:p,spotAvailable:u.getValue("string"),token:r})}async function xt({amount:e,destination:t,sender:n,sourceDex:r,sweep:i,token:o}){if(i&&r!==void 0&&r!=="spot")throw new l("helpers_invalid_params",{message:"HyperCore sweep drains spot and requires sourceDex spot",sourceDex:r});let s=await Re({destination:t,sender:n});if(!i){let u=await $e({activationFee:s,amount:e,sourceDex:r,token:o,user:n});return{amount:e,sourceDex:u}}if(!Ie(o))return await qe({activationFee:s,token:o,user:n}),{amount:e,sourceDex:"spot"};if(s<=0)return{amount:e,sourceDex:"spot"};let p=new O(e).sub(s);if(p.lte(0))throw new l("toolbox_hypercore_insufficient_balance",{activationFee:s,spotAvailable:e,token:o});return{amount:p.getValue("string"),sourceDex:"spot"}}async function bt({assetValue:e,recipient:t,sender:n,signatureChainId:r,sweep:i,time:o,endpoint:s}){let p=A(t,"core_transaction_invalid_recipient_address"),u=A(n,"core_transaction_invalid_sender_address"),S=e.address;if(!S)throw new l("helpers_invalid_params",{asset:e.toString(),from:u});let h=i?await ve({assetValue:e,sender:u,token:S}):e.getValue("string"),m=s??await J(),H=o||Date.now(),a={amount:h,destination:p,hyperliquidChain:De,signatureChainId:r||D,time:H,token:S,type:"spotSend"};return{action:a,endpoint:m,nonce:H,typedData:At(a)}}async function xe({assetValue:e,destinationDex:t,endpoint:n,fromSubAccount:r,recipient:i,sender:o,signatureChainId:s,sourceDex:p,sweep:u,time:S}){let h=A(i,"core_transaction_invalid_recipient_address"),m=A(o,"core_transaction_invalid_sender_address"),H=r?A(r,"helpers_invalid_params"):"",a=H||m,d=await Ht(e),f=u?await ve({assetValue:e,sender:a,token:d}):e.getValue("string"),{amount:x,sourceDex:C}=await xt({amount:f,destination:h,sender:a,sourceDex:p,sweep:u,token:d}),g=se({amount:x,destination:h,destinationDex:t??"spot",fromSubAccount:H,hyperliquidChain:De,nonce:S||Date.now(),signatureChainId:s||D,sourceDex:C,token:d});return Pe({action:g,endpoint:n})}async function Be(e){let t=await N.post(e.endpoint,{json:{action:e.action,...typeof e.expiresAfter==="number"?{expiresAfter:e.expiresAfter}:{},nonce:e.nonce,signature:e.signature,vaultAddress:e.vaultAddress??null},retry:{maxRetries:0}});if(t?.status!=="ok")throw new l("core_transaction_failed",{definitive:t?.status==="err",response:t});return t}async function be({amount:e,destination:t,nonce:n,token:r,user:i}){let o=A(i,"helpers_invalid_params"),s=await E(),p=n-5000,u=t?.toLowerCase(),S=r?.toUpperCase(),h=({delta:m,time:H})=>{if(!(H&&H>=p&&m?.type==="send"&&m.nonce===n))return!1;if(u&&m?.destination?.toLowerCase()!==u)return!1;let a=F(m?.amount);if(e!==void 0&&!a?.eqValue(e))return!1;if(S!==void 0){if(!m?.token)return!1;let d=m.token.toUpperCase();if(d!==S&&!S.startsWith(`${d}:`))return!1}return!0};for(let m=0;m<8;m++){if(m>0)await new Promise((H)=>setTimeout(H,1500));try{let H=await N.post(`${s}/info`,{json:{startTime:p,type:"userNonFundingLedgerUpdates",user:o},...Oe}),a=Array.isArray(H)?H.find(h):void 0;if(a?.hash)return a.hash}catch{}}return""}async function Se({kind:e,lookup:t,signed:n}){try{await Be(n)}catch(i){if(i instanceof l&&i.errorKey==="core_transaction_failed"&&i.cause?.definitive===!0)throw i;let s=await be(t);if(s)return s;throw new l("toolbox_hypercore_transfer_hash_not_found",{broadcast:"unknown",guidance:"Delivery of this broadcast is unknown and the nonce is single-use — do not retry or re-sign; check the account ledger for the transfer first.",nonce:t.nonce,transportError:String(i)})}let r=await be(t);if(!r)throw new l("toolbox_hypercore_transfer_hash_not_found",{broadcast:"accepted",guidance:`Do not retry or re-sign — the exchange accepted this nonce, so re-submitting risks a duplicate ${e}. Check the account ledger for the transfer first.`,nonce:t.nonce});return r}function Te({action:e,nonce:t,user:n}){return{amount:e.amount,destination:e.destination,nonce:t,token:e.token,user:n}}function Ne(e){return e.startsWith("0x")&&Ue(e)}function Xt(e){let t=e&&"index"in e?e.index||0:0,n=Xe(e&&"derivationPath"in e&&e.derivationPath?e.derivationPath:tt(et[U],{index:t})),r,i=!1;function o(){if(i)return r;return r=it(e).with({phrase:Z.string},({phrase:a})=>rt.fromPhrase(a,void 0,n)).with({signer:Z.not(Z.nullish)},({signer:a})=>a).otherwise(()=>{return}),i=!0,r}async function s(){let a=o();return a?await a.getAddress():""}async function p(a){let d=o();if(!d)throw new l("toolbox_hypercore_no_signer");let f=we(a.typedData),x=await d.signTypedData(f.domain,f.types,f.message);return{action:a.action,endpoint:a.endpoint,nonce:a.nonce,signature:ue(x),..."expiresAfter"in a?{expiresAfter:a.expiresAfter}:{},..."vaultAddress"in a?{vaultAddress:a.vaultAddress}:{}}}async function u(a){let d=A(a,"helpers_invalid_params"),f=await E(),[x,C,g]=await Promise.all([N.post(`${f}/info`,{json:{type:"spotClearinghouseState",user:d}}),N.post(`${f}/info`,{json:{type:"clearinghouseState",user:d}}),N.post(`${f}/info`,{json:{type:"spotMeta"}})]),T=(x.spotState?.balances||x.balances||[]).map(({coin:w,token:R,total:P})=>He({coin:w,spotMeta:g,token:R,value:P})).filter((w)=>!!w),_=He({coin:"USDC",spotMeta:g,value:C.withdrawable||C.marginSummary?.accountValue||C.marginSummary?.totalRawUsd});return Ct(_?[...T,_]:T)}async function S(a,d=!0){let f=A(a,"helpers_invalid_params");try{let x=await nt.getChainBalance({address:f,chain:U,scamFilter:d});if(x.length){let C=x.map(({identifier:T,value:_,decimal:w})=>new M({decimal:w||ee,identifier:T,value:_}));return C.some((T)=>T.isGasAsset)?C:[M.from({chain:U}),...C]}}catch{}return u(f)}async function h({sweep:a,...d}){let f=o();if(!f)throw new l("toolbox_hypercore_no_signer");let x=d.sender||await f.getAddress(),C=await xe({...d,feeRate:0,sender:x,sweep:a}),g=await p(C);return Se({kind:"transfer",lookup:Te({action:C.action,nonce:C.nonce,user:C.action.fromSubAccount||x}),signed:g})}async function m(a){let d=o();if(!d)throw new l("toolbox_hypercore_no_signer");let{action:f,typedData:x,...C}=a,g=structuredClone(f),T=structuredClone(x),_=await d.getAddress(),w=await J(),R=[...new Set([w,ot??w])];Ae({...C,action:g,allowedEndpoints:R,typedData:T});let P=g.fromSubAccount?A(g.fromSubAccount,"helpers_invalid_params"):_,L=await Re({destination:g.destination,sender:P});await $e({activationFee:L,amount:g.amount,sourceDex:g.sourceDex,token:g.token,user:P});let j=await p({action:g,endpoint:w,nonce:g.nonce,typedData:T});return Se({kind:"payin",lookup:Te({action:g,nonce:g.nonce,user:P}),signed:j})}function H(){return M.from({chain:U,value:0})}return{broadcastTransaction:Be,createL1ActionRequest:ht,createSendAssetTransaction:xe,createTransaction:bt,createUserSignedActionRequest:Pe,estimateTransactionFee:H,getAddress:s,getBalance:S,getBalanceFromChain:u,getState:{clearinghouse:te,frontendOpenOrders:lt,openOrders:ut,orderStatus:gt,spotClearinghouse:ke,userFills:ft,userFillsByTime:mt},signAndBroadcastSendAsset:m,signTransaction:p,transfer:h,validateAddress:Ne}}export{B as HYPERCORE_USDC_TOKEN_ID,Rt as buildApproveAgentAction,It as buildApproveBuilderFeeAction,_t as buildBatchModifyAction,Tt as buildCancelAction,wt as buildCancelByCloidAction,Ut as buildModifyAction,St as buildOrderAction,Pt as buildScheduleCancelAction,se as buildSendAssetAction,qt as buildTokenDelegateAction,kt as buildTopUpIsolatedOnlyMarginAction,Ot as buildUpdateIsolatedMarginAction,Dt as buildUpdateLeverageAction,vt as buildUsdClassTransferAction,ht as createL1ActionRequest,xe as createSendAssetTransaction,bt as createTransaction,Pe as createUserSignedActionRequest,Xt as getHyperCoreToolbox,Ne as validateHyperCoreAddress};
package/dist/src/index.js CHANGED
@@ -1 +1 @@
1
- import{ka as o}from"../chunk-pz8xe0qj.js";import{AssetValue as k,Chain as t,CosmosChains as x,EVMChains as c,FeeOption as v,SubstrateChains as O,SwapKitError as V,UTXOChains as C}from"@swapkit/helpers";async function H(){let{match:l}=await import("ts-pattern"),{validateAleoAddress:r}=await import("./aleo/index.js"),{validateAptosAddress:s}=await import("./aptos/index.js"),{validateEVMAddress:e}=await import("./evm/index.js"),{validateCardanoAddress:a}=await import("./cardano/index.js"),{getCosmosAddressValidator:i}=await import("./cosmos/index.js"),{getSubstrateAddressValidator:p}=await import("./substrate/index.js"),{validateHyperCoreAddress:m}=await import("./hypercore/index.js"),{validateSolanaAddress:h}=await import("./solana/index.js"),{validateStarknetAddress:u}=await import("./starknet/index.js"),{validateSuiAddress:d}=await import("./sui/index.js"),{validateTonAddress:f}=await import("./ton/index.js"),{getUTXOAddressValidator:g}=await import("./utxo/index.js"),{validateNearAddress:w}=await import("./near/index.js"),{validateRadixAddress:S}=await import("./radix/index.js"),{validateRippleAddress:P}=await import("./ripple/index.js"),{validateTronAddress:A}=await import("./tron/index.js"),{validateStellarAddress:R}=await import("./stellar/index.js");return function({address:n,chain:W}){return l(W).with(...c,()=>e(n)).with(...C,(T)=>g(T)(n)).with(...x,(T)=>i(T)(n)).with(...O,(T)=>p({chain:T})(n)).with(t.Aleo,()=>r(n)).with(t.Aptos,()=>s(n)).with(t.Radix,()=>S(n)).with(t.Hype,()=>m(n)).with(t.Near,()=>w(n)).with(t.Ripple,()=>P(n)).with(t.Solana,()=>h(n)).with(t.Stellar,()=>R(n)).with(t.Starknet,()=>u(n)).with(t.Sui,()=>d(n)).with(t.Ton,()=>f(n)).with(t.Tron,()=>A(n)).with(t.Cardano,()=>a(n)).otherwise(()=>!1)}}function F(l){return async function(s){let{match:e}=await import("ts-pattern");return e(l).returnType().with(...c,async(a)=>{let i=await b(a),p=await i.createTransaction(s),m="feeOptionKey"in s?s.feeOptionKey:v.Fast;return i.estimateTransactionFee({...p,feeOption:m})}).with(t.Bitcoin,t.BitcoinCash,t.Dogecoin,t.Dash,t.Litecoin,t.Solana,t.Ripple,t.Tron,t.Near,t.Cardano,t.Hype,async(a)=>(await b(a)).estimateTransactionFee(s)).with(t.Aptos,async()=>{let{getAptosToolbox:a}=await import("./aptos/index.js");return a().estimateTransactionFee(s)}).with(t.Aleo,async()=>{let{getAleoToolbox:a}=await import("./aleo/index.js");return a().estimateTransactionFee(s)}).with(t.Starknet,async()=>{let{getStarknetToolbox:a}=await import("./starknet/index.js");return(await a()).estimateTransactionFee(s)}).with(t.Stellar,async()=>{let{getStellarToolbox:a}=await import("./stellar/index.js");return a().estimateTransactionFee()}).with(t.Sui,async()=>{let{getSuiToolbox:a}=await import("./sui/index.js");return a().estimateTransactionFee(s)}).with(t.Ton,async()=>{let{getTONToolbox:a}=await import("./ton/index.js");return a().estimateTransactionFee(s)}).with(...x,async()=>{let{estimateTransactionFee:a}=await import("./cosmos/index.js");return a(s)}).otherwise(async()=>k.from({chain:l}))}}async function b(l,r){let{match:s}=await import("ts-pattern");return s(l).returnType().with(...c,async()=>{let{getEvmToolboxAsync:e}=await import("../chunk-bmj5dnhd.js");return await e(l,r)}).with(...C,async()=>{let{getUtxoToolbox:e}=await import("./utxo/index.js");return e(l,r)}).with(...x,async()=>{let{getCosmosToolbox:e}=await import("./cosmos/index.js");return e(l,r)}).with(t.Aleo,async()=>{let{getAleoToolbox:e}=await import("./aleo/index.js");return e(r)}).with(t.Aptos,async()=>{let{getAptosToolbox:e}=await import("./aptos/index.js");return e(r)}).with(t.Hype,async()=>{let{getHyperCoreToolbox:e}=await import("./hypercore/index.js");return e(r)}).with(t.Radix,async()=>{let{getRadixToolbox:e}=await import("./radix/index.js");return e(r)}).with(t.Ripple,async()=>{let{getRippleToolbox:e}=await import("./ripple/index.js");return e(r)}).with(t.Solana,async()=>{let{getSolanaToolbox:e}=await import("./solana/index.js");return e(r)}).with(t.Stellar,async()=>{let{getStellarToolbox:e}=await import("./stellar/index.js");return e(r)}).with(t.Starknet,async()=>{let{getStarknetToolbox:e}=await import("./starknet/index.js");return e(r)}).with(t.Sui,async()=>{let{getSuiToolbox:e}=await import("./sui/index.js");return e(r)}).with(t.Tron,async()=>{let{getTronToolbox:e}=await import("./tron/index.js");return e(r)}).with(t.Near,async()=>{let{getNearToolbox:e}=await import("./near/index.js");return e(r)}).with(t.Cardano,async()=>{let{getCardanoToolbox:e}=await import("./cardano/index.js");return e(r)}).with(t.Ton,async()=>{let{getTONToolbox:e}=await import("./ton/index.js");return e(r)}).otherwise(()=>{throw new V("toolbox_not_supported",{chain:l})})}export{H as getAddressValidator,F as getFeeEstimator,b as getToolbox};
1
+ import{ka as o}from"../chunk-pz8xe0qj.js";import{AssetValue as k,Chain as t,CosmosChains as x,EVMChains as c,FeeOption as v,SubstrateChains as O,SwapKitError as V,UTXOChains as C}from"@swapkit/helpers";async function H(){let{match:l}=await import("ts-pattern"),{validateAleoAddress:r}=await import("./aleo/index.js"),{validateAptosAddress:s}=await import("./aptos/index.js"),{validateEVMAddress:e}=await import("./evm/index.js"),{validateCardanoAddress:a}=await import("./cardano/index.js"),{getCosmosAddressValidator:i}=await import("./cosmos/index.js"),{getSubstrateAddressValidator:p}=await import("./substrate/index.js"),{validateHyperCoreAddress:m}=await import("./hypercore/index.js"),{validateSolanaAddress:h}=await import("./solana/index.js"),{validateStarknetAddress:u}=await import("./starknet/index.js"),{validateSuiAddress:d}=await import("./sui/index.js"),{validateTonAddress:f}=await import("./ton/index.js"),{getUTXOAddressValidator:g}=await import("./utxo/index.js"),{validateNearAddress:w}=await import("./near/index.js"),{validateRadixAddress:S}=await import("./radix/index.js"),{validateRippleAddress:P}=await import("./ripple/index.js"),{validateTronAddress:A}=await import("./tron/index.js"),{validateStellarAddress:R}=await import("./stellar/index.js");return function({address:n,chain:W}){return l(W).with(...c,()=>e(n)).with(...C,(T)=>g(T)(n)).with(...x,(T)=>i(T)(n)).with(...O,(T)=>p({chain:T})(n)).with(t.Aleo,()=>r(n)).with(t.Aptos,()=>s(n)).with(t.Radix,()=>S(n)).with(t.Hype,()=>m(n)).with(t.Near,()=>w(n)).with(t.Ripple,()=>P(n)).with(t.Solana,()=>h(n)).with(t.Stellar,()=>R(n)).with(t.Starknet,()=>u(n)).with(t.Sui,()=>d(n)).with(t.Ton,()=>f(n)).with(t.Tron,()=>A(n)).with(t.Cardano,()=>a(n)).otherwise(()=>!1)}}function F(l){return async function(s){let{match:e}=await import("ts-pattern");return e(l).returnType().with(...c,async(a)=>{let i=await b(a),p=await i.createTransaction(s),m="feeOptionKey"in s?s.feeOptionKey:v.Fast;return i.estimateTransactionFee({...p,feeOption:m})}).with(t.Bitcoin,t.BitcoinCash,t.Dogecoin,t.Dash,t.Litecoin,t.Solana,t.Ripple,t.Tron,t.Near,t.Cardano,t.Hype,async(a)=>(await b(a)).estimateTransactionFee(s)).with(t.Aptos,async()=>{let{getAptosToolbox:a}=await import("./aptos/index.js");return a().estimateTransactionFee(s)}).with(t.Aleo,async()=>{let{getAleoToolbox:a}=await import("./aleo/index.js");return a().estimateTransactionFee(s)}).with(t.Starknet,async()=>{let{getStarknetToolbox:a}=await import("./starknet/index.js");return(await a()).estimateTransactionFee(s)}).with(t.Stellar,async()=>{let{getStellarToolbox:a}=await import("./stellar/index.js");return a().estimateTransactionFee()}).with(t.Sui,async()=>{let{getSuiToolbox:a}=await import("./sui/index.js");return a().estimateTransactionFee(s)}).with(t.Ton,async()=>{let{getTONToolbox:a}=await import("./ton/index.js");return a().estimateTransactionFee(s)}).with(...x,async()=>{let{estimateTransactionFee:a}=await import("./cosmos/index.js");return a(s)}).otherwise(async()=>k.from({chain:l}))}}async function b(l,r){let{match:s}=await import("ts-pattern");return s(l).returnType().with(...c,async()=>{let{getEvmToolboxAsync:e}=await import("../chunk-3y8attb1.js");return await e(l,r)}).with(...C,async()=>{let{getUtxoToolbox:e}=await import("./utxo/index.js");return e(l,r)}).with(...x,async()=>{let{getCosmosToolbox:e}=await import("./cosmos/index.js");return e(l,r)}).with(t.Aleo,async()=>{let{getAleoToolbox:e}=await import("./aleo/index.js");return e(r)}).with(t.Aptos,async()=>{let{getAptosToolbox:e}=await import("./aptos/index.js");return e(r)}).with(t.Hype,async()=>{let{getHyperCoreToolbox:e}=await import("./hypercore/index.js");return e(r)}).with(t.Radix,async()=>{let{getRadixToolbox:e}=await import("./radix/index.js");return e(r)}).with(t.Ripple,async()=>{let{getRippleToolbox:e}=await import("./ripple/index.js");return e(r)}).with(t.Solana,async()=>{let{getSolanaToolbox:e}=await import("./solana/index.js");return e(r)}).with(t.Stellar,async()=>{let{getStellarToolbox:e}=await import("./stellar/index.js");return e(r)}).with(t.Starknet,async()=>{let{getStarknetToolbox:e}=await import("./starknet/index.js");return e(r)}).with(t.Sui,async()=>{let{getSuiToolbox:e}=await import("./sui/index.js");return e(r)}).with(t.Tron,async()=>{let{getTronToolbox:e}=await import("./tron/index.js");return e(r)}).with(t.Near,async()=>{let{getNearToolbox:e}=await import("./near/index.js");return e(r)}).with(t.Cardano,async()=>{let{getCardanoToolbox:e}=await import("./cardano/index.js");return e(r)}).with(t.Ton,async()=>{let{getTONToolbox:e}=await import("./ton/index.js");return e(r)}).otherwise(()=>{throw new V("toolbox_not_supported",{chain:l})})}export{H as getAddressValidator,F as getFeeEstimator,b as getToolbox};
@@ -1 +1 @@
1
- import{ka as b}from"../../chunk-pz8xe0qj.js";import{hexToU8a as M,isHex as _,u8aToHex as G}from"@polkadot/util";import{decodeAddress as T,encodeAddress as v}from"@polkadot/util-crypto";import{AssetValue as F,Chain as y,getRPCUrl as U,SubstrateChains as W,SwapKitError as d,SwapKitNumber as H}from"@swapkit/helpers";import{match as w,P as A}from"ts-pattern";import{AssetValue as K,Chain as B,SwapKitNumber as x}from"@swapkit/helpers";async function N(e,t,n){let a=[t.set(0)];if(!n)return a;try{let r=await e.query.system?.account?.(n);if(!r)return a;let{data:{free:i}}=r,c=x.fromBigInt(BigInt(i.toString()),t.decimal).getValue("string");return[t.set(c)]}catch(r){let i=r instanceof Error?r.message:String(r);return console.error(`Error fetching substrate balance: ${i}`),a}}async function j(e,t,n){let a=[t.set(0)];if(!n)return a;try{let r=await e.query.flip?.account?.(n);if(!r)return a;let i=r.balance||r.data?.balance;if(!i||i.isEmpty)return a;let c=x.fromBigInt(BigInt(i.toString()),t.decimal).getValue("string");return[t.set(c)]}catch(r){let i=r instanceof Error?r.message:String(r);return console.error(`Error fetching chainflip balance: ${i}`),a}}function I(e,t){return function(a){let r=K.from({chain:e});switch(e){case B.Chainflip:return j(t,r,a);default:return N(t,r,a)}}}var R={decimals:[10],displayName:"Polkadot Relay Chain",network:"polkadot",prefix:0,standardAccount:"*25519",symbols:["DOT"],website:"https://polkadot.network"},D={decimals:[18],displayName:"Chainflip",network:"chainflip",prefix:2112,standardAccount:"*25519",symbols:["FLIP"],website:"https://chainflip.io/"},V={decimals:[],displayName:"Substrate",network:"substrate",prefix:42,standardAccount:"*25519",symbols:[],website:"https://substrate.io/"},p={DOT:R,FLIP:D,GENERIC:V};function de(e,t){return w(e).with(...W,(n)=>ee({chain:n,...t})).exhaustive()}function f(e){return"address"in e}async function k(e,t){let{Keyring:n}=await import("@polkadot/keyring"),{cryptoWaitReady:a}=await import("@polkadot/util-crypto");return await a(),new n({ss58Format:t,type:"sr25519"}).addFromUri(e)}var S=(e,t)=>e.rpc.system.accountNextIndex(t),h=(e,{recipient:t,assetValue:n,sweep:a})=>{let r=a?e.tx.balances?.transferAll?.(t,!0):e.tx.balances?.transferAllowDeath?.(t,n.getBaseValue("number"));if(a&&!r)throw new d("toolbox_substrate_transfer_error");return r},m=(e,t)=>{if(e===y.Chainflip&&t)throw new d("toolbox_substrate_not_supported")},L=async(e,t,n)=>{let a=h(e,n);if(!a)throw new d("toolbox_substrate_transfer_error");let r=f(t),i=r?t.address:n.sender;if(!i)throw new d("core_transaction_invalid_sender_address");let c=await S(e,i);return(await a.signAndSend(r?t:i,{nonce:c,signer:r?void 0:t})).toString()},q=async(e,t,n,a)=>{let r=h(e,a),i=f(t)?t.address:a.sender;if(!i)return Promise.resolve(n.set(0));let c=await r?.paymentInfo(i,{nonce:await S(e,i)})||{partialFee:0};return n.set(H.fromBigInt(BigInt(c.partialFee.toString()),n.decimal).getValue("string"))},O=async(e,t)=>{if(t)return e.send(t);return(await e.send()).toString()},z=async(e,t)=>await t.signAsync(e),J=(e,t,n)=>{if(n)return t.signAndSend(e,n);return t.signAndSend(e).toString()},Q=async({signer:e,address:t,tx:n,callback:a,api:r})=>{let i=await S(r,t);if(a)n.signAndSend(t,{nonce:i,signer:e},a);return n.signAndSend(t,{nonce:i,signer:e}).toString()};function X(e,t){let n=T(e);return v(n,t)}function C(e,t){return _(e)?M(e):T(e,void 0,t)}function Y(e,t="ss58",n){if(t==="hex")return G(e);return v(e,n)}function Z({chain:e,prefix:t}){let n=t||w(e).with(y.Polkadot,()=>p.DOT.prefix).with(y.Chainflip,()=>p.FLIP.prefix).otherwise(()=>p.GENERIC.prefix);return function(r){if(typeof r!=="string"||_(r))return!1;try{return C(r,n).length===32}catch{return!1}}}function ee({chain:e,generic:t=!1,...n}){let a=F.from({chain:e}),r;async function i(){let{ApiPromise:s,WsProvider:o}=await import("@polkadot/api"),u=await U(e),l=new o(u);return s.create({noInitWarn:!0,provider:l})}async function c(){if(r)return r;return r=await w(n).with({phrase:A.string},({phrase:s})=>k(s,p[e].prefix)).with({signer:A.any},({signer:s})=>s).otherwise(()=>{return}),r}let g=t?p.GENERIC:p[e];async function P(s){let o=await c(),u=s||o;if(!u)throw new d("core_wallet_not_keypair_wallet");return f(u)?u.address:void 0}return{broadcast:O,convertAddress:X,createKeyring:(s)=>k(s,g.prefix),createTransaction:async(s)=>{m(e,s.sweep);let o=await i();return h(o,s)},decodeAddress:C,encodeAddress:Y,estimateTransactionFee:async(s)=>{m(e,s.sweep);let o=await c();if(!o)throw new d("core_wallet_not_keypair_wallet");let u=await i();return q(u,o,a,s)},gasAsset:a,getAddress:P,getApi:i,getBalance:async(s)=>{let o=await i(),u=I(e,o),l=s||await P();return u(l)},network:g,sign:async(s)=>{let o=await c();if(!o)throw new d("core_wallet_not_keypair_wallet");if(f(o))return z(o,s);throw new d("core_wallet_not_keypair_wallet","Signer does not have keyring pair capabilities required for signing.")},signAndBroadcast:async({tx:s,callback:o,address:u})=>{let l=await c();if(!l)throw new d("core_wallet_not_keypair_wallet");if(f(l))return J(l,s,o);let E=await i();if(u)return Q({address:u,api:E,callback:o,signer:l,tx:s});throw new d("core_wallet_not_keypair_wallet","Signer does not have keyring pair capabilities required for signing.")},transfer:async(s)=>{m(e,s.sweep);let o=await c();if(!o)throw new d("core_wallet_not_keypair_wallet");let u=await i();return L(u,o,s)},validateAddress:Z({chain:e,prefix:g.prefix})}}export{p as SubstrateNetwork,k as createKeyring,ee as createSubstrateToolbox,Z as getSubstrateAddressValidator,de as getSubstrateToolbox,f as isKeyringPair};
1
+ import{ka as b}from"../../chunk-pz8xe0qj.js";import{hexToU8a as M,isHex as _,u8aToHex as G}from"@polkadot/util";import{decodeAddress as T,encodeAddress as v}from"@polkadot/util-crypto";import{AssetValue as F,Chain as y,getRPCUrl as U,SubstrateChains as W,SwapKitError as d,SwapKitNumber as H}from"@swapkit/helpers";import{match as w,P as A}from"ts-pattern";import{AssetValue as K,Chain as B,SwapKitNumber as x}from"@swapkit/helpers";async function N(e,t,n){let a=[t.set(0)];if(!n)return a;try{let r=await e.query.system?.account?.(n);if(!r)return a;let{data:{free:i}}=r,c=x.fromBigInt(BigInt(i.toString()),t.decimal).getValue("string");return[t.set(c)]}catch(r){let i=r instanceof Error?r.message:String(r);return console.error(`Error fetching substrate balance: ${i}`),a}}async function j(e,t,n){let a=[t.set(0)];if(!n)return a;try{let r=await e.query.flip?.account?.(n);if(!r)return a;let i=r.balance||r.data?.balance;if(!i||i.isEmpty)return a;let c=x.fromBigInt(BigInt(i.toString()),t.decimal).getValue("string");return[t.set(c)]}catch(r){let i=r instanceof Error?r.message:String(r);return console.error(`Error fetching chainflip balance: ${i}`),a}}function I(e,t){return function(a){let r=K.from({chain:e});switch(e){case B.Chainflip:return j(t,r,a);default:return N(t,r,a)}}}var R={decimals:[10],displayName:"Polkadot Relay Chain",network:"polkadot",prefix:0,standardAccount:"*25519",symbols:["DOT"],website:"https://polkadot.network"},D={decimals:[18],displayName:"Chainflip",network:"chainflip",prefix:2112,standardAccount:"*25519",symbols:["FLIP"],website:"https://chainflip.io/"},V={decimals:[],displayName:"Substrate",network:"substrate",prefix:42,standardAccount:"*25519",symbols:[],website:"https://substrate.io/"},p={DOT:R,FLIP:D,GENERIC:V};function de(e,t){return w(e).with(...W,(n)=>ee({chain:n,...t})).exhaustive()}function f(e){return"address"in e}async function k(e,t){let{Keyring:n}=await import("@polkadot/keyring"),{cryptoWaitReady:a}=await import("@polkadot/util-crypto");return await a(),new n({ss58Format:t,type:"sr25519"}).addFromUri(e)}var S=(e,t)=>e.rpc.system.accountNextIndex(t),h=(e,{recipient:t,assetValue:n,sweep:a})=>{let r=a?e.tx.balances?.transferAll?.(t,!0):e.tx.balances?.transferAllowDeath?.(t,n.getBaseValue("bigint"));if(a&&!r)throw new d("toolbox_substrate_transfer_error");return r},m=(e,t)=>{if(e===y.Chainflip&&t)throw new d("toolbox_substrate_not_supported")},L=async(e,t,n)=>{let a=h(e,n);if(!a)throw new d("toolbox_substrate_transfer_error");let r=f(t),i=r?t.address:n.sender;if(!i)throw new d("core_transaction_invalid_sender_address");let c=await S(e,i);return(await a.signAndSend(r?t:i,{nonce:c,signer:r?void 0:t})).toString()},q=async(e,t,n,a)=>{let r=h(e,a),i=f(t)?t.address:a.sender;if(!i)return Promise.resolve(n.set(0));let c=await r?.paymentInfo(i,{nonce:await S(e,i)})||{partialFee:0};return n.set(H.fromBigInt(BigInt(c.partialFee.toString()),n.decimal).getValue("string"))},O=async(e,t)=>{if(t)return e.send(t);return(await e.send()).toString()},z=async(e,t)=>await t.signAsync(e),J=async(e,t,n)=>{if(n)return t.signAndSend(e,n);return(await t.signAndSend(e)).toString()},Q=async({signer:e,address:t,tx:n,callback:a,api:r})=>{let i=await S(r,t);if(a)return n.signAndSend(t,{nonce:i,signer:e},a);return(await n.signAndSend(t,{nonce:i,signer:e})).toString()};function X(e,t){let n=T(e);return v(n,t)}function C(e,t){return _(e)?M(e):T(e,void 0,t)}function Y(e,t="ss58",n){if(t==="hex")return G(e);return v(e,n)}function Z({chain:e,prefix:t}){let n=t||w(e).with(y.Polkadot,()=>p.DOT.prefix).with(y.Chainflip,()=>p.FLIP.prefix).otherwise(()=>p.GENERIC.prefix);return function(r){if(typeof r!=="string"||_(r))return!1;try{return C(r,n).length===32}catch{return!1}}}function ee({chain:e,generic:t=!1,...n}){let a=F.from({chain:e}),r;async function i(){let{ApiPromise:s,WsProvider:o}=await import("@polkadot/api"),u=await U(e),l=new o(u);return s.create({noInitWarn:!0,provider:l})}async function c(){if(r)return r;return r=await w(n).with({phrase:A.string},({phrase:s})=>k(s,p[e].prefix)).with({signer:A.any},({signer:s})=>s).otherwise(()=>{return}),r}let g=t?p.GENERIC:p[e];async function P(s){let o=await c(),u=s||o;if(!u)throw new d("core_wallet_not_keypair_wallet");return f(u)?u.address:void 0}return{broadcast:O,convertAddress:X,createKeyring:(s)=>k(s,g.prefix),createTransaction:async(s)=>{m(e,s.sweep);let o=await i();return h(o,s)},decodeAddress:C,encodeAddress:Y,estimateTransactionFee:async(s)=>{m(e,s.sweep);let o=await c();if(!o)throw new d("core_wallet_not_keypair_wallet");let u=await i();return q(u,o,a,s)},gasAsset:a,getAddress:P,getApi:i,getBalance:async(s)=>{let o=await i(),u=I(e,o),l=s||await P();return u(l)},network:g,sign:async(s)=>{let o=await c();if(!o)throw new d("core_wallet_not_keypair_wallet");if(f(o))return z(o,s);throw new d("core_wallet_not_keypair_wallet","Signer does not have keyring pair capabilities required for signing.")},signAndBroadcast:async({tx:s,callback:o,address:u})=>{let l=await c();if(!l)throw new d("core_wallet_not_keypair_wallet");if(f(l))return J(l,s,o);let E=await i();if(u)return Q({address:u,api:E,callback:o,signer:l,tx:s});throw new d("core_wallet_not_keypair_wallet","Signer does not have keyring pair capabilities required for signing.")},transfer:async(s)=>{m(e,s.sweep);let o=await c();if(!o)throw new d("core_wallet_not_keypair_wallet");let u=await i();return L(u,o,s)},validateAddress:Z({chain:e,prefix:g.prefix})}}export{p as SubstrateNetwork,k as createKeyring,ee as createSubstrateToolbox,Z as getSubstrateAddressValidator,de as getSubstrateToolbox,f as isKeyringPair};
@@ -1,2 +1,2 @@
1
- import{ia as St,ja as tr}from"../../chunk-qk8kg62t.js";import"../../chunk-pz8xe0qj.js";import{NetworkDerivationPath as Kr}from"@swapkit/helpers";function Z(e,t){if(!Number.isInteger(t)||t<0)throw RangeError(`${e} must be a non-negative integer, got: ${t}`)}function re({accountIndex:e,chain:t,derivationPath:r}){if(e!==void 0)Z("accountIndex",e);let[n,o,i]=r??Kr[t];return[n,o,e??i]}function Oe({accountIndex:e,change:t=!1,chain:r,derivationPath:n,index:o}){return Z("index",o),[...re({accountIndex:e,chain:r,derivationPath:n}),Number(t),o]}function pe(e){return e[2]??0}function Fr({deriveAddress:e,getBalance:t,getUtxos:r}){async function n(s){let{accountIndex:p,count:c,startIndex:u=0,change:a=!1}=s;if(Z("count",c),c<1)throw RangeError("count must be at least 1");Z("startIndex",u);let l=[];for(let h=0;h<c;h++){let m=await e({accountIndex:p,change:a,index:u+h});if(m)l.push(m)}return l}async function o(s){let{gapLimit:p=20,change:c=!1}=s??{},u=[],a=0,l=0;while(a<p){let h=await e({change:c,index:l});if(!h)break;if((await t(h.address)).some((y)=>y.getValue("number")>0))u.push(h),a=0;else a++;l++}return u}async function i(s=20){let[p,c]=await Promise.all([o({change:!1,gapLimit:s}),o({change:!0,gapLimit:s})]),u=[...p,...c],a=await Promise.all(u.map(async(h)=>{let f=(await t(h.address)).reduce((y,x)=>y+x.getValue("number"),0);return{...h,balance:f}})),l=a.reduce((h,m)=>h+m.balance,0);return{addresses:a,total:l}}async function d(s=20){let[p,c]=await Promise.all([o({change:!1,gapLimit:s}),o({change:!0,gapLimit:s})]),u=[...p,...c];return(await Promise.all(u.map(async(l)=>(await r(l.address)).map((m)=>({...m,address:l.address,derivationIndex:l.index,isChange:l.change}))))).flat()}return{deriveAddresses:n,getAggregatedBalance:i,getAggregatedUtxos:d,scanForAddresses:o}}import{Chain as C,getRPCUrl as Dr,RequestClient as Re,SKConfig as Ct,SwapKitError as R,warnOnce as Ir}from"@swapkit/helpers";import{NETWORKS as le}from"@swapkit/utxo-signer";async function Hr({chain:e,txHash:t}){let r=`${he(e)}/push/transaction`,n=JSON.stringify({data:t});try{let o=await Re.post(r,{body:n,headers:{"Content-Type":"application/json"}});if(o.context.code!==200)throw new R("toolbox_utxo_broadcast_failed",{error:o.context.error||"Transaction broadcast failed"});return o.data?.transaction_hash||t}catch(o){let i=await Dr(e);if(i){let d=JSON.stringify({id:St(),jsonrpc:"2.0",method:"sendrawtransaction",params:[t]}),s=await Re.post(i,{body:d,headers:{"Content-Type":"application/json"}});if(s.error)throw new R("toolbox_utxo_broadcast_failed",{error:s.error?.message});if(s.result.includes('"code":-26'))throw new R("toolbox_utxo_invalid_transaction",{error:"Transaction amount was too low"});return s.result}throw o}}function he(e){return`${(Ct.get("blockchairApiUrl")||"https://api.blockchair.com").replace(/\/+$/,"")}/${Rr(e)}`}function At(e){switch(e){case C.Bitcoin:return 5;case C.Dogecoin:return 1e4;case C.Litecoin:return 1;case C.Zcash:return 1;default:return 2}}function Rr(e){switch(e){case C.BitcoinCash:return"bitcoin-cash";case C.Litecoin:return"litecoin";case C.Dash:return"dash";case C.Dogecoin:return"dogecoin";case C.Zcash:return"zcash";case C.Polkadot:return"polkadot";default:return"bitcoin"}}async function Mr(e){try{let{feePerKb:t}=await Re.get(`https://app.bitgo.com/api/v2/${e.toLowerCase()}/tx/fee`),r=t/1000;return Math.max(r,At(e))}catch{return At(e)}}async function Se(e,t){let r=await Re.get(`${e}${t?`${e.includes("?")?"&":"?"}key=${t}`:""}`);if(!r||r.context.code!==200)throw new R("toolbox_utxo_api_error",{error:`Failed to query ${e}`});return r.data}async function Er({chain:e,apiKey:t}){let r=await Se(`${he(e)}/stats`,t);if(typeof r.best_block_height!=="number")throw new R("toolbox_utxo_api_error",{error:"Missing best_block_height in stats response"});return r.best_block_height}async function Xt({address:e,chain:t,apiKey:r}){if(!e)throw new R("toolbox_utxo_invalid_params",{error:"Address is required"});try{return(await Se(`${he(t)}/dashboards/address/${e}?transaction_details=true`,r))[e]}catch{return{address:{balance:0,transaction_count:0},utxo:[]}}}async function Nr({address:e,chain:t,apiKey:r}){return(await Xt({address:e,apiKey:r,chain:t}))?.address.balance||0}async function Bt({chain:e,apiKey:t,txHash:r}){if(!r)throw new R("toolbox_utxo_invalid_params",{error:"TxHash is required"});try{return(await Se(`${he(e)}/raw/transaction/${r}`,t))?.[r]?.raw_transaction||""}catch(n){let o=n instanceof Error?n.message:String(n);return console.error(`Failed to fetch raw transaction: ${o}`),""}}var Wr=4294967294;async function Zr({chain:e,apiKey:t,txHash:r}){if(!r)throw new R("toolbox_utxo_invalid_params",{error:"TxHash is required"});let o=(await Se(`${he(e)}/dashboards/transaction/${r}`,t))?.[r];if(!o)throw new R("toolbox_utxo_tx_not_found",{txHash:r});let{transaction:i,inputs:d,outputs:s}=o,p=d.map((u)=>u.spending_sequence),c=i.is_rbf===!0||p.some((u)=>u<Wr);return{blockId:i.block_id,confirmed:i.block_id!==-1,fee:i.fee,inputs:d,isRBF:c,outputs:s,sequences:p,size:i.size,txid:i.hash,weight:i.weight}}async function zr({chain:e,address:t,apiKey:r,offset:n=0,limit:o=30}){return(await Se(`${he(e)}/outputs?q=recipient(${t}),is_spent(false)&s=value(desc)&fields=is_spent,transaction_hash,index,value,script_hex,block_id,spending_signature_hex&limit=${o}&offset=${n}`,r)).map(({is_spent:p,script_hex:c,block_id:u,transaction_hash:a,index:l,value:h,spending_signature_hex:m})=>({hash:a,index:l,is_confirmed:u!==-1,is_spent:p,script_hex:c,txHex:m,value:h}))}function $r(e){return e.reduce((t,r)=>t+r.value,0)}function Ot(e,t){let r=[...e].sort((n,o)=>o.value-n.value);if(t){let n=[],o=0;for(let i of r)if(n.push(i),o+=i.value,o>=t)break;return n}return r}async function kt({chain:e,address:t,apiKey:r,targetValue:n,accumulativeValue:o=0,offset:i=0,limit:d=30}){if(!t)throw new R("toolbox_utxo_invalid_params",{error:"Address is required"});try{let s=await zr({address:t,apiKey:r,chain:e,limit:d,offset:i,targetValue:n}),c=s.length<d,u=s.filter(({is_spent:y})=>!y),a=$r(u),l=o+a,h=n&&l>=n;if(c||h)return Ot(u,n);let m=await kt({accumulativeValue:l,address:t,apiKey:r,chain:e,limit:d,offset:i+d,targetValue:n}),f=[...u,...m];return Ot(f,n)}catch(s){let p=s instanceof Error?s.message:String(s);return console.error(`Failed to fetch unspent UTXOs: ${p}`),[]}}async function Lr({address:e,chain:t,apiKey:r,fetchTxHex:n=!0,targetValue:o}){let i=await kt({address:e,apiKey:r,chain:t,targetValue:o}),d=n?await Promise.all(i.map(({hash:s})=>Bt({apiKey:r,chain:t,txHash:s}))):[];return i.map(({hash:s,index:p,script_hex:c,value:u},a)=>({address:e,hash:s,index:p,txHex:n?d[a]:void 0,value:u,witnessUtxo:{script:Buffer.from(c,"hex"),value:u}}))}function A(e){let t=Ct.get("apiKeys").blockchair||"";return Ir({condition:!t,id:"no_blockchair_api_key_warning",warning:"No Blockchair API key found. Functionality will be limited."}),{broadcastTx:(r)=>Hr({chain:e,txHash:r}),getAddressData:(r)=>Xt({address:r,apiKey:t,chain:e}),getBalance:(r)=>Nr({address:r,apiKey:t,chain:e}),getBlockHeight:()=>Er({apiKey:t,chain:e}),getRawTx:(r)=>Bt({apiKey:t,chain:e,txHash:r}),getSuggestedTxFee:()=>Mr(e),getTransactionDetails:(r)=>Zr({apiKey:t,chain:e,txHash:r}),getUtxos:(r)=>Lr({...r,apiKey:t,chain:e})}}function Lo(e){return e}function Vo(){return function(t){switch(t){case C.Bitcoin:return le.bitcoin;case C.BitcoinCash:return le.bitcoinCash;case C.Dash:return le.dash;case C.Litecoin:return le.litecoin;case C.Dogecoin:return le.dogecoin;case C.Zcash:return le.zcash;default:throw new R("toolbox_utxo_not_supported",{chain:t})}}}import{sha256 as Qr}from"@noble/hashes/sha2.js";import{createBase58check as en}from"@scure/base";import{SwapKitError as Ft}from"@swapkit/helpers";import{CashAddrType as Me,decodeCashAddr as Vr,encodeCashAddr as qr}from"@swapkit/utxo-signer";var Yr={P2PKH:Me.P2PKH,P2SH:Me.P2SH},Gr={[Me.P2PKH]:"P2PKH",[Me.P2SH]:"P2SH"};function jr(e,t,r){return qr({hash:r,prefix:e,type:Yr[t]})}function Jr(e){let t=Vr(e),r=Gr[t.type];if(!r)throw Error(`Unknown CashAddr type: ${t.type}`);return{hash:t.hash,prefix:t.prefix,type:r}}var st={decode:Jr,encode:jr};var Dt=en(Qr);var It;((r)=>{r.Mainnet="mainnet";r.Testnet="testnet"})(It||={});var ne={["legacy"]:{["mainnet"]:{["p2pkh"]:0,["p2sh"]:5},["testnet"]:{["p2pkh"]:111,["p2sh"]:196}},["bitpay"]:{["mainnet"]:{["p2pkh"]:28,["p2sh"]:40},["testnet"]:{["p2pkh"]:111,["p2sh"]:196}}},tn={["p2pkh"]:"pkh",["p2sh"]:"sh"};function ts(e){return Ne(e)!==void 0}function rs(e){return it(e).network}function G(e){let t=it(e);if(t.format==="legacy")return e;return on(t)}function Ee(e){let t=it(e);return sn(t)}function Ne(e){if(typeof e!=="string")return;let t=rn(e)??nn(e);return t&&{...t,scriptType:tn[t.type]}}function it(e){let t=Ne(e);if(!t)throw new Ft("toolbox_utxo_invalid_address",{address:e});return t}function rn(e){try{let t=Dt.decode(e);if(t.length!==21)throw new Ft("toolbox_utxo_invalid_address",{address:e});let r=t[0],n=Array.prototype.slice.call(t,1);switch(r){case ne.legacy.mainnet.p2pkh:return{format:"legacy",hash:n,network:"mainnet",type:"p2pkh"};case ne.legacy.mainnet.p2sh:return{format:"legacy",hash:n,network:"mainnet",type:"p2sh"};case ne.legacy.testnet.p2pkh:return{format:"legacy",hash:n,network:"testnet",type:"p2pkh"};case ne.legacy.testnet.p2sh:return{format:"legacy",hash:n,network:"testnet",type:"p2sh"};case ne.bitpay.mainnet.p2pkh:return{format:"bitpay",hash:n,network:"mainnet",type:"p2pkh"};case ne.bitpay.mainnet.p2sh:return{format:"bitpay",hash:n,network:"mainnet",type:"p2sh"};default:return}}catch{return}}function nn(e){if(e.indexOf(":")!==-1)try{return Kt(e)}catch{}else{let t=["bitcoincash","bchtest","bchreg"];for(let r of t)try{return Kt(`${r}:${e}`)}catch{}}return}function Kt(e){try{let{hash:t,prefix:r,type:n}=st.decode(e);return{format:"cashaddr",hash:Array.prototype.slice.call(t,0),network:r==="bitcoincash"?"mainnet":"testnet",type:n==="P2PKH"?"p2pkh":"p2sh"}}catch{return}}function on(e){let t=ne.legacy[e.network][e.type],r=Buffer.alloc(1+e.hash.length);return r[0]=t,r.set(e.hash,1),Dt.encode(r)}function sn(e){let t=e.network==="mainnet"?"bitcoincash":"bchtest",r=e.type==="p2pkh"?"P2PKH":"P2SH",n=new Uint8Array(e.hash);return st.encode(t,r,n)}import{Chain as ae,SwapKitError as mt}from"@swapkit/helpers";import{SwapKitError as qe,UTXO_SCRIPT_TYPE_LIST as On,UTXO_SCRIPT_TYPES as Vt,UTXOScriptType as Ye}from"@swapkit/helpers";import{Script as Sn}from"@swapkit/utxo-signer";import{Chain as Ht}from"@swapkit/helpers";import{getAddressScriptType as cn,getZcashAddressType as dn}from"@swapkit/utxo-signer";import{match as un}from"ts-pattern";import{Chain as fe}from"@swapkit/helpers";import{NETWORKS as Te}from"@swapkit/utxo-signer";import{match as an}from"ts-pattern";function U(e){return an(e).with(fe.Bitcoin,()=>Te.bitcoin).with(fe.BitcoinCash,()=>Te.bitcoinCash).with(fe.Dash,()=>Te.dash).with(fe.Dogecoin,()=>Te.dogecoin).with(fe.Litecoin,()=>Te.litecoin).with(fe.Zcash,()=>Te.zcash).exhaustive()}function z(e){return e.replace(/(bchtest:|bitcoincash:)/,"")}function Ce(e){if(typeof e!=="string")return null;let t=Ne(z(e));if(!t||t.network!=="mainnet")return null;return t.scriptType}function j({address:e,chain:t}){return un(t).with(Ht.BitcoinCash,()=>Ce(e)).with(Ht.Zcash,()=>dn(e)).otherwise(()=>cn(e,U(t)))}import{Chain as oe,derivationPathToString as Rt,getPurposeFromPath as pn,getUTXOScriptTypeForPath as Mt,getUTXOScriptTypeForPurpose as Wt,resolveDerivationPath as ln,SwapKitError as Xe,UTXO_SCRIPT_TYPE_LIST as Et,UTXO_SCRIPT_TYPES as me,UTXOChains as hn,UTXOScriptType as O,updateDerivationPath as fn,warnOnce as Tn}from"@swapkit/helpers";import{CashAddrPrefix as mn,CashAddrType as yn,encodeCashAddr as gn,OutScript as Zt,p2pkh as xn,p2sh as bn,p2tr as wn,p2wpkh as Nt}from"@swapkit/utxo-signer";var We=Object.freeze([O.P2PKH]),Pn=Object.freeze({[oe.Bitcoin]:Et,[oe.BitcoinCash]:We,[oe.Dash]:We,[oe.Dogecoin]:We,[oe.Litecoin]:Et,[oe.Zcash]:We});function ze(e){return Pn[e]}function ct(e){return ze(e).some((t)=>me[t].witness)}function ye(e,t){return ze(e).includes(t)}function $e(e,t){if(ye(e,t))return t;throw new Xe("toolbox_utxo_unsupported_script_type",{chain:e,error:`${e} cannot encode ${t}; supported: ${ze(e).join(", ")}`,scriptType:t,supported:ze(e)})}var zt=hn.filter((e)=>!ct(e));function Un({purpose:e,scriptType:t}){let r=Wt(e);return r===void 0||r===t}function dt({chain:e,purpose:t,scriptType:r}){Tn({condition:!Un({purpose:t,scriptType:r}),id:`utxo_off_standard_encoding_${e}_${t}_${r}`,warning:`${e}: encoding m/${t}' keys as ${r}, not the ${Wt(t)} the path implies. No other wallet derives these addresses: move funds out of them, never receive into them.`})}function Le({chain:e,derivationPath:t,index:r=0,scriptType:n}){if(t){if(!n){let s=Mt(t);throw new Xe("toolbox_utxo_invalid_params",{chain:e,derivationPath:Rt(t),error:`scriptType is required alongside derivationPath: getUTXOScriptTypeForPath gives the standard one${s?` (${s})`:""}, or state another deliberately.`})}return $e(e,n),dt({chain:e,purpose:pn(t),scriptType:n}),{derivationPath:t,scriptType:n}}let o=ln({chain:e,index:r}),i=n?fn(o,{purpose:me[n].purpose}):o,d=n??Mt(i);if(!d)throw new Xe("toolbox_utxo_invalid_params",{chain:e,derivationPath:Rt(i),error:`${e}: the default derivation path has no standard script type`});return $e(e,d),{derivationPath:i,scriptType:d}}function _n(e){return e.length===32?e:e.slice(1)}function Ze(e,t){if(!e.address)throw new Xe("toolbox_utxo_invalid_address",{error:`Could not derive a ${t} address`});return e}var vn={[O.P2PKH]:(e,t)=>{let{address:r,script:n}=Ze(xn(e,t),O.P2PKH);return{address:r,script:n}},[O.P2SH_P2WPKH]:(e,t)=>{let r=Nt(e,t),{address:n,script:o}=Ze(bn(r,t),O.P2SH_P2WPKH);return{address:n,redeemScript:r.script,script:o}},[O.P2WPKH]:(e,t)=>{let{address:r,script:n}=Ze(Nt(e,t),O.P2WPKH);return{address:r,script:n}},[O.P2TR]:(e,t)=>{let r=_n(e),{address:n,script:o}=Ze(wn(r,void 0,t),O.P2TR);return{address:n,script:o,tapInternalKey:r}}};function Ve(e,t,r){return vn[e](t,r)}function ut(e,t){if(e!==oe.BitcoinCash)return t.address;let r=Zt.decode(t.script);if(r.type!=="pkh")throw new Xe("toolbox_utxo_invalid_address",{chain:e,error:`Cannot encode ${r.type} as CashAddr`});return gn({hash:r.hash,prefix:mn.MAINNET,type:yn.P2PKH}).replace(/^bitcoincash:/,"")}var An=Object.freeze({pkh:O.P2PKH,sh:O.P2SH_P2WPKH,tr:O.P2TR,wpkh:O.P2WPKH}),at=Object.freeze({pkh:me[O.P2PKH].outputSize,sh:me[O.P2SH_P2WPKH].outputSize,tr:me[O.P2TR].outputSize,wpkh:me[O.P2WPKH].outputSize,wsh:43});function $t(e){return e in at}function Lt(e){if(e==="tex")return at.pkh;return $t(e)?at[e]:void 0}function Be(e){return An[e]}function pt(e){try{let{type:t}=Zt.decode(e);return $t(t)?Be(t):void 0}catch{return}}import{UTXOScriptType as ie}from"@swapkit/helpers";var ws=1000,ht=10,Cn=2,Xn=10;function M(e){let t=new Uint8Array(Buffer.from(e,"utf8"));return Sn.encode(["RETURN",t])}function qt(e){return Object.fromEntries(On.map((t)=>[t,Vt[t][e]]))}var Yt=qt("inputSize"),lt=qt("outputSize"),ft=(e)=>Vt[e].witness,Ge=(e,t)=>{let r=j({address:e,chain:t});if(!r)throw new qe("toolbox_utxo_invalid_address",{address:e,chain:t});let n=Be(r);if(!n||!ye(t,n))throw new qe("toolbox_utxo_unsupported_script_type",{address:e,addressType:r,chain:t,error:"Address is valid but its script type is not one the SDK spends from"});return n},Bn=(e,t)=>{let r=j({address:e,chain:t});if(!r)throw new qe("toolbox_utxo_invalid_address",{address:e,chain:t});let n=Lt(r);if(!n)throw new qe("toolbox_utxo_unsupported_script_type",{address:e,addressType:r,chain:t,error:"Address is valid but a transparent transaction cannot pay to it"});return n},ge=({chain:e,inputs:t,outputs:r,feeRate:n})=>{let o=t[0]?ke(t[0],e):Ye.P2PKH,i=n?t.filter((u)=>u.value>=Yt["type"in u&&u.type?u.type:Ye.P2PKH]*Math.ceil(n)):t,d=0,s=0;for(let u of i)if(d+=se(u,e),!ft(ke(u,e)))s++;let p=r?.reduce((u,a)=>u+je(a,e),0)||lt[o],c=s<i.length;return ht+d+p+Tt(c,s)},ke=(e,t)=>{if("type"in e&&e.type)return e.type;if("address"in e&&e.address)return Ge(e.address,t);return Ye.P2PKH},se=(e,t)=>Yt[ke(e,t)],Tt=(e,t)=>e?Math.ceil((Cn+t)/4):0,je=(e,t,r)=>{if(e?.script)return Xn+e.script.length+(e.script.length>=74?2:1);if(r)return lt[r];if("address"in e&&e.address)return Bn(e.address,t);return lt[Ye.P2PKH]};function Ke(e){switch(e){case ae.Bitcoin:case ae.BitcoinCash:return 550;case ae.Dash:case ae.Litecoin:return 5500;case ae.Dogecoin:return 1e5;case ae.Zcash:return 546;default:throw new mt("toolbox_utxo_not_supported",{chain:e})}}function E({inputs:e,outputs:t,feeRate:r=1,chain:n=ae.Bitcoin,changeAddress:o="",sweep:i=!1}){let d=Ke(n),s=e.filter((f)=>{let y=se(f,n)*r;return i?f.value>Math.max(y,d):y<=f.value});if(i){let f=Math.ceil(r*ge({chain:n,inputs:s,outputs:t})),y=s.reduce((X,q)=>X+q.value,0),x=y-f;if(x<=d)throw new mt("toolbox_sweep_amount_too_low",{available:y,dustThreshold:d,fee:f});let S=t.findIndex((X)=>("address"in X)&&X.address);if(S===-1)throw new mt("toolbox_utxo_invalid_params",{error:"Sweep requires a recipient output"});return{fee:f,inputs:s,outputs:t.map((X,q)=>q===S?{...X,value:x}:X)}}let p=ht+t.reduce((f,y)=>f+je(y,n),0),c=t.reduce((f,y)=>f+y.value,0),u=0,a=0,l=!1,h=0,m=[];for(let f of s){if(u+=se(f,n),ft(ke(f,n)))l=!0;else a++;h+=f.value,m.push(f);let y=(p+u+Tt(l,a))*r,x=y+c;if(h<x)continue;let S=h-x,X=r*je({address:o,value:0},n);if(S>X){let q=X+y,Ue=h-(c+Math.ceil(q));if(Ue>Math.max(se({value:0},n)*r,Ke(n)))return{fee:Math.ceil(q),inputs:m,outputs:t.concat({address:o,value:Ue})}}return{fee:Math.ceil(y),inputs:m,outputs:t}}return{fee:Math.ceil(r*ge({chain:n,inputs:e,outputs:t}))}}import{secp256k1 as kn}from"@noble/curves/secp256k1.js";import{base64 as Kn,utf8 as Gt}from"@scure/base";import{SwapKitError as Fn,UTXOScriptType as yt}from"@swapkit/helpers";import{CompactSize as Dn,utils as In}from"@swapkit/utxo-signer";var Hn=Gt.decode(`\x18Bitcoin Signed Message:
2
- `),jt={[yt.P2PKH]:31,[yt.P2SH_P2WPKH]:35,[yt.P2WPKH]:39};function Rn(e){return jt[e]!==void 0}function Mn(e){let t=Gt.decode(e);return In.sha256x2(Hn,Dn.encode(BigInt(t.length)),t)}function Jt({message:e,privateKey:t,scriptType:r}){let n=jt[r];if(n===void 0)throw new Fn("toolbox_utxo_unsupported_script_type",{error:`BIP-137 message signatures cannot express a ${r} address`,scriptType:r});let o=kn.sign(Mn(e),t,{format:"recovered",prehash:!1}),[i=0]=o,d=new Uint8Array(65);return d[0]=n+i,d.set(o.subarray(1),1),Kn.encode(d)}import{Chain as Pe,SwapKitError as Eo}from"@swapkit/helpers";import{hex as hr}from"@scure/base";import{Chain as io,derivationPathToString as ao,FeeOption as co,resolveDerivationPath as uo,SwapKitError as L}from"@swapkit/helpers";import{BCHSigHash as po,CashAddrPrefix as fr,CashAddrType as Tr,encodeCashAddr as mr,NETWORKS as lo,p2pkh as yr,Transaction as gr}from"@swapkit/utxo-signer";import{secp256k1 as En}from"@noble/curves/secp256k1.js";import{hex as J}from"@scure/base";import{HDKey as rr}from"@scure/bip32";import{mnemonicToSeedSync as bt}from"@scure/bip39";import{AssetValue as gt,applyFeeMultiplier as Qt,Chain as be,derivationPathToString as Fe,FeeOption as N,NetworkDerivationPath as Nn,SwapKitError as P,SwapKitNumber as Wn,UTXO_SCRIPT_TYPES as Zn,warnOnce as zn}from"@swapkit/helpers";import{BCHSigHash as nr,RBF_SEQUENCE as $n,SigHash as er,Transaction as Je,utils as Ln,WIF as or}from"@swapkit/utxo-signer";var Qe=[be.Bitcoin];function sr({address:e,chain:t}){return j({address:e,chain:t})!==null}function Vn({phrase:e,derivationPath:t,network:r,seed:n}){let o=n??bt(e),d=rr.fromMasterSeed(o,r.bip32).derive(t);if(!d.privateKey)throw new P("toolbox_utxo_invalid_params",{error:"Could not derive private key from phrase"});return d.privateKey}function xt(e){return En.getPublicKey(e,!0)}function De({publicKey:e,chain:t,network:r,scriptType:n}){return ut(t,Ve(n,e,r))}function xe({phrase:e,derivationPath:t,chain:r,wif:n,seed:o}){let i=U(r);if(n){let c=or(i).decode(n),u=xt(c);return{privateKey:c,publicKey:u}}if(!e)throw new P("toolbox_utxo_invalid_params",{error:"Either phrase or wif must be provided"});let d=t||Fe(Nn[r]),s=Vn({derivationPath:d,network:i,phrase:e,seed:o}),p=xt(s);return{privateKey:s,publicKey:p}}function qn(e,t){return or(U(t)).encode(e)}function Yn({phrase:e,derivationPath:t,chain:r,seed:n}){let o=t.split("/");if(o.length<4)throw new P("toolbox_utxo_invalid_params",{error:`Derivation path must have at least 4 levels (got ${o.length}): ${t}`});let i=U(r),d=n??bt(e),s=rr.fromMasterSeed(d,i.bip32),p=o.slice(0,4).join("/");return s.derive(p)}function Gn(e,t){if(!e||!Zn[e].witness)return!1;return e!==ie.P2SH_P2WPKH||!!t}function ir({chain:e,script:t,publicKey:r,network:n}){let o=pt(t);if(o!==ie.P2SH_P2WPKH&&o!==ie.P2TR)return{};if(!ye(e,o))return{};let i=Ve(o,r,n);if(Ln.compareBytes(i.script,t)!==0)return{};return o===ie.P2TR?{tapInternalKey:i.tapInternalKey}:{redeemScript:i.redeemScript}}function jn(e,t,r){if(!r)return!1;let n=j({address:e,chain:t}),o=n?Be(n):void 0;if(!o||!ye(t,o))return!1;let i=ut(t,Ve(o,r,U(t)));return t===be.BitcoinCash?z(i)===z(e):i===e}function Jn(e){return e.witnessUtxo?.script??e.nonWitnessUtxo?.outputs[e.index??0]?.script}function wt({chain:e,tx:t,publicKey:r,network:n,indexes:o}){let i=o??Array.from({length:t.inputsLength},(s,p)=>p),d=[];for(let s of i){let p=t.getInput(s),c=Jn(p);if(!c)continue;let{redeemScript:u,tapInternalKey:a}=ir({chain:e,network:n,publicKey:r,script:c}),l={index:s};if(u&&!p.redeemScript)l.redeemScript=u;if(a&&!p.tapInternalKey)l.tapInternalKey=a;if(l.redeemScript||l.tapInternalKey)d.push(l)}return d}function ce({inputs:e,outputs:t,chain:r,tx:n,sender:o,compiledMemo:i,enableRBF:d=!1}){let s=U(r),p=ct(r),c=d?$n:void 0,u=new Set;for(let a of e){let l=`${a.hash}:${a.index}`;if(u.has(l))throw new P("toolbox_utxo_invalid_params",{error:"Duplicate input detected"});u.add(l);let h=typeof a.hash==="string"?J.decode(a.hash):a.hash,m=a.witnessUtxo?pt(a.witnessUtxo.script):void 0,f=a.publicKey&&a.witnessUtxo?ir({chain:r,network:s,publicKey:a.publicKey,script:a.witnessUtxo.script}):{};if(p&&a.witnessUtxo&&Gn(m,f.redeemScript))n.addInput({...f,index:a.index,sequence:c,txid:h,witnessUtxo:{amount:BigInt(a.witnessUtxo.value),script:a.witnessUtxo.script}});else if(a.txHex)n.addInput({...f,index:a.index,nonWitnessUtxo:J.decode(a.txHex),sequence:c,txid:h,...r===be.BitcoinCash?{sighashType:nr.ALL}:{}});else throw new P("toolbox_utxo_invalid_params",{error:`Input ${l} cannot be signed from its witnessUtxo alone: it needs its previous transaction (txHex), or — if it is a nested-segwit output — the public key that controls it, which its redeemScript derives from`})}for(let a of t){let l="address"in a&&a.address?a.address:o;if(r===be.BitcoinCash)l=G(l);if(a.script)if(i)n.addOutput({amount:0n,script:i});else throw new P("toolbox_utxo_invalid_params",{error:"An output carrying a script needs the compiled memo it carries"});else n.addOutputAddress(l,BigInt(a.value),s)}return{inputs:e,tx:n}}async function we(e){let t=await A(e).getSuggestedTxFee();return{[N.Average]:t,[N.Fast]:Qt(t,N.Fast),[N.Fastest]:Qt(t,N.Fastest)}}async function ar({assetValue:e,recipient:t,memo:r,sender:n,sweep:o,fetchTxHex:i=!1,publicKey:d},s,{forEstimateOnly:p=!1}={}){let c=e.chain,u=Ge(n,c),a=u===ie.P2PKH||u===ie.P2SH_P2WPKH&&!jn(n,c,d),l=i||!p&&a,h=e.getBaseValue("number"),m=o?void 0:s??(await we(c))[N.Fastest],f=o||m===void 0?void 0:Math.ceil(h+m*5000);return{inputs:await A(c).getUtxos({address:n,fetchTxHex:l,targetValue:f}),outputs:[{address:t,value:o?0:h},...r?[{address:"",script:M(r),value:0}]:[]]}}async function cr({assetValue:e,recipient:t,memo:r,feeRate:n,sender:o,fetchTxHex:i=!1,enableRBF:d=!1,sweep:s,publicKey:p}){let c=e.chain,u=r?M(r):null,a=await ar({assetValue:e,fetchTxHex:i,memo:r,publicKey:p,recipient:t,sender:o,sweep:s},n),{inputs:l,outputs:h}=E({...a,chain:c,changeAddress:o,feeRate:n,sweep:s});if(!(l&&h))throw new P("toolbox_utxo_insufficient_balance",{assetValue:e,sender:o});let m=p?l.map((S)=>({...S,publicKey:p})):l,f=new Je({allowUnknownOutputs:!!u,version:1}),{inputs:y,tx:x}=ce({chain:c,compiledMemo:u,enableRBF:d,inputs:m,outputs:h,sender:o,tx:f});return{inputs:y,tx:x,utxos:a.inputs}}async function dr({assetValue:e,feeOptionKey:t=N.Fast,feeRate:r,memo:n,sender:o,recipient:i,sweep:d}){let s=e.chain,p,c;if(r!==void 0)p=r,c=Math.floor(r);else{let a=await we(s);p=a[N.Fastest],c=a[t]}let u=await ar({assetValue:e,memo:n,recipient:i,sender:o,sweep:d},p,{forEstimateOnly:!0});return E({...u,chain:s,changeAddress:o,feeRate:c,sweep:d})}function Qn(e){return async function({from:r,memo:n,feeRate:o,feeOptionKey:i=N.Fast,recipient:d=r,recipients:s=1}){let p=o??(await we(e))[i],u=(await A(e).getUtxos({address:r,fetchTxHex:!1})).filter((f)=>f.value>Math.max(Ke(e),se(f,e)*p));if(!u.length)return gt.from({chain:e});let a=typeof s==="number"?Math.max(s,1):s.length,l=typeof s==="number"||a===0?Array.from({length:a||1},()=>({address:d,value:0})):[...s];if(n)l.push({address:r,script:M(n),value:0});let{outputs:h}=E({chain:e,feeRate:p,inputs:u,outputs:l,sweep:!0}),m=h?.[0]?.value??0;return gt.from({chain:e,value:BigInt(m)})}}function eo(e){return async function(r){let{fee:n}=await dr(r);return gt.from({chain:e,value:Wn.fromBigInt(BigInt(n),8).getValue("string")})}}function to({chain:e,phrase:t,derivationPath:r,scriptType:n,seed:o}){let i=U(e),{privateKey:d,publicKey:s}=xe({chain:e,derivationPath:r,phrase:t,seed:o}),p=ur(e);return{getAddress:()=>De({chain:e,network:i,publicKey:s,scriptType:n}),privateKey:d,publicKey:s,signTransaction:(c)=>{for(let{index:u,...a}of wt({chain:e,network:i,publicKey:s,tx:c}))c.updateInput(u,a);return c.sign(d,p),c}}}function ur(e){return e===be.BitcoinCash?[nr.ALL]:[er.ALL,er.DEFAULT]}function ro(e,t,r){return async function({memo:o,recipient:i,feeOptionKey:d,feeRate:s,assetValue:p,enableRBF:c=!1,sweep:u}){let a=await t?.getAddress();if(!(t&&a))throw new P("toolbox_utxo_no_signer");if(!i)throw new P("toolbox_utxo_invalid_params",{error:"Recipient address must be provided"});zn({condition:c&&!Qe.includes(e),id:`rbf_not_supported_${e}`,warning:`RBF (Replace-by-Fee) is not reliably supported on ${e}. Transaction will be created without RBF signaling.`});let l=c&&Qe.includes(e),h=s||(await we(e))[d||N.Fast],{tx:m}=await cr({assetValue:p,enableRBF:l,feeRate:h,memo:o,publicKey:r,recipient:i,sender:a,sweep:u}),f=await t.signTransaction(m);return f.finalize(),A(e).broadcastTx(J.encode(f.extract()))}}function pr(e){return(t)=>sr({address:t,chain:e})}function lr(e,{scriptType:t}){let r=U(e);return function(o){if(!o)throw new P("toolbox_utxo_invalid_params",{error:"Keys must be provided"});return De({chain:e,network:r,publicKey:o.publicKey,scriptType:t})}}function no(e){let t=e?.publicKey;if(t===void 0)return;if(t instanceof Uint8Array&&t.length===33)return t;throw new P("toolbox_utxo_invalid_params",{error:"signer.publicKey must be a 33-byte compressed public key (Uint8Array)"})}function de(e){let{chain:t}=e,r=e.phrase?e:void 0;if(!r&&"derivationPath"in e&&e.derivationPath!==void 0)throw new P("toolbox_utxo_invalid_params",{error:"derivationPath needs a phrase; a toolbox built around a signer uses the signer's addresses"});let n=r?.phrase,o=r?.index??0,i=n?bt(n):void 0,{derivationPath:d,scriptType:s}=Le({chain:t,derivationPath:r?.derivationPath,index:o,scriptType:e.scriptType}),p=Fe(d),c=n?to({chain:t,derivationPath:p,phrase:n,scriptType:s,seed:i}):void 0,u=r?void 0:e.signer,a=c||u,l=n?xe({chain:t,derivationPath:p,phrase:n,seed:i}):void 0,h=l?.publicKey??no(u);function m(){if(a)return a.getAddress();return Promise.resolve(void 0)}function f(T){if(!n)return;let g=re({accountIndex:T,chain:t,derivationPath:d});return Yn({chain:t,derivationPath:Fe(g),phrase:n,seed:i})}let y=f();function x(){if(!y)return;return y.publicExtendedKey}function S({accountIndex:T}={}){let g=T===void 0?y:f(T);if(!g)return;let w=re({accountIndex:T,chain:t,derivationPath:d});return{accountIndex:pe(w),path:Fe(w),xpub:g.publicExtendedKey}}function X({accountIndex:T,index:g,change:w=!1}){let v=T===void 0?y:f(T);if(!v)return;let b=Oe({accountIndex:T,chain:t,change:w,derivationPath:d,index:g}),K=U(t),I=v.deriveChild(Number(w)).deriveChild(g);if(!I.publicKey)throw new P("toolbox_utxo_invalid_params",{error:"Could not derive public key"});let B=De({chain:t,network:K,publicKey:I.publicKey,scriptType:s}),F=J.encode(I.publicKey);return{accountIndex:pe(b),address:B,change:w,index:g,path:Fe(b),pubkey:F}}async function q(T){if(!Qe.includes(t))return{reason:`RBF is not supported on ${t}`,supported:!1};let g=await A(t).getTransactionDetails(T);return{canReplace:g.isRBF&&!g.confirmed,confirmed:g.confirmed,enabled:g.isRBF,fee:g.fee,sequences:g.sequences,supported:!0}}async function Ue({txid:T,newFeeRate:g,recipient:w,memo:v}){if(!Qe.includes(t))throw new P("toolbox_utxo_rbf_not_supported",{chain:t});let b=await A(t).getTransactionDetails(T);if(!b.isRBF)throw new P("toolbox_utxo_tx_not_replaceable",{txid:T});if(b.confirmed)throw new P("toolbox_utxo_tx_already_confirmed",{blockId:b.blockId,txid:T});let K=b.inputs.reduce((_,D)=>_+D.value,0),B=b.outputs.find((_)=>_.recipient===w)?.value||0;if(B===0)throw new P("toolbox_utxo_invalid_params",{error:"Could not determine send amount from original transaction"});let F=await Promise.all(b.inputs.map(async(_)=>{let D=await A(t).getRawTx(_.transaction_hash),k=Je.fromRaw(J.decode(D),{allowUnknownOutputs:!0,disableScriptCheck:!0}).getOutput(_.index);return{address:_.recipient,hash:_.transaction_hash,index:_.index,publicKey:h,txHex:D,value:_.value,witnessUtxo:k.script&&k.amount!==void 0?{script:Buffer.from(k.script),value:Number(k.amount)}:void 0}})),H=v?M(v):null,ee=K-B-b.fee,_e=await m(),ue=[];if(H)ue.push({address:"",script:H,value:0});if(ee>Ke(t)&&_e)ue.push({address:_e,value:ee});let He=ge({chain:t,inputs:F.map((_)=>({..._,type:Ge(_.address,t)})),outputs:[{address:w,value:B},...ue]}),Y=Math.ceil(He*g);if(Y<=b.fee)throw new P("toolbox_utxo_rbf_fee_too_low",{newFee:Y,originalFee:b.fee});let ve=Y-b.fee,te=B-ve;if(te<=0)throw new P("toolbox_utxo_rbf_insufficient_change");let Ae=new Je({allowUnknownOutputs:!!H,version:1}),rt=[{address:w,value:te},...ue];return ce({chain:t,compiledMemo:H,inputs:F,outputs:rt,sender:_e||w,tx:Ae}),{feeDelta:ve,newFee:Y,originalFee:b.fee,tx:Ae}}async function Or({txid:T,newFeeRate:g,recipient:w,memo:v}){let{tx:b,originalFee:K,newFee:I}=await Ue({memo:v,newFeeRate:g,recipient:w,txid:T}),B=await tt(b);B.finalize();let F=await A(t).broadcastTx(J.encode(B.extract()));return{newFee:I,originalFee:K,txid:F}}function _t({accountIndex:T,index:g,change:w=!1}){Z("index",g);let v=T===void 0?y:f(T);if(!v)return;return v.deriveChild(Number(w)).deriveChild(g).privateKey||void 0}function vt({tx:T,inputDerivations:g}){if(!y)throw new P("toolbox_utxo_no_signer");let w=ur(t),v=U(t);for(let b=0;b<g.length;b++){let K=g[b];if(!K)continue;let{derivationIndex:I,isChange:B}=K,F=_t({change:B,index:I});if(!F)throw new P("toolbox_utxo_invalid_params",{error:`Could not derive private key for input ${b} at index ${I}`});for(let{index:H,...ee}of wt({chain:t,indexes:[b],network:v,publicKey:xt(F),tx:T}))T.updateInput(H,ee);T.signIdx(F,b,w)}return T}async function Sr({utxos:T,recipient:g,assetValue:w,memo:v,feeRate:b,feeOptionKey:K,changeAddress:I,sweep:B}){if(B)throw new P("toolbox_utxo_invalid_params",{error:"Sweep is not supported for transfers from multiple addresses"});if(!y)throw new P("toolbox_utxo_no_signer");let F=b||(await we(t))[K||N.Fast],H=v?M(v):null,ee=[{address:g,value:w.getBaseValue("number")}];if(H)ee.push({address:"",script:H,value:0});let _e=T.map(({address:_,hash:D,index:k,value:nt,txHex:kr,witnessUtxo:ot})=>({address:_,hash:D,index:k,txHex:kr,value:nt,witnessUtxo:ot?{script:ot.script,value:ot.value}:void 0})),ue=T[0]?.address,He=I||await m()||ue||g,{inputs:Y,outputs:ve}=E({chain:t,changeAddress:He,feeRate:F,inputs:_e,outputs:ee});if(!(Y&&ve))throw new P("toolbox_utxo_insufficient_balance",{assetValue:w,sender:"multiple addresses"});let te=new Je({allowUnknownOutputs:!!H,version:1}),Ae=Y.map((_)=>{let D=T.find((k)=>k.hash===_.hash&&k.index===_.index);return D?{derivationIndex:D.derivationIndex,isChange:D.isChange}:{derivationIndex:0,isChange:!1}}),rt=Y.map((_,D)=>{let k=Ae[D],nt=k?y.deriveChild(Number(k.isChange)).deriveChild(k.derivationIndex).publicKey:null;return{..._,publicKey:nt??void 0}});return ce({chain:t,compiledMemo:H,inputs:rt,outputs:ve,sender:He,tx:te}),vt({inputDerivations:Ae,tx:te}),te.finalize(),A(t).broadcastTx(J.encode(te.extract()))}function Cr({address:T,gapLimit:g=20}){if(!y)return;for(let w=0;w<g;w++){let v=X({change:!1,index:w}),b=X({change:!0,index:w}),K=v?.address===T?!1:b?.address===T;if(v?.address===T||b?.address===T)return{change:K,index:w}}return}function tt(T){if(!a)throw new P("toolbox_utxo_no_signer");return a.signTransaction(T)}let Xr=t===be.Bitcoin&&l?async(T)=>Jt({message:T,privateKey:l.privateKey,scriptType:s}):void 0;async function Br(T){let g=await tt(T);return g.finalize(),await A(t).broadcastTx(J.encode(g.extract()))}return{accumulative:E,broadcastTx:(T)=>A(t).broadcastTx(T),bumpFee:Or,calculateTxSize:(T)=>ge({...T,chain:t}),createKeysForPath:(T)=>xe({...T,chain:t}),createReplacementTransaction:Ue,createTransaction:(T)=>cr({publicKey:h,...T}),deriveAddressAtIndex:X,derivePrivateKeyAtIndex:_t,estimateMaxSendableAmount:Qn(t),estimateTransactionFee:eo(t),getAddress:m,getAddressFromKeys:lr(t,{scriptType:s}),getAddressType:(T)=>j({address:T,chain:t}),getBalance:tr(t),getExtendedPublicKey:x,getExtendedPublicKeyInfo:S,getFeeRates:()=>we(t),getInputsOutputsFee:dr,getNetworkForChain:()=>U(t),getPrivateKeyFromMnemonic:(T)=>qn(xe({...T,chain:t}).privateKey,t),isRBFEnabled:q,keys:l,resolveDerivationIndex:Cr,scriptType:s,signAndBroadcastTransaction:Br,signMessage:Xr,signTransaction:tt,signTransactionWithMultipleKeys:vt,transfer:ro(t,a,h),transferFromMultipleAddresses:Sr,validateAddress:pr(t)}}import{getZcashAddressType as oo,toTransparentZcashAddress as so,validateZcashAddress as Pt}from"@swapkit/utxo-signer";function Ie(e){return Ce(e)!==null}var W=io.BitcoinCash;function et(e){return z(Ee(e))}function ho(e){let t=U(W);function r(o){return o.sign(e.privateKey,[po.ALL]),o}function n(){let o=yr(e.publicKey,t);if(!o.hash)throw new L("toolbox_utxo_invalid_address",{error:"Could not derive BCH address hash"});let i=mr({hash:o.hash,prefix:fr.MAINNET,type:Tr.P2PKH});return Promise.resolve(i.replace(/^bitcoincash:/,""))}return{getAddress:n,signTransaction:r}}function xr(e={}){let t="phrase"in e?e.phrase:void 0,r="index"in e?e.index||0:0,n="derivationPath"in e?e.derivationPath:void 0,o=uo({chain:W,derivationPath:n,index:r}),i=ao(o),d=t?xe({chain:W,derivationPath:i,phrase:t}):void 0,s=d?ho(d):("signer"in e)?e.signer:void 0;function p(){return Promise.resolve(s?.getAddress())}let c="scriptType"in e?e.scriptType:void 0,{getBalance:u,getFeeRates:a,broadcastTx:l,...h}=de(t?{chain:W,index:r,phrase:t,...n?{derivationPath:n,scriptType:c}:{scriptType:c}}:{chain:W,scriptType:c});function m(x,S=!0){return u(z(Ee(x)))}function f(x){if(!s)throw new L("toolbox_utxo_no_signer");return s.signTransaction(x)}async function y(x){let S=await f(x);return S.finalize(),await l(hr.encode(S.extract()))}return{...h,broadcastTx:l,buildTx:To,createTransaction:br,getAddress:p,getAddressFromKeys:mo,getBalance:m,getFeeRates:a,signAndBroadcastTransaction:y,signTransaction:f,stripPrefix:z,stripToCashAddress:et,transfer:fo({broadcastTx:l,getFeeRates:a,signer:s}),validateAddress:Ie}}async function br({assetValue:e,recipient:t,memo:r,feeRate:n,sender:o,sweep:i}){if(!Ie(t))throw new L("toolbox_utxo_invalid_address",{address:t});let d=Math.ceil(e.getBaseValue("number")+n*7500),s=await A(W).getUtxos({address:et(o),fetchTxHex:!0,targetValue:i?void 0:d}),p=r?M(r):null,c=[],u=G(t);if(c.push({address:u,value:i?0:e.getBaseValue("number")}),p)c.push({script:p,value:0});let{inputs:a,outputs:l}=E({chain:W,feeRate:n,inputs:s,outputs:c,sweep:i});if(!(a&&l))throw new L("toolbox_utxo_insufficient_balance",{assetValue:e,sender:o});let h=new gr({allowUnknownOutputs:!!p,version:1}),m=G(o),{inputs:f,tx:y}=ce({chain:W,compiledMemo:p,inputs:a,outputs:l.map((x)=>("address"in x)&&x.address?{...x,address:G(x.address)}:x),sender:m,tx:h});return{inputs:f,tx:y,utxos:a}}function fo({broadcastTx:e,getFeeRates:t,signer:r}){return async function({recipient:o,assetValue:i,feeOptionKey:d=co.Fast,sweep:s,...p}){let c=await r?.getAddress();if(!(r&&c))throw new L("toolbox_utxo_no_signer");if(!o)throw new L("toolbox_utxo_invalid_params",{error:"Recipient address must be provided"});let u=p.feeRate||(await t())[d],{tx:a}=await br({...p,assetValue:i,feeRate:u,recipient:o,sender:c,sweep:s}),l=await r.signTransaction(a);return l.finalize(),e(hr.encode(l.extract()))}}async function To({assetValue:e,recipient:t,memo:r,feeRate:n,sender:o}){let i=Ee(t);if(!Ie(i))throw new L("toolbox_utxo_invalid_address",{address:i});let d=Math.ceil(e.getBaseValue("number")+n*7500),s=await A(W).getUtxos({address:et(o),fetchTxHex:!0,targetValue:d}),p=Number(n.toFixed(0)),c=r?M(r):null,u=[];if(u.push({address:G(t),value:e.getBaseValue("number")}),c)u.push({script:c,value:0});let{inputs:a,outputs:l}=E({chain:W,feeRate:p,inputs:s,outputs:u});if(!(a&&l))throw new L("toolbox_utxo_insufficient_balance",{assetValue:e,sender:o});let h=new gr({allowUnknownOutputs:!!c,version:1}),{inputs:m,tx:f}=ce({chain:W,compiledMemo:c,inputs:a,outputs:l,sender:G(o),tx:h});return{inputs:m,tx:f,utxos:s}}function mo(e){let t=lo.bitcoinCash,r=yr(e.publicKey,t);if(!r.hash)throw new L("toolbox_utxo_invalid_address",{error:"Could not derive BCH address hash"});return mr({hash:r.hash,prefix:fr.MAINNET,type:Tr.P2PKH}).replace(/^bitcoincash:/,"")}import{createBase58check as yo,hex as go}from"@scure/base";import{HDKey as Ur}from"@scure/bip32";import{mnemonicToSeedSync as _r}from"@scure/bip39";import{Chain as V,derivationPathToString as xo,FeeOption as bo,SwapKitError as Q}from"@swapkit/helpers";import{Address as wo,createZcashTransaction as Po,getZcashTransactionFormat as Uo,isTransparentZcashAddress as wr,OutScript as _o,toTransparentZcashAddress as vo,utils as vr,WIF as Ao,ZcashSigHash as Oo}from"@swapkit/utxo-signer";import{match as So,P as Ut}from"ts-pattern";var Co=yo(vr.sha256);function Xo(e){return Co.encode(e)}function Bo({phrase:e,derivationPath:t}){let r=_r(e),o=Ur.fromMasterSeed(r).derive(t);if(!o.privateKey||!o.publicKey)throw new Q("toolbox_utxo_invalid_params");let{privateKey:i,publicKey:d}=o,s=vr.hash160(d),p=new Uint8Array([28,184]),c=new Uint8Array(p.length+s.length);c.set(p,0),c.set(s,p.length);let u=Xo(c);return{getAddress:()=>Promise.resolve(u),signTransaction:(a)=>{if(a.signAllInputs(i,d,Oo.ALL),"extract"in a)return a.finalizeAllInputs(),Promise.resolve(a.extract());return Promise.resolve(a)}}}function ko({inputs:e,outputs:t,tx:r,sender:n,compiledMemo:o}){let i=U(V.Zcash);for(let d of e){let s=wo(i).decode(n),p=_o.encode(s);r.addInput({index:d.index,script:p,sequence:4294967295,txid:go.decode(d.hash),value:BigInt(d.value)})}for(let d of t){let s="address"in d&&d.address?d.address:n,p=d.script;if(p&&!o)continue;if(p&&o)r.addOutput({amount:0n,script:o});else r.addOutputAddress(s,BigInt(d.value),i)}return{inputs:e,tx:r}}async function Ko(){try{let e=await A(V.Zcash).getBlockHeight();return Uo(e+1)}catch(e){throw new Q({errorKey:"toolbox_utxo_api_error",info:{chain:V.Zcash,reason:"Block height is required to choose the Zcash transaction format"}},e)}}async function Pr(e){let{assetValue:t,recipient:r,memo:n,feeRate:o,sender:i,fetchTxHex:d,sweep:s}=e,p=U(V.Zcash);if(!wr(i,p))throw new Q("toolbox_utxo_invalid_address",{address:i});let c=vo(r);if(!wr(c,p))throw new Q("toolbox_utxo_invalid_address",{address:r,error:"Zcash transaction creation currently supports transparent addresses only"});let u=n?M(n):null,a=await A(V.Zcash).getUtxos({address:i,fetchTxHex:d!==!1}),l=[{address:c,value:s?0:Number(t.getBaseValue("string"))},...u?[{script:u,value:0}]:[]],{inputs:h,outputs:m}=E({chain:V.Zcash,changeAddress:i,feeRate:o,inputs:a,outputs:l,sweep:s});if(!(h&&m))throw new Q("toolbox_utxo_insufficient_balance",{assetValue:t,sender:i});let f=Po({...await Ko(),expiryHeight:0,lockTime:0}),{tx:y,inputs:x}=ko({compiledMemo:u,inputs:h,outputs:m,sender:i,tx:f});return{inputs:x,outputs:m,tx:y}}function Ar(e={}){let t="scriptType"in e?e.scriptType:void 0,r=So(e).with({signer:Ut.not(Ut.nullish)},({signer:c})=>c).with({phrase:Ut.string},({phrase:c,derivationPath:u,index:a=0})=>{let{derivationPath:l}=Le({chain:V.Zcash,derivationPath:u,index:a,scriptType:t}),h=xo(l);return Bo({derivationPath:h,phrase:c})}).otherwise(()=>{return}),n=de({chain:V.Zcash,scriptType:t,signer:r});async function o(c){if(!r)throw new Q("toolbox_utxo_no_signer");return await r.signTransaction(c)}async function i(c){let u=await o(c);return n.broadcastTx(u.toHex())}async function d({recipient:c,assetValue:u,feeOptionKey:a=bo.Fast,sweep:l,...h}){let m=await r?.getAddress();if(!(r&&m))throw new Q("toolbox_utxo_no_signer");let f=h.feeRate||(await n.getFeeRates())[a],{tx:y}=await Pr({...h,assetValue:u,feeRate:f,recipient:c,sender:m,sweep:l}),S=(await r.signTransaction(y)).toHex();return n.broadcastTx(S)}function s({phrase:c,derivationPath:u="m/44'/133'/0'/0/0"}){let a=_r(c),h=Ur.fromMasterSeed(a).derive(u);if(!h.privateKey||!h.publicKey)throw new Q("toolbox_utxo_invalid_params");return{privateKey:h.privateKey,publicKey:h.publicKey}}function p({phrase:c,derivationPath:u="m/44'/133'/0'/0/0"}){let a=s({derivationPath:u,phrase:c}),l=U(V.Zcash);return Ao(l).encode(a.privateKey)}return{...n,createKeysForPath:s,createTransaction:Pr,getPrivateKeyFromMnemonic:p,signAndBroadcastTransaction:i,signTransaction:o,transfer:d,validateAddress:Pt}}import{hex as Fo}from"@scure/base";import{HDKey as Do}from"@scure/bip32";import{derivationPathToString as Io,NetworkDerivationPath as Ho,updateDerivationPath as Ro}from"@swapkit/helpers";function Mo({xpub:e,chain:t,count:r,startIndex:n=0,accountIndex:o,purpose:i,scriptType:d}){if(Z("count",r),r<1)throw RangeError("count must be at least 1");Z("startIndex",n),$e(t,d),dt({chain:t,purpose:i,scriptType:d});let s=U(t),p=Do.fromExtendedKey(e,s.bip32),c=i===void 0?void 0:Ro(Ho[t],{purpose:i}),u=re({accountIndex:o,chain:t,derivationPath:c}),a=pe(u),l=[];for(let h of[!1,!0]){let m=p.deriveChild(Number(h));for(let f=0;f<r;f++){let y=n+f,x=m.deriveChild(y);if(!x.publicKey)continue;let S=Oe({accountIndex:o,chain:t,change:h,derivationPath:c,index:y});l.push({accountIndex:a,address:De({chain:t,network:s,publicKey:x.publicKey,scriptType:d}),change:h,index:y,pubkey:Fo.encode(x.publicKey),...i===void 0?{}:{path:Io(S)}})}}return l}function Ki(e,t){switch(e){case Pe.BitcoinCash:return xr(t||{});case Pe.Zcash:return Ar(t);case Pe.Bitcoin:case Pe.Dogecoin:case Pe.Litecoin:case Pe.Dash:return de({chain:e,...t});default:throw new Eo("toolbox_utxo_not_supported",{chain:e})}}export{Yt as InputSizes,ws as MIN_TX_FEE,Xn as OP_RETURN_OVERHEAD,lt as OutputSizes,Cn as SEGWIT_MARKER_FLAG_WEIGHT,ht as TX_OVERHEAD,ie as UTXOScriptType,It as UtxoNetwork,E as accumulative,ce as addInputsAndOutputs,lr as addressFromKeysGetter,Z as assertDerivationIndex,he as baseUrl,ge as calculateTxSize,Rn as canSignBitcoinMessage,M as compileMemo,xr as createBCHToolbox,Lo as createCustomUtxoApi,Fr as createHDWalletHelpers,de as createUTXOToolbox,Ar as createZcashToolbox,Mo as deriveAddressesFromXpub,rs as detectAddressNetwork,Ce as getBchAddressType,Ke as getDustThreshold,ke as getInputScriptType,se as getInputSize,wt as getMissingSpendingMetadata,U as getNetworkForChain,je as getOutputSize,Bn as getOutputSizeForAddress,Ge as getScriptTypeForAddress,pe as getUTXOAccountIndexFromPath,re as getUTXOAccountPath,Oe as getUTXOAddressPath,pr as getUTXOAddressValidator,j as getUtxoAddressType,A as getUtxoApi,Vo as getUtxoNetwork,Ki as getUtxoToolbox,Tt as getWitnessOverhead,oo as getZcashAddressType,ft as isSegwitScriptType,ts as isValidAddress,zt as nonSegwitChains,z as stripPrefix,et as stripToCashAddress,Ee as toCashAddress,G as toLegacyAddress,so as toTransparentZcashAddress,Ne as tryDecodeAddress,Ie as validateBchAddress,sr as validateUtxoAddress,Pt as validateZcashAddress};
1
+ import{ia as Ft,ja as fn}from"../../chunk-qk8kg62t.js";import"../../chunk-pz8xe0qj.js";import{NetworkDerivationPath as $n}from"@swapkit/helpers";function W(e,t){if(!Number.isInteger(t)||t<0)throw RangeError(`${e} must be a non-negative integer, got: ${t}`)}function se({accountIndex:e,chain:t,derivationPath:n}){if(e!==void 0)W("accountIndex",e);let[r,o,a]=n??$n[t];return[r,o,e??a]}function Be({accountIndex:e,change:t=!1,chain:n,derivationPath:r,index:o}){return W("index",o),[...se({accountIndex:e,chain:n,derivationPath:r}),Number(t),o]}function he(e){return e[2]??0}function Ln({deriveAddress:e,getBalance:t,getUtxos:n}){async function r(s){let{accountIndex:d,count:p,startIndex:c=0,change:i=!1}=s;if(W("count",p),p<1)throw RangeError("count must be at least 1");W("startIndex",c);let l=[];for(let f=0;f<p;f++){let g=await e({accountIndex:d,change:i,index:c+f});if(g)l.push(g)}return l}async function o(s){let{gapLimit:d=20,change:p=!1}=s??{},c=[],i=0,l=0;while(i<d){let f=await e({change:p,index:l});if(!f)break;if((await t(f.address)).some((h)=>h.getValue("number")>0))c.push(f),i=0;else i++;l++}return c}async function a(s=20){let[d,p]=await Promise.all([o({change:!1,gapLimit:s}),o({change:!0,gapLimit:s})]),c=[...d,...p],i=await Promise.all(c.map(async(f)=>{let T=(await t(f.address)).reduce((h,y)=>h+y.getValue("number"),0);return{...f,balance:T}})),l=i.reduce((f,g)=>f+g.balance,0);return{addresses:i,total:l}}async function u(s=20){let[d,p]=await Promise.all([o({change:!1,gapLimit:s}),o({change:!0,gapLimit:s})]),c=[...d,...p];return(await Promise.all(c.map(async(l)=>(await n(l.address)).map((g)=>({...g,address:l.address,derivationIndex:l.index,isChange:l.change}))))).flat()}return{deriveAddresses:r,getAggregatedBalance:a,getAggregatedUtxos:u,scanForAddresses:o}}import{Chain as S,getRPCUrl as Vn,RequestClient as Ne,SKConfig as It,SwapKitError as R,warnOnce as qn}from"@swapkit/helpers";import{NETWORKS as fe}from"@swapkit/utxo-signer";async function Gn({chain:e,txHash:t}){let n=`${Te(e)}/push/transaction`,r=JSON.stringify({data:t});try{let o=await Ne.post(n,{body:r,headers:{"Content-Type":"application/json"}});if(o.context.code!==200)throw new R("toolbox_utxo_broadcast_failed",{error:o.context.error||"Transaction broadcast failed"});return o.data?.transaction_hash||t}catch(o){let a=await Vn(e);if(a){let u=JSON.stringify({id:Ft(),jsonrpc:"2.0",method:"sendrawtransaction",params:[t]}),s=await Ne.post(a,{body:u,headers:{"Content-Type":"application/json"}});if(s.error)throw new R("toolbox_utxo_broadcast_failed",{error:s.error?.message});if(s.result.includes('"code":-26'))throw new R("toolbox_utxo_invalid_transaction",{error:"Transaction amount was too low"});return s.result}throw o}}function Te(e){return`${(It.get("blockchairApiUrl")||"https://api.blockchair.com").replace(/\/+$/,"")}/${Yn(e)}`}function pt(e){switch(e){case S.Bitcoin:return 5;case S.Dogecoin:return 1e4;case S.Litecoin:return 1;case S.Zcash:return 1;default:return 2}}function Yn(e){switch(e){case S.BitcoinCash:return"bitcoin-cash";case S.Litecoin:return"litecoin";case S.Dash:return"dash";case S.Dogecoin:return"dogecoin";case S.Zcash:return"zcash";case S.Polkadot:return"polkadot";default:return"bitcoin"}}async function jn(e){if(e===S.Zcash)return pt(e);try{let{feePerKb:t}=await Ne.get(`https://app.bitgo.com/api/v2/${e.toLowerCase()}/tx/fee`),n=t/1000;return Math.max(n,pt(e))}catch{return pt(e)}}async function Ke(e,t){let n=await Ne.get(`${e}${t?`${e.includes("?")?"&":"?"}key=${t}`:""}`);if(!n||n.context.code!==200)throw new R("toolbox_utxo_api_error",{error:`Failed to query ${e}`});return n.data}async function Jn({chain:e,apiKey:t}){let n=await Ke(`${Te(e)}/stats`,t);if(typeof n.best_block_height!=="number")throw new R("toolbox_utxo_api_error",{error:"Missing best_block_height in stats response"});return n.best_block_height}async function Dt({address:e,chain:t,apiKey:n}){if(!e)throw new R("toolbox_utxo_invalid_params",{error:"Address is required"});try{return(await Ke(`${Te(t)}/dashboards/address/${e}?transaction_details=true`,n))[e]}catch{return{address:{balance:0,transaction_count:0},utxo:[]}}}async function Qn({address:e,chain:t,apiKey:n}){return(await Dt({address:e,apiKey:n,chain:t}))?.address.balance||0}async function Ht({chain:e,apiKey:t,txHash:n}){if(!n)throw new R("toolbox_utxo_invalid_params",{error:"TxHash is required"});try{return(await Ke(`${Te(e)}/raw/transaction/${n}`,t))?.[n]?.raw_transaction||""}catch(r){let o=r instanceof Error?r.message:String(r);return console.error(`Failed to fetch raw transaction: ${o}`),""}}var er=4294967294;async function tr({chain:e,apiKey:t,txHash:n}){if(!n)throw new R("toolbox_utxo_invalid_params",{error:"TxHash is required"});let o=(await Ke(`${Te(e)}/dashboards/transaction/${n}`,t))?.[n];if(!o)throw new R("toolbox_utxo_tx_not_found",{txHash:n});let{transaction:a,inputs:u,outputs:s}=o,d=u.map((c)=>c.spending_sequence),p=a.is_rbf===!0||d.some((c)=>c<er);return{blockId:a.block_id,confirmed:a.block_id!==-1,fee:a.fee,inputs:u,isRBF:p,outputs:s,sequences:d,size:a.size,txid:a.hash,weight:a.weight}}async function nr({chain:e,address:t,apiKey:n,offset:r=0,limit:o=30}){return(await Ke(`${Te(e)}/outputs?q=recipient(${t}),is_spent(false)&s=value(desc)&fields=is_spent,transaction_hash,index,value,script_hex,block_id,spending_signature_hex&limit=${o}&offset=${r}`,n)).map(({is_spent:d,script_hex:p,block_id:c,transaction_hash:i,index:l,value:f,spending_signature_hex:g})=>({hash:i,index:l,is_confirmed:c!==-1,is_spent:d,script_hex:p,txHex:g,value:f}))}function rr(e){return e.reduce((t,n)=>t+n.value,0)}function kt(e,t){let n=[...e].sort((r,o)=>o.value-r.value);if(t){let r=[],o=0;for(let a of n)if(r.push(a),o+=a.value,o>=t)break;return r}return n}async function Rt({chain:e,address:t,apiKey:n,targetValue:r,accumulativeValue:o=0,offset:a=0,limit:u=30}){if(!t)throw new R("toolbox_utxo_invalid_params",{error:"Address is required"});try{let s=await nr({address:t,apiKey:n,chain:e,limit:u,offset:a,targetValue:r}),p=s.length<u,c=s.filter(({is_spent:h})=>!h),i=rr(c),l=o+i,f=r&&l>=r;if(p||f)return kt(c,r);let g=await Rt({accumulativeValue:l,address:t,apiKey:n,chain:e,limit:u,offset:a+u,targetValue:r}),T=[...c,...g];return kt(T,r)}catch(s){let d=s instanceof Error?s.message:String(s);return console.error(`Failed to fetch unspent UTXOs: ${d}`),[]}}async function or({address:e,chain:t,apiKey:n,fetchTxHex:r=!0,targetValue:o}){let a=await Rt({address:e,apiKey:n,chain:t,targetValue:o}),u=r?await Promise.all(a.map(({hash:s})=>Ht({apiKey:n,chain:t,txHash:s}))):[];return a.map(({hash:s,index:d,script_hex:p,value:c},i)=>({address:e,hash:s,index:d,txHex:r?u[i]:void 0,value:c,witnessUtxo:{script:Buffer.from(p,"hex"),value:c}}))}function A(e){let t=It.get("apiKeys").blockchair||"";return qn({condition:!t,id:"no_blockchair_api_key_warning",warning:"No Blockchair API key found. Functionality will be limited."}),{broadcastTx:(n)=>Gn({chain:e,txHash:n}),getAddressData:(n)=>Dt({address:n,apiKey:t,chain:e}),getBalance:(n)=>Qn({address:n,apiKey:t,chain:e}),getBlockHeight:()=>Jn({apiKey:t,chain:e}),getRawTx:(n)=>Ht({apiKey:t,chain:e,txHash:n}),getSuggestedTxFee:()=>jn(e),getTransactionDetails:(n)=>tr({apiKey:t,chain:e,txHash:n}),getUtxos:(n)=>or({...n,apiKey:t,chain:e})}}function ls(e){return e}function hs(){return function(t){switch(t){case S.Bitcoin:return fe.bitcoin;case S.BitcoinCash:return fe.bitcoinCash;case S.Dash:return fe.dash;case S.Litecoin:return fe.litecoin;case S.Dogecoin:return fe.dogecoin;case S.Zcash:return fe.zcash;default:throw new R("toolbox_utxo_not_supported",{chain:t})}}}import{sha256 as pr}from"@noble/hashes/sha2.js";import{createBase58check as lr}from"@scure/base";import{SwapKitError as Mt}from"@swapkit/helpers";import{CashAddrType as ze,decodeCashAddr as sr,encodeCashAddr as ar}from"@swapkit/utxo-signer";var ir={P2PKH:ze.P2PKH,P2SH:ze.P2SH},cr={[ze.P2PKH]:"P2PKH",[ze.P2SH]:"P2SH"};function ur(e,t,n){return ar({hash:n,prefix:e,type:ir[t]})}function dr(e){let t=sr(e),n=cr[t.type];if(!n)throw Error(`Unknown CashAddr type: ${t.type}`);return{hash:t.hash,prefix:t.prefix,type:n}}var lt={decode:dr,encode:ur};var Zt=lr(pr);var Nt;((n)=>{n.Mainnet="mainnet";n.Testnet="testnet"})(Nt||={});var ae={["legacy"]:{["mainnet"]:{["p2pkh"]:0,["p2sh"]:5},["testnet"]:{["p2pkh"]:111,["p2sh"]:196}},["bitpay"]:{["mainnet"]:{["p2pkh"]:28,["p2sh"]:40},["testnet"]:{["p2pkh"]:111,["p2sh"]:196}}},hr={["p2pkh"]:"pkh",["p2sh"]:"sh"};function ws(e){return $e(e)!==void 0}function Ps(e){return ht(e).network}function j(e){let t=ht(e);if(t.format==="legacy")return e;return mr(t)}function We(e){let t=ht(e);return gr(t)}function $e(e){if(typeof e!=="string")return;let t=fr(e)??Tr(e);return t&&{...t,scriptType:hr[t.type]}}function ht(e){let t=$e(e);if(!t)throw new Mt("toolbox_utxo_invalid_address",{address:e});return t}function fr(e){try{let t=Zt.decode(e);if(t.length!==21)throw new Mt("toolbox_utxo_invalid_address",{address:e});let n=t[0],r=Array.prototype.slice.call(t,1);switch(n){case ae.legacy.mainnet.p2pkh:return{format:"legacy",hash:r,network:"mainnet",type:"p2pkh"};case ae.legacy.mainnet.p2sh:return{format:"legacy",hash:r,network:"mainnet",type:"p2sh"};case ae.legacy.testnet.p2pkh:return{format:"legacy",hash:r,network:"testnet",type:"p2pkh"};case ae.legacy.testnet.p2sh:return{format:"legacy",hash:r,network:"testnet",type:"p2sh"};case ae.bitpay.mainnet.p2pkh:return{format:"bitpay",hash:r,network:"mainnet",type:"p2pkh"};case ae.bitpay.mainnet.p2sh:return{format:"bitpay",hash:r,network:"mainnet",type:"p2sh"};default:return}}catch{return}}function Tr(e){if(e.indexOf(":")!==-1)try{return Et(e)}catch{}else{let t=["bitcoincash","bchtest","bchreg"];for(let n of t)try{return Et(`${n}:${e}`)}catch{}}return}function Et(e){try{let{hash:t,prefix:n,type:r}=lt.decode(e);return{format:"cashaddr",hash:Array.prototype.slice.call(t,0),network:n==="bitcoincash"?"mainnet":"testnet",type:r==="P2PKH"?"p2pkh":"p2sh"}}catch{return}}function mr(e){let t=ae.legacy[e.network][e.type],n=Buffer.alloc(1+e.hash.length);return n[0]=t,n.set(e.hash,1),Zt.encode(n)}function gr(e){let t=e.network==="mainnet"?"bitcoincash":"bchtest",n=e.type==="p2pkh"?"P2PKH":"P2SH",r=new Uint8Array(e.hash);return lt.encode(t,n,r)}import{Chain as cn}from"@swapkit/helpers";import{Chain as be,SwapKitError as ce,UTXO_SCRIPT_TYPE_LIST as Rr,UTXO_SCRIPT_TYPES as Qt,UTXOScriptType as Je}from"@swapkit/helpers";import{Script as Er}from"@swapkit/utxo-signer";import{Chain as zt}from"@swapkit/helpers";import{getAddressScriptType as xr,getZcashAddressType as br}from"@swapkit/utxo-signer";import{match as wr}from"ts-pattern";import{Chain as me}from"@swapkit/helpers";import{NETWORKS as ge}from"@swapkit/utxo-signer";import{match as yr}from"ts-pattern";function U(e){return yr(e).with(me.Bitcoin,()=>ge.bitcoin).with(me.BitcoinCash,()=>ge.bitcoinCash).with(me.Dash,()=>ge.dash).with(me.Dogecoin,()=>ge.dogecoin).with(me.Litecoin,()=>ge.litecoin).with(me.Zcash,()=>ge.zcash).exhaustive()}function L(e){return e.replace(/(bchtest:|bitcoincash:)/,"")}function ke(e){if(typeof e!=="string")return null;let t=$e(L(e));if(!t||t.network!=="mainnet")return null;return t.scriptType}function J({address:e,chain:t}){return wr(t).with(zt.BitcoinCash,()=>ke(e)).with(zt.Zcash,()=>br(e)).otherwise(()=>xr(e,U(t)))}import{Chain as ie,derivationPathToString as Wt,getPurposeFromPath as Pr,getUTXOScriptTypeForPath as $t,getUTXOScriptTypeForPurpose as qt,resolveDerivationPath as Ur,SwapKitError as Fe,UTXO_SCRIPT_TYPE_LIST as Lt,UTXO_SCRIPT_TYPES as ye,UTXOChains as _r,UTXOScriptType as C,updateDerivationPath as vr,warnOnce as Ar}from"@swapkit/helpers";import{CashAddrPrefix as Or,CashAddrType as Sr,encodeCashAddr as Cr,OutScript as Gt,p2pkh as Xr,p2sh as Br,p2tr as Kr,p2wpkh as Vt}from"@swapkit/utxo-signer";var Le=Object.freeze([C.P2PKH]),kr=Object.freeze({[ie.Bitcoin]:Lt,[ie.BitcoinCash]:Le,[ie.Dash]:Le,[ie.Dogecoin]:Le,[ie.Litecoin]:Lt,[ie.Zcash]:Le});function qe(e){return kr[e]}function Tt(e){return qe(e).some((t)=>ye[t].witness)}function xe(e,t){return qe(e).includes(t)}function Ge(e,t){if(xe(e,t))return t;throw new Fe("toolbox_utxo_unsupported_script_type",{chain:e,error:`${e} cannot encode ${t}; supported: ${qe(e).join(", ")}`,scriptType:t,supported:qe(e)})}var Yt=_r.filter((e)=>!Tt(e));function Fr({purpose:e,scriptType:t}){let n=qt(e);return n===void 0||n===t}function mt({chain:e,purpose:t,scriptType:n}){Ar({condition:!Fr({purpose:t,scriptType:n}),id:`utxo_off_standard_encoding_${e}_${t}_${n}`,warning:`${e}: encoding m/${t}' keys as ${n}, not the ${qt(t)} the path implies. No other wallet derives these addresses: move funds out of them, never receive into them.`})}function Ye({chain:e,derivationPath:t,index:n=0,scriptType:r}){if(t){if(!r){let s=$t(t);throw new Fe("toolbox_utxo_invalid_params",{chain:e,derivationPath:Wt(t),error:`scriptType is required alongside derivationPath: getUTXOScriptTypeForPath gives the standard one${s?` (${s})`:""}, or state another deliberately.`})}return Ge(e,r),mt({chain:e,purpose:Pr(t),scriptType:r}),{derivationPath:t,scriptType:r}}let o=Ur({chain:e,index:n}),a=r?vr(o,{purpose:ye[r].purpose}):o,u=r??$t(a);if(!u)throw new Fe("toolbox_utxo_invalid_params",{chain:e,derivationPath:Wt(a),error:`${e}: the default derivation path has no standard script type`});return Ge(e,u),{derivationPath:a,scriptType:u}}function Ir(e){return e.length===32?e:e.slice(1)}function Ve(e,t){if(!e.address)throw new Fe("toolbox_utxo_invalid_address",{error:`Could not derive a ${t} address`});return e}var Dr={[C.P2PKH]:(e,t)=>{let{address:n,script:r}=Ve(Xr(e,t),C.P2PKH);return{address:n,script:r}},[C.P2SH_P2WPKH]:(e,t)=>{let n=Vt(e,t),{address:r,script:o}=Ve(Br(n,t),C.P2SH_P2WPKH);return{address:r,redeemScript:n.script,script:o}},[C.P2WPKH]:(e,t)=>{let{address:n,script:r}=Ve(Vt(e,t),C.P2WPKH);return{address:n,script:r}},[C.P2TR]:(e,t)=>{let n=Ir(e),{address:r,script:o}=Ve(Kr(n,void 0,t),C.P2TR);return{address:r,script:o,tapInternalKey:n}}};function je(e,t,n){return Dr[e](t,n)}function gt(e,t){if(e!==ie.BitcoinCash)return t.address;let n=Gt.decode(t.script);if(n.type!=="pkh")throw new Fe("toolbox_utxo_invalid_address",{chain:e,error:`Cannot encode ${n.type} as CashAddr`});return Cr({hash:n.hash,prefix:Or.MAINNET,type:Sr.P2PKH}).replace(/^bitcoincash:/,"")}var Hr=Object.freeze({pkh:C.P2PKH,sh:C.P2SH_P2WPKH,tr:C.P2TR,wpkh:C.P2WPKH}),ft=Object.freeze({pkh:ye[C.P2PKH].outputSize,sh:ye[C.P2SH_P2WPKH].outputSize,tr:ye[C.P2TR].outputSize,wpkh:ye[C.P2WPKH].outputSize,wsh:43});function jt(e){return e in ft}function Jt(e){if(e==="tex")return ft.pkh;return jt(e)?ft[e]:void 0}function Ie(e){return Hr[e]}function yt(e){try{let{type:t}=Gt.decode(e);return jt(t)?Ie(t):void 0}catch{return}}import{UTXOScriptType as ue}from"@swapkit/helpers";var Zs=1000,bt=10,Mr=2,Zr=10;function Q(e){switch(e){case be.Bitcoin:case be.BitcoinCash:return 550;case be.Dash:case be.Litecoin:return 5500;case be.Dogecoin:return 1e5;case be.Zcash:return 546;default:throw new ce("toolbox_utxo_not_supported",{chain:e})}}function Qe({inputs:e,outputs:t,fee:n,dustThreshold:r}){let o=e.reduce((s,d)=>s+d.value,0),a=o-n;if(a<=r)throw new ce("toolbox_sweep_amount_too_low",{available:o,dustThreshold:r,fee:n});let u=t.findIndex((s)=>("address"in s)&&s.address);if(u===-1)throw new ce("toolbox_utxo_invalid_params",{error:"Sweep requires a recipient output"});return{fee:n,inputs:e,outputs:t.map((s,d)=>d===u?{...s,value:a}:s)}}function E(e){let t=new Uint8Array(Buffer.from(e,"utf8"));return Er.encode(["RETURN",t])}function en(e){return Object.fromEntries(Rr.map((t)=>[t,Qt[t][e]]))}var tn=en("inputSize"),xt=en("outputSize"),wt=(e)=>Qt[e].witness,et=(e,t)=>{let n=J({address:e,chain:t});if(!n)throw new ce("toolbox_utxo_invalid_address",{address:e,chain:t});let r=Ie(n);if(!r||!xe(t,r))throw new ce("toolbox_utxo_unsupported_script_type",{address:e,addressType:n,chain:t,error:"Address is valid but its script type is not one the SDK spends from"});return r},Nr=(e,t)=>{let n=J({address:e,chain:t});if(!n)throw new ce("toolbox_utxo_invalid_address",{address:e,chain:t});let r=Jt(n);if(!r)throw new ce("toolbox_utxo_unsupported_script_type",{address:e,addressType:n,chain:t,error:"Address is valid but a transparent transaction cannot pay to it"});return r},we=({chain:e,inputs:t,outputs:n,feeRate:r})=>{let o=t[0]?De(t[0],e):Je.P2PKH,a=r?t.filter((c)=>c.value>=tn["type"in c&&c.type?c.type:Je.P2PKH]*Math.ceil(r)):t,u=0,s=0;for(let c of a)if(u+=I(c,e),!wt(De(c,e)))s++;let d=n?.reduce((c,i)=>c+Pe(i,e),0)||xt[o],p=s<a.length;return bt+u+d+Pt(p,s)},De=(e,t)=>{if("type"in e&&e.type)return e.type;if("address"in e&&e.address)return et(e.address,t);return Je.P2PKH},I=(e,t)=>tn[De(e,t)],Pt=(e,t)=>e?Math.ceil((Mr+t)/4):0,Pe=(e,t,n)=>{if(e?.script)return Zr+e.script.length+(e.script.length>=74?2:1);if(n)return xt[n];if("address"in e&&e.address)return Nr(e.address,t);return xt[Je.P2PKH]};import{Chain as tt}from"@swapkit/helpers";var nt=5000,zr=1000,Wr=3590000,$r=12,Lr=2,nn=150,Vr=34,qr=5000;function Ue(e){return e!==void 0&&e>=Wr+$r?zr:nt}function Ut({inputBytes:e,outputBytes:t,marginalFee:n=nt}){let r=Math.max(Math.ceil(e/nn),Math.ceil(t/Vr));return n*Math.max(Lr,r)}function rn(e){if(!e.script)return Pe(e,tt.Zcash);let t=e.script.length;return 8+Gr(t)+t}function Gr(e){if(e<253)return 1;return e<=65535?3:5}function on(e){return e.reduce((t,n)=>t+rn(n),0)}function Yr({inputs:e,outputs:t,marginalFee:n}){return Ut({inputBytes:e.reduce((r,o)=>r+I(o,tt.Zcash),0),marginalFee:n,outputBytes:on(t)})}function jr(e,t=nt){return t*Math.ceil(I(e,tt.Zcash)/nn)}function sn(e=nt){return Ut({inputBytes:qr,marginalFee:e,outputBytes:0})}function an({inputs:e,outputs:t,changeAddress:n="",sweep:r=!1,marginalFee:o=Ue()}){let a=tt.Zcash,u=Q(a),s=on(t),d=(T,h=0)=>Ut({inputBytes:T,marginalFee:o,outputBytes:s+h}),p=[...e].sort((T,h)=>h.value-T.value),c=0,i=0,l=[];if(r){for(let h of p){let y=I(h,a),_=d(c+y)-d(c);if(h.value<=Math.max(_,u))continue;c+=y,l.push(h)}let T=Qe({dustThreshold:u,fee:d(c),inputs:l,outputs:t});return{fee:T.fee,inputs:T.inputs,outputs:T.outputs}}let f=rn({address:n,value:0}),g=t.reduce((T,h)=>T+h.value,0);for(let T of p){let h=I(T,a),y=d(c+h)-d(c);if(T.value<=y)continue;c+=h,i+=T.value,l.push(T);let _=d(c);if(i<_+g)continue;let G=d(c,f),ne=i-g-G;if(ne>Math.max(jr({value:0},o),u))return{fee:G,inputs:l,outputs:t.concat({address:n,value:ne})};return{fee:i-g,inputs:l,outputs:t}}return{fee:Yr({inputs:e,marginalFee:o,outputs:t})}}function M({inputs:e,outputs:t,feeRate:n=1,chain:r=cn.Bitcoin,changeAddress:o="",sweep:a=!1,marginalFee:u}){if(r===cn.Zcash)return an({changeAddress:o,inputs:e,marginalFee:u,outputs:t,sweep:a});let s=Q(r),d=e.filter((h)=>{let y=I(h,r)*n;return a?h.value>Math.max(y,s):y<=h.value});if(a){let h=Math.ceil(n*we({chain:r,inputs:d,outputs:t})),y=Qe({dustThreshold:s,fee:h,inputs:d,outputs:t});return{fee:y.fee,inputs:y.inputs,outputs:y.outputs}}let p=bt+t.reduce((h,y)=>h+Pe(y,r),0),c=t.reduce((h,y)=>h+y.value,0),i=0,l=0,f=!1,g=0,T=[];for(let h of d){if(i+=I(h,r),wt(De(h,r)))f=!0;else l++;g+=h.value,T.push(h);let y=(p+i+Pt(f,l))*n,_=y+c;if(g<_)continue;let G=g-_,ne=n*Pe({address:o,value:0},r);if(G>ne){let Oe=ne+y,Me=g-(c+Math.ceil(Oe));if(Me>Math.max(I({value:0},r)*n,Q(r)))return{fee:Math.ceil(Oe),inputs:T,outputs:t.concat({address:o,value:Me})}}return{fee:Math.ceil(y),inputs:T,outputs:t}}return{fee:Math.ceil(n*we({chain:r,inputs:e,outputs:t}))}}import{secp256k1 as Jr}from"@noble/curves/secp256k1.js";import{base64 as Qr,utf8 as un}from"@scure/base";import{SwapKitError as eo,UTXOScriptType as _t}from"@swapkit/helpers";import{CompactSize as to,utils as no}from"@swapkit/utxo-signer";var ro=un.decode(`\x18Bitcoin Signed Message:
2
+ `),dn={[_t.P2PKH]:31,[_t.P2SH_P2WPKH]:35,[_t.P2WPKH]:39};function oo(e){return dn[e]!==void 0}function so(e){let t=un.decode(e);return no.sha256x2(ro,to.encode(BigInt(t.length)),t)}function pn({message:e,privateKey:t,scriptType:n}){let r=dn[n];if(r===void 0)throw new eo("toolbox_utxo_unsupported_script_type",{error:`BIP-137 message signatures cannot express a ${n} address`,scriptType:n});let o=Jr.sign(so(e),t,{format:"recovered",prehash:!1}),[a=0]=o,u=new Uint8Array(65);return u[0]=r+a,u.set(o.subarray(1),1),Qr.encode(u)}import{Chain as Ae,SwapKitError as as}from"@swapkit/helpers";import{hex as An}from"@scure/base";import{Chain as Oo,derivationPathToString as So,FeeOption as Co,resolveDerivationPath as Xo,SwapKitError as q}from"@swapkit/helpers";import{BCHSigHash as Bo,CashAddrPrefix as On,CashAddrType as Sn,encodeCashAddr as Cn,NETWORKS as Ko,p2pkh as Xn,Transaction as Bn}from"@swapkit/utxo-signer";import{secp256k1 as ao}from"@noble/curves/secp256k1.js";import{hex as ee}from"@scure/base";import{HDKey as Tn}from"@scure/bip32";import{mnemonicToSeedSync as At}from"@scure/bip39";import{AssetValue as rt,applyFeeMultiplier as ln,Chain as N,derivationPathToString as He,FeeOption as Z,NetworkDerivationPath as io,SwapKitError as P,SwapKitNumber as co,UTXO_SCRIPT_TYPES as uo,warnOnce as po}from"@swapkit/helpers";import{BCHSigHash as mn,RBF_SEQUENCE as lo,SigHash as hn,Transaction as ot,utils as ho,WIF as gn}from"@swapkit/utxo-signer";var st=[N.Bitcoin];function yn({address:e,chain:t}){return J({address:e,chain:t})!==null}function fo({phrase:e,derivationPath:t,network:n,seed:r}){let o=r??At(e),u=Tn.fromMasterSeed(o,n.bip32).derive(t);if(!u.privateKey)throw new P("toolbox_utxo_invalid_params",{error:"Could not derive private key from phrase"});return u.privateKey}function vt(e){return ao.getPublicKey(e,!0)}function Re({publicKey:e,chain:t,network:n,scriptType:r}){return gt(t,je(r,e,n))}function _e({phrase:e,derivationPath:t,chain:n,wif:r,seed:o}){let a=U(n);if(r){let p=gn(a).decode(r),c=vt(p);return{privateKey:p,publicKey:c}}if(!e)throw new P("toolbox_utxo_invalid_params",{error:"Either phrase or wif must be provided"});let u=t||He(io[n]),s=fo({derivationPath:u,network:a,phrase:e,seed:o}),d=vt(s);return{privateKey:s,publicKey:d}}function To(e,t){return gn(U(t)).encode(e)}function mo({phrase:e,derivationPath:t,chain:n,seed:r}){let o=t.split("/");if(o.length<4)throw new P("toolbox_utxo_invalid_params",{error:`Derivation path must have at least 4 levels (got ${o.length}): ${t}`});let a=U(n),u=r??At(e),s=Tn.fromMasterSeed(u,a.bip32),d=o.slice(0,4).join("/");return s.derive(d)}function go(e,t){if(!e||!uo[e].witness)return!1;return e!==ue.P2SH_P2WPKH||!!t}function xn({chain:e,script:t,publicKey:n,network:r}){let o=yt(t);if(o!==ue.P2SH_P2WPKH&&o!==ue.P2TR)return{};if(!xe(e,o))return{};let a=je(o,n,r);if(ho.compareBytes(a.script,t)!==0)return{};return o===ue.P2TR?{tapInternalKey:a.tapInternalKey}:{redeemScript:a.redeemScript}}function yo(e,t,n){if(!n)return!1;let r=J({address:e,chain:t}),o=r?Ie(r):void 0;if(!o||!xe(t,o))return!1;let a=gt(t,je(o,n,U(t)));return t===N.BitcoinCash?L(a)===L(e):a===e}function xo(e){return e.witnessUtxo?.script??e.nonWitnessUtxo?.outputs[e.index??0]?.script}function Ot({chain:e,tx:t,publicKey:n,network:r,indexes:o}){let a=o??Array.from({length:t.inputsLength},(s,d)=>d),u=[];for(let s of a){let d=t.getInput(s),p=xo(d);if(!p)continue;let{redeemScript:c,tapInternalKey:i}=xn({chain:e,network:r,publicKey:n,script:p}),l={index:s};if(c&&!d.redeemScript)l.redeemScript=c;if(i&&!d.tapInternalKey)l.tapInternalKey=i;if(l.redeemScript||l.tapInternalKey)u.push(l)}return u}function de({inputs:e,outputs:t,chain:n,tx:r,sender:o,compiledMemo:a,enableRBF:u=!1}){let s=U(n),d=Tt(n),p=u?lo:void 0,c=new Set;for(let i of e){let l=`${i.hash}:${i.index}`;if(c.has(l))throw new P("toolbox_utxo_invalid_params",{error:"Duplicate input detected"});c.add(l);let f=typeof i.hash==="string"?ee.decode(i.hash):i.hash,g=i.witnessUtxo?yt(i.witnessUtxo.script):void 0,T=i.publicKey&&i.witnessUtxo?xn({chain:n,network:s,publicKey:i.publicKey,script:i.witnessUtxo.script}):{};if(d&&i.witnessUtxo&&go(g,T.redeemScript))r.addInput({...T,index:i.index,sequence:p,txid:f,witnessUtxo:{amount:BigInt(i.witnessUtxo.value),script:i.witnessUtxo.script}});else if(i.txHex)r.addInput({...T,index:i.index,nonWitnessUtxo:ee.decode(i.txHex),sequence:p,txid:f,...n===N.BitcoinCash?{sighashType:mn.ALL}:{}});else throw new P("toolbox_utxo_invalid_params",{error:`Input ${l} cannot be signed from its witnessUtxo alone: it needs its previous transaction (txHex), or — if it is a nested-segwit output — the public key that controls it, which its redeemScript derives from`})}for(let i of t){let l="address"in i&&i.address?i.address:o;if(n===N.BitcoinCash)l=j(l);if(i.script)if(a)r.addOutput({amount:0n,script:a});else throw new P("toolbox_utxo_invalid_params",{error:"An output carrying a script needs the compiled memo it carries"});else r.addOutputAddress(l,BigInt(i.value),s)}return{inputs:e,tx:r}}async function ve(e){let t=await A(e).getSuggestedTxFee();return{[Z.Average]:t,[Z.Fast]:ln(t,Z.Fast),[Z.Fastest]:ln(t,Z.Fastest)}}async function St(e){if(e!==N.Zcash)return;try{return Ue(await A(N.Zcash).getBlockHeight()+1)}catch{return Ue()}}async function bn({assetValue:e,recipient:t,memo:n,sender:r,sweep:o,fetchTxHex:a=!1,publicKey:u},s,{forEstimateOnly:d=!1,marginalFee:p}={}){let c=e.chain,i=et(r,c),l=i===ue.P2PKH||i===ue.P2SH_P2WPKH&&!yo(r,c,u),f=a||!d&&l,g=e.getBaseValue("number"),T=o?void 0:s??(await ve(c))[Z.Fastest],h=c===N.Zcash?sn(p):(T??0)*5000,y=o||T===void 0?void 0:Math.ceil(g+h);return{inputs:await A(c).getUtxos({address:r,fetchTxHex:f,targetValue:y}),outputs:[{address:t,value:o?0:g},...n?[{address:"",script:E(n),value:0}]:[]]}}async function wn({assetValue:e,recipient:t,memo:n,feeRate:r,sender:o,fetchTxHex:a=!1,enableRBF:u=!1,sweep:s,publicKey:d}){let p=e.chain,c=n?E(n):null,i=await bn({assetValue:e,fetchTxHex:a,memo:n,publicKey:d,recipient:t,sender:o,sweep:s},r),{inputs:l,outputs:f}=M({...i,chain:p,changeAddress:o,feeRate:r,sweep:s});if(!(l&&f))throw new P("toolbox_utxo_insufficient_balance",{assetValue:e,sender:o});let g=d?l.map((_)=>({..._,publicKey:d})):l,T=new ot({allowUnknownOutputs:!!c,version:1}),{inputs:h,tx:y}=de({chain:p,compiledMemo:c,enableRBF:u,inputs:g,outputs:f,sender:o,tx:T});return{inputs:h,tx:y,utxos:i.inputs}}async function Pn({assetValue:e,feeOptionKey:t=Z.Fast,feeRate:n,memo:r,sender:o,recipient:a,sweep:u}){let s=e.chain,d,p;if(n!==void 0)d=n,p=Math.floor(n);else{let l=await ve(s);d=l[Z.Fastest],p=l[t]}let c=await St(s),i=await bn({assetValue:e,memo:r,recipient:a,sender:o,sweep:u},d,{forEstimateOnly:!0,marginalFee:c});return M({...i,chain:s,changeAddress:o,feeRate:p,marginalFee:c,sweep:u})}function bo(e){return async function({from:n,memo:r,feeRate:o,feeOptionKey:a=Z.Fast,recipient:u=n,recipients:s=1}){let d=o??(await ve(e))[a],p=await St(e),c=await A(e).getUtxos({address:n,fetchTxHex:!1}),i=e===N.Zcash?c:c.filter((h)=>h.value>Math.max(Q(e),I(h,e)*d));if(!i.length)return rt.from({chain:e});let l=typeof s==="number"?Math.max(s,1):s.length,f=typeof s==="number"||l===0?Array.from({length:l||1},()=>({address:u,value:0})):[...s];if(r)f.push({address:n,script:E(r),value:0});let g;try{({outputs:g}=M({chain:e,feeRate:d,inputs:i,marginalFee:p,outputs:f,sweep:!0}))}catch(h){let y=h instanceof P&&h.errorKey==="toolbox_sweep_amount_too_low";if(e===N.Zcash&&y)return rt.from({chain:e});throw h}let T=g?.[0]?.value??0;return rt.from({chain:e,value:BigInt(T)})}}function wo(e){return async function(n){let{fee:r}=await Pn(n);return rt.from({chain:e,value:co.fromBigInt(BigInt(r),8).getValue("string")})}}function Po({chain:e,phrase:t,derivationPath:n,scriptType:r,seed:o}){let a=U(e),{privateKey:u,publicKey:s}=_e({chain:e,derivationPath:n,phrase:t,seed:o}),d=Un(e);return{getAddress:()=>Re({chain:e,network:a,publicKey:s,scriptType:r}),privateKey:u,publicKey:s,signTransaction:(p)=>{for(let{index:c,...i}of Ot({chain:e,network:a,publicKey:s,tx:p}))p.updateInput(c,i);return p.sign(u,d),p}}}function Un(e){return e===N.BitcoinCash?[mn.ALL]:[hn.ALL,hn.DEFAULT]}function Uo(e,t,n){return async function({memo:o,recipient:a,feeOptionKey:u,feeRate:s,assetValue:d,enableRBF:p=!1,sweep:c}){let i=await t?.getAddress();if(!(t&&i))throw new P("toolbox_utxo_no_signer");if(!a)throw new P("toolbox_utxo_invalid_params",{error:"Recipient address must be provided"});po({condition:p&&!st.includes(e),id:`rbf_not_supported_${e}`,warning:`RBF (Replace-by-Fee) is not reliably supported on ${e}. Transaction will be created without RBF signaling.`});let l=p&&st.includes(e),f=s||(await ve(e))[u||Z.Fast],{tx:g}=await wn({assetValue:d,enableRBF:l,feeRate:f,memo:o,publicKey:n,recipient:a,sender:i,sweep:c}),T=await t.signTransaction(g);return T.finalize(),A(e).broadcastTx(ee.encode(T.extract()))}}function _n(e){return(t)=>yn({address:t,chain:e})}function vn(e,{scriptType:t}){let n=U(e);return function(o){if(!o)throw new P("toolbox_utxo_invalid_params",{error:"Keys must be provided"});return Re({chain:e,network:n,publicKey:o.publicKey,scriptType:t})}}function _o(e){let t=e?.publicKey;if(t===void 0)return;if(t instanceof Uint8Array&&t.length===33)return t;throw new P("toolbox_utxo_invalid_params",{error:"signer.publicKey must be a 33-byte compressed public key (Uint8Array)"})}function pe(e){let{chain:t}=e,n=e.phrase?e:void 0;if(!n&&"derivationPath"in e&&e.derivationPath!==void 0)throw new P("toolbox_utxo_invalid_params",{error:"derivationPath needs a phrase; a toolbox built around a signer uses the signer's addresses"});let r=n?.phrase,o=n?.index??0,a=r?At(r):void 0,{derivationPath:u,scriptType:s}=Ye({chain:t,derivationPath:n?.derivationPath,index:o,scriptType:e.scriptType}),d=He(u),p=r?Po({chain:t,derivationPath:d,phrase:r,scriptType:s,seed:a}):void 0,c=n?void 0:e.signer,i=p||c,l=r?_e({chain:t,derivationPath:d,phrase:r,seed:a}):void 0,f=l?.publicKey??_o(c);function g(){if(i)return i.getAddress();return Promise.resolve(void 0)}function T(m){if(!r)return;let x=se({accountIndex:m,chain:t,derivationPath:u});return mo({chain:t,derivationPath:He(x),phrase:r,seed:a})}let h=T();function y(){if(!h)return;return h.publicExtendedKey}function _({accountIndex:m}={}){let x=m===void 0?h:T(m);if(!x)return;let w=se({accountIndex:m,chain:t,derivationPath:u});return{accountIndex:he(w),path:He(w),xpub:x.publicExtendedKey}}function G({accountIndex:m,index:x,change:w=!1}){let O=m===void 0?h:T(m);if(!O)return;let b=Be({accountIndex:m,chain:t,change:w,derivationPath:u,index:x}),K=U(t),D=O.deriveChild(Number(w)).deriveChild(x);if(!D.publicKey)throw new P("toolbox_utxo_invalid_params",{error:"Could not derive public key"});let X=Re({chain:t,network:K,publicKey:D.publicKey,scriptType:s}),k=ee.encode(D.publicKey);return{accountIndex:he(b),address:X,change:w,index:x,path:He(b),pubkey:k}}async function ne(m){if(!st.includes(t))return{reason:`RBF is not supported on ${t}`,supported:!1};let x=await A(t).getTransactionDetails(m);return{canReplace:x.isRBF&&!x.confirmed,confirmed:x.confirmed,enabled:x.isRBF,fee:x.fee,sequences:x.sequences,supported:!0}}async function Oe({txid:m,newFeeRate:x,recipient:w,memo:O}){if(!st.includes(t))throw new P("toolbox_utxo_rbf_not_supported",{chain:t});let b=await A(t).getTransactionDetails(m);if(!b.isRBF)throw new P("toolbox_utxo_tx_not_replaceable",{txid:m});if(b.confirmed)throw new P("toolbox_utxo_tx_already_confirmed",{blockId:b.blockId,txid:m});let K=b.inputs.reduce((v,F)=>v+F.value,0),X=b.outputs.find((v)=>v.recipient===w)?.value||0;if(X===0)throw new P("toolbox_utxo_invalid_params",{error:"Could not determine send amount from original transaction"});let k=await Promise.all(b.inputs.map(async(v)=>{let F=await A(t).getRawTx(v.transaction_hash),B=ot.fromRaw(ee.decode(F),{allowUnknownOutputs:!0,disableScriptCheck:!0}).getOutput(v.index);return{address:v.recipient,hash:v.transaction_hash,index:v.index,publicKey:f,txHex:F,value:v.value,witnessUtxo:B.script&&B.amount!==void 0?{script:Buffer.from(B.script),value:Number(B.amount)}:void 0}})),H=O?E(O):null,re=K-X-b.fee,Se=await g(),le=[];if(H)le.push({address:"",script:H,value:0});if(re>Q(t)&&Se)le.push({address:Se,value:re});let Ze=we({chain:t,inputs:k.map((v)=>({...v,type:et(v.address,t)})),outputs:[{address:w,value:X},...le]}),Y=Math.ceil(Ze*x);if(Y<=b.fee)throw new P("toolbox_utxo_rbf_fee_too_low",{newFee:Y,originalFee:b.fee});let Ce=Y-b.fee,oe=X-Ce;if(oe<=0)throw new P("toolbox_utxo_rbf_insufficient_change");let Xe=new ot({allowUnknownOutputs:!!H,version:1}),ct=[{address:w,value:oe},...le];return de({chain:t,compiledMemo:H,inputs:k,outputs:ct,sender:Se||w,tx:Xe}),{feeDelta:Ce,newFee:Y,originalFee:b.fee,tx:Xe}}async function Me({txid:m,newFeeRate:x,recipient:w,memo:O}){let{tx:b,originalFee:K,newFee:D}=await Oe({memo:O,newFeeRate:x,recipient:w,txid:m}),X=await it(b);X.finalize();let k=await A(t).broadcastTx(ee.encode(X.extract()));return{newFee:D,originalFee:K,txid:k}}function Bt({accountIndex:m,index:x,change:w=!1}){W("index",x);let O=m===void 0?h:T(m);if(!O)return;return O.deriveChild(Number(w)).deriveChild(x).privateKey||void 0}function Kt({tx:m,inputDerivations:x}){if(!h)throw new P("toolbox_utxo_no_signer");let w=Un(t),O=U(t);for(let b=0;b<x.length;b++){let K=x[b];if(!K)continue;let{derivationIndex:D,isChange:X}=K,k=Bt({change:X,index:D});if(!k)throw new P("toolbox_utxo_invalid_params",{error:`Could not derive private key for input ${b} at index ${D}`});for(let{index:H,...re}of Ot({chain:t,indexes:[b],network:O,publicKey:vt(k),tx:m}))m.updateInput(H,re);m.signIdx(k,b,w)}return m}async function Mn({utxos:m,recipient:x,assetValue:w,memo:O,feeRate:b,feeOptionKey:K,changeAddress:D,sweep:X}){if(X)throw new P("toolbox_utxo_invalid_params",{error:"Sweep is not supported for transfers from multiple addresses"});if(!h)throw new P("toolbox_utxo_no_signer");let k=b||(await ve(t))[K||Z.Fast],H=O?E(O):null,re=[{address:x,value:w.getBaseValue("number")}];if(H)re.push({address:"",script:H,value:0});let Se=m.map(({address:v,hash:F,index:B,value:ut,txHex:Wn,witnessUtxo:dt})=>({address:v,hash:F,index:B,txHex:Wn,value:ut,witnessUtxo:dt?{script:dt.script,value:dt.value}:void 0})),le=m[0]?.address,Ze=D||await g()||le||x,{inputs:Y,outputs:Ce}=M({chain:t,changeAddress:Ze,feeRate:k,inputs:Se,marginalFee:await St(t),outputs:re});if(!(Y&&Ce))throw new P("toolbox_utxo_insufficient_balance",{assetValue:w,sender:"multiple addresses"});let oe=new ot({allowUnknownOutputs:!!H,version:1}),Xe=Y.map((v)=>{let F=m.find((B)=>B.hash===v.hash&&B.index===v.index);return F?{derivationIndex:F.derivationIndex,isChange:F.isChange}:{derivationIndex:0,isChange:!1}}),ct=Y.map((v,F)=>{let B=Xe[F],ut=B?h.deriveChild(Number(B.isChange)).deriveChild(B.derivationIndex).publicKey:null;return{...v,publicKey:ut??void 0}});return de({chain:t,compiledMemo:H,inputs:ct,outputs:Ce,sender:Ze,tx:oe}),Kt({inputDerivations:Xe,tx:oe}),oe.finalize(),A(t).broadcastTx(ee.encode(oe.extract()))}function Zn({address:m,gapLimit:x=20}){if(!h)return;for(let w=0;w<x;w++){let O=G({change:!1,index:w}),b=G({change:!0,index:w}),K=O?.address===m?!1:b?.address===m;if(O?.address===m||b?.address===m)return{change:K,index:w}}return}function it(m){if(!i)throw new P("toolbox_utxo_no_signer");return i.signTransaction(m)}let Nn=t===N.Bitcoin&&l?async(m)=>pn({message:m,privateKey:l.privateKey,scriptType:s}):void 0;async function zn(m){let x=await it(m);return x.finalize(),await A(t).broadcastTx(ee.encode(x.extract()))}return{accumulative:M,broadcastTx:(m)=>A(t).broadcastTx(m),bumpFee:Me,calculateTxSize:(m)=>we({...m,chain:t}),createKeysForPath:(m)=>_e({...m,chain:t}),createReplacementTransaction:Oe,createTransaction:(m)=>wn({publicKey:f,...m}),deriveAddressAtIndex:G,derivePrivateKeyAtIndex:Bt,estimateMaxSendableAmount:bo(t),estimateTransactionFee:wo(t),getAddress:g,getAddressFromKeys:vn(t,{scriptType:s}),getAddressType:(m)=>J({address:m,chain:t}),getBalance:fn(t),getExtendedPublicKey:y,getExtendedPublicKeyInfo:_,getFeeRates:()=>ve(t),getInputsOutputsFee:Pn,getNetworkForChain:()=>U(t),getPrivateKeyFromMnemonic:(m)=>To(_e({...m,chain:t}).privateKey,t),isRBFEnabled:ne,keys:l,resolveDerivationIndex:Zn,scriptType:s,signAndBroadcastTransaction:zn,signMessage:Nn,signTransaction:it,signTransactionWithMultipleKeys:Kt,transfer:Uo(t,i,f),transferFromMultipleAddresses:Mn,validateAddress:_n(t)}}import{getZcashAddressType as vo,toTransparentZcashAddress as Ao,validateZcashAddress as Ct}from"@swapkit/utxo-signer";function Ee(e){return ke(e)!==null}var z=Oo.BitcoinCash;function at(e){return L(We(e))}function ko(e){let t=U(z);function n(o){return o.sign(e.privateKey,[Bo.ALL]),o}function r(){let o=Xn(e.publicKey,t);if(!o.hash)throw new q("toolbox_utxo_invalid_address",{error:"Could not derive BCH address hash"});let a=Cn({hash:o.hash,prefix:On.MAINNET,type:Sn.P2PKH});return Promise.resolve(a.replace(/^bitcoincash:/,""))}return{getAddress:r,signTransaction:n}}function Kn(e={}){let t="phrase"in e?e.phrase:void 0,n="index"in e?e.index||0:0,r="derivationPath"in e?e.derivationPath:void 0,o=Xo({chain:z,derivationPath:r,index:n}),a=So(o),u=t?_e({chain:z,derivationPath:a,phrase:t}):void 0,s=u?ko(u):("signer"in e)?e.signer:void 0;function d(){return Promise.resolve(s?.getAddress())}let p="scriptType"in e?e.scriptType:void 0,{getBalance:c,getFeeRates:i,broadcastTx:l,...f}=pe(t?{chain:z,index:n,phrase:t,...r?{derivationPath:r,scriptType:p}:{scriptType:p}}:{chain:z,scriptType:p});function g(y,_=!0){return c(L(We(y)))}function T(y){if(!s)throw new q("toolbox_utxo_no_signer");return s.signTransaction(y)}async function h(y){let _=await T(y);return _.finalize(),await l(An.encode(_.extract()))}return{...f,broadcastTx:l,buildTx:Io,createTransaction:kn,getAddress:d,getAddressFromKeys:Do,getBalance:g,getFeeRates:i,signAndBroadcastTransaction:h,signTransaction:T,stripPrefix:L,stripToCashAddress:at,transfer:Fo({broadcastTx:l,getFeeRates:i,signer:s}),validateAddress:Ee}}async function kn({assetValue:e,recipient:t,memo:n,feeRate:r,sender:o,sweep:a}){if(!Ee(t))throw new q("toolbox_utxo_invalid_address",{address:t});let u=Math.ceil(e.getBaseValue("number")+r*7500),s=await A(z).getUtxos({address:at(o),fetchTxHex:!0,targetValue:a?void 0:u}),d=n?E(n):null,p=[],c=j(t);if(p.push({address:c,value:a?0:e.getBaseValue("number")}),d)p.push({script:d,value:0});let{inputs:i,outputs:l}=M({chain:z,feeRate:r,inputs:s,outputs:p,sweep:a});if(!(i&&l))throw new q("toolbox_utxo_insufficient_balance",{assetValue:e,sender:o});let f=new Bn({allowUnknownOutputs:!!d,version:1}),g=j(o),{inputs:T,tx:h}=de({chain:z,compiledMemo:d,inputs:i,outputs:l.map((y)=>("address"in y)&&y.address?{...y,address:j(y.address)}:y),sender:g,tx:f});return{inputs:T,tx:h,utxos:i}}function Fo({broadcastTx:e,getFeeRates:t,signer:n}){return async function({recipient:o,assetValue:a,feeOptionKey:u=Co.Fast,sweep:s,...d}){let p=await n?.getAddress();if(!(n&&p))throw new q("toolbox_utxo_no_signer");if(!o)throw new q("toolbox_utxo_invalid_params",{error:"Recipient address must be provided"});let c=d.feeRate||(await t())[u],{tx:i}=await kn({...d,assetValue:a,feeRate:c,recipient:o,sender:p,sweep:s}),l=await n.signTransaction(i);return l.finalize(),e(An.encode(l.extract()))}}async function Io({assetValue:e,recipient:t,memo:n,feeRate:r,sender:o}){let a=We(t);if(!Ee(a))throw new q("toolbox_utxo_invalid_address",{address:a});let u=Math.ceil(e.getBaseValue("number")+r*7500),s=await A(z).getUtxos({address:at(o),fetchTxHex:!0,targetValue:u}),d=Number(r.toFixed(0)),p=n?E(n):null,c=[];if(c.push({address:j(t),value:e.getBaseValue("number")}),p)c.push({script:p,value:0});let{inputs:i,outputs:l}=M({chain:z,feeRate:d,inputs:s,outputs:c});if(!(i&&l))throw new q("toolbox_utxo_insufficient_balance",{assetValue:e,sender:o});let f=new Bn({allowUnknownOutputs:!!p,version:1}),{inputs:g,tx:T}=de({chain:z,compiledMemo:p,inputs:i,outputs:l,sender:j(o),tx:f});return{inputs:g,tx:T,utxos:s}}function Do(e){let t=Ko.bitcoinCash,n=Xn(e.publicKey,t);if(!n.hash)throw new q("toolbox_utxo_invalid_address",{error:"Could not derive BCH address hash"});return Cn({hash:n.hash,prefix:On.MAINNET,type:Sn.P2PKH}).replace(/^bitcoincash:/,"")}import{createBase58check as Ho,hex as Ro}from"@scure/base";import{HDKey as Dn}from"@scure/bip32";import{mnemonicToSeedSync as Hn}from"@scure/bip39";import{Chain as V,derivationPathToString as Eo,FeeOption as Mo,SwapKitError as te}from"@swapkit/helpers";import{Address as Zo,createZcashTransaction as No,getZcashTransactionFormat as zo,isTransparentZcashAddress as Fn,OutScript as Wo,toTransparentZcashAddress as $o,utils as Rn,WIF as Lo,ZcashSigHash as Vo}from"@swapkit/utxo-signer";import{match as qo,P as Xt}from"ts-pattern";var Go=Ho(Rn.sha256);function Yo(e){return Go.encode(e)}function jo({phrase:e,derivationPath:t}){let n=Hn(e),o=Dn.fromMasterSeed(n).derive(t);if(!o.privateKey||!o.publicKey)throw new te("toolbox_utxo_invalid_params");let{privateKey:a,publicKey:u}=o,s=Rn.hash160(u),d=new Uint8Array([28,184]),p=new Uint8Array(d.length+s.length);p.set(d,0),p.set(s,d.length);let c=Yo(p);return{getAddress:()=>Promise.resolve(c),signTransaction:(i)=>{if(i.signAllInputs(a,u,Vo.ALL),"extract"in i)return i.finalizeAllInputs(),Promise.resolve(i.extract());return Promise.resolve(i)}}}function Jo({inputs:e,outputs:t,tx:n,sender:r,compiledMemo:o}){let a=U(V.Zcash);for(let u of e){let s=Zo(a).decode(r),d=Wo.encode(s);n.addInput({index:u.index,script:d,sequence:4294967295,txid:Ro.decode(u.hash),value:BigInt(u.value)})}for(let u of t){let s="address"in u&&u.address?u.address:r,d=u.script;if(d&&!o)continue;if(d&&o)n.addOutput({amount:0n,script:o});else n.addOutputAddress(s,BigInt(u.value),a)}return{inputs:e,tx:n}}async function Qo(){try{return await A(V.Zcash).getBlockHeight()+1}catch(e){throw new te({errorKey:"toolbox_utxo_api_error",info:{chain:V.Zcash,reason:"Block height is required to choose the Zcash transaction format"}},e)}}async function In(e){let{assetValue:t,recipient:n,memo:r,feeRate:o,sender:a,fetchTxHex:u,sweep:s}=e,d=U(V.Zcash);if(!Fn(a,d))throw new te("toolbox_utxo_invalid_address",{address:a});let p=$o(n);if(!Fn(p,d))throw new te("toolbox_utxo_invalid_address",{address:n,error:"Zcash transaction creation currently supports transparent addresses only"});let c=r?E(r):null,i=await A(V.Zcash).getUtxos({address:a,fetchTxHex:u!==!1}),l=[{address:p,value:s?0:Number(t.getBaseValue("string"))},...c?[{script:c,value:0}]:[]],f=await Qo(),{inputs:g,outputs:T}=M({chain:V.Zcash,changeAddress:a,feeRate:o,inputs:i,marginalFee:Ue(f),outputs:l,sweep:s});if(!(g&&T))throw new te("toolbox_utxo_insufficient_balance",{assetValue:t,sender:a});let h=No({...zo(f),expiryHeight:0,lockTime:0}),{tx:y,inputs:_}=Jo({compiledMemo:c,inputs:g,outputs:T,sender:a,tx:h});return{inputs:_,outputs:T,tx:y}}function En(e={}){let t="scriptType"in e?e.scriptType:void 0,n=qo(e).with({signer:Xt.not(Xt.nullish)},({signer:p})=>p).with({phrase:Xt.string},({phrase:p,derivationPath:c,index:i=0})=>{let{derivationPath:l}=Ye({chain:V.Zcash,derivationPath:c,index:i,scriptType:t}),f=Eo(l);return jo({derivationPath:f,phrase:p})}).otherwise(()=>{return}),r=pe({chain:V.Zcash,scriptType:t,signer:n});async function o(p){if(!n)throw new te("toolbox_utxo_no_signer");return await n.signTransaction(p)}async function a(p){let c=await o(p);return r.broadcastTx(c.toHex())}async function u({recipient:p,assetValue:c,feeOptionKey:i=Mo.Fast,sweep:l,...f}){let g=await n?.getAddress();if(!(n&&g))throw new te("toolbox_utxo_no_signer");let T=f.feeRate||(await r.getFeeRates())[i],{tx:h}=await In({...f,assetValue:c,feeRate:T,recipient:p,sender:g,sweep:l}),_=(await n.signTransaction(h)).toHex();return r.broadcastTx(_)}function s({phrase:p,derivationPath:c="m/44'/133'/0'/0/0"}){let i=Hn(p),f=Dn.fromMasterSeed(i).derive(c);if(!f.privateKey||!f.publicKey)throw new te("toolbox_utxo_invalid_params");return{privateKey:f.privateKey,publicKey:f.publicKey}}function d({phrase:p,derivationPath:c="m/44'/133'/0'/0/0"}){let i=s({derivationPath:c,phrase:p}),l=U(V.Zcash);return Lo(l).encode(i.privateKey)}return{...r,createKeysForPath:s,createTransaction:In,getPrivateKeyFromMnemonic:d,signAndBroadcastTransaction:a,signTransaction:o,transfer:u,validateAddress:Ct}}import{hex as es}from"@scure/base";import{HDKey as ts}from"@scure/bip32";import{derivationPathToString as ns,NetworkDerivationPath as rs,updateDerivationPath as os}from"@swapkit/helpers";function ss({xpub:e,chain:t,count:n,startIndex:r=0,accountIndex:o,purpose:a,scriptType:u}){if(W("count",n),n<1)throw RangeError("count must be at least 1");W("startIndex",r),Ge(t,u),mt({chain:t,purpose:a,scriptType:u});let s=U(t),d=ts.fromExtendedKey(e,s.bip32),p=a===void 0?void 0:os(rs[t],{purpose:a}),c=se({accountIndex:o,chain:t,derivationPath:p}),i=he(c),l=[];for(let f of[!1,!0]){let g=d.deriveChild(Number(f));for(let T=0;T<n;T++){let h=r+T,y=g.deriveChild(h);if(!y.publicKey)continue;let _=Be({accountIndex:o,chain:t,change:f,derivationPath:p,index:h});l.push({accountIndex:i,address:Re({chain:t,network:s,publicKey:y.publicKey,scriptType:u}),change:f,index:h,pubkey:es.encode(y.publicKey),...a===void 0?{}:{path:ns(_)}})}}return l}function oi(e,t){switch(e){case Ae.BitcoinCash:return Kn(t||{});case Ae.Zcash:return En(t);case Ae.Bitcoin:case Ae.Dogecoin:case Ae.Litecoin:case Ae.Dash:return pe({chain:e,...t});default:throw new as("toolbox_utxo_not_supported",{chain:e})}}export{tn as InputSizes,Zs as MIN_TX_FEE,Zr as OP_RETURN_OVERHEAD,xt as OutputSizes,Mr as SEGWIT_MARKER_FLAG_WEIGHT,bt as TX_OVERHEAD,ue as UTXOScriptType,Nt as UtxoNetwork,Wr as ZCASH_FEE_REDUCTION_HEIGHT,$r as ZCASH_FEE_REDUCTION_MARGIN_BLOCKS,Lr as ZIP317_GRACE_ACTIONS,nt as ZIP317_MARGINAL_FEE,nn as ZIP317_P2PKH_STANDARD_INPUT_SIZE,Vr as ZIP317_P2PKH_STANDARD_OUTPUT_SIZE,zr as ZIP317_REDUCED_MARGINAL_FEE,M as accumulative,an as accumulativeZcash,de as addInputsAndOutputs,vn as addressFromKeysGetter,W as assertDerivationIndex,Te as baseUrl,Qe as buildSweep,we as calculateTxSize,Yr as calculateZcashFee,Ut as calculateZip317Fee,oo as canSignBitcoinMessage,E as compileMemo,Kn as createBCHToolbox,ls as createCustomUtxoApi,Ln as createHDWalletHelpers,pe as createUTXOToolbox,En as createZcashToolbox,ss as deriveAddressesFromXpub,Ps as detectAddressNetwork,ke as getBchAddressType,Q as getDustThreshold,De as getInputScriptType,I as getInputSize,Ot as getMissingSpendingMetadata,U as getNetworkForChain,Pe as getOutputSize,Nr as getOutputSizeForAddress,et as getScriptTypeForAddress,he as getUTXOAccountIndexFromPath,se as getUTXOAccountPath,Be as getUTXOAddressPath,_n as getUTXOAddressValidator,J as getUtxoAddressType,A as getUtxoApi,hs as getUtxoNetwork,oi as getUtxoToolbox,Pt as getWitnessOverhead,vo as getZcashAddressType,sn as getZcashFeeBuffer,Ue as getZcashMarginalFee,wt as isSegwitScriptType,ws as isValidAddress,Yt as nonSegwitChains,L as stripPrefix,at as stripToCashAddress,We as toCashAddress,j as toLegacyAddress,Ao as toTransparentZcashAddress,$e as tryDecodeAddress,Ee as validateBchAddress,yn as validateUtxoAddress,Ct as validateZcashAddress};
@@ -7,9 +7,9 @@ type AccumulativeParams<T extends UTXOSizeInput> = {
7
7
  chain: UTXOChain;
8
8
  changeAddress?: string;
9
9
  sweep?: boolean;
10
+ marginalFee?: number;
10
11
  };
11
- export declare function getDustThreshold(chain: UTXOChain): 100000 | 550 | 5500 | 546;
12
- export declare function accumulative<T extends UTXOSizeInput>({ inputs, outputs, feeRate, chain, changeAddress, sweep, }: AccumulativeParams<T>): {
12
+ export declare function accumulative<T extends UTXOSizeInput>({ inputs, outputs, feeRate, chain, changeAddress, sweep, marginalFee, }: AccumulativeParams<T>): {
13
13
  fee: number;
14
14
  inputs: T[];
15
15
  outputs: TargetOutput[];
@@ -3,3 +3,4 @@ export * from "./bchaddrjs";
3
3
  export * from "./coinselect";
4
4
  export { canSignBitcoinMessage } from "./messageSigning";
5
5
  export * from "./txSize";
6
+ export * from "./zip317";
@@ -9,6 +9,17 @@ export declare const MIN_TX_FEE = 1000;
9
9
  export declare const TX_OVERHEAD: number;
10
10
  export declare const SEGWIT_MARKER_FLAG_WEIGHT = 2;
11
11
  export declare const OP_RETURN_OVERHEAD: number;
12
+ export declare function getDustThreshold(chain: UTXOChain): 100000 | 550 | 5500 | 546;
13
+ export declare function buildSweep<T extends UTXOSizeInput>({ inputs, outputs, fee, dustThreshold, }: {
14
+ inputs: T[];
15
+ outputs: TargetOutput[];
16
+ fee: number;
17
+ dustThreshold: number;
18
+ }): {
19
+ fee: number;
20
+ inputs: T[];
21
+ outputs: TargetOutput[];
22
+ };
12
23
  export declare function compileMemo(memo: string): Uint8Array;
13
24
  export { UTXOScriptType } from "@swapkit/helpers";
14
25
  export declare const InputSizes: Record<UTXOScriptType, number>;
@@ -0,0 +1,38 @@
1
+ import type { TargetOutput, UTXOSizeInput } from "../types";
2
+ export declare const ZIP317_MARGINAL_FEE = 5000;
3
+ export declare const ZIP317_REDUCED_MARGINAL_FEE = 1000;
4
+ export declare const ZCASH_FEE_REDUCTION_HEIGHT = 3590000;
5
+ export declare const ZCASH_FEE_REDUCTION_MARGIN_BLOCKS = 12;
6
+ export declare const ZIP317_GRACE_ACTIONS = 2;
7
+ export declare const ZIP317_P2PKH_STANDARD_INPUT_SIZE = 150;
8
+ export declare const ZIP317_P2PKH_STANDARD_OUTPUT_SIZE = 34;
9
+ type ZcashFeeParams = {
10
+ inputs: UTXOSizeInput[];
11
+ outputs: TargetOutput[];
12
+ marginalFee?: number;
13
+ };
14
+ type ZcashSelectionParams<T extends UTXOSizeInput> = {
15
+ inputs: T[];
16
+ outputs: TargetOutput[];
17
+ changeAddress?: string;
18
+ sweep?: boolean;
19
+ marginalFee?: number;
20
+ };
21
+ export declare function getZcashMarginalFee(targetHeight?: number): 5000 | 1000;
22
+ export declare function calculateZip317Fee({ inputBytes, outputBytes, marginalFee, }: {
23
+ inputBytes: number;
24
+ outputBytes: number;
25
+ marginalFee?: number;
26
+ }): number;
27
+ export declare function calculateZcashFee({ inputs, outputs, marginalFee }: ZcashFeeParams): number;
28
+ export declare function getZcashFeeBuffer(marginalFee?: number): number;
29
+ export declare function accumulativeZcash<T extends UTXOSizeInput>({ inputs, outputs, changeAddress, sweep, marginalFee, }: ZcashSelectionParams<T>): {
30
+ fee: number;
31
+ inputs: T[];
32
+ outputs: TargetOutput[];
33
+ } | {
34
+ fee: number;
35
+ inputs?: undefined;
36
+ outputs?: undefined;
37
+ };
38
+ export {};
package/package.json CHANGED
@@ -1,5 +1,5 @@
1
1
  {
2
- "dependencies": { "@swapkit/helpers": "6.4.2", "@swapkit/utxo-signer": "3.3.0" },
2
+ "dependencies": { "@swapkit/helpers": "6.5.0", "@swapkit/utxo-signer": "3.3.0" },
3
3
  "description": "SwapKit - Toolboxes",
4
4
  "devDependencies": {
5
5
  "@aptos-labs/ts-sdk": "7.0.1",
@@ -133,5 +133,5 @@
133
133
  "type-check:go": "tsgo"
134
134
  },
135
135
  "type": "module",
136
- "version": "6.6.0"
136
+ "version": "6.6.2"
137
137
  }
@@ -1,2 +0,0 @@
1
- import{ja as Ve}from"./chunk-qk8kg62t.js";import{ka as de}from"./chunk-pz8xe0qj.js";import{Chain as x}from"@swapkit/helpers";import{match as In}from"ts-pattern";import{Chain as g,getChainConfig as J,getRPCUrl as At,SKConfig as Mt,SwapKitError as U}from"@swapkit/helpers";import{FallbackProvider as Gt,getAddress as Ee,Interface as Ot,JsonRpcProvider as se,Network as Bt}from"ethers";import{match as _e}from"ts-pattern";function It(e){return new se(e)}async function Nn(e,t){return It(t||await At(e))}function Ce(e){let t=Mt.get("rpcUrls")[e]?.filter(Boolean)??[];if(t.length===0)throw new U("helpers_chain_no_public_or_set_rpc_url",{chain:e});let{chainId:n}=J(e),o=Bt.from(Number(n)),[a]=t;if(t.length===1)return new se(a,o,{staticNetwork:o});return new Gt(t.map((r,i)=>({priority:i+1,provider:new se(r,o,{staticNetwork:o}),stallTimeout:2000})),o,{quorum:1})}function O(e){return e>0n?`0x${e.toString(16)}`:"0x0"}function Fe(e){let{explorerUrl:t,chainIdHex:n,rpcUrls:o}=J(e);return function(){return e!==g.Ethereum?{...Vt({chain:e}),blockExplorerUrls:[t],chainId:n,rpcUrls:o}:void 0}}function Ae(e){return![g.Adi,g.Arbitrum,g.BinanceSmartChain,g.Robinhood].includes(e)}function Vt({chain:e}){let{name:t,nativeCurrency:n,baseDecimal:o}=J(e);return _e(e).with(g.Arbitrum,()=>({chainName:"Arbitrum One",nativeCurrency:{decimals:o,name:"Ethereum",symbol:g.Ethereum}})).with(g.Aurora,()=>({chainName:"Aurora Mainnet",nativeCurrency:{decimals:o,name:"Ethereum",symbol:g.Ethereum}})).with(g.Avalanche,()=>({chainName:"Avalanche Network",nativeCurrency:{decimals:o,name:"Avalanche",symbol:e}})).with(g.Base,()=>({chainName:"Base Mainnet",nativeCurrency:{decimals:o,name:"Ethereum",symbol:g.Ethereum}})).with(g.Berachain,()=>({chainName:"Berachain",nativeCurrency:{decimals:o,name:"Berachain",symbol:"BERA"}})).with(g.XLayer,()=>({chainName:"X Layer",nativeCurrency:{decimals:o,name:"OKB",symbol:"OKB"}})).with(g.BinanceSmartChain,()=>({chainName:"BNB Smart Chain Mainnet",nativeCurrency:{decimals:o,name:"Binance Coin",symbol:"BNB"}})).with(g.Gnosis,()=>({chainName:"Gnosis",nativeCurrency:{decimals:o,name:"xDAI",symbol:"XDAI"}})).with(g.Optimism,()=>({chainName:"OP Mainnet",nativeCurrency:{decimals:o,name:"Ethereum",symbol:g.Ethereum}})).with(g.Polygon,()=>({chainName:"Polygon Mainnet",nativeCurrency:{decimals:o,name:"Polygon",symbol:g.Polygon}})).with(g.Robinhood,()=>({chainName:"Robinhood Chain",nativeCurrency:{decimals:o,name:"Ethereum",symbol:g.Ethereum}})).otherwise(()=>({chainName:t,nativeCurrency:{decimals:o,name:n,symbol:n}}))}async function Me(e,t){if(!("authorize"in e))throw Error("Signer does not support EIP-7702 authorization. Requires ethers.js v6.14+");let n={...t,nonce:t.nonce!==void 0?BigInt(t.nonce):void 0};return await e.authorize(n)}var ve=(e)=>typeof e==="string"&&/^0x[a-fA-F0-9]{64}$/.test(e),Rt=(e)=>{try{return typeof e==="string"&&!!Ee(e)}catch{return!1}};function St(e,t){let n=t!==void 0?`index ${t}: `:"",o=(a,r)=>{throw new U({errorKey:"toolbox_evm_invalid_eip7702_authorization",info:{field:a,message:`${n}${r}`}})};_e(e).when(({chainId:a})=>typeof a!=="bigint",()=>o("chainId","chainId must be a bigint")).when(({address:a})=>!Rt(a),()=>o("address","address must be a valid checksummed address")).when(({nonce:a})=>typeof a!=="bigint"||a<0n,()=>o("nonce","nonce must be a non-negative bigint")).when(({signature:a})=>!a,()=>o("signature","signature is required")).when(({signature:a})=>typeof a?.yParity!=="number"||![0,1].includes(a.yParity),()=>o("signature.yParity","yParity must be 0 or 1")).when(({signature:a})=>!ve(a?.r),()=>o("signature.r","r must be a 32-byte hex string")).when(({signature:a})=>!ve(a?.s),()=>o("signature.s","s must be a 32-byte hex string")).otherwise(()=>{})}function Ge(e){return[{key:"name",type:"string"},{key:"version",type:"string"},{key:"chainId",type:"uint256"},{key:"verifyingContract",type:"address"},{key:"salt",type:"bytes32"}].filter(({key:t})=>e[t]!=null).map(({key:t,type:n})=>({name:t,type:n}))}function Oe(e){if(!("EIP712Domain"in e.types))return e;let{EIP712Domain:t,...n}=e.types,o=Ge(e.domain);if(!(Array.isArray(t)&&t.length===o.length&&o.every(({name:r,type:i},s)=>t[s]?.name===r&&t[s]?.type===i)))throw new U({errorKey:"toolbox_evm_typed_data_domain_mismatch",info:{declared:t,expected:o}});return{...e,types:n}}function ce(e){return e.charAt(0).toUpperCase()+e.slice(1)}function ue(e,t){if(e.isTuple()&&e.components){let n=ce(e.name);return t[n]=e.components.map((o)=>({name:o.name,type:ue(o,t)})),n}if(e.isArray()){let n=e.arrayChildren;if(n?.isTuple()&&n.components){let o=ce(e.name.replace(/s$/,""));return t[o]=n.components.map((a)=>({name:a.name,type:ue(a,t)})),`${o}[]`}return`${n?.type??"bytes"}[]`}return e.type}function le(e,t){if(typeof e==="bigint")return e;if(t?.isTuple()&&typeof e?.toObject==="function"){let n=e.toObject(),o={};for(let[a,r]of(t.components??[]).entries())o[r.name]=le(n[r.name]??e[a],r);return o}if(Array.isArray(e)){let n=t?.arrayChildren;return e.map((o)=>le(o,n??void 0))}return e}function Ln({chain:e,abi:t,data:n,to:o}){let r=new Ot(t).parseTransaction({data:n});if(!r)throw new U({errorKey:"toolbox_evm_invalid_params",info:{error:"Could not decode calldata"}});let i={},s=ce(r.name);i[s]=r.fragment.inputs.map((p)=>({name:p.name,type:ue(p,i)}));let c={};for(let[p,b]of r.fragment.inputs.entries())c[b.name]=le(r.args[p],b);let{chainId:l}=J(e),u={chainId:Number(l),verifyingContract:Ee(o)},d=Ge(u);return{domain:u,message:c,primaryType:s,types:{EIP712Domain:d,...i}}}function Be(e,t){if(!Array.isArray(e)||e.length===0)throw new U({errorKey:"toolbox_evm_invalid_eip7702_authorization",info:{message:"EIP-7702 transactions require at least one authorization"}});for(let[n,o]of e.entries())if(St(o,n),t!==void 0&&o.chainId!==t)throw new U({errorKey:"toolbox_evm_invalid_eip7702_authorization",info:{field:"chainId",message:`index ${n}: authorization chainId (${o.chainId}) does not match transaction chainId (${t})`}})}import{Chain as T,derivationPathToString as Fn,FeeOption as An,resolveDerivationPath as Mn}from"@swapkit/helpers";import{HDNodeWallet as Gn}from"ethers";import{match as On,P as ot}from"ts-pattern";var Ie=[{inputs:[{components:[{internalType:"address",name:"target",type:"address"},{internalType:"bytes",name:"callData",type:"bytes"}],internalType:"struct Multicall2.Call[]",name:"calls",type:"tuple[]"}],name:"aggregate",outputs:[{internalType:"uint256",name:"blockNumber",type:"uint256"},{internalType:"bytes[]",name:"returnData",type:"bytes[]"}],stateMutability:"nonpayable",type:"function"},{inputs:[{components:[{internalType:"address",name:"target",type:"address"},{internalType:"bytes",name:"callData",type:"bytes"}],internalType:"struct Multicall2.Call[]",name:"calls",type:"tuple[]"}],name:"blockAndAggregate",outputs:[{internalType:"uint256",name:"blockNumber",type:"uint256"},{internalType:"bytes32",name:"blockHash",type:"bytes32"},{components:[{internalType:"bool",name:"success",type:"bool"},{internalType:"bytes",name:"returnData",type:"bytes"}],internalType:"struct Multicall2.Result[]",name:"returnData",type:"tuple[]"}],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"uint256",name:"blockNumber",type:"uint256"}],name:"getBlockHash",outputs:[{internalType:"bytes32",name:"blockHash",type:"bytes32"}],stateMutability:"view",type:"function"},{inputs:[],name:"getBlockNumber",outputs:[{internalType:"uint256",name:"blockNumber",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[],name:"getCurrentBlockCoinbase",outputs:[{internalType:"address",name:"coinbase",type:"address"}],stateMutability:"view",type:"function"},{inputs:[],name:"getCurrentBlockDifficulty",outputs:[{internalType:"uint256",name:"difficulty",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[],name:"getCurrentBlockGasLimit",outputs:[{internalType:"uint256",name:"gaslimit",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[],name:"getCurrentBlockTimestamp",outputs:[{internalType:"uint256",name:"timestamp",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"address",name:"addr",type:"address"}],name:"getEthBalance",outputs:[{internalType:"uint256",name:"balance",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[],name:"getLastBlockHash",outputs:[{internalType:"bytes32",name:"blockHash",type:"bytes32"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"bool",name:"requireSuccess",type:"bool"},{components:[{internalType:"address",name:"target",type:"address"},{internalType:"bytes",name:"callData",type:"bytes"}],internalType:"struct Multicall2.Call[]",name:"calls",type:"tuple[]"}],name:"tryAggregate",outputs:[{components:[{internalType:"bool",name:"success",type:"bool"},{internalType:"bytes",name:"returnData",type:"bytes"}],internalType:"struct Multicall2.Result[]",name:"returnData",type:"tuple[]"}],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"bool",name:"requireSuccess",type:"bool"},{components:[{internalType:"address",name:"target",type:"address"},{internalType:"bytes",name:"callData",type:"bytes"}],internalType:"struct Multicall2.Call[]",name:"calls",type:"tuple[]"}],name:"tryBlockAndAggregate",outputs:[{internalType:"uint256",name:"blockNumber",type:"uint256"},{internalType:"bytes32",name:"blockHash",type:"bytes32"},{components:[{internalType:"bool",name:"success",type:"bool"},{internalType:"bytes",name:"returnData",type:"bytes"}],internalType:"struct Multicall2.Result[]",name:"returnData",type:"tuple[]"}],stateMutability:"nonpayable",type:"function"}];import{AssetValue as kt,applyFeeMultiplierToBigInt as M,Chain as j,EVMChains as Nt,FeeOption as y,isGasAsset as ke,SwapKitError as m,SwapKitNumber as Q}from"@swapkit/helpers";import{erc20ABI as K}from"@swapkit/helpers/contracts";import{BrowserProvider as Lt,Contract as Ne,getAddress as ee,getBytes as Dt,Interface as Le,isError as D,resolveAddress as zt,Transaction as pe}from"ethers";import{match as De}from"ts-pattern";function Y(e){return{getBalance:Ve(e)}}function Kn(e){return e}var be=BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff");function te({chain:e=j.Ethereum,provider:t,signer:n,isEIP1559Compatible:o=!0,estimateGasPrices:a,estimateAdditionalFee:r}){let i=a??X({chain:e,isEIP1559Compatible:o,provider:t}),s=$e({chain:e,estimateAdditionalFee:r,estimateGasPrices:i,isEIP1559Compatible:o,provider:t,signer:n});return{approve:tn({chain:e,isEIP1559Compatible:o,provider:t,signer:n}),approvedAmount:qe({chain:e,provider:t}),broadcastTransaction:(c)=>t.broadcastTransaction(c),call:ae({chain:e,isEIP1559Compatible:o,provider:t,signer:n}),createApprovalTx:yn({chain:e,provider:t,signer:n}),createContract:Kt({chain:e,provider:t}),createContractTxObject:W({chain:e,provider:t}),createTransaction:s,createTransferTx:s,EIP1193SendTransaction:oe(t),estimateCall:je({provider:t,signer:n}),estimateGasLimit:on({chain:e,provider:t,signer:n}),estimateGasPrices:i,estimateTransactionFee:dn({chain:e,isEIP1559Compatible:o,provider:t}),getAddress:()=>n?n.getAddress():void 0,getBalance:Y(e).getBalance,getNetworkParams:Fe(e),isApproved:en({chain:e,provider:t}),sendTransaction:Xe({chain:e,estimateGasPrices:i,isEIP1559Compatible:o,provider:t,signer:n}),signAuthorization:an({signer:n}),signMessage:n?(c)=>n.signMessage(c):void 0,signTypedData:n?async(c)=>{let{domain:l,types:u,value:d}=Oe(c);return await n.signTypedData(l,u,d)}:void 0,transfer:nn({chain:e,estimateAdditionalFee:r,estimateGasPrices:i,isEIP1559Compatible:o,provider:t,signer:n}),validateAddress:Ut}}function Ut(e){try{return ee(e),!0}catch{return!1}}function ne(e){return e instanceof Lt}function ge(e,t,n){return new Ne(e,Le.from(t),n)}function Kt({provider:e}){return function(n,o){return new Ne(n,Le.from(o),e)}}var Ht=["payable","nonpayable"];function qt({abi:e,funcName:t}){let n=e.find((o)=>o.name===t);if(!n)throw new m("toolbox_evm_no_abi_fragment",{funcName:t});return n.stateMutability&&Ht.includes(n.stateMutability)}function Yn(e){return ee(e)}var jt=30000,Re=new WeakMap,Se=()=>{};function Wt(e,t,n){let o=Date.now();for(let[r,i]of e)if(i.held===0&&o-i.at>jt)e.delete(r);let a=e.get(t);if(!a||n>=a.next){let r={at:o,held:1,next:n+1,released:new Set};return e.set(t,r),{floor:r,nonce:n}}a.held+=1;for(let r of[...a.released].sort((i,s)=>i-s))if(a.released.delete(r),r>=n)return{floor:a,nonce:r};return{floor:a,nonce:a.next++}}async function ze({address:e,nonce:t,provider:n}){if(t!==void 0&&t!==null)return{nonce:t,release:Se,settle:Se};let{chainId:o}=await n.getNetwork(),a=Re.get(n)??new Map;Re.set(n,a);let r=`${o}:${e.toLowerCase()}`,i=await n.getTransactionCount(e,"pending"),{floor:s,nonce:c}=Wt(a,r,i),l=!1,u=(d)=>{if(l)return;if(l=!0,s.held-=1,s.at=Date.now(),d)s.released.add(c)};return{nonce:c,release:()=>u(!0),settle:()=>u(!1)}}function Z(e,t=0){if(!e||t>3)return"";if(typeof e==="string")return e.toLowerCase();if(typeof e!=="object")return"";let{error:n,info:o,message:a,shortMessage:r}=e;return[(typeof r==="string"?r:typeof a==="string"?a:"").toLowerCase(),Z(n,t+1),Z(o?.error,t+1)].filter(Boolean).join(" ")}function fe(e){if(D(e,"NONCE_EXPIRED")||D(e,"REPLACEMENT_UNDERPRICED"))return!0;let t=Z(e);return/nonce (?:is )?too low/.test(t)||t.includes("replacement transaction underpriced")}function ye(e){let t=Z(e);return t.includes("already known")||t.includes("known transaction")||t.includes("already imported")}function Ue(e){return D(e,"NETWORK_ERROR")||D(e,"SERVER_ERROR")||D(e,"TIMEOUT")}function Xt(e){return Ue(e)||D(e,"UNSUPPORTED_OPERATION")}function Ke(e){return Ue(e)||ye(e)}function He(e,t){return e.getTransaction(t).then((n)=>n!==null,()=>!1)}async function $t({provider:e,signer:t,txObject:n}){try{let o=pe.from(await t.signTransaction(n)).hash;return o&&await He(e,o)?o:null}catch{return null}}function oe(e,t=!1){return function({value:o,...a}){if(!ne(e))throw new m("toolbox_evm_provider_not_eip1193_compatible");let r={...a,gasPrice:"gasPrice"in a?a.gasPrice:void 0,maxFeePerGas:"maxFeePerGas"in a?a.maxFeePerGas:void 0,maxPriorityFeePerGas:"maxPriorityFeePerGas"in a?a.maxPriorityFeePerGas:void 0},{gasLimit:i,gasPrice:s,maxFeePerGas:c,maxPriorityFeePerGas:l,...u}=r,d={...u,...t&&i!==void 0&&{gas:O(BigInt(i))},...t&&s!==void 0&&{gasPrice:O(BigInt(s))},...t&&c!==void 0&&{maxFeePerGas:O(BigInt(c))},...t&&l!==void 0&&{maxPriorityFeePerGas:O(BigInt(l))},value:O(BigInt(o||0))};return e.send("eth_sendTransaction",[d])}}function Qn(e,t){let n=xe(e,t);if(n)return ee(n.toLowerCase());throw new m("toolbox_evm_invalid_gas_asset_address")}var Jt=Nt.reduce((e,t)=>(e[t]="0x0000000000000000000000000000000000000000",e),{}),Yt={...Jt,[j.Polygon]:"0x0000000000000000000000000000000000001010"},Qt="0x4200000000000000000000000000000000000042";function xe({chain:e,symbol:t,ticker:n},o){try{if(ke({chain:e,symbol:t}))return Yt[o];if(e===j.Optimism&&t==="OP")return Qt;return ee(t.slice(n.length+1).replace(/^0X/,""))}catch{return null}}function W({provider:e}){return async({contractAddress:t,abi:n,funcName:o,funcParams:a=[],txOverrides:r})=>{let i=await ge(t,n,e).getFunction(o).populateTransaction(...a.concat(r).filter((s)=>typeof s<"u"));return{...i,value:O(BigInt(i.value||0))}}}function X({chain:e,provider:t,isEIP1559Compatible:n=!0}){return De(e).with(j.Gnosis,()=>async function(){try{let{gasPrice:a,maxPriorityFeePerGas:r}=await t.getFeeData();if(!a||r===null)throw new m("toolbox_evm_no_fee_data");return{[y.Average]:{maxFeePerGas:M(a,y.Average),maxPriorityFeePerGas:M(r,y.Average)},[y.Fast]:{maxFeePerGas:M(a,y.Fast),maxPriorityFeePerGas:M(r,y.Fast)},[y.Fastest]:{maxFeePerGas:M(a,y.Fastest),maxPriorityFeePerGas:M(r,y.Fastest)}}}catch(a){throw new m("toolbox_evm_gas_estimation_error",{error:a.msg??a.toString()})}}).with(j.Arbitrum,()=>async function(){try{let{gasPrice:a}=await t.getFeeData();if(!a)throw new m("toolbox_evm_no_fee_data");let r=a*12n/10n;return{[y.Average]:{gasPrice:r},[y.Fast]:{gasPrice:M(r,y.Fast)},[y.Fastest]:{gasPrice:M(r,y.Fastest)}}}catch(a){throw new m("toolbox_evm_gas_estimation_error",{error:a.msg??a.toString()})}}).otherwise(()=>async function(){try{let{maxFeePerGas:a,maxPriorityFeePerGas:r,gasPrice:i}=await t.getFeeData();if(n){if(a===null||r===null)throw new m("toolbox_evm_no_fee_data");return{[y.Average]:{maxFeePerGas:a,maxPriorityFeePerGas:r},[y.Fast]:{maxFeePerGas:M(a,y.Fast),maxPriorityFeePerGas:M(r,y.Fast)},[y.Fastest]:{maxFeePerGas:M(a,y.Fastest),maxPriorityFeePerGas:M(r,y.Fastest)}}}if(!i)throw new m("toolbox_evm_no_gas_price");return{[y.Average]:{gasPrice:i},[y.Fast]:{gasPrice:M(i,y.Fast)},[y.Fastest]:{gasPrice:M(i,y.Fastest)}}}catch(a){throw new m("toolbox_evm_gas_estimation_error",{error:a.msg??a.toString()})}})}async function Zt({chain:e,contract:t,contractProvider:n,feeOption:o,funcName:a,funcParams:r,isEIP1559Compatible:i,provider:s,signer:c,txOverrides:l}){let u=l?.from||await c.getAddress();if(!u)throw new m("toolbox_evm_no_signer_address");let d=t.connect(c),p=X({chain:e,isEIP1559Compatible:i,provider:s}),[{maxFeePerGas:b,maxPriorityFeePerGas:f,gasPrice:P},A]=await Promise.all([p().then((_)=>_[o]),t.getFunction(a).estimateGas(...r,l)]),C=typeof u==="string"?u:await zt(u,n),{nonce:G,release:R,settle:k}=await ze({address:C,nonce:l?.nonce,provider:c.provider??s});try{let _=await d[a](...r,{...l,gasLimit:A,gasPrice:P,maxFeePerGas:b,maxPriorityFeePerGas:f,nonce:G});return typeof _?.hash==="string"?_?.hash:_}catch(_){if(fe(_)){let E=l?.nonce!=null?"caller":"pending",w={address:C,error:_,nonce:G,nonceSource:E};throw new m({errorKey:"toolbox_evm_nonce_conflict",info:w},w)}if(!Ke(_))R();throw _}finally{k()}}function ae({provider:e,isEIP1559Compatible:t,signer:n,chain:o}){return async function({callProvider:r,contractAddress:i,abi:s,funcName:c,funcParams:l=[],txOverrides:u={},feeOption:d=y.Fast}){let p=r||e;if(!i)throw new m("toolbox_evm_invalid_params",{error:"contractAddress must be provided"});let b=qt({abi:s,funcName:c});if(b&&ne(p)&&n){let A=W({chain:o,provider:p}),C=u?.from||await n?.getAddress(),G=await A({abi:s,contractAddress:i,funcName:c,funcParams:l,txOverrides:{...u,from:C}});return oe(p)(G)}let f=ge(i,s,p);if(b){if(!n)throw new m("toolbox_evm_no_signer");return Zt({chain:o,contract:f,contractProvider:p,feeOption:d,funcName:c,funcParams:l,isEIP1559Compatible:t,provider:e,signer:n,txOverrides:u})}let P=await f[c]?.(...l);return typeof P?.hash==="string"?P?.hash:P}}function qe({provider:e,chain:t}){return function({assetAddress:o,spenderAddress:a,from:r}){return ae({chain:t,isEIP1559Compatible:!0,provider:e})({abi:K,contractAddress:o,funcName:"allowance",funcParams:[r,a]})}}function en({provider:e,chain:t}){return async function({assetAddress:o,spenderAddress:a,from:r,amount:i=be}){let s=await qe({chain:t,provider:e})({assetAddress:o,from:r,spenderAddress:a});return Q.fromBigInt(s).gte(Q.fromBigInt(BigInt(i)))}}function tn({signer:e,isEIP1559Compatible:t=!0,provider:n,chain:o}){return async function({assetAddress:r,spenderAddress:i,feeOptionKey:s=y.Fast,amount:c,gasLimitFallback:l,from:u,nonce:d}){let p=[i,BigInt(c||be)],b=await e?.getAddress()||u,f={abi:K,contractAddress:r,funcName:"approve",funcParams:p,signer:e,txOverrides:{from:b}};if(ne(n)){let A=W({chain:o,provider:n}),C=oe(n),G=await A(f);return C(G)}return ae({chain:o,isEIP1559Compatible:t,provider:n,signer:e})({...f,feeOption:s,funcParams:p,txOverrides:{from:b,gasLimit:l?BigInt(l.toString()):void 0,nonce:d}})}}function nn({chain:e,estimateGasPrices:t,estimateAdditionalFee:n,signer:o,isEIP1559Compatible:a=!0,provider:r}){return async function({assetValue:s,memo:c,recipient:l,feeOptionKey:u=y.Fast,sender:d,sweep:p,...b}){let f=d||await o?.getAddress(),P=Xe({chain:e,estimateGasPrices:t,isEIP1559Compatible:a,provider:r,signer:o});if(!f)throw new m("toolbox_evm_no_from_address");let A=await $e({chain:e,estimateAdditionalFee:n,estimateGasPrices:t,isEIP1559Compatible:a,provider:r,signer:o})({assetValue:s,feeOptionKey:u,memo:c,recipient:l,sender:f,sweep:p,...b});return P({...A,feeOptionKey:u,sweep:p})}}function je({provider:e,signer:t}){return function({contractAddress:o,abi:a,funcName:r,funcParams:i=[],txOverrides:s}){if(!o)throw new m("toolbox_evm_no_contract_address");let c=ge(o,a,e);return t?c.connect(t).getFunction(r).estimateGas(...i,s):c.getFunction(r).estimateGas(...i,s)}}function on({provider:e,signer:t}){return async function({assetValue:o,recipient:a,memo:r,data:i,sender:s,funcName:c,funcParams:l,txOverrides:u}){let d=o.bigIntValue,p=o.isGasAsset?null:xe(o,o.chain);if(p&&c)return je({provider:e,signer:t})({abi:K,contractAddress:p,funcName:c,funcParams:l,txOverrides:u});let{hexlify:b,toUtf8Bytes:f}=await import("ethers");return e.estimateGas({data:i?i:r?b(f(r)):void 0,from:s,to:a,value:d})}}function an({signer:e}){if(!e)return;return(t)=>Me(e,t)}var We=(e)=>e.type===4||(e.authorizations?.length??0)>0,rn=(e)=>!We(e)&&(e.type===2||!!e.maxFeePerGas||!!e.maxPriorityFeePerGas),sn=(e,t=!0)=>{if(We(e))return"eip7702";if(rn(e))return"eip1559";if(e.gasPrice!=null)return"legacy";return t?"eip1559":"legacy"};function cn(e,t){if(e==="legacy"){if(t.gasPrice===void 0)throw new m("toolbox_evm_no_fee_data");return{gasPrice:O(t.gasPrice)}}if(t.maxFeePerGas===void 0||t.maxPriorityFeePerGas===void 0)throw new m("toolbox_evm_no_fee_data");return{maxFeePerGas:O(t.maxFeePerGas),maxPriorityFeePerGas:O(t.maxPriorityFeePerGas)}}function Xe({chain:e,estimateGasPrices:t,provider:n,signer:o,isEIP1559Compatible:a=!0}){return async function({feeOptionKey:i=y.Fast,sweep:s,...c}){let{from:l,to:u,data:d,value:p,...b}=c;if(!o)throw new m("toolbox_evm_no_signer");if(!u)throw new m("toolbox_evm_no_to_address");let f={...b,data:d||"0x",from:l,to:u,value:BigInt(p||0)};if(ne(n))return oe(n,s)(f);let P=l||await o.getAddress(),{chainId:A}=await n.getNetwork(),C=o.provider??n,{nonce:G,release:R,settle:k}=await ze({address:P,nonce:c.nonce,provider:C}),_=async()=>{let E=sn(f,a);if(E==="eip7702")Be(f.authorizations||[],A);let w=De(E).with("eip7702",()=>4).with("eip1559",()=>2).otherwise(()=>0),I={...f,chainId:A,nonce:G,type:w,...E==="eip7702"&&{authorizationList:f.authorizations}},F=t??X({chain:e,isEIP1559Compatible:a,provider:n}),V=(E==="legacy"?f.gasPrice!==void 0:f.maxFeePerGas!==void 0&&f.maxPriorityFeePerGas!==void 0)?{}:cn(E,(await F())[i]),h;try{h=O(f.gasLimit?BigInt(f.gasLimit):await n.estimateGas(I)*11n/10n)}catch(B){throw new m("toolbox_evm_error_estimating_gas_limit",{error:B})}return{...I,gasLimit:h,...V}};try{let E=await _().catch((w)=>{throw R(),w});try{return(await o.sendTransaction(E)).hash}catch(w){let I=c.nonce!=null?"caller":"pending",F={address:P,error:w,nonce:G,nonceSource:I};if(fe(w))throw new m({errorKey:"toolbox_evm_nonce_conflict",info:F},F);if(ye(w)){let h=await $t({provider:C,signer:o,txObject:{...E,from:P}});if(h)return h;throw new m({errorKey:"toolbox_evm_tx_already_known",info:F},F)}if(!Xt(w))throw R(),new m({errorKey:"toolbox_evm_error_sending_transaction",info:F},F);let N=D(w,"UNSUPPORTED_OPERATION"),V;try{V=await o.signTransaction({...E,from:P})}catch(h){if(N)R();let B={...F,fallbackError:h};throw new m({errorKey:"toolbox_evm_error_sending_transaction",info:B},B)}try{return(await C.broadcastTransaction(V)).hash}catch(h){let B={...F,fallbackError:h};if(ye(h)){let z=pe.from(V).hash;if(z)return z}if(fe(h)){let z=pe.from(V).hash;if(z&&await He(C,z))return z;throw new m({errorKey:"toolbox_evm_nonce_conflict",info:B},B)}if(N&&!Ke(h))R();throw new m({errorKey:"toolbox_evm_error_sending_transaction",info:B},B)}}}finally{k()}}}function L(e,t){throw new m({errorKey:"toolbox_sweep_amount_too_low",info:{balance:e.toString(),fee:t.toString()}})}function un(e,t){if(t){if(e.maxFeePerGas===void 0||e.maxPriorityFeePerGas===void 0)throw new m("toolbox_evm_no_fee_data");return{feeFields:{maxFeePerGas:e.maxFeePerGas,maxPriorityFeePerGas:e.maxPriorityFeePerGas},feePerGas:e.maxFeePerGas}}if(e.gasPrice===void 0)throw new m("toolbox_evm_no_fee_data");return{feeFields:{gasPrice:e.gasPrice},feePerGas:e.gasPrice}}function Pe(e,t){if(e>t)return e;return t}function ln(e){return Dt(e).reduce((t,n)=>t+(n===0?4n:16n),21000n)}function me(e){let n=(e instanceof Error?e.message:String(e)).toLowerCase();return n.includes("insufficient funds")||n.includes("insufficient balance")||n.includes("gas required exceeds allowance")}async function mn({balance:e,estimateAdditionalFee:t,feeOptionKey:n,l2Reserve:o,sweepTx:a,valueBeforeL1Fee:r}){if(!t)return 0n;let i=await t({...a,value:r})??0n,s=M(i,n),c=r-s;if(c<=0n)L(e,o+s);let l=await t({...a,value:c})??i;return M(Pe(i,l),n)}async function pn({chain:e,data:t,estimateGasPrices:n,estimateAdditionalFee:o,feeOptionKey:a,from:r,isEIP1559Compatible:i,provider:s,recipient:c,transaction:l}){let u=await s.getBalance(r),d=n??X({chain:e,isEIP1559Compatible:i,provider:s}),{feeFields:p,feePerGas:b}=un((await d())[a],i),f={...l,...p,data:t,from:r,to:c},P=ln(t)*b;if(u-P<=0n)L(u,P);let A=(u-P)/2n,C;try{C=await s.estimateGas({...f,value:A})}catch(h){if(!me(h))throw h;try{C=await s.estimateGas({...f,value:0n})}catch(B){if(me(B))L(u,P);throw B}}let G=C*b;if(u-G<=0n)L(u,G);let _=C*11n/10n*b,E=u>_?u-_:0n,w;try{w=await s.estimateGas({...f,value:E})}catch(h){if(!me(h))throw h;L(u,_)}let I=w*b,F=u-I;if(F<=0n)L(u,I);let N=await mn({balance:u,estimateAdditionalFee:o,feeOptionKey:a,l2Reserve:I,sweepTx:{...f,gasLimit:w},valueBeforeL1Fee:F}),V=F-N;if(V<=0n)L(u,I+N);return{...f,gasLimit:w,value:O(V)}}async function fn({chain:e,contractAddress:t,from:n,provider:o}){let a=await ae({chain:e,provider:o})({abi:K,contractAddress:t,funcName:"balanceOf",funcParams:[n]});if(typeof a!=="bigint")throw new m({errorKey:"toolbox_evm_invalid_transaction",info:{error:"Invalid ERC20 balance"}});return a}function $e({chain:e,estimateAdditionalFee:t,estimateGasPrices:n,isEIP1559Compatible:o=!0,provider:a,signer:r}){return async function({assetValue:s,authorizations:c,memo:l,recipient:u,data:d,feeOptionKey:p=y.Fast,gasLimit:b,sender:f,sweep:P,type:A,maxFeePerGas:C,maxPriorityFeePerGas:G,gasPrice:R,...k}){let _=s.getBaseValue("bigint"),E=f||await r?.getAddress();if(!E)throw new m("toolbox_evm_no_from_address");if(P&&(A===4||(c?.length??0)>0))throw new m({errorKey:"toolbox_not_supported",info:{chain:e,reason:"EIP-7702 sweep transactions are not supported"}});if(ke(s)){let{hexlify:N,toUtf8Bytes:V}=await import("ethers"),h=d||N(V(l||""));if(!P)return{...k,...c!==void 0&&{authorizations:c},data:h,from:E,...b!==void 0&&{gasLimit:b},to:u,...A!==void 0&&{type:A},value:O(_)};return pn({chain:e,data:h,estimateAdditionalFee:t,estimateGasPrices:n,feeOptionKey:p,from:E,isEIP1559Compatible:o,provider:a,recipient:u,transaction:{nonce:k.nonce,type:A}})}let w=xe(s,e);if(!w)throw new m("toolbox_evm_no_contract_address");let I=W({chain:e,provider:a}),F=P?await fn({chain:e,contractAddress:w,from:E,provider:a}):_;if(P&&F<=0n)throw new m({errorKey:"toolbox_sweep_amount_too_low",info:{asset:s.toString(),balance:F.toString()}});return I({abi:K,contractAddress:w,funcName:"transfer",funcParams:[u,F],txOverrides:{from:E,gasLimit:b,gasPrice:R,maxFeePerGas:C,maxPriorityFeePerGas:G,nonce:k.nonce}})}}function yn({provider:e,signer:t,chain:n}){return async function({assetAddress:a,spenderAddress:r,amount:i,from:s,nonce:c}){let l=await t?.getAddress()||s,u=W({chain:n,provider:e}),d=["bigint","number"].includes(typeof i)?i:i||be;return await u({abi:K,contractAddress:a,funcName:"approve",funcParams:[r,BigInt(d)],txOverrides:{from:l,nonce:c}})}}function dn({provider:e,isEIP1559Compatible:t=!0,chain:n}){return async function({feeOption:a=y.Fast,...r}){let s=await X({chain:n,isEIP1559Compatible:t,provider:e})(),c=await e.estimateGas(r),l=kt.from({chain:n}),{gasPrice:u,maxFeePerGas:d,maxPriorityFeePerGas:p}=s[a];if(!t&&u)return l.set(Q.fromBigInt(u*c,l.decimal));if(d&&p){let b=(d+p)*c;return l.set(Q.fromBigInt(b,l.decimal))}throw new m("toolbox_evm_no_gas_price")}}import{applyFeeMultiplierToBigInt as H,Chain as Qe,derivationPathToString as bn,FeeOption as S,getChainConfig as gn,resolveDerivationPath as xn,SwapKitError as q}from"@swapkit/helpers";import{Contract as Pn,HDNodeWallet as Tn}from"ethers";import{match as wn,P as Ye}from"ts-pattern";var Je=[{inputs:[{internalType:"address",name:"_owner",type:"address"}],stateMutability:"nonpayable",type:"constructor"},{anonymous:!1,inputs:[{indexed:!1,internalType:"uint256",name:"",type:"uint256"}],name:"DecimalsUpdated",type:"event"},{anonymous:!1,inputs:[{indexed:!1,internalType:"uint256",name:"",type:"uint256"}],name:"GasPriceUpdated",type:"event"},{anonymous:!1,inputs:[{indexed:!1,internalType:"uint256",name:"",type:"uint256"}],name:"L1BaseFeeUpdated",type:"event"},{anonymous:!1,inputs:[{indexed:!1,internalType:"uint256",name:"",type:"uint256"}],name:"OverheadUpdated",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"previousOwner",type:"address"},{indexed:!0,internalType:"address",name:"newOwner",type:"address"}],name:"OwnershipTransferred",type:"event"},{anonymous:!1,inputs:[{indexed:!1,internalType:"uint256",name:"",type:"uint256"}],name:"ScalarUpdated",type:"event"},{inputs:[],name:"decimals",outputs:[{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[],name:"gasPrice",outputs:[{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"bytes",name:"_data",type:"bytes"}],name:"getL1Fee",outputs:[{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"bytes",name:"_data",type:"bytes"}],name:"getL1GasUsed",outputs:[{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"uint256",name:"_gasUsed",type:"uint256"}],name:"getOperatorFee",outputs:[{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[],name:"l1BaseFee",outputs:[{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[],name:"overhead",outputs:[{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[],name:"owner",outputs:[{internalType:"address",name:"",type:"address"}],stateMutability:"view",type:"function"},{inputs:[],name:"renounceOwnership",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[],name:"scalar",outputs:[{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"uint256",name:"_decimals",type:"uint256"}],name:"setDecimals",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"uint256",name:"_gasPrice",type:"uint256"}],name:"setGasPrice",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"uint256",name:"_baseFee",type:"uint256"}],name:"setL1BaseFee",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"uint256",name:"_overhead",type:"uint256"}],name:"setOverhead",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"uint256",name:"_scalar",type:"uint256"}],name:"setScalar",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"address",name:"newOwner",type:"address"}],name:"transferOwnership",outputs:[],stateMutability:"nonpayable",type:"function"}];var hn="0x420000000000000000000000000000000000000f";function re(e){return new Pn(hn,Je,e)}function Ze(e){return async function(){let n=re(e);if(n&&"l1BaseFee"in n)return await n?.l1BaseFee();return}}function et(e){return async function({from:n,to:o,nonce:a,...r}){let{Transaction:i}=await import("ethers");if(!o)throw new q("toolbox_evm_invalid_transaction",{error:"Missing to address"});return i.from({...r,authorizationList:r.authorizationList,nonce:a??(n?await e.getTransactionCount(n,"pending"):0),to:o}).unsignedSerialized}}function we(e,t){return async function(o){let a=re(e),r=o.chainId??t??(await e.getNetwork()).chainId,i=await et(e)({...o,chainId:r});if(a&&"getL1Fee"in a){let s=await a.getL1Fee(i);if(typeof s!=="bigint")throw new q({errorKey:"toolbox_evm_invalid_transaction",info:{error:"Invalid OP-stack L1 fee"}});return s}return}}function he(e){return async function(n){let o=re(e);if(o&&"getOperatorFee"in o){let a=await o.getOperatorFee(n);if(typeof a!=="bigint")throw new q({errorKey:"toolbox_evm_invalid_transaction",info:{error:"Invalid OP-stack operator fee"}});return a}return 0n}}function vn(e,t){let n=we(e,t),o=he(e);return async function(r){if(r.gasLimit===void 0||r.gasLimit===null)throw new q({errorKey:"toolbox_evm_invalid_transaction",info:{error:"Missing gas limit for OP-stack fee estimation"}});let[i,s]=await Promise.all([n(r),o(BigInt(r.gasLimit.toString()))]);return(i??0n)+s}}function tt(e){return async function(n){let a=(await e.getFeeData()).gasPrice??0n,r=await e.estimateGas(n);return a*r}}function En(e){return async function(n){let o=await we(e)(n)??0n,a=await tt(e)(n),r=n.gasLimit??await e.estimateGas(n),i=await he(e)(BigInt(r.toString()));return o+a+i}}function _n(e){return async function(n){let o=re(e),a=await et(e)(n);if(o&&"getL1GasUsed"in o)return o.getL1GasUsed(a)}}function Te({feeOption:e,maxFeePerGas:t,maxPriorityFeePerGas:n}){let o=H(t,e),a=H(n,e);return{maxFeePerGas:Pe(o,a),maxPriorityFeePerGas:a}}function Cn(e){return async function(){try{let{maxFeePerGas:n,maxPriorityFeePerGas:o,gasPrice:a}=await e.getFeeData(),r=await Ze(e)(),i=a;if(!(n&&o))throw new q("toolbox_evm_no_fee_data");return{[S.Average]:{gasPrice:i,l1GasPrice:r,...Te({feeOption:S.Average,maxFeePerGas:n,maxPriorityFeePerGas:o})},[S.Fast]:{gasPrice:H(i,S.Fast),l1GasPrice:H(r||0n,S.Fast),...Te({feeOption:S.Fast,maxFeePerGas:n,maxPriorityFeePerGas:o})},[S.Fastest]:{gasPrice:H(i,S.Fastest),l1GasPrice:H(r||0n,S.Fastest),...Te({feeOption:S.Fastest,maxFeePerGas:n,maxPriorityFeePerGas:o})}}}catch(n){throw new q("toolbox_evm_gas_estimation_error",{error:n.msg??n.toString()})}}}function ie(e){return function({provider:n,...o}){let a=wn(o).with({phrase:Ye.string},({phrase:p,derivationPath:b,index:f=0})=>Tn.fromPhrase(p,void 0,bn(xn({chain:e,derivationPath:b,index:f}))).connect(n)).with({signer:Ye.any},({signer:p})=>p).otherwise(()=>{return}),r=Ze(n),i=BigInt(gn(e).chainId),s=we(n,i),c=vn(n,i),l=he(n),u=e===Qe.Optimism?Cn(n):void 0;return{...te({chain:e,estimateAdditionalFee:c,estimateGasPrices:u,provider:n,signer:a}),estimateL1Gas:_n(n),estimateL1GasCost:s,estimateL2GasCost:tt(n),estimateOperatorFee:l,estimateTotalGasCost:En(n),getBalance:Y(e).getBalance,getL1GasPrice:r}}}var nt=ie(Qe.Optimism);function at(e){let t=v(T.Ethereum)(e);async function n(o,a="0x5ba1e12693dc8f9c48aad8770482f4739beed696",r="aggregate",i=An.Fast){let s=await t.createContractTxObject({abi:Ie,contractAddress:a,funcName:r,funcParams:[o]});return t.sendTransaction({...s,feeOptionKey:i})}return{...t,multicall:n}}var rt=v(T.Adi),it=v(T.Arbitrum),st=v(T.Arc),ct=v(T.Aurora),ut=v(T.Avalanche),lt=ie(T.Base),mt=v(T.Berachain),pt=v(T.BinanceSmartChain),ft=v(T.Botanix),yt=v(T.Core),dt=v(T.Corn),bt=v(T.Cronos),gt=v(T.Gnosis),xt=v(T.Robinhood),Pt=v(T.Hyperevm),Tt=v(T.Linea),wt=v(T.Polygon),ht=v(T.MegaETH),vt=v(T.Monad),Et=v(T.Plasma),_t=v(T.Sonic),Ct=ie(T.Unichain),Ft=v(T.XLayer);function v(e){return function({provider:n,...o}){let a=Ae(e),r=On(o).with({phrase:ot.string},({phrase:s,derivationPath:c,index:l=0})=>Gn.fromPhrase(s,void 0,Fn(Mn({chain:e,derivationPath:c,index:l}))).connect(n)).with({signer:ot.any},({signer:s})=>s).otherwise(()=>{return});return te({chain:e,isEIP1559Compatible:a,provider:n,signer:r})}}function Vn(e,t){return In(e).with(x.Adi,()=>rt(t)).with(x.Arbitrum,()=>it(t)).with(x.Arc,()=>st(t)).with(x.Aurora,()=>ct(t)).with(x.Avalanche,()=>ut(t)).with(x.Base,()=>lt(t)).with(x.Berachain,()=>mt(t)).with(x.BinanceSmartChain,()=>pt(t)).with(x.Botanix,()=>ft(t)).with(x.Core,()=>yt(t)).with(x.Corn,()=>dt(t)).with(x.Cronos,()=>bt(t)).with(x.Ethereum,()=>at(t)).with(x.Gnosis,()=>gt(t)).with(x.Hyperevm,()=>Pt(t)).with(x.Linea,()=>Tt(t)).with(x.MegaETH,()=>ht(t)).with(x.Monad,()=>vt(t)).with(x.Optimism,()=>nt(t)).with(x.Plasma,()=>Et(t)).with(x.Polygon,()=>wt(t)).with(x.Robinhood,()=>xt(t)).with(x.Sonic,()=>_t(t)).with(x.Unichain,()=>Ct(t)).with(x.XLayer,()=>Ft(t)).exhaustive()}async function To(e,t){let n={...t,provider:t?.provider||Ce(e)};return Vn(e,n)}
2
- export{Y as b,Kn as c,It as d,Nn as e,Ce as f,O as g,Fe as h,Ae as i,Me as j,St as k,Ge as l,Oe as m,Ln as n,Be as o,be as p,te as q,Ut as r,ne as s,ge as t,Kt as u,qt as v,Yn as w,oe as x,Qn as y,Yt as z,xe as A,W as B,X as C,We as D,rn as E,sn as F,Pe as G,Te as H,ie as I,nt as J,at as K,rt as L,it as M,st as N,ct as O,ut as P,lt as Q,mt as R,pt as S,ft as T,yt as U,dt as V,bt as W,gt as X,xt as Y,Pt as Z,Tt as _,wt as $,ht as aa,vt as ba,Et as ca,_t as da,Ct as ea,Ft as fa,Vn as ga,To as ha};