@swapkit/toolboxes 6.4.1 → 6.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,18 @@
1
1
  # @swapkit/toolboxes
2
2
 
3
+ ## 6.5.0
4
+
5
+ ### Minor Changes
6
+
7
+ - [#460](https://github.com/swapkit/sdk/pull/460) [`9190931`](https://github.com/swapkit/sdk/commit/9190931bb2c1f911543a22cb8ccc91e3913cfe6c) Thanks [@hippocampusSK](https://github.com/hippocampusSK)! - The keystore can now sign Bitcoin messages (BIP-137) and declares the `btcMessage` capability for Bitcoin, so flows that need a Bitcoin signed message, like cancelling a Harbor Bitcoin limit order, work with it.
8
+ - [#467](https://github.com/swapkit/sdk/pull/467) [`6ddbd12`](https://github.com/swapkit/sdk/commit/6ddbd12b87af88d304aa575518970214ca4516e9) Thanks [@ice-chillios](https://github.com/ice-chillios)! - `getTokenAddress` and `getChecksumAddressFromAsset` now use `isGasAsset`, so `MONAD.MON`, `XLAYER.OKB` and `GNO.xDAI` resolve to the native asset address instead of returning `null` or throwing. Identifiers that repeat the chain name on a chain whose gas asset has another ticker, such as `ARB.ARB` or `BSC.BSC`, no longer resolve to the native asset address. `ContractAddress[Chain.Optimism]` is now the zero address, like every EVM chain except Polygon, so `OP.ETH` resolves to the zero address instead of the OP token contract (`0x4200000000000000000000000000000000000042`). `OP.OP` without an address still resolves to the OP token contract. The Botanix toolbox now targets the Botanix network instead of Sonic.
9
+ - [#460](https://github.com/swapkit/sdk/pull/460) [`9190931`](https://github.com/swapkit/sdk/commit/9190931bb2c1f911543a22cb8ccc91e3913cfe6c) Thanks [@hippocampusSK](https://github.com/hippocampusSK)! - EVM transactions that carry only a legacy `gasPrice` are now sent as legacy transactions instead of failing on chains that support EIP-1559.
10
+ - [#468](https://github.com/swapkit/sdk/pull/468) [`8062907`](https://github.com/swapkit/sdk/commit/8062907e7f2dd5a7c12f436b9ee3a2b5fad66e15) Thanks [@ice-chillios](https://github.com/ice-chillios)! - The TON toolbox no longer falls back to Orbs TON Access when every configured TON RPC fails. That service no longer returns any nodes, so the fallback itself failed with an unclear error. Now the toolbox throws `helpers_chain_rpc_connection_failed`, and jetton transfers and sweeps report that error instead of `core_swap_contract_not_found`. Set a working endpoint with `SKConfig.setRpcUrl(Chain.Ton, [...])` or pass `provider` to the toolbox. The `@orbs-network/ton-access` dependency is removed.
11
+ - [#474](https://github.com/swapkit/sdk/pull/474) [`f107064`](https://github.com/swapkit/sdk/commit/f10706478e42440912a009b011b92b4e345104f8) Thanks [@ice-chillios](https://github.com/ice-chillios)! - The TON toolbox spaces out and retries its requests to the public Toncenter endpoint, which allows about one request per second without an API key, so TON jetton sales such as TON.USDT are much less likely to fail there. Requests to the chain's default endpoints start at least 1.1 seconds apart, through a queue shared by every toolbox in the process. Waits therefore grow with concurrent TON activity; for servers and other high-volume use, configure a custom TON RPC or a Toncenter API key, which is not spaced out. The endpoint health check is not queued. A request rejected with 429 or a gateway error (502 and above) is sent again after 1, 2 and 4 seconds. A node's 500 answer, such as a rejected message, a timeout and a network failure fail at once. A jetton lookup that the RPC does not answer is reported as `helpers_chain_rpc_connection_failed` instead of `core_swap_contract_not_found`. A toolbox looks up each jetton wallet address only once per jetton and owner.
12
+ - [#465](https://github.com/swapkit/sdk/pull/465) [`d03591d`](https://github.com/swapkit/sdk/commit/d03591dd257fb2735d1ce1eb72540e11082a084e) Thanks [@towanTG](https://github.com/towanTG)! - Zcash transactions keep working through the NU7 network upgrade (mainnet block 3,543,405, around 5 November 2026), which rejects version 4 transactions. From the activation block on, the Zcash toolbox builds version 5 transactions with the NU7 consensus branch id `0x77190ad9`; before it, nothing changes. If the block height can't be fetched, building a Zcash transaction now fails with `toolbox_utxo_api_error` instead of guessing the format, because a guess on the wrong side of an upgrade produces a transaction the network rejects. `@swapkit/utxo-signer` can now build, sign, parse and compute the txid of transparent version 5 transactions, including version 5 PSBTs and PCZTs, and exports `getZcashTransactionFormat` and `ZCASH_NU7_ACTIVATION_HEIGHT`. Parsing a raw Zcash transaction now keeps input txids in the right byte order, so re-serializing it no longer changes them.
13
+ - [#460](https://github.com/swapkit/sdk/pull/460) [`9190931`](https://github.com/swapkit/sdk/commit/9190931bb2c1f911543a22cb8ccc91e3913cfe6c) Thanks [@hippocampusSK](https://github.com/hippocampusSK)! - `SwapKitApi` now covers the full limit-order API: `getLimitOrderTokens`, `getLimitOrderQuote`, `buildLimitOrder`, `submitLimitOrder`, `getLimitOrders`, `getLimitOrder`, `buildLimitOrderCancel` and `submitLimitOrderCancel`, with typed responses and `LimitOrderStatus` and `LimitOrderTxType` constants. `getLimitOrderQuote` accepts an optional `providers` list to restrict the quote to those providers. Each call can be overridden through `SKConfig.endpoints`. (via @swapkit/helpers@6.4.0)
14
+ - [#464](https://github.com/swapkit/sdk/pull/464) [`c20cc10`](https://github.com/swapkit/sdk/commit/c20cc10b4534c7948dfe4b57f29e07f1b183f1ca) Thanks [@github-actions](https://github.com/apps/github-actions)! - Update generated token lists. (via @swapkit/helpers@6.4.0)
15
+
3
16
  ## 6.4.1
4
17
 
5
18
  ### Patch Changes
@@ -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("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};
@@ -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-vdabez6b.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-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 +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-vdabez6b.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-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 +1 @@
1
- import"../../chunk-qsbf0z90.js";import{m as Te,r as we}from"../../chunk-vdabez6b.js";import"../../chunk-qk8kg62t.js";import"../../chunk-pz8xe0qj.js";function Sn({builder:e,grouping:n="na",orders:t}){return{builder:e,grouping:n,orders:t,type:"order"}}function Tn({cancels:e}){return{cancels:e,type:"cancel"}}function wn({cancels:e}){return{cancels:e,type:"cancelByCloid"}}function Un({oid:e,order:n}){return{oid:e,order:n,type:"modify"}}function _n({modifies:e}){return{modifies:e,type:"batchModify"}}function Dn({asset:e,isCross:n,leverage:t}){return{asset:e,isCross:n,leverage:t,type:"updateLeverage"}}function On({asset:e,isBuy:n,ntli:t}){return{asset:e,isBuy:n,ntli:t,type:"updateIsolatedMargin"}}function kn({asset:e,leverage:n}){return{asset:e,leverage:n,type:"topUpIsolatedOnlyMargin"}}function Pn({time:e}){return{time:e,type:"scheduleCancel"}}function vn({amount:e,hyperliquidChain:n,nonce:t,signatureChainId:r,toPerp:i}){return{amount:e,hyperliquidChain:n,nonce:t,signatureChainId:r,toPerp:i,type:"usdClassTransfer"}}function oe({amount:e,destination:n,destinationDex:t,fromSubAccount:r,hyperliquidChain:i,nonce:o,signatureChainId:s,sourceDex:p,token:u}){return{amount:e,destination:n,destinationDex:t,fromSubAccount:r,hyperliquidChain:i,nonce:o,signatureChainId:s,sourceDex:p,token:u,type:"sendAsset"}}function Rn({agentAddress:e,agentName:n,hyperliquidChain:t,nonce:r,signatureChainId:i}){return{agentAddress:e,agentName:n,hyperliquidChain:t,nonce:r,signatureChainId:i,type:"approveAgent"}}function In({builder:e,hyperliquidChain:n,maxFeeRate:t,nonce:r,signatureChainId:i}){return{builder:e,hyperliquidChain:n,maxFeeRate:t,nonce:r,signatureChainId:i,type:"approveBuilderFee"}}function qn({hyperliquidChain:e,isUndelegate:n,nonce:t,signatureChainId:r,validator:i,wei:o}){return{hyperliquidChain:e,isUndelegate:n,nonce:t,signatureChainId:r,type:"tokenDelegate",validator:i,wei:o}}import{SwapKitError as We,SwapKitNumber as Ve}from"@swapkit/helpers";import{HYPERCORE_USDC_TOKEN_ID as B}from"@swapkit/helpers/api";import{SwapKitError as V}from"@swapkit/helpers";import{keccak256 as Ne,Signature as Me}from"ethers";var I="0x0000000000000000000000000000000000000000",D="0xa4b1",q={name:"HyperliquidSignTransaction",verifyingContract:I,version:"1"},Fe={chainId:1337,name:"Exchange",verifyingContract:I,version:"1"},Le={Agent:[{name:"source",type:"string"},{name:"connectionId",type:"bytes32"}]},ae="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"},je=new TextEncoder;function b(...e){let n=e.reduce((i,o)=>i+o.length,0),t=new Uint8Array(n),r=0;for(let i of e)t.set(i,r),r+=i.length;return t}function Ee(e,n,t){if(t<n)return new Uint8Array([e+t]);if(t<=255)return new Uint8Array([e+n,t]);if(t<=65535)return new Uint8Array([e+n+1,t>>8,t&255]);return new Uint8Array([e+n+2,t>>>24&255,t>>>16&255,t>>>8&255,t&255])}function v(e,n){let t=new Uint8Array(n),r=e;for(let i=n-1;i>=0;i-=1)t[i]=Number(r&0xffn),r>>=8n;return t}function se(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 pe(e){let n=je.encode(e);if(n.length<32)return b(new Uint8Array([160+n.length]),n);return b(Ee(217,0,n.length),n)}function Je(e){let n=e.map((r)=>Y(r)),t=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(t,...n)}function ze(e){let n=Object.entries(e).filter(([,r])=>typeof r<"u"),t=n.length<16?new Uint8Array([128+n.length]):n.length<=65535?new Uint8Array([222,n.length>>8,n.length&255]):new Uint8Array([223,n.length>>>24&255,n.length>>>16&255,n.length>>>8&255,n.length&255]);return b(t,...n.flatMap(([r,i])=>[pe(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 pe(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 se(BigInt(e))}if(typeof e==="bigint")return se(e);if(e instanceof Uint8Array){let n=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(n,e)}if(Array.isArray(e))return Je(e);if(typeof e==="object")return ze(e);throw new V("helpers_invalid_params",{message:`Unsupported Hyperliquid msgpack value: ${String(e)}`})}function Ke(e){let n=e.startsWith("0x")?e.slice(2):e;if(n.length%2!==0||/[^a-fA-F0-9]/u.test(n))throw new V("helpers_invalid_params",{hexValue:e});let t=new Uint8Array(n.length/2);for(let r=0;r<n.length;r+=2)t[r/2]=Number.parseInt(n.slice(r,r+2),16);return t}function ce(e){return{domain:Fe,message:{connectionId:e,source:"a"},primaryType:"Agent",types:{Agent:[...Le.Agent]}}}function de(e){let n=G[e.type],t=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||ae},primaryType:n,types:{[n]:t}}}function ye(e){let n=Me.from(e);return{r:n.r,s:n.s,v:n.v}}function ue(e,n,{expiresAfter:t,vaultAddress:r}={}){let i=Y(e),o=v(BigInt(n),8),s=r?b(new Uint8Array([1]),Ke(r.toLowerCase())):new Uint8Array([0]),p=typeof t==="number"?b(new Uint8Array([0]),v(BigInt(t),8)):new Uint8Array;return Ne(b(i,o,s,p))}function le(e){let n=e.hyperliquidChain||ae;switch(e.type){case"approveAgent":return{...e,agentAddress:e.agentAddress.toLowerCase(),hyperliquidChain:n};case"approveBuilderFee":return{...e,builder:e.builder.toLowerCase(),hyperliquidChain:n};case"sendAsset":return{...e,destination:e.destination.toLowerCase(),fromSubAccount:e.fromSubAccount.toLowerCase(),hyperliquidChain:n};case"tokenDelegate":return{...e,hyperliquidChain:n,validator:e.validator.toLowerCase()};case"usdClassTransfer":return{...e,hyperliquidChain:n};default:return e}}var ge=Number.parseInt(D,16),Qe=new Set(["chainId","name","verifyingContract","version"]),fe=/^0x[0-9a-fA-F]{40}$/,X=Q.sendAsset;var c=(e)=>{throw new We("toolbox_hypercore_payload_mismatch",{problems:[e]})};function me(e){try{return new URL(e)}catch{return}}function Ce({action:e,allowedEndpoints:n,expectedAmount:t,expectedDestination:r,expectedFromSubAccount:i,expectedSourceDex:o,expectedToken:s,submitTo:p,typedData:u}){let{domain:f,message:T,primaryType:m,types:H}=u,a=G.sendAsset;if(m!==a)c(`primaryType is ${JSON.stringify(m)}, expected "${a}"`);if(e.type!=="sendAsset")c(`action.type is ${JSON.stringify(e.type)}, expected "sendAsset"`);let y=X.map(({name:d})=>d),C=new Set([...y,"signatureChainId","type"]),x=Object.keys(e).filter((d)=>!C.has(d));if(x.length)c(`action carries unexpected keys: ${x.join(", ")}`);for(let{name:d}of X)if(T[d]!==e[d])c(`${d}: signed ${JSON.stringify(T[d])} != submitted ${JSON.stringify(e[d])}`);let A=Object.keys(T),l=A.filter((d)=>!y.includes(d)),S=y.filter((d)=>!A.includes(d));if(l.length||S.length){let d=[l.length?`declares undeclared keys [${l.join(",")}]`:"",S.length?`is missing keys [${S.join(",")}]`:""].filter(Boolean).join(" / ");c(`message ${d}`)}let _=X.map(({name:d,type:W})=>`${d}:${W}`).join(","),w=(H[a]??[]).map(({name:d,type:W})=>`${d}:${W}`).join(",");if(w!==_)c(`types.${a} is [${w}], expected [${_}]`);let R=Object.keys(H).filter((d)=>d!==a&&d!=="EIP712Domain");if(R.length)c(`types carries unexpected entries: ${R.join(", ")}`);if(Number(f.chainId)!==ge)c(`domain.chainId is ${f.chainId}, expected ${ge} (Arbitrum)`);if(f.name!==q.name)c(`domain.name is ${JSON.stringify(f.name)}, expected "${q.name}"`);if(f.version!==q.version)c(`domain.version is ${JSON.stringify(f.version)}, expected "${q.version}"`);if(f.verifyingContract!==I)c(`domain.verifyingContract is ${f.verifyingContract}, expected the zero address`);let P=Object.keys(f).filter((d)=>!Qe.has(d));if(P.length)c(`domain carries unexpected keys: ${P.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(e.destinationDex!=="")c(`action.destinationDex is ${JSON.stringify(e.destinationDex)}, expected ""`);if(s!==B)c(`route sell token is ${JSON.stringify(s)}, expected "${B}"`);if(e.token!==s)c(`action.token is ${JSON.stringify(e.token)}, expected route sell token "${s}"`);if(e.sourceDex!==""&&e.sourceDex!=="spot")c(`action.sourceDex is ${JSON.stringify(e.sourceDex)}, expected "" or "spot"`);if(typeof e.sourceDex!=="string"||e.sourceDex!==o)c(`action.sourceDex is ${JSON.stringify(e.sourceDex)}, expected route sourceDex ${JSON.stringify(o)}`);let L=e.fromSubAccount;if(typeof L!=="string"||typeof i!=="string"||L.toLowerCase()!==i.toLowerCase())c(`action.fromSubAccount is ${JSON.stringify(e.fromSubAccount)}, expected ${JSON.stringify(i)}`);if(i&&!fe.test(i))c(`expectedFromSubAccount ${JSON.stringify(i)} is not a well-formed 0x address`);if(!t)c("expectedAmount is missing — cannot verify action.amount");let j=!1;try{j=new Ve(String(e.amount)).eqValue(t)}catch{c(`action.amount ${JSON.stringify(e.amount)} is not comparable to ${t}`)}if(!j)c(`action.amount ${JSON.stringify(e.amount)} != route sell amount ${t}`);let z=typeof e.destination==="string"?e.destination:"";if(!fe.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 re=me(p),K=re?.origin,ie=n.flatMap((d)=>me(d)?.origin??[]);if(re?.protocol!=="https:")c(`submitTo ${JSON.stringify(p)} must be an https URL`);if(!K||!ie.includes(K))c(`submitTo origin ${K} is not one of the allowed exchange origins [${ie.join(", ")}]`)}import{AssetValue as M,Chain as Ge,derivationPathToString as Ye,getChainConfig as Ue,getRPCUrl as Xe,NetworkDerivationPath as Ze,RequestClient as N,SwapKitError as g,SwapKitNumber as O,updateDerivationPath as en}from"@swapkit/helpers";import{SwapKitApi as nn}from"@swapkit/helpers/api";import{HDNodeWallet as tn}from"ethers";import{match as rn,P as Z}from"ts-pattern";var U=Ge.Hype,{baseDecimal:ee,rpcUrls:Ae}=Ue(U),on=Ae[0]?`${Ae[0]}/exchange`:void 0,sn={HYPE:ee,USDC:6,USDT:6},_e="Mainnet",an=/^\d+(?:\.\d+)?$/,pn=/^[^:]+:0x[0-9a-fA-F]+$/,cn={spotSend:[{name:"hyperliquidChain",type:"string"},{name:"destination",type:"string"},{name:"token",type:"string"},{name:"amount",type:"string"},{name:"time",type:"uint64"}]},dn={spotSend:"HyperliquidTransaction:SpotSend"};function h(e,n){if(!$e(e))throw new g(n,{address:e});return e.toLowerCase()}function F(e){if(e===void 0)return;try{return new O(e)}catch{return}}var De={retry:{maxRetries:0},timeoutMs:5000};async function k({requestOptions:e,...n}){let t=await E();return N.post(`${t}/info`,{json:n,...e})}function ne({dex:e,user:n}){return k({...e?{dex:e}:{},type:"clearinghouseState",user:h(n,"helpers_invalid_params")})}function Oe({user:e}){return k({type:"spotClearinghouseState",user:h(e,"helpers_invalid_params")})}function yn({destination:e,sender:n}){let t=h(n,"helpers_invalid_params"),r=h(e,"helpers_invalid_params");return k({requestOptions:De,source:t,type:"preTransferCheck",user:r})}function un({dex:e,user:n}){return k({...e?{dex:e}:{},type:"openOrders",user:h(n,"helpers_invalid_params")})}function ln({dex:e,user:n}){return k({...e?{dex:e}:{},type:"frontendOpenOrders",user:h(n,"helpers_invalid_params")})}function gn({oidOrCloid:e,user:n}){return k({oid:e,type:"orderStatus",user:h(n,"helpers_invalid_params")})}function fn({aggregateByTime:e,user:n}){return k({...typeof e==="boolean"?{aggregateByTime:e}:{},type:"userFills",user:h(n,"helpers_invalid_params")})}function mn({aggregateByTime:e,endTime:n,startTime:t,user:r}){return k({...typeof e==="boolean"?{aggregateByTime:e}:{},...typeof n==="number"?{endTime:n}:{},startTime:t,type:"userFillsByTime",user:h(r,"helpers_invalid_params")})}function he({coin:e,token:n,value:t,spotMeta:r}){if(!t||Number(t)<=0)return null;let i=e?.toUpperCase()||`TOKEN-${n||"UNKNOWN"}`,o=r?.tokens?.find((u)=>u.name===e||n!==void 0&&u.index===Number(n)),s=o?.weiDecimals??sn[i]??ee,p=o?`${U}.${i}-${o.name}:${o.tokenId}`:`${U}.${i}`;return new M({decimal:s,identifier:p,value:t})}function Cn(e){let n=new Map;for(let t of e){let r=t.toString({includeSynthProtocol:!0}),i=n.get(r);n.set(r,i?i.add(t):t)}if(![...n.values()].some((t)=>t.isGasAsset||t.ticker==="HYPE")){let t=M.from({chain:U,value:0});n.set(t.toString({includeSynthProtocol:!0}),t)}return[...n.values()]}async function E(){try{return await Xe(U)}catch{let[e]=Ue(U).rpcUrls;if(!e)throw new g("helpers_chain_no_public_or_set_rpc_url",{chain:U});return e}}async function J(){return`${await E()}/exchange`}function An(e){let n=dn[e.type],{type:t,...r}=e;return{domain:{chainId:Number.parseInt(e.signatureChainId,16),name:"HyperliquidSignTransaction",verifyingContract:I,version:"1"},message:r,primaryType:n,types:{[n]:cn[t]}}}async function hn({action:e,expiresAfter:n,nonce:t,vaultAddress:r}){let i=t||Date.now(),o=r?h(r,"helpers_invalid_params"):void 0,s=await J(),p=ue(e,i,{expiresAfter:n,vaultAddress:o});return{action:e,endpoint:s,expiresAfter:n,nonce:i,typedData:ce(p),vaultAddress:o}}async function ke({action:e,endpoint:n,nonce:t,signatureChainId:r}){let i=t||e.nonce||Date.now(),o=r||e.signatureChainId||D,s=le({...e,nonce:i,signatureChainId:o});return{action:s,endpoint:n??await J(),nonce:i,typedData:de(s)}}async function te({token:e,user:n}){let t=await Oe({user:n}),i=(t.spotState?.balances||t.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 Pe({assetValue:e,sender:n,token:t}){let r=(await te({token:t,user:n}))?.getValue("string");if(!r||Number(r)<=0)throw new g("toolbox_sweep_amount_too_low",{asset:e.toString(),balance:r||"0"});return r}async function Hn(e){if(e.address&&pn.test(e.address))return e.address;let t=(await k({type:"spotMeta"}))?.tokens?.find(({name:r})=>r?.toUpperCase()===e.ticker.toUpperCase());if(t)return`${t.name}:${t.tokenId}`;throw new g("helpers_invalid_params",{asset:e.toString(),message:"Unable to resolve the HyperCore spot token id"})}async function ve({destination:e,sender:n}){let t;try{t=await yn({destination:e,sender:n})}catch(o){throw new g("toolbox_hypercore_pre_transfer_check_failed",o)}if(typeof t?.isSanctioned!=="boolean"||typeof t.userExists!=="boolean")throw new g("toolbox_hypercore_pre_transfer_check_failed",{response:t});let{fee:r}=t,i=typeof r==="string"&&an.test(r)?Number(r):Number.NaN;if(!Number.isFinite(i))throw new g("toolbox_hypercore_pre_transfer_check_failed",{response:t});if(t.isSanctioned)throw new g("toolbox_hypercore_destination_sanctioned",{destination:e,sender:n});return i}function Re(e){return e.toUpperCase().startsWith("USDC:")}async function Ie({activationFee:e,token:n,user:t}){if(e<=0)return;let[r,i]=await Promise.all([ne({user:t}),te({token:B,user:t})]),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 g("toolbox_hypercore_insufficient_balance",{activationFee:e,feeToken:B,perpsWithdrawable:o.getValue("string"),spotAvailable:s.getValue("string"),token:n})}async function qe({activationFee:e,amount:n,sourceDex:t,token:r,user:i}){let o=Re(r),s=o?new O(n).add(e):new O(n);if(t!==void 0&&t!==""&&t!=="spot")throw new g("helpers_invalid_params",{message:"Unsupported HyperCore sourceDex",sourceDex:t});if(!o&&t==="")throw new g("helpers_invalid_params",{message:"Only a collateral token can be sent from a perp DEX",sourceDex:t,token:r});let p="0";if(o&&t!=="spot"){if(p=(await ne({user:i})).withdrawable||"0",s.lte(F(p)??0))return"";if(t==="")throw new g("toolbox_hypercore_insufficient_balance",{amountRequired:s.getValue("string"),perpsWithdrawable:p,spotAvailable:"0",token:r})}let u=await te({token:r,user:i})??new O(0);if(u.gte(s)){if(!o)await Ie({activationFee:e,token:r,user:i});return"spot"}throw new g("toolbox_hypercore_insufficient_balance",{amountRequired:s.getValue("string"),perpsWithdrawable:p,spotAvailable:u.getValue("string"),token:r})}async function xn({amount:e,destination:n,sender:t,sourceDex:r,sweep:i,token:o}){if(i&&r!==void 0&&r!=="spot")throw new g("helpers_invalid_params",{message:"HyperCore sweep drains spot and requires sourceDex spot",sourceDex:r});let s=await ve({destination:n,sender:t});if(!i){let u=await qe({activationFee:s,amount:e,sourceDex:r,token:o,user:t});return{amount:e,sourceDex:u}}if(!Re(o))return await Ie({activationFee:s,token:o,user:t}),{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 g("toolbox_hypercore_insufficient_balance",{activationFee:s,spotAvailable:e,token:o});return{amount:p.getValue("string"),sourceDex:"spot"}}async function bn({assetValue:e,recipient:n,sender:t,signatureChainId:r,sweep:i,time:o,endpoint:s}){let p=h(n,"core_transaction_invalid_recipient_address"),u=h(t,"core_transaction_invalid_sender_address"),f=e.address;if(!f)throw new g("helpers_invalid_params",{asset:e.toString(),from:u});let T=i?await Pe({assetValue:e,sender:u,token:f}):e.getValue("string"),m=s??await J(),H=o||Date.now(),a={amount:T,destination:p,hyperliquidChain:_e,signatureChainId:r||D,time:H,token:f,type:"spotSend"};return{action:a,endpoint:m,nonce:H,typedData:An(a)}}async function He({assetValue:e,destinationDex:n,endpoint:t,fromSubAccount:r,recipient:i,sender:o,signatureChainId:s,sourceDex:p,sweep:u,time:f}){let T=h(i,"core_transaction_invalid_recipient_address"),m=h(o,"core_transaction_invalid_sender_address"),H=r?h(r,"helpers_invalid_params"):"",a=H||m,y=await Hn(e),C=u?await Pe({assetValue:e,sender:a,token:y}):e.getValue("string"),{amount:x,sourceDex:A}=await xn({amount:C,destination:T,sender:a,sourceDex:p,sweep:u,token:y}),l=oe({amount:x,destination:T,destinationDex:n??"spot",fromSubAccount:H,hyperliquidChain:_e,nonce:f||Date.now(),signatureChainId:s||D,sourceDex:A,token:y});return ke({action:l,endpoint:t})}async function Be(e){let n=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(n?.status!=="ok")throw new g("core_transaction_failed",{definitive:n?.status==="err",response:n});return n}async function xe({amount:e,destination:n,nonce:t,token:r,user:i}){let o=h(i,"helpers_invalid_params"),s=await E(),p=t-5000,u=n?.toLowerCase(),f=r?.toUpperCase(),T=({delta:m,time:H})=>{if(!(H&&H>=p&&m?.type==="send"&&m.nonce===t))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(f!==void 0){if(!m?.token)return!1;let y=m.token.toUpperCase();if(y!==f&&!f.startsWith(`${y}:`))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},...De}),a=Array.isArray(H)?H.find(T):void 0;if(a?.hash)return a.hash}catch{}}return""}async function be({kind:e,lookup:n,signed:t}){try{await Be(t)}catch(i){if(i instanceof g&&i.errorKey==="core_transaction_failed"&&i.cause?.definitive===!0)throw i;let s=await xe(n);if(s)return s;throw new g("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:n.nonce,transportError:String(i)})}let r=await xe(n);if(!r)throw new g("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:n.nonce});return r}function Se({action:e,nonce:n,user:t}){return{amount:e.amount,destination:e.destination,nonce:n,token:e.token,user:t}}function $e(e){return e.startsWith("0x")&&we(e)}function Xn(e){let n=e&&"index"in e?e.index||0:0,t=Ye(e&&"derivationPath"in e&&e.derivationPath?e.derivationPath:en(Ze[U],{index:n})),r,i=!1;function o(){if(i)return r;return r=rn(e).with({phrase:Z.string},({phrase:a})=>tn.fromPhrase(a,void 0,t)).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 y=o();if(!y)throw new g("toolbox_hypercore_no_signer");let C=Te(a.typedData),x=await y.signTypedData(C.domain,C.types,C.message);return{action:a.action,endpoint:a.endpoint,nonce:a.nonce,signature:ye(x),..."expiresAfter"in a?{expiresAfter:a.expiresAfter}:{},..."vaultAddress"in a?{vaultAddress:a.vaultAddress}:{}}}async function u(a){let y=h(a,"helpers_invalid_params"),C=await E(),[x,A,l]=await Promise.all([N.post(`${C}/info`,{json:{type:"spotClearinghouseState",user:y}}),N.post(`${C}/info`,{json:{type:"clearinghouseState",user:y}}),N.post(`${C}/info`,{json:{type:"spotMeta"}})]),S=(x.spotState?.balances||x.balances||[]).map(({coin:w,token:R,total:P})=>he({coin:w,spotMeta:l,token:R,value:P})).filter((w)=>!!w),_=he({coin:"USDC",spotMeta:l,value:A.withdrawable||A.marginSummary?.accountValue||A.marginSummary?.totalRawUsd});return Cn(_?[...S,_]:S)}async function f(a,y=!0){let C=h(a,"helpers_invalid_params");try{let x=await nn.getChainBalance({address:C,chain:U,scamFilter:y});if(x.length){let A=x.map(({identifier:S,value:_,decimal:w})=>new M({decimal:w||ee,identifier:S,value:_}));return A.some((S)=>S.isGasAsset)?A:[M.from({chain:U}),...A]}}catch{}return u(C)}async function T({sweep:a,...y}){let C=o();if(!C)throw new g("toolbox_hypercore_no_signer");let x=y.sender||await C.getAddress(),A=await He({...y,feeRate:0,sender:x,sweep:a}),l=await p(A);return be({kind:"transfer",lookup:Se({action:A.action,nonce:A.nonce,user:A.action.fromSubAccount||x}),signed:l})}async function m(a){let y=o();if(!y)throw new g("toolbox_hypercore_no_signer");let{action:C,typedData:x,...A}=a,l=structuredClone(C),S=structuredClone(x),_=await y.getAddress(),w=await J(),R=[...new Set([w,on??w])];Ce({...A,action:l,allowedEndpoints:R,typedData:S});let P=l.fromSubAccount?h(l.fromSubAccount,"helpers_invalid_params"):_,L=await ve({destination:l.destination,sender:P});await qe({activationFee:L,amount:l.amount,sourceDex:l.sourceDex,token:l.token,user:P});let j=await p({action:l,endpoint:w,nonce:l.nonce,typedData:S});return be({kind:"payin",lookup:Se({action:l,nonce:l.nonce,user:P}),signed:j})}function H(){return M.from({chain:U,value:0})}return{broadcastTransaction:Be,createL1ActionRequest:hn,createSendAssetTransaction:He,createTransaction:bn,createUserSignedActionRequest:ke,estimateTransactionFee:H,getAddress:s,getBalance:f,getBalanceFromChain:u,getState:{clearinghouse:ne,frontendOpenOrders:ln,openOrders:un,orderStatus:gn,spotClearinghouse:Oe,userFills:fn,userFillsByTime:mn},signAndBroadcastSendAsset:m,signTransaction:p,transfer:T,validateAddress:$e}}export{B as HYPERCORE_USDC_TOKEN_ID,Rn as buildApproveAgentAction,In as buildApproveBuilderFeeAction,_n as buildBatchModifyAction,Tn as buildCancelAction,wn as buildCancelByCloidAction,Un as buildModifyAction,Sn as buildOrderAction,Pn as buildScheduleCancelAction,oe as buildSendAssetAction,qn as buildTokenDelegateAction,kn as buildTopUpIsolatedOnlyMarginAction,On as buildUpdateIsolatedMarginAction,Dn as buildUpdateLeverageAction,vn as buildUsdClassTransferAction,hn as createL1ActionRequest,He as createSendAssetTransaction,bn as createTransaction,ke as createUserSignedActionRequest,Xn as getHyperCoreToolbox,$e as validateHyperCoreAddress};
1
+ import"../../chunk-qsbf0z90.js";import{m as Te,r as we}from"../../chunk-2q4pxsyg.js";import"../../chunk-qk8kg62t.js";import"../../chunk-pz8xe0qj.js";function Sn({builder:e,grouping:n="na",orders:t}){return{builder:e,grouping:n,orders:t,type:"order"}}function Tn({cancels:e}){return{cancels:e,type:"cancel"}}function wn({cancels:e}){return{cancels:e,type:"cancelByCloid"}}function Un({oid:e,order:n}){return{oid:e,order:n,type:"modify"}}function _n({modifies:e}){return{modifies:e,type:"batchModify"}}function Dn({asset:e,isCross:n,leverage:t}){return{asset:e,isCross:n,leverage:t,type:"updateLeverage"}}function On({asset:e,isBuy:n,ntli:t}){return{asset:e,isBuy:n,ntli:t,type:"updateIsolatedMargin"}}function kn({asset:e,leverage:n}){return{asset:e,leverage:n,type:"topUpIsolatedOnlyMargin"}}function Pn({time:e}){return{time:e,type:"scheduleCancel"}}function vn({amount:e,hyperliquidChain:n,nonce:t,signatureChainId:r,toPerp:i}){return{amount:e,hyperliquidChain:n,nonce:t,signatureChainId:r,toPerp:i,type:"usdClassTransfer"}}function oe({amount:e,destination:n,destinationDex:t,fromSubAccount:r,hyperliquidChain:i,nonce:o,signatureChainId:s,sourceDex:p,token:u}){return{amount:e,destination:n,destinationDex:t,fromSubAccount:r,hyperliquidChain:i,nonce:o,signatureChainId:s,sourceDex:p,token:u,type:"sendAsset"}}function Rn({agentAddress:e,agentName:n,hyperliquidChain:t,nonce:r,signatureChainId:i}){return{agentAddress:e,agentName:n,hyperliquidChain:t,nonce:r,signatureChainId:i,type:"approveAgent"}}function In({builder:e,hyperliquidChain:n,maxFeeRate:t,nonce:r,signatureChainId:i}){return{builder:e,hyperliquidChain:n,maxFeeRate:t,nonce:r,signatureChainId:i,type:"approveBuilderFee"}}function qn({hyperliquidChain:e,isUndelegate:n,nonce:t,signatureChainId:r,validator:i,wei:o}){return{hyperliquidChain:e,isUndelegate:n,nonce:t,signatureChainId:r,type:"tokenDelegate",validator:i,wei:o}}import{SwapKitError as We,SwapKitNumber as Ve}from"@swapkit/helpers";import{HYPERCORE_USDC_TOKEN_ID as B}from"@swapkit/helpers/api";import{SwapKitError as V}from"@swapkit/helpers";import{keccak256 as Ne,Signature as Me}from"ethers";var I="0x0000000000000000000000000000000000000000",D="0xa4b1",q={name:"HyperliquidSignTransaction",verifyingContract:I,version:"1"},Fe={chainId:1337,name:"Exchange",verifyingContract:I,version:"1"},Le={Agent:[{name:"source",type:"string"},{name:"connectionId",type:"bytes32"}]},ae="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"},je=new TextEncoder;function b(...e){let n=e.reduce((i,o)=>i+o.length,0),t=new Uint8Array(n),r=0;for(let i of e)t.set(i,r),r+=i.length;return t}function Ee(e,n,t){if(t<n)return new Uint8Array([e+t]);if(t<=255)return new Uint8Array([e+n,t]);if(t<=65535)return new Uint8Array([e+n+1,t>>8,t&255]);return new Uint8Array([e+n+2,t>>>24&255,t>>>16&255,t>>>8&255,t&255])}function v(e,n){let t=new Uint8Array(n),r=e;for(let i=n-1;i>=0;i-=1)t[i]=Number(r&0xffn),r>>=8n;return t}function se(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 pe(e){let n=je.encode(e);if(n.length<32)return b(new Uint8Array([160+n.length]),n);return b(Ee(217,0,n.length),n)}function Je(e){let n=e.map((r)=>Y(r)),t=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(t,...n)}function ze(e){let n=Object.entries(e).filter(([,r])=>typeof r<"u"),t=n.length<16?new Uint8Array([128+n.length]):n.length<=65535?new Uint8Array([222,n.length>>8,n.length&255]):new Uint8Array([223,n.length>>>24&255,n.length>>>16&255,n.length>>>8&255,n.length&255]);return b(t,...n.flatMap(([r,i])=>[pe(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 pe(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 se(BigInt(e))}if(typeof e==="bigint")return se(e);if(e instanceof Uint8Array){let n=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(n,e)}if(Array.isArray(e))return Je(e);if(typeof e==="object")return ze(e);throw new V("helpers_invalid_params",{message:`Unsupported Hyperliquid msgpack value: ${String(e)}`})}function Ke(e){let n=e.startsWith("0x")?e.slice(2):e;if(n.length%2!==0||/[^a-fA-F0-9]/u.test(n))throw new V("helpers_invalid_params",{hexValue:e});let t=new Uint8Array(n.length/2);for(let r=0;r<n.length;r+=2)t[r/2]=Number.parseInt(n.slice(r,r+2),16);return t}function ce(e){return{domain:Fe,message:{connectionId:e,source:"a"},primaryType:"Agent",types:{Agent:[...Le.Agent]}}}function de(e){let n=G[e.type],t=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||ae},primaryType:n,types:{[n]:t}}}function ye(e){let n=Me.from(e);return{r:n.r,s:n.s,v:n.v}}function ue(e,n,{expiresAfter:t,vaultAddress:r}={}){let i=Y(e),o=v(BigInt(n),8),s=r?b(new Uint8Array([1]),Ke(r.toLowerCase())):new Uint8Array([0]),p=typeof t==="number"?b(new Uint8Array([0]),v(BigInt(t),8)):new Uint8Array;return Ne(b(i,o,s,p))}function le(e){let n=e.hyperliquidChain||ae;switch(e.type){case"approveAgent":return{...e,agentAddress:e.agentAddress.toLowerCase(),hyperliquidChain:n};case"approveBuilderFee":return{...e,builder:e.builder.toLowerCase(),hyperliquidChain:n};case"sendAsset":return{...e,destination:e.destination.toLowerCase(),fromSubAccount:e.fromSubAccount.toLowerCase(),hyperliquidChain:n};case"tokenDelegate":return{...e,hyperliquidChain:n,validator:e.validator.toLowerCase()};case"usdClassTransfer":return{...e,hyperliquidChain:n};default:return e}}var ge=Number.parseInt(D,16),Qe=new Set(["chainId","name","verifyingContract","version"]),fe=/^0x[0-9a-fA-F]{40}$/,X=Q.sendAsset;var c=(e)=>{throw new We("toolbox_hypercore_payload_mismatch",{problems:[e]})};function me(e){try{return new URL(e)}catch{return}}function Ce({action:e,allowedEndpoints:n,expectedAmount:t,expectedDestination:r,expectedFromSubAccount:i,expectedSourceDex:o,expectedToken:s,submitTo:p,typedData:u}){let{domain:f,message:T,primaryType:m,types:H}=u,a=G.sendAsset;if(m!==a)c(`primaryType is ${JSON.stringify(m)}, expected "${a}"`);if(e.type!=="sendAsset")c(`action.type is ${JSON.stringify(e.type)}, expected "sendAsset"`);let y=X.map(({name:d})=>d),C=new Set([...y,"signatureChainId","type"]),x=Object.keys(e).filter((d)=>!C.has(d));if(x.length)c(`action carries unexpected keys: ${x.join(", ")}`);for(let{name:d}of X)if(T[d]!==e[d])c(`${d}: signed ${JSON.stringify(T[d])} != submitted ${JSON.stringify(e[d])}`);let A=Object.keys(T),l=A.filter((d)=>!y.includes(d)),S=y.filter((d)=>!A.includes(d));if(l.length||S.length){let d=[l.length?`declares undeclared keys [${l.join(",")}]`:"",S.length?`is missing keys [${S.join(",")}]`:""].filter(Boolean).join(" / ");c(`message ${d}`)}let _=X.map(({name:d,type:W})=>`${d}:${W}`).join(","),w=(H[a]??[]).map(({name:d,type:W})=>`${d}:${W}`).join(",");if(w!==_)c(`types.${a} is [${w}], expected [${_}]`);let R=Object.keys(H).filter((d)=>d!==a&&d!=="EIP712Domain");if(R.length)c(`types carries unexpected entries: ${R.join(", ")}`);if(Number(f.chainId)!==ge)c(`domain.chainId is ${f.chainId}, expected ${ge} (Arbitrum)`);if(f.name!==q.name)c(`domain.name is ${JSON.stringify(f.name)}, expected "${q.name}"`);if(f.version!==q.version)c(`domain.version is ${JSON.stringify(f.version)}, expected "${q.version}"`);if(f.verifyingContract!==I)c(`domain.verifyingContract is ${f.verifyingContract}, expected the zero address`);let P=Object.keys(f).filter((d)=>!Qe.has(d));if(P.length)c(`domain carries unexpected keys: ${P.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(e.destinationDex!=="")c(`action.destinationDex is ${JSON.stringify(e.destinationDex)}, expected ""`);if(s!==B)c(`route sell token is ${JSON.stringify(s)}, expected "${B}"`);if(e.token!==s)c(`action.token is ${JSON.stringify(e.token)}, expected route sell token "${s}"`);if(e.sourceDex!==""&&e.sourceDex!=="spot")c(`action.sourceDex is ${JSON.stringify(e.sourceDex)}, expected "" or "spot"`);if(typeof e.sourceDex!=="string"||e.sourceDex!==o)c(`action.sourceDex is ${JSON.stringify(e.sourceDex)}, expected route sourceDex ${JSON.stringify(o)}`);let L=e.fromSubAccount;if(typeof L!=="string"||typeof i!=="string"||L.toLowerCase()!==i.toLowerCase())c(`action.fromSubAccount is ${JSON.stringify(e.fromSubAccount)}, expected ${JSON.stringify(i)}`);if(i&&!fe.test(i))c(`expectedFromSubAccount ${JSON.stringify(i)} is not a well-formed 0x address`);if(!t)c("expectedAmount is missing — cannot verify action.amount");let j=!1;try{j=new Ve(String(e.amount)).eqValue(t)}catch{c(`action.amount ${JSON.stringify(e.amount)} is not comparable to ${t}`)}if(!j)c(`action.amount ${JSON.stringify(e.amount)} != route sell amount ${t}`);let z=typeof e.destination==="string"?e.destination:"";if(!fe.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 re=me(p),K=re?.origin,ie=n.flatMap((d)=>me(d)?.origin??[]);if(re?.protocol!=="https:")c(`submitTo ${JSON.stringify(p)} must be an https URL`);if(!K||!ie.includes(K))c(`submitTo origin ${K} is not one of the allowed exchange origins [${ie.join(", ")}]`)}import{AssetValue as M,Chain as Ge,derivationPathToString as Ye,getChainConfig as Ue,getRPCUrl as Xe,NetworkDerivationPath as Ze,RequestClient as N,SwapKitError as g,SwapKitNumber as O,updateDerivationPath as en}from"@swapkit/helpers";import{SwapKitApi as nn}from"@swapkit/helpers/api";import{HDNodeWallet as tn}from"ethers";import{match as rn,P as Z}from"ts-pattern";var U=Ge.Hype,{baseDecimal:ee,rpcUrls:Ae}=Ue(U),on=Ae[0]?`${Ae[0]}/exchange`:void 0,sn={HYPE:ee,USDC:6,USDT:6},_e="Mainnet",an=/^\d+(?:\.\d+)?$/,pn=/^[^:]+:0x[0-9a-fA-F]+$/,cn={spotSend:[{name:"hyperliquidChain",type:"string"},{name:"destination",type:"string"},{name:"token",type:"string"},{name:"amount",type:"string"},{name:"time",type:"uint64"}]},dn={spotSend:"HyperliquidTransaction:SpotSend"};function h(e,n){if(!$e(e))throw new g(n,{address:e});return e.toLowerCase()}function F(e){if(e===void 0)return;try{return new O(e)}catch{return}}var De={retry:{maxRetries:0},timeoutMs:5000};async function k({requestOptions:e,...n}){let t=await E();return N.post(`${t}/info`,{json:n,...e})}function ne({dex:e,user:n}){return k({...e?{dex:e}:{},type:"clearinghouseState",user:h(n,"helpers_invalid_params")})}function Oe({user:e}){return k({type:"spotClearinghouseState",user:h(e,"helpers_invalid_params")})}function yn({destination:e,sender:n}){let t=h(n,"helpers_invalid_params"),r=h(e,"helpers_invalid_params");return k({requestOptions:De,source:t,type:"preTransferCheck",user:r})}function un({dex:e,user:n}){return k({...e?{dex:e}:{},type:"openOrders",user:h(n,"helpers_invalid_params")})}function ln({dex:e,user:n}){return k({...e?{dex:e}:{},type:"frontendOpenOrders",user:h(n,"helpers_invalid_params")})}function gn({oidOrCloid:e,user:n}){return k({oid:e,type:"orderStatus",user:h(n,"helpers_invalid_params")})}function fn({aggregateByTime:e,user:n}){return k({...typeof e==="boolean"?{aggregateByTime:e}:{},type:"userFills",user:h(n,"helpers_invalid_params")})}function mn({aggregateByTime:e,endTime:n,startTime:t,user:r}){return k({...typeof e==="boolean"?{aggregateByTime:e}:{},...typeof n==="number"?{endTime:n}:{},startTime:t,type:"userFillsByTime",user:h(r,"helpers_invalid_params")})}function he({coin:e,token:n,value:t,spotMeta:r}){if(!t||Number(t)<=0)return null;let i=e?.toUpperCase()||`TOKEN-${n||"UNKNOWN"}`,o=r?.tokens?.find((u)=>u.name===e||n!==void 0&&u.index===Number(n)),s=o?.weiDecimals??sn[i]??ee,p=o?`${U}.${i}-${o.name}:${o.tokenId}`:`${U}.${i}`;return new M({decimal:s,identifier:p,value:t})}function Cn(e){let n=new Map;for(let t of e){let r=t.toString({includeSynthProtocol:!0}),i=n.get(r);n.set(r,i?i.add(t):t)}if(![...n.values()].some((t)=>t.isGasAsset||t.ticker==="HYPE")){let t=M.from({chain:U,value:0});n.set(t.toString({includeSynthProtocol:!0}),t)}return[...n.values()]}async function E(){try{return await Xe(U)}catch{let[e]=Ue(U).rpcUrls;if(!e)throw new g("helpers_chain_no_public_or_set_rpc_url",{chain:U});return e}}async function J(){return`${await E()}/exchange`}function An(e){let n=dn[e.type],{type:t,...r}=e;return{domain:{chainId:Number.parseInt(e.signatureChainId,16),name:"HyperliquidSignTransaction",verifyingContract:I,version:"1"},message:r,primaryType:n,types:{[n]:cn[t]}}}async function hn({action:e,expiresAfter:n,nonce:t,vaultAddress:r}){let i=t||Date.now(),o=r?h(r,"helpers_invalid_params"):void 0,s=await J(),p=ue(e,i,{expiresAfter:n,vaultAddress:o});return{action:e,endpoint:s,expiresAfter:n,nonce:i,typedData:ce(p),vaultAddress:o}}async function ke({action:e,endpoint:n,nonce:t,signatureChainId:r}){let i=t||e.nonce||Date.now(),o=r||e.signatureChainId||D,s=le({...e,nonce:i,signatureChainId:o});return{action:s,endpoint:n??await J(),nonce:i,typedData:de(s)}}async function te({token:e,user:n}){let t=await Oe({user:n}),i=(t.spotState?.balances||t.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 Pe({assetValue:e,sender:n,token:t}){let r=(await te({token:t,user:n}))?.getValue("string");if(!r||Number(r)<=0)throw new g("toolbox_sweep_amount_too_low",{asset:e.toString(),balance:r||"0"});return r}async function Hn(e){if(e.address&&pn.test(e.address))return e.address;let t=(await k({type:"spotMeta"}))?.tokens?.find(({name:r})=>r?.toUpperCase()===e.ticker.toUpperCase());if(t)return`${t.name}:${t.tokenId}`;throw new g("helpers_invalid_params",{asset:e.toString(),message:"Unable to resolve the HyperCore spot token id"})}async function ve({destination:e,sender:n}){let t;try{t=await yn({destination:e,sender:n})}catch(o){throw new g("toolbox_hypercore_pre_transfer_check_failed",o)}if(typeof t?.isSanctioned!=="boolean"||typeof t.userExists!=="boolean")throw new g("toolbox_hypercore_pre_transfer_check_failed",{response:t});let{fee:r}=t,i=typeof r==="string"&&an.test(r)?Number(r):Number.NaN;if(!Number.isFinite(i))throw new g("toolbox_hypercore_pre_transfer_check_failed",{response:t});if(t.isSanctioned)throw new g("toolbox_hypercore_destination_sanctioned",{destination:e,sender:n});return i}function Re(e){return e.toUpperCase().startsWith("USDC:")}async function Ie({activationFee:e,token:n,user:t}){if(e<=0)return;let[r,i]=await Promise.all([ne({user:t}),te({token:B,user:t})]),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 g("toolbox_hypercore_insufficient_balance",{activationFee:e,feeToken:B,perpsWithdrawable:o.getValue("string"),spotAvailable:s.getValue("string"),token:n})}async function qe({activationFee:e,amount:n,sourceDex:t,token:r,user:i}){let o=Re(r),s=o?new O(n).add(e):new O(n);if(t!==void 0&&t!==""&&t!=="spot")throw new g("helpers_invalid_params",{message:"Unsupported HyperCore sourceDex",sourceDex:t});if(!o&&t==="")throw new g("helpers_invalid_params",{message:"Only a collateral token can be sent from a perp DEX",sourceDex:t,token:r});let p="0";if(o&&t!=="spot"){if(p=(await ne({user:i})).withdrawable||"0",s.lte(F(p)??0))return"";if(t==="")throw new g("toolbox_hypercore_insufficient_balance",{amountRequired:s.getValue("string"),perpsWithdrawable:p,spotAvailable:"0",token:r})}let u=await te({token:r,user:i})??new O(0);if(u.gte(s)){if(!o)await Ie({activationFee:e,token:r,user:i});return"spot"}throw new g("toolbox_hypercore_insufficient_balance",{amountRequired:s.getValue("string"),perpsWithdrawable:p,spotAvailable:u.getValue("string"),token:r})}async function xn({amount:e,destination:n,sender:t,sourceDex:r,sweep:i,token:o}){if(i&&r!==void 0&&r!=="spot")throw new g("helpers_invalid_params",{message:"HyperCore sweep drains spot and requires sourceDex spot",sourceDex:r});let s=await ve({destination:n,sender:t});if(!i){let u=await qe({activationFee:s,amount:e,sourceDex:r,token:o,user:t});return{amount:e,sourceDex:u}}if(!Re(o))return await Ie({activationFee:s,token:o,user:t}),{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 g("toolbox_hypercore_insufficient_balance",{activationFee:s,spotAvailable:e,token:o});return{amount:p.getValue("string"),sourceDex:"spot"}}async function bn({assetValue:e,recipient:n,sender:t,signatureChainId:r,sweep:i,time:o,endpoint:s}){let p=h(n,"core_transaction_invalid_recipient_address"),u=h(t,"core_transaction_invalid_sender_address"),f=e.address;if(!f)throw new g("helpers_invalid_params",{asset:e.toString(),from:u});let T=i?await Pe({assetValue:e,sender:u,token:f}):e.getValue("string"),m=s??await J(),H=o||Date.now(),a={amount:T,destination:p,hyperliquidChain:_e,signatureChainId:r||D,time:H,token:f,type:"spotSend"};return{action:a,endpoint:m,nonce:H,typedData:An(a)}}async function He({assetValue:e,destinationDex:n,endpoint:t,fromSubAccount:r,recipient:i,sender:o,signatureChainId:s,sourceDex:p,sweep:u,time:f}){let T=h(i,"core_transaction_invalid_recipient_address"),m=h(o,"core_transaction_invalid_sender_address"),H=r?h(r,"helpers_invalid_params"):"",a=H||m,y=await Hn(e),C=u?await Pe({assetValue:e,sender:a,token:y}):e.getValue("string"),{amount:x,sourceDex:A}=await xn({amount:C,destination:T,sender:a,sourceDex:p,sweep:u,token:y}),l=oe({amount:x,destination:T,destinationDex:n??"spot",fromSubAccount:H,hyperliquidChain:_e,nonce:f||Date.now(),signatureChainId:s||D,sourceDex:A,token:y});return ke({action:l,endpoint:t})}async function Be(e){let n=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(n?.status!=="ok")throw new g("core_transaction_failed",{definitive:n?.status==="err",response:n});return n}async function xe({amount:e,destination:n,nonce:t,token:r,user:i}){let o=h(i,"helpers_invalid_params"),s=await E(),p=t-5000,u=n?.toLowerCase(),f=r?.toUpperCase(),T=({delta:m,time:H})=>{if(!(H&&H>=p&&m?.type==="send"&&m.nonce===t))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(f!==void 0){if(!m?.token)return!1;let y=m.token.toUpperCase();if(y!==f&&!f.startsWith(`${y}:`))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},...De}),a=Array.isArray(H)?H.find(T):void 0;if(a?.hash)return a.hash}catch{}}return""}async function be({kind:e,lookup:n,signed:t}){try{await Be(t)}catch(i){if(i instanceof g&&i.errorKey==="core_transaction_failed"&&i.cause?.definitive===!0)throw i;let s=await xe(n);if(s)return s;throw new g("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:n.nonce,transportError:String(i)})}let r=await xe(n);if(!r)throw new g("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:n.nonce});return r}function Se({action:e,nonce:n,user:t}){return{amount:e.amount,destination:e.destination,nonce:n,token:e.token,user:t}}function $e(e){return e.startsWith("0x")&&we(e)}function Xn(e){let n=e&&"index"in e?e.index||0:0,t=Ye(e&&"derivationPath"in e&&e.derivationPath?e.derivationPath:en(Ze[U],{index:n})),r,i=!1;function o(){if(i)return r;return r=rn(e).with({phrase:Z.string},({phrase:a})=>tn.fromPhrase(a,void 0,t)).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 y=o();if(!y)throw new g("toolbox_hypercore_no_signer");let C=Te(a.typedData),x=await y.signTypedData(C.domain,C.types,C.message);return{action:a.action,endpoint:a.endpoint,nonce:a.nonce,signature:ye(x),..."expiresAfter"in a?{expiresAfter:a.expiresAfter}:{},..."vaultAddress"in a?{vaultAddress:a.vaultAddress}:{}}}async function u(a){let y=h(a,"helpers_invalid_params"),C=await E(),[x,A,l]=await Promise.all([N.post(`${C}/info`,{json:{type:"spotClearinghouseState",user:y}}),N.post(`${C}/info`,{json:{type:"clearinghouseState",user:y}}),N.post(`${C}/info`,{json:{type:"spotMeta"}})]),S=(x.spotState?.balances||x.balances||[]).map(({coin:w,token:R,total:P})=>he({coin:w,spotMeta:l,token:R,value:P})).filter((w)=>!!w),_=he({coin:"USDC",spotMeta:l,value:A.withdrawable||A.marginSummary?.accountValue||A.marginSummary?.totalRawUsd});return Cn(_?[...S,_]:S)}async function f(a,y=!0){let C=h(a,"helpers_invalid_params");try{let x=await nn.getChainBalance({address:C,chain:U,scamFilter:y});if(x.length){let A=x.map(({identifier:S,value:_,decimal:w})=>new M({decimal:w||ee,identifier:S,value:_}));return A.some((S)=>S.isGasAsset)?A:[M.from({chain:U}),...A]}}catch{}return u(C)}async function T({sweep:a,...y}){let C=o();if(!C)throw new g("toolbox_hypercore_no_signer");let x=y.sender||await C.getAddress(),A=await He({...y,feeRate:0,sender:x,sweep:a}),l=await p(A);return be({kind:"transfer",lookup:Se({action:A.action,nonce:A.nonce,user:A.action.fromSubAccount||x}),signed:l})}async function m(a){let y=o();if(!y)throw new g("toolbox_hypercore_no_signer");let{action:C,typedData:x,...A}=a,l=structuredClone(C),S=structuredClone(x),_=await y.getAddress(),w=await J(),R=[...new Set([w,on??w])];Ce({...A,action:l,allowedEndpoints:R,typedData:S});let P=l.fromSubAccount?h(l.fromSubAccount,"helpers_invalid_params"):_,L=await ve({destination:l.destination,sender:P});await qe({activationFee:L,amount:l.amount,sourceDex:l.sourceDex,token:l.token,user:P});let j=await p({action:l,endpoint:w,nonce:l.nonce,typedData:S});return be({kind:"payin",lookup:Se({action:l,nonce:l.nonce,user:P}),signed:j})}function H(){return M.from({chain:U,value:0})}return{broadcastTransaction:Be,createL1ActionRequest:hn,createSendAssetTransaction:He,createTransaction:bn,createUserSignedActionRequest:ke,estimateTransactionFee:H,getAddress:s,getBalance:f,getBalanceFromChain:u,getState:{clearinghouse:ne,frontendOpenOrders:ln,openOrders:un,orderStatus:gn,spotClearinghouse:Oe,userFills:fn,userFillsByTime:mn},signAndBroadcastSendAsset:m,signTransaction:p,transfer:T,validateAddress:$e}}export{B as HYPERCORE_USDC_TOKEN_ID,Rn as buildApproveAgentAction,In as buildApproveBuilderFeeAction,_n as buildBatchModifyAction,Tn as buildCancelAction,wn as buildCancelByCloidAction,Un as buildModifyAction,Sn as buildOrderAction,Pn as buildScheduleCancelAction,oe as buildSendAssetAction,qn as buildTokenDelegateAction,kn as buildTopUpIsolatedOnlyMarginAction,On as buildUpdateIsolatedMarginAction,Dn as buildUpdateLeverageAction,vn as buildUsdClassTransferAction,hn as createL1ActionRequest,He as createSendAssetTransaction,bn as createTransaction,ke as createUserSignedActionRequest,Xn as getHyperCoreToolbox,$e 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-1shb645r.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-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 +1 @@
1
- import{ja as U}from"../../chunk-qk8kg62t.js";import{ka as w}from"../../chunk-pz8xe0qj.js";import{AssetValue as et,Chain as g,getChainConfig as nt,getRPCUrl as ot,NetworkDerivationPath as rt,SwapKitError as d,SwapKitNumber as st}from"@swapkit/helpers";import{Address as i,beginCell as x,Cell as j,external as at,internal as it,loadStateInit as ct,SendMode as N,storeMessage as dt,toNano as L}from"@ton/core";import{match as F,P as B}from"ts-pattern";var lt=260734629,ut=L("0.01"),ft=L("0.05"),G=N.PAY_GAS_SEPARATELY+N.IGNORE_ERRORS,gt=N.CARRY_ALL_REMAINING_BALANCE+N.IGNORE_ERRORS,Tt=60000,O,v=0;async function wt(){let u=Date.now();if(O&&u-v<Tt)return O;let{getHttpEndpoint:p}=await import("@orbs-network/ton-access");return O=await p(),v=u,O}async function pt(){try{return await ot(g.Ton)}catch{return await wt()}}function Nt(u={}){let p,S,A;async function f(){if(!p){let{TonClient:t}=await import("@ton/ton"),e=u.provider??await pt();p=new t({endpoint:e})}return p}async function h(){return(await b()).address.toString()}async function C(){if(A)return A;return A=await F(u).with({phrase:B.string},async({phrase:t,derivationPath:e,index:n=0})=>{let r=rt[g.Ton],o=e?.some((a,c)=>a!==r[c]);if(n||o)throw new d("toolbox_derivation_slot_unsupported",{chain:g.Ton,derivationPath:e,index:n});let{mnemonicToWalletKey:s}=await import("@ton/crypto");return s(t.split(" "))}).with({signer:B.any},({signer:t})=>t).otherwise(()=>{return}),A}async function b(t){if(!S||t){let e=await C(),n=await f(),r=t||e;if(!r)throw new d("core_wallet_connection_not_found");let{WalletContractV4:o}=await import("@ton/ton"),s=o.create({publicKey:r.publicKey,workchain:0});S=n.open(s)}return S}let J=U(g.Ton);async function q({assetValue:t,recipient:e,memo:n,sender:r,sweep:o,jettonWalletAddress:s}){if(t.isGasAsset){if(o){let tt=r||await h(),K=await(await f()).getBalance(i.parse(tt));if(K<=0n)throw new d("toolbox_sweep_amount_too_low",{asset:t.toString(),balance:K.toString()})}let Z=n?D(n).toBoc().toString("base64"):void 0;return[{address:e,amount:t.getBaseValue("string"),payload:Z}]}let a=t.address;if(!a)throw new d({errorKey:"core_swap_contract_not_found",info:{asset:t.toString()}});let c=r??await h(),l=s?i.parse(s):await I({jettonMasterAddress:a,ownerAddress:c}),y=l.toString(),_=i.parse(e),T=i.parse(c),m=o?await H(l):t.getBaseValue("bigint");if(o&&m<=0n)throw new d("toolbox_sweep_amount_too_low",{asset:t.toString(),balance:m.toString()});let Q=n?D(n):void 0,X=V({destinationAddress:_,forwardPayload:Q,jettonAmount:m,responseAddress:T});return[{address:y,amount:ft.toString(),payload:X.toBoc().toString("base64")}]}async function M({sender:t,sweep:e,...n}){let r=e&&n.assetValue.isGasAsset?gt:G;return{messages:await q({...n,sender:t,sweep:e}),sendMode:r}}function k(t){if(!Array.isArray(t))return t;let[e]=t;return{messages:t.map(({sendMode:r,...o})=>o),sendMode:e?.sendMode??G}}function E(t){return t.map((e)=>{let n=e.payload?j.fromBase64(e.payload):void 0,r=e.stateInit?ct(j.fromBase64(e.stateInit).asSlice()):void 0,o=i.parse(e.address),s=i.isFriendly(e.address)?i.parseFriendly(e.address).isBounceable:!0;return it({body:n,bounce:s,init:r,to:o,value:BigInt(e.amount)})})}async function P(t){let e=await C(),n=await b();if(!n||!e)throw new d("core_wallet_connection_not_found");let r=await f(),{state:o}=await r.getContractState(n.address),s=o==="active",a=s?await n.getSeqno():0,{messages:c,sendMode:l}=k(t),y=n.createTransfer({messages:E(c),secretKey:e.secretKey,sendMode:l,seqno:a}),_=at({body:y,init:s?void 0:n.init,to:n.address});return x().store(dt(_)).endCell()}async function W(t){return await(await f()).sendFile(t.toBoc()),t.hash().toString("hex")}async function R(t){let e=await P(t);return W(e)}async function Y({assetValue:t,recipient:e,memo:n,sweep:r}){let o=await M({assetValue:t,memo:n,recipient:e,sweep:r});return R(o)}async function z({sender:t,...e}){let{baseDecimal:n}=nt(g.Ton),r=await F(t).with(B.string,(a)=>i.parseFriendly(a).address).otherwise(async()=>(await b()).address);if(!r)throw new d("toolbox_fee_estimation_failed",{chain:g.Ton});let o=et.from({chain:g.Ton,value:"0.01"}),s=await f();try{let a=await M({sender:t,...e}),c=await C(),l=await b();if(!l||!c)return o;let y=await l.getSeqno(),_=l.createTransfer({messages:E(a.messages),secretKey:c.secretKey,sendMode:a.sendMode,seqno:y}),{source_fees:T}=await s.estimateExternalMessageFee(r,{body:_,ignoreSignature:!0,initCode:null,initData:null}),m=T.in_fwd_fee+T.storage_fee+T.gas_fee+T.fwd_fee;return o.set(st.fromBigInt(BigInt(m),n))}catch{return o}}async function I({jettonMasterAddress:t,ownerAddress:e}){try{let n=await f(),r=i.parse(t),o=i.parse(e),{JettonMaster:s}=await import("@ton/ton");return await n.open(s.create(r)).getWalletAddress(o)}catch{throw new d({errorKey:"core_swap_contract_not_found",info:{jettonMasterAddress:t,ownerAddress:e}})}}async function H(t){try{let e=await f(),{JettonWallet:n}=await import("@ton/ton");return await e.open(n.create(t)).getBalance()}catch{throw new d({errorKey:"core_swap_contract_not_found",info:{jettonWalletAddress:t.toString()}})}}function V({jettonAmount:t,destinationAddress:e,responseAddress:n,forwardAmount:r=ut,forwardPayload:o}){let s=x().storeUint(lt,32).storeUint(0,64).storeCoins(t).storeAddress(e).storeAddress(n).storeBit(0).storeCoins(r);if(o)s.storeBit(1).storeRef(o);else s.storeBit(0);return s.endCell()}function D(t){return x().storeUint(0,32).storeStringTail(t).endCell()}return{broadcastTransaction:W,createTransaction:M,estimateTransactionFee:z,getAddress:h,getBalance:J,getJettonWalletAddress:I,sign:P,signAndBroadcastTransaction:R,transfer:Y,validateAddress:yt}}function yt(u){try{return i.parse(u),!0}catch{return!1}}export{Nt as getTONToolbox,yt as validateTonAddress};
1
+ import{ja as U}from"../../chunk-qk8kg62t.js";import{ka as h}from"../../chunk-pz8xe0qj.js";import{AssetValue as at,Chain as T,getChainConfig as q,getRPCUrl as it,NetworkDerivationPath as ct,RequestClient as dt,SwapKitError as g,SwapKitNumber as lt}from"@swapkit/helpers";import{Address as f,beginCell as x,Cell as j,external as ut,internal as ft,loadStateInit as pt,SendMode as N,storeMessage as Tt,toNano as k}from"@ton/core";import{match as F,P as E}from"ts-pattern";var wt=260734629,gt=k("0.01"),yt=k("0.05"),G=N.PAY_GAS_SEPARATELY+N.IGNORE_ERRORS,mt=N.CARRY_ALL_REMAINING_BALANCE+N.IGNORE_ERRORS,_t=1100,At=[1000,2000,4000],L=new Map,J=(r)=>new Promise((a)=>setTimeout(a,r));function bt(r){let a=L.get(r)??{nextStartAt:0,tail:Promise.resolve()};return L.set(r,a),a.tail=a.tail.then(async()=>{let d=a.nextStartAt-performance.now();if(d>0)await J(d);a.nextStartAt=performance.now()+_t}),a.tail}function Y(r){return r?.cause?.status}function ht(r){let a=Y(r);return a===429||a!==void 0&&a>=502}function v(r,a){let d=Y(r);return d!==void 0||r instanceof TypeError||r instanceof Error&&r.name==="AbortError"?new g({errorKey:"helpers_chain_rpc_connection_failed",info:{chain:T.Ton,status:d,...a}}):new g({errorKey:"core_swap_contract_not_found",info:a})}async function Q({attempt:r=0,body:a,headers:d,url:p}){if(q(T.Ton).rpcUrls.some((l)=>l===p))await bt(p);try{return await dt.post(p,{body:a,headers:d,retry:{maxRetries:0}})}catch(l){let m=At[r];if(m===void 0||!ht(l))throw l;return await J(m),Q({attempt:r+1,body:a,headers:d,url:p})}}var St=async(r)=>{let a=await Q({body:r.data,headers:r.headers.toJSON(),url:r.url??""});return{config:r,data:a,headers:{},status:200,statusText:"OK"}};function Mt(r={}){let a,d,p,C=new Map;async function l(){if(!a){let{TonClient:t}=await import("@ton/ton"),e=r.provider??await it(T.Ton,{allowRateLimited:!0});a=new t({endpoint:e,httpAdapter:St})}return a}async function m(){return(await S()).address.toString()}async function O(){if(p)return p;return p=await F(r).with({phrase:E.string},async({phrase:t,derivationPath:e,index:n=0})=>{let o=ct[T.Ton],s=e?.some((c,u)=>c!==o[u]);if(n||s)throw new g("toolbox_derivation_slot_unsupported",{chain:T.Ton,derivationPath:e,index:n});let{mnemonicToWalletKey:i}=await import("@ton/crypto");return i(t.split(" "))}).with({signer:E.any},({signer:t})=>t).otherwise(()=>{return}),p}async function S(t){if(!d||t){let e=await O(),n=await l(),o=t||e;if(!o)throw new g("core_wallet_connection_not_found");let{WalletContractV4:s}=await import("@ton/ton"),i=s.create({publicKey:o.publicKey,workchain:0});d=n.open(i)}return d}let V=U(T.Ton);async function z({assetValue:t,recipient:e,memo:n,sender:o,sweep:s,jettonWalletAddress:i}){if(t.isGasAsset){if(s){let st=o||await m(),K=await(await l()).getBalance(f.parse(st));if(K<=0n)throw new g("toolbox_sweep_amount_too_low",{asset:t.toString(),balance:K.toString()})}let rt=n?D(n).toBoc().toString("base64"):void 0;return[{address:e,amount:t.getBaseValue("string"),payload:rt}]}let c=t.address;if(!c)throw new g({errorKey:"core_swap_contract_not_found",info:{asset:t.toString()}});let u=o??await m(),w=i?f.parse(i):await I({jettonMasterAddress:c,ownerAddress:u}),y=w.toString(),A=f.parse(e),_=f.parse(u),b=s?await tt(w):t.getBaseValue("bigint");if(s&&b<=0n)throw new g("toolbox_sweep_amount_too_low",{asset:t.toString(),balance:b.toString()});let nt=n?D(n):void 0,ot=et({destinationAddress:A,forwardPayload:nt,jettonAmount:b,responseAddress:_});return[{address:y,amount:yt.toString(),payload:ot.toBoc().toString("base64")}]}async function R({sender:t,sweep:e,...n}){let o=e&&n.assetValue.isGasAsset?mt:G;return{messages:await z({...n,sender:t,sweep:e}),sendMode:o}}function H(t){if(!Array.isArray(t))return t;let[e]=t;return{messages:t.map(({sendMode:o,...s})=>s),sendMode:e?.sendMode??G}}function M(t){return t.map((e)=>{let n=e.payload?j.fromBase64(e.payload):void 0,o=e.stateInit?pt(j.fromBase64(e.stateInit).asSlice()):void 0,s=f.parse(e.address),i=f.isFriendly(e.address)?f.parseFriendly(e.address).isBounceable:!0;return ft({body:n,bounce:i,init:o,to:s,value:BigInt(e.amount)})})}async function P(t){let e=await O(),n=await S();if(!n||!e)throw new g("core_wallet_connection_not_found");let o=await l(),{state:s}=await o.getContractState(n.address),i=s==="active",c=i?await n.getSeqno():0,{messages:u,sendMode:w}=H(t),y=n.createTransfer({messages:M(u),secretKey:e.secretKey,sendMode:w,seqno:c}),A=ut({body:y,init:i?void 0:n.init,to:n.address});return x().store(Tt(A)).endCell()}async function B(t){return await(await l()).sendFile(t.toBoc()),t.hash().toString("hex")}async function W(t){let e=await P(t);return B(e)}async function X({assetValue:t,recipient:e,memo:n,sweep:o}){let s=await R({assetValue:t,memo:n,recipient:e,sweep:o});return W(s)}async function Z({sender:t,...e}){let{baseDecimal:n}=q(T.Ton),o=await F(t).with(E.string,(c)=>f.parseFriendly(c).address).otherwise(async()=>(await S()).address);if(!o)throw new g("toolbox_fee_estimation_failed",{chain:T.Ton});let s=at.from({chain:T.Ton,value:"0.01"}),i=await l();try{let c=await R({sender:t,...e}),u=await O(),w=await S();if(!w||!u)return s;let y=await w.getSeqno(),A=w.createTransfer({messages:M(c.messages),secretKey:u.secretKey,sendMode:c.sendMode,seqno:y}),{source_fees:_}=await i.estimateExternalMessageFee(o,{body:A,ignoreSignature:!0,initCode:null,initData:null}),b=_.in_fwd_fee+_.storage_fee+_.gas_fee+_.fwd_fee;return s.set(lt.fromBigInt(BigInt(b),n))}catch{return s}}async function I({jettonMasterAddress:t,ownerAddress:e}){let n=await l();try{let o=f.parse(t),s=f.parse(e),i=`${o.toRawString()}:${s.toRawString()}`,c=C.get(i);if(c)return c;let{JettonMaster:u}=await import("@ton/ton"),y=await n.open(u.create(o)).getWalletAddress(s);return C.set(i,y),y}catch(o){throw v(o,{jettonMasterAddress:t,ownerAddress:e})}}async function tt(t){let e=await l();try{let{JettonWallet:n}=await import("@ton/ton");return await e.open(n.create(t)).getBalance()}catch(n){throw v(n,{jettonWalletAddress:t.toString()})}}function et({jettonAmount:t,destinationAddress:e,responseAddress:n,forwardAmount:o=gt,forwardPayload:s}){let i=x().storeUint(wt,32).storeUint(0,64).storeCoins(t).storeAddress(e).storeAddress(n).storeBit(0).storeCoins(o);if(s)i.storeBit(1).storeRef(s);else i.storeBit(0);return i.endCell()}function D(t){return x().storeUint(0,32).storeStringTail(t).endCell()}return{broadcastTransaction:B,createTransaction:R,estimateTransactionFee:Z,getAddress:m,getBalance:V,getJettonWalletAddress:I,sign:P,signAndBroadcastTransaction:W,transfer:X,validateAddress:Nt}}function Nt(r){try{return f.parse(r),!0}catch{return!1}}export{Mt as getTONToolbox,Nt as validateTonAddress};
@@ -1 +1,2 @@
1
- import{ia as St,ja as jt}from"../../chunk-qk8kg62t.js";import"../../chunk-pz8xe0qj.js";import{NetworkDerivationPath as Cn}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 te({accountIndex:e,chain:t,derivationPath:n}){if(e!==void 0)z("accountIndex",e);let[r,s,a]=n??Cn[t];return[r,s,e??a]}function Ae({accountIndex:e,change:t=!1,chain:n,derivationPath:r,index:s}){return z("index",s),[...te({accountIndex:e,chain:n,derivationPath:r}),Number(t),s]}function pe(e){return e[2]??0}function Xn({deriveAddress:e,getBalance:t,getUtxos:n}){async function r(o){let{accountIndex:p,count:c,startIndex:u=0,change:i=!1}=o;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:i,index:u+h});if(m)l.push(m)}return l}async function s(o){let{gapLimit:p=20,change:c=!1}=o??{},u=[],i=0,l=0;while(i<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),i=0;else i++;l++}return u}async function a(o=20){let[p,c]=await Promise.all([s({change:!1,gapLimit:o}),s({change:!0,gapLimit:o})]),u=[...p,...c],i=await Promise.all(u.map(async(h)=>{let f=(await t(h.address)).reduce((y,b)=>y+b.getValue("number"),0);return{...h,balance:f}})),l=i.reduce((h,m)=>h+m.balance,0);return{addresses:i,total:l}}async function d(o=20){let[p,c]=await Promise.all([s({change:!1,gapLimit:o}),s({change:!0,gapLimit:o})]),u=[...p,...c];return(await Promise.all(u.map(async(l)=>(await n(l.address)).map((m)=>({...m,address:l.address,derivationIndex:l.index,isChange:l.change}))))).flat()}return{deriveAddresses:r,getAggregatedBalance:a,getAggregatedUtxos:d,scanForAddresses:s}}import{Chain as C,getRPCUrl as Bn,RequestClient as Re,SKConfig as kn,SwapKitError as R,warnOnce as Kn}from"@swapkit/helpers";import{NETWORKS as le}from"@swapkit/utxo-signer";async function Fn({chain:e,txHash:t}){let n=`${he(e)}/push/transaction`,r=JSON.stringify({data:t});try{let s=await Re.post(n,{body:r,headers:{"Content-Type":"application/json"}});if(s.context.code!==200)throw new R("toolbox_utxo_broadcast_failed",{error:s.context.error||"Transaction broadcast failed"});return s.data?.transaction_hash||t}catch(s){let a=await Bn(e);if(a){let d=JSON.stringify({id:St(),jsonrpc:"2.0",method:"sendrawtransaction",params:[t]}),o=await Re.post(a,{body:d,headers:{"Content-Type":"application/json"}});if(o.error)throw new R("toolbox_utxo_broadcast_failed",{error:o.error?.message});if(o.result.includes('"code":-26'))throw new R("toolbox_utxo_invalid_transaction",{error:"Transaction amount was too low"});return o.result}throw s}}function he(e){return`https://api.blockchair.com/${Dn(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 Dn(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 In(e){try{let{feePerKb:t}=await Re.get(`https://app.bitgo.com/api/v2/${e.toLowerCase()}/tx/fee`),n=t/1000;return Math.max(n,At(e))}catch{return At(e)}}async function Oe(e,t){let n=await Re.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 Hn({chain:e,apiKey:t}){let n=await Oe(`${he(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 Ct({address:e,chain:t,apiKey:n}){if(!e)throw new R("toolbox_utxo_invalid_params",{error:"Address is required"});try{return(await Oe(`${he(t)}/dashboards/address/${e}?transaction_details=true`,n))[e]}catch{return{address:{balance:0,transaction_count:0},utxo:[]}}}async function Rn({address:e,chain:t,apiKey:n}){return(await Ct({address:e,apiKey:n,chain:t}))?.address.balance||0}async function Xt({chain:e,apiKey:t,txHash:n}){if(!n)throw new R("toolbox_utxo_invalid_params",{error:"TxHash is required"});try{return(await Oe(`${he(e)}/raw/transaction/${n}`,t))?.[n]?.raw_transaction||""}catch(r){let s=r instanceof Error?r.message:String(r);return console.error(`Failed to fetch raw transaction: ${s}`),""}}var En=4294967294;async function Mn({chain:e,apiKey:t,txHash:n}){if(!n)throw new R("toolbox_utxo_invalid_params",{error:"TxHash is required"});let s=(await Oe(`${he(e)}/dashboards/transaction/${n}`,t))?.[n];if(!s)throw new R("toolbox_utxo_tx_not_found",{txHash:n});let{transaction:a,inputs:d,outputs:o}=s,p=d.map((u)=>u.spending_sequence),c=a.is_rbf===!0||p.some((u)=>u<En);return{blockId:a.block_id,confirmed:a.block_id!==-1,fee:a.fee,inputs:d,isRBF:c,outputs:o,sequences:p,size:a.size,txid:a.hash,weight:a.weight}}async function Nn({chain:e,address:t,apiKey:n,offset:r=0,limit:s=30}){return(await Oe(`${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=${s}&offset=${r}`,n)).map(({is_spent:p,script_hex:c,block_id:u,transaction_hash:i,index:l,value:h,spending_signature_hex:m})=>({hash:i,index:l,is_confirmed:u!==-1,is_spent:p,script_hex:c,txHex:m,value:h}))}function Zn(e){return e.reduce((t,n)=>t+n.value,0)}function Ot(e,t){let n=[...e].sort((r,s)=>s.value-r.value);if(t){let r=[],s=0;for(let a of n)if(r.push(a),s+=a.value,s>=t)break;return r}return n}async function Bt({chain:e,address:t,apiKey:n,targetValue:r,accumulativeValue:s=0,offset:a=0,limit:d=30}){if(!t)throw new R("toolbox_utxo_invalid_params",{error:"Address is required"});try{let o=await Nn({address:t,apiKey:n,chain:e,limit:d,offset:a,targetValue:r}),c=o.length<d,u=o.filter(({is_spent:y})=>!y),i=Zn(u),l=s+i,h=r&&l>=r;if(c||h)return Ot(u,r);let m=await Bt({accumulativeValue:l,address:t,apiKey:n,chain:e,limit:d,offset:a+d,targetValue:r}),f=[...u,...m];return Ot(f,r)}catch(o){let p=o instanceof Error?o.message:String(o);return console.error(`Failed to fetch unspent UTXOs: ${p}`),[]}}async function zn({address:e,chain:t,apiKey:n,fetchTxHex:r=!0,targetValue:s}){let a=await Bt({address:e,apiKey:n,chain:t,targetValue:s}),d=r?await Promise.all(a.map(({hash:o})=>Xt({apiKey:n,chain:t,txHash:o}))):[];return a.map(({hash:o,index:p,script_hex:c,value:u},i)=>({address:e,hash:o,index:p,txHex:r?d[i]:void 0,value:u,witnessUtxo:{script:Buffer.from(c,"hex"),value:u}}))}function A(e){let t=kn.get("apiKeys").blockchair||"";return Kn({condition:!t,id:"no_blockchair_api_key_warning",warning:"No Blockchair API key found. Functionality will be limited."}),{broadcastTx:(n)=>Fn({chain:e,txHash:n}),getAddressData:(n)=>Ct({address:n,apiKey:t,chain:e}),getBalance:(n)=>Rn({address:n,apiKey:t,chain:e}),getBlockHeight:()=>Hn({apiKey:t,chain:e}),getRawTx:(n)=>Xt({apiKey:t,chain:e,txHash:n}),getSuggestedTxFee:()=>In(e),getTransactionDetails:(n)=>Mn({apiKey:t,chain:e,txHash:n}),getUtxos:(n)=>zn({...n,apiKey:t,chain:e})}}function Hs(e){return e}function Rs(){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 Yn}from"@noble/hashes/sha2.js";import{createBase58check as jn}from"@scure/base";import{SwapKitError as Kt}from"@swapkit/helpers";import{CashAddrType as Ee,decodeCashAddr as Wn,encodeCashAddr as Ln}from"@swapkit/utxo-signer";var $n={P2PKH:Ee.P2PKH,P2SH:Ee.P2SH},Vn={[Ee.P2PKH]:"P2PKH",[Ee.P2SH]:"P2SH"};function qn(e,t,n){return Ln({hash:n,prefix:e,type:$n[t]})}function Gn(e){let t=Wn(e),n=Vn[t.type];if(!n)throw Error(`Unknown CashAddr type: ${t.type}`);return{hash:t.hash,prefix:t.prefix,type:n}}var ot={decode:Gn,encode:qn};var Ft=jn(Yn);var Dt;((n)=>{n.Mainnet="mainnet";n.Testnet="testnet"})(Dt||={});var ne={["legacy"]:{["mainnet"]:{["p2pkh"]:0,["p2sh"]:5},["testnet"]:{["p2pkh"]:111,["p2sh"]:196}},["bitpay"]:{["mainnet"]:{["p2pkh"]:28,["p2sh"]:40},["testnet"]:{["p2pkh"]:111,["p2sh"]:196}}},Jn={["p2pkh"]:"pkh",["p2sh"]:"sh"};function $s(e){return Ne(e)!==void 0}function Vs(e){return at(e).network}function G(e){let t=at(e);if(t.format==="legacy")return e;return tr(t)}function Me(e){let t=at(e);return nr(t)}function Ne(e){if(typeof e!=="string")return;let t=Qn(e)??er(e);return t&&{...t,scriptType:Jn[t.type]}}function at(e){let t=Ne(e);if(!t)throw new Kt("toolbox_utxo_invalid_address",{address:e});return t}function Qn(e){try{let t=Ft.decode(e);if(t.length!==21)throw new Kt("toolbox_utxo_invalid_address",{address:e});let n=t[0],r=Array.prototype.slice.call(t,1);switch(n){case ne.legacy.mainnet.p2pkh:return{format:"legacy",hash:r,network:"mainnet",type:"p2pkh"};case ne.legacy.mainnet.p2sh:return{format:"legacy",hash:r,network:"mainnet",type:"p2sh"};case ne.legacy.testnet.p2pkh:return{format:"legacy",hash:r,network:"testnet",type:"p2pkh"};case ne.legacy.testnet.p2sh:return{format:"legacy",hash:r,network:"testnet",type:"p2sh"};case ne.bitpay.mainnet.p2pkh:return{format:"bitpay",hash:r,network:"mainnet",type:"p2pkh"};case ne.bitpay.mainnet.p2sh:return{format:"bitpay",hash:r,network:"mainnet",type:"p2sh"};default:return}}catch{return}}function er(e){if(e.indexOf(":")!==-1)try{return kt(e)}catch{}else{let t=["bitcoincash","bchtest","bchreg"];for(let n of t)try{return kt(`${n}:${e}`)}catch{}}return}function kt(e){try{let{hash:t,prefix:n,type:r}=ot.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 tr(e){let t=ne.legacy[e.network][e.type],n=Buffer.alloc(1+e.hash.length);return n[0]=t,n.set(e.hash,1),Ft.encode(n)}function nr(e){let t=e.network==="mainnet"?"bitcoincash":"bchtest",n=e.type==="p2pkh"?"P2PKH":"P2SH",r=new Uint8Array(e.hash);return ot.encode(t,n,r)}import{Chain as ae,SwapKitError as mt}from"@swapkit/helpers";import{SwapKitError as qe,UTXO_SCRIPT_TYPE_LIST as Ar,UTXO_SCRIPT_TYPES as $t,UTXOScriptType as Ge}from"@swapkit/helpers";import{Script as Or}from"@swapkit/utxo-signer";import{Chain as it}from"@swapkit/helpers";import{getAddressScriptType as sr,getTransparentZcashAddressType as or,getZcashAddressType as ar}from"@swapkit/utxo-signer";import{match as ir}from"ts-pattern";import{Chain as fe}from"@swapkit/helpers";import{NETWORKS as Te}from"@swapkit/utxo-signer";import{match as rr}from"ts-pattern";function U(e){return rr(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 W(e){return e.replace(/(bchtest:|bitcoincash:)/,"")}function Se(e){if(typeof e!=="string")return null;let t=Ne(W(e));if(!t||t.network!=="mainnet")return null;return t.scriptType}var cr=["sprout","sapling","unified"];function dr(e){let t=or(e,U(it.Zcash));if(t)return t;let n=ar(e);return n&&cr.includes(n)?n:null}function Y({address:e,chain:t}){return ir(t).with(it.BitcoinCash,()=>Se(e)).with(it.Zcash,()=>dr(e)).otherwise(()=>sr(e,U(t)))}import{Chain as re,derivationPathToString as It,getPurposeFromPath as ur,getUTXOScriptTypeForPath as Ht,getUTXOScriptTypeForPurpose as Mt,resolveDerivationPath as pr,SwapKitError as Ce,UTXO_SCRIPT_TYPE_LIST as Rt,UTXO_SCRIPT_TYPES as me,UTXOChains as lr,UTXOScriptType as O,updateDerivationPath as hr,warnOnce as fr}from"@swapkit/helpers";import{CashAddrPrefix as Tr,CashAddrType as mr,encodeCashAddr as yr,OutScript as Nt,p2pkh as gr,p2sh as xr,p2tr as br,p2wpkh as Et}from"@swapkit/utxo-signer";var Ze=Object.freeze([O.P2PKH]),wr=Object.freeze({[re.Bitcoin]:Rt,[re.BitcoinCash]:Ze,[re.Dash]:Ze,[re.Dogecoin]:Ze,[re.Litecoin]:Rt,[re.Zcash]:Ze});function We(e){return wr[e]}function ct(e){return We(e).some((t)=>me[t].witness)}function ye(e,t){return We(e).includes(t)}function Le(e,t){if(ye(e,t))return t;throw new Ce("toolbox_utxo_unsupported_script_type",{chain:e,error:`${e} cannot encode ${t}; supported: ${We(e).join(", ")}`,scriptType:t,supported:We(e)})}var Zt=lr.filter((e)=>!ct(e));function Pr({purpose:e,scriptType:t}){let n=Mt(e);return n===void 0||n===t}function dt({chain:e,purpose:t,scriptType:n}){fr({condition:!Pr({purpose:t,scriptType:n}),id:`utxo_off_standard_encoding_${e}_${t}_${n}`,warning:`${e}: encoding m/${t}' keys as ${n}, not the ${Mt(t)} the path implies. No other wallet derives these addresses: move funds out of them, never receive into them.`})}function $e({chain:e,derivationPath:t,index:n=0,scriptType:r}){if(t){if(!r){let o=Ht(t);throw new Ce("toolbox_utxo_invalid_params",{chain:e,derivationPath:It(t),error:`scriptType is required alongside derivationPath: getUTXOScriptTypeForPath gives the standard one${o?` (${o})`:""}, or state another deliberately.`})}return Le(e,r),dt({chain:e,purpose:ur(t),scriptType:r}),{derivationPath:t,scriptType:r}}let s=pr({chain:e,index:n}),a=r?hr(s,{purpose:me[r].purpose}):s,d=r??Ht(a);if(!d)throw new Ce("toolbox_utxo_invalid_params",{chain:e,derivationPath:It(a),error:`${e}: the default derivation path has no standard script type`});return Le(e,d),{derivationPath:a,scriptType:d}}function Ur(e){return e.length===32?e:e.slice(1)}function ze(e,t){if(!e.address)throw new Ce("toolbox_utxo_invalid_address",{error:`Could not derive a ${t} address`});return e}var vr={[O.P2PKH]:(e,t)=>{let{address:n,script:r}=ze(gr(e,t),O.P2PKH);return{address:n,script:r}},[O.P2SH_P2WPKH]:(e,t)=>{let n=Et(e,t),{address:r,script:s}=ze(xr(n,t),O.P2SH_P2WPKH);return{address:r,redeemScript:n.script,script:s}},[O.P2WPKH]:(e,t)=>{let{address:n,script:r}=ze(Et(e,t),O.P2WPKH);return{address:n,script:r}},[O.P2TR]:(e,t)=>{let n=Ur(e),{address:r,script:s}=ze(br(n,void 0,t),O.P2TR);return{address:r,script:s,tapInternalKey:n}}};function Ve(e,t,n){return vr[e](t,n)}function ut(e,t){if(e!==re.BitcoinCash)return t.address;let n=Nt.decode(t.script);if(n.type!=="pkh")throw new Ce("toolbox_utxo_invalid_address",{chain:e,error:`Cannot encode ${n.type} as CashAddr`});return yr({hash:n.hash,prefix:Tr.MAINNET,type:mr.P2PKH}).replace(/^bitcoincash:/,"")}var _r=Object.freeze({pkh:O.P2PKH,sh:O.P2SH_P2WPKH,tr:O.P2TR,wpkh:O.P2WPKH}),zt=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 Wt(e){return e in zt}function Lt(e){return Wt(e)?zt[e]:void 0}function Xe(e){return _r[e]}function pt(e){try{let{type:t}=Nt.decode(e);return Wt(t)?Xe(t):void 0}catch{return}}import{UTXOScriptType as oe}from"@swapkit/helpers";var ho=1000,ht=10,Sr=2,Cr=10;function E(e){let t=new Uint8Array(Buffer.from(e,"utf8"));return Or.encode(["RETURN",t])}function Vt(e){return Object.fromEntries(Ar.map((t)=>[t,$t[t][e]]))}var qt=Vt("inputSize"),lt=Vt("outputSize"),ft=(e)=>$t[e].witness,Ye=(e,t)=>{let n=Y({address:e,chain:t});if(!n)throw new qe("toolbox_utxo_invalid_address",{address:e,chain:t});let r=Xe(n);if(!r||!ye(t,r))throw new qe("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},Xr=(e,t)=>{let n=Y({address:e,chain:t});if(!n)throw new qe("toolbox_utxo_invalid_address",{address:e,chain:t});let r=Lt(n);if(!r)throw new qe("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},ge=({chain:e,inputs:t,outputs:n,feeRate:r})=>{let s=t[0]?Be(t[0],e):Ge.P2PKH,a=r?t.filter((u)=>u.value>=qt["type"in u&&u.type?u.type:Ge.P2PKH]*Math.ceil(r)):t,d=0,o=0;for(let u of a)if(d+=se(u,e),!ft(Be(u,e)))o++;let p=n?.reduce((u,i)=>u+je(i,e),0)||lt[s],c=o<a.length;return ht+d+p+Tt(c,o)},Be=(e,t)=>{if("type"in e&&e.type)return e.type;if("address"in e&&e.address)return Ye(e.address,t);return Ge.P2PKH},se=(e,t)=>qt[Be(e,t)],Tt=(e,t)=>e?Math.ceil((Sr+t)/4):0,je=(e,t,n)=>{if(e?.script)return Cr+e.script.length+(e.script.length>=74?2:1);if(n)return lt[n];if("address"in e&&e.address)return Xr(e.address,t);return lt[Ge.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 M({inputs:e,outputs:t,feeRate:n=1,chain:r=ae.Bitcoin,changeAddress:s="",sweep:a=!1}){let d=ke(r),o=e.filter((f)=>{let y=se(f,r)*n;return a?f.value>Math.max(y,d):y<=f.value});if(a){let f=Math.ceil(n*ge({chain:r,inputs:o,outputs:t})),y=o.reduce((X,V)=>X+V.value,0),b=y-f;if(b<=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:o,outputs:t.map((X,V)=>V===S?{...X,value:b}:X)}}let p=ht+t.reduce((f,y)=>f+je(y,r),0),c=t.reduce((f,y)=>f+y.value,0),u=0,i=0,l=!1,h=0,m=[];for(let f of o){if(u+=se(f,r),ft(Be(f,r)))l=!0;else i++;h+=f.value,m.push(f);let y=(p+u+Tt(l,i))*n,b=y+c;if(h<b)continue;let S=h-b,X=n*je({address:s,value:0},r);if(S>X){let V=X+y,Pe=h-(c+Math.ceil(V));if(Pe>Math.max(se({value:0},r)*n,ke(r)))return{fee:Math.ceil(V),inputs:m,outputs:t.concat({address:s,value:Pe})}}return{fee:Math.ceil(y),inputs:m,outputs:t}}return{fee:Math.ceil(n*ge({chain:r,inputs:e,outputs:t}))}}import{Chain as we,SwapKitError as Bs}from"@swapkit/helpers";import{hex as un}from"@scure/base";import{Chain as Yr,derivationPathToString as jr,FeeOption as Jr,resolveDerivationPath as Qr,SwapKitError as L}from"@swapkit/helpers";import{BCHSigHash as es,CashAddrPrefix as pn,CashAddrType as ln,encodeCashAddr as hn,NETWORKS as ts,p2pkh as fn,Transaction as Tn}from"@swapkit/utxo-signer";import{secp256k1 as Br}from"@noble/curves/secp256k1.js";import{hex as j}from"@scure/base";import{HDKey as Jt}from"@scure/bip32";import{mnemonicToSeedSync as xt}from"@scure/bip39";import{AssetValue as yt,applyFeeMultiplier as Gt,Chain as Fe,derivationPathToString as Ke,FeeOption as N,NetworkDerivationPath as kr,SwapKitError as P,SwapKitNumber as Kr,UTXO_SCRIPT_TYPES as Fr,warnOnce as Dr}from"@swapkit/helpers";import{BCHSigHash as Qt,RBF_SEQUENCE as Ir,SigHash as Yt,Transaction as Je,utils as Hr,WIF as en}from"@swapkit/utxo-signer";var Qe=[Fe.Bitcoin];function tn({address:e,chain:t}){return Y({address:e,chain:t})!==null}function Rr({phrase:e,derivationPath:t,network:n,seed:r}){let s=r??xt(e),d=Jt.fromMasterSeed(s,n.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 gt(e){return Br.getPublicKey(e,!0)}function De({publicKey:e,chain:t,network:n,scriptType:r}){return ut(t,Ve(r,e,n))}function xe({phrase:e,derivationPath:t,chain:n,wif:r,seed:s}){let a=U(n);if(r){let c=en(a).decode(r),u=gt(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||Ke(kr[n]),o=Rr({derivationPath:d,network:a,phrase:e,seed:s}),p=gt(o);return{privateKey:o,publicKey:p}}function Er(e,t){return en(U(t)).encode(e)}function Mr({phrase:e,derivationPath:t,chain:n,seed:r}){let s=t.split("/");if(s.length<4)throw new P("toolbox_utxo_invalid_params",{error:`Derivation path must have at least 4 levels (got ${s.length}): ${t}`});let a=U(n),d=r??xt(e),o=Jt.fromMasterSeed(d,a.bip32),p=s.slice(0,4).join("/");return o.derive(p)}function Nr(e,t){if(!e||!Fr[e].witness)return!1;return e!==oe.P2SH_P2WPKH||!!t}function nn({chain:e,script:t,publicKey:n,network:r}){let s=pt(t);if(s!==oe.P2SH_P2WPKH&&s!==oe.P2TR)return{};if(!ye(e,s))return{};let a=Ve(s,n,r);if(Hr.compareBytes(a.script,t)!==0)return{};return s===oe.P2TR?{tapInternalKey:a.tapInternalKey}:{redeemScript:a.redeemScript}}function Zr(e,t,n){if(!n)return!1;let r=Y({address:e,chain:t}),s=r?Xe(r):void 0;if(!s||!ye(t,s))return!1;let a=ut(t,Ve(s,n,U(t)));return t===Fe.BitcoinCash?W(a)===W(e):a===e}function zr(e){return e.witnessUtxo?.script??e.nonWitnessUtxo?.outputs[e.index??0]?.script}function bt({chain:e,tx:t,publicKey:n,network:r,indexes:s}){let a=s??Array.from({length:t.inputsLength},(o,p)=>p),d=[];for(let o of a){let p=t.getInput(o),c=zr(p);if(!c)continue;let{redeemScript:u,tapInternalKey:i}=nn({chain:e,network:r,publicKey:n,script:c}),l={index:o};if(u&&!p.redeemScript)l.redeemScript=u;if(i&&!p.tapInternalKey)l.tapInternalKey=i;if(l.redeemScript||l.tapInternalKey)d.push(l)}return d}function ie({inputs:e,outputs:t,chain:n,tx:r,sender:s,compiledMemo:a,enableRBF:d=!1}){let o=U(n),p=ct(n),c=d?Ir:void 0,u=new Set;for(let i of e){let l=`${i.hash}:${i.index}`;if(u.has(l))throw new P("toolbox_utxo_invalid_params",{error:"Duplicate input detected"});u.add(l);let h=typeof i.hash==="string"?j.decode(i.hash):i.hash,m=i.witnessUtxo?pt(i.witnessUtxo.script):void 0,f=i.publicKey&&i.witnessUtxo?nn({chain:n,network:o,publicKey:i.publicKey,script:i.witnessUtxo.script}):{};if(p&&i.witnessUtxo&&Nr(m,f.redeemScript))r.addInput({...f,index:i.index,sequence:c,txid:h,witnessUtxo:{amount:BigInt(i.witnessUtxo.value),script:i.witnessUtxo.script}});else if(i.txHex)r.addInput({...f,index:i.index,nonWitnessUtxo:j.decode(i.txHex),sequence:c,txid:h,...n===Fe.BitcoinCash?{sighashType:Qt.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:s;if(n===Fe.BitcoinCash)l=G(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),o)}return{inputs:e,tx:r}}async function be(e){let t=await A(e).getSuggestedTxFee();return{[N.Average]:t,[N.Fast]:Gt(t,N.Fast),[N.Fastest]:Gt(t,N.Fastest)}}async function rn({assetValue:e,recipient:t,memo:n,sender:r,sweep:s,fetchTxHex:a=!1,publicKey:d},o,{forEstimateOnly:p=!1}={}){let c=e.chain,u=Ye(r,c),i=u===oe.P2PKH||u===oe.P2SH_P2WPKH&&!Zr(r,c,d),l=a||!p&&i,h=e.getBaseValue("number"),m=s?void 0:o??(await be(c))[N.Fastest],f=s||m===void 0?void 0:Math.ceil(h+m*5000);return{inputs:await A(c).getUtxos({address:r,fetchTxHex:l,targetValue:f}),outputs:[{address:t,value:s?0:h},...n?[{address:"",script:E(n),value:0}]:[]]}}async function sn({assetValue:e,recipient:t,memo:n,feeRate:r,sender:s,fetchTxHex:a=!1,enableRBF:d=!1,sweep:o,publicKey:p}){let c=e.chain,u=n?E(n):null,i=await rn({assetValue:e,fetchTxHex:a,memo:n,publicKey:p,recipient:t,sender:s,sweep:o},r),{inputs:l,outputs:h}=M({...i,chain:c,changeAddress:s,feeRate:r,sweep:o});if(!(l&&h))throw new P("toolbox_utxo_insufficient_balance",{assetValue:e,sender:s});let m=p?l.map((S)=>({...S,publicKey:p})):l,f=new Je({allowUnknownOutputs:!!u,version:1}),{inputs:y,tx:b}=ie({chain:c,compiledMemo:u,enableRBF:d,inputs:m,outputs:h,sender:s,tx:f});return{inputs:y,tx:b,utxos:i.inputs}}async function on({assetValue:e,feeOptionKey:t=N.Fast,feeRate:n,memo:r,sender:s,recipient:a,sweep:d}){let o=e.chain,p,c;if(n!==void 0)p=n,c=Math.floor(n);else{let i=await be(o);p=i[N.Fastest],c=i[t]}let u=await rn({assetValue:e,memo:r,recipient:a,sender:s,sweep:d},p,{forEstimateOnly:!0});return M({...u,chain:o,changeAddress:s,feeRate:c,sweep:d})}function Wr(e){return async function({from:n,memo:r,feeRate:s,feeOptionKey:a=N.Fast,recipient:d=n,recipients:o=1}){let p=s??(await be(e))[a],u=(await A(e).getUtxos({address:n,fetchTxHex:!1})).filter((f)=>f.value>Math.max(ke(e),se(f,e)*p));if(!u.length)return yt.from({chain:e});let i=typeof o==="number"?Math.max(o,1):o.length,l=typeof o==="number"||i===0?Array.from({length:i||1},()=>({address:d,value:0})):[...o];if(r)l.push({address:n,script:E(r),value:0});let{outputs:h}=M({chain:e,feeRate:p,inputs:u,outputs:l,sweep:!0}),m=h?.[0]?.value??0;return yt.from({chain:e,value:BigInt(m)})}}function Lr(e){return async function(n){let{fee:r}=await on(n);return yt.from({chain:e,value:Kr.fromBigInt(BigInt(r),8).getValue("string")})}}function $r({chain:e,phrase:t,derivationPath:n,scriptType:r,seed:s}){let a=U(e),{privateKey:d,publicKey:o}=xe({chain:e,derivationPath:n,phrase:t,seed:s}),p=an(e);return{getAddress:()=>De({chain:e,network:a,publicKey:o,scriptType:r}),privateKey:d,publicKey:o,signTransaction:(c)=>{for(let{index:u,...i}of bt({chain:e,network:a,publicKey:o,tx:c}))c.updateInput(u,i);return c.sign(d,p),c}}}function an(e){return e===Fe.BitcoinCash?[Qt.ALL]:[Yt.ALL,Yt.DEFAULT]}function Vr(e,t,n){return async function({memo:s,recipient:a,feeOptionKey:d,feeRate:o,assetValue:p,enableRBF:c=!1,sweep:u}){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"});Dr({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=o||(await be(e))[d||N.Fast],{tx:m}=await sn({assetValue:p,enableRBF:l,feeRate:h,memo:s,publicKey:n,recipient:a,sender:i,sweep:u}),f=await t.signTransaction(m);return f.finalize(),A(e).broadcastTx(j.encode(f.extract()))}}function cn(e){return(t)=>tn({address:t,chain:e})}function dn(e,{scriptType:t}){let n=U(e);return function(s){if(!s)throw new P("toolbox_utxo_invalid_params",{error:"Keys must be provided"});return De({chain:e,network:n,publicKey:s.publicKey,scriptType:t})}}function qr(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 ce(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,s=n?.index??0,a=r?xt(r):void 0,{derivationPath:d,scriptType:o}=$e({chain:t,derivationPath:n?.derivationPath,index:s,scriptType:e.scriptType}),p=Ke(d),c=r?$r({chain:t,derivationPath:p,phrase:r,scriptType:o,seed:a}):void 0,u=n?void 0:e.signer,i=c||u,l=r?xe({chain:t,derivationPath:p,phrase:r,seed:a}):void 0,h=l?.publicKey??qr(u);function m(){if(i)return i.getAddress();return Promise.resolve(void 0)}function f(T){if(!r)return;let g=te({accountIndex:T,chain:t,derivationPath:d});return Mr({chain:t,derivationPath:Ke(g),phrase:r,seed:a})}let y=f();function b(){if(!y)return;return y.publicExtendedKey}function S({accountIndex:T}={}){let g=T===void 0?y:f(T);if(!g)return;let w=te({accountIndex:T,chain:t,derivationPath:d});return{accountIndex:pe(w),path:Ke(w),xpub:g.publicExtendedKey}}function X({accountIndex:T,index:g,change:w=!1}){let _=T===void 0?y:f(T);if(!_)return;let x=Ae({accountIndex:T,chain:t,change:w,derivationPath:d,index:g}),K=U(t),I=_.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:o}),F=j.encode(I.publicKey);return{accountIndex:pe(x),address:B,change:w,index:g,path:Ke(x),pubkey:F}}async function V(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 Pe({txid:T,newFeeRate:g,recipient:w,memo:_}){if(!Qe.includes(t))throw new P("toolbox_utxo_rbf_not_supported",{chain:t});let x=await A(t).getTransactionDetails(T);if(!x.isRBF)throw new P("toolbox_utxo_tx_not_replaceable",{txid:T});if(x.confirmed)throw new P("toolbox_utxo_tx_already_confirmed",{blockId:x.blockId,txid:T});let K=x.inputs.reduce((v,D)=>v+D.value,0),B=x.outputs.find((v)=>v.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(x.inputs.map(async(v)=>{let D=await A(t).getRawTx(v.transaction_hash),k=Je.fromRaw(j.decode(D),{allowUnknownOutputs:!0,disableScriptCheck:!0}).getOutput(v.index);return{address:v.recipient,hash:v.transaction_hash,index:v.index,publicKey:h,txHex:D,value:v.value,witnessUtxo:k.script&&k.amount!==void 0?{script:Buffer.from(k.script),value:Number(k.amount)}:void 0}})),H=_?E(_):null,Q=K-B-x.fee,Ue=await m(),ue=[];if(H)ue.push({address:"",script:H,value:0});if(Q>ke(t)&&Ue)ue.push({address:Ue,value:Q});let He=ge({chain:t,inputs:F.map((v)=>({...v,type:Ye(v.address,t)})),outputs:[{address:w,value:B},...ue]}),q=Math.ceil(He*g);if(q<=x.fee)throw new P("toolbox_utxo_rbf_fee_too_low",{newFee:q,originalFee:x.fee});let ve=q-x.fee,ee=B-ve;if(ee<=0)throw new P("toolbox_utxo_rbf_insufficient_change");let _e=new Je({allowUnknownOutputs:!!H,version:1}),nt=[{address:w,value:ee},...ue];return ie({chain:t,compiledMemo:H,inputs:F,outputs:nt,sender:Ue||w,tx:_e}),{feeDelta:ve,newFee:q,originalFee:x.fee,tx:_e}}async function vn({txid:T,newFeeRate:g,recipient:w,memo:_}){let{tx:x,originalFee:K,newFee:I}=await Pe({memo:_,newFeeRate:g,recipient:w,txid:T}),B=await tt(x);B.finalize();let F=await A(t).broadcastTx(j.encode(B.extract()));return{newFee:I,originalFee:K,txid:F}}function vt({accountIndex:T,index:g,change:w=!1}){z("index",g);let _=T===void 0?y:f(T);if(!_)return;return _.deriveChild(Number(w)).deriveChild(g).privateKey||void 0}function _t({tx:T,inputDerivations:g}){if(!y)throw new P("toolbox_utxo_no_signer");let w=an(t),_=U(t);for(let x=0;x<g.length;x++){let K=g[x];if(!K)continue;let{derivationIndex:I,isChange:B}=K,F=vt({change:B,index:I});if(!F)throw new P("toolbox_utxo_invalid_params",{error:`Could not derive private key for input ${x} at index ${I}`});for(let{index:H,...Q}of bt({chain:t,indexes:[x],network:_,publicKey:gt(F),tx:T}))T.updateInput(H,Q);T.signIdx(F,x,w)}return T}async function _n({utxos:T,recipient:g,assetValue:w,memo:_,feeRate:x,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=x||(await be(t))[K||N.Fast],H=_?E(_):null,Q=[{address:g,value:w.getBaseValue("number")}];if(H)Q.push({address:"",script:H,value:0});let Ue=T.map(({address:v,hash:D,index:k,value:rt,txHex:Sn,witnessUtxo:st})=>({address:v,hash:D,index:k,txHex:Sn,value:rt,witnessUtxo:st?{script:st.script,value:st.value}:void 0})),ue=T[0]?.address,He=I||await m()||ue||g,{inputs:q,outputs:ve}=M({chain:t,changeAddress:He,feeRate:F,inputs:Ue,outputs:Q});if(!(q&&ve))throw new P("toolbox_utxo_insufficient_balance",{assetValue:w,sender:"multiple addresses"});let ee=new Je({allowUnknownOutputs:!!H,version:1}),_e=q.map((v)=>{let D=T.find((k)=>k.hash===v.hash&&k.index===v.index);return D?{derivationIndex:D.derivationIndex,isChange:D.isChange}:{derivationIndex:0,isChange:!1}}),nt=q.map((v,D)=>{let k=_e[D],rt=k?y.deriveChild(Number(k.isChange)).deriveChild(k.derivationIndex).publicKey:null;return{...v,publicKey:rt??void 0}});return ie({chain:t,compiledMemo:H,inputs:nt,outputs:ve,sender:He,tx:ee}),_t({inputDerivations:_e,tx:ee}),ee.finalize(),A(t).broadcastTx(j.encode(ee.extract()))}function An({address:T,gapLimit:g=20}){if(!y)return;for(let w=0;w<g;w++){let _=X({change:!1,index:w}),x=X({change:!0,index:w}),K=_?.address===T?!1:x?.address===T;if(_?.address===T||x?.address===T)return{change:K,index:w}}return}function tt(T){if(!i)throw new P("toolbox_utxo_no_signer");return i.signTransaction(T)}async function On(T){let g=await tt(T);return g.finalize(),await A(t).broadcastTx(j.encode(g.extract()))}return{accumulative:M,broadcastTx:(T)=>A(t).broadcastTx(T),bumpFee:vn,calculateTxSize:(T)=>ge({...T,chain:t}),createKeysForPath:(T)=>xe({...T,chain:t}),createReplacementTransaction:Pe,createTransaction:(T)=>sn({publicKey:h,...T}),deriveAddressAtIndex:X,derivePrivateKeyAtIndex:vt,estimateMaxSendableAmount:Wr(t),estimateTransactionFee:Lr(t),getAddress:m,getAddressFromKeys:dn(t,{scriptType:o}),getAddressType:(T)=>Y({address:T,chain:t}),getBalance:jt(t),getExtendedPublicKey:b,getExtendedPublicKeyInfo:S,getFeeRates:()=>be(t),getInputsOutputsFee:on,getNetworkForChain:()=>U(t),getPrivateKeyFromMnemonic:(T)=>Er(xe({...T,chain:t}).privateKey,t),isRBFEnabled:V,keys:l,resolveDerivationIndex:An,scriptType:o,signAndBroadcastTransaction:On,signTransaction:tt,signTransactionWithMultipleKeys:_t,transfer:Vr(t,i,h),transferFromMultipleAddresses:_n,validateAddress:cn(t)}}import{getZcashAddressType as Gr,validateZcashAddress as wt}from"@swapkit/utxo-signer";function Ie(e){return Se(e)!==null}var Z=Yr.BitcoinCash;function et(e){return W(Me(e))}function ns(e){let t=U(Z);function n(s){return s.sign(e.privateKey,[es.ALL]),s}function r(){let s=fn(e.publicKey,t);if(!s.hash)throw new L("toolbox_utxo_invalid_address",{error:"Could not derive BCH address hash"});let a=hn({hash:s.hash,prefix:pn.MAINNET,type:ln.P2PKH});return Promise.resolve(a.replace(/^bitcoincash:/,""))}return{getAddress:r,signTransaction:n}}function mn(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,s=Qr({chain:Z,derivationPath:r,index:n}),a=jr(s),d=t?xe({chain:Z,derivationPath:a,phrase:t}):void 0,o=d?ns(d):("signer"in e)?e.signer:void 0;function p(){return Promise.resolve(o?.getAddress())}let c="scriptType"in e?e.scriptType:void 0,{getBalance:u,getFeeRates:i,broadcastTx:l,...h}=ce(t?{chain:Z,index:n,phrase:t,...r?{derivationPath:r,scriptType:c}:{scriptType:c}}:{chain:Z,scriptType:c});function m(b,S=!0){return u(W(Me(b)))}function f(b){if(!o)throw new L("toolbox_utxo_no_signer");return o.signTransaction(b)}async function y(b){let S=await f(b);return S.finalize(),await l(un.encode(S.extract()))}return{...h,broadcastTx:l,buildTx:ss,createTransaction:yn,getAddress:p,getAddressFromKeys:os,getBalance:m,getFeeRates:i,signAndBroadcastTransaction:y,signTransaction:f,stripPrefix:W,stripToCashAddress:et,transfer:rs({broadcastTx:l,getFeeRates:i,signer:o}),validateAddress:Ie}}async function yn({assetValue:e,recipient:t,memo:n,feeRate:r,sender:s,sweep:a}){if(!Ie(t))throw new L("toolbox_utxo_invalid_address",{address:t});let d=Math.ceil(e.getBaseValue("number")+r*7500),o=await A(Z).getUtxos({address:et(s),fetchTxHex:!0,targetValue:a?void 0:d}),p=n?E(n):null,c=[],u=G(t);if(c.push({address:u,value:a?0:e.getBaseValue("number")}),p)c.push({script:p,value:0});let{inputs:i,outputs:l}=M({chain:Z,feeRate:r,inputs:o,outputs:c,sweep:a});if(!(i&&l))throw new L("toolbox_utxo_insufficient_balance",{assetValue:e,sender:s});let h=new Tn({allowUnknownOutputs:!!p,version:1}),m=G(s),{inputs:f,tx:y}=ie({chain:Z,compiledMemo:p,inputs:i,outputs:l.map((b)=>("address"in b)&&b.address?{...b,address:G(b.address)}:b),sender:m,tx:h});return{inputs:f,tx:y,utxos:i}}function rs({broadcastTx:e,getFeeRates:t,signer:n}){return async function({recipient:s,assetValue:a,feeOptionKey:d=Jr.Fast,sweep:o,...p}){let c=await n?.getAddress();if(!(n&&c))throw new L("toolbox_utxo_no_signer");if(!s)throw new L("toolbox_utxo_invalid_params",{error:"Recipient address must be provided"});let u=p.feeRate||(await t())[d],{tx:i}=await yn({...p,assetValue:a,feeRate:u,recipient:s,sender:c,sweep:o}),l=await n.signTransaction(i);return l.finalize(),e(un.encode(l.extract()))}}async function ss({assetValue:e,recipient:t,memo:n,feeRate:r,sender:s}){let a=Me(t);if(!Ie(a))throw new L("toolbox_utxo_invalid_address",{address:a});let d=Math.ceil(e.getBaseValue("number")+r*7500),o=await A(Z).getUtxos({address:et(s),fetchTxHex:!0,targetValue:d}),p=Number(r.toFixed(0)),c=n?E(n):null,u=[];if(u.push({address:G(t),value:e.getBaseValue("number")}),c)u.push({script:c,value:0});let{inputs:i,outputs:l}=M({chain:Z,feeRate:p,inputs:o,outputs:u});if(!(i&&l))throw new L("toolbox_utxo_insufficient_balance",{assetValue:e,sender:s});let h=new Tn({allowUnknownOutputs:!!c,version:1}),{inputs:m,tx:f}=ie({chain:Z,compiledMemo:c,inputs:i,outputs:l,sender:G(s),tx:h});return{inputs:m,tx:f,utxos:o}}function os(e){let t=ts.bitcoinCash,n=fn(e.publicKey,t);if(!n.hash)throw new L("toolbox_utxo_invalid_address",{error:"Could not derive BCH address hash"});return hn({hash:n.hash,prefix:pn.MAINNET,type:ln.P2PKH}).replace(/^bitcoincash:/,"")}import{createBase58check as as,hex as is}from"@scure/base";import{HDKey as bn}from"@scure/bip32";import{mnemonicToSeedSync as wn}from"@scure/bip39";import{Chain as J,derivationPathToString as cs,FeeOption as ds,SwapKitError as de}from"@swapkit/helpers";import{Address as us,createZcashTransaction as ps,getZcashConsensusBranchId as ls,isTransparentZcashAddress as gn,OutScript as hs,PCZT as fs,utils as Pn,WIF as Ts,ZcashConsensusBranchId as ms,ZcashPSBT as ys,ZcashSigHash as Pt,ZcashVersionGroupId as gs}from"@swapkit/utxo-signer";import{match as xs,P as Ut}from"ts-pattern";var bs=as(Pn.sha256);function ws(e){return bs.encode(e)}function Ps({phrase:e,derivationPath:t}){let n=wn(e),s=bn.fromMasterSeed(n).derive(t);if(!s.privateKey||!s.publicKey)throw new de("toolbox_utxo_invalid_params");let{privateKey:a,publicKey:d}=s,o=Pn.hash160(d),p=new Uint8Array([28,184]),c=new Uint8Array(p.length+o.length);c.set(p,0),c.set(o,p.length);let u=ws(c);return{getAddress:()=>Promise.resolve(u),signTransaction:(i)=>{if(i instanceof ys){let l=i.toPCZT();return l.signAllInputs(a,d,Pt.ALL),l.finalizeAllInputs(),Promise.resolve(l.extract())}if(i instanceof fs)return i.signAllInputs(a,d,Pt.ALL),i.finalizeAllInputs(),Promise.resolve(i.extract());return i.signAllInputs(a,d,Pt.ALL),Promise.resolve(i)}}}function Us({inputs:e,outputs:t,tx:n,sender:r,compiledMemo:s}){let a=U(J.Zcash);for(let d of e){let o=us(a).decode(r),p=hs.encode(o);n.addInput({index:d.index,script:p,sequence:4294967295,txid:is.decode(d.hash),value:BigInt(d.value)})}for(let d of t){let o="address"in d&&d.address?d.address:r,p=d.script;if(p&&!s)continue;if(p&&s)n.addOutput({amount:0n,script:s});else n.addOutputAddress(o,BigInt(d.value),a)}return{inputs:e,tx:n}}async function vs(){try{let e=await A(J.Zcash).getBlockHeight();return ls(e+1)}catch{return ms.IRONWOOD}}async function xn(e){let{assetValue:t,recipient:n,memo:r,feeRate:s,sender:a,fetchTxHex:d,sweep:o}=e,p=U(J.Zcash);if(!gn(a,p))throw new de("toolbox_utxo_invalid_address",{address:a});if(!gn(n,p))throw new de("toolbox_utxo_invalid_address",{address:n,error:"Zcash transaction creation currently supports transparent addresses only"});let c=r?E(r):null,u=await A(J.Zcash).getUtxos({address:a,fetchTxHex:d!==!1}),i=[{address:n,value:o?0:Number(t.getBaseValue("string"))},...c?[{script:c,value:0}]:[]],{inputs:l,outputs:h}=M({chain:J.Zcash,changeAddress:a,feeRate:s,inputs:u,outputs:i,sweep:o});if(!(l&&h))throw new de("toolbox_utxo_insufficient_balance",{assetValue:t,sender:a});let m=ps({consensusBranchId:await vs(),expiryHeight:0,lockTime:0,version:4,versionGroupId:gs.SAPLING}),{tx:f,inputs:y}=Us({compiledMemo:c,inputs:l,outputs:h,sender:a,tx:m});return{inputs:y,outputs:h,tx:f}}function Un(e={}){let t="scriptType"in e?e.scriptType:void 0,n=xs(e).with({signer:Ut.not(Ut.nullish)},({signer:c})=>c).with({phrase:Ut.string},({phrase:c,derivationPath:u,index:i=0})=>{let{derivationPath:l}=$e({chain:J.Zcash,derivationPath:u,index:i,scriptType:t}),h=cs(l);return Ps({derivationPath:h,phrase:c})}).otherwise(()=>{return}),r=ce({chain:J.Zcash,scriptType:t,signer:n});async function s(c){if(!n)throw new de("toolbox_utxo_no_signer");return await n.signTransaction(c)}async function a(c){let u=await s(c);return r.broadcastTx(u.toHex())}async function d({recipient:c,assetValue:u,feeOptionKey:i=ds.Fast,sweep:l,...h}){let m=await n?.getAddress();if(!(n&&m))throw new de("toolbox_utxo_no_signer");let f=h.feeRate||(await r.getFeeRates())[i],{tx:y}=await xn({...h,assetValue:u,feeRate:f,recipient:c,sender:m,sweep:l}),S=(await n.signTransaction(y)).toHex();return r.broadcastTx(S)}function o({phrase:c,derivationPath:u="m/44'/133'/0'/0/0"}){let i=wn(c),h=bn.fromMasterSeed(i).derive(u);if(!h.privateKey||!h.publicKey)throw new de("toolbox_utxo_invalid_params");return{privateKey:h.privateKey,publicKey:h.publicKey}}function p({phrase:c,derivationPath:u="m/44'/133'/0'/0/0"}){let i=o({derivationPath:u,phrase:c}),l=U(J.Zcash);return Ts(l).encode(i.privateKey)}return{...r,createKeysForPath:o,createTransaction:xn,getPrivateKeyFromMnemonic:p,signAndBroadcastTransaction:a,signTransaction:s,transfer:d,validateAddress:wt}}import{hex as _s}from"@scure/base";import{HDKey as As}from"@scure/bip32";import{derivationPathToString as Os,NetworkDerivationPath as Ss,updateDerivationPath as Cs}from"@swapkit/helpers";function Xs({xpub:e,chain:t,count:n,startIndex:r=0,accountIndex:s,purpose:a,scriptType:d}){if(z("count",n),n<1)throw RangeError("count must be at least 1");z("startIndex",r),Le(t,d),dt({chain:t,purpose:a,scriptType:d});let o=U(t),p=As.fromExtendedKey(e,o.bip32),c=a===void 0?void 0:Cs(Ss[t],{purpose:a}),u=te({accountIndex:s,chain:t,derivationPath:c}),i=pe(u),l=[];for(let h of[!1,!0]){let m=p.deriveChild(Number(h));for(let f=0;f<n;f++){let y=r+f,b=m.deriveChild(y);if(!b.publicKey)continue;let S=Ae({accountIndex:s,chain:t,change:h,derivationPath:c,index:y});l.push({accountIndex:i,address:De({chain:t,network:o,publicKey:b.publicKey,scriptType:d}),change:h,index:y,pubkey:_s.encode(b.publicKey),...a===void 0?{}:{path:Os(S)}})}}return l}function ga(e,t){switch(e){case we.BitcoinCash:return mn(t||{});case we.Zcash:return Un(t);case we.Bitcoin:case we.Dogecoin:case we.Litecoin:case we.Dash:return ce({chain:e,...t});default:throw new Bs("toolbox_utxo_not_supported",{chain:e})}}export{qt as InputSizes,ho as MIN_TX_FEE,Cr as OP_RETURN_OVERHEAD,lt as OutputSizes,Sr as SEGWIT_MARKER_FLAG_WEIGHT,ht as TX_OVERHEAD,oe as UTXOScriptType,Dt as UtxoNetwork,M as accumulative,ie as addInputsAndOutputs,dn as addressFromKeysGetter,z as assertDerivationIndex,ge as calculateTxSize,E as compileMemo,mn as createBCHToolbox,Hs as createCustomUtxoApi,Xn as createHDWalletHelpers,ce as createUTXOToolbox,Un as createZcashToolbox,Xs as deriveAddressesFromXpub,Vs as detectAddressNetwork,Se as getBchAddressType,ke as getDustThreshold,Be as getInputScriptType,se as getInputSize,bt as getMissingSpendingMetadata,U as getNetworkForChain,je as getOutputSize,Xr as getOutputSizeForAddress,Ye as getScriptTypeForAddress,pe as getUTXOAccountIndexFromPath,te as getUTXOAccountPath,Ae as getUTXOAddressPath,cn as getUTXOAddressValidator,Y as getUtxoAddressType,A as getUtxoApi,Rs as getUtxoNetwork,ga as getUtxoToolbox,Tt as getWitnessOverhead,Gr as getZcashAddressType,ft as isSegwitScriptType,$s as isValidAddress,Zt as nonSegwitChains,W as stripPrefix,et as stripToCashAddress,Me as toCashAddress,G as toLegacyAddress,Ne as tryDecodeAddress,Ie as validateBchAddress,tn as validateUtxoAddress,wt as validateZcashAddress};
1
+ import{ia as Ct,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,s]=r??Kr[t];return[n,o,e??s]}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(i){let{accountIndex:p,count:c,startIndex:u=0,change:a=!1}=i;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(i){let{gapLimit:p=20,change:c=!1}=i??{},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 s(i=20){let[p,c]=await Promise.all([o({change:!1,gapLimit:i}),o({change:!0,gapLimit:i})]),u=[...p,...c],a=await Promise.all(u.map(async(h)=>{let f=(await t(h.address)).reduce((y,b)=>y+b.getValue("number"),0);return{...h,balance:f}})),l=a.reduce((h,m)=>h+m.balance,0);return{addresses:a,total:l}}async function d(i=20){let[p,c]=await Promise.all([o({change:!1,gapLimit:i}),o({change:!0,gapLimit:i})]),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:s,getAggregatedUtxos:d,scanForAddresses:o}}import{Chain as C,getRPCUrl as Dr,RequestClient as Re,SKConfig as Ir,SwapKitError as R,warnOnce as Hr}from"@swapkit/helpers";import{NETWORKS as le}from"@swapkit/utxo-signer";async function Rr({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 s=await Dr(e);if(s){let d=JSON.stringify({id:Ct(),jsonrpc:"2.0",method:"sendrawtransaction",params:[t]}),i=await Re.post(s,{body:d,headers:{"Content-Type":"application/json"}});if(i.error)throw new R("toolbox_utxo_broadcast_failed",{error:i.error?.message});if(i.result.includes('"code":-26'))throw new R("toolbox_utxo_invalid_transaction",{error:"Transaction amount was too low"});return i.result}throw o}}function he(e){return`https://api.blockchair.com/${Er(e)}`}function Ot(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 Er(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,Ot(e))}catch{return Ot(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 Nr({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 Zr({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 zr=4294967294;async function Wr({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:s,inputs:d,outputs:i}=o,p=d.map((u)=>u.spending_sequence),c=s.is_rbf===!0||p.some((u)=>u<zr);return{blockId:s.block_id,confirmed:s.block_id!==-1,fee:s.fee,inputs:d,isRBF:c,outputs:i,sequences:p,size:s.size,txid:s.hash,weight:s.weight}}async function $r({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 Lr(e){return e.reduce((t,r)=>t+r.value,0)}function St(e,t){let r=[...e].sort((n,o)=>o.value-n.value);if(t){let n=[],o=0;for(let s of r)if(n.push(s),o+=s.value,o>=t)break;return n}return r}async function kt({chain:e,address:t,apiKey:r,targetValue:n,accumulativeValue:o=0,offset:s=0,limit:d=30}){if(!t)throw new R("toolbox_utxo_invalid_params",{error:"Address is required"});try{let i=await $r({address:t,apiKey:r,chain:e,limit:d,offset:s,targetValue:n}),c=i.length<d,u=i.filter(({is_spent:y})=>!y),a=Lr(u),l=o+a,h=n&&l>=n;if(c||h)return St(u,n);let m=await kt({accumulativeValue:l,address:t,apiKey:r,chain:e,limit:d,offset:s+d,targetValue:n}),f=[...u,...m];return St(f,n)}catch(i){let p=i instanceof Error?i.message:String(i);return console.error(`Failed to fetch unspent UTXOs: ${p}`),[]}}async function Vr({address:e,chain:t,apiKey:r,fetchTxHex:n=!0,targetValue:o}){let s=await kt({address:e,apiKey:r,chain:t,targetValue:o}),d=n?await Promise.all(s.map(({hash:i})=>Bt({apiKey:r,chain:t,txHash:i}))):[];return s.map(({hash:i,index:p,script_hex:c,value:u},a)=>({address:e,hash:i,index:p,txHex:n?d[a]:void 0,value:u,witnessUtxo:{script:Buffer.from(c,"hex"),value:u}}))}function A(e){let t=Ir.get("apiKeys").blockchair||"";return Hr({condition:!t,id:"no_blockchair_api_key_warning",warning:"No Blockchair API key found. Functionality will be limited."}),{broadcastTx:(r)=>Rr({chain:e,txHash:r}),getAddressData:(r)=>Xt({address:r,apiKey:t,chain:e}),getBalance:(r)=>Zr({address:r,apiKey:t,chain:e}),getBlockHeight:()=>Nr({apiKey:t,chain:e}),getRawTx:(r)=>Bt({apiKey:t,chain:e,txHash:r}),getSuggestedTxFee:()=>Mr(e),getTransactionDetails:(r)=>Wr({apiKey:t,chain:e,txHash:r}),getUtxos:(r)=>Vr({...r,apiKey:t,chain:e})}}function Yo(e){return e}function Go(){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 en}from"@noble/hashes/sha2.js";import{createBase58check as tn}from"@scure/base";import{SwapKitError as Ft}from"@swapkit/helpers";import{CashAddrType as Ee,decodeCashAddr as qr,encodeCashAddr as Yr}from"@swapkit/utxo-signer";var Gr={P2PKH:Ee.P2PKH,P2SH:Ee.P2SH},jr={[Ee.P2PKH]:"P2PKH",[Ee.P2SH]:"P2SH"};function Jr(e,t,r){return Yr({hash:r,prefix:e,type:Gr[t]})}function Qr(e){let t=qr(e),r=jr[t.type];if(!r)throw Error(`Unknown CashAddr type: ${t.type}`);return{hash:t.hash,prefix:t.prefix,type:r}}var st={decode:Qr,encode:Jr};var Dt=tn(en);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}}},rn={["p2pkh"]:"pkh",["p2sh"]:"sh"};function os(e){return Ne(e)!==void 0}function ss(e){return it(e).network}function G(e){let t=it(e);if(t.format==="legacy")return e;return sn(t)}function Me(e){let t=it(e);return an(t)}function Ne(e){if(typeof e!=="string")return;let t=nn(e)??on(e);return t&&{...t,scriptType:rn[t.type]}}function it(e){let t=Ne(e);if(!t)throw new Ft("toolbox_utxo_invalid_address",{address:e});return t}function nn(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 on(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 sn(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 an(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 Bn,UTXO_SCRIPT_TYPES as Vt,UTXOScriptType as Ye}from"@swapkit/helpers";import{Script as kn}from"@swapkit/utxo-signer";import{Chain as at}from"@swapkit/helpers";import{getAddressScriptType as dn,getTransparentZcashAddressType as un,getZcashAddressType as pn}from"@swapkit/utxo-signer";import{match as ln}from"ts-pattern";import{Chain as fe}from"@swapkit/helpers";import{NETWORKS as Te}from"@swapkit/utxo-signer";import{match as cn}from"ts-pattern";function U(e){return cn(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 W(e){return e.replace(/(bchtest:|bitcoincash:)/,"")}function Ce(e){if(typeof e!=="string")return null;let t=Ne(W(e));if(!t||t.network!=="mainnet")return null;return t.scriptType}var hn=["sprout","sapling","unified"];function fn(e){let t=un(e,U(at.Zcash));if(t)return t;let r=pn(e);return r&&hn.includes(r)?r:null}function j({address:e,chain:t}){return ln(t).with(at.BitcoinCash,()=>Ce(e)).with(at.Zcash,()=>fn(e)).otherwise(()=>dn(e,U(t)))}import{Chain as oe,derivationPathToString as Ht,getPurposeFromPath as Tn,getUTXOScriptTypeForPath as Rt,getUTXOScriptTypeForPurpose as Nt,resolveDerivationPath as mn,SwapKitError as Xe,UTXO_SCRIPT_TYPE_LIST as Et,UTXO_SCRIPT_TYPES as me,UTXOChains as yn,UTXOScriptType as O,updateDerivationPath as gn,warnOnce as xn}from"@swapkit/helpers";import{CashAddrPrefix as bn,CashAddrType as wn,encodeCashAddr as Pn,OutScript as Zt,p2pkh as Un,p2sh as _n,p2tr as vn,p2wpkh as Mt}from"@swapkit/utxo-signer";var Ze=Object.freeze([O.P2PKH]),An=Object.freeze({[oe.Bitcoin]:Et,[oe.BitcoinCash]:Ze,[oe.Dash]:Ze,[oe.Dogecoin]:Ze,[oe.Litecoin]:Et,[oe.Zcash]:Ze});function We(e){return An[e]}function ct(e){return We(e).some((t)=>me[t].witness)}function ye(e,t){return We(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: ${We(e).join(", ")}`,scriptType:t,supported:We(e)})}var zt=yn.filter((e)=>!ct(e));function On({purpose:e,scriptType:t}){let r=Nt(e);return r===void 0||r===t}function dt({chain:e,purpose:t,scriptType:r}){xn({condition:!On({purpose:t,scriptType:r}),id:`utxo_off_standard_encoding_${e}_${t}_${r}`,warning:`${e}: encoding m/${t}' keys as ${r}, not the ${Nt(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 i=Rt(t);throw new Xe("toolbox_utxo_invalid_params",{chain:e,derivationPath:Ht(t),error:`scriptType is required alongside derivationPath: getUTXOScriptTypeForPath gives the standard one${i?` (${i})`:""}, or state another deliberately.`})}return $e(e,n),dt({chain:e,purpose:Tn(t),scriptType:n}),{derivationPath:t,scriptType:n}}let o=mn({chain:e,index:r}),s=n?gn(o,{purpose:me[n].purpose}):o,d=n??Rt(s);if(!d)throw new Xe("toolbox_utxo_invalid_params",{chain:e,derivationPath:Ht(s),error:`${e}: the default derivation path has no standard script type`});return $e(e,d),{derivationPath:s,scriptType:d}}function Sn(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 Cn={[O.P2PKH]:(e,t)=>{let{address:r,script:n}=ze(Un(e,t),O.P2PKH);return{address:r,script:n}},[O.P2SH_P2WPKH]:(e,t)=>{let r=Mt(e,t),{address:n,script:o}=ze(_n(r,t),O.P2SH_P2WPKH);return{address:n,redeemScript:r.script,script:o}},[O.P2WPKH]:(e,t)=>{let{address:r,script:n}=ze(Mt(e,t),O.P2WPKH);return{address:r,script:n}},[O.P2TR]:(e,t)=>{let r=Sn(e),{address:n,script:o}=ze(vn(r,void 0,t),O.P2TR);return{address:n,script:o,tapInternalKey:r}}};function Ve(e,t,r){return Cn[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 Pn({hash:r.hash,prefix:bn.MAINNET,type:wn.P2PKH}).replace(/^bitcoincash:/,"")}var Xn=Object.freeze({pkh:O.P2PKH,sh:O.P2SH_P2WPKH,tr:O.P2TR,wpkh:O.P2WPKH}),Wt=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 Wt}function Lt(e){return $t(e)?Wt[e]:void 0}function Be(e){return Xn[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 _s=1000,ht=10,Kn=2,Fn=10;function E(e){let t=new Uint8Array(Buffer.from(e,"utf8"));return kn.encode(["RETURN",t])}function qt(e){return Object.fromEntries(Bn.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},Dn=(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,s=n?t.filter((u)=>u.value>=Yt["type"in u&&u.type?u.type:Ye.P2PKH]*Math.ceil(n)):t,d=0,i=0;for(let u of s)if(d+=se(u,e),!ft(ke(u,e)))i++;let p=r?.reduce((u,a)=>u+je(a,e),0)||lt[o],c=i<s.length;return ht+d+p+Tt(c,i)},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((Kn+t)/4):0,je=(e,t,r)=>{if(e?.script)return Fn+e.script.length+(e.script.length>=74?2:1);if(r)return lt[r];if("address"in e&&e.address)return Dn(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 M({inputs:e,outputs:t,feeRate:r=1,chain:n=ae.Bitcoin,changeAddress:o="",sweep:s=!1}){let d=Ke(n),i=e.filter((f)=>{let y=se(f,n)*r;return s?f.value>Math.max(y,d):y<=f.value});if(s){let f=Math.ceil(r*ge({chain:n,inputs:i,outputs:t})),y=i.reduce((X,q)=>X+q.value,0),b=y-f;if(b<=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:i,outputs:t.map((X,q)=>q===S?{...X,value:b}: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 i){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,b=y+c;if(h<b)continue;let S=h-b,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 In}from"@noble/curves/secp256k1.js";import{base64 as Hn,utf8 as Gt}from"@scure/base";import{SwapKitError as Rn,UTXOScriptType as yt}from"@swapkit/helpers";import{CompactSize as En,utils as Mn}from"@swapkit/utxo-signer";var Nn=Gt.decode(`\x18Bitcoin Signed Message:
2
+ `),jt={[yt.P2PKH]:31,[yt.P2SH_P2WPKH]:35,[yt.P2WPKH]:39};function Zn(e){return jt[e]!==void 0}function zn(e){let t=Gt.decode(e);return Mn.sha256x2(Nn,En.encode(BigInt(t.length)),t)}function Jt({message:e,privateKey:t,scriptType:r}){let n=jt[r];if(n===void 0)throw new Rn("toolbox_utxo_unsupported_script_type",{error:`BIP-137 message signatures cannot express a ${r} address`,scriptType:r});let o=In.sign(zn(e),t,{format:"recovered",prehash:!1}),[s=0]=o,d=new Uint8Array(65);return d[0]=n+s,d.set(o.subarray(1),1),Hn.encode(d)}import{Chain as Pe,SwapKitError as zo}from"@swapkit/helpers";import{hex as hr}from"@scure/base";import{Chain as uo,derivationPathToString as po,FeeOption as lo,resolveDerivationPath as ho,SwapKitError as L}from"@swapkit/helpers";import{BCHSigHash as fo,CashAddrPrefix as fr,CashAddrType as Tr,encodeCashAddr as mr,NETWORKS as To,p2pkh as yr,Transaction as gr}from"@swapkit/utxo-signer";import{secp256k1 as Wn}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 $n,SwapKitError as P,SwapKitNumber as Ln,UTXO_SCRIPT_TYPES as Vn,warnOnce as qn}from"@swapkit/helpers";import{BCHSigHash as nr,RBF_SEQUENCE as Yn,SigHash as er,Transaction as Je,utils as Gn,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 jn({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 Wn.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 s=U(r);if(n){let c=or(s).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($n[r]),i=jn({derivationPath:d,network:s,phrase:e,seed:o}),p=xt(i);return{privateKey:i,publicKey:p}}function Jn(e,t){return or(U(t)).encode(e)}function Qn({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 s=U(r),d=n??bt(e),i=rr.fromMasterSeed(d,s.bip32),p=o.slice(0,4).join("/");return i.derive(p)}function eo(e,t){if(!e||!Vn[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 s=Ve(o,r,n);if(Gn.compareBytes(s.script,t)!==0)return{};return o===ie.P2TR?{tapInternalKey:s.tapInternalKey}:{redeemScript:s.redeemScript}}function to(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 s=ut(t,Ve(o,r,U(t)));return t===be.BitcoinCash?W(s)===W(e):s===e}function ro(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 s=o??Array.from({length:t.inputsLength},(i,p)=>p),d=[];for(let i of s){let p=t.getInput(i),c=ro(p);if(!c)continue;let{redeemScript:u,tapInternalKey:a}=ir({chain:e,network:n,publicKey:r,script:c}),l={index:i};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:s,enableRBF:d=!1}){let i=U(r),p=ct(r),c=d?Yn: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:i,publicKey:a.publicKey,script:a.witnessUtxo.script}):{};if(p&&a.witnessUtxo&&eo(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(s)n.addOutput({amount:0n,script:s});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),i)}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:s=!1,publicKey:d},i,{forEstimateOnly:p=!1}={}){let c=e.chain,u=Ge(n,c),a=u===ie.P2PKH||u===ie.P2SH_P2WPKH&&!to(n,c,d),l=s||!p&&a,h=e.getBaseValue("number"),m=o?void 0:i??(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:E(r),value:0}]:[]]}}async function cr({assetValue:e,recipient:t,memo:r,feeRate:n,sender:o,fetchTxHex:s=!1,enableRBF:d=!1,sweep:i,publicKey:p}){let c=e.chain,u=r?E(r):null,a=await ar({assetValue:e,fetchTxHex:s,memo:r,publicKey:p,recipient:t,sender:o,sweep:i},n),{inputs:l,outputs:h}=M({...a,chain:c,changeAddress:o,feeRate:n,sweep:i});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:b}=ce({chain:c,compiledMemo:u,enableRBF:d,inputs:m,outputs:h,sender:o,tx:f});return{inputs:y,tx:b,utxos:a.inputs}}async function dr({assetValue:e,feeOptionKey:t=N.Fast,feeRate:r,memo:n,sender:o,recipient:s,sweep:d}){let i=e.chain,p,c;if(r!==void 0)p=r,c=Math.floor(r);else{let a=await we(i);p=a[N.Fastest],c=a[t]}let u=await ar({assetValue:e,memo:n,recipient:s,sender:o,sweep:d},p,{forEstimateOnly:!0});return M({...u,chain:i,changeAddress:o,feeRate:c,sweep:d})}function no(e){return async function({from:r,memo:n,feeRate:o,feeOptionKey:s=N.Fast,recipient:d=r,recipients:i=1}){let p=o??(await we(e))[s],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 i==="number"?Math.max(i,1):i.length,l=typeof i==="number"||a===0?Array.from({length:a||1},()=>({address:d,value:0})):[...i];if(n)l.push({address:r,script:E(n),value:0});let{outputs:h}=M({chain:e,feeRate:p,inputs:u,outputs:l,sweep:!0}),m=h?.[0]?.value??0;return gt.from({chain:e,value:BigInt(m)})}}function oo(e){return async function(r){let{fee:n}=await dr(r);return gt.from({chain:e,value:Ln.fromBigInt(BigInt(n),8).getValue("string")})}}function so({chain:e,phrase:t,derivationPath:r,scriptType:n,seed:o}){let s=U(e),{privateKey:d,publicKey:i}=xe({chain:e,derivationPath:r,phrase:t,seed:o}),p=ur(e);return{getAddress:()=>De({chain:e,network:s,publicKey:i,scriptType:n}),privateKey:d,publicKey:i,signTransaction:(c)=>{for(let{index:u,...a}of wt({chain:e,network:s,publicKey:i,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 io(e,t,r){return async function({memo:o,recipient:s,feeOptionKey:d,feeRate:i,assetValue:p,enableRBF:c=!1,sweep:u}){let a=await t?.getAddress();if(!(t&&a))throw new P("toolbox_utxo_no_signer");if(!s)throw new P("toolbox_utxo_invalid_params",{error:"Recipient address must be provided"});qn({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=i||(await we(e))[d||N.Fast],{tx:m}=await cr({assetValue:p,enableRBF:l,feeRate:h,memo:o,publicKey:r,recipient:s,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 ao(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,s=n?bt(n):void 0,{derivationPath:d,scriptType:i}=Le({chain:t,derivationPath:r?.derivationPath,index:o,scriptType:e.scriptType}),p=Fe(d),c=n?so({chain:t,derivationPath:p,phrase:n,scriptType:i,seed:s}):void 0,u=r?void 0:e.signer,a=c||u,l=n?xe({chain:t,derivationPath:p,phrase:n,seed:s}):void 0,h=l?.publicKey??ao(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 Qn({chain:t,derivationPath:Fe(g),phrase:n,seed:s})}let y=f();function b(){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 x=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:i}),F=J.encode(I.publicKey);return{accountIndex:pe(x),address:B,change:w,index:g,path:Fe(x),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 x=await A(t).getTransactionDetails(T);if(!x.isRBF)throw new P("toolbox_utxo_tx_not_replaceable",{txid:T});if(x.confirmed)throw new P("toolbox_utxo_tx_already_confirmed",{blockId:x.blockId,txid:T});let K=x.inputs.reduce((_,D)=>_+D.value,0),B=x.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(x.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?E(v):null,ee=K-B-x.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<=x.fee)throw new P("toolbox_utxo_rbf_fee_too_low",{newFee:Y,originalFee:x.fee});let ve=Y-x.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:x.fee,tx:Ae}}async function Or({txid:T,newFeeRate:g,recipient:w,memo:v}){let{tx:x,originalFee:K,newFee:I}=await Ue({memo:v,newFeeRate:g,recipient:w,txid:T}),B=await tt(x);B.finalize();let F=await A(t).broadcastTx(J.encode(B.extract()));return{newFee:I,originalFee:K,txid:F}}function vt({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 At({tx:T,inputDerivations:g}){if(!y)throw new P("toolbox_utxo_no_signer");let w=ur(t),v=U(t);for(let x=0;x<g.length;x++){let K=g[x];if(!K)continue;let{derivationIndex:I,isChange:B}=K,F=vt({change:B,index:I});if(!F)throw new P("toolbox_utxo_invalid_params",{error:`Could not derive private key for input ${x} at index ${I}`});for(let{index:H,...ee}of wt({chain:t,indexes:[x],network:v,publicKey:xt(F),tx:T}))T.updateInput(H,ee);T.signIdx(F,x,w)}return T}async function Sr({utxos:T,recipient:g,assetValue:w,memo:v,feeRate:x,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=x||(await we(t))[K||N.Fast],H=v?E(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}=M({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}),At({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}),x=X({change:!0,index:w}),K=v?.address===T?!1:x?.address===T;if(v?.address===T||x?.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:i}):void 0;async function Br(T){let g=await tt(T);return g.finalize(),await A(t).broadcastTx(J.encode(g.extract()))}return{accumulative:M,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:vt,estimateMaxSendableAmount:no(t),estimateTransactionFee:oo(t),getAddress:m,getAddressFromKeys:lr(t,{scriptType:i}),getAddressType:(T)=>j({address:T,chain:t}),getBalance:tr(t),getExtendedPublicKey:b,getExtendedPublicKeyInfo:S,getFeeRates:()=>we(t),getInputsOutputsFee:dr,getNetworkForChain:()=>U(t),getPrivateKeyFromMnemonic:(T)=>Jn(xe({...T,chain:t}).privateKey,t),isRBFEnabled:q,keys:l,resolveDerivationIndex:Cr,scriptType:i,signAndBroadcastTransaction:Br,signMessage:Xr,signTransaction:tt,signTransactionWithMultipleKeys:At,transfer:io(t,a,h),transferFromMultipleAddresses:Sr,validateAddress:pr(t)}}import{getZcashAddressType as co,validateZcashAddress as Pt}from"@swapkit/utxo-signer";function Ie(e){return Ce(e)!==null}var Z=uo.BitcoinCash;function et(e){return W(Me(e))}function mo(e){let t=U(Z);function r(o){return o.sign(e.privateKey,[fo.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 s=mr({hash:o.hash,prefix:fr.MAINNET,type:Tr.P2PKH});return Promise.resolve(s.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=ho({chain:Z,derivationPath:n,index:r}),s=po(o),d=t?xe({chain:Z,derivationPath:s,phrase:t}):void 0,i=d?mo(d):("signer"in e)?e.signer:void 0;function p(){return Promise.resolve(i?.getAddress())}let c="scriptType"in e?e.scriptType:void 0,{getBalance:u,getFeeRates:a,broadcastTx:l,...h}=de(t?{chain:Z,index:r,phrase:t,...n?{derivationPath:n,scriptType:c}:{scriptType:c}}:{chain:Z,scriptType:c});function m(b,S=!0){return u(W(Me(b)))}function f(b){if(!i)throw new L("toolbox_utxo_no_signer");return i.signTransaction(b)}async function y(b){let S=await f(b);return S.finalize(),await l(hr.encode(S.extract()))}return{...h,broadcastTx:l,buildTx:go,createTransaction:br,getAddress:p,getAddressFromKeys:xo,getBalance:m,getFeeRates:a,signAndBroadcastTransaction:y,signTransaction:f,stripPrefix:W,stripToCashAddress:et,transfer:yo({broadcastTx:l,getFeeRates:a,signer:i}),validateAddress:Ie}}async function br({assetValue:e,recipient:t,memo:r,feeRate:n,sender:o,sweep:s}){if(!Ie(t))throw new L("toolbox_utxo_invalid_address",{address:t});let d=Math.ceil(e.getBaseValue("number")+n*7500),i=await A(Z).getUtxos({address:et(o),fetchTxHex:!0,targetValue:s?void 0:d}),p=r?E(r):null,c=[],u=G(t);if(c.push({address:u,value:s?0:e.getBaseValue("number")}),p)c.push({script:p,value:0});let{inputs:a,outputs:l}=M({chain:Z,feeRate:n,inputs:i,outputs:c,sweep:s});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:Z,compiledMemo:p,inputs:a,outputs:l.map((b)=>("address"in b)&&b.address?{...b,address:G(b.address)}:b),sender:m,tx:h});return{inputs:f,tx:y,utxos:a}}function yo({broadcastTx:e,getFeeRates:t,signer:r}){return async function({recipient:o,assetValue:s,feeOptionKey:d=lo.Fast,sweep:i,...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:s,feeRate:u,recipient:o,sender:c,sweep:i}),l=await r.signTransaction(a);return l.finalize(),e(hr.encode(l.extract()))}}async function go({assetValue:e,recipient:t,memo:r,feeRate:n,sender:o}){let s=Me(t);if(!Ie(s))throw new L("toolbox_utxo_invalid_address",{address:s});let d=Math.ceil(e.getBaseValue("number")+n*7500),i=await A(Z).getUtxos({address:et(o),fetchTxHex:!0,targetValue:d}),p=Number(n.toFixed(0)),c=r?E(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}=M({chain:Z,feeRate:p,inputs:i,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:Z,compiledMemo:c,inputs:a,outputs:l,sender:G(o),tx:h});return{inputs:m,tx:f,utxos:i}}function xo(e){let t=To.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 bo,hex as wo}from"@scure/base";import{HDKey as Ur}from"@scure/bip32";import{mnemonicToSeedSync as _r}from"@scure/bip39";import{Chain as V,derivationPathToString as Po,FeeOption as Uo,SwapKitError as Q}from"@swapkit/helpers";import{Address as _o,createZcashTransaction as vo,getZcashTransactionFormat as Ao,isTransparentZcashAddress as wr,OutScript as Oo,PCZT as So,utils as vr,WIF as Co,ZcashPSBT as Xo,ZcashSigHash as Ut}from"@swapkit/utxo-signer";import{match as Bo,P as _t}from"ts-pattern";var ko=bo(vr.sha256);function Ko(e){return ko.encode(e)}function Fo({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:s,publicKey:d}=o,i=vr.hash160(d),p=new Uint8Array([28,184]),c=new Uint8Array(p.length+i.length);c.set(p,0),c.set(i,p.length);let u=Ko(c);return{getAddress:()=>Promise.resolve(u),signTransaction:(a)=>{if(a instanceof Xo){let l=a.toPCZT();return l.signAllInputs(s,d,Ut.ALL),l.finalizeAllInputs(),Promise.resolve(l.extract())}if(a instanceof So)return a.signAllInputs(s,d,Ut.ALL),a.finalizeAllInputs(),Promise.resolve(a.extract());return a.signAllInputs(s,d,Ut.ALL),Promise.resolve(a)}}}function Do({inputs:e,outputs:t,tx:r,sender:n,compiledMemo:o}){let s=U(V.Zcash);for(let d of e){let i=_o(s).decode(n),p=Oo.encode(i);r.addInput({index:d.index,script:p,sequence:4294967295,txid:wo.decode(d.hash),value:BigInt(d.value)})}for(let d of t){let i="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(i,BigInt(d.value),s)}return{inputs:e,tx:r}}async function Io(){try{let e=await A(V.Zcash).getBlockHeight();return Ao(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:s,fetchTxHex:d,sweep:i}=e,p=U(V.Zcash);if(!wr(s,p))throw new Q("toolbox_utxo_invalid_address",{address:s});if(!wr(r,p))throw new Q("toolbox_utxo_invalid_address",{address:r,error:"Zcash transaction creation currently supports transparent addresses only"});let c=n?E(n):null,u=await A(V.Zcash).getUtxos({address:s,fetchTxHex:d!==!1}),a=[{address:r,value:i?0:Number(t.getBaseValue("string"))},...c?[{script:c,value:0}]:[]],{inputs:l,outputs:h}=M({chain:V.Zcash,changeAddress:s,feeRate:o,inputs:u,outputs:a,sweep:i});if(!(l&&h))throw new Q("toolbox_utxo_insufficient_balance",{assetValue:t,sender:s});let m=vo({...await Io(),expiryHeight:0,lockTime:0}),{tx:f,inputs:y}=Do({compiledMemo:c,inputs:l,outputs:h,sender:s,tx:m});return{inputs:y,outputs:h,tx:f}}function Ar(e={}){let t="scriptType"in e?e.scriptType:void 0,r=Bo(e).with({signer:_t.not(_t.nullish)},({signer:c})=>c).with({phrase:_t.string},({phrase:c,derivationPath:u,index:a=0})=>{let{derivationPath:l}=Le({chain:V.Zcash,derivationPath:u,index:a,scriptType:t}),h=Po(l);return Fo({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 s(c){let u=await o(c);return n.broadcastTx(u.toHex())}async function d({recipient:c,assetValue:u,feeOptionKey:a=Uo.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 i({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=i({derivationPath:u,phrase:c}),l=U(V.Zcash);return Co(l).encode(a.privateKey)}return{...n,createKeysForPath:i,createTransaction:Pr,getPrivateKeyFromMnemonic:p,signAndBroadcastTransaction:s,signTransaction:o,transfer:d,validateAddress:Pt}}import{hex as Ho}from"@scure/base";import{HDKey as Ro}from"@scure/bip32";import{derivationPathToString as Eo,NetworkDerivationPath as Mo,updateDerivationPath as No}from"@swapkit/helpers";function Zo({xpub:e,chain:t,count:r,startIndex:n=0,accountIndex:o,purpose:s,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:s,scriptType:d});let i=U(t),p=Ro.fromExtendedKey(e,i.bip32),c=s===void 0?void 0:No(Mo[t],{purpose:s}),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,b=m.deriveChild(y);if(!b.publicKey)continue;let S=Oe({accountIndex:o,chain:t,change:h,derivationPath:c,index:y});l.push({accountIndex:a,address:De({chain:t,network:i,publicKey:b.publicKey,scriptType:d}),change:h,index:y,pubkey:Ho.encode(b.publicKey),...s===void 0?{}:{path:Eo(S)}})}}return l}function Ii(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 zo("toolbox_utxo_not_supported",{chain:e})}}export{Yt as InputSizes,_s as MIN_TX_FEE,Fn as OP_RETURN_OVERHEAD,lt as OutputSizes,Kn as SEGWIT_MARKER_FLAG_WEIGHT,ht as TX_OVERHEAD,ie as UTXOScriptType,It as UtxoNetwork,M as accumulative,ce as addInputsAndOutputs,lr as addressFromKeysGetter,z as assertDerivationIndex,ge as calculateTxSize,Zn as canSignBitcoinMessage,E as compileMemo,xr as createBCHToolbox,Yo as createCustomUtxoApi,Fr as createHDWalletHelpers,de as createUTXOToolbox,Ar as createZcashToolbox,Zo as deriveAddressesFromXpub,ss as detectAddressNetwork,Ce as getBchAddressType,Ke as getDustThreshold,ke as getInputScriptType,se as getInputSize,wt as getMissingSpendingMetadata,U as getNetworkForChain,je as getOutputSize,Dn as getOutputSizeForAddress,Ge as getScriptTypeForAddress,pe as getUTXOAccountIndexFromPath,re as getUTXOAccountPath,Oe as getUTXOAddressPath,pr as getUTXOAddressValidator,j as getUtxoAddressType,A as getUtxoApi,Go as getUtxoNetwork,Ii as getUtxoToolbox,Tt as getWitnessOverhead,co as getZcashAddressType,ft as isSegwitScriptType,os as isValidAddress,zt as nonSegwitChains,W as stripPrefix,et as stripToCashAddress,Me as toCashAddress,G as toLegacyAddress,Ne as tryDecodeAddress,Ie as validateBchAddress,sr as validateUtxoAddress,Pt as validateZcashAddress};
@@ -2,7 +2,7 @@ import type { ChainSigner, DerivationPathArray, FeeOption, GenericCreateTransact
2
2
  import { Chain } from "@swapkit/helpers";
3
3
  import type { AuthorizationLike, BigNumberish, BrowserProvider, JsonFragment, JsonRpcSigner, Provider, Signer, TransactionRequest, TypedDataField } from "ethers";
4
4
  import type { getProvider } from "./index";
5
- import type { ADIToolbox, ARBToolbox, ARCToolbox, AURORAToolbox, AVAXToolbox, BASEToolbox, BERAToolbox, BSCToolbox, COREToolbox, CORNToolbox, CROToolbox, ETHToolbox, GNOToolbox, HOODToolbox, HYPEREVMToolbox, LINEAToolbox, MATICToolbox, MEGAETHToolbox, MONADToolbox, OPToolbox, PLASMAToolbox, SONICToolbox, UNIToolbox, XLayerToolbox } from "./toolbox";
5
+ import type { ADIToolbox, ARBToolbox, ARCToolbox, AURORAToolbox, AVAXToolbox, BASEToolbox, BERAToolbox, BotanixToolbox, BSCToolbox, COREToolbox, CORNToolbox, CROToolbox, ETHToolbox, GNOToolbox, HOODToolbox, HYPEREVMToolbox, LINEAToolbox, MATICToolbox, MEGAETHToolbox, MONADToolbox, OPToolbox, PLASMAToolbox, SONICToolbox, UNIToolbox, XLayerToolbox } from "./toolbox";
6
6
  export declare enum EthNetwork {
7
7
  Test = "goerli",
8
8
  Main = "homestead"
@@ -107,7 +107,7 @@ export type EVMToolboxes = {
107
107
  [Chain.Base]: ReturnType<typeof BASEToolbox>;
108
108
  [Chain.Berachain]: ReturnType<typeof BERAToolbox>;
109
109
  [Chain.BinanceSmartChain]: ReturnType<typeof BSCToolbox>;
110
- [Chain.Botanix]: ReturnType<typeof SONICToolbox>;
110
+ [Chain.Botanix]: ReturnType<typeof BotanixToolbox>;
111
111
  [Chain.Core]: ReturnType<typeof COREToolbox>;
112
112
  [Chain.Corn]: ReturnType<typeof CORNToolbox>;
113
113
  [Chain.Cronos]: ReturnType<typeof CROToolbox>;
@@ -156,6 +156,7 @@ export declare function toolboxFor(scriptType: FlowScriptType): {
156
156
  } | undefined;
157
157
  scriptType: UTXOScriptType;
158
158
  signAndBroadcastTransaction: (tx: InstanceType<typeof Transaction>) => Promise<string>;
159
+ signMessage: ((message: string) => Promise<string>) | undefined;
159
160
  signTransaction: (tx: InstanceType<typeof Transaction>) => Transaction | Promise<Transaction>;
160
161
  signTransactionWithMultipleKeys: ({ tx, inputDerivations, }: {
161
162
  tx: InstanceType<typeof Transaction>;
@@ -1,4 +1,5 @@
1
1
  export * from "./api";
2
2
  export * from "./bchaddrjs";
3
3
  export * from "./coinselect";
4
+ export { canSignBitcoinMessage } from "./messageSigning";
4
5
  export * from "./txSize";
@@ -0,0 +1,7 @@
1
+ import { UTXOScriptType } from "@swapkit/helpers";
2
+ export declare function canSignBitcoinMessage(scriptType: UTXOScriptType): boolean;
3
+ export declare function signBitcoinMessage({ message, privateKey, scriptType, }: {
4
+ message: string;
5
+ privateKey: Uint8Array;
6
+ scriptType: UTXOScriptType;
7
+ }): string;
@@ -111,6 +111,7 @@ export declare function createBCHToolbox<T extends typeof Chain.BitcoinCash>(too
111
111
  index: number;
112
112
  } | undefined;
113
113
  scriptType: import("@swapkit/helpers").UTXOScriptType;
114
+ signMessage: ((message: string) => Promise<string>) | undefined;
114
115
  signTransactionWithMultipleKeys: ({ tx, inputDerivations, }: {
115
116
  tx: InstanceType<typeof Transaction>;
116
117
  inputDerivations: import("..").InputDerivation[];
@@ -207,6 +207,7 @@ export declare function createUTXOToolbox<T extends UTXOChain>(toolboxParams: (U
207
207
  } | undefined;
208
208
  scriptType: UTXOScriptType;
209
209
  signAndBroadcastTransaction: (tx: InstanceType<typeof Transaction>) => Promise<string>;
210
+ signMessage: ((message: string) => Promise<string>) | undefined;
210
211
  signTransaction: (tx: InstanceType<typeof Transaction>) => Transaction | Promise<Transaction>;
211
212
  signTransactionWithMultipleKeys: ({ tx, inputDerivations, }: {
212
213
  tx: InstanceType<typeof Transaction>;
@@ -116,6 +116,7 @@ export declare function createZcashToolbox(toolboxParams?: {
116
116
  index: number;
117
117
  } | undefined;
118
118
  scriptType: import("@swapkit/helpers").UTXOScriptType;
119
+ signMessage: ((message: string) => Promise<string>) | undefined;
119
120
  signTransactionWithMultipleKeys: ({ tx, inputDerivations, }: {
120
121
  tx: InstanceType<typeof import("@swapkit/utxo-signer").Transaction>;
121
122
  inputDerivations: import("..").InputDerivation[];
package/package.json CHANGED
@@ -1,5 +1,5 @@
1
1
  {
2
- "dependencies": { "@swapkit/helpers": "6.3.0", "@swapkit/utxo-signer": "3.1.1" },
2
+ "dependencies": { "@swapkit/helpers": "6.4.0", "@swapkit/utxo-signer": "3.2.0" },
3
3
  "description": "SwapKit - Toolboxes",
4
4
  "devDependencies": {
5
5
  "@aptos-labs/ts-sdk": "7.0.1",
@@ -16,7 +16,6 @@
16
16
  "@nomicfoundation/hardhat-ethers": "4.0.10",
17
17
  "@nomicfoundation/hardhat-network-helpers": "3.0.7",
18
18
  "@nomicfoundation/hardhat-toolbox": "7.0.0",
19
- "@orbs-network/ton-access": "2.3.3",
20
19
  "@polkadot/api": "16.5.6",
21
20
  "@polkadot/keyring": "14.0.3",
22
21
  "@polkadot/types": "16.5.6",
@@ -90,7 +89,6 @@
90
89
  "@near-js/utils": "2.5.1",
91
90
  "@noble/curves": "2.2.0",
92
91
  "@noble/hashes": "2.2.0",
93
- "@orbs-network/ton-access": "2.3.3",
94
92
  "@polkadot/api": "16.5.6",
95
93
  "@polkadot/keyring": "14.0.3",
96
94
  "@polkadot/rpc-provider": "16.5.6",
@@ -135,5 +133,5 @@
135
133
  "type-check:go": "tsgo"
136
134
  },
137
135
  "type": "module",
138
- "version": "6.4.1"
136
+ "version": "6.5.0"
139
137
  }
@@ -1,2 +0,0 @@
1
- import{ja as Se}from"./chunk-qk8kg62t.js";import{ka as ye}from"./chunk-pz8xe0qj.js";import{Chain as x}from"@swapkit/helpers";import{match as On}from"ts-pattern";import{Chain as g,getChainConfig as J,getRPCUrl as Ct,SKConfig as Ft,SwapKitError as z}from"@swapkit/helpers";import{FallbackProvider as At,getAddress as _e,Interface as Mt,JsonRpcProvider as se,Network as Gt}from"ethers";import{match as Ce}from"ts-pattern";function Bt(e){return new se(e)}async function kn(e,t){return Bt(t||await Ct(e))}function Fe(e){let t=Ft.get("rpcUrls")[e]?.filter(Boolean)??[];if(t.length===0)throw new z("helpers_chain_no_public_or_set_rpc_url",{chain:e});let{chainId:n}=J(e),o=Gt.from(Number(n)),[a]=t;if(t.length===1)return new se(a,o,{staticNetwork:o});return new At(t.map((r,i)=>({priority:i+1,provider:new se(r,o,{staticNetwork:o}),stallTimeout:2000})),o,{quorum:1})}function B(e){return e>0n?`0x${e.toString(16)}`:"0x0"}function Ae(e){let{explorerUrl:t,chainIdHex:n,rpcUrls:o}=J(e);return function(){return e!==g.Ethereum?{...Ot({chain:e}),blockExplorerUrls:[t],chainId:n,rpcUrls:o}:void 0}}function Me(e){return![g.Adi,g.Arbitrum,g.BinanceSmartChain,g.Robinhood].includes(e)}function Ot({chain:e}){let{name:t,nativeCurrency:n,baseDecimal:o}=J(e);return Ce(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 Ge(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 Ee=(e)=>typeof e==="string"&&/^0x[a-fA-F0-9]{64}$/.test(e),It=(e)=>{try{return typeof e==="string"&&!!_e(e)}catch{return!1}};function Vt(e,t){let n=t!==void 0?`index ${t}: `:"",o=(a,r)=>{throw new z({errorKey:"toolbox_evm_invalid_eip7702_authorization",info:{field:a,message:`${n}${r}`}})};Ce(e).when(({chainId:a})=>typeof a!=="bigint",()=>o("chainId","chainId must be a bigint")).when(({address:a})=>!It(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})=>!Ee(a?.r),()=>o("signature.r","r must be a 32-byte hex string")).when(({signature:a})=>!Ee(a?.s),()=>o("signature.s","s must be a 32-byte hex string")).otherwise(()=>{})}function Be(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=Be(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 z({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 Nn({chain:e,abi:t,data:n,to:o}){let r=new Mt(t).parseTransaction({data:n});if(!r)throw new z({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:_e(o)},y=Be(u);return{domain:u,message:c,primaryType:s,types:{EIP712Domain:y,...i}}}function Ie(e,t){if(!Array.isArray(e)||e.length===0)throw new z({errorKey:"toolbox_evm_invalid_eip7702_authorization",info:{message:"EIP-7702 transactions require at least one authorization"}});for(let[n,o]of e.entries())if(Vt(o,n),t!==void 0&&o.chainId!==t)throw new z({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 Cn,FeeOption as Fn,resolveDerivationPath as An}from"@swapkit/helpers";import{HDNodeWallet as Mn}from"ethers";import{match as Gn,P as ot}from"ts-pattern";var Ve=[{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 St,applyFeeMultiplierToBigInt as M,Chain as O,EVMChains as Rt,FeeOption as d,isGasAsset as kt,SwapKitError as m,SwapKitNumber as Q}from"@swapkit/helpers";import{erc20ABI as K}from"@swapkit/helpers/contracts";import{BrowserProvider as Nt,Contract as Ne,getAddress as ee,getBytes as Lt,Interface as Le,isError as U,resolveAddress as Dt,Transaction as pe}from"ethers";import{match as De}from"ts-pattern";function Y(e){return{getBalance:Se(e)}}function Hn(e){return e}var be=BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff");function te({chain:e=O.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:en({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:fn({chain:e,provider:t,signer:n}),createContract:Ht({chain:e,provider:t}),createContractTxObject:W({chain:e,provider:t}),createTransaction:s,createTransferTx:s,EIP1193SendTransaction:oe(t),estimateCall:je({provider:t,signer:n}),estimateGasLimit:nn({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:Ae(e),isApproved:Zt({chain:e,provider:t}),sendTransaction:Xe({chain:e,estimateGasPrices:i,isEIP1559Compatible:o,provider:t,signer:n}),signAuthorization:on({signer:n}),signMessage:n?(c)=>n.signMessage(c):void 0,signTypedData:n?async(c)=>{let{domain:l,types:u,value:y}=Oe(c);return await n.signTypedData(l,u,y)}:void 0,transfer:tn({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 Nt}function ge(e,t,n){return new Ne(e,Le.from(t),n)}function Ht({provider:e}){return function(n,o){return new Ne(n,Le.from(o),e)}}var zt=["payable","nonpayable"];function Kt({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&&zt.includes(n.stateMutability)}function Jn(e){return ee(e)}var qt=30000,Re=new WeakMap,ke=()=>{};function jt(e,t,n){let o=Date.now();for(let[r,i]of e)if(i.held===0&&o-i.at>qt)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 Ue({address:e,nonce:t,provider:n}){if(t!==void 0&&t!==null)return{nonce:t,release:ke,settle:ke};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}=jt(a,r,i),l=!1,u=(y)=>{if(l)return;if(l=!0,s.held-=1,s.at=Date.now(),y)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(U(e,"NONCE_EXPIRED")||U(e,"REPLACEMENT_UNDERPRICED"))return!0;let t=Z(e);return/nonce (?:is )?too low/.test(t)||t.includes("replacement transaction underpriced")}function de(e){let t=Z(e);return t.includes("already known")||t.includes("known transaction")||t.includes("already imported")}function He(e){return U(e,"NETWORK_ERROR")||U(e,"SERVER_ERROR")||U(e,"TIMEOUT")}function Wt(e){return He(e)||U(e,"UNSUPPORTED_OPERATION")}function ze(e){return He(e)||de(e)}function Ke(e,t){return e.getTransaction(t).then((n)=>n!==null,()=>!1)}async function Xt({provider:e,signer:t,txObject:n}){try{let o=pe.from(await t.signTransaction(n)).hash;return o&&await Ke(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,y={...u,...t&&i!==void 0&&{gas:B(BigInt(i))},...t&&s!==void 0&&{gasPrice:B(BigInt(s))},...t&&c!==void 0&&{maxFeePerGas:B(BigInt(c))},...t&&l!==void 0&&{maxPriorityFeePerGas:B(BigInt(l))},value:B(BigInt(o||0))};return e.send("eth_sendTransaction",[y])}}function Yn(e,t){let n=xe(e,t);if(n)return ee(n.toLowerCase());throw new m("toolbox_evm_invalid_gas_asset_address")}var $t=Rt.reduce((e,t)=>(e[t]="0x0000000000000000000000000000000000000000",e),{}),Jt={...$t,[O.Optimism]:"0x4200000000000000000000000000000000000042",[O.Polygon]:"0x0000000000000000000000000000000000001010"},Yt=[O.Arbitrum,O.Aurora,O.Base,O.Optimism,O.Robinhood];function xe({chain:e,symbol:t,ticker:n},o){try{let a=e===O.BinanceSmartChain&&t==="BNB"&&n==="BNB",r=e===O.Hyperevm&&t==="HYPE"&&n==="HYPE",i=e===o&&t===o&&n===o,s=Yt.includes(e)&&t==="ETH"&&n==="ETH",c=e===O.Arc&&t==="USDC"&&n==="USDC";if(i||a||r||s||c)return Jt[o];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:B(BigInt(i.value||0))}}}function X({chain:e,provider:t,isEIP1559Compatible:n=!0}){return De(e).with(O.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{[d.Average]:{maxFeePerGas:M(a,d.Average),maxPriorityFeePerGas:M(r,d.Average)},[d.Fast]:{maxFeePerGas:M(a,d.Fast),maxPriorityFeePerGas:M(r,d.Fast)},[d.Fastest]:{maxFeePerGas:M(a,d.Fastest),maxPriorityFeePerGas:M(r,d.Fastest)}}}catch(a){throw new m("toolbox_evm_gas_estimation_error",{error:a.msg??a.toString()})}}).with(O.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{[d.Average]:{gasPrice:r},[d.Fast]:{gasPrice:M(r,d.Fast)},[d.Fastest]:{gasPrice:M(r,d.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{[d.Average]:{maxFeePerGas:a,maxPriorityFeePerGas:r},[d.Fast]:{maxFeePerGas:M(a,d.Fast),maxPriorityFeePerGas:M(r,d.Fast)},[d.Fastest]:{maxFeePerGas:M(a,d.Fastest),maxPriorityFeePerGas:M(r,d.Fastest)}}}if(!i)throw new m("toolbox_evm_no_gas_price");return{[d.Average]:{gasPrice:i},[d.Fast]:{gasPrice:M(i,d.Fast)},[d.Fastest]:{gasPrice:M(i,d.Fastest)}}}catch(a){throw new m("toolbox_evm_gas_estimation_error",{error:a.msg??a.toString()})}})}async function Qt({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 y=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 Dt(u,n),{nonce:G,release:R,settle:N}=await Ue({address:C,nonce:l?.nonce,provider:c.provider??s});try{let _=await y[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(!ze(_))R();throw _}finally{N()}}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:y=d.Fast}){let p=r||e;if(!i)throw new m("toolbox_evm_invalid_params",{error:"contractAddress must be provided"});let b=Kt({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 Qt({chain:o,contract:f,contractProvider:p,feeOption:y,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 Zt({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 en({signer:e,isEIP1559Compatible:t=!0,provider:n,chain:o}){return async function({assetAddress:r,spenderAddress:i,feeOptionKey:s=d.Fast,amount:c,gasLimitFallback:l,from:u,nonce:y}){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:y}})}}function tn({chain:e,estimateGasPrices:t,estimateAdditionalFee:n,signer:o,isEIP1559Compatible:a=!0,provider:r}){return async function({assetValue:s,memo:c,recipient:l,feeOptionKey:u=d.Fast,sender:y,sweep:p,...b}){let f=y||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 nn({provider:e,signer:t}){return async function({assetValue:o,recipient:a,memo:r,data:i,sender:s,funcName:c,funcParams:l,txOverrides:u}){let y=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:y})}}function on({signer:e}){if(!e)return;return(t)=>Ge(e,t)}var We=(e)=>e.type===4||(e.authorizations?.length??0)>0,an=(e)=>!We(e)&&(e.type===2||!!e.maxFeePerGas||!!e.maxPriorityFeePerGas),rn=(e,t=!0)=>{if(We(e))return"eip7702";if(an(e)||t)return"eip1559";return"legacy"};function sn(e,t){if(e==="legacy"){if(t.gasPrice===void 0)throw new m("toolbox_evm_no_fee_data");return{gasPrice:B(t.gasPrice)}}if(t.maxFeePerGas===void 0||t.maxPriorityFeePerGas===void 0)throw new m("toolbox_evm_no_fee_data");return{maxFeePerGas:B(t.maxFeePerGas),maxPriorityFeePerGas:B(t.maxPriorityFeePerGas)}}function Xe({chain:e,estimateGasPrices:t,provider:n,signer:o,isEIP1559Compatible:a=!0}){return async function({feeOptionKey:i=d.Fast,sweep:s,...c}){let{from:l,to:u,data:y,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:y||"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:N}=await Ue({address:P,nonce:c.nonce,provider:C}),_=async()=>{let E=rn(f,a);if(E==="eip7702")Ie(f.authorizations||[],A);let w=De(E).with("eip7702",()=>4).with("eip1559",()=>2).otherwise(()=>0),V={...f,chainId:A,nonce:G,type:w,...E==="eip7702"&&{authorizationList:f.authorizations}},F=t??X({chain:e,isEIP1559Compatible:a,provider:n}),S=(E==="legacy"?f.gasPrice!==void 0:f.maxFeePerGas!==void 0&&f.maxPriorityFeePerGas!==void 0)?{}:sn(E,(await F())[i]),h;try{h=B(f.gasLimit?BigInt(f.gasLimit):await n.estimateGas(V)*11n/10n)}catch(I){throw new m("toolbox_evm_error_estimating_gas_limit",{error:I})}return{...V,gasLimit:h,...S}};try{let E=await _().catch((w)=>{throw R(),w});try{return(await o.sendTransaction(E)).hash}catch(w){let V=c.nonce!=null?"caller":"pending",F={address:P,error:w,nonce:G,nonceSource:V};if(fe(w))throw new m({errorKey:"toolbox_evm_nonce_conflict",info:F},F);if(de(w)){let h=await Xt({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(!Wt(w))throw R(),new m({errorKey:"toolbox_evm_error_sending_transaction",info:F},F);let L=U(w,"UNSUPPORTED_OPERATION"),S;try{S=await o.signTransaction({...E,from:P})}catch(h){if(L)R();let I={...F,fallbackError:h};throw new m({errorKey:"toolbox_evm_error_sending_transaction",info:I},I)}try{return(await C.broadcastTransaction(S)).hash}catch(h){let I={...F,fallbackError:h};if(de(h)){let H=pe.from(S).hash;if(H)return H}if(fe(h)){let H=pe.from(S).hash;if(H&&await Ke(C,H))return H;throw new m({errorKey:"toolbox_evm_nonce_conflict",info:I},I)}if(L&&!ze(h))R();throw new m({errorKey:"toolbox_evm_error_sending_transaction",info:I},I)}}}finally{N()}}}function D(e,t){throw new m({errorKey:"toolbox_sweep_amount_too_low",info:{balance:e.toString(),fee:t.toString()}})}function cn(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 un(e){return Lt(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 ln({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)D(e,o+s);let l=await t({...a,value:c})??i;return M(Pe(i,l),n)}async function mn({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),y=n??X({chain:e,isEIP1559Compatible:i,provider:s}),{feeFields:p,feePerGas:b}=cn((await y())[a],i),f={...l,...p,data:t,from:r,to:c},P=un(t)*b;if(u-P<=0n)D(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(I){if(me(I))D(u,P);throw I}}let G=C*b;if(u-G<=0n)D(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;D(u,_)}let V=w*b,F=u-V;if(F<=0n)D(u,V);let L=await ln({balance:u,estimateAdditionalFee:o,feeOptionKey:a,l2Reserve:V,sweepTx:{...f,gasLimit:w},valueBeforeL1Fee:F}),S=F-L;if(S<=0n)D(u,V+L);return{...f,gasLimit:w,value:B(S)}}async function pn({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:y,feeOptionKey:p=d.Fast,gasLimit:b,sender:f,sweep:P,type:A,maxFeePerGas:C,maxPriorityFeePerGas:G,gasPrice:R,...N}){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(kt(s)){let{hexlify:L,toUtf8Bytes:S}=await import("ethers"),h=y||L(S(l||""));if(!P)return{...N,...c!==void 0&&{authorizations:c},data:h,from:E,...b!==void 0&&{gasLimit:b},to:u,...A!==void 0&&{type:A},value:B(_)};return mn({chain:e,data:h,estimateAdditionalFee:t,estimateGasPrices:n,feeOptionKey:p,from:E,isEIP1559Compatible:o,provider:a,recipient:u,transaction:{nonce:N.nonce,type:A}})}let w=xe(s,e);if(!w)throw new m("toolbox_evm_no_contract_address");let V=W({chain:e,provider:a}),F=P?await pn({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 V({abi:K,contractAddress:w,funcName:"transfer",funcParams:[u,F],txOverrides:{from:E,gasLimit:b,gasPrice:R,maxFeePerGas:C,maxPriorityFeePerGas:G,nonce:N.nonce}})}}function fn({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}),y=["bigint","number"].includes(typeof i)?i:i||be;return await u({abi:K,contractAddress:a,funcName:"approve",funcParams:[r,BigInt(y)],txOverrides:{from:l,nonce:c}})}}function dn({provider:e,isEIP1559Compatible:t=!0,chain:n}){return async function({feeOption:a=d.Fast,...r}){let s=await X({chain:n,isEIP1559Compatible:t,provider:e})(),c=await e.estimateGas(r),l=St.from({chain:n}),{gasPrice:u,maxFeePerGas:y,maxPriorityFeePerGas:p}=s[a];if(!t&&u)return l.set(Q.fromBigInt(u*c,l.decimal));if(y&&p){let b=(y+p)*c;return l.set(Q.fromBigInt(b,l.decimal))}throw new m("toolbox_evm_no_gas_price")}}import{applyFeeMultiplierToBigInt as q,Chain as Qe,derivationPathToString as yn,FeeOption as k,getChainConfig as bn,resolveDerivationPath as gn,SwapKitError as j}from"@swapkit/helpers";import{Contract as xn,HDNodeWallet as Pn}from"ethers";import{match as Tn,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 wn="0x420000000000000000000000000000000000000f";function re(e){return new xn(wn,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 j("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 j({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 j({errorKey:"toolbox_evm_invalid_transaction",info:{error:"Invalid OP-stack operator fee"}});return a}return 0n}}function hn(e,t){let n=we(e,t),o=he(e);return async function(r){if(r.gasLimit===void 0||r.gasLimit===null)throw new j({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 vn(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 En(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=q(t,e),a=q(n,e);return{maxFeePerGas:Pe(o,a),maxPriorityFeePerGas:a}}function _n(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 j("toolbox_evm_no_fee_data");return{[k.Average]:{gasPrice:i,l1GasPrice:r,...Te({feeOption:k.Average,maxFeePerGas:n,maxPriorityFeePerGas:o})},[k.Fast]:{gasPrice:q(i,k.Fast),l1GasPrice:q(r||0n,k.Fast),...Te({feeOption:k.Fast,maxFeePerGas:n,maxPriorityFeePerGas:o})},[k.Fastest]:{gasPrice:q(i,k.Fastest),l1GasPrice:q(r||0n,k.Fastest),...Te({feeOption:k.Fastest,maxFeePerGas:n,maxPriorityFeePerGas:o})}}}catch(n){throw new j("toolbox_evm_gas_estimation_error",{error:n.msg??n.toString()})}}}function ie(e){return function({provider:n,...o}){let a=Tn(o).with({phrase:Ye.string},({phrase:p,derivationPath:b,index:f=0})=>Pn.fromPhrase(p,void 0,yn(gn({chain:e,derivationPath:b,index:f}))).connect(n)).with({signer:Ye.any},({signer:p})=>p).otherwise(()=>{return}),r=Ze(n),i=BigInt(bn(e).chainId),s=we(n,i),c=hn(n,i),l=he(n),u=e===Qe.Optimism?_n(n):void 0;return{...te({chain:e,estimateAdditionalFee:c,estimateGasPrices:u,provider:n,signer:a}),estimateL1Gas:En(n),estimateL1GasCost:s,estimateL2GasCost:tt(n),estimateOperatorFee:l,estimateTotalGasCost:vn(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=Fn.Fast){let s=await t.createContractTxObject({abi:Ve,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),yo=v(T.Botanix),ft=v(T.Core),dt=v(T.Corn),yt=v(T.Cronos),bt=v(T.Gnosis),gt=v(T.Robinhood),xt=v(T.Hyperevm),Pt=v(T.Linea),Tt=v(T.Polygon),wt=v(T.MegaETH),ht=v(T.Monad),vt=v(T.Plasma),ve=v(T.Sonic),Et=ie(T.Unichain),_t=v(T.XLayer);function v(e){return function({provider:n,...o}){let a=Me(e),r=Gn(o).with({phrase:ot.string},({phrase:s,derivationPath:c,index:l=0})=>Mn.fromPhrase(s,void 0,Cn(An({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 In(e,t){return On(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,()=>ve(t)).with(x.Core,()=>ft(t)).with(x.Corn,()=>dt(t)).with(x.Cronos,()=>yt(t)).with(x.Ethereum,()=>at(t)).with(x.Gnosis,()=>bt(t)).with(x.Hyperevm,()=>xt(t)).with(x.Linea,()=>Pt(t)).with(x.MegaETH,()=>wt(t)).with(x.Monad,()=>ht(t)).with(x.Optimism,()=>nt(t)).with(x.Plasma,()=>vt(t)).with(x.Polygon,()=>Tt(t)).with(x.Robinhood,()=>gt(t)).with(x.Sonic,()=>ve(t)).with(x.Unichain,()=>Et(t)).with(x.XLayer,()=>_t(t)).exhaustive()}async function To(e,t){let n={...t,provider:t?.provider||Fe(e)};return In(e,n)}
2
- export{Y as b,Hn as c,Bt as d,kn as e,Fe as f,B as g,Ae as h,Me as i,Ge as j,Vt as k,Be as l,Oe as m,Nn as n,Ie as o,be as p,te as q,Ut as r,ne as s,ge as t,Ht as u,Kt as v,Jn as w,oe as x,Yn as y,Jt as z,xe as A,W as B,X as C,We as D,an as E,rn 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,yo as T,ft as U,dt as V,yt as W,bt as X,gt as Y,xt as Z,Pt as _,Tt as $,wt as aa,ht as ba,vt as ca,ve as da,Et as ea,_t as fa,In as ga,To as ha};