@swapkit/toolboxes 6.6.1 → 6.6.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +9 -0
- package/dist/{chunk-bmj5dnhd.js → chunk-3y8attb1.js} +1 -1
- package/dist/chunk-6fcz98xe.js +2 -0
- package/dist/src/evm/index.js +1 -1
- package/dist/src/hypercore/index.js +1 -1
- package/dist/src/index.js +1 -1
- package/dist/src/substrate/index.js +1 -1
- package/package.json +2 -2
- package/dist/chunk-2q4pxsyg.js +0 -2
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,14 @@
|
|
|
1
1
|
# @swapkit/toolboxes
|
|
2
2
|
|
|
3
|
+
## 6.6.2
|
|
4
|
+
|
|
5
|
+
### Patch Changes
|
|
6
|
+
|
|
7
|
+
- [#489](https://github.com/swapkit/sdk/pull/489) [`3fb0f51`](https://github.com/swapkit/sdk/commit/3fb0f511c3c1a460bcc768f4dd05689786cc1a9d) Thanks [@hippocampusSK](https://github.com/hippocampusSK)! - `helpers_chain_rpc_connection_failed` now says which chain failed and why each configured RPC endpoint was rejected in its message and `info`. The reason is always one of a fixed set (an HTTP status, `timeout`, `invalid_url`, `dns_error`, `connection_refused` or `network_error`), never the raw error text, so the error stays small and carries nothing from upstream. Before, the details were passed as the error's cause, so the message only showed the error key. Endpoints are reported by origin only, so API keys in RPC URLs never reach the logs. `helpers_chain_no_public_or_set_rpc_url` also carries the chain in its message now.
|
|
8
|
+
- [#490](https://github.com/swapkit/sdk/pull/490) [`4da7435`](https://github.com/swapkit/sdk/commit/4da7435524265403abdc4f07d32a6fdf19b4d64d) Thanks [@hippocampusSK](https://github.com/hippocampusSK)! - Fix three Substrate toolbox (Polkadot, Chainflip) signing bugs:
|
|
9
|
+
- [#486](https://github.com/swapkit/sdk/pull/486) [`8b15231`](https://github.com/swapkit/sdk/commit/8b15231a8af87f7cdbbd6c40e308cb01e80e6186) Thanks [@hippocampusSK](https://github.com/hippocampusSK)! - Allow quote and swap requests to opt into selling the full balance of a native asset, and expose whether a route was adjusted for it (via @swapkit/helpers@6.5.0)
|
|
10
|
+
- [#484](https://github.com/swapkit/sdk/pull/484) [`c03235b`](https://github.com/swapkit/sdk/commit/c03235b7a06fc3c71c67c0407a2c8c5159b4cb17) Thanks [@github-actions](https://github.com/apps/github-actions)! - Update generated token lists. (via @swapkit/helpers@6.5.0)
|
|
11
|
+
|
|
3
12
|
## 6.6.1
|
|
4
13
|
|
|
5
14
|
### Patch Changes
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{$ as M,A as l,B as m,C as n,D as o,E as p,F as q,G as r,H as s,I as t,J as u,K as v,L as w,M as x,N as y,O as z,P as A,Q as B,R as C,S as D,T as E,U as F,V as G,W as H,X as I,Y as J,Z as K,_ as L,aa as N,ba as O,ca as P,da as Q,ea as R,fa as S,ga as T,ha as U,p as a,q as b,r as c,s as d,t as e,u as f,v as g,w as h,x as i,y as j,z as k}from"./chunk-
|
|
1
|
+
import{$ as M,A as l,B as m,C as n,D as o,E as p,F as q,G as r,H as s,I as t,J as u,K as v,L as w,M as x,N as y,O as z,P as A,Q as B,R as C,S as D,T as E,U as F,V as G,W as H,X as I,Y as J,Z as K,_ as L,aa as N,ba as O,ca as P,da as Q,ea as R,fa as S,ga as T,ha as U,p as a,q as b,r as c,s as d,t as e,u as f,v as g,w as h,x as i,y as j,z as k}from"./chunk-6fcz98xe.js";import"./chunk-qk8kg62t.js";import"./chunk-pz8xe0qj.js";export{w as ADIToolbox,x as ARBToolbox,y as ARCToolbox,z as AURORAToolbox,A as AVAXToolbox,B as BASEToolbox,C as BERAToolbox,D as BSCToolbox,b as BaseEVMToolbox,E as BotanixToolbox,F as COREToolbox,G as CORNToolbox,H as CROToolbox,k as ContractAddress,v as ETHToolbox,I as GNOToolbox,J as HOODToolbox,K as HYPEREVMToolbox,L as LINEAToolbox,M as MATICToolbox,a as MAX_APPROVAL,N as MEGAETHToolbox,O as MONADToolbox,u as OPToolbox,P as PLASMAToolbox,Q as SONICToolbox,R as UNIToolbox,S as XLayerToolbox,e as createContract,t as createOPStackToolbox,j as getChecksumAddressFromAsset,f as getCreateContract,m as getCreateContractTxObject,i as getEIP1193SendTransaction,q as getEVMTxType,n as getEstimateGasPrices,T as getEvmToolbox,U as getEvmToolboxAsync,l as getTokenAddress,d as isBrowserProvider,p as isEIP1559Transaction,o as isEIP7702Transaction,g as isStateChangingCall,r as maxBigInt,s as scaleEIP1559Fees,h as toChecksumAddress,c as validateEVMAddress};
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{ja as Ve}from"./chunk-qk8kg62t.js";import{ka as de}from"./chunk-pz8xe0qj.js";import{Chain as x}from"@swapkit/helpers";import{match as In}from"ts-pattern";import{Chain as g,getChainConfig as J,getRPCUrl as At,SKConfig as Mt,SwapKitError as U}from"@swapkit/helpers";import{FallbackProvider as Gt,getAddress as Ee,Interface as Ot,JsonRpcProvider as se,Network as Bt}from"ethers";import{match as _e}from"ts-pattern";function It(e){return new se(e)}async function Nn(e,t){return It(t||await At(e))}function Ce(e){let t=Mt.get("rpcUrls")[e]?.filter(Boolean)??[];if(t.length===0)throw new U({errorKey:"helpers_chain_no_public_or_set_rpc_url",info:{chain:e}});let{chainId:n}=J(e),o=Bt.from(Number(n)),[a]=t;if(t.length===1)return new se(a,o,{staticNetwork:o});return new Gt(t.map((r,i)=>({priority:i+1,provider:new se(r,o,{staticNetwork:o}),stallTimeout:2000})),o,{quorum:1})}function O(e){return e>0n?`0x${e.toString(16)}`:"0x0"}function Fe(e){let{explorerUrl:t,chainIdHex:n,rpcUrls:o}=J(e);return function(){return e!==g.Ethereum?{...Vt({chain:e}),blockExplorerUrls:[t],chainId:n,rpcUrls:o}:void 0}}function Ae(e){return![g.Adi,g.Arbitrum,g.BinanceSmartChain,g.Robinhood].includes(e)}function Vt({chain:e}){let{name:t,nativeCurrency:n,baseDecimal:o}=J(e);return _e(e).with(g.Arbitrum,()=>({chainName:"Arbitrum One",nativeCurrency:{decimals:o,name:"Ethereum",symbol:g.Ethereum}})).with(g.Aurora,()=>({chainName:"Aurora Mainnet",nativeCurrency:{decimals:o,name:"Ethereum",symbol:g.Ethereum}})).with(g.Avalanche,()=>({chainName:"Avalanche Network",nativeCurrency:{decimals:o,name:"Avalanche",symbol:e}})).with(g.Base,()=>({chainName:"Base Mainnet",nativeCurrency:{decimals:o,name:"Ethereum",symbol:g.Ethereum}})).with(g.Berachain,()=>({chainName:"Berachain",nativeCurrency:{decimals:o,name:"Berachain",symbol:"BERA"}})).with(g.XLayer,()=>({chainName:"X Layer",nativeCurrency:{decimals:o,name:"OKB",symbol:"OKB"}})).with(g.BinanceSmartChain,()=>({chainName:"BNB Smart Chain Mainnet",nativeCurrency:{decimals:o,name:"Binance Coin",symbol:"BNB"}})).with(g.Gnosis,()=>({chainName:"Gnosis",nativeCurrency:{decimals:o,name:"xDAI",symbol:"XDAI"}})).with(g.Optimism,()=>({chainName:"OP Mainnet",nativeCurrency:{decimals:o,name:"Ethereum",symbol:g.Ethereum}})).with(g.Polygon,()=>({chainName:"Polygon Mainnet",nativeCurrency:{decimals:o,name:"Polygon",symbol:g.Polygon}})).with(g.Robinhood,()=>({chainName:"Robinhood Chain",nativeCurrency:{decimals:o,name:"Ethereum",symbol:g.Ethereum}})).otherwise(()=>({chainName:t,nativeCurrency:{decimals:o,name:n,symbol:n}}))}async function Me(e,t){if(!("authorize"in e))throw Error("Signer does not support EIP-7702 authorization. Requires ethers.js v6.14+");let n={...t,nonce:t.nonce!==void 0?BigInt(t.nonce):void 0};return await e.authorize(n)}var ve=(e)=>typeof e==="string"&&/^0x[a-fA-F0-9]{64}$/.test(e),Rt=(e)=>{try{return typeof e==="string"&&!!Ee(e)}catch{return!1}};function St(e,t){let n=t!==void 0?`index ${t}: `:"",o=(a,r)=>{throw new U({errorKey:"toolbox_evm_invalid_eip7702_authorization",info:{field:a,message:`${n}${r}`}})};_e(e).when(({chainId:a})=>typeof a!=="bigint",()=>o("chainId","chainId must be a bigint")).when(({address:a})=>!Rt(a),()=>o("address","address must be a valid checksummed address")).when(({nonce:a})=>typeof a!=="bigint"||a<0n,()=>o("nonce","nonce must be a non-negative bigint")).when(({signature:a})=>!a,()=>o("signature","signature is required")).when(({signature:a})=>typeof a?.yParity!=="number"||![0,1].includes(a.yParity),()=>o("signature.yParity","yParity must be 0 or 1")).when(({signature:a})=>!ve(a?.r),()=>o("signature.r","r must be a 32-byte hex string")).when(({signature:a})=>!ve(a?.s),()=>o("signature.s","s must be a 32-byte hex string")).otherwise(()=>{})}function Ge(e){return[{key:"name",type:"string"},{key:"version",type:"string"},{key:"chainId",type:"uint256"},{key:"verifyingContract",type:"address"},{key:"salt",type:"bytes32"}].filter(({key:t})=>e[t]!=null).map(({key:t,type:n})=>({name:t,type:n}))}function Oe(e){if(!("EIP712Domain"in e.types))return e;let{EIP712Domain:t,...n}=e.types,o=Ge(e.domain);if(!(Array.isArray(t)&&t.length===o.length&&o.every(({name:r,type:i},s)=>t[s]?.name===r&&t[s]?.type===i)))throw new U({errorKey:"toolbox_evm_typed_data_domain_mismatch",info:{declared:t,expected:o}});return{...e,types:n}}function ce(e){return e.charAt(0).toUpperCase()+e.slice(1)}function ue(e,t){if(e.isTuple()&&e.components){let n=ce(e.name);return t[n]=e.components.map((o)=>({name:o.name,type:ue(o,t)})),n}if(e.isArray()){let n=e.arrayChildren;if(n?.isTuple()&&n.components){let o=ce(e.name.replace(/s$/,""));return t[o]=n.components.map((a)=>({name:a.name,type:ue(a,t)})),`${o}[]`}return`${n?.type??"bytes"}[]`}return e.type}function le(e,t){if(typeof e==="bigint")return e;if(t?.isTuple()&&typeof e?.toObject==="function"){let n=e.toObject(),o={};for(let[a,r]of(t.components??[]).entries())o[r.name]=le(n[r.name]??e[a],r);return o}if(Array.isArray(e)){let n=t?.arrayChildren;return e.map((o)=>le(o,n??void 0))}return e}function Ln({chain:e,abi:t,data:n,to:o}){let r=new Ot(t).parseTransaction({data:n});if(!r)throw new U({errorKey:"toolbox_evm_invalid_params",info:{error:"Could not decode calldata"}});let i={},s=ce(r.name);i[s]=r.fragment.inputs.map((p)=>({name:p.name,type:ue(p,i)}));let c={};for(let[p,b]of r.fragment.inputs.entries())c[b.name]=le(r.args[p],b);let{chainId:l}=J(e),u={chainId:Number(l),verifyingContract:Ee(o)},d=Ge(u);return{domain:u,message:c,primaryType:s,types:{EIP712Domain:d,...i}}}function Be(e,t){if(!Array.isArray(e)||e.length===0)throw new U({errorKey:"toolbox_evm_invalid_eip7702_authorization",info:{message:"EIP-7702 transactions require at least one authorization"}});for(let[n,o]of e.entries())if(St(o,n),t!==void 0&&o.chainId!==t)throw new U({errorKey:"toolbox_evm_invalid_eip7702_authorization",info:{field:"chainId",message:`index ${n}: authorization chainId (${o.chainId}) does not match transaction chainId (${t})`}})}import{Chain as T,derivationPathToString as Fn,FeeOption as An,resolveDerivationPath as Mn}from"@swapkit/helpers";import{HDNodeWallet as Gn}from"ethers";import{match as On,P as ot}from"ts-pattern";var Ie=[{inputs:[{components:[{internalType:"address",name:"target",type:"address"},{internalType:"bytes",name:"callData",type:"bytes"}],internalType:"struct Multicall2.Call[]",name:"calls",type:"tuple[]"}],name:"aggregate",outputs:[{internalType:"uint256",name:"blockNumber",type:"uint256"},{internalType:"bytes[]",name:"returnData",type:"bytes[]"}],stateMutability:"nonpayable",type:"function"},{inputs:[{components:[{internalType:"address",name:"target",type:"address"},{internalType:"bytes",name:"callData",type:"bytes"}],internalType:"struct Multicall2.Call[]",name:"calls",type:"tuple[]"}],name:"blockAndAggregate",outputs:[{internalType:"uint256",name:"blockNumber",type:"uint256"},{internalType:"bytes32",name:"blockHash",type:"bytes32"},{components:[{internalType:"bool",name:"success",type:"bool"},{internalType:"bytes",name:"returnData",type:"bytes"}],internalType:"struct Multicall2.Result[]",name:"returnData",type:"tuple[]"}],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"uint256",name:"blockNumber",type:"uint256"}],name:"getBlockHash",outputs:[{internalType:"bytes32",name:"blockHash",type:"bytes32"}],stateMutability:"view",type:"function"},{inputs:[],name:"getBlockNumber",outputs:[{internalType:"uint256",name:"blockNumber",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[],name:"getCurrentBlockCoinbase",outputs:[{internalType:"address",name:"coinbase",type:"address"}],stateMutability:"view",type:"function"},{inputs:[],name:"getCurrentBlockDifficulty",outputs:[{internalType:"uint256",name:"difficulty",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[],name:"getCurrentBlockGasLimit",outputs:[{internalType:"uint256",name:"gaslimit",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[],name:"getCurrentBlockTimestamp",outputs:[{internalType:"uint256",name:"timestamp",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"address",name:"addr",type:"address"}],name:"getEthBalance",outputs:[{internalType:"uint256",name:"balance",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[],name:"getLastBlockHash",outputs:[{internalType:"bytes32",name:"blockHash",type:"bytes32"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"bool",name:"requireSuccess",type:"bool"},{components:[{internalType:"address",name:"target",type:"address"},{internalType:"bytes",name:"callData",type:"bytes"}],internalType:"struct Multicall2.Call[]",name:"calls",type:"tuple[]"}],name:"tryAggregate",outputs:[{components:[{internalType:"bool",name:"success",type:"bool"},{internalType:"bytes",name:"returnData",type:"bytes"}],internalType:"struct Multicall2.Result[]",name:"returnData",type:"tuple[]"}],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"bool",name:"requireSuccess",type:"bool"},{components:[{internalType:"address",name:"target",type:"address"},{internalType:"bytes",name:"callData",type:"bytes"}],internalType:"struct Multicall2.Call[]",name:"calls",type:"tuple[]"}],name:"tryBlockAndAggregate",outputs:[{internalType:"uint256",name:"blockNumber",type:"uint256"},{internalType:"bytes32",name:"blockHash",type:"bytes32"},{components:[{internalType:"bool",name:"success",type:"bool"},{internalType:"bytes",name:"returnData",type:"bytes"}],internalType:"struct Multicall2.Result[]",name:"returnData",type:"tuple[]"}],stateMutability:"nonpayable",type:"function"}];import{AssetValue as kt,applyFeeMultiplierToBigInt as M,Chain as j,EVMChains as Nt,FeeOption as y,isGasAsset as ke,SwapKitError as m,SwapKitNumber as Q}from"@swapkit/helpers";import{erc20ABI as K}from"@swapkit/helpers/contracts";import{BrowserProvider as Lt,Contract as Ne,getAddress as ee,getBytes as Dt,Interface as Le,isError as D,resolveAddress as zt,Transaction as pe}from"ethers";import{match as De}from"ts-pattern";function Y(e){return{getBalance:Ve(e)}}function Kn(e){return e}var be=BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff");function te({chain:e=j.Ethereum,provider:t,signer:n,isEIP1559Compatible:o=!0,estimateGasPrices:a,estimateAdditionalFee:r}){let i=a??X({chain:e,isEIP1559Compatible:o,provider:t}),s=$e({chain:e,estimateAdditionalFee:r,estimateGasPrices:i,isEIP1559Compatible:o,provider:t,signer:n});return{approve:tn({chain:e,isEIP1559Compatible:o,provider:t,signer:n}),approvedAmount:qe({chain:e,provider:t}),broadcastTransaction:(c)=>t.broadcastTransaction(c),call:ae({chain:e,isEIP1559Compatible:o,provider:t,signer:n}),createApprovalTx:yn({chain:e,provider:t,signer:n}),createContract:Kt({chain:e,provider:t}),createContractTxObject:W({chain:e,provider:t}),createTransaction:s,createTransferTx:s,EIP1193SendTransaction:oe(t),estimateCall:je({provider:t,signer:n}),estimateGasLimit:on({chain:e,provider:t,signer:n}),estimateGasPrices:i,estimateTransactionFee:dn({chain:e,isEIP1559Compatible:o,provider:t}),getAddress:()=>n?n.getAddress():void 0,getBalance:Y(e).getBalance,getNetworkParams:Fe(e),isApproved:en({chain:e,provider:t}),sendTransaction:Xe({chain:e,estimateGasPrices:i,isEIP1559Compatible:o,provider:t,signer:n}),signAuthorization:an({signer:n}),signMessage:n?(c)=>n.signMessage(c):void 0,signTypedData:n?async(c)=>{let{domain:l,types:u,value:d}=Oe(c);return await n.signTypedData(l,u,d)}:void 0,transfer:nn({chain:e,estimateAdditionalFee:r,estimateGasPrices:i,isEIP1559Compatible:o,provider:t,signer:n}),validateAddress:Ut}}function Ut(e){try{return ee(e),!0}catch{return!1}}function ne(e){return e instanceof Lt}function ge(e,t,n){return new Ne(e,Le.from(t),n)}function Kt({provider:e}){return function(n,o){return new Ne(n,Le.from(o),e)}}var Ht=["payable","nonpayable"];function qt({abi:e,funcName:t}){let n=e.find((o)=>o.name===t);if(!n)throw new m("toolbox_evm_no_abi_fragment",{funcName:t});return n.stateMutability&&Ht.includes(n.stateMutability)}function Yn(e){return ee(e)}var jt=30000,Re=new WeakMap,Se=()=>{};function Wt(e,t,n){let o=Date.now();for(let[r,i]of e)if(i.held===0&&o-i.at>jt)e.delete(r);let a=e.get(t);if(!a||n>=a.next){let r={at:o,held:1,next:n+1,released:new Set};return e.set(t,r),{floor:r,nonce:n}}a.held+=1;for(let r of[...a.released].sort((i,s)=>i-s))if(a.released.delete(r),r>=n)return{floor:a,nonce:r};return{floor:a,nonce:a.next++}}async function ze({address:e,nonce:t,provider:n}){if(t!==void 0&&t!==null)return{nonce:t,release:Se,settle:Se};let{chainId:o}=await n.getNetwork(),a=Re.get(n)??new Map;Re.set(n,a);let r=`${o}:${e.toLowerCase()}`,i=await n.getTransactionCount(e,"pending"),{floor:s,nonce:c}=Wt(a,r,i),l=!1,u=(d)=>{if(l)return;if(l=!0,s.held-=1,s.at=Date.now(),d)s.released.add(c)};return{nonce:c,release:()=>u(!0),settle:()=>u(!1)}}function Z(e,t=0){if(!e||t>3)return"";if(typeof e==="string")return e.toLowerCase();if(typeof e!=="object")return"";let{error:n,info:o,message:a,shortMessage:r}=e;return[(typeof r==="string"?r:typeof a==="string"?a:"").toLowerCase(),Z(n,t+1),Z(o?.error,t+1)].filter(Boolean).join(" ")}function fe(e){if(D(e,"NONCE_EXPIRED")||D(e,"REPLACEMENT_UNDERPRICED"))return!0;let t=Z(e);return/nonce (?:is )?too low/.test(t)||t.includes("replacement transaction underpriced")}function ye(e){let t=Z(e);return t.includes("already known")||t.includes("known transaction")||t.includes("already imported")}function Ue(e){return D(e,"NETWORK_ERROR")||D(e,"SERVER_ERROR")||D(e,"TIMEOUT")}function Xt(e){return Ue(e)||D(e,"UNSUPPORTED_OPERATION")}function Ke(e){return Ue(e)||ye(e)}function He(e,t){return e.getTransaction(t).then((n)=>n!==null,()=>!1)}async function $t({provider:e,signer:t,txObject:n}){try{let o=pe.from(await t.signTransaction(n)).hash;return o&&await He(e,o)?o:null}catch{return null}}function oe(e,t=!1){return function({value:o,...a}){if(!ne(e))throw new m("toolbox_evm_provider_not_eip1193_compatible");let r={...a,gasPrice:"gasPrice"in a?a.gasPrice:void 0,maxFeePerGas:"maxFeePerGas"in a?a.maxFeePerGas:void 0,maxPriorityFeePerGas:"maxPriorityFeePerGas"in a?a.maxPriorityFeePerGas:void 0},{gasLimit:i,gasPrice:s,maxFeePerGas:c,maxPriorityFeePerGas:l,...u}=r,d={...u,...t&&i!==void 0&&{gas:O(BigInt(i))},...t&&s!==void 0&&{gasPrice:O(BigInt(s))},...t&&c!==void 0&&{maxFeePerGas:O(BigInt(c))},...t&&l!==void 0&&{maxPriorityFeePerGas:O(BigInt(l))},value:O(BigInt(o||0))};return e.send("eth_sendTransaction",[d])}}function Qn(e,t){let n=xe(e,t);if(n)return ee(n.toLowerCase());throw new m("toolbox_evm_invalid_gas_asset_address")}var Jt=Nt.reduce((e,t)=>(e[t]="0x0000000000000000000000000000000000000000",e),{}),Yt={...Jt,[j.Polygon]:"0x0000000000000000000000000000000000001010"},Qt="0x4200000000000000000000000000000000000042";function xe({chain:e,symbol:t,ticker:n},o){try{if(ke({chain:e,symbol:t}))return Yt[o];if(e===j.Optimism&&t==="OP")return Qt;return ee(t.slice(n.length+1).replace(/^0X/,""))}catch{return null}}function W({provider:e}){return async({contractAddress:t,abi:n,funcName:o,funcParams:a=[],txOverrides:r})=>{let i=await ge(t,n,e).getFunction(o).populateTransaction(...a.concat(r).filter((s)=>typeof s<"u"));return{...i,value:O(BigInt(i.value||0))}}}function X({chain:e,provider:t,isEIP1559Compatible:n=!0}){return De(e).with(j.Gnosis,()=>async function(){try{let{gasPrice:a,maxPriorityFeePerGas:r}=await t.getFeeData();if(!a||r===null)throw new m("toolbox_evm_no_fee_data");return{[y.Average]:{maxFeePerGas:M(a,y.Average),maxPriorityFeePerGas:M(r,y.Average)},[y.Fast]:{maxFeePerGas:M(a,y.Fast),maxPriorityFeePerGas:M(r,y.Fast)},[y.Fastest]:{maxFeePerGas:M(a,y.Fastest),maxPriorityFeePerGas:M(r,y.Fastest)}}}catch(a){throw new m("toolbox_evm_gas_estimation_error",{error:a.msg??a.toString()})}}).with(j.Arbitrum,()=>async function(){try{let{gasPrice:a}=await t.getFeeData();if(!a)throw new m("toolbox_evm_no_fee_data");let r=a*12n/10n;return{[y.Average]:{gasPrice:r},[y.Fast]:{gasPrice:M(r,y.Fast)},[y.Fastest]:{gasPrice:M(r,y.Fastest)}}}catch(a){throw new m("toolbox_evm_gas_estimation_error",{error:a.msg??a.toString()})}}).otherwise(()=>async function(){try{let{maxFeePerGas:a,maxPriorityFeePerGas:r,gasPrice:i}=await t.getFeeData();if(n){if(a===null||r===null)throw new m("toolbox_evm_no_fee_data");return{[y.Average]:{maxFeePerGas:a,maxPriorityFeePerGas:r},[y.Fast]:{maxFeePerGas:M(a,y.Fast),maxPriorityFeePerGas:M(r,y.Fast)},[y.Fastest]:{maxFeePerGas:M(a,y.Fastest),maxPriorityFeePerGas:M(r,y.Fastest)}}}if(!i)throw new m("toolbox_evm_no_gas_price");return{[y.Average]:{gasPrice:i},[y.Fast]:{gasPrice:M(i,y.Fast)},[y.Fastest]:{gasPrice:M(i,y.Fastest)}}}catch(a){throw new m("toolbox_evm_gas_estimation_error",{error:a.msg??a.toString()})}})}async function Zt({chain:e,contract:t,contractProvider:n,feeOption:o,funcName:a,funcParams:r,isEIP1559Compatible:i,provider:s,signer:c,txOverrides:l}){let u=l?.from||await c.getAddress();if(!u)throw new m("toolbox_evm_no_signer_address");let d=t.connect(c),p=X({chain:e,isEIP1559Compatible:i,provider:s}),[{maxFeePerGas:b,maxPriorityFeePerGas:f,gasPrice:P},A]=await Promise.all([p().then((_)=>_[o]),t.getFunction(a).estimateGas(...r,l)]),C=typeof u==="string"?u:await zt(u,n),{nonce:G,release:R,settle:k}=await ze({address:C,nonce:l?.nonce,provider:c.provider??s});try{let _=await d[a](...r,{...l,gasLimit:A,gasPrice:P,maxFeePerGas:b,maxPriorityFeePerGas:f,nonce:G});return typeof _?.hash==="string"?_?.hash:_}catch(_){if(fe(_)){let E=l?.nonce!=null?"caller":"pending",w={address:C,error:_,nonce:G,nonceSource:E};throw new m({errorKey:"toolbox_evm_nonce_conflict",info:w},w)}if(!Ke(_))R();throw _}finally{k()}}function ae({provider:e,isEIP1559Compatible:t,signer:n,chain:o}){return async function({callProvider:r,contractAddress:i,abi:s,funcName:c,funcParams:l=[],txOverrides:u={},feeOption:d=y.Fast}){let p=r||e;if(!i)throw new m("toolbox_evm_invalid_params",{error:"contractAddress must be provided"});let b=qt({abi:s,funcName:c});if(b&&ne(p)&&n){let A=W({chain:o,provider:p}),C=u?.from||await n?.getAddress(),G=await A({abi:s,contractAddress:i,funcName:c,funcParams:l,txOverrides:{...u,from:C}});return oe(p)(G)}let f=ge(i,s,p);if(b){if(!n)throw new m("toolbox_evm_no_signer");return Zt({chain:o,contract:f,contractProvider:p,feeOption:d,funcName:c,funcParams:l,isEIP1559Compatible:t,provider:e,signer:n,txOverrides:u})}let P=await f[c]?.(...l);return typeof P?.hash==="string"?P?.hash:P}}function qe({provider:e,chain:t}){return function({assetAddress:o,spenderAddress:a,from:r}){return ae({chain:t,isEIP1559Compatible:!0,provider:e})({abi:K,contractAddress:o,funcName:"allowance",funcParams:[r,a]})}}function en({provider:e,chain:t}){return async function({assetAddress:o,spenderAddress:a,from:r,amount:i=be}){let s=await qe({chain:t,provider:e})({assetAddress:o,from:r,spenderAddress:a});return Q.fromBigInt(s).gte(Q.fromBigInt(BigInt(i)))}}function tn({signer:e,isEIP1559Compatible:t=!0,provider:n,chain:o}){return async function({assetAddress:r,spenderAddress:i,feeOptionKey:s=y.Fast,amount:c,gasLimitFallback:l,from:u,nonce:d}){let p=[i,BigInt(c||be)],b=await e?.getAddress()||u,f={abi:K,contractAddress:r,funcName:"approve",funcParams:p,signer:e,txOverrides:{from:b}};if(ne(n)){let A=W({chain:o,provider:n}),C=oe(n),G=await A(f);return C(G)}return ae({chain:o,isEIP1559Compatible:t,provider:n,signer:e})({...f,feeOption:s,funcParams:p,txOverrides:{from:b,gasLimit:l?BigInt(l.toString()):void 0,nonce:d}})}}function nn({chain:e,estimateGasPrices:t,estimateAdditionalFee:n,signer:o,isEIP1559Compatible:a=!0,provider:r}){return async function({assetValue:s,memo:c,recipient:l,feeOptionKey:u=y.Fast,sender:d,sweep:p,...b}){let f=d||await o?.getAddress(),P=Xe({chain:e,estimateGasPrices:t,isEIP1559Compatible:a,provider:r,signer:o});if(!f)throw new m("toolbox_evm_no_from_address");let A=await $e({chain:e,estimateAdditionalFee:n,estimateGasPrices:t,isEIP1559Compatible:a,provider:r,signer:o})({assetValue:s,feeOptionKey:u,memo:c,recipient:l,sender:f,sweep:p,...b});return P({...A,feeOptionKey:u,sweep:p})}}function je({provider:e,signer:t}){return function({contractAddress:o,abi:a,funcName:r,funcParams:i=[],txOverrides:s}){if(!o)throw new m("toolbox_evm_no_contract_address");let c=ge(o,a,e);return t?c.connect(t).getFunction(r).estimateGas(...i,s):c.getFunction(r).estimateGas(...i,s)}}function on({provider:e,signer:t}){return async function({assetValue:o,recipient:a,memo:r,data:i,sender:s,funcName:c,funcParams:l,txOverrides:u}){let d=o.bigIntValue,p=o.isGasAsset?null:xe(o,o.chain);if(p&&c)return je({provider:e,signer:t})({abi:K,contractAddress:p,funcName:c,funcParams:l,txOverrides:u});let{hexlify:b,toUtf8Bytes:f}=await import("ethers");return e.estimateGas({data:i?i:r?b(f(r)):void 0,from:s,to:a,value:d})}}function an({signer:e}){if(!e)return;return(t)=>Me(e,t)}var We=(e)=>e.type===4||(e.authorizations?.length??0)>0,rn=(e)=>!We(e)&&(e.type===2||!!e.maxFeePerGas||!!e.maxPriorityFeePerGas),sn=(e,t=!0)=>{if(We(e))return"eip7702";if(rn(e))return"eip1559";if(e.gasPrice!=null)return"legacy";return t?"eip1559":"legacy"};function cn(e,t){if(e==="legacy"){if(t.gasPrice===void 0)throw new m("toolbox_evm_no_fee_data");return{gasPrice:O(t.gasPrice)}}if(t.maxFeePerGas===void 0||t.maxPriorityFeePerGas===void 0)throw new m("toolbox_evm_no_fee_data");return{maxFeePerGas:O(t.maxFeePerGas),maxPriorityFeePerGas:O(t.maxPriorityFeePerGas)}}function Xe({chain:e,estimateGasPrices:t,provider:n,signer:o,isEIP1559Compatible:a=!0}){return async function({feeOptionKey:i=y.Fast,sweep:s,...c}){let{from:l,to:u,data:d,value:p,...b}=c;if(!o)throw new m("toolbox_evm_no_signer");if(!u)throw new m("toolbox_evm_no_to_address");let f={...b,data:d||"0x",from:l,to:u,value:BigInt(p||0)};if(ne(n))return oe(n,s)(f);let P=l||await o.getAddress(),{chainId:A}=await n.getNetwork(),C=o.provider??n,{nonce:G,release:R,settle:k}=await ze({address:P,nonce:c.nonce,provider:C}),_=async()=>{let E=sn(f,a);if(E==="eip7702")Be(f.authorizations||[],A);let w=De(E).with("eip7702",()=>4).with("eip1559",()=>2).otherwise(()=>0),I={...f,chainId:A,nonce:G,type:w,...E==="eip7702"&&{authorizationList:f.authorizations}},F=t??X({chain:e,isEIP1559Compatible:a,provider:n}),V=(E==="legacy"?f.gasPrice!==void 0:f.maxFeePerGas!==void 0&&f.maxPriorityFeePerGas!==void 0)?{}:cn(E,(await F())[i]),h;try{h=O(f.gasLimit?BigInt(f.gasLimit):await n.estimateGas(I)*11n/10n)}catch(B){throw new m("toolbox_evm_error_estimating_gas_limit",{error:B})}return{...I,gasLimit:h,...V}};try{let E=await _().catch((w)=>{throw R(),w});try{return(await o.sendTransaction(E)).hash}catch(w){let I=c.nonce!=null?"caller":"pending",F={address:P,error:w,nonce:G,nonceSource:I};if(fe(w))throw new m({errorKey:"toolbox_evm_nonce_conflict",info:F},F);if(ye(w)){let h=await $t({provider:C,signer:o,txObject:{...E,from:P}});if(h)return h;throw new m({errorKey:"toolbox_evm_tx_already_known",info:F},F)}if(!Xt(w))throw R(),new m({errorKey:"toolbox_evm_error_sending_transaction",info:F},F);let N=D(w,"UNSUPPORTED_OPERATION"),V;try{V=await o.signTransaction({...E,from:P})}catch(h){if(N)R();let B={...F,fallbackError:h};throw new m({errorKey:"toolbox_evm_error_sending_transaction",info:B},B)}try{return(await C.broadcastTransaction(V)).hash}catch(h){let B={...F,fallbackError:h};if(ye(h)){let z=pe.from(V).hash;if(z)return z}if(fe(h)){let z=pe.from(V).hash;if(z&&await He(C,z))return z;throw new m({errorKey:"toolbox_evm_nonce_conflict",info:B},B)}if(N&&!Ke(h))R();throw new m({errorKey:"toolbox_evm_error_sending_transaction",info:B},B)}}}finally{k()}}}function L(e,t){throw new m({errorKey:"toolbox_sweep_amount_too_low",info:{balance:e.toString(),fee:t.toString()}})}function un(e,t){if(t){if(e.maxFeePerGas===void 0||e.maxPriorityFeePerGas===void 0)throw new m("toolbox_evm_no_fee_data");return{feeFields:{maxFeePerGas:e.maxFeePerGas,maxPriorityFeePerGas:e.maxPriorityFeePerGas},feePerGas:e.maxFeePerGas}}if(e.gasPrice===void 0)throw new m("toolbox_evm_no_fee_data");return{feeFields:{gasPrice:e.gasPrice},feePerGas:e.gasPrice}}function Pe(e,t){if(e>t)return e;return t}function ln(e){return Dt(e).reduce((t,n)=>t+(n===0?4n:16n),21000n)}function me(e){let n=(e instanceof Error?e.message:String(e)).toLowerCase();return n.includes("insufficient funds")||n.includes("insufficient balance")||n.includes("gas required exceeds allowance")}async function mn({balance:e,estimateAdditionalFee:t,feeOptionKey:n,l2Reserve:o,sweepTx:a,valueBeforeL1Fee:r}){if(!t)return 0n;let i=await t({...a,value:r})??0n,s=M(i,n),c=r-s;if(c<=0n)L(e,o+s);let l=await t({...a,value:c})??i;return M(Pe(i,l),n)}async function pn({chain:e,data:t,estimateGasPrices:n,estimateAdditionalFee:o,feeOptionKey:a,from:r,isEIP1559Compatible:i,provider:s,recipient:c,transaction:l}){let u=await s.getBalance(r),d=n??X({chain:e,isEIP1559Compatible:i,provider:s}),{feeFields:p,feePerGas:b}=un((await d())[a],i),f={...l,...p,data:t,from:r,to:c},P=ln(t)*b;if(u-P<=0n)L(u,P);let A=(u-P)/2n,C;try{C=await s.estimateGas({...f,value:A})}catch(h){if(!me(h))throw h;try{C=await s.estimateGas({...f,value:0n})}catch(B){if(me(B))L(u,P);throw B}}let G=C*b;if(u-G<=0n)L(u,G);let _=C*11n/10n*b,E=u>_?u-_:0n,w;try{w=await s.estimateGas({...f,value:E})}catch(h){if(!me(h))throw h;L(u,_)}let I=w*b,F=u-I;if(F<=0n)L(u,I);let N=await mn({balance:u,estimateAdditionalFee:o,feeOptionKey:a,l2Reserve:I,sweepTx:{...f,gasLimit:w},valueBeforeL1Fee:F}),V=F-N;if(V<=0n)L(u,I+N);return{...f,gasLimit:w,value:O(V)}}async function fn({chain:e,contractAddress:t,from:n,provider:o}){let a=await ae({chain:e,provider:o})({abi:K,contractAddress:t,funcName:"balanceOf",funcParams:[n]});if(typeof a!=="bigint")throw new m({errorKey:"toolbox_evm_invalid_transaction",info:{error:"Invalid ERC20 balance"}});return a}function $e({chain:e,estimateAdditionalFee:t,estimateGasPrices:n,isEIP1559Compatible:o=!0,provider:a,signer:r}){return async function({assetValue:s,authorizations:c,memo:l,recipient:u,data:d,feeOptionKey:p=y.Fast,gasLimit:b,sender:f,sweep:P,type:A,maxFeePerGas:C,maxPriorityFeePerGas:G,gasPrice:R,...k}){let _=s.getBaseValue("bigint"),E=f||await r?.getAddress();if(!E)throw new m("toolbox_evm_no_from_address");if(P&&(A===4||(c?.length??0)>0))throw new m({errorKey:"toolbox_not_supported",info:{chain:e,reason:"EIP-7702 sweep transactions are not supported"}});if(ke(s)){let{hexlify:N,toUtf8Bytes:V}=await import("ethers"),h=d||N(V(l||""));if(!P)return{...k,...c!==void 0&&{authorizations:c},data:h,from:E,...b!==void 0&&{gasLimit:b},to:u,...A!==void 0&&{type:A},value:O(_)};return pn({chain:e,data:h,estimateAdditionalFee:t,estimateGasPrices:n,feeOptionKey:p,from:E,isEIP1559Compatible:o,provider:a,recipient:u,transaction:{nonce:k.nonce,type:A}})}let w=xe(s,e);if(!w)throw new m("toolbox_evm_no_contract_address");let I=W({chain:e,provider:a}),F=P?await fn({chain:e,contractAddress:w,from:E,provider:a}):_;if(P&&F<=0n)throw new m({errorKey:"toolbox_sweep_amount_too_low",info:{asset:s.toString(),balance:F.toString()}});return I({abi:K,contractAddress:w,funcName:"transfer",funcParams:[u,F],txOverrides:{from:E,gasLimit:b,gasPrice:R,maxFeePerGas:C,maxPriorityFeePerGas:G,nonce:k.nonce}})}}function yn({provider:e,signer:t,chain:n}){return async function({assetAddress:a,spenderAddress:r,amount:i,from:s,nonce:c}){let l=await t?.getAddress()||s,u=W({chain:n,provider:e}),d=["bigint","number"].includes(typeof i)?i:i||be;return await u({abi:K,contractAddress:a,funcName:"approve",funcParams:[r,BigInt(d)],txOverrides:{from:l,nonce:c}})}}function dn({provider:e,isEIP1559Compatible:t=!0,chain:n}){return async function({feeOption:a=y.Fast,...r}){let s=await X({chain:n,isEIP1559Compatible:t,provider:e})(),c=await e.estimateGas(r),l=kt.from({chain:n}),{gasPrice:u,maxFeePerGas:d,maxPriorityFeePerGas:p}=s[a];if(!t&&u)return l.set(Q.fromBigInt(u*c,l.decimal));if(d&&p){let b=(d+p)*c;return l.set(Q.fromBigInt(b,l.decimal))}throw new m("toolbox_evm_no_gas_price")}}import{applyFeeMultiplierToBigInt as H,Chain as Qe,derivationPathToString as bn,FeeOption as S,getChainConfig as gn,resolveDerivationPath as xn,SwapKitError as q}from"@swapkit/helpers";import{Contract as Pn,HDNodeWallet as Tn}from"ethers";import{match as wn,P as Ye}from"ts-pattern";var Je=[{inputs:[{internalType:"address",name:"_owner",type:"address"}],stateMutability:"nonpayable",type:"constructor"},{anonymous:!1,inputs:[{indexed:!1,internalType:"uint256",name:"",type:"uint256"}],name:"DecimalsUpdated",type:"event"},{anonymous:!1,inputs:[{indexed:!1,internalType:"uint256",name:"",type:"uint256"}],name:"GasPriceUpdated",type:"event"},{anonymous:!1,inputs:[{indexed:!1,internalType:"uint256",name:"",type:"uint256"}],name:"L1BaseFeeUpdated",type:"event"},{anonymous:!1,inputs:[{indexed:!1,internalType:"uint256",name:"",type:"uint256"}],name:"OverheadUpdated",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"previousOwner",type:"address"},{indexed:!0,internalType:"address",name:"newOwner",type:"address"}],name:"OwnershipTransferred",type:"event"},{anonymous:!1,inputs:[{indexed:!1,internalType:"uint256",name:"",type:"uint256"}],name:"ScalarUpdated",type:"event"},{inputs:[],name:"decimals",outputs:[{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[],name:"gasPrice",outputs:[{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"bytes",name:"_data",type:"bytes"}],name:"getL1Fee",outputs:[{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"bytes",name:"_data",type:"bytes"}],name:"getL1GasUsed",outputs:[{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"uint256",name:"_gasUsed",type:"uint256"}],name:"getOperatorFee",outputs:[{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[],name:"l1BaseFee",outputs:[{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[],name:"overhead",outputs:[{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[],name:"owner",outputs:[{internalType:"address",name:"",type:"address"}],stateMutability:"view",type:"function"},{inputs:[],name:"renounceOwnership",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[],name:"scalar",outputs:[{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"uint256",name:"_decimals",type:"uint256"}],name:"setDecimals",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"uint256",name:"_gasPrice",type:"uint256"}],name:"setGasPrice",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"uint256",name:"_baseFee",type:"uint256"}],name:"setL1BaseFee",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"uint256",name:"_overhead",type:"uint256"}],name:"setOverhead",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"uint256",name:"_scalar",type:"uint256"}],name:"setScalar",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"address",name:"newOwner",type:"address"}],name:"transferOwnership",outputs:[],stateMutability:"nonpayable",type:"function"}];var hn="0x420000000000000000000000000000000000000f";function re(e){return new Pn(hn,Je,e)}function Ze(e){return async function(){let n=re(e);if(n&&"l1BaseFee"in n)return await n?.l1BaseFee();return}}function et(e){return async function({from:n,to:o,nonce:a,...r}){let{Transaction:i}=await import("ethers");if(!o)throw new q("toolbox_evm_invalid_transaction",{error:"Missing to address"});return i.from({...r,authorizationList:r.authorizationList,nonce:a??(n?await e.getTransactionCount(n,"pending"):0),to:o}).unsignedSerialized}}function we(e,t){return async function(o){let a=re(e),r=o.chainId??t??(await e.getNetwork()).chainId,i=await et(e)({...o,chainId:r});if(a&&"getL1Fee"in a){let s=await a.getL1Fee(i);if(typeof s!=="bigint")throw new q({errorKey:"toolbox_evm_invalid_transaction",info:{error:"Invalid OP-stack L1 fee"}});return s}return}}function he(e){return async function(n){let o=re(e);if(o&&"getOperatorFee"in o){let a=await o.getOperatorFee(n);if(typeof a!=="bigint")throw new q({errorKey:"toolbox_evm_invalid_transaction",info:{error:"Invalid OP-stack operator fee"}});return a}return 0n}}function vn(e,t){let n=we(e,t),o=he(e);return async function(r){if(r.gasLimit===void 0||r.gasLimit===null)throw new q({errorKey:"toolbox_evm_invalid_transaction",info:{error:"Missing gas limit for OP-stack fee estimation"}});let[i,s]=await Promise.all([n(r),o(BigInt(r.gasLimit.toString()))]);return(i??0n)+s}}function tt(e){return async function(n){let a=(await e.getFeeData()).gasPrice??0n,r=await e.estimateGas(n);return a*r}}function En(e){return async function(n){let o=await we(e)(n)??0n,a=await tt(e)(n),r=n.gasLimit??await e.estimateGas(n),i=await he(e)(BigInt(r.toString()));return o+a+i}}function _n(e){return async function(n){let o=re(e),a=await et(e)(n);if(o&&"getL1GasUsed"in o)return o.getL1GasUsed(a)}}function Te({feeOption:e,maxFeePerGas:t,maxPriorityFeePerGas:n}){let o=H(t,e),a=H(n,e);return{maxFeePerGas:Pe(o,a),maxPriorityFeePerGas:a}}function Cn(e){return async function(){try{let{maxFeePerGas:n,maxPriorityFeePerGas:o,gasPrice:a}=await e.getFeeData(),r=await Ze(e)(),i=a;if(!(n&&o))throw new q("toolbox_evm_no_fee_data");return{[S.Average]:{gasPrice:i,l1GasPrice:r,...Te({feeOption:S.Average,maxFeePerGas:n,maxPriorityFeePerGas:o})},[S.Fast]:{gasPrice:H(i,S.Fast),l1GasPrice:H(r||0n,S.Fast),...Te({feeOption:S.Fast,maxFeePerGas:n,maxPriorityFeePerGas:o})},[S.Fastest]:{gasPrice:H(i,S.Fastest),l1GasPrice:H(r||0n,S.Fastest),...Te({feeOption:S.Fastest,maxFeePerGas:n,maxPriorityFeePerGas:o})}}}catch(n){throw new q("toolbox_evm_gas_estimation_error",{error:n.msg??n.toString()})}}}function ie(e){return function({provider:n,...o}){let a=wn(o).with({phrase:Ye.string},({phrase:p,derivationPath:b,index:f=0})=>Tn.fromPhrase(p,void 0,bn(xn({chain:e,derivationPath:b,index:f}))).connect(n)).with({signer:Ye.any},({signer:p})=>p).otherwise(()=>{return}),r=Ze(n),i=BigInt(gn(e).chainId),s=we(n,i),c=vn(n,i),l=he(n),u=e===Qe.Optimism?Cn(n):void 0;return{...te({chain:e,estimateAdditionalFee:c,estimateGasPrices:u,provider:n,signer:a}),estimateL1Gas:_n(n),estimateL1GasCost:s,estimateL2GasCost:tt(n),estimateOperatorFee:l,estimateTotalGasCost:En(n),getBalance:Y(e).getBalance,getL1GasPrice:r}}}var nt=ie(Qe.Optimism);function at(e){let t=v(T.Ethereum)(e);async function n(o,a="0x5ba1e12693dc8f9c48aad8770482f4739beed696",r="aggregate",i=An.Fast){let s=await t.createContractTxObject({abi:Ie,contractAddress:a,funcName:r,funcParams:[o]});return t.sendTransaction({...s,feeOptionKey:i})}return{...t,multicall:n}}var rt=v(T.Adi),it=v(T.Arbitrum),st=v(T.Arc),ct=v(T.Aurora),ut=v(T.Avalanche),lt=ie(T.Base),mt=v(T.Berachain),pt=v(T.BinanceSmartChain),ft=v(T.Botanix),yt=v(T.Core),dt=v(T.Corn),bt=v(T.Cronos),gt=v(T.Gnosis),xt=v(T.Robinhood),Pt=v(T.Hyperevm),Tt=v(T.Linea),wt=v(T.Polygon),ht=v(T.MegaETH),vt=v(T.Monad),Et=v(T.Plasma),_t=v(T.Sonic),Ct=ie(T.Unichain),Ft=v(T.XLayer);function v(e){return function({provider:n,...o}){let a=Ae(e),r=On(o).with({phrase:ot.string},({phrase:s,derivationPath:c,index:l=0})=>Gn.fromPhrase(s,void 0,Fn(Mn({chain:e,derivationPath:c,index:l}))).connect(n)).with({signer:ot.any},({signer:s})=>s).otherwise(()=>{return});return te({chain:e,isEIP1559Compatible:a,provider:n,signer:r})}}function Vn(e,t){return In(e).with(x.Adi,()=>rt(t)).with(x.Arbitrum,()=>it(t)).with(x.Arc,()=>st(t)).with(x.Aurora,()=>ct(t)).with(x.Avalanche,()=>ut(t)).with(x.Base,()=>lt(t)).with(x.Berachain,()=>mt(t)).with(x.BinanceSmartChain,()=>pt(t)).with(x.Botanix,()=>ft(t)).with(x.Core,()=>yt(t)).with(x.Corn,()=>dt(t)).with(x.Cronos,()=>bt(t)).with(x.Ethereum,()=>at(t)).with(x.Gnosis,()=>gt(t)).with(x.Hyperevm,()=>Pt(t)).with(x.Linea,()=>Tt(t)).with(x.MegaETH,()=>ht(t)).with(x.Monad,()=>vt(t)).with(x.Optimism,()=>nt(t)).with(x.Plasma,()=>Et(t)).with(x.Polygon,()=>wt(t)).with(x.Robinhood,()=>xt(t)).with(x.Sonic,()=>_t(t)).with(x.Unichain,()=>Ct(t)).with(x.XLayer,()=>Ft(t)).exhaustive()}async function To(e,t){let n={...t,provider:t?.provider||Ce(e)};return Vn(e,n)}
|
|
2
|
+
export{Y as b,Kn as c,It as d,Nn as e,Ce as f,O as g,Fe as h,Ae as i,Me as j,St as k,Ge as l,Oe as m,Ln as n,Be as o,be as p,te as q,Ut as r,ne as s,ge as t,Kt as u,qt as v,Yn as w,oe as x,Qn as y,Yt as z,xe as A,W as B,X as C,We as D,rn as E,sn as F,Pe as G,Te as H,ie as I,nt as J,at as K,rt as L,it as M,st as N,ct as O,ut as P,lt as Q,mt as R,pt as S,ft as T,yt as U,dt as V,bt as W,gt as X,xt as Y,Pt as Z,Tt as _,wt as $,ht as aa,vt as ba,Et as ca,_t as da,Ct as ea,Ft as fa,Vn as ga,To as ha};
|
package/dist/src/evm/index.js
CHANGED
|
@@ -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-
|
|
1
|
+
import{a as ia}from"../../chunk-qsbf0z90.js";import{$ as _,A as z,B as A,C as B,D as C,E as D,F as E,G as F,H as G,I as H,J as I,K as J,L as K,M as L,N as M,O as N,P as O,Q as P,R as Q,S as R,T as S,U as T,V as U,W as V,X as W,Y as X,Z as Y,_ as Z,aa,b as a,ba,c as b,ca,d as c,da,e as d,ea,f as e,fa,g as f,ga,h as g,ha,i as h,j as i,k as j,l as k,m as l,n as m,o as n,p as o,q as p,r as q,s as r,t as s,u as t,v as u,w as v,x as w,y as x,z as y}from"../../chunk-6fcz98xe.js";import"../../chunk-qk8kg62t.js";import"../../chunk-pz8xe0qj.js";export{K as ADIToolbox,L as ARBToolbox,M as ARCToolbox,N as AURORAToolbox,O as AVAXToolbox,P as BASEToolbox,Q as BERAToolbox,R as BSCToolbox,p as BaseEVMToolbox,S as BotanixToolbox,T as COREToolbox,U as CORNToolbox,V as CROToolbox,y as ContractAddress,J as ETHToolbox,ia as EthNetwork,W as GNOToolbox,X as HOODToolbox,Y as HYPEREVMToolbox,Z as LINEAToolbox,_ as MATICToolbox,o as MAX_APPROVAL,aa as MEGAETHToolbox,ba as MONADToolbox,I as OPToolbox,ca as PLASMAToolbox,da as SONICToolbox,ea as UNIToolbox,fa as XLayerToolbox,k as buildEIP712DomainType,s as createContract,b as createCustomEvmApi,H as createOPStackToolbox,x as getChecksumAddressFromAsset,t as getCreateContract,A as getCreateContractTxObject,w as getEIP1193SendTransaction,E as getEVMTxType,B as getEstimateGasPrices,a as getEvmApi,ga as getEvmToolbox,ha as getEvmToolboxAsync,e as getFallbackProvider,h as getIsEIP1559Compatible,g as getNetworkParams,d as getProvider,c as getProviderSync,z as getTokenAddress,r as isBrowserProvider,D as isEIP1559Transaction,C as isEIP7702Transaction,u as isStateChangingCall,F as maxBigInt,l as normalizeTypedDataForSigner,m as parseEIP712FromEVMTx,G as scaleEIP1559Fees,i as signAuthorization,v as toChecksumAddress,f as toHexString,j as validateAuthorization,n as validateAuthorizations,q as validateEVMAddress};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import"../../chunk-qsbf0z90.js";import{m as we,r as Ue}from"../../chunk-2q4pxsyg.js";import"../../chunk-qk8kg62t.js";import"../../chunk-pz8xe0qj.js";function St({builder:e,grouping:t="na",orders:n}){return{builder:e,grouping:t,orders:n,type:"order"}}function Tt({cancels:e}){return{cancels:e,type:"cancel"}}function wt({cancels:e}){return{cancels:e,type:"cancelByCloid"}}function Ut({oid:e,order:t}){return{oid:e,order:t,type:"modify"}}function _t({modifies:e}){return{modifies:e,type:"batchModify"}}function Dt({asset:e,isCross:t,leverage:n}){return{asset:e,isCross:t,leverage:n,type:"updateLeverage"}}function Ot({asset:e,isBuy:t,ntli:n}){return{asset:e,isBuy:t,ntli:n,type:"updateIsolatedMargin"}}function kt({asset:e,leverage:t}){return{asset:e,leverage:t,type:"topUpIsolatedOnlyMargin"}}function Pt({time:e}){return{time:e,type:"scheduleCancel"}}function vt({amount:e,hyperliquidChain:t,nonce:n,signatureChainId:r,toPerp:i}){return{amount:e,hyperliquidChain:t,nonce:n,signatureChainId:r,toPerp:i,type:"usdClassTransfer"}}function se({amount:e,destination:t,destinationDex:n,fromSubAccount:r,hyperliquidChain:i,nonce:o,signatureChainId:s,sourceDex:p,token:u}){return{amount:e,destination:t,destinationDex:n,fromSubAccount:r,hyperliquidChain:i,nonce:o,signatureChainId:s,sourceDex:p,token:u,type:"sendAsset"}}function Rt({agentAddress:e,agentName:t,hyperliquidChain:n,nonce:r,signatureChainId:i}){return{agentAddress:e,agentName:t,hyperliquidChain:n,nonce:r,signatureChainId:i,type:"approveAgent"}}function It({builder:e,hyperliquidChain:t,maxFeeRate:n,nonce:r,signatureChainId:i}){return{builder:e,hyperliquidChain:t,maxFeeRate:n,nonce:r,signatureChainId:i,type:"approveBuilderFee"}}function qt({hyperliquidChain:e,isUndelegate:t,nonce:n,signatureChainId:r,validator:i,wei:o}){return{hyperliquidChain:e,isUndelegate:t,nonce:n,signatureChainId:r,type:"tokenDelegate",validator:i,wei:o}}import{SwapKitError as Ve,SwapKitNumber as Qe}from"@swapkit/helpers";import{HYPERCORE_USDC_TOKEN_ID as B}from"@swapkit/helpers/api";import{SwapKitError as V}from"@swapkit/helpers";import{keccak256 as Me,Signature as Fe}from"ethers";var I="0x0000000000000000000000000000000000000000",D="0xa4b1",q={name:"HyperliquidSignTransaction",verifyingContract:I,version:"1"},Le={chainId:1337,name:"Exchange",verifyingContract:I,version:"1"},je={Agent:[{name:"source",type:"string"},{name:"connectionId",type:"bytes32"}]},pe="Mainnet",Q={approveAgent:[{name:"hyperliquidChain",type:"string"},{name:"agentAddress",type:"address"},{name:"agentName",type:"string"},{name:"nonce",type:"uint64"}],approveBuilderFee:[{name:"hyperliquidChain",type:"string"},{name:"maxFeeRate",type:"string"},{name:"builder",type:"address"},{name:"nonce",type:"uint64"}],sendAsset:[{name:"hyperliquidChain",type:"string"},{name:"destination",type:"string"},{name:"sourceDex",type:"string"},{name:"destinationDex",type:"string"},{name:"token",type:"string"},{name:"amount",type:"string"},{name:"fromSubAccount",type:"string"},{name:"nonce",type:"uint64"}],tokenDelegate:[{name:"hyperliquidChain",type:"string"},{name:"validator",type:"address"},{name:"wei",type:"uint64"},{name:"isUndelegate",type:"bool"},{name:"nonce",type:"uint64"}],usdClassTransfer:[{name:"hyperliquidChain",type:"string"},{name:"amount",type:"string"},{name:"toPerp",type:"bool"},{name:"nonce",type:"uint64"}]},G={approveAgent:"HyperliquidTransaction:ApproveAgent",approveBuilderFee:"HyperliquidTransaction:ApproveBuilderFee",sendAsset:"HyperliquidTransaction:SendAsset",tokenDelegate:"HyperliquidTransaction:TokenDelegate",usdClassTransfer:"HyperliquidTransaction:UsdClassTransfer"},Ee=new TextEncoder;function b(...e){let t=e.reduce((i,o)=>i+o.length,0),n=new Uint8Array(t),r=0;for(let i of e)n.set(i,r),r+=i.length;return n}function Je(e,t,n){if(n<t)return new Uint8Array([e+n]);if(n<=255)return new Uint8Array([e+t,n]);if(n<=65535)return new Uint8Array([e+t+1,n>>8,n&255]);return new Uint8Array([e+t+2,n>>>24&255,n>>>16&255,n>>>8&255,n&255])}function v(e,t){let n=new Uint8Array(t),r=e;for(let i=t-1;i>=0;i-=1)n[i]=Number(r&0xffn),r>>=8n;return n}function ae(e){if(e>=0n){if(e<=0x7fn)return new Uint8Array([Number(e)]);if(e<=0xffn)return new Uint8Array([204,Number(e)]);if(e<=0xffffn)return b(new Uint8Array([205]),v(e,2));if(e<=0xffffffffn)return b(new Uint8Array([206]),v(e,4));return b(new Uint8Array([207]),v(e,8))}if(e>=-32n)return new Uint8Array([256+Number(e)]);if(e>=-128n)return new Uint8Array([208,256+Number(e)]);if(e>=-32768n)return b(new Uint8Array([209]),v(BigInt.asUintN(16,e),2));if(e>=-2147483648n)return b(new Uint8Array([210]),v(BigInt.asUintN(32,e),4));return b(new Uint8Array([211]),v(BigInt.asUintN(64,e),8))}function ce(e){let t=Ee.encode(e);if(t.length<32)return b(new Uint8Array([160+t.length]),t);return b(Je(217,0,t.length),t)}function ze(e){let t=e.map((r)=>Y(r)),n=e.length<16?new Uint8Array([144+e.length]):e.length<=65535?new Uint8Array([220,e.length>>8,e.length&255]):new Uint8Array([221,e.length>>>24&255,e.length>>>16&255,e.length>>>8&255,e.length&255]);return b(n,...t)}function Ke(e){let t=Object.entries(e).filter(([,r])=>typeof r<"u"),n=t.length<16?new Uint8Array([128+t.length]):t.length<=65535?new Uint8Array([222,t.length>>8,t.length&255]):new Uint8Array([223,t.length>>>24&255,t.length>>>16&255,t.length>>>8&255,t.length&255]);return b(n,...t.flatMap(([r,i])=>[ce(r),Y(i)]))}function Y(e){if(e===null)return new Uint8Array([192]);if(typeof e==="boolean")return new Uint8Array([e?195:194]);if(typeof e==="string")return ce(e);if(typeof e==="number"){if(!Number.isFinite(e)||!Number.isInteger(e))throw new V("helpers_invalid_params",{message:"Hyperliquid msgpack only supports integers"});return ae(BigInt(e))}if(typeof e==="bigint")return ae(e);if(e instanceof Uint8Array){let t=e.length<=255?new Uint8Array([196,e.length]):e.length<=65535?new Uint8Array([197,e.length>>8,e.length&255]):new Uint8Array([198,e.length>>>24&255,e.length>>>16&255,e.length>>>8&255,e.length&255]);return b(t,e)}if(Array.isArray(e))return ze(e);if(typeof e==="object")return Ke(e);throw new V("helpers_invalid_params",{message:`Unsupported Hyperliquid msgpack value: ${String(e)}`})}function We(e){let t=e.startsWith("0x")?e.slice(2):e;if(t.length%2!==0||/[^a-fA-F0-9]/u.test(t))throw new V("helpers_invalid_params",{hexValue:e});let n=new Uint8Array(t.length/2);for(let r=0;r<t.length;r+=2)n[r/2]=Number.parseInt(t.slice(r,r+2),16);return n}function de(e){return{domain:Le,message:{connectionId:e,source:"a"},primaryType:"Agent",types:{Agent:[...je.Agent]}}}function ye(e){let t=G[e.type],n=Q[e.type],{signatureChainId:r,type:i,...o}=e,s=Number.parseInt(r||D,16);return{domain:{...q,chainId:s},message:{...o,hyperliquidChain:o.hyperliquidChain||pe},primaryType:t,types:{[t]:n}}}function ue(e){let t=Fe.from(e);return{r:t.r,s:t.s,v:t.v}}function le(e,t,{expiresAfter:n,vaultAddress:r}={}){let i=Y(e),o=v(BigInt(t),8),s=r?b(new Uint8Array([1]),We(r.toLowerCase())):new Uint8Array([0]),p=typeof n==="number"?b(new Uint8Array([0]),v(BigInt(n),8)):new Uint8Array;return Me(b(i,o,s,p))}function ge(e){let t=e.hyperliquidChain||pe;switch(e.type){case"approveAgent":return{...e,agentAddress:e.agentAddress.toLowerCase(),hyperliquidChain:t};case"approveBuilderFee":return{...e,builder:e.builder.toLowerCase(),hyperliquidChain:t};case"sendAsset":return{...e,destination:e.destination.toLowerCase(),fromSubAccount:e.fromSubAccount.toLowerCase(),hyperliquidChain:t};case"tokenDelegate":return{...e,hyperliquidChain:t,validator:e.validator.toLowerCase()};case"usdClassTransfer":return{...e,hyperliquidChain:t};default:return e}}var fe=Number.parseInt(D,16),Ge=new Set(["chainId","name","verifyingContract","version"]),me=/^0x[0-9a-fA-F]{40}$/,X=Q.sendAsset;var c=(e)=>{throw new Ve("toolbox_hypercore_payload_mismatch",{problems:[e]})};function Ce(e){try{return new URL(e)}catch{return}}function Ae({action:e,allowedEndpoints:t,expectedAmount:n,expectedDestination:r,expectedDestinationDex:i,expectedFromSubAccount:o,expectedSourceDex:s,expectedToken:p,submitTo:u,typedData:S}){let{domain:h,message:m,primaryType:H,types:a}=S,d=G.sendAsset;if(H!==d)c(`primaryType is ${JSON.stringify(H)}, expected "${d}"`);if(e.type!=="sendAsset")c(`action.type is ${JSON.stringify(e.type)}, expected "sendAsset"`);let f=X.map(({name:y})=>y),x=new Set([...f,"signatureChainId","type"]),C=Object.keys(e).filter((y)=>!x.has(y));if(C.length)c(`action carries unexpected keys: ${C.join(", ")}`);for(let{name:y}of X)if(m[y]!==e[y])c(`${y}: signed ${JSON.stringify(m[y])} != submitted ${JSON.stringify(e[y])}`);let g=Object.keys(m),T=g.filter((y)=>!f.includes(y)),_=f.filter((y)=>!g.includes(y));if(T.length||_.length){let y=[T.length?`declares undeclared keys [${T.join(",")}]`:"",_.length?`is missing keys [${_.join(",")}]`:""].filter(Boolean).join(" / ");c(`message ${y}`)}let w=X.map(({name:y,type:W})=>`${y}:${W}`).join(","),R=(a[d]??[]).map(({name:y,type:W})=>`${y}:${W}`).join(",");if(R!==w)c(`types.${d} is [${R}], expected [${w}]`);let P=Object.keys(a).filter((y)=>y!==d&&y!=="EIP712Domain");if(P.length)c(`types carries unexpected entries: ${P.join(", ")}`);if(Number(h.chainId)!==fe)c(`domain.chainId is ${h.chainId}, expected ${fe} (Arbitrum)`);if(h.name!==q.name)c(`domain.name is ${JSON.stringify(h.name)}, expected "${q.name}"`);if(h.version!==q.version)c(`domain.version is ${JSON.stringify(h.version)}, expected "${q.version}"`);if(h.verifyingContract!==I)c(`domain.verifyingContract is ${h.verifyingContract}, expected the zero address`);let L=Object.keys(h).filter((y)=>!Ge.has(y));if(L.length)c(`domain carries unexpected keys: ${L.join(", ")}`);if(typeof e.signatureChainId!=="string"||e.signatureChainId.toLowerCase()!==D)c(`action.signatureChainId is ${JSON.stringify(e.signatureChainId)}, expected "${D}"`);if(e.hyperliquidChain!=="Mainnet")c(`action.hyperliquidChain is ${JSON.stringify(e.hyperliquidChain)}, expected "Mainnet"`);if(typeof e.nonce!=="number"||!Number.isSafeInteger(e.nonce)||e.nonce<=0)c(`action.nonce is ${JSON.stringify(e.nonce)}, expected a positive safe integer`);if(i!==""&&i!=="spot")c(`expectedDestinationDex ${JSON.stringify(i)} is not "" or "spot"`);if(e.destinationDex!==i)c(`action.destinationDex is ${JSON.stringify(e.destinationDex)}, expected ${JSON.stringify(i)}`);if(p!==B)c(`route sell token is ${JSON.stringify(p)}, expected "${B}"`);if(e.token!==p)c(`action.token is ${JSON.stringify(e.token)}, expected route sell token "${p}"`);if(e.sourceDex!==""&&e.sourceDex!=="spot")c(`action.sourceDex is ${JSON.stringify(e.sourceDex)}, expected "" or "spot"`);if(typeof e.sourceDex!=="string"||e.sourceDex!==s)c(`action.sourceDex is ${JSON.stringify(e.sourceDex)}, expected route sourceDex ${JSON.stringify(s)}`);let j=e.fromSubAccount;if(typeof j!=="string"||typeof o!=="string"||j.toLowerCase()!==o.toLowerCase())c(`action.fromSubAccount is ${JSON.stringify(e.fromSubAccount)}, expected ${JSON.stringify(o)}`);if(o&&!me.test(o))c(`expectedFromSubAccount ${JSON.stringify(o)} is not a well-formed 0x address`);if(!n)c("expectedAmount is missing — cannot verify action.amount");let re=!1;try{re=new Qe(String(e.amount)).eqValue(n)}catch{c(`action.amount ${JSON.stringify(e.amount)} is not comparable to ${n}`)}if(!re)c(`action.amount ${JSON.stringify(e.amount)} != route sell amount ${n}`);let z=typeof e.destination==="string"?e.destination:"";if(!me.test(z))c(`action.destination ${JSON.stringify(e.destination)} is not a well-formed 0x address`);if(!r)c("expectedDestination is missing — cannot verify action.destination");if(z.toLowerCase()!==r.toLowerCase())c(`action.destination ${z} != expected destination ${r}`);let ie=Ce(u),K=ie?.origin,oe=t.flatMap((y)=>Ce(y)?.origin??[]);if(ie?.protocol!=="https:")c(`submitTo ${JSON.stringify(u)} must be an https URL`);if(!K||!oe.includes(K))c(`submitTo origin ${K} is not one of the allowed exchange origins [${oe.join(", ")}]`)}import{AssetValue as M,Chain as Ye,derivationPathToString as Xe,getChainConfig as _e,getRPCUrl as Ze,NetworkDerivationPath as et,RequestClient as N,SwapKitError as l,SwapKitNumber as O,updateDerivationPath as tt}from"@swapkit/helpers";import{SwapKitApi as nt}from"@swapkit/helpers/api";import{HDNodeWallet as rt}from"ethers";import{match as it,P as Z}from"ts-pattern";var U=Ye.Hype,{baseDecimal:ee,rpcUrls:he}=_e(U),ot=he[0]?`${he[0]}/exchange`:void 0,st={HYPE:ee,USDC:6,USDT:6},De="Mainnet",at=/^\d+(?:\.\d+)?$/,pt=/^[^:]+:0x[0-9a-fA-F]+$/,ct={spotSend:[{name:"hyperliquidChain",type:"string"},{name:"destination",type:"string"},{name:"token",type:"string"},{name:"amount",type:"string"},{name:"time",type:"uint64"}]},dt={spotSend:"HyperliquidTransaction:SpotSend"};function A(e,t){if(!Ne(e))throw new l(t,{address:e});return e.toLowerCase()}function F(e){if(e===void 0)return;try{return new O(e)}catch{return}}var Oe={retry:{maxRetries:0},timeoutMs:5000};async function k({requestOptions:e,...t}){let n=await E();return N.post(`${n}/info`,{json:t,...e})}function te({dex:e,user:t}){return k({...e?{dex:e}:{},type:"clearinghouseState",user:A(t,"helpers_invalid_params")})}function ke({user:e}){return k({type:"spotClearinghouseState",user:A(e,"helpers_invalid_params")})}function yt({destination:e,sender:t}){let n=A(t,"helpers_invalid_params"),r=A(e,"helpers_invalid_params");return k({requestOptions:Oe,source:n,type:"preTransferCheck",user:r})}function ut({dex:e,user:t}){return k({...e?{dex:e}:{},type:"openOrders",user:A(t,"helpers_invalid_params")})}function lt({dex:e,user:t}){return k({...e?{dex:e}:{},type:"frontendOpenOrders",user:A(t,"helpers_invalid_params")})}function gt({oidOrCloid:e,user:t}){return k({oid:e,type:"orderStatus",user:A(t,"helpers_invalid_params")})}function ft({aggregateByTime:e,user:t}){return k({...typeof e==="boolean"?{aggregateByTime:e}:{},type:"userFills",user:A(t,"helpers_invalid_params")})}function mt({aggregateByTime:e,endTime:t,startTime:n,user:r}){return k({...typeof e==="boolean"?{aggregateByTime:e}:{},...typeof t==="number"?{endTime:t}:{},startTime:n,type:"userFillsByTime",user:A(r,"helpers_invalid_params")})}function He({coin:e,token:t,value:n,spotMeta:r}){if(!n||Number(n)<=0)return null;let i=e?.toUpperCase()||`TOKEN-${t||"UNKNOWN"}`,o=r?.tokens?.find((u)=>u.name===e||t!==void 0&&u.index===Number(t)),s=o?.weiDecimals??st[i]??ee,p=o?`${U}.${i}-${o.name}:${o.tokenId}`:`${U}.${i}`;return new M({decimal:s,identifier:p,value:n})}function Ct(e){let t=new Map;for(let n of e){let r=n.toString({includeSynthProtocol:!0}),i=t.get(r);t.set(r,i?i.add(n):n)}if(![...t.values()].some((n)=>n.isGasAsset||n.ticker==="HYPE")){let n=M.from({chain:U,value:0});t.set(n.toString({includeSynthProtocol:!0}),n)}return[...t.values()]}async function E(){try{return await Ze(U)}catch{let[e]=_e(U).rpcUrls;if(!e)throw new l("helpers_chain_no_public_or_set_rpc_url",{chain:U});return e}}async function J(){return`${await E()}/exchange`}function At(e){let t=dt[e.type],{type:n,...r}=e;return{domain:{chainId:Number.parseInt(e.signatureChainId,16),name:"HyperliquidSignTransaction",verifyingContract:I,version:"1"},message:r,primaryType:t,types:{[t]:ct[n]}}}async function ht({action:e,expiresAfter:t,nonce:n,vaultAddress:r}){let i=n||Date.now(),o=r?A(r,"helpers_invalid_params"):void 0,s=await J(),p=le(e,i,{expiresAfter:t,vaultAddress:o});return{action:e,endpoint:s,expiresAfter:t,nonce:i,typedData:de(p),vaultAddress:o}}async function Pe({action:e,endpoint:t,nonce:n,signatureChainId:r}){let i=n||e.nonce||Date.now(),o=r||e.signatureChainId||D,s=ge({...e,nonce:i,signatureChainId:o});return{action:s,endpoint:t??await J(),nonce:i,typedData:ye(s)}}async function ne({token:e,user:t}){let n=await ke({user:t}),i=(n.spotState?.balances||n.balances||[]).find(({coin:p})=>p&&e.startsWith(`${p}:`)),o=F(i?.total||0),s=F(i?.hold||0);return o&&s?o.sub(s):void 0}async function ve({assetValue:e,sender:t,token:n}){let r=(await ne({token:n,user:t}))?.getValue("string");if(!r||Number(r)<=0)throw new l("toolbox_sweep_amount_too_low",{asset:e.toString(),balance:r||"0"});return r}async function Ht(e){if(e.address&&pt.test(e.address))return e.address;let n=(await k({type:"spotMeta"}))?.tokens?.find(({name:r})=>r?.toUpperCase()===e.ticker.toUpperCase());if(n)return`${n.name}:${n.tokenId}`;throw new l("helpers_invalid_params",{asset:e.toString(),message:"Unable to resolve the HyperCore spot token id"})}async function Re({destination:e,sender:t}){let n;try{n=await yt({destination:e,sender:t})}catch(o){throw new l("toolbox_hypercore_pre_transfer_check_failed",o)}if(typeof n?.isSanctioned!=="boolean"||typeof n.userExists!=="boolean")throw new l("toolbox_hypercore_pre_transfer_check_failed",{response:n});let{fee:r}=n,i=typeof r==="string"&&at.test(r)?Number(r):Number.NaN;if(!Number.isFinite(i))throw new l("toolbox_hypercore_pre_transfer_check_failed",{response:n});if(n.isSanctioned)throw new l("toolbox_hypercore_destination_sanctioned",{destination:e,sender:t});return i}function Ie(e){return e.toUpperCase().startsWith("USDC:")}async function qe({activationFee:e,token:t,user:n}){if(e<=0)return;let[r,i]=await Promise.all([te({user:n}),ne({token:B,user:n})]),o=F(r.withdrawable||"0")??new O(0),s=i??new O(0);if(new O(e).lte(o)||new O(e).lte(s))return;throw new l("toolbox_hypercore_insufficient_balance",{activationFee:e,feeToken:B,perpsWithdrawable:o.getValue("string"),spotAvailable:s.getValue("string"),token:t})}async function $e({activationFee:e,amount:t,sourceDex:n,token:r,user:i}){let o=Ie(r),s=o?new O(t).add(e):new O(t);if(n!==void 0&&n!==""&&n!=="spot")throw new l("helpers_invalid_params",{message:"Unsupported HyperCore sourceDex",sourceDex:n});if(!o&&n==="")throw new l("helpers_invalid_params",{message:"Only a collateral token can be sent from a perp DEX",sourceDex:n,token:r});let p="0";if(o&&n!=="spot"){if(p=(await te({user:i})).withdrawable||"0",s.lte(F(p)??0))return"";if(n==="")throw new l("toolbox_hypercore_insufficient_balance",{amountRequired:s.getValue("string"),perpsWithdrawable:p,spotAvailable:"0",token:r})}let u=await ne({token:r,user:i})??new O(0);if(u.gte(s)){if(!o)await qe({activationFee:e,token:r,user:i});return"spot"}throw new l("toolbox_hypercore_insufficient_balance",{amountRequired:s.getValue("string"),perpsWithdrawable:p,spotAvailable:u.getValue("string"),token:r})}async function xt({amount:e,destination:t,sender:n,sourceDex:r,sweep:i,token:o}){if(i&&r!==void 0&&r!=="spot")throw new l("helpers_invalid_params",{message:"HyperCore sweep drains spot and requires sourceDex spot",sourceDex:r});let s=await Re({destination:t,sender:n});if(!i){let u=await $e({activationFee:s,amount:e,sourceDex:r,token:o,user:n});return{amount:e,sourceDex:u}}if(!Ie(o))return await qe({activationFee:s,token:o,user:n}),{amount:e,sourceDex:"spot"};if(s<=0)return{amount:e,sourceDex:"spot"};let p=new O(e).sub(s);if(p.lte(0))throw new l("toolbox_hypercore_insufficient_balance",{activationFee:s,spotAvailable:e,token:o});return{amount:p.getValue("string"),sourceDex:"spot"}}async function bt({assetValue:e,recipient:t,sender:n,signatureChainId:r,sweep:i,time:o,endpoint:s}){let p=A(t,"core_transaction_invalid_recipient_address"),u=A(n,"core_transaction_invalid_sender_address"),S=e.address;if(!S)throw new l("helpers_invalid_params",{asset:e.toString(),from:u});let h=i?await ve({assetValue:e,sender:u,token:S}):e.getValue("string"),m=s??await J(),H=o||Date.now(),a={amount:h,destination:p,hyperliquidChain:De,signatureChainId:r||D,time:H,token:S,type:"spotSend"};return{action:a,endpoint:m,nonce:H,typedData:At(a)}}async function xe({assetValue:e,destinationDex:t,endpoint:n,fromSubAccount:r,recipient:i,sender:o,signatureChainId:s,sourceDex:p,sweep:u,time:S}){let h=A(i,"core_transaction_invalid_recipient_address"),m=A(o,"core_transaction_invalid_sender_address"),H=r?A(r,"helpers_invalid_params"):"",a=H||m,d=await Ht(e),f=u?await ve({assetValue:e,sender:a,token:d}):e.getValue("string"),{amount:x,sourceDex:C}=await xt({amount:f,destination:h,sender:a,sourceDex:p,sweep:u,token:d}),g=se({amount:x,destination:h,destinationDex:t??"spot",fromSubAccount:H,hyperliquidChain:De,nonce:S||Date.now(),signatureChainId:s||D,sourceDex:C,token:d});return Pe({action:g,endpoint:n})}async function Be(e){let t=await N.post(e.endpoint,{json:{action:e.action,...typeof e.expiresAfter==="number"?{expiresAfter:e.expiresAfter}:{},nonce:e.nonce,signature:e.signature,vaultAddress:e.vaultAddress??null},retry:{maxRetries:0}});if(t?.status!=="ok")throw new l("core_transaction_failed",{definitive:t?.status==="err",response:t});return t}async function be({amount:e,destination:t,nonce:n,token:r,user:i}){let o=A(i,"helpers_invalid_params"),s=await E(),p=n-5000,u=t?.toLowerCase(),S=r?.toUpperCase(),h=({delta:m,time:H})=>{if(!(H&&H>=p&&m?.type==="send"&&m.nonce===n))return!1;if(u&&m?.destination?.toLowerCase()!==u)return!1;let a=F(m?.amount);if(e!==void 0&&!a?.eqValue(e))return!1;if(S!==void 0){if(!m?.token)return!1;let d=m.token.toUpperCase();if(d!==S&&!S.startsWith(`${d}:`))return!1}return!0};for(let m=0;m<8;m++){if(m>0)await new Promise((H)=>setTimeout(H,1500));try{let H=await N.post(`${s}/info`,{json:{startTime:p,type:"userNonFundingLedgerUpdates",user:o},...Oe}),a=Array.isArray(H)?H.find(h):void 0;if(a?.hash)return a.hash}catch{}}return""}async function Se({kind:e,lookup:t,signed:n}){try{await Be(n)}catch(i){if(i instanceof l&&i.errorKey==="core_transaction_failed"&&i.cause?.definitive===!0)throw i;let s=await be(t);if(s)return s;throw new l("toolbox_hypercore_transfer_hash_not_found",{broadcast:"unknown",guidance:"Delivery of this broadcast is unknown and the nonce is single-use — do not retry or re-sign; check the account ledger for the transfer first.",nonce:t.nonce,transportError:String(i)})}let r=await be(t);if(!r)throw new l("toolbox_hypercore_transfer_hash_not_found",{broadcast:"accepted",guidance:`Do not retry or re-sign — the exchange accepted this nonce, so re-submitting risks a duplicate ${e}. Check the account ledger for the transfer first.`,nonce:t.nonce});return r}function Te({action:e,nonce:t,user:n}){return{amount:e.amount,destination:e.destination,nonce:t,token:e.token,user:n}}function Ne(e){return e.startsWith("0x")&&Ue(e)}function Xt(e){let t=e&&"index"in e?e.index||0:0,n=Xe(e&&"derivationPath"in e&&e.derivationPath?e.derivationPath:tt(et[U],{index:t})),r,i=!1;function o(){if(i)return r;return r=it(e).with({phrase:Z.string},({phrase:a})=>rt.fromPhrase(a,void 0,n)).with({signer:Z.not(Z.nullish)},({signer:a})=>a).otherwise(()=>{return}),i=!0,r}async function s(){let a=o();return a?await a.getAddress():""}async function p(a){let d=o();if(!d)throw new l("toolbox_hypercore_no_signer");let f=we(a.typedData),x=await d.signTypedData(f.domain,f.types,f.message);return{action:a.action,endpoint:a.endpoint,nonce:a.nonce,signature:ue(x),..."expiresAfter"in a?{expiresAfter:a.expiresAfter}:{},..."vaultAddress"in a?{vaultAddress:a.vaultAddress}:{}}}async function u(a){let d=A(a,"helpers_invalid_params"),f=await E(),[x,C,g]=await Promise.all([N.post(`${f}/info`,{json:{type:"spotClearinghouseState",user:d}}),N.post(`${f}/info`,{json:{type:"clearinghouseState",user:d}}),N.post(`${f}/info`,{json:{type:"spotMeta"}})]),T=(x.spotState?.balances||x.balances||[]).map(({coin:w,token:R,total:P})=>He({coin:w,spotMeta:g,token:R,value:P})).filter((w)=>!!w),_=He({coin:"USDC",spotMeta:g,value:C.withdrawable||C.marginSummary?.accountValue||C.marginSummary?.totalRawUsd});return Ct(_?[...T,_]:T)}async function S(a,d=!0){let f=A(a,"helpers_invalid_params");try{let x=await nt.getChainBalance({address:f,chain:U,scamFilter:d});if(x.length){let C=x.map(({identifier:T,value:_,decimal:w})=>new M({decimal:w||ee,identifier:T,value:_}));return C.some((T)=>T.isGasAsset)?C:[M.from({chain:U}),...C]}}catch{}return u(f)}async function h({sweep:a,...d}){let f=o();if(!f)throw new l("toolbox_hypercore_no_signer");let x=d.sender||await f.getAddress(),C=await xe({...d,feeRate:0,sender:x,sweep:a}),g=await p(C);return Se({kind:"transfer",lookup:Te({action:C.action,nonce:C.nonce,user:C.action.fromSubAccount||x}),signed:g})}async function m(a){let d=o();if(!d)throw new l("toolbox_hypercore_no_signer");let{action:f,typedData:x,...C}=a,g=structuredClone(f),T=structuredClone(x),_=await d.getAddress(),w=await J(),R=[...new Set([w,ot??w])];Ae({...C,action:g,allowedEndpoints:R,typedData:T});let P=g.fromSubAccount?A(g.fromSubAccount,"helpers_invalid_params"):_,L=await Re({destination:g.destination,sender:P});await $e({activationFee:L,amount:g.amount,sourceDex:g.sourceDex,token:g.token,user:P});let j=await p({action:g,endpoint:w,nonce:g.nonce,typedData:T});return Se({kind:"payin",lookup:Te({action:g,nonce:g.nonce,user:P}),signed:j})}function H(){return M.from({chain:U,value:0})}return{broadcastTransaction:Be,createL1ActionRequest:ht,createSendAssetTransaction:xe,createTransaction:bt,createUserSignedActionRequest:Pe,estimateTransactionFee:H,getAddress:s,getBalance:S,getBalanceFromChain:u,getState:{clearinghouse:te,frontendOpenOrders:lt,openOrders:ut,orderStatus:gt,spotClearinghouse:ke,userFills:ft,userFillsByTime:mt},signAndBroadcastSendAsset:m,signTransaction:p,transfer:h,validateAddress:Ne}}export{B as HYPERCORE_USDC_TOKEN_ID,Rt as buildApproveAgentAction,It as buildApproveBuilderFeeAction,_t as buildBatchModifyAction,Tt as buildCancelAction,wt as buildCancelByCloidAction,Ut as buildModifyAction,St as buildOrderAction,Pt as buildScheduleCancelAction,se as buildSendAssetAction,qt as buildTokenDelegateAction,kt as buildTopUpIsolatedOnlyMarginAction,Ot as buildUpdateIsolatedMarginAction,Dt as buildUpdateLeverageAction,vt as buildUsdClassTransferAction,ht as createL1ActionRequest,xe as createSendAssetTransaction,bt as createTransaction,Pe as createUserSignedActionRequest,Xt as getHyperCoreToolbox,Ne as validateHyperCoreAddress};
|
|
1
|
+
import"../../chunk-qsbf0z90.js";import{m as we,r as Ue}from"../../chunk-6fcz98xe.js";import"../../chunk-qk8kg62t.js";import"../../chunk-pz8xe0qj.js";function St({builder:e,grouping:t="na",orders:n}){return{builder:e,grouping:t,orders:n,type:"order"}}function Tt({cancels:e}){return{cancels:e,type:"cancel"}}function wt({cancels:e}){return{cancels:e,type:"cancelByCloid"}}function Ut({oid:e,order:t}){return{oid:e,order:t,type:"modify"}}function _t({modifies:e}){return{modifies:e,type:"batchModify"}}function Dt({asset:e,isCross:t,leverage:n}){return{asset:e,isCross:t,leverage:n,type:"updateLeverage"}}function Ot({asset:e,isBuy:t,ntli:n}){return{asset:e,isBuy:t,ntli:n,type:"updateIsolatedMargin"}}function kt({asset:e,leverage:t}){return{asset:e,leverage:t,type:"topUpIsolatedOnlyMargin"}}function Pt({time:e}){return{time:e,type:"scheduleCancel"}}function vt({amount:e,hyperliquidChain:t,nonce:n,signatureChainId:r,toPerp:i}){return{amount:e,hyperliquidChain:t,nonce:n,signatureChainId:r,toPerp:i,type:"usdClassTransfer"}}function se({amount:e,destination:t,destinationDex:n,fromSubAccount:r,hyperliquidChain:i,nonce:o,signatureChainId:s,sourceDex:p,token:u}){return{amount:e,destination:t,destinationDex:n,fromSubAccount:r,hyperliquidChain:i,nonce:o,signatureChainId:s,sourceDex:p,token:u,type:"sendAsset"}}function Rt({agentAddress:e,agentName:t,hyperliquidChain:n,nonce:r,signatureChainId:i}){return{agentAddress:e,agentName:t,hyperliquidChain:n,nonce:r,signatureChainId:i,type:"approveAgent"}}function It({builder:e,hyperliquidChain:t,maxFeeRate:n,nonce:r,signatureChainId:i}){return{builder:e,hyperliquidChain:t,maxFeeRate:n,nonce:r,signatureChainId:i,type:"approveBuilderFee"}}function qt({hyperliquidChain:e,isUndelegate:t,nonce:n,signatureChainId:r,validator:i,wei:o}){return{hyperliquidChain:e,isUndelegate:t,nonce:n,signatureChainId:r,type:"tokenDelegate",validator:i,wei:o}}import{SwapKitError as Ve,SwapKitNumber as Qe}from"@swapkit/helpers";import{HYPERCORE_USDC_TOKEN_ID as B}from"@swapkit/helpers/api";import{SwapKitError as V}from"@swapkit/helpers";import{keccak256 as Me,Signature as Fe}from"ethers";var I="0x0000000000000000000000000000000000000000",D="0xa4b1",q={name:"HyperliquidSignTransaction",verifyingContract:I,version:"1"},Le={chainId:1337,name:"Exchange",verifyingContract:I,version:"1"},je={Agent:[{name:"source",type:"string"},{name:"connectionId",type:"bytes32"}]},pe="Mainnet",Q={approveAgent:[{name:"hyperliquidChain",type:"string"},{name:"agentAddress",type:"address"},{name:"agentName",type:"string"},{name:"nonce",type:"uint64"}],approveBuilderFee:[{name:"hyperliquidChain",type:"string"},{name:"maxFeeRate",type:"string"},{name:"builder",type:"address"},{name:"nonce",type:"uint64"}],sendAsset:[{name:"hyperliquidChain",type:"string"},{name:"destination",type:"string"},{name:"sourceDex",type:"string"},{name:"destinationDex",type:"string"},{name:"token",type:"string"},{name:"amount",type:"string"},{name:"fromSubAccount",type:"string"},{name:"nonce",type:"uint64"}],tokenDelegate:[{name:"hyperliquidChain",type:"string"},{name:"validator",type:"address"},{name:"wei",type:"uint64"},{name:"isUndelegate",type:"bool"},{name:"nonce",type:"uint64"}],usdClassTransfer:[{name:"hyperliquidChain",type:"string"},{name:"amount",type:"string"},{name:"toPerp",type:"bool"},{name:"nonce",type:"uint64"}]},G={approveAgent:"HyperliquidTransaction:ApproveAgent",approveBuilderFee:"HyperliquidTransaction:ApproveBuilderFee",sendAsset:"HyperliquidTransaction:SendAsset",tokenDelegate:"HyperliquidTransaction:TokenDelegate",usdClassTransfer:"HyperliquidTransaction:UsdClassTransfer"},Ee=new TextEncoder;function b(...e){let t=e.reduce((i,o)=>i+o.length,0),n=new Uint8Array(t),r=0;for(let i of e)n.set(i,r),r+=i.length;return n}function Je(e,t,n){if(n<t)return new Uint8Array([e+n]);if(n<=255)return new Uint8Array([e+t,n]);if(n<=65535)return new Uint8Array([e+t+1,n>>8,n&255]);return new Uint8Array([e+t+2,n>>>24&255,n>>>16&255,n>>>8&255,n&255])}function v(e,t){let n=new Uint8Array(t),r=e;for(let i=t-1;i>=0;i-=1)n[i]=Number(r&0xffn),r>>=8n;return n}function ae(e){if(e>=0n){if(e<=0x7fn)return new Uint8Array([Number(e)]);if(e<=0xffn)return new Uint8Array([204,Number(e)]);if(e<=0xffffn)return b(new Uint8Array([205]),v(e,2));if(e<=0xffffffffn)return b(new Uint8Array([206]),v(e,4));return b(new Uint8Array([207]),v(e,8))}if(e>=-32n)return new Uint8Array([256+Number(e)]);if(e>=-128n)return new Uint8Array([208,256+Number(e)]);if(e>=-32768n)return b(new Uint8Array([209]),v(BigInt.asUintN(16,e),2));if(e>=-2147483648n)return b(new Uint8Array([210]),v(BigInt.asUintN(32,e),4));return b(new Uint8Array([211]),v(BigInt.asUintN(64,e),8))}function ce(e){let t=Ee.encode(e);if(t.length<32)return b(new Uint8Array([160+t.length]),t);return b(Je(217,0,t.length),t)}function Ke(e){let t=e.map((r)=>Y(r)),n=e.length<16?new Uint8Array([144+e.length]):e.length<=65535?new Uint8Array([220,e.length>>8,e.length&255]):new Uint8Array([221,e.length>>>24&255,e.length>>>16&255,e.length>>>8&255,e.length&255]);return b(n,...t)}function ze(e){let t=Object.entries(e).filter(([,r])=>typeof r<"u"),n=t.length<16?new Uint8Array([128+t.length]):t.length<=65535?new Uint8Array([222,t.length>>8,t.length&255]):new Uint8Array([223,t.length>>>24&255,t.length>>>16&255,t.length>>>8&255,t.length&255]);return b(n,...t.flatMap(([r,i])=>[ce(r),Y(i)]))}function Y(e){if(e===null)return new Uint8Array([192]);if(typeof e==="boolean")return new Uint8Array([e?195:194]);if(typeof e==="string")return ce(e);if(typeof e==="number"){if(!Number.isFinite(e)||!Number.isInteger(e))throw new V("helpers_invalid_params",{message:"Hyperliquid msgpack only supports integers"});return ae(BigInt(e))}if(typeof e==="bigint")return ae(e);if(e instanceof Uint8Array){let t=e.length<=255?new Uint8Array([196,e.length]):e.length<=65535?new Uint8Array([197,e.length>>8,e.length&255]):new Uint8Array([198,e.length>>>24&255,e.length>>>16&255,e.length>>>8&255,e.length&255]);return b(t,e)}if(Array.isArray(e))return Ke(e);if(typeof e==="object")return ze(e);throw new V("helpers_invalid_params",{message:`Unsupported Hyperliquid msgpack value: ${String(e)}`})}function We(e){let t=e.startsWith("0x")?e.slice(2):e;if(t.length%2!==0||/[^a-fA-F0-9]/u.test(t))throw new V("helpers_invalid_params",{hexValue:e});let n=new Uint8Array(t.length/2);for(let r=0;r<t.length;r+=2)n[r/2]=Number.parseInt(t.slice(r,r+2),16);return n}function de(e){return{domain:Le,message:{connectionId:e,source:"a"},primaryType:"Agent",types:{Agent:[...je.Agent]}}}function ye(e){let t=G[e.type],n=Q[e.type],{signatureChainId:r,type:i,...o}=e,s=Number.parseInt(r||D,16);return{domain:{...q,chainId:s},message:{...o,hyperliquidChain:o.hyperliquidChain||pe},primaryType:t,types:{[t]:n}}}function ue(e){let t=Fe.from(e);return{r:t.r,s:t.s,v:t.v}}function le(e,t,{expiresAfter:n,vaultAddress:r}={}){let i=Y(e),o=v(BigInt(t),8),s=r?b(new Uint8Array([1]),We(r.toLowerCase())):new Uint8Array([0]),p=typeof n==="number"?b(new Uint8Array([0]),v(BigInt(n),8)):new Uint8Array;return Me(b(i,o,s,p))}function ge(e){let t=e.hyperliquidChain||pe;switch(e.type){case"approveAgent":return{...e,agentAddress:e.agentAddress.toLowerCase(),hyperliquidChain:t};case"approveBuilderFee":return{...e,builder:e.builder.toLowerCase(),hyperliquidChain:t};case"sendAsset":return{...e,destination:e.destination.toLowerCase(),fromSubAccount:e.fromSubAccount.toLowerCase(),hyperliquidChain:t};case"tokenDelegate":return{...e,hyperliquidChain:t,validator:e.validator.toLowerCase()};case"usdClassTransfer":return{...e,hyperliquidChain:t};default:return e}}var fe=Number.parseInt(D,16),Ge=new Set(["chainId","name","verifyingContract","version"]),me=/^0x[0-9a-fA-F]{40}$/,X=Q.sendAsset;var c=(e)=>{throw new Ve("toolbox_hypercore_payload_mismatch",{problems:[e]})};function Ce(e){try{return new URL(e)}catch{return}}function Ae({action:e,allowedEndpoints:t,expectedAmount:n,expectedDestination:r,expectedDestinationDex:i,expectedFromSubAccount:o,expectedSourceDex:s,expectedToken:p,submitTo:u,typedData:S}){let{domain:h,message:m,primaryType:H,types:a}=S,d=G.sendAsset;if(H!==d)c(`primaryType is ${JSON.stringify(H)}, expected "${d}"`);if(e.type!=="sendAsset")c(`action.type is ${JSON.stringify(e.type)}, expected "sendAsset"`);let f=X.map(({name:y})=>y),x=new Set([...f,"signatureChainId","type"]),C=Object.keys(e).filter((y)=>!x.has(y));if(C.length)c(`action carries unexpected keys: ${C.join(", ")}`);for(let{name:y}of X)if(m[y]!==e[y])c(`${y}: signed ${JSON.stringify(m[y])} != submitted ${JSON.stringify(e[y])}`);let g=Object.keys(m),T=g.filter((y)=>!f.includes(y)),_=f.filter((y)=>!g.includes(y));if(T.length||_.length){let y=[T.length?`declares undeclared keys [${T.join(",")}]`:"",_.length?`is missing keys [${_.join(",")}]`:""].filter(Boolean).join(" / ");c(`message ${y}`)}let w=X.map(({name:y,type:W})=>`${y}:${W}`).join(","),R=(a[d]??[]).map(({name:y,type:W})=>`${y}:${W}`).join(",");if(R!==w)c(`types.${d} is [${R}], expected [${w}]`);let P=Object.keys(a).filter((y)=>y!==d&&y!=="EIP712Domain");if(P.length)c(`types carries unexpected entries: ${P.join(", ")}`);if(Number(h.chainId)!==fe)c(`domain.chainId is ${h.chainId}, expected ${fe} (Arbitrum)`);if(h.name!==q.name)c(`domain.name is ${JSON.stringify(h.name)}, expected "${q.name}"`);if(h.version!==q.version)c(`domain.version is ${JSON.stringify(h.version)}, expected "${q.version}"`);if(h.verifyingContract!==I)c(`domain.verifyingContract is ${h.verifyingContract}, expected the zero address`);let L=Object.keys(h).filter((y)=>!Ge.has(y));if(L.length)c(`domain carries unexpected keys: ${L.join(", ")}`);if(typeof e.signatureChainId!=="string"||e.signatureChainId.toLowerCase()!==D)c(`action.signatureChainId is ${JSON.stringify(e.signatureChainId)}, expected "${D}"`);if(e.hyperliquidChain!=="Mainnet")c(`action.hyperliquidChain is ${JSON.stringify(e.hyperliquidChain)}, expected "Mainnet"`);if(typeof e.nonce!=="number"||!Number.isSafeInteger(e.nonce)||e.nonce<=0)c(`action.nonce is ${JSON.stringify(e.nonce)}, expected a positive safe integer`);if(i!==""&&i!=="spot")c(`expectedDestinationDex ${JSON.stringify(i)} is not "" or "spot"`);if(e.destinationDex!==i)c(`action.destinationDex is ${JSON.stringify(e.destinationDex)}, expected ${JSON.stringify(i)}`);if(p!==B)c(`route sell token is ${JSON.stringify(p)}, expected "${B}"`);if(e.token!==p)c(`action.token is ${JSON.stringify(e.token)}, expected route sell token "${p}"`);if(e.sourceDex!==""&&e.sourceDex!=="spot")c(`action.sourceDex is ${JSON.stringify(e.sourceDex)}, expected "" or "spot"`);if(typeof e.sourceDex!=="string"||e.sourceDex!==s)c(`action.sourceDex is ${JSON.stringify(e.sourceDex)}, expected route sourceDex ${JSON.stringify(s)}`);let j=e.fromSubAccount;if(typeof j!=="string"||typeof o!=="string"||j.toLowerCase()!==o.toLowerCase())c(`action.fromSubAccount is ${JSON.stringify(e.fromSubAccount)}, expected ${JSON.stringify(o)}`);if(o&&!me.test(o))c(`expectedFromSubAccount ${JSON.stringify(o)} is not a well-formed 0x address`);if(!n)c("expectedAmount is missing — cannot verify action.amount");let re=!1;try{re=new Qe(String(e.amount)).eqValue(n)}catch{c(`action.amount ${JSON.stringify(e.amount)} is not comparable to ${n}`)}if(!re)c(`action.amount ${JSON.stringify(e.amount)} != route sell amount ${n}`);let K=typeof e.destination==="string"?e.destination:"";if(!me.test(K))c(`action.destination ${JSON.stringify(e.destination)} is not a well-formed 0x address`);if(!r)c("expectedDestination is missing — cannot verify action.destination");if(K.toLowerCase()!==r.toLowerCase())c(`action.destination ${K} != expected destination ${r}`);let ie=Ce(u),z=ie?.origin,oe=t.flatMap((y)=>Ce(y)?.origin??[]);if(ie?.protocol!=="https:")c(`submitTo ${JSON.stringify(u)} must be an https URL`);if(!z||!oe.includes(z))c(`submitTo origin ${z} is not one of the allowed exchange origins [${oe.join(", ")}]`)}import{AssetValue as M,Chain as Ye,derivationPathToString as Xe,getChainConfig as _e,getRPCUrl as Ze,NetworkDerivationPath as et,RequestClient as N,SwapKitError as l,SwapKitNumber as O,updateDerivationPath as tt}from"@swapkit/helpers";import{SwapKitApi as nt}from"@swapkit/helpers/api";import{HDNodeWallet as rt}from"ethers";import{match as it,P as Z}from"ts-pattern";var U=Ye.Hype,{baseDecimal:ee,rpcUrls:he}=_e(U),ot=he[0]?`${he[0]}/exchange`:void 0,st={HYPE:ee,USDC:6,USDT:6},De="Mainnet",at=/^\d+(?:\.\d+)?$/,pt=/^[^:]+:0x[0-9a-fA-F]+$/,ct={spotSend:[{name:"hyperliquidChain",type:"string"},{name:"destination",type:"string"},{name:"token",type:"string"},{name:"amount",type:"string"},{name:"time",type:"uint64"}]},dt={spotSend:"HyperliquidTransaction:SpotSend"};function A(e,t){if(!Ne(e))throw new l(t,{address:e});return e.toLowerCase()}function F(e){if(e===void 0)return;try{return new O(e)}catch{return}}var Oe={retry:{maxRetries:0},timeoutMs:5000};async function k({requestOptions:e,...t}){let n=await E();return N.post(`${n}/info`,{json:t,...e})}function te({dex:e,user:t}){return k({...e?{dex:e}:{},type:"clearinghouseState",user:A(t,"helpers_invalid_params")})}function ke({user:e}){return k({type:"spotClearinghouseState",user:A(e,"helpers_invalid_params")})}function yt({destination:e,sender:t}){let n=A(t,"helpers_invalid_params"),r=A(e,"helpers_invalid_params");return k({requestOptions:Oe,source:n,type:"preTransferCheck",user:r})}function ut({dex:e,user:t}){return k({...e?{dex:e}:{},type:"openOrders",user:A(t,"helpers_invalid_params")})}function lt({dex:e,user:t}){return k({...e?{dex:e}:{},type:"frontendOpenOrders",user:A(t,"helpers_invalid_params")})}function gt({oidOrCloid:e,user:t}){return k({oid:e,type:"orderStatus",user:A(t,"helpers_invalid_params")})}function ft({aggregateByTime:e,user:t}){return k({...typeof e==="boolean"?{aggregateByTime:e}:{},type:"userFills",user:A(t,"helpers_invalid_params")})}function mt({aggregateByTime:e,endTime:t,startTime:n,user:r}){return k({...typeof e==="boolean"?{aggregateByTime:e}:{},...typeof t==="number"?{endTime:t}:{},startTime:n,type:"userFillsByTime",user:A(r,"helpers_invalid_params")})}function He({coin:e,token:t,value:n,spotMeta:r}){if(!n||Number(n)<=0)return null;let i=e?.toUpperCase()||`TOKEN-${t||"UNKNOWN"}`,o=r?.tokens?.find((u)=>u.name===e||t!==void 0&&u.index===Number(t)),s=o?.weiDecimals??st[i]??ee,p=o?`${U}.${i}-${o.name}:${o.tokenId}`:`${U}.${i}`;return new M({decimal:s,identifier:p,value:n})}function Ct(e){let t=new Map;for(let n of e){let r=n.toString({includeSynthProtocol:!0}),i=t.get(r);t.set(r,i?i.add(n):n)}if(![...t.values()].some((n)=>n.isGasAsset||n.ticker==="HYPE")){let n=M.from({chain:U,value:0});t.set(n.toString({includeSynthProtocol:!0}),n)}return[...t.values()]}async function E(){try{return await Ze(U)}catch{let[e]=_e(U).rpcUrls;if(!e)throw new l({errorKey:"helpers_chain_no_public_or_set_rpc_url",info:{chain:U}});return e}}async function J(){return`${await E()}/exchange`}function At(e){let t=dt[e.type],{type:n,...r}=e;return{domain:{chainId:Number.parseInt(e.signatureChainId,16),name:"HyperliquidSignTransaction",verifyingContract:I,version:"1"},message:r,primaryType:t,types:{[t]:ct[n]}}}async function ht({action:e,expiresAfter:t,nonce:n,vaultAddress:r}){let i=n||Date.now(),o=r?A(r,"helpers_invalid_params"):void 0,s=await J(),p=le(e,i,{expiresAfter:t,vaultAddress:o});return{action:e,endpoint:s,expiresAfter:t,nonce:i,typedData:de(p),vaultAddress:o}}async function Pe({action:e,endpoint:t,nonce:n,signatureChainId:r}){let i=n||e.nonce||Date.now(),o=r||e.signatureChainId||D,s=ge({...e,nonce:i,signatureChainId:o});return{action:s,endpoint:t??await J(),nonce:i,typedData:ye(s)}}async function ne({token:e,user:t}){let n=await ke({user:t}),i=(n.spotState?.balances||n.balances||[]).find(({coin:p})=>p&&e.startsWith(`${p}:`)),o=F(i?.total||0),s=F(i?.hold||0);return o&&s?o.sub(s):void 0}async function ve({assetValue:e,sender:t,token:n}){let r=(await ne({token:n,user:t}))?.getValue("string");if(!r||Number(r)<=0)throw new l("toolbox_sweep_amount_too_low",{asset:e.toString(),balance:r||"0"});return r}async function Ht(e){if(e.address&&pt.test(e.address))return e.address;let n=(await k({type:"spotMeta"}))?.tokens?.find(({name:r})=>r?.toUpperCase()===e.ticker.toUpperCase());if(n)return`${n.name}:${n.tokenId}`;throw new l("helpers_invalid_params",{asset:e.toString(),message:"Unable to resolve the HyperCore spot token id"})}async function Re({destination:e,sender:t}){let n;try{n=await yt({destination:e,sender:t})}catch(o){throw new l("toolbox_hypercore_pre_transfer_check_failed",o)}if(typeof n?.isSanctioned!=="boolean"||typeof n.userExists!=="boolean")throw new l("toolbox_hypercore_pre_transfer_check_failed",{response:n});let{fee:r}=n,i=typeof r==="string"&&at.test(r)?Number(r):Number.NaN;if(!Number.isFinite(i))throw new l("toolbox_hypercore_pre_transfer_check_failed",{response:n});if(n.isSanctioned)throw new l("toolbox_hypercore_destination_sanctioned",{destination:e,sender:t});return i}function Ie(e){return e.toUpperCase().startsWith("USDC:")}async function qe({activationFee:e,token:t,user:n}){if(e<=0)return;let[r,i]=await Promise.all([te({user:n}),ne({token:B,user:n})]),o=F(r.withdrawable||"0")??new O(0),s=i??new O(0);if(new O(e).lte(o)||new O(e).lte(s))return;throw new l("toolbox_hypercore_insufficient_balance",{activationFee:e,feeToken:B,perpsWithdrawable:o.getValue("string"),spotAvailable:s.getValue("string"),token:t})}async function $e({activationFee:e,amount:t,sourceDex:n,token:r,user:i}){let o=Ie(r),s=o?new O(t).add(e):new O(t);if(n!==void 0&&n!==""&&n!=="spot")throw new l("helpers_invalid_params",{message:"Unsupported HyperCore sourceDex",sourceDex:n});if(!o&&n==="")throw new l("helpers_invalid_params",{message:"Only a collateral token can be sent from a perp DEX",sourceDex:n,token:r});let p="0";if(o&&n!=="spot"){if(p=(await te({user:i})).withdrawable||"0",s.lte(F(p)??0))return"";if(n==="")throw new l("toolbox_hypercore_insufficient_balance",{amountRequired:s.getValue("string"),perpsWithdrawable:p,spotAvailable:"0",token:r})}let u=await ne({token:r,user:i})??new O(0);if(u.gte(s)){if(!o)await qe({activationFee:e,token:r,user:i});return"spot"}throw new l("toolbox_hypercore_insufficient_balance",{amountRequired:s.getValue("string"),perpsWithdrawable:p,spotAvailable:u.getValue("string"),token:r})}async function xt({amount:e,destination:t,sender:n,sourceDex:r,sweep:i,token:o}){if(i&&r!==void 0&&r!=="spot")throw new l("helpers_invalid_params",{message:"HyperCore sweep drains spot and requires sourceDex spot",sourceDex:r});let s=await Re({destination:t,sender:n});if(!i){let u=await $e({activationFee:s,amount:e,sourceDex:r,token:o,user:n});return{amount:e,sourceDex:u}}if(!Ie(o))return await qe({activationFee:s,token:o,user:n}),{amount:e,sourceDex:"spot"};if(s<=0)return{amount:e,sourceDex:"spot"};let p=new O(e).sub(s);if(p.lte(0))throw new l("toolbox_hypercore_insufficient_balance",{activationFee:s,spotAvailable:e,token:o});return{amount:p.getValue("string"),sourceDex:"spot"}}async function bt({assetValue:e,recipient:t,sender:n,signatureChainId:r,sweep:i,time:o,endpoint:s}){let p=A(t,"core_transaction_invalid_recipient_address"),u=A(n,"core_transaction_invalid_sender_address"),S=e.address;if(!S)throw new l("helpers_invalid_params",{asset:e.toString(),from:u});let h=i?await ve({assetValue:e,sender:u,token:S}):e.getValue("string"),m=s??await J(),H=o||Date.now(),a={amount:h,destination:p,hyperliquidChain:De,signatureChainId:r||D,time:H,token:S,type:"spotSend"};return{action:a,endpoint:m,nonce:H,typedData:At(a)}}async function xe({assetValue:e,destinationDex:t,endpoint:n,fromSubAccount:r,recipient:i,sender:o,signatureChainId:s,sourceDex:p,sweep:u,time:S}){let h=A(i,"core_transaction_invalid_recipient_address"),m=A(o,"core_transaction_invalid_sender_address"),H=r?A(r,"helpers_invalid_params"):"",a=H||m,d=await Ht(e),f=u?await ve({assetValue:e,sender:a,token:d}):e.getValue("string"),{amount:x,sourceDex:C}=await xt({amount:f,destination:h,sender:a,sourceDex:p,sweep:u,token:d}),g=se({amount:x,destination:h,destinationDex:t??"spot",fromSubAccount:H,hyperliquidChain:De,nonce:S||Date.now(),signatureChainId:s||D,sourceDex:C,token:d});return Pe({action:g,endpoint:n})}async function Be(e){let t=await N.post(e.endpoint,{json:{action:e.action,...typeof e.expiresAfter==="number"?{expiresAfter:e.expiresAfter}:{},nonce:e.nonce,signature:e.signature,vaultAddress:e.vaultAddress??null},retry:{maxRetries:0}});if(t?.status!=="ok")throw new l("core_transaction_failed",{definitive:t?.status==="err",response:t});return t}async function be({amount:e,destination:t,nonce:n,token:r,user:i}){let o=A(i,"helpers_invalid_params"),s=await E(),p=n-5000,u=t?.toLowerCase(),S=r?.toUpperCase(),h=({delta:m,time:H})=>{if(!(H&&H>=p&&m?.type==="send"&&m.nonce===n))return!1;if(u&&m?.destination?.toLowerCase()!==u)return!1;let a=F(m?.amount);if(e!==void 0&&!a?.eqValue(e))return!1;if(S!==void 0){if(!m?.token)return!1;let d=m.token.toUpperCase();if(d!==S&&!S.startsWith(`${d}:`))return!1}return!0};for(let m=0;m<8;m++){if(m>0)await new Promise((H)=>setTimeout(H,1500));try{let H=await N.post(`${s}/info`,{json:{startTime:p,type:"userNonFundingLedgerUpdates",user:o},...Oe}),a=Array.isArray(H)?H.find(h):void 0;if(a?.hash)return a.hash}catch{}}return""}async function Se({kind:e,lookup:t,signed:n}){try{await Be(n)}catch(i){if(i instanceof l&&i.errorKey==="core_transaction_failed"&&i.cause?.definitive===!0)throw i;let s=await be(t);if(s)return s;throw new l("toolbox_hypercore_transfer_hash_not_found",{broadcast:"unknown",guidance:"Delivery of this broadcast is unknown and the nonce is single-use — do not retry or re-sign; check the account ledger for the transfer first.",nonce:t.nonce,transportError:String(i)})}let r=await be(t);if(!r)throw new l("toolbox_hypercore_transfer_hash_not_found",{broadcast:"accepted",guidance:`Do not retry or re-sign — the exchange accepted this nonce, so re-submitting risks a duplicate ${e}. Check the account ledger for the transfer first.`,nonce:t.nonce});return r}function Te({action:e,nonce:t,user:n}){return{amount:e.amount,destination:e.destination,nonce:t,token:e.token,user:n}}function Ne(e){return e.startsWith("0x")&&Ue(e)}function Xt(e){let t=e&&"index"in e?e.index||0:0,n=Xe(e&&"derivationPath"in e&&e.derivationPath?e.derivationPath:tt(et[U],{index:t})),r,i=!1;function o(){if(i)return r;return r=it(e).with({phrase:Z.string},({phrase:a})=>rt.fromPhrase(a,void 0,n)).with({signer:Z.not(Z.nullish)},({signer:a})=>a).otherwise(()=>{return}),i=!0,r}async function s(){let a=o();return a?await a.getAddress():""}async function p(a){let d=o();if(!d)throw new l("toolbox_hypercore_no_signer");let f=we(a.typedData),x=await d.signTypedData(f.domain,f.types,f.message);return{action:a.action,endpoint:a.endpoint,nonce:a.nonce,signature:ue(x),..."expiresAfter"in a?{expiresAfter:a.expiresAfter}:{},..."vaultAddress"in a?{vaultAddress:a.vaultAddress}:{}}}async function u(a){let d=A(a,"helpers_invalid_params"),f=await E(),[x,C,g]=await Promise.all([N.post(`${f}/info`,{json:{type:"spotClearinghouseState",user:d}}),N.post(`${f}/info`,{json:{type:"clearinghouseState",user:d}}),N.post(`${f}/info`,{json:{type:"spotMeta"}})]),T=(x.spotState?.balances||x.balances||[]).map(({coin:w,token:R,total:P})=>He({coin:w,spotMeta:g,token:R,value:P})).filter((w)=>!!w),_=He({coin:"USDC",spotMeta:g,value:C.withdrawable||C.marginSummary?.accountValue||C.marginSummary?.totalRawUsd});return Ct(_?[...T,_]:T)}async function S(a,d=!0){let f=A(a,"helpers_invalid_params");try{let x=await nt.getChainBalance({address:f,chain:U,scamFilter:d});if(x.length){let C=x.map(({identifier:T,value:_,decimal:w})=>new M({decimal:w||ee,identifier:T,value:_}));return C.some((T)=>T.isGasAsset)?C:[M.from({chain:U}),...C]}}catch{}return u(f)}async function h({sweep:a,...d}){let f=o();if(!f)throw new l("toolbox_hypercore_no_signer");let x=d.sender||await f.getAddress(),C=await xe({...d,feeRate:0,sender:x,sweep:a}),g=await p(C);return Se({kind:"transfer",lookup:Te({action:C.action,nonce:C.nonce,user:C.action.fromSubAccount||x}),signed:g})}async function m(a){let d=o();if(!d)throw new l("toolbox_hypercore_no_signer");let{action:f,typedData:x,...C}=a,g=structuredClone(f),T=structuredClone(x),_=await d.getAddress(),w=await J(),R=[...new Set([w,ot??w])];Ae({...C,action:g,allowedEndpoints:R,typedData:T});let P=g.fromSubAccount?A(g.fromSubAccount,"helpers_invalid_params"):_,L=await Re({destination:g.destination,sender:P});await $e({activationFee:L,amount:g.amount,sourceDex:g.sourceDex,token:g.token,user:P});let j=await p({action:g,endpoint:w,nonce:g.nonce,typedData:T});return Se({kind:"payin",lookup:Te({action:g,nonce:g.nonce,user:P}),signed:j})}function H(){return M.from({chain:U,value:0})}return{broadcastTransaction:Be,createL1ActionRequest:ht,createSendAssetTransaction:xe,createTransaction:bt,createUserSignedActionRequest:Pe,estimateTransactionFee:H,getAddress:s,getBalance:S,getBalanceFromChain:u,getState:{clearinghouse:te,frontendOpenOrders:lt,openOrders:ut,orderStatus:gt,spotClearinghouse:ke,userFills:ft,userFillsByTime:mt},signAndBroadcastSendAsset:m,signTransaction:p,transfer:h,validateAddress:Ne}}export{B as HYPERCORE_USDC_TOKEN_ID,Rt as buildApproveAgentAction,It as buildApproveBuilderFeeAction,_t as buildBatchModifyAction,Tt as buildCancelAction,wt as buildCancelByCloidAction,Ut as buildModifyAction,St as buildOrderAction,Pt as buildScheduleCancelAction,se as buildSendAssetAction,qt as buildTokenDelegateAction,kt as buildTopUpIsolatedOnlyMarginAction,Ot as buildUpdateIsolatedMarginAction,Dt as buildUpdateLeverageAction,vt as buildUsdClassTransferAction,ht as createL1ActionRequest,xe as createSendAssetTransaction,bt as createTransaction,Pe as createUserSignedActionRequest,Xt as getHyperCoreToolbox,Ne as validateHyperCoreAddress};
|
package/dist/src/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{ka as o}from"../chunk-pz8xe0qj.js";import{AssetValue as k,Chain as t,CosmosChains as x,EVMChains as c,FeeOption as v,SubstrateChains as O,SwapKitError as V,UTXOChains as C}from"@swapkit/helpers";async function H(){let{match:l}=await import("ts-pattern"),{validateAleoAddress:r}=await import("./aleo/index.js"),{validateAptosAddress:s}=await import("./aptos/index.js"),{validateEVMAddress:e}=await import("./evm/index.js"),{validateCardanoAddress:a}=await import("./cardano/index.js"),{getCosmosAddressValidator:i}=await import("./cosmos/index.js"),{getSubstrateAddressValidator:p}=await import("./substrate/index.js"),{validateHyperCoreAddress:m}=await import("./hypercore/index.js"),{validateSolanaAddress:h}=await import("./solana/index.js"),{validateStarknetAddress:u}=await import("./starknet/index.js"),{validateSuiAddress:d}=await import("./sui/index.js"),{validateTonAddress:f}=await import("./ton/index.js"),{getUTXOAddressValidator:g}=await import("./utxo/index.js"),{validateNearAddress:w}=await import("./near/index.js"),{validateRadixAddress:S}=await import("./radix/index.js"),{validateRippleAddress:P}=await import("./ripple/index.js"),{validateTronAddress:A}=await import("./tron/index.js"),{validateStellarAddress:R}=await import("./stellar/index.js");return function({address:n,chain:W}){return l(W).with(...c,()=>e(n)).with(...C,(T)=>g(T)(n)).with(...x,(T)=>i(T)(n)).with(...O,(T)=>p({chain:T})(n)).with(t.Aleo,()=>r(n)).with(t.Aptos,()=>s(n)).with(t.Radix,()=>S(n)).with(t.Hype,()=>m(n)).with(t.Near,()=>w(n)).with(t.Ripple,()=>P(n)).with(t.Solana,()=>h(n)).with(t.Stellar,()=>R(n)).with(t.Starknet,()=>u(n)).with(t.Sui,()=>d(n)).with(t.Ton,()=>f(n)).with(t.Tron,()=>A(n)).with(t.Cardano,()=>a(n)).otherwise(()=>!1)}}function F(l){return async function(s){let{match:e}=await import("ts-pattern");return e(l).returnType().with(...c,async(a)=>{let i=await b(a),p=await i.createTransaction(s),m="feeOptionKey"in s?s.feeOptionKey:v.Fast;return i.estimateTransactionFee({...p,feeOption:m})}).with(t.Bitcoin,t.BitcoinCash,t.Dogecoin,t.Dash,t.Litecoin,t.Solana,t.Ripple,t.Tron,t.Near,t.Cardano,t.Hype,async(a)=>(await b(a)).estimateTransactionFee(s)).with(t.Aptos,async()=>{let{getAptosToolbox:a}=await import("./aptos/index.js");return a().estimateTransactionFee(s)}).with(t.Aleo,async()=>{let{getAleoToolbox:a}=await import("./aleo/index.js");return a().estimateTransactionFee(s)}).with(t.Starknet,async()=>{let{getStarknetToolbox:a}=await import("./starknet/index.js");return(await a()).estimateTransactionFee(s)}).with(t.Stellar,async()=>{let{getStellarToolbox:a}=await import("./stellar/index.js");return a().estimateTransactionFee()}).with(t.Sui,async()=>{let{getSuiToolbox:a}=await import("./sui/index.js");return a().estimateTransactionFee(s)}).with(t.Ton,async()=>{let{getTONToolbox:a}=await import("./ton/index.js");return a().estimateTransactionFee(s)}).with(...x,async()=>{let{estimateTransactionFee:a}=await import("./cosmos/index.js");return a(s)}).otherwise(async()=>k.from({chain:l}))}}async function b(l,r){let{match:s}=await import("ts-pattern");return s(l).returnType().with(...c,async()=>{let{getEvmToolboxAsync:e}=await import("../chunk-
|
|
1
|
+
import{ka as o}from"../chunk-pz8xe0qj.js";import{AssetValue as k,Chain as t,CosmosChains as x,EVMChains as c,FeeOption as v,SubstrateChains as O,SwapKitError as V,UTXOChains as C}from"@swapkit/helpers";async function H(){let{match:l}=await import("ts-pattern"),{validateAleoAddress:r}=await import("./aleo/index.js"),{validateAptosAddress:s}=await import("./aptos/index.js"),{validateEVMAddress:e}=await import("./evm/index.js"),{validateCardanoAddress:a}=await import("./cardano/index.js"),{getCosmosAddressValidator:i}=await import("./cosmos/index.js"),{getSubstrateAddressValidator:p}=await import("./substrate/index.js"),{validateHyperCoreAddress:m}=await import("./hypercore/index.js"),{validateSolanaAddress:h}=await import("./solana/index.js"),{validateStarknetAddress:u}=await import("./starknet/index.js"),{validateSuiAddress:d}=await import("./sui/index.js"),{validateTonAddress:f}=await import("./ton/index.js"),{getUTXOAddressValidator:g}=await import("./utxo/index.js"),{validateNearAddress:w}=await import("./near/index.js"),{validateRadixAddress:S}=await import("./radix/index.js"),{validateRippleAddress:P}=await import("./ripple/index.js"),{validateTronAddress:A}=await import("./tron/index.js"),{validateStellarAddress:R}=await import("./stellar/index.js");return function({address:n,chain:W}){return l(W).with(...c,()=>e(n)).with(...C,(T)=>g(T)(n)).with(...x,(T)=>i(T)(n)).with(...O,(T)=>p({chain:T})(n)).with(t.Aleo,()=>r(n)).with(t.Aptos,()=>s(n)).with(t.Radix,()=>S(n)).with(t.Hype,()=>m(n)).with(t.Near,()=>w(n)).with(t.Ripple,()=>P(n)).with(t.Solana,()=>h(n)).with(t.Stellar,()=>R(n)).with(t.Starknet,()=>u(n)).with(t.Sui,()=>d(n)).with(t.Ton,()=>f(n)).with(t.Tron,()=>A(n)).with(t.Cardano,()=>a(n)).otherwise(()=>!1)}}function F(l){return async function(s){let{match:e}=await import("ts-pattern");return e(l).returnType().with(...c,async(a)=>{let i=await b(a),p=await i.createTransaction(s),m="feeOptionKey"in s?s.feeOptionKey:v.Fast;return i.estimateTransactionFee({...p,feeOption:m})}).with(t.Bitcoin,t.BitcoinCash,t.Dogecoin,t.Dash,t.Litecoin,t.Solana,t.Ripple,t.Tron,t.Near,t.Cardano,t.Hype,async(a)=>(await b(a)).estimateTransactionFee(s)).with(t.Aptos,async()=>{let{getAptosToolbox:a}=await import("./aptos/index.js");return a().estimateTransactionFee(s)}).with(t.Aleo,async()=>{let{getAleoToolbox:a}=await import("./aleo/index.js");return a().estimateTransactionFee(s)}).with(t.Starknet,async()=>{let{getStarknetToolbox:a}=await import("./starknet/index.js");return(await a()).estimateTransactionFee(s)}).with(t.Stellar,async()=>{let{getStellarToolbox:a}=await import("./stellar/index.js");return a().estimateTransactionFee()}).with(t.Sui,async()=>{let{getSuiToolbox:a}=await import("./sui/index.js");return a().estimateTransactionFee(s)}).with(t.Ton,async()=>{let{getTONToolbox:a}=await import("./ton/index.js");return a().estimateTransactionFee(s)}).with(...x,async()=>{let{estimateTransactionFee:a}=await import("./cosmos/index.js");return a(s)}).otherwise(async()=>k.from({chain:l}))}}async function b(l,r){let{match:s}=await import("ts-pattern");return s(l).returnType().with(...c,async()=>{let{getEvmToolboxAsync:e}=await import("../chunk-3y8attb1.js");return await e(l,r)}).with(...C,async()=>{let{getUtxoToolbox:e}=await import("./utxo/index.js");return e(l,r)}).with(...x,async()=>{let{getCosmosToolbox:e}=await import("./cosmos/index.js");return e(l,r)}).with(t.Aleo,async()=>{let{getAleoToolbox:e}=await import("./aleo/index.js");return e(r)}).with(t.Aptos,async()=>{let{getAptosToolbox:e}=await import("./aptos/index.js");return e(r)}).with(t.Hype,async()=>{let{getHyperCoreToolbox:e}=await import("./hypercore/index.js");return e(r)}).with(t.Radix,async()=>{let{getRadixToolbox:e}=await import("./radix/index.js");return e(r)}).with(t.Ripple,async()=>{let{getRippleToolbox:e}=await import("./ripple/index.js");return e(r)}).with(t.Solana,async()=>{let{getSolanaToolbox:e}=await import("./solana/index.js");return e(r)}).with(t.Stellar,async()=>{let{getStellarToolbox:e}=await import("./stellar/index.js");return e(r)}).with(t.Starknet,async()=>{let{getStarknetToolbox:e}=await import("./starknet/index.js");return e(r)}).with(t.Sui,async()=>{let{getSuiToolbox:e}=await import("./sui/index.js");return e(r)}).with(t.Tron,async()=>{let{getTronToolbox:e}=await import("./tron/index.js");return e(r)}).with(t.Near,async()=>{let{getNearToolbox:e}=await import("./near/index.js");return e(r)}).with(t.Cardano,async()=>{let{getCardanoToolbox:e}=await import("./cardano/index.js");return e(r)}).with(t.Ton,async()=>{let{getTONToolbox:e}=await import("./ton/index.js");return e(r)}).otherwise(()=>{throw new V("toolbox_not_supported",{chain:l})})}export{H as getAddressValidator,F as getFeeEstimator,b as getToolbox};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{ka as b}from"../../chunk-pz8xe0qj.js";import{hexToU8a as M,isHex as _,u8aToHex as G}from"@polkadot/util";import{decodeAddress as T,encodeAddress as v}from"@polkadot/util-crypto";import{AssetValue as F,Chain as y,getRPCUrl as U,SubstrateChains as W,SwapKitError as d,SwapKitNumber as H}from"@swapkit/helpers";import{match as w,P as A}from"ts-pattern";import{AssetValue as K,Chain as B,SwapKitNumber as x}from"@swapkit/helpers";async function N(e,t,n){let a=[t.set(0)];if(!n)return a;try{let r=await e.query.system?.account?.(n);if(!r)return a;let{data:{free:i}}=r,c=x.fromBigInt(BigInt(i.toString()),t.decimal).getValue("string");return[t.set(c)]}catch(r){let i=r instanceof Error?r.message:String(r);return console.error(`Error fetching substrate balance: ${i}`),a}}async function j(e,t,n){let a=[t.set(0)];if(!n)return a;try{let r=await e.query.flip?.account?.(n);if(!r)return a;let i=r.balance||r.data?.balance;if(!i||i.isEmpty)return a;let c=x.fromBigInt(BigInt(i.toString()),t.decimal).getValue("string");return[t.set(c)]}catch(r){let i=r instanceof Error?r.message:String(r);return console.error(`Error fetching chainflip balance: ${i}`),a}}function I(e,t){return function(a){let r=K.from({chain:e});switch(e){case B.Chainflip:return j(t,r,a);default:return N(t,r,a)}}}var R={decimals:[10],displayName:"Polkadot Relay Chain",network:"polkadot",prefix:0,standardAccount:"*25519",symbols:["DOT"],website:"https://polkadot.network"},D={decimals:[18],displayName:"Chainflip",network:"chainflip",prefix:2112,standardAccount:"*25519",symbols:["FLIP"],website:"https://chainflip.io/"},V={decimals:[],displayName:"Substrate",network:"substrate",prefix:42,standardAccount:"*25519",symbols:[],website:"https://substrate.io/"},p={DOT:R,FLIP:D,GENERIC:V};function de(e,t){return w(e).with(...W,(n)=>ee({chain:n,...t})).exhaustive()}function f(e){return"address"in e}async function k(e,t){let{Keyring:n}=await import("@polkadot/keyring"),{cryptoWaitReady:a}=await import("@polkadot/util-crypto");return await a(),new n({ss58Format:t,type:"sr25519"}).addFromUri(e)}var S=(e,t)=>e.rpc.system.accountNextIndex(t),h=(e,{recipient:t,assetValue:n,sweep:a})=>{let r=a?e.tx.balances?.transferAll?.(t,!0):e.tx.balances?.transferAllowDeath?.(t,n.getBaseValue("
|
|
1
|
+
import{ka as b}from"../../chunk-pz8xe0qj.js";import{hexToU8a as M,isHex as _,u8aToHex as G}from"@polkadot/util";import{decodeAddress as T,encodeAddress as v}from"@polkadot/util-crypto";import{AssetValue as F,Chain as y,getRPCUrl as U,SubstrateChains as W,SwapKitError as d,SwapKitNumber as H}from"@swapkit/helpers";import{match as w,P as A}from"ts-pattern";import{AssetValue as K,Chain as B,SwapKitNumber as x}from"@swapkit/helpers";async function N(e,t,n){let a=[t.set(0)];if(!n)return a;try{let r=await e.query.system?.account?.(n);if(!r)return a;let{data:{free:i}}=r,c=x.fromBigInt(BigInt(i.toString()),t.decimal).getValue("string");return[t.set(c)]}catch(r){let i=r instanceof Error?r.message:String(r);return console.error(`Error fetching substrate balance: ${i}`),a}}async function j(e,t,n){let a=[t.set(0)];if(!n)return a;try{let r=await e.query.flip?.account?.(n);if(!r)return a;let i=r.balance||r.data?.balance;if(!i||i.isEmpty)return a;let c=x.fromBigInt(BigInt(i.toString()),t.decimal).getValue("string");return[t.set(c)]}catch(r){let i=r instanceof Error?r.message:String(r);return console.error(`Error fetching chainflip balance: ${i}`),a}}function I(e,t){return function(a){let r=K.from({chain:e});switch(e){case B.Chainflip:return j(t,r,a);default:return N(t,r,a)}}}var R={decimals:[10],displayName:"Polkadot Relay Chain",network:"polkadot",prefix:0,standardAccount:"*25519",symbols:["DOT"],website:"https://polkadot.network"},D={decimals:[18],displayName:"Chainflip",network:"chainflip",prefix:2112,standardAccount:"*25519",symbols:["FLIP"],website:"https://chainflip.io/"},V={decimals:[],displayName:"Substrate",network:"substrate",prefix:42,standardAccount:"*25519",symbols:[],website:"https://substrate.io/"},p={DOT:R,FLIP:D,GENERIC:V};function de(e,t){return w(e).with(...W,(n)=>ee({chain:n,...t})).exhaustive()}function f(e){return"address"in e}async function k(e,t){let{Keyring:n}=await import("@polkadot/keyring"),{cryptoWaitReady:a}=await import("@polkadot/util-crypto");return await a(),new n({ss58Format:t,type:"sr25519"}).addFromUri(e)}var S=(e,t)=>e.rpc.system.accountNextIndex(t),h=(e,{recipient:t,assetValue:n,sweep:a})=>{let r=a?e.tx.balances?.transferAll?.(t,!0):e.tx.balances?.transferAllowDeath?.(t,n.getBaseValue("bigint"));if(a&&!r)throw new d("toolbox_substrate_transfer_error");return r},m=(e,t)=>{if(e===y.Chainflip&&t)throw new d("toolbox_substrate_not_supported")},L=async(e,t,n)=>{let a=h(e,n);if(!a)throw new d("toolbox_substrate_transfer_error");let r=f(t),i=r?t.address:n.sender;if(!i)throw new d("core_transaction_invalid_sender_address");let c=await S(e,i);return(await a.signAndSend(r?t:i,{nonce:c,signer:r?void 0:t})).toString()},q=async(e,t,n,a)=>{let r=h(e,a),i=f(t)?t.address:a.sender;if(!i)return Promise.resolve(n.set(0));let c=await r?.paymentInfo(i,{nonce:await S(e,i)})||{partialFee:0};return n.set(H.fromBigInt(BigInt(c.partialFee.toString()),n.decimal).getValue("string"))},O=async(e,t)=>{if(t)return e.send(t);return(await e.send()).toString()},z=async(e,t)=>await t.signAsync(e),J=async(e,t,n)=>{if(n)return t.signAndSend(e,n);return(await t.signAndSend(e)).toString()},Q=async({signer:e,address:t,tx:n,callback:a,api:r})=>{let i=await S(r,t);if(a)return n.signAndSend(t,{nonce:i,signer:e},a);return(await n.signAndSend(t,{nonce:i,signer:e})).toString()};function X(e,t){let n=T(e);return v(n,t)}function C(e,t){return _(e)?M(e):T(e,void 0,t)}function Y(e,t="ss58",n){if(t==="hex")return G(e);return v(e,n)}function Z({chain:e,prefix:t}){let n=t||w(e).with(y.Polkadot,()=>p.DOT.prefix).with(y.Chainflip,()=>p.FLIP.prefix).otherwise(()=>p.GENERIC.prefix);return function(r){if(typeof r!=="string"||_(r))return!1;try{return C(r,n).length===32}catch{return!1}}}function ee({chain:e,generic:t=!1,...n}){let a=F.from({chain:e}),r;async function i(){let{ApiPromise:s,WsProvider:o}=await import("@polkadot/api"),u=await U(e),l=new o(u);return s.create({noInitWarn:!0,provider:l})}async function c(){if(r)return r;return r=await w(n).with({phrase:A.string},({phrase:s})=>k(s,p[e].prefix)).with({signer:A.any},({signer:s})=>s).otherwise(()=>{return}),r}let g=t?p.GENERIC:p[e];async function P(s){let o=await c(),u=s||o;if(!u)throw new d("core_wallet_not_keypair_wallet");return f(u)?u.address:void 0}return{broadcast:O,convertAddress:X,createKeyring:(s)=>k(s,g.prefix),createTransaction:async(s)=>{m(e,s.sweep);let o=await i();return h(o,s)},decodeAddress:C,encodeAddress:Y,estimateTransactionFee:async(s)=>{m(e,s.sweep);let o=await c();if(!o)throw new d("core_wallet_not_keypair_wallet");let u=await i();return q(u,o,a,s)},gasAsset:a,getAddress:P,getApi:i,getBalance:async(s)=>{let o=await i(),u=I(e,o),l=s||await P();return u(l)},network:g,sign:async(s)=>{let o=await c();if(!o)throw new d("core_wallet_not_keypair_wallet");if(f(o))return z(o,s);throw new d("core_wallet_not_keypair_wallet","Signer does not have keyring pair capabilities required for signing.")},signAndBroadcast:async({tx:s,callback:o,address:u})=>{let l=await c();if(!l)throw new d("core_wallet_not_keypair_wallet");if(f(l))return J(l,s,o);let E=await i();if(u)return Q({address:u,api:E,callback:o,signer:l,tx:s});throw new d("core_wallet_not_keypair_wallet","Signer does not have keyring pair capabilities required for signing.")},transfer:async(s)=>{m(e,s.sweep);let o=await c();if(!o)throw new d("core_wallet_not_keypair_wallet");let u=await i();return L(u,o,s)},validateAddress:Z({chain:e,prefix:g.prefix})}}export{p as SubstrateNetwork,k as createKeyring,ee as createSubstrateToolbox,Z as getSubstrateAddressValidator,de as getSubstrateToolbox,f as isKeyringPair};
|
package/package.json
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
{
|
|
2
|
-
"dependencies": { "@swapkit/helpers": "6.
|
|
2
|
+
"dependencies": { "@swapkit/helpers": "6.5.0", "@swapkit/utxo-signer": "3.3.0" },
|
|
3
3
|
"description": "SwapKit - Toolboxes",
|
|
4
4
|
"devDependencies": {
|
|
5
5
|
"@aptos-labs/ts-sdk": "7.0.1",
|
|
@@ -133,5 +133,5 @@
|
|
|
133
133
|
"type-check:go": "tsgo"
|
|
134
134
|
},
|
|
135
135
|
"type": "module",
|
|
136
|
-
"version": "6.6.
|
|
136
|
+
"version": "6.6.2"
|
|
137
137
|
}
|
package/dist/chunk-2q4pxsyg.js
DELETED
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
import{ja as Ve}from"./chunk-qk8kg62t.js";import{ka as de}from"./chunk-pz8xe0qj.js";import{Chain as x}from"@swapkit/helpers";import{match as In}from"ts-pattern";import{Chain as g,getChainConfig as J,getRPCUrl as At,SKConfig as Mt,SwapKitError as U}from"@swapkit/helpers";import{FallbackProvider as Gt,getAddress as Ee,Interface as Ot,JsonRpcProvider as se,Network as Bt}from"ethers";import{match as _e}from"ts-pattern";function It(e){return new se(e)}async function Nn(e,t){return It(t||await At(e))}function Ce(e){let t=Mt.get("rpcUrls")[e]?.filter(Boolean)??[];if(t.length===0)throw new U("helpers_chain_no_public_or_set_rpc_url",{chain:e});let{chainId:n}=J(e),o=Bt.from(Number(n)),[a]=t;if(t.length===1)return new se(a,o,{staticNetwork:o});return new Gt(t.map((r,i)=>({priority:i+1,provider:new se(r,o,{staticNetwork:o}),stallTimeout:2000})),o,{quorum:1})}function O(e){return e>0n?`0x${e.toString(16)}`:"0x0"}function Fe(e){let{explorerUrl:t,chainIdHex:n,rpcUrls:o}=J(e);return function(){return e!==g.Ethereum?{...Vt({chain:e}),blockExplorerUrls:[t],chainId:n,rpcUrls:o}:void 0}}function Ae(e){return![g.Adi,g.Arbitrum,g.BinanceSmartChain,g.Robinhood].includes(e)}function Vt({chain:e}){let{name:t,nativeCurrency:n,baseDecimal:o}=J(e);return _e(e).with(g.Arbitrum,()=>({chainName:"Arbitrum One",nativeCurrency:{decimals:o,name:"Ethereum",symbol:g.Ethereum}})).with(g.Aurora,()=>({chainName:"Aurora Mainnet",nativeCurrency:{decimals:o,name:"Ethereum",symbol:g.Ethereum}})).with(g.Avalanche,()=>({chainName:"Avalanche Network",nativeCurrency:{decimals:o,name:"Avalanche",symbol:e}})).with(g.Base,()=>({chainName:"Base Mainnet",nativeCurrency:{decimals:o,name:"Ethereum",symbol:g.Ethereum}})).with(g.Berachain,()=>({chainName:"Berachain",nativeCurrency:{decimals:o,name:"Berachain",symbol:"BERA"}})).with(g.XLayer,()=>({chainName:"X Layer",nativeCurrency:{decimals:o,name:"OKB",symbol:"OKB"}})).with(g.BinanceSmartChain,()=>({chainName:"BNB Smart Chain Mainnet",nativeCurrency:{decimals:o,name:"Binance Coin",symbol:"BNB"}})).with(g.Gnosis,()=>({chainName:"Gnosis",nativeCurrency:{decimals:o,name:"xDAI",symbol:"XDAI"}})).with(g.Optimism,()=>({chainName:"OP Mainnet",nativeCurrency:{decimals:o,name:"Ethereum",symbol:g.Ethereum}})).with(g.Polygon,()=>({chainName:"Polygon Mainnet",nativeCurrency:{decimals:o,name:"Polygon",symbol:g.Polygon}})).with(g.Robinhood,()=>({chainName:"Robinhood Chain",nativeCurrency:{decimals:o,name:"Ethereum",symbol:g.Ethereum}})).otherwise(()=>({chainName:t,nativeCurrency:{decimals:o,name:n,symbol:n}}))}async function Me(e,t){if(!("authorize"in e))throw Error("Signer does not support EIP-7702 authorization. Requires ethers.js v6.14+");let n={...t,nonce:t.nonce!==void 0?BigInt(t.nonce):void 0};return await e.authorize(n)}var ve=(e)=>typeof e==="string"&&/^0x[a-fA-F0-9]{64}$/.test(e),Rt=(e)=>{try{return typeof e==="string"&&!!Ee(e)}catch{return!1}};function St(e,t){let n=t!==void 0?`index ${t}: `:"",o=(a,r)=>{throw new U({errorKey:"toolbox_evm_invalid_eip7702_authorization",info:{field:a,message:`${n}${r}`}})};_e(e).when(({chainId:a})=>typeof a!=="bigint",()=>o("chainId","chainId must be a bigint")).when(({address:a})=>!Rt(a),()=>o("address","address must be a valid checksummed address")).when(({nonce:a})=>typeof a!=="bigint"||a<0n,()=>o("nonce","nonce must be a non-negative bigint")).when(({signature:a})=>!a,()=>o("signature","signature is required")).when(({signature:a})=>typeof a?.yParity!=="number"||![0,1].includes(a.yParity),()=>o("signature.yParity","yParity must be 0 or 1")).when(({signature:a})=>!ve(a?.r),()=>o("signature.r","r must be a 32-byte hex string")).when(({signature:a})=>!ve(a?.s),()=>o("signature.s","s must be a 32-byte hex string")).otherwise(()=>{})}function Ge(e){return[{key:"name",type:"string"},{key:"version",type:"string"},{key:"chainId",type:"uint256"},{key:"verifyingContract",type:"address"},{key:"salt",type:"bytes32"}].filter(({key:t})=>e[t]!=null).map(({key:t,type:n})=>({name:t,type:n}))}function Oe(e){if(!("EIP712Domain"in e.types))return e;let{EIP712Domain:t,...n}=e.types,o=Ge(e.domain);if(!(Array.isArray(t)&&t.length===o.length&&o.every(({name:r,type:i},s)=>t[s]?.name===r&&t[s]?.type===i)))throw new U({errorKey:"toolbox_evm_typed_data_domain_mismatch",info:{declared:t,expected:o}});return{...e,types:n}}function ce(e){return e.charAt(0).toUpperCase()+e.slice(1)}function ue(e,t){if(e.isTuple()&&e.components){let n=ce(e.name);return t[n]=e.components.map((o)=>({name:o.name,type:ue(o,t)})),n}if(e.isArray()){let n=e.arrayChildren;if(n?.isTuple()&&n.components){let o=ce(e.name.replace(/s$/,""));return t[o]=n.components.map((a)=>({name:a.name,type:ue(a,t)})),`${o}[]`}return`${n?.type??"bytes"}[]`}return e.type}function le(e,t){if(typeof e==="bigint")return e;if(t?.isTuple()&&typeof e?.toObject==="function"){let n=e.toObject(),o={};for(let[a,r]of(t.components??[]).entries())o[r.name]=le(n[r.name]??e[a],r);return o}if(Array.isArray(e)){let n=t?.arrayChildren;return e.map((o)=>le(o,n??void 0))}return e}function Ln({chain:e,abi:t,data:n,to:o}){let r=new Ot(t).parseTransaction({data:n});if(!r)throw new U({errorKey:"toolbox_evm_invalid_params",info:{error:"Could not decode calldata"}});let i={},s=ce(r.name);i[s]=r.fragment.inputs.map((p)=>({name:p.name,type:ue(p,i)}));let c={};for(let[p,b]of r.fragment.inputs.entries())c[b.name]=le(r.args[p],b);let{chainId:l}=J(e),u={chainId:Number(l),verifyingContract:Ee(o)},d=Ge(u);return{domain:u,message:c,primaryType:s,types:{EIP712Domain:d,...i}}}function Be(e,t){if(!Array.isArray(e)||e.length===0)throw new U({errorKey:"toolbox_evm_invalid_eip7702_authorization",info:{message:"EIP-7702 transactions require at least one authorization"}});for(let[n,o]of e.entries())if(St(o,n),t!==void 0&&o.chainId!==t)throw new U({errorKey:"toolbox_evm_invalid_eip7702_authorization",info:{field:"chainId",message:`index ${n}: authorization chainId (${o.chainId}) does not match transaction chainId (${t})`}})}import{Chain as T,derivationPathToString as Fn,FeeOption as An,resolveDerivationPath as Mn}from"@swapkit/helpers";import{HDNodeWallet as Gn}from"ethers";import{match as On,P as ot}from"ts-pattern";var Ie=[{inputs:[{components:[{internalType:"address",name:"target",type:"address"},{internalType:"bytes",name:"callData",type:"bytes"}],internalType:"struct Multicall2.Call[]",name:"calls",type:"tuple[]"}],name:"aggregate",outputs:[{internalType:"uint256",name:"blockNumber",type:"uint256"},{internalType:"bytes[]",name:"returnData",type:"bytes[]"}],stateMutability:"nonpayable",type:"function"},{inputs:[{components:[{internalType:"address",name:"target",type:"address"},{internalType:"bytes",name:"callData",type:"bytes"}],internalType:"struct Multicall2.Call[]",name:"calls",type:"tuple[]"}],name:"blockAndAggregate",outputs:[{internalType:"uint256",name:"blockNumber",type:"uint256"},{internalType:"bytes32",name:"blockHash",type:"bytes32"},{components:[{internalType:"bool",name:"success",type:"bool"},{internalType:"bytes",name:"returnData",type:"bytes"}],internalType:"struct Multicall2.Result[]",name:"returnData",type:"tuple[]"}],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"uint256",name:"blockNumber",type:"uint256"}],name:"getBlockHash",outputs:[{internalType:"bytes32",name:"blockHash",type:"bytes32"}],stateMutability:"view",type:"function"},{inputs:[],name:"getBlockNumber",outputs:[{internalType:"uint256",name:"blockNumber",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[],name:"getCurrentBlockCoinbase",outputs:[{internalType:"address",name:"coinbase",type:"address"}],stateMutability:"view",type:"function"},{inputs:[],name:"getCurrentBlockDifficulty",outputs:[{internalType:"uint256",name:"difficulty",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[],name:"getCurrentBlockGasLimit",outputs:[{internalType:"uint256",name:"gaslimit",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[],name:"getCurrentBlockTimestamp",outputs:[{internalType:"uint256",name:"timestamp",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"address",name:"addr",type:"address"}],name:"getEthBalance",outputs:[{internalType:"uint256",name:"balance",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[],name:"getLastBlockHash",outputs:[{internalType:"bytes32",name:"blockHash",type:"bytes32"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"bool",name:"requireSuccess",type:"bool"},{components:[{internalType:"address",name:"target",type:"address"},{internalType:"bytes",name:"callData",type:"bytes"}],internalType:"struct Multicall2.Call[]",name:"calls",type:"tuple[]"}],name:"tryAggregate",outputs:[{components:[{internalType:"bool",name:"success",type:"bool"},{internalType:"bytes",name:"returnData",type:"bytes"}],internalType:"struct Multicall2.Result[]",name:"returnData",type:"tuple[]"}],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"bool",name:"requireSuccess",type:"bool"},{components:[{internalType:"address",name:"target",type:"address"},{internalType:"bytes",name:"callData",type:"bytes"}],internalType:"struct Multicall2.Call[]",name:"calls",type:"tuple[]"}],name:"tryBlockAndAggregate",outputs:[{internalType:"uint256",name:"blockNumber",type:"uint256"},{internalType:"bytes32",name:"blockHash",type:"bytes32"},{components:[{internalType:"bool",name:"success",type:"bool"},{internalType:"bytes",name:"returnData",type:"bytes"}],internalType:"struct Multicall2.Result[]",name:"returnData",type:"tuple[]"}],stateMutability:"nonpayable",type:"function"}];import{AssetValue as kt,applyFeeMultiplierToBigInt as M,Chain as j,EVMChains as Nt,FeeOption as y,isGasAsset as ke,SwapKitError as m,SwapKitNumber as Q}from"@swapkit/helpers";import{erc20ABI as K}from"@swapkit/helpers/contracts";import{BrowserProvider as Lt,Contract as Ne,getAddress as ee,getBytes as Dt,Interface as Le,isError as D,resolveAddress as zt,Transaction as pe}from"ethers";import{match as De}from"ts-pattern";function Y(e){return{getBalance:Ve(e)}}function Kn(e){return e}var be=BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff");function te({chain:e=j.Ethereum,provider:t,signer:n,isEIP1559Compatible:o=!0,estimateGasPrices:a,estimateAdditionalFee:r}){let i=a??X({chain:e,isEIP1559Compatible:o,provider:t}),s=$e({chain:e,estimateAdditionalFee:r,estimateGasPrices:i,isEIP1559Compatible:o,provider:t,signer:n});return{approve:tn({chain:e,isEIP1559Compatible:o,provider:t,signer:n}),approvedAmount:qe({chain:e,provider:t}),broadcastTransaction:(c)=>t.broadcastTransaction(c),call:ae({chain:e,isEIP1559Compatible:o,provider:t,signer:n}),createApprovalTx:yn({chain:e,provider:t,signer:n}),createContract:Kt({chain:e,provider:t}),createContractTxObject:W({chain:e,provider:t}),createTransaction:s,createTransferTx:s,EIP1193SendTransaction:oe(t),estimateCall:je({provider:t,signer:n}),estimateGasLimit:on({chain:e,provider:t,signer:n}),estimateGasPrices:i,estimateTransactionFee:dn({chain:e,isEIP1559Compatible:o,provider:t}),getAddress:()=>n?n.getAddress():void 0,getBalance:Y(e).getBalance,getNetworkParams:Fe(e),isApproved:en({chain:e,provider:t}),sendTransaction:Xe({chain:e,estimateGasPrices:i,isEIP1559Compatible:o,provider:t,signer:n}),signAuthorization:an({signer:n}),signMessage:n?(c)=>n.signMessage(c):void 0,signTypedData:n?async(c)=>{let{domain:l,types:u,value:d}=Oe(c);return await n.signTypedData(l,u,d)}:void 0,transfer:nn({chain:e,estimateAdditionalFee:r,estimateGasPrices:i,isEIP1559Compatible:o,provider:t,signer:n}),validateAddress:Ut}}function Ut(e){try{return ee(e),!0}catch{return!1}}function ne(e){return e instanceof Lt}function ge(e,t,n){return new Ne(e,Le.from(t),n)}function Kt({provider:e}){return function(n,o){return new Ne(n,Le.from(o),e)}}var Ht=["payable","nonpayable"];function qt({abi:e,funcName:t}){let n=e.find((o)=>o.name===t);if(!n)throw new m("toolbox_evm_no_abi_fragment",{funcName:t});return n.stateMutability&&Ht.includes(n.stateMutability)}function Yn(e){return ee(e)}var jt=30000,Re=new WeakMap,Se=()=>{};function Wt(e,t,n){let o=Date.now();for(let[r,i]of e)if(i.held===0&&o-i.at>jt)e.delete(r);let a=e.get(t);if(!a||n>=a.next){let r={at:o,held:1,next:n+1,released:new Set};return e.set(t,r),{floor:r,nonce:n}}a.held+=1;for(let r of[...a.released].sort((i,s)=>i-s))if(a.released.delete(r),r>=n)return{floor:a,nonce:r};return{floor:a,nonce:a.next++}}async function ze({address:e,nonce:t,provider:n}){if(t!==void 0&&t!==null)return{nonce:t,release:Se,settle:Se};let{chainId:o}=await n.getNetwork(),a=Re.get(n)??new Map;Re.set(n,a);let r=`${o}:${e.toLowerCase()}`,i=await n.getTransactionCount(e,"pending"),{floor:s,nonce:c}=Wt(a,r,i),l=!1,u=(d)=>{if(l)return;if(l=!0,s.held-=1,s.at=Date.now(),d)s.released.add(c)};return{nonce:c,release:()=>u(!0),settle:()=>u(!1)}}function Z(e,t=0){if(!e||t>3)return"";if(typeof e==="string")return e.toLowerCase();if(typeof e!=="object")return"";let{error:n,info:o,message:a,shortMessage:r}=e;return[(typeof r==="string"?r:typeof a==="string"?a:"").toLowerCase(),Z(n,t+1),Z(o?.error,t+1)].filter(Boolean).join(" ")}function fe(e){if(D(e,"NONCE_EXPIRED")||D(e,"REPLACEMENT_UNDERPRICED"))return!0;let t=Z(e);return/nonce (?:is )?too low/.test(t)||t.includes("replacement transaction underpriced")}function ye(e){let t=Z(e);return t.includes("already known")||t.includes("known transaction")||t.includes("already imported")}function Ue(e){return D(e,"NETWORK_ERROR")||D(e,"SERVER_ERROR")||D(e,"TIMEOUT")}function Xt(e){return Ue(e)||D(e,"UNSUPPORTED_OPERATION")}function Ke(e){return Ue(e)||ye(e)}function He(e,t){return e.getTransaction(t).then((n)=>n!==null,()=>!1)}async function $t({provider:e,signer:t,txObject:n}){try{let o=pe.from(await t.signTransaction(n)).hash;return o&&await He(e,o)?o:null}catch{return null}}function oe(e,t=!1){return function({value:o,...a}){if(!ne(e))throw new m("toolbox_evm_provider_not_eip1193_compatible");let r={...a,gasPrice:"gasPrice"in a?a.gasPrice:void 0,maxFeePerGas:"maxFeePerGas"in a?a.maxFeePerGas:void 0,maxPriorityFeePerGas:"maxPriorityFeePerGas"in a?a.maxPriorityFeePerGas:void 0},{gasLimit:i,gasPrice:s,maxFeePerGas:c,maxPriorityFeePerGas:l,...u}=r,d={...u,...t&&i!==void 0&&{gas:O(BigInt(i))},...t&&s!==void 0&&{gasPrice:O(BigInt(s))},...t&&c!==void 0&&{maxFeePerGas:O(BigInt(c))},...t&&l!==void 0&&{maxPriorityFeePerGas:O(BigInt(l))},value:O(BigInt(o||0))};return e.send("eth_sendTransaction",[d])}}function Qn(e,t){let n=xe(e,t);if(n)return ee(n.toLowerCase());throw new m("toolbox_evm_invalid_gas_asset_address")}var Jt=Nt.reduce((e,t)=>(e[t]="0x0000000000000000000000000000000000000000",e),{}),Yt={...Jt,[j.Polygon]:"0x0000000000000000000000000000000000001010"},Qt="0x4200000000000000000000000000000000000042";function xe({chain:e,symbol:t,ticker:n},o){try{if(ke({chain:e,symbol:t}))return Yt[o];if(e===j.Optimism&&t==="OP")return Qt;return ee(t.slice(n.length+1).replace(/^0X/,""))}catch{return null}}function W({provider:e}){return async({contractAddress:t,abi:n,funcName:o,funcParams:a=[],txOverrides:r})=>{let i=await ge(t,n,e).getFunction(o).populateTransaction(...a.concat(r).filter((s)=>typeof s<"u"));return{...i,value:O(BigInt(i.value||0))}}}function X({chain:e,provider:t,isEIP1559Compatible:n=!0}){return De(e).with(j.Gnosis,()=>async function(){try{let{gasPrice:a,maxPriorityFeePerGas:r}=await t.getFeeData();if(!a||r===null)throw new m("toolbox_evm_no_fee_data");return{[y.Average]:{maxFeePerGas:M(a,y.Average),maxPriorityFeePerGas:M(r,y.Average)},[y.Fast]:{maxFeePerGas:M(a,y.Fast),maxPriorityFeePerGas:M(r,y.Fast)},[y.Fastest]:{maxFeePerGas:M(a,y.Fastest),maxPriorityFeePerGas:M(r,y.Fastest)}}}catch(a){throw new m("toolbox_evm_gas_estimation_error",{error:a.msg??a.toString()})}}).with(j.Arbitrum,()=>async function(){try{let{gasPrice:a}=await t.getFeeData();if(!a)throw new m("toolbox_evm_no_fee_data");let r=a*12n/10n;return{[y.Average]:{gasPrice:r},[y.Fast]:{gasPrice:M(r,y.Fast)},[y.Fastest]:{gasPrice:M(r,y.Fastest)}}}catch(a){throw new m("toolbox_evm_gas_estimation_error",{error:a.msg??a.toString()})}}).otherwise(()=>async function(){try{let{maxFeePerGas:a,maxPriorityFeePerGas:r,gasPrice:i}=await t.getFeeData();if(n){if(a===null||r===null)throw new m("toolbox_evm_no_fee_data");return{[y.Average]:{maxFeePerGas:a,maxPriorityFeePerGas:r},[y.Fast]:{maxFeePerGas:M(a,y.Fast),maxPriorityFeePerGas:M(r,y.Fast)},[y.Fastest]:{maxFeePerGas:M(a,y.Fastest),maxPriorityFeePerGas:M(r,y.Fastest)}}}if(!i)throw new m("toolbox_evm_no_gas_price");return{[y.Average]:{gasPrice:i},[y.Fast]:{gasPrice:M(i,y.Fast)},[y.Fastest]:{gasPrice:M(i,y.Fastest)}}}catch(a){throw new m("toolbox_evm_gas_estimation_error",{error:a.msg??a.toString()})}})}async function Zt({chain:e,contract:t,contractProvider:n,feeOption:o,funcName:a,funcParams:r,isEIP1559Compatible:i,provider:s,signer:c,txOverrides:l}){let u=l?.from||await c.getAddress();if(!u)throw new m("toolbox_evm_no_signer_address");let d=t.connect(c),p=X({chain:e,isEIP1559Compatible:i,provider:s}),[{maxFeePerGas:b,maxPriorityFeePerGas:f,gasPrice:P},A]=await Promise.all([p().then((_)=>_[o]),t.getFunction(a).estimateGas(...r,l)]),C=typeof u==="string"?u:await zt(u,n),{nonce:G,release:R,settle:k}=await ze({address:C,nonce:l?.nonce,provider:c.provider??s});try{let _=await d[a](...r,{...l,gasLimit:A,gasPrice:P,maxFeePerGas:b,maxPriorityFeePerGas:f,nonce:G});return typeof _?.hash==="string"?_?.hash:_}catch(_){if(fe(_)){let E=l?.nonce!=null?"caller":"pending",w={address:C,error:_,nonce:G,nonceSource:E};throw new m({errorKey:"toolbox_evm_nonce_conflict",info:w},w)}if(!Ke(_))R();throw _}finally{k()}}function ae({provider:e,isEIP1559Compatible:t,signer:n,chain:o}){return async function({callProvider:r,contractAddress:i,abi:s,funcName:c,funcParams:l=[],txOverrides:u={},feeOption:d=y.Fast}){let p=r||e;if(!i)throw new m("toolbox_evm_invalid_params",{error:"contractAddress must be provided"});let b=qt({abi:s,funcName:c});if(b&&ne(p)&&n){let A=W({chain:o,provider:p}),C=u?.from||await n?.getAddress(),G=await A({abi:s,contractAddress:i,funcName:c,funcParams:l,txOverrides:{...u,from:C}});return oe(p)(G)}let f=ge(i,s,p);if(b){if(!n)throw new m("toolbox_evm_no_signer");return Zt({chain:o,contract:f,contractProvider:p,feeOption:d,funcName:c,funcParams:l,isEIP1559Compatible:t,provider:e,signer:n,txOverrides:u})}let P=await f[c]?.(...l);return typeof P?.hash==="string"?P?.hash:P}}function qe({provider:e,chain:t}){return function({assetAddress:o,spenderAddress:a,from:r}){return ae({chain:t,isEIP1559Compatible:!0,provider:e})({abi:K,contractAddress:o,funcName:"allowance",funcParams:[r,a]})}}function en({provider:e,chain:t}){return async function({assetAddress:o,spenderAddress:a,from:r,amount:i=be}){let s=await qe({chain:t,provider:e})({assetAddress:o,from:r,spenderAddress:a});return Q.fromBigInt(s).gte(Q.fromBigInt(BigInt(i)))}}function tn({signer:e,isEIP1559Compatible:t=!0,provider:n,chain:o}){return async function({assetAddress:r,spenderAddress:i,feeOptionKey:s=y.Fast,amount:c,gasLimitFallback:l,from:u,nonce:d}){let p=[i,BigInt(c||be)],b=await e?.getAddress()||u,f={abi:K,contractAddress:r,funcName:"approve",funcParams:p,signer:e,txOverrides:{from:b}};if(ne(n)){let A=W({chain:o,provider:n}),C=oe(n),G=await A(f);return C(G)}return ae({chain:o,isEIP1559Compatible:t,provider:n,signer:e})({...f,feeOption:s,funcParams:p,txOverrides:{from:b,gasLimit:l?BigInt(l.toString()):void 0,nonce:d}})}}function nn({chain:e,estimateGasPrices:t,estimateAdditionalFee:n,signer:o,isEIP1559Compatible:a=!0,provider:r}){return async function({assetValue:s,memo:c,recipient:l,feeOptionKey:u=y.Fast,sender:d,sweep:p,...b}){let f=d||await o?.getAddress(),P=Xe({chain:e,estimateGasPrices:t,isEIP1559Compatible:a,provider:r,signer:o});if(!f)throw new m("toolbox_evm_no_from_address");let A=await $e({chain:e,estimateAdditionalFee:n,estimateGasPrices:t,isEIP1559Compatible:a,provider:r,signer:o})({assetValue:s,feeOptionKey:u,memo:c,recipient:l,sender:f,sweep:p,...b});return P({...A,feeOptionKey:u,sweep:p})}}function je({provider:e,signer:t}){return function({contractAddress:o,abi:a,funcName:r,funcParams:i=[],txOverrides:s}){if(!o)throw new m("toolbox_evm_no_contract_address");let c=ge(o,a,e);return t?c.connect(t).getFunction(r).estimateGas(...i,s):c.getFunction(r).estimateGas(...i,s)}}function on({provider:e,signer:t}){return async function({assetValue:o,recipient:a,memo:r,data:i,sender:s,funcName:c,funcParams:l,txOverrides:u}){let d=o.bigIntValue,p=o.isGasAsset?null:xe(o,o.chain);if(p&&c)return je({provider:e,signer:t})({abi:K,contractAddress:p,funcName:c,funcParams:l,txOverrides:u});let{hexlify:b,toUtf8Bytes:f}=await import("ethers");return e.estimateGas({data:i?i:r?b(f(r)):void 0,from:s,to:a,value:d})}}function an({signer:e}){if(!e)return;return(t)=>Me(e,t)}var We=(e)=>e.type===4||(e.authorizations?.length??0)>0,rn=(e)=>!We(e)&&(e.type===2||!!e.maxFeePerGas||!!e.maxPriorityFeePerGas),sn=(e,t=!0)=>{if(We(e))return"eip7702";if(rn(e))return"eip1559";if(e.gasPrice!=null)return"legacy";return t?"eip1559":"legacy"};function cn(e,t){if(e==="legacy"){if(t.gasPrice===void 0)throw new m("toolbox_evm_no_fee_data");return{gasPrice:O(t.gasPrice)}}if(t.maxFeePerGas===void 0||t.maxPriorityFeePerGas===void 0)throw new m("toolbox_evm_no_fee_data");return{maxFeePerGas:O(t.maxFeePerGas),maxPriorityFeePerGas:O(t.maxPriorityFeePerGas)}}function Xe({chain:e,estimateGasPrices:t,provider:n,signer:o,isEIP1559Compatible:a=!0}){return async function({feeOptionKey:i=y.Fast,sweep:s,...c}){let{from:l,to:u,data:d,value:p,...b}=c;if(!o)throw new m("toolbox_evm_no_signer");if(!u)throw new m("toolbox_evm_no_to_address");let f={...b,data:d||"0x",from:l,to:u,value:BigInt(p||0)};if(ne(n))return oe(n,s)(f);let P=l||await o.getAddress(),{chainId:A}=await n.getNetwork(),C=o.provider??n,{nonce:G,release:R,settle:k}=await ze({address:P,nonce:c.nonce,provider:C}),_=async()=>{let E=sn(f,a);if(E==="eip7702")Be(f.authorizations||[],A);let w=De(E).with("eip7702",()=>4).with("eip1559",()=>2).otherwise(()=>0),I={...f,chainId:A,nonce:G,type:w,...E==="eip7702"&&{authorizationList:f.authorizations}},F=t??X({chain:e,isEIP1559Compatible:a,provider:n}),V=(E==="legacy"?f.gasPrice!==void 0:f.maxFeePerGas!==void 0&&f.maxPriorityFeePerGas!==void 0)?{}:cn(E,(await F())[i]),h;try{h=O(f.gasLimit?BigInt(f.gasLimit):await n.estimateGas(I)*11n/10n)}catch(B){throw new m("toolbox_evm_error_estimating_gas_limit",{error:B})}return{...I,gasLimit:h,...V}};try{let E=await _().catch((w)=>{throw R(),w});try{return(await o.sendTransaction(E)).hash}catch(w){let I=c.nonce!=null?"caller":"pending",F={address:P,error:w,nonce:G,nonceSource:I};if(fe(w))throw new m({errorKey:"toolbox_evm_nonce_conflict",info:F},F);if(ye(w)){let h=await $t({provider:C,signer:o,txObject:{...E,from:P}});if(h)return h;throw new m({errorKey:"toolbox_evm_tx_already_known",info:F},F)}if(!Xt(w))throw R(),new m({errorKey:"toolbox_evm_error_sending_transaction",info:F},F);let N=D(w,"UNSUPPORTED_OPERATION"),V;try{V=await o.signTransaction({...E,from:P})}catch(h){if(N)R();let B={...F,fallbackError:h};throw new m({errorKey:"toolbox_evm_error_sending_transaction",info:B},B)}try{return(await C.broadcastTransaction(V)).hash}catch(h){let B={...F,fallbackError:h};if(ye(h)){let z=pe.from(V).hash;if(z)return z}if(fe(h)){let z=pe.from(V).hash;if(z&&await He(C,z))return z;throw new m({errorKey:"toolbox_evm_nonce_conflict",info:B},B)}if(N&&!Ke(h))R();throw new m({errorKey:"toolbox_evm_error_sending_transaction",info:B},B)}}}finally{k()}}}function L(e,t){throw new m({errorKey:"toolbox_sweep_amount_too_low",info:{balance:e.toString(),fee:t.toString()}})}function un(e,t){if(t){if(e.maxFeePerGas===void 0||e.maxPriorityFeePerGas===void 0)throw new m("toolbox_evm_no_fee_data");return{feeFields:{maxFeePerGas:e.maxFeePerGas,maxPriorityFeePerGas:e.maxPriorityFeePerGas},feePerGas:e.maxFeePerGas}}if(e.gasPrice===void 0)throw new m("toolbox_evm_no_fee_data");return{feeFields:{gasPrice:e.gasPrice},feePerGas:e.gasPrice}}function Pe(e,t){if(e>t)return e;return t}function ln(e){return Dt(e).reduce((t,n)=>t+(n===0?4n:16n),21000n)}function me(e){let n=(e instanceof Error?e.message:String(e)).toLowerCase();return n.includes("insufficient funds")||n.includes("insufficient balance")||n.includes("gas required exceeds allowance")}async function mn({balance:e,estimateAdditionalFee:t,feeOptionKey:n,l2Reserve:o,sweepTx:a,valueBeforeL1Fee:r}){if(!t)return 0n;let i=await t({...a,value:r})??0n,s=M(i,n),c=r-s;if(c<=0n)L(e,o+s);let l=await t({...a,value:c})??i;return M(Pe(i,l),n)}async function pn({chain:e,data:t,estimateGasPrices:n,estimateAdditionalFee:o,feeOptionKey:a,from:r,isEIP1559Compatible:i,provider:s,recipient:c,transaction:l}){let u=await s.getBalance(r),d=n??X({chain:e,isEIP1559Compatible:i,provider:s}),{feeFields:p,feePerGas:b}=un((await d())[a],i),f={...l,...p,data:t,from:r,to:c},P=ln(t)*b;if(u-P<=0n)L(u,P);let A=(u-P)/2n,C;try{C=await s.estimateGas({...f,value:A})}catch(h){if(!me(h))throw h;try{C=await s.estimateGas({...f,value:0n})}catch(B){if(me(B))L(u,P);throw B}}let G=C*b;if(u-G<=0n)L(u,G);let _=C*11n/10n*b,E=u>_?u-_:0n,w;try{w=await s.estimateGas({...f,value:E})}catch(h){if(!me(h))throw h;L(u,_)}let I=w*b,F=u-I;if(F<=0n)L(u,I);let N=await mn({balance:u,estimateAdditionalFee:o,feeOptionKey:a,l2Reserve:I,sweepTx:{...f,gasLimit:w},valueBeforeL1Fee:F}),V=F-N;if(V<=0n)L(u,I+N);return{...f,gasLimit:w,value:O(V)}}async function fn({chain:e,contractAddress:t,from:n,provider:o}){let a=await ae({chain:e,provider:o})({abi:K,contractAddress:t,funcName:"balanceOf",funcParams:[n]});if(typeof a!=="bigint")throw new m({errorKey:"toolbox_evm_invalid_transaction",info:{error:"Invalid ERC20 balance"}});return a}function $e({chain:e,estimateAdditionalFee:t,estimateGasPrices:n,isEIP1559Compatible:o=!0,provider:a,signer:r}){return async function({assetValue:s,authorizations:c,memo:l,recipient:u,data:d,feeOptionKey:p=y.Fast,gasLimit:b,sender:f,sweep:P,type:A,maxFeePerGas:C,maxPriorityFeePerGas:G,gasPrice:R,...k}){let _=s.getBaseValue("bigint"),E=f||await r?.getAddress();if(!E)throw new m("toolbox_evm_no_from_address");if(P&&(A===4||(c?.length??0)>0))throw new m({errorKey:"toolbox_not_supported",info:{chain:e,reason:"EIP-7702 sweep transactions are not supported"}});if(ke(s)){let{hexlify:N,toUtf8Bytes:V}=await import("ethers"),h=d||N(V(l||""));if(!P)return{...k,...c!==void 0&&{authorizations:c},data:h,from:E,...b!==void 0&&{gasLimit:b},to:u,...A!==void 0&&{type:A},value:O(_)};return pn({chain:e,data:h,estimateAdditionalFee:t,estimateGasPrices:n,feeOptionKey:p,from:E,isEIP1559Compatible:o,provider:a,recipient:u,transaction:{nonce:k.nonce,type:A}})}let w=xe(s,e);if(!w)throw new m("toolbox_evm_no_contract_address");let I=W({chain:e,provider:a}),F=P?await fn({chain:e,contractAddress:w,from:E,provider:a}):_;if(P&&F<=0n)throw new m({errorKey:"toolbox_sweep_amount_too_low",info:{asset:s.toString(),balance:F.toString()}});return I({abi:K,contractAddress:w,funcName:"transfer",funcParams:[u,F],txOverrides:{from:E,gasLimit:b,gasPrice:R,maxFeePerGas:C,maxPriorityFeePerGas:G,nonce:k.nonce}})}}function yn({provider:e,signer:t,chain:n}){return async function({assetAddress:a,spenderAddress:r,amount:i,from:s,nonce:c}){let l=await t?.getAddress()||s,u=W({chain:n,provider:e}),d=["bigint","number"].includes(typeof i)?i:i||be;return await u({abi:K,contractAddress:a,funcName:"approve",funcParams:[r,BigInt(d)],txOverrides:{from:l,nonce:c}})}}function dn({provider:e,isEIP1559Compatible:t=!0,chain:n}){return async function({feeOption:a=y.Fast,...r}){let s=await X({chain:n,isEIP1559Compatible:t,provider:e})(),c=await e.estimateGas(r),l=kt.from({chain:n}),{gasPrice:u,maxFeePerGas:d,maxPriorityFeePerGas:p}=s[a];if(!t&&u)return l.set(Q.fromBigInt(u*c,l.decimal));if(d&&p){let b=(d+p)*c;return l.set(Q.fromBigInt(b,l.decimal))}throw new m("toolbox_evm_no_gas_price")}}import{applyFeeMultiplierToBigInt as H,Chain as Qe,derivationPathToString as bn,FeeOption as S,getChainConfig as gn,resolveDerivationPath as xn,SwapKitError as q}from"@swapkit/helpers";import{Contract as Pn,HDNodeWallet as Tn}from"ethers";import{match as wn,P as Ye}from"ts-pattern";var Je=[{inputs:[{internalType:"address",name:"_owner",type:"address"}],stateMutability:"nonpayable",type:"constructor"},{anonymous:!1,inputs:[{indexed:!1,internalType:"uint256",name:"",type:"uint256"}],name:"DecimalsUpdated",type:"event"},{anonymous:!1,inputs:[{indexed:!1,internalType:"uint256",name:"",type:"uint256"}],name:"GasPriceUpdated",type:"event"},{anonymous:!1,inputs:[{indexed:!1,internalType:"uint256",name:"",type:"uint256"}],name:"L1BaseFeeUpdated",type:"event"},{anonymous:!1,inputs:[{indexed:!1,internalType:"uint256",name:"",type:"uint256"}],name:"OverheadUpdated",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"previousOwner",type:"address"},{indexed:!0,internalType:"address",name:"newOwner",type:"address"}],name:"OwnershipTransferred",type:"event"},{anonymous:!1,inputs:[{indexed:!1,internalType:"uint256",name:"",type:"uint256"}],name:"ScalarUpdated",type:"event"},{inputs:[],name:"decimals",outputs:[{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[],name:"gasPrice",outputs:[{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"bytes",name:"_data",type:"bytes"}],name:"getL1Fee",outputs:[{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"bytes",name:"_data",type:"bytes"}],name:"getL1GasUsed",outputs:[{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"uint256",name:"_gasUsed",type:"uint256"}],name:"getOperatorFee",outputs:[{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[],name:"l1BaseFee",outputs:[{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[],name:"overhead",outputs:[{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[],name:"owner",outputs:[{internalType:"address",name:"",type:"address"}],stateMutability:"view",type:"function"},{inputs:[],name:"renounceOwnership",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[],name:"scalar",outputs:[{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"uint256",name:"_decimals",type:"uint256"}],name:"setDecimals",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"uint256",name:"_gasPrice",type:"uint256"}],name:"setGasPrice",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"uint256",name:"_baseFee",type:"uint256"}],name:"setL1BaseFee",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"uint256",name:"_overhead",type:"uint256"}],name:"setOverhead",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"uint256",name:"_scalar",type:"uint256"}],name:"setScalar",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"address",name:"newOwner",type:"address"}],name:"transferOwnership",outputs:[],stateMutability:"nonpayable",type:"function"}];var hn="0x420000000000000000000000000000000000000f";function re(e){return new Pn(hn,Je,e)}function Ze(e){return async function(){let n=re(e);if(n&&"l1BaseFee"in n)return await n?.l1BaseFee();return}}function et(e){return async function({from:n,to:o,nonce:a,...r}){let{Transaction:i}=await import("ethers");if(!o)throw new q("toolbox_evm_invalid_transaction",{error:"Missing to address"});return i.from({...r,authorizationList:r.authorizationList,nonce:a??(n?await e.getTransactionCount(n,"pending"):0),to:o}).unsignedSerialized}}function we(e,t){return async function(o){let a=re(e),r=o.chainId??t??(await e.getNetwork()).chainId,i=await et(e)({...o,chainId:r});if(a&&"getL1Fee"in a){let s=await a.getL1Fee(i);if(typeof s!=="bigint")throw new q({errorKey:"toolbox_evm_invalid_transaction",info:{error:"Invalid OP-stack L1 fee"}});return s}return}}function he(e){return async function(n){let o=re(e);if(o&&"getOperatorFee"in o){let a=await o.getOperatorFee(n);if(typeof a!=="bigint")throw new q({errorKey:"toolbox_evm_invalid_transaction",info:{error:"Invalid OP-stack operator fee"}});return a}return 0n}}function vn(e,t){let n=we(e,t),o=he(e);return async function(r){if(r.gasLimit===void 0||r.gasLimit===null)throw new q({errorKey:"toolbox_evm_invalid_transaction",info:{error:"Missing gas limit for OP-stack fee estimation"}});let[i,s]=await Promise.all([n(r),o(BigInt(r.gasLimit.toString()))]);return(i??0n)+s}}function tt(e){return async function(n){let a=(await e.getFeeData()).gasPrice??0n,r=await e.estimateGas(n);return a*r}}function En(e){return async function(n){let o=await we(e)(n)??0n,a=await tt(e)(n),r=n.gasLimit??await e.estimateGas(n),i=await he(e)(BigInt(r.toString()));return o+a+i}}function _n(e){return async function(n){let o=re(e),a=await et(e)(n);if(o&&"getL1GasUsed"in o)return o.getL1GasUsed(a)}}function Te({feeOption:e,maxFeePerGas:t,maxPriorityFeePerGas:n}){let o=H(t,e),a=H(n,e);return{maxFeePerGas:Pe(o,a),maxPriorityFeePerGas:a}}function Cn(e){return async function(){try{let{maxFeePerGas:n,maxPriorityFeePerGas:o,gasPrice:a}=await e.getFeeData(),r=await Ze(e)(),i=a;if(!(n&&o))throw new q("toolbox_evm_no_fee_data");return{[S.Average]:{gasPrice:i,l1GasPrice:r,...Te({feeOption:S.Average,maxFeePerGas:n,maxPriorityFeePerGas:o})},[S.Fast]:{gasPrice:H(i,S.Fast),l1GasPrice:H(r||0n,S.Fast),...Te({feeOption:S.Fast,maxFeePerGas:n,maxPriorityFeePerGas:o})},[S.Fastest]:{gasPrice:H(i,S.Fastest),l1GasPrice:H(r||0n,S.Fastest),...Te({feeOption:S.Fastest,maxFeePerGas:n,maxPriorityFeePerGas:o})}}}catch(n){throw new q("toolbox_evm_gas_estimation_error",{error:n.msg??n.toString()})}}}function ie(e){return function({provider:n,...o}){let a=wn(o).with({phrase:Ye.string},({phrase:p,derivationPath:b,index:f=0})=>Tn.fromPhrase(p,void 0,bn(xn({chain:e,derivationPath:b,index:f}))).connect(n)).with({signer:Ye.any},({signer:p})=>p).otherwise(()=>{return}),r=Ze(n),i=BigInt(gn(e).chainId),s=we(n,i),c=vn(n,i),l=he(n),u=e===Qe.Optimism?Cn(n):void 0;return{...te({chain:e,estimateAdditionalFee:c,estimateGasPrices:u,provider:n,signer:a}),estimateL1Gas:_n(n),estimateL1GasCost:s,estimateL2GasCost:tt(n),estimateOperatorFee:l,estimateTotalGasCost:En(n),getBalance:Y(e).getBalance,getL1GasPrice:r}}}var nt=ie(Qe.Optimism);function at(e){let t=v(T.Ethereum)(e);async function n(o,a="0x5ba1e12693dc8f9c48aad8770482f4739beed696",r="aggregate",i=An.Fast){let s=await t.createContractTxObject({abi:Ie,contractAddress:a,funcName:r,funcParams:[o]});return t.sendTransaction({...s,feeOptionKey:i})}return{...t,multicall:n}}var rt=v(T.Adi),it=v(T.Arbitrum),st=v(T.Arc),ct=v(T.Aurora),ut=v(T.Avalanche),lt=ie(T.Base),mt=v(T.Berachain),pt=v(T.BinanceSmartChain),ft=v(T.Botanix),yt=v(T.Core),dt=v(T.Corn),bt=v(T.Cronos),gt=v(T.Gnosis),xt=v(T.Robinhood),Pt=v(T.Hyperevm),Tt=v(T.Linea),wt=v(T.Polygon),ht=v(T.MegaETH),vt=v(T.Monad),Et=v(T.Plasma),_t=v(T.Sonic),Ct=ie(T.Unichain),Ft=v(T.XLayer);function v(e){return function({provider:n,...o}){let a=Ae(e),r=On(o).with({phrase:ot.string},({phrase:s,derivationPath:c,index:l=0})=>Gn.fromPhrase(s,void 0,Fn(Mn({chain:e,derivationPath:c,index:l}))).connect(n)).with({signer:ot.any},({signer:s})=>s).otherwise(()=>{return});return te({chain:e,isEIP1559Compatible:a,provider:n,signer:r})}}function Vn(e,t){return In(e).with(x.Adi,()=>rt(t)).with(x.Arbitrum,()=>it(t)).with(x.Arc,()=>st(t)).with(x.Aurora,()=>ct(t)).with(x.Avalanche,()=>ut(t)).with(x.Base,()=>lt(t)).with(x.Berachain,()=>mt(t)).with(x.BinanceSmartChain,()=>pt(t)).with(x.Botanix,()=>ft(t)).with(x.Core,()=>yt(t)).with(x.Corn,()=>dt(t)).with(x.Cronos,()=>bt(t)).with(x.Ethereum,()=>at(t)).with(x.Gnosis,()=>gt(t)).with(x.Hyperevm,()=>Pt(t)).with(x.Linea,()=>Tt(t)).with(x.MegaETH,()=>ht(t)).with(x.Monad,()=>vt(t)).with(x.Optimism,()=>nt(t)).with(x.Plasma,()=>Et(t)).with(x.Polygon,()=>wt(t)).with(x.Robinhood,()=>xt(t)).with(x.Sonic,()=>_t(t)).with(x.Unichain,()=>Ct(t)).with(x.XLayer,()=>Ft(t)).exhaustive()}async function To(e,t){let n={...t,provider:t?.provider||Ce(e)};return Vn(e,n)}
|
|
2
|
-
export{Y as b,Kn as c,It as d,Nn as e,Ce as f,O as g,Fe as h,Ae as i,Me as j,St as k,Ge as l,Oe as m,Ln as n,Be as o,be as p,te as q,Ut as r,ne as s,ge as t,Kt as u,qt as v,Yn as w,oe as x,Qn as y,Yt as z,xe as A,W as B,X as C,We as D,rn as E,sn as F,Pe as G,Te as H,ie as I,nt as J,at as K,rt as L,it as M,st as N,ct as O,ut as P,lt as Q,mt as R,pt as S,ft as T,yt as U,dt as V,bt as W,gt as X,xt as Y,Pt as Z,Tt as _,wt as $,ht as aa,vt as ba,Et as ca,_t as da,Ct as ea,Ft as fa,Vn as ga,To as ha};
|