@swapkit/toolboxes 5.0.0 → 5.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,14 @@
1
1
  # @swapkit/toolboxes
2
2
 
3
+ ## 5.1.0
4
+
5
+ ### Minor Changes
6
+
7
+ - [#363](https://github.com/swapkit/sdk/pull/363) [`7b9f214`](https://github.com/swapkit/sdk/commit/7b9f2145e8644975620db1f2b39775c33cb40d20) Thanks [@towanTG](https://github.com/towanTG)! - HyperCore balances are now API-first: `getBalance` queries the SwapKit
8
+ - [#366](https://github.com/swapkit/sdk/pull/366) [`c64be1d`](https://github.com/swapkit/sdk/commit/c64be1d700ef8855495ca9d7ef0ebe18f46687ee) Thanks [@towanTG](https://github.com/towanTG)! - HyperCore chain-query balances take decimals from Hyperliquid spotMeta
9
+ - Update generated token lists. (via @swapkit/helpers@5.0.1)
10
+ - [#363](https://github.com/swapkit/sdk/pull/363) [`7b9f214`](https://github.com/swapkit/sdk/commit/7b9f2145e8644975620db1f2b39775c33cb40d20) Thanks [@towanTG](https://github.com/towanTG)! - Correct the Hyperliquid chain display names: `Chain.Hyperevm`'s config is now (via @swapkit/helpers@5.0.1)
11
+
3
12
  ## 5.0.0
4
13
 
5
14
  ### Major Changes
@@ -1 +1 @@
1
- import"../../chunk-44m22jy1.js";import{q as KH}from"../../chunk-55jkfkar.js";import{fa as VH}from"../../chunk-nvfkjbyq.js";import"../../chunk-xbdjxeqd.js";function qM({builder:H,grouping:M="na",orders:G}){return{builder:H,grouping:M,orders:G,type:"order"}}function FM({cancels:H}){return{cancels:H,type:"cancel"}}function VM({cancels:H}){return{cancels:H,type:"cancelByCloid"}}function KM({oid:H,order:M}){return{oid:H,order:M,type:"modify"}}function EM({modifies:H}){return{modifies:H,type:"batchModify"}}function BM({asset:H,isCross:M,leverage:G}){return{asset:H,isCross:M,leverage:G,type:"updateLeverage"}}function PM({asset:H,isBuy:M,ntli:G}){return{asset:H,isBuy:M,ntli:G,type:"updateIsolatedMargin"}}function wM({asset:H,leverage:M}){return{asset:H,leverage:M,type:"topUpIsolatedOnlyMargin"}}function TM({time:H}){return{time:H,type:"scheduleCancel"}}function AM({amount:H,hyperliquidChain:M,nonce:G,signatureChainId:J,toPerp:X}){return{amount:H,hyperliquidChain:M,nonce:G,signatureChainId:J,toPerp:X,type:"usdClassTransfer"}}function JH({amount:H,destination:M,destinationDex:G,fromSubAccount:J,hyperliquidChain:X,nonce:$,signatureChainId:Z,sourceDex:Q,token:C}){return{amount:H,destination:M,destinationDex:G,fromSubAccount:J,hyperliquidChain:X,nonce:$,signatureChainId:Z,sourceDex:Q,token:C,type:"sendAsset"}}function DM({agentAddress:H,agentName:M,hyperliquidChain:G,nonce:J,signatureChainId:X}){return{agentAddress:H,agentName:M,hyperliquidChain:G,nonce:J,signatureChainId:X,type:"approveAgent"}}function bM({builder:H,hyperliquidChain:M,maxFeeRate:G,nonce:J,signatureChainId:X}){return{builder:H,hyperliquidChain:M,maxFeeRate:G,nonce:J,signatureChainId:X,type:"approveBuilderFee"}}function yM({hyperliquidChain:H,isUndelegate:M,nonce:G,signatureChainId:J,validator:X,wei:$}){return{hyperliquidChain:H,isUndelegate:M,nonce:G,signatureChainId:J,type:"tokenDelegate",validator:X,wei:$}}import{SwapKitError as iH,SwapKitNumber as oH}from"@swapkit/helpers";import{HYPERCORE_USDC_TOKEN_ID as x}from"@swapkit/helpers/api";import{SwapKitError as r}from"@swapkit/helpers";import{keccak256 as gH,Signature as vH}from"ethers";var k="0x0000000000000000000000000000000000000000",P="0xa4b1",S={name:"HyperliquidSignTransaction",verifyingContract:k,version:"1"},pH={chainId:1337,name:"Exchange",verifyingContract:k,version:"1"},mH={Agent:[{name:"source",type:"string"},{name:"connectionId",type:"bytes32"}]},ZH="Mainnet",i={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"}]},o={approveAgent:"HyperliquidTransaction:ApproveAgent",approveBuilderFee:"HyperliquidTransaction:ApproveBuilderFee",sendAsset:"HyperliquidTransaction:SendAsset",tokenDelegate:"HyperliquidTransaction:TokenDelegate",usdClassTransfer:"HyperliquidTransaction:UsdClassTransfer"},lH=new TextEncoder;function F(...H){let M=H.reduce((X,$)=>X+$.length,0),G=new Uint8Array(M),J=0;for(let X of H)G.set(X,J),J+=X.length;return G}function uH(H,M,G){if(G<M)return new Uint8Array([H+G]);if(G<=255)return new Uint8Array([H+M,G]);if(G<=65535)return new Uint8Array([H+M+1,G>>8,G&255]);return new Uint8Array([H+M+2,G>>>24&255,G>>>16&255,G>>>8&255,G&255])}function D(H,M){let G=new Uint8Array(M),J=H;for(let X=M-1;X>=0;X-=1)G[X]=Number(J&0xffn),J>>=8n;return G}function XH(H){if(H>=0n){if(H<=0x7fn)return new Uint8Array([Number(H)]);if(H<=0xffn)return new Uint8Array([204,Number(H)]);if(H<=0xffffn)return F(new Uint8Array([205]),D(H,2));if(H<=0xffffffffn)return F(new Uint8Array([206]),D(H,4));return F(new Uint8Array([207]),D(H,8))}if(H>=-32n)return new Uint8Array([256+Number(H)]);if(H>=-128n)return new Uint8Array([208,256+Number(H)]);if(H>=-32768n)return F(new Uint8Array([209]),D(BigInt.asUintN(16,H),2));if(H>=-2147483648n)return F(new Uint8Array([210]),D(BigInt.asUintN(32,H),4));return F(new Uint8Array([211]),D(BigInt.asUintN(64,H),8))}function $H(H){let M=lH.encode(H);if(M.length<32)return F(new Uint8Array([160+M.length]),M);return F(uH(217,0,M.length),M)}function cH(H){let M=H.map((J)=>s(J)),G=H.length<16?new Uint8Array([144+H.length]):H.length<=65535?new Uint8Array([220,H.length>>8,H.length&255]):new Uint8Array([221,H.length>>>24&255,H.length>>>16&255,H.length>>>8&255,H.length&255]);return F(G,...M)}function dH(H){let M=Object.entries(H).filter(([,J])=>typeof J<"u"),G=M.length<16?new Uint8Array([128+M.length]):M.length<=65535?new Uint8Array([222,M.length>>8,M.length&255]):new Uint8Array([223,M.length>>>24&255,M.length>>>16&255,M.length>>>8&255,M.length&255]);return F(G,...M.flatMap(([J,X])=>[$H(J),s(X)]))}function s(H){if(H===null)return new Uint8Array([192]);if(typeof H==="boolean")return new Uint8Array([H?195:194]);if(typeof H==="string")return $H(H);if(typeof H==="number"){if(!Number.isFinite(H)||!Number.isInteger(H))throw new r("helpers_invalid_params",{message:"Hyperliquid msgpack only supports integers"});return XH(BigInt(H))}if(typeof H==="bigint")return XH(H);if(H instanceof Uint8Array){let M=H.length<=255?new Uint8Array([196,H.length]):H.length<=65535?new Uint8Array([197,H.length>>8,H.length&255]):new Uint8Array([198,H.length>>>24&255,H.length>>>16&255,H.length>>>8&255,H.length&255]);return F(M,H)}if(Array.isArray(H))return cH(H);if(typeof H==="object")return dH(H);throw new r("helpers_invalid_params",{message:`Unsupported Hyperliquid msgpack value: ${String(H)}`})}function rH(H){let M=H.startsWith("0x")?H.slice(2):H;if(M.length%2!==0||/[^a-fA-F0-9]/u.test(M))throw new r("helpers_invalid_params",{hexValue:H});let G=new Uint8Array(M.length/2);for(let J=0;J<M.length;J+=2)G[J/2]=Number.parseInt(M.slice(J,J+2),16);return G}function OH(H){return{domain:pH,message:{connectionId:H,source:"a"},primaryType:"Agent",types:{Agent:[...mH.Agent]}}}function QH(H){let M=o[H.type],G=i[H.type],{signatureChainId:J,type:X,...$}=H,Z=Number.parseInt(J||P,16);return{domain:{...S,chainId:Z},message:{...$,hyperliquidChain:$.hyperliquidChain||ZH},primaryType:M,types:{[M]:G}}}function YH(H){let M=vH.from(H);return{r:M.r,s:M.s,v:M.v}}function WH(H,M,{expiresAfter:G,vaultAddress:J}={}){let X=s(H),$=D(BigInt(M),8),Z=J?F(new Uint8Array([1]),rH(J.toLowerCase())):new Uint8Array([0]),Q=typeof G==="number"?F(new Uint8Array([0]),D(BigInt(G),8)):new Uint8Array;return gH(F(X,$,Z,Q))}function CH(H){let M=H.hyperliquidChain||ZH;switch(H.type){case"approveAgent":return{...H,agentAddress:H.agentAddress.toLowerCase(),hyperliquidChain:M};case"approveBuilderFee":return{...H,builder:H.builder.toLowerCase(),hyperliquidChain:M};case"sendAsset":return{...H,destination:H.destination.toLowerCase(),fromSubAccount:H.fromSubAccount.toLowerCase(),hyperliquidChain:M};case"tokenDelegate":return{...H,hyperliquidChain:M,validator:H.validator.toLowerCase()};case"usdClassTransfer":return{...H,hyperliquidChain:M};default:return H}}var _H=Number.parseInt(P,16),sH=new Set(["chainId","name","verifyingContract","version"]),RH=/^0x[0-9a-fA-F]{40}$/,n=i.sendAsset;var Y=(H)=>{throw new iH("toolbox_hypercore_payload_mismatch",{problems:[H]})};function NH(H){try{return new URL(H)}catch{return}}function UH(H){if(!("EIP712Domain"in H.types))return H;let{EIP712Domain:M,...G}=H.types;return{...H,types:G}}function jH({action:H,allowedEndpoints:M,expectedAmount:G,expectedDestination:J,expectedFromSubAccount:X,expectedSourceDex:$,expectedToken:Z,submitTo:Q,typedData:C}){let{domain:U,message:V,primaryType:j,types:I}=C,O=o.sendAsset;if(j!==O)Y(`primaryType is ${JSON.stringify(j)}, expected "${O}"`);if(H.type!=="sendAsset")Y(`action.type is ${JSON.stringify(H.type)}, expected "sendAsset"`);let _=n.map(({name:W})=>W),L=new Set([..._,"signatureChainId","type"]),q=Object.keys(H).filter((W)=>!L.has(W));if(q.length)Y(`action carries unexpected keys: ${q.join(", ")}`);for(let{name:W}of n)if(V[W]!==H[W])Y(`${W}: signed ${JSON.stringify(V[W])} != submitted ${JSON.stringify(H[W])}`);let z=Object.keys(V),N=z.filter((W)=>!_.includes(W)),B=_.filter((W)=>!z.includes(W));if(N.length||B.length){let W=[N.length?`declares undeclared keys [${N.join(",")}]`:"",B.length?`is missing keys [${B.join(",")}]`:""].filter(Boolean).join(" / ");Y(`message ${W}`)}let b=n.map(({name:W,type:d})=>`${W}:${d}`).join(","),K=(I[O]??[]).map(({name:W,type:d})=>`${W}:${d}`).join(",");if(K!==b)Y(`types.${O} is [${K}], expected [${b}]`);let y=Object.keys(I).filter((W)=>W!==O&&W!=="EIP712Domain");if(y.length)Y(`types carries unexpected entries: ${y.join(", ")}`);if(Number(U.chainId)!==_H)Y(`domain.chainId is ${U.chainId}, expected ${_H} (Arbitrum)`);if(U.name!==S.name)Y(`domain.name is ${JSON.stringify(U.name)}, expected "${S.name}"`);if(U.version!==S.version)Y(`domain.version is ${JSON.stringify(U.version)}, expected "${S.version}"`);if(U.verifyingContract!==k)Y(`domain.verifyingContract is ${U.verifyingContract}, expected the zero address`);let A=Object.keys(U).filter((W)=>!sH.has(W));if(A.length)Y(`domain carries unexpected keys: ${A.join(", ")}`);if(typeof H.signatureChainId!=="string"||H.signatureChainId.toLowerCase()!==P)Y(`action.signatureChainId is ${JSON.stringify(H.signatureChainId)}, expected "${P}"`);if(H.hyperliquidChain!=="Mainnet")Y(`action.hyperliquidChain is ${JSON.stringify(H.hyperliquidChain)}, expected "Mainnet"`);if(typeof H.nonce!=="number"||!Number.isSafeInteger(H.nonce)||H.nonce<=0)Y(`action.nonce is ${JSON.stringify(H.nonce)}, expected a positive safe integer`);if(H.destinationDex!=="")Y(`action.destinationDex is ${JSON.stringify(H.destinationDex)}, expected ""`);if(Z!==x)Y(`route sell token is ${JSON.stringify(Z)}, expected "${x}"`);if(H.token!==Z)Y(`action.token is ${JSON.stringify(H.token)}, expected route sell token "${Z}"`);if(H.sourceDex!==""&&H.sourceDex!=="spot")Y(`action.sourceDex is ${JSON.stringify(H.sourceDex)}, expected "" or "spot"`);if(typeof H.sourceDex!=="string"||H.sourceDex!==$)Y(`action.sourceDex is ${JSON.stringify(H.sourceDex)}, expected route sourceDex ${JSON.stringify($)}`);let v=H.fromSubAccount;if(typeof v!=="string"||typeof X!=="string"||v.toLowerCase()!==X.toLowerCase())Y(`action.fromSubAccount is ${JSON.stringify(H.fromSubAccount)}, expected ${JSON.stringify(X)}`);if(X&&!RH.test(X))Y(`expectedFromSubAccount ${JSON.stringify(X)} is not a well-formed 0x address`);if(!G)Y("expectedAmount is missing — cannot verify action.amount");let p=!1;try{p=new oH(String(H.amount)).eqValue(G)}catch{Y(`action.amount ${JSON.stringify(H.amount)} is not comparable to ${G}`)}if(!p)Y(`action.amount ${JSON.stringify(H.amount)} != route sell amount ${G}`);let u=typeof H.destination==="string"?H.destination:"";if(!RH.test(u))Y(`action.destination ${JSON.stringify(H.destination)} is not a well-formed 0x address`);if(!J)Y("expectedDestination is missing — cannot verify action.destination");if(u.toLowerCase()!==J.toLowerCase())Y(`action.destination ${u} != expected destination ${J}`);let MH=NH(Q),c=MH?.origin,GH=M.flatMap((W)=>NH(W)?.origin??[]);if(MH?.protocol!=="https:")Y(`submitTo ${JSON.stringify(Q)} must be an https URL`);if(!c||!GH.includes(c))Y(`submitTo origin ${c} is not one of the allowed exchange origins [${GH.join(", ")}]`)}import{AssetValue as a,Chain as nH,derivationPathToString as tH,getChainConfig as EH,getRPCUrl as aH,NetworkDerivationPath as eH,RequestClient as h,SwapKitError as R,SwapKitNumber as w,updateDerivationPath as HM}from"@swapkit/helpers";import{HDNodeWallet as MM}from"ethers";import{match as GM,P as t}from"ts-pattern";var E=nH.Hype,{baseDecimal:BH,rpcUrls:IH}=EH(E),JM=IH[0]?`${IH[0]}/exchange`:void 0,XM={HYPE:BH,USDC:6,USDT:6},PH="Mainnet",ZM=/^\d+(?:\.\d+)?$/,$M=/^[^:]+:0x[0-9a-fA-F]+$/,OM={spotSend:[{name:"hyperliquidChain",type:"string"},{name:"destination",type:"string"},{name:"token",type:"string"},{name:"amount",type:"string"},{name:"time",type:"uint64"}]},QM={spotSend:"HyperliquidTransaction:SpotSend"};function f(H,M){if(!hH(H))throw new R(M,{address:H});return H.toLowerCase()}function g(H){if(H===void 0)return;try{return new w(H)}catch{return}}var wH={retry:{maxRetries:0},timeoutMs:5000};async function T({requestOptions:H,...M}){let G=await m();return h.post(`${G}/info`,{json:M,...H})}function e({dex:H,user:M}){return T({...H?{dex:H}:{},type:"clearinghouseState",user:f(M,"helpers_invalid_params")})}function TH({user:H}){return T({type:"spotClearinghouseState",user:f(H,"helpers_invalid_params")})}function YM({destination:H,sender:M}){let G=f(M,"helpers_invalid_params"),J=f(H,"helpers_invalid_params");return T({requestOptions:wH,source:G,type:"preTransferCheck",user:J})}function WM({dex:H,user:M}){return T({...H?{dex:H}:{},type:"openOrders",user:f(M,"helpers_invalid_params")})}function CM({dex:H,user:M}){return T({...H?{dex:H}:{},type:"frontendOpenOrders",user:f(M,"helpers_invalid_params")})}function _M({oidOrCloid:H,user:M}){return T({oid:H,type:"orderStatus",user:f(M,"helpers_invalid_params")})}function RM({aggregateByTime:H,user:M}){return T({...typeof H==="boolean"?{aggregateByTime:H}:{},type:"userFills",user:f(M,"helpers_invalid_params")})}function NM({aggregateByTime:H,endTime:M,startTime:G,user:J}){return T({...typeof H==="boolean"?{aggregateByTime:H}:{},...typeof M==="number"?{endTime:M}:{},startTime:G,type:"userFillsByTime",user:f(J,"helpers_invalid_params")})}function fH({coin:H,token:M,value:G,spotMeta:J}){if(!G||Number(G)<=0)return null;let X=H?.toUpperCase()||`TOKEN-${M||"UNKNOWN"}`,$=XM[X]||BH,Z=J?.tokens?.find((C)=>C.name===H||M!==void 0&&C.index===Number(M)),Q=Z?`${E}.${X}-${Z.name}:${Z.tokenId}`:`${E}.${X}`;return new a({decimal:$,identifier:Q,value:G})}function UM(H){let M=new Map;for(let G of H){let J=G.toString({includeSynthProtocol:!0}),X=M.get(J);M.set(J,X?X.add(G):G)}if(![...M.values()].some((G)=>G.isGasAsset||G.ticker==="HYPE")){let G=a.from({chain:E,value:0});M.set(G.toString({includeSynthProtocol:!0}),G)}return[...M.values()]}async function m(){try{return await aH(E)}catch{let[H]=EH(E).rpcUrls;if(!H)throw new R("helpers_chain_no_public_or_set_rpc_url",{chain:E});return H}}async function l(){return`${await m()}/exchange`}function jM(H){let M=QM[H.type],{type:G,...J}=H;return{domain:{chainId:Number.parseInt(H.signatureChainId,16),name:"HyperliquidSignTransaction",verifyingContract:k,version:"1"},message:J,primaryType:M,types:{[M]:OM[G]}}}async function IM({action:H,expiresAfter:M,nonce:G,vaultAddress:J}){let X=G||Date.now(),$=J?f(J,"helpers_invalid_params"):void 0,Z=await l(),Q=WH(H,X,{expiresAfter:M,vaultAddress:$});return{action:H,endpoint:Z,expiresAfter:M,nonce:X,typedData:OH(Q),vaultAddress:$}}async function AH({action:H,endpoint:M,nonce:G,signatureChainId:J}){let X=G||H.nonce||Date.now(),$=J||H.signatureChainId||P,Z=CH({...H,nonce:X,signatureChainId:$});return{action:Z,endpoint:M??await l(),nonce:X,typedData:QH(Z)}}async function HH({token:H,user:M}){let G=await TH({user:M}),X=(G.spotState?.balances||G.balances||[]).find(({coin:Q})=>Q&&H.startsWith(`${Q}:`)),$=g(X?.total||0),Z=g(X?.hold||0);return $&&Z?$.sub(Z):void 0}async function DH({assetValue:H,sender:M,token:G}){let J=(await HH({token:G,user:M}))?.getValue("string");if(!J||Number(J)<=0)throw new R("toolbox_sweep_amount_too_low",{asset:H.toString(),balance:J||"0"});return J}async function fM(H){if(H.address&&$M.test(H.address))return H.address;let G=(await T({type:"spotMeta"}))?.tokens?.find(({name:J})=>J?.toUpperCase()===H.ticker.toUpperCase());if(G)return`${G.name}:${G.tokenId}`;throw new R("helpers_invalid_params",{asset:H.toString(),message:"Unable to resolve the HyperCore spot token id"})}async function bH({destination:H,sender:M}){let G;try{G=await YM({destination:H,sender:M})}catch($){throw new R("toolbox_hypercore_pre_transfer_check_failed",$)}if(typeof G?.isSanctioned!=="boolean"||typeof G.userExists!=="boolean")throw new R("toolbox_hypercore_pre_transfer_check_failed",{response:G});let{fee:J}=G,X=typeof J==="string"&&ZM.test(J)?Number(J):Number.NaN;if(!Number.isFinite(X))throw new R("toolbox_hypercore_pre_transfer_check_failed",{response:G});if(G.isSanctioned)throw new R("toolbox_hypercore_destination_sanctioned",{destination:H,sender:M});return X}function yH(H){return H.toUpperCase().startsWith("USDC:")}async function kH({activationFee:H,token:M,user:G}){if(H<=0)return;let[J,X]=await Promise.all([e({user:G}),HH({token:x,user:G})]),$=g(J.withdrawable||"0")??new w(0),Z=X??new w(0);if(new w(H).lte($)||new w(H).lte(Z))return;throw new R("toolbox_hypercore_insufficient_balance",{activationFee:H,feeToken:x,perpsWithdrawable:$.getValue("string"),spotAvailable:Z.getValue("string"),token:M})}async function SH({activationFee:H,amount:M,sourceDex:G,token:J,user:X}){let $=yH(J),Z=$?new w(M).add(H):new w(M);if(G!==void 0&&G!==""&&G!=="spot")throw new R("helpers_invalid_params",{message:"Unsupported HyperCore sourceDex",sourceDex:G});if(!$&&G==="")throw new R("helpers_invalid_params",{message:"Only a collateral token can be sent from a perp DEX",sourceDex:G,token:J});let Q="0";if($&&G!=="spot"){if(Q=(await e({user:X})).withdrawable||"0",Z.lte(g(Q)??0))return"";if(G==="")throw new R("toolbox_hypercore_insufficient_balance",{amountRequired:Z.getValue("string"),perpsWithdrawable:Q,spotAvailable:"0",token:J})}let C=await HH({token:J,user:X})??new w(0);if(C.gte(Z)){if(!$)await kH({activationFee:H,token:J,user:X});return"spot"}throw new R("toolbox_hypercore_insufficient_balance",{amountRequired:Z.getValue("string"),perpsWithdrawable:Q,spotAvailable:C.getValue("string"),token:J})}async function LM({amount:H,destination:M,sender:G,sourceDex:J,sweep:X,token:$}){if(X&&J!==void 0&&J!=="spot")throw new R("helpers_invalid_params",{message:"HyperCore sweep drains spot and requires sourceDex spot",sourceDex:J});let Z=await bH({destination:M,sender:G});if(!X){let C=await SH({activationFee:Z,amount:H,sourceDex:J,token:$,user:G});return{amount:H,sourceDex:C}}if(!yH($))return await kH({activationFee:Z,token:$,user:G}),{amount:H,sourceDex:"spot"};if(Z<=0)return{amount:H,sourceDex:"spot"};let Q=new w(H).sub(Z);if(Q.lte(0))throw new R("toolbox_hypercore_insufficient_balance",{activationFee:Z,spotAvailable:H,token:$});return{amount:Q.getValue("string"),sourceDex:"spot"}}async function zM({assetValue:H,recipient:M,sender:G,signatureChainId:J,sweep:X,time:$,endpoint:Z}){let Q=f(M,"core_transaction_invalid_recipient_address"),C=f(G,"core_transaction_invalid_sender_address"),U=H.address;if(!U)throw new R("helpers_invalid_params",{asset:H.toString(),from:C});let V=X?await DH({assetValue:H,sender:C,token:U}):H.getValue("string"),j=Z??await l(),I=$||Date.now(),O={amount:V,destination:Q,hyperliquidChain:PH,signatureChainId:J||P,time:I,token:U,type:"spotSend"};return{action:O,endpoint:j,nonce:I,typedData:jM(O)}}async function LH({assetValue:H,destinationDex:M,endpoint:G,fromSubAccount:J,recipient:X,sender:$,signatureChainId:Z,sourceDex:Q,sweep:C,time:U}){let V=f(X,"core_transaction_invalid_recipient_address"),j=f($,"core_transaction_invalid_sender_address"),I=J?f(J,"helpers_invalid_params"):"",O=I||j,_=await fM(H),L=C?await DH({assetValue:H,sender:O,token:_}):H.getValue("string"),{amount:q,sourceDex:z}=await LM({amount:L,destination:V,sender:O,sourceDex:Q,sweep:C,token:_}),N=JH({amount:q,destination:V,destinationDex:M??"spot",fromSubAccount:I,hyperliquidChain:PH,nonce:U||Date.now(),signatureChainId:Z||P,sourceDex:z,token:_});return AH({action:N,endpoint:G})}async function xH(H){let M=await h.post(H.endpoint,{json:{action:H.action,...typeof H.expiresAfter==="number"?{expiresAfter:H.expiresAfter}:{},nonce:H.nonce,signature:H.signature,vaultAddress:H.vaultAddress??null},retry:{maxRetries:0}});if(M?.status!=="ok")throw new R("core_transaction_failed",{definitive:M?.status==="err",response:M});return M}async function zH({amount:H,destination:M,nonce:G,token:J,user:X}){let $=f(X,"helpers_invalid_params"),Z=await m(),Q=G-5000,C=M?.toLowerCase(),U=J?.toUpperCase(),V=({delta:j,time:I})=>{if(!(I&&I>=Q&&j?.type==="send"&&j.nonce===G))return!1;if(C&&j?.destination?.toLowerCase()!==C)return!1;let O=g(j?.amount);if(H!==void 0&&!O?.eqValue(H))return!1;if(U!==void 0){if(!j?.token)return!1;let _=j.token.toUpperCase();if(_!==U&&!U.startsWith(`${_}:`))return!1}return!0};for(let j=0;j<8;j++){if(j>0)await new Promise((I)=>setTimeout(I,1500));try{let I=await h.post(`${Z}/info`,{json:{startTime:Q,type:"userNonFundingLedgerUpdates",user:$},...wH}),O=Array.isArray(I)?I.find(V):void 0;if(O?.hash)return O.hash}catch{}}return""}async function qH({kind:H,lookup:M,signed:G}){try{await xH(G)}catch(X){if(X instanceof R&&X.errorKey==="core_transaction_failed"&&X.cause?.definitive===!0)throw X;let Z=await zH(M);if(Z)return Z;throw new R("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:M.nonce,transportError:String(X)})}let J=await zH(M);if(!J)throw new R("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 ${H}. Check the account ledger for the transfer first.`,nonce:M.nonce});return J}function FH({action:H,nonce:M,user:G}){return{amount:H.amount,destination:H.destination,nonce:M,token:H.token,user:G}}function hH(H){return H.startsWith("0x")&&KH(H)}function nM(H){let M=VH(E),G=H&&"index"in H?H.index||0:0,J=tH(H&&"derivationPath"in H&&H.derivationPath?H.derivationPath:HM(eH[E],{index:G})),X,$=!1;function Z(){if($)return X;return X=GM(H).with({phrase:t.string},({phrase:O})=>{return MM.fromPhrase(O,void 0,J)}).with({signer:t.not(t.nullish)},({signer:O})=>O).otherwise(()=>{return}),$=!0,X}async function Q(){let O=Z();return O?await O.getAddress():""}async function C(O){let _=Z();if(!_)throw new R("toolbox_hypercore_no_signer");let L=UH(O.typedData),q=await _.signTypedData(L.domain,L.types,L.message);return{action:O.action,endpoint:O.endpoint,nonce:O.nonce,signature:YH(q),..."expiresAfter"in O?{expiresAfter:O.expiresAfter}:{},..."vaultAddress"in O?{vaultAddress:O.vaultAddress}:{}}}async function U(O){let _=f(O,"helpers_invalid_params");try{let L=await m(),[q,z,N]=await Promise.all([h.post(`${L}/info`,{json:{type:"spotClearinghouseState",user:_}}),h.post(`${L}/info`,{json:{type:"clearinghouseState",user:_}}),h.post(`${L}/info`,{json:{type:"spotMeta"}})]),B=(q.spotState?.balances||q.balances||[]).map(({coin:K,token:y,total:A})=>fH({coin:K,spotMeta:N,token:y,value:A})).filter((K)=>!!K),b=fH({coin:"USDC",spotMeta:N,value:z.withdrawable||z.marginSummary?.accountValue||z.marginSummary?.totalRawUsd});return UM(b?[...B,b]:B)}catch{return M(_)}}async function V({sweep:O,..._}){let L=Z();if(!L)throw new R("toolbox_hypercore_no_signer");let q=_.sender||await L.getAddress(),z=await LH({..._,feeRate:0,sender:q,sweep:O}),N=await C(z);return qH({kind:"transfer",lookup:FH({action:z.action,nonce:z.nonce,user:z.action.fromSubAccount||q}),signed:N})}async function j(O){let _=Z();if(!_)throw new R("toolbox_hypercore_no_signer");let{action:L,typedData:q,...z}=O,N=structuredClone(L),B=structuredClone(q),b=await _.getAddress(),K=await l(),y=[...new Set([K,JM??K])];jH({...z,action:N,allowedEndpoints:y,typedData:B});let A=N.fromSubAccount?f(N.fromSubAccount,"helpers_invalid_params"):b,v=await bH({destination:N.destination,sender:A});await SH({activationFee:v,amount:N.amount,sourceDex:N.sourceDex,token:N.token,user:A});let p=await C({action:N,endpoint:K,nonce:N.nonce,typedData:B});return qH({kind:"payin",lookup:FH({action:N,nonce:N.nonce,user:A}),signed:p})}function I(){return a.from({chain:E,value:0})}return{broadcastTransaction:xH,createL1ActionRequest:IM,createSendAssetTransaction:LH,createTransaction:zM,createUserSignedActionRequest:AH,estimateTransactionFee:I,getAddress:Q,getBalance:U,getState:{clearinghouse:e,frontendOpenOrders:CM,openOrders:WM,orderStatus:_M,spotClearinghouse:TH,userFills:RM,userFillsByTime:NM},signAndBroadcastSendAsset:j,signTransaction:C,transfer:V,validateAddress:hH}}export{hH as validateHyperCoreAddress,nM as getHyperCoreToolbox,AH as createUserSignedActionRequest,zM as createTransaction,LH as createSendAssetTransaction,IM as createL1ActionRequest,AM as buildUsdClassTransferAction,BM as buildUpdateLeverageAction,PM as buildUpdateIsolatedMarginAction,wM as buildTopUpIsolatedOnlyMarginAction,yM as buildTokenDelegateAction,JH as buildSendAssetAction,TM as buildScheduleCancelAction,qM as buildOrderAction,KM as buildModifyAction,VM as buildCancelByCloidAction,FM as buildCancelAction,EM as buildBatchModifyAction,bM as buildApproveBuilderFeeAction,DM as buildApproveAgentAction,x as HYPERCORE_USDC_TOKEN_ID};
1
+ import"../../chunk-44m22jy1.js";import{q as KH}from"../../chunk-55jkfkar.js";import"../../chunk-nvfkjbyq.js";import"../../chunk-xbdjxeqd.js";function zM({builder:H,grouping:M="na",orders:G}){return{builder:H,grouping:M,orders:G,type:"order"}}function FM({cancels:H}){return{cancels:H,type:"cancel"}}function VM({cancels:H}){return{cancels:H,type:"cancelByCloid"}}function KM({oid:H,order:M}){return{oid:H,order:M,type:"modify"}}function EM({modifies:H}){return{modifies:H,type:"batchModify"}}function BM({asset:H,isCross:M,leverage:G}){return{asset:H,isCross:M,leverage:G,type:"updateLeverage"}}function PM({asset:H,isBuy:M,ntli:G}){return{asset:H,isBuy:M,ntli:G,type:"updateIsolatedMargin"}}function wM({asset:H,leverage:M}){return{asset:H,leverage:M,type:"topUpIsolatedOnlyMargin"}}function TM({time:H}){return{time:H,type:"scheduleCancel"}}function DM({amount:H,hyperliquidChain:M,nonce:G,signatureChainId:J,toPerp:X}){return{amount:H,hyperliquidChain:M,nonce:G,signatureChainId:J,toPerp:X,type:"usdClassTransfer"}}function XH({amount:H,destination:M,destinationDex:G,fromSubAccount:J,hyperliquidChain:X,nonce:Z,signatureChainId:$,sourceDex:Q,token:C}){return{amount:H,destination:M,destinationDex:G,fromSubAccount:J,hyperliquidChain:X,nonce:Z,signatureChainId:$,sourceDex:Q,token:C,type:"sendAsset"}}function AM({agentAddress:H,agentName:M,hyperliquidChain:G,nonce:J,signatureChainId:X}){return{agentAddress:H,agentName:M,hyperliquidChain:G,nonce:J,signatureChainId:X,type:"approveAgent"}}function bM({builder:H,hyperliquidChain:M,maxFeeRate:G,nonce:J,signatureChainId:X}){return{builder:H,hyperliquidChain:M,maxFeeRate:G,nonce:J,signatureChainId:X,type:"approveBuilderFee"}}function yM({hyperliquidChain:H,isUndelegate:M,nonce:G,signatureChainId:J,validator:X,wei:Z}){return{hyperliquidChain:H,isUndelegate:M,nonce:G,signatureChainId:J,type:"tokenDelegate",validator:X,wei:Z}}import{SwapKitError as rH,SwapKitNumber as oH}from"@swapkit/helpers";import{HYPERCORE_USDC_TOKEN_ID as x}from"@swapkit/helpers/api";import{SwapKitError as o}from"@swapkit/helpers";import{keccak256 as hH,Signature as gH}from"ethers";var k="0x0000000000000000000000000000000000000000",w="0xa4b1",S={name:"HyperliquidSignTransaction",verifyingContract:k,version:"1"},vH={chainId:1337,name:"Exchange",verifyingContract:k,version:"1"},pH={Agent:[{name:"source",type:"string"},{name:"connectionId",type:"bytes32"}]},$H="Mainnet",i={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"}]},s={approveAgent:"HyperliquidTransaction:ApproveAgent",approveBuilderFee:"HyperliquidTransaction:ApproveBuilderFee",sendAsset:"HyperliquidTransaction:SendAsset",tokenDelegate:"HyperliquidTransaction:TokenDelegate",usdClassTransfer:"HyperliquidTransaction:UsdClassTransfer"},mH=new TextEncoder;function F(...H){let M=H.reduce((X,Z)=>X+Z.length,0),G=new Uint8Array(M),J=0;for(let X of H)G.set(X,J),J+=X.length;return G}function lH(H,M,G){if(G<M)return new Uint8Array([H+G]);if(G<=255)return new Uint8Array([H+M,G]);if(G<=65535)return new Uint8Array([H+M+1,G>>8,G&255]);return new Uint8Array([H+M+2,G>>>24&255,G>>>16&255,G>>>8&255,G&255])}function b(H,M){let G=new Uint8Array(M),J=H;for(let X=M-1;X>=0;X-=1)G[X]=Number(J&0xffn),J>>=8n;return G}function ZH(H){if(H>=0n){if(H<=0x7fn)return new Uint8Array([Number(H)]);if(H<=0xffn)return new Uint8Array([204,Number(H)]);if(H<=0xffffn)return F(new Uint8Array([205]),b(H,2));if(H<=0xffffffffn)return F(new Uint8Array([206]),b(H,4));return F(new Uint8Array([207]),b(H,8))}if(H>=-32n)return new Uint8Array([256+Number(H)]);if(H>=-128n)return new Uint8Array([208,256+Number(H)]);if(H>=-32768n)return F(new Uint8Array([209]),b(BigInt.asUintN(16,H),2));if(H>=-2147483648n)return F(new Uint8Array([210]),b(BigInt.asUintN(32,H),4));return F(new Uint8Array([211]),b(BigInt.asUintN(64,H),8))}function OH(H){let M=mH.encode(H);if(M.length<32)return F(new Uint8Array([160+M.length]),M);return F(lH(217,0,M.length),M)}function uH(H){let M=H.map((J)=>n(J)),G=H.length<16?new Uint8Array([144+H.length]):H.length<=65535?new Uint8Array([220,H.length>>8,H.length&255]):new Uint8Array([221,H.length>>>24&255,H.length>>>16&255,H.length>>>8&255,H.length&255]);return F(G,...M)}function cH(H){let M=Object.entries(H).filter(([,J])=>typeof J<"u"),G=M.length<16?new Uint8Array([128+M.length]):M.length<=65535?new Uint8Array([222,M.length>>8,M.length&255]):new Uint8Array([223,M.length>>>24&255,M.length>>>16&255,M.length>>>8&255,M.length&255]);return F(G,...M.flatMap(([J,X])=>[OH(J),n(X)]))}function n(H){if(H===null)return new Uint8Array([192]);if(typeof H==="boolean")return new Uint8Array([H?195:194]);if(typeof H==="string")return OH(H);if(typeof H==="number"){if(!Number.isFinite(H)||!Number.isInteger(H))throw new o("helpers_invalid_params",{message:"Hyperliquid msgpack only supports integers"});return ZH(BigInt(H))}if(typeof H==="bigint")return ZH(H);if(H instanceof Uint8Array){let M=H.length<=255?new Uint8Array([196,H.length]):H.length<=65535?new Uint8Array([197,H.length>>8,H.length&255]):new Uint8Array([198,H.length>>>24&255,H.length>>>16&255,H.length>>>8&255,H.length&255]);return F(M,H)}if(Array.isArray(H))return uH(H);if(typeof H==="object")return cH(H);throw new o("helpers_invalid_params",{message:`Unsupported Hyperliquid msgpack value: ${String(H)}`})}function dH(H){let M=H.startsWith("0x")?H.slice(2):H;if(M.length%2!==0||/[^a-fA-F0-9]/u.test(M))throw new o("helpers_invalid_params",{hexValue:H});let G=new Uint8Array(M.length/2);for(let J=0;J<M.length;J+=2)G[J/2]=Number.parseInt(M.slice(J,J+2),16);return G}function QH(H){return{domain:vH,message:{connectionId:H,source:"a"},primaryType:"Agent",types:{Agent:[...pH.Agent]}}}function YH(H){let M=s[H.type],G=i[H.type],{signatureChainId:J,type:X,...Z}=H,$=Number.parseInt(J||w,16);return{domain:{...S,chainId:$},message:{...Z,hyperliquidChain:Z.hyperliquidChain||$H},primaryType:M,types:{[M]:G}}}function WH(H){let M=gH.from(H);return{r:M.r,s:M.s,v:M.v}}function _H(H,M,{expiresAfter:G,vaultAddress:J}={}){let X=n(H),Z=b(BigInt(M),8),$=J?F(new Uint8Array([1]),dH(J.toLowerCase())):new Uint8Array([0]),Q=typeof G==="number"?F(new Uint8Array([0]),b(BigInt(G),8)):new Uint8Array;return hH(F(X,Z,$,Q))}function CH(H){let M=H.hyperliquidChain||$H;switch(H.type){case"approveAgent":return{...H,agentAddress:H.agentAddress.toLowerCase(),hyperliquidChain:M};case"approveBuilderFee":return{...H,builder:H.builder.toLowerCase(),hyperliquidChain:M};case"sendAsset":return{...H,destination:H.destination.toLowerCase(),fromSubAccount:H.fromSubAccount.toLowerCase(),hyperliquidChain:M};case"tokenDelegate":return{...H,hyperliquidChain:M,validator:H.validator.toLowerCase()};case"usdClassTransfer":return{...H,hyperliquidChain:M};default:return H}}var RH=Number.parseInt(w,16),iH=new Set(["chainId","name","verifyingContract","version"]),NH=/^0x[0-9a-fA-F]{40}$/,t=i.sendAsset;var Y=(H)=>{throw new rH("toolbox_hypercore_payload_mismatch",{problems:[H]})};function UH(H){try{return new URL(H)}catch{return}}function jH(H){if(!("EIP712Domain"in H.types))return H;let{EIP712Domain:M,...G}=H.types;return{...H,types:G}}function IH({action:H,allowedEndpoints:M,expectedAmount:G,expectedDestination:J,expectedFromSubAccount:X,expectedSourceDex:Z,expectedToken:$,submitTo:Q,typedData:C}){let{domain:U,message:K,primaryType:j,types:q}=C,O=s.sendAsset;if(j!==O)Y(`primaryType is ${JSON.stringify(j)}, expected "${O}"`);if(H.type!=="sendAsset")Y(`action.type is ${JSON.stringify(H.type)}, expected "sendAsset"`);let _=t.map(({name:W})=>W),I=new Set([..._,"signatureChainId","type"]),z=Object.keys(H).filter((W)=>!I.has(W));if(z.length)Y(`action carries unexpected keys: ${z.join(", ")}`);for(let{name:W}of t)if(K[W]!==H[W])Y(`${W}: signed ${JSON.stringify(K[W])} != submitted ${JSON.stringify(H[W])}`);let f=Object.keys(K),R=f.filter((W)=>!_.includes(W)),V=_.filter((W)=>!f.includes(W));if(R.length||V.length){let W=[R.length?`declares undeclared keys [${R.join(",")}]`:"",V.length?`is missing keys [${V.join(",")}]`:""].filter(Boolean).join(" / ");Y(`message ${W}`)}let P=t.map(({name:W,type:r})=>`${W}:${r}`).join(","),E=(q[O]??[]).map(({name:W,type:r})=>`${W}:${r}`).join(",");if(E!==P)Y(`types.${O} is [${E}], expected [${P}]`);let y=Object.keys(q).filter((W)=>W!==O&&W!=="EIP712Domain");if(y.length)Y(`types carries unexpected entries: ${y.join(", ")}`);if(Number(U.chainId)!==RH)Y(`domain.chainId is ${U.chainId}, expected ${RH} (Arbitrum)`);if(U.name!==S.name)Y(`domain.name is ${JSON.stringify(U.name)}, expected "${S.name}"`);if(U.version!==S.version)Y(`domain.version is ${JSON.stringify(U.version)}, expected "${S.version}"`);if(U.verifyingContract!==k)Y(`domain.verifyingContract is ${U.verifyingContract}, expected the zero address`);let A=Object.keys(U).filter((W)=>!iH.has(W));if(A.length)Y(`domain carries unexpected keys: ${A.join(", ")}`);if(typeof H.signatureChainId!=="string"||H.signatureChainId.toLowerCase()!==w)Y(`action.signatureChainId is ${JSON.stringify(H.signatureChainId)}, expected "${w}"`);if(H.hyperliquidChain!=="Mainnet")Y(`action.hyperliquidChain is ${JSON.stringify(H.hyperliquidChain)}, expected "Mainnet"`);if(typeof H.nonce!=="number"||!Number.isSafeInteger(H.nonce)||H.nonce<=0)Y(`action.nonce is ${JSON.stringify(H.nonce)}, expected a positive safe integer`);if(H.destinationDex!=="")Y(`action.destinationDex is ${JSON.stringify(H.destinationDex)}, expected ""`);if($!==x)Y(`route sell token is ${JSON.stringify($)}, expected "${x}"`);if(H.token!==$)Y(`action.token is ${JSON.stringify(H.token)}, expected route sell token "${$}"`);if(H.sourceDex!==""&&H.sourceDex!=="spot")Y(`action.sourceDex is ${JSON.stringify(H.sourceDex)}, expected "" or "spot"`);if(typeof H.sourceDex!=="string"||H.sourceDex!==Z)Y(`action.sourceDex is ${JSON.stringify(H.sourceDex)}, expected route sourceDex ${JSON.stringify(Z)}`);let p=H.fromSubAccount;if(typeof p!=="string"||typeof X!=="string"||p.toLowerCase()!==X.toLowerCase())Y(`action.fromSubAccount is ${JSON.stringify(H.fromSubAccount)}, expected ${JSON.stringify(X)}`);if(X&&!NH.test(X))Y(`expectedFromSubAccount ${JSON.stringify(X)} is not a well-formed 0x address`);if(!G)Y("expectedAmount is missing — cannot verify action.amount");let m=!1;try{m=new oH(String(H.amount)).eqValue(G)}catch{Y(`action.amount ${JSON.stringify(H.amount)} is not comparable to ${G}`)}if(!m)Y(`action.amount ${JSON.stringify(H.amount)} != route sell amount ${G}`);let c=typeof H.destination==="string"?H.destination:"";if(!NH.test(c))Y(`action.destination ${JSON.stringify(H.destination)} is not a well-formed 0x address`);if(!J)Y("expectedDestination is missing — cannot verify action.destination");if(c.toLowerCase()!==J.toLowerCase())Y(`action.destination ${c} != expected destination ${J}`);let GH=UH(Q),d=GH?.origin,JH=M.flatMap((W)=>UH(W)?.origin??[]);if(GH?.protocol!=="https:")Y(`submitTo ${JSON.stringify(Q)} must be an https URL`);if(!d||!JH.includes(d))Y(`submitTo origin ${d} is not one of the allowed exchange origins [${JH.join(", ")}]`)}import{AssetValue as g,Chain as sH,derivationPathToString as nH,getChainConfig as EH,getRPCUrl as tH,NetworkDerivationPath as aH,RequestClient as h,SwapKitError as N,SwapKitNumber as T,updateDerivationPath as eH}from"@swapkit/helpers";import{SwapKitApi as HM}from"@swapkit/helpers/api";import{HDNodeWallet as MM}from"ethers";import{match as GM,P as a}from"ts-pattern";var B=sH.Hype,{baseDecimal:e,rpcUrls:fH}=EH(B),JM=fH[0]?`${fH[0]}/exchange`:void 0,XM={HYPE:e,USDC:6,USDT:6},BH="Mainnet",ZM=/^\d+(?:\.\d+)?$/,$M=/^[^:]+:0x[0-9a-fA-F]+$/,OM={spotSend:[{name:"hyperliquidChain",type:"string"},{name:"destination",type:"string"},{name:"token",type:"string"},{name:"amount",type:"string"},{name:"time",type:"uint64"}]},QM={spotSend:"HyperliquidTransaction:SpotSend"};function L(H,M){if(!xH(H))throw new N(M,{address:H});return H.toLowerCase()}function v(H){if(H===void 0)return;try{return new T(H)}catch{return}}var PH={retry:{maxRetries:0},timeoutMs:5000};async function D({requestOptions:H,...M}){let G=await l();return h.post(`${G}/info`,{json:M,...H})}function HH({dex:H,user:M}){return D({...H?{dex:H}:{},type:"clearinghouseState",user:L(M,"helpers_invalid_params")})}function wH({user:H}){return D({type:"spotClearinghouseState",user:L(H,"helpers_invalid_params")})}function YM({destination:H,sender:M}){let G=L(M,"helpers_invalid_params"),J=L(H,"helpers_invalid_params");return D({requestOptions:PH,source:G,type:"preTransferCheck",user:J})}function WM({dex:H,user:M}){return D({...H?{dex:H}:{},type:"openOrders",user:L(M,"helpers_invalid_params")})}function _M({dex:H,user:M}){return D({...H?{dex:H}:{},type:"frontendOpenOrders",user:L(M,"helpers_invalid_params")})}function CM({oidOrCloid:H,user:M}){return D({oid:H,type:"orderStatus",user:L(M,"helpers_invalid_params")})}function RM({aggregateByTime:H,user:M}){return D({...typeof H==="boolean"?{aggregateByTime:H}:{},type:"userFills",user:L(M,"helpers_invalid_params")})}function NM({aggregateByTime:H,endTime:M,startTime:G,user:J}){return D({...typeof H==="boolean"?{aggregateByTime:H}:{},...typeof M==="number"?{endTime:M}:{},startTime:G,type:"userFillsByTime",user:L(J,"helpers_invalid_params")})}function LH({coin:H,token:M,value:G,spotMeta:J}){if(!G||Number(G)<=0)return null;let X=H?.toUpperCase()||`TOKEN-${M||"UNKNOWN"}`,Z=J?.tokens?.find((C)=>C.name===H||M!==void 0&&C.index===Number(M)),$=Z?.weiDecimals??XM[X]??e,Q=Z?`${B}.${X}-${Z.name}:${Z.tokenId}`:`${B}.${X}`;return new g({decimal:$,identifier:Q,value:G})}function UM(H){let M=new Map;for(let G of H){let J=G.toString({includeSynthProtocol:!0}),X=M.get(J);M.set(J,X?X.add(G):G)}if(![...M.values()].some((G)=>G.isGasAsset||G.ticker==="HYPE")){let G=g.from({chain:B,value:0});M.set(G.toString({includeSynthProtocol:!0}),G)}return[...M.values()]}async function l(){try{return await tH(B)}catch{let[H]=EH(B).rpcUrls;if(!H)throw new N("helpers_chain_no_public_or_set_rpc_url",{chain:B});return H}}async function u(){return`${await l()}/exchange`}function jM(H){let M=QM[H.type],{type:G,...J}=H;return{domain:{chainId:Number.parseInt(H.signatureChainId,16),name:"HyperliquidSignTransaction",verifyingContract:k,version:"1"},message:J,primaryType:M,types:{[M]:OM[G]}}}async function IM({action:H,expiresAfter:M,nonce:G,vaultAddress:J}){let X=G||Date.now(),Z=J?L(J,"helpers_invalid_params"):void 0,$=await u(),Q=_H(H,X,{expiresAfter:M,vaultAddress:Z});return{action:H,endpoint:$,expiresAfter:M,nonce:X,typedData:QH(Q),vaultAddress:Z}}async function TH({action:H,endpoint:M,nonce:G,signatureChainId:J}){let X=G||H.nonce||Date.now(),Z=J||H.signatureChainId||w,$=CH({...H,nonce:X,signatureChainId:Z});return{action:$,endpoint:M??await u(),nonce:X,typedData:YH($)}}async function MH({token:H,user:M}){let G=await wH({user:M}),X=(G.spotState?.balances||G.balances||[]).find(({coin:Q})=>Q&&H.startsWith(`${Q}:`)),Z=v(X?.total||0),$=v(X?.hold||0);return Z&&$?Z.sub($):void 0}async function DH({assetValue:H,sender:M,token:G}){let J=(await MH({token:G,user:M}))?.getValue("string");if(!J||Number(J)<=0)throw new N("toolbox_sweep_amount_too_low",{asset:H.toString(),balance:J||"0"});return J}async function fM(H){if(H.address&&$M.test(H.address))return H.address;let G=(await D({type:"spotMeta"}))?.tokens?.find(({name:J})=>J?.toUpperCase()===H.ticker.toUpperCase());if(G)return`${G.name}:${G.tokenId}`;throw new N("helpers_invalid_params",{asset:H.toString(),message:"Unable to resolve the HyperCore spot token id"})}async function AH({destination:H,sender:M}){let G;try{G=await YM({destination:H,sender:M})}catch(Z){throw new N("toolbox_hypercore_pre_transfer_check_failed",Z)}if(typeof G?.isSanctioned!=="boolean"||typeof G.userExists!=="boolean")throw new N("toolbox_hypercore_pre_transfer_check_failed",{response:G});let{fee:J}=G,X=typeof J==="string"&&ZM.test(J)?Number(J):Number.NaN;if(!Number.isFinite(X))throw new N("toolbox_hypercore_pre_transfer_check_failed",{response:G});if(G.isSanctioned)throw new N("toolbox_hypercore_destination_sanctioned",{destination:H,sender:M});return X}function bH(H){return H.toUpperCase().startsWith("USDC:")}async function yH({activationFee:H,token:M,user:G}){if(H<=0)return;let[J,X]=await Promise.all([HH({user:G}),MH({token:x,user:G})]),Z=v(J.withdrawable||"0")??new T(0),$=X??new T(0);if(new T(H).lte(Z)||new T(H).lte($))return;throw new N("toolbox_hypercore_insufficient_balance",{activationFee:H,feeToken:x,perpsWithdrawable:Z.getValue("string"),spotAvailable:$.getValue("string"),token:M})}async function kH({activationFee:H,amount:M,sourceDex:G,token:J,user:X}){let Z=bH(J),$=Z?new T(M).add(H):new T(M);if(G!==void 0&&G!==""&&G!=="spot")throw new N("helpers_invalid_params",{message:"Unsupported HyperCore sourceDex",sourceDex:G});if(!Z&&G==="")throw new N("helpers_invalid_params",{message:"Only a collateral token can be sent from a perp DEX",sourceDex:G,token:J});let Q="0";if(Z&&G!=="spot"){if(Q=(await HH({user:X})).withdrawable||"0",$.lte(v(Q)??0))return"";if(G==="")throw new N("toolbox_hypercore_insufficient_balance",{amountRequired:$.getValue("string"),perpsWithdrawable:Q,spotAvailable:"0",token:J})}let C=await MH({token:J,user:X})??new T(0);if(C.gte($)){if(!Z)await yH({activationFee:H,token:J,user:X});return"spot"}throw new N("toolbox_hypercore_insufficient_balance",{amountRequired:$.getValue("string"),perpsWithdrawable:Q,spotAvailable:C.getValue("string"),token:J})}async function LM({amount:H,destination:M,sender:G,sourceDex:J,sweep:X,token:Z}){if(X&&J!==void 0&&J!=="spot")throw new N("helpers_invalid_params",{message:"HyperCore sweep drains spot and requires sourceDex spot",sourceDex:J});let $=await AH({destination:M,sender:G});if(!X){let C=await kH({activationFee:$,amount:H,sourceDex:J,token:Z,user:G});return{amount:H,sourceDex:C}}if(!bH(Z))return await yH({activationFee:$,token:Z,user:G}),{amount:H,sourceDex:"spot"};if($<=0)return{amount:H,sourceDex:"spot"};let Q=new T(H).sub($);if(Q.lte(0))throw new N("toolbox_hypercore_insufficient_balance",{activationFee:$,spotAvailable:H,token:Z});return{amount:Q.getValue("string"),sourceDex:"spot"}}async function qM({assetValue:H,recipient:M,sender:G,signatureChainId:J,sweep:X,time:Z,endpoint:$}){let Q=L(M,"core_transaction_invalid_recipient_address"),C=L(G,"core_transaction_invalid_sender_address"),U=H.address;if(!U)throw new N("helpers_invalid_params",{asset:H.toString(),from:C});let K=X?await DH({assetValue:H,sender:C,token:U}):H.getValue("string"),j=$??await u(),q=Z||Date.now(),O={amount:K,destination:Q,hyperliquidChain:BH,signatureChainId:J||w,time:q,token:U,type:"spotSend"};return{action:O,endpoint:j,nonce:q,typedData:jM(O)}}async function qH({assetValue:H,destinationDex:M,endpoint:G,fromSubAccount:J,recipient:X,sender:Z,signatureChainId:$,sourceDex:Q,sweep:C,time:U}){let K=L(X,"core_transaction_invalid_recipient_address"),j=L(Z,"core_transaction_invalid_sender_address"),q=J?L(J,"helpers_invalid_params"):"",O=q||j,_=await fM(H),I=C?await DH({assetValue:H,sender:O,token:_}):H.getValue("string"),{amount:z,sourceDex:f}=await LM({amount:I,destination:K,sender:O,sourceDex:Q,sweep:C,token:_}),R=XH({amount:z,destination:K,destinationDex:M??"spot",fromSubAccount:q,hyperliquidChain:BH,nonce:U||Date.now(),signatureChainId:$||w,sourceDex:f,token:_});return TH({action:R,endpoint:G})}async function SH(H){let M=await h.post(H.endpoint,{json:{action:H.action,...typeof H.expiresAfter==="number"?{expiresAfter:H.expiresAfter}:{},nonce:H.nonce,signature:H.signature,vaultAddress:H.vaultAddress??null},retry:{maxRetries:0}});if(M?.status!=="ok")throw new N("core_transaction_failed",{definitive:M?.status==="err",response:M});return M}async function zH({amount:H,destination:M,nonce:G,token:J,user:X}){let Z=L(X,"helpers_invalid_params"),$=await l(),Q=G-5000,C=M?.toLowerCase(),U=J?.toUpperCase(),K=({delta:j,time:q})=>{if(!(q&&q>=Q&&j?.type==="send"&&j.nonce===G))return!1;if(C&&j?.destination?.toLowerCase()!==C)return!1;let O=v(j?.amount);if(H!==void 0&&!O?.eqValue(H))return!1;if(U!==void 0){if(!j?.token)return!1;let _=j.token.toUpperCase();if(_!==U&&!U.startsWith(`${_}:`))return!1}return!0};for(let j=0;j<8;j++){if(j>0)await new Promise((q)=>setTimeout(q,1500));try{let q=await h.post(`${$}/info`,{json:{startTime:Q,type:"userNonFundingLedgerUpdates",user:Z},...PH}),O=Array.isArray(q)?q.find(K):void 0;if(O?.hash)return O.hash}catch{}}return""}async function FH({kind:H,lookup:M,signed:G}){try{await SH(G)}catch(X){if(X instanceof N&&X.errorKey==="core_transaction_failed"&&X.cause?.definitive===!0)throw X;let $=await zH(M);if($)return $;throw new N("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:M.nonce,transportError:String(X)})}let J=await zH(M);if(!J)throw new N("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 ${H}. Check the account ledger for the transfer first.`,nonce:M.nonce});return J}function VH({action:H,nonce:M,user:G}){return{amount:H.amount,destination:H.destination,nonce:M,token:H.token,user:G}}function xH(H){return H.startsWith("0x")&&KH(H)}function nM(H){let M=H&&"index"in H?H.index||0:0,G=nH(H&&"derivationPath"in H&&H.derivationPath?H.derivationPath:eH(aH[B],{index:M})),J,X=!1;function Z(){if(X)return J;return J=GM(H).with({phrase:a.string},({phrase:O})=>{return MM.fromPhrase(O,void 0,G)}).with({signer:a.not(a.nullish)},({signer:O})=>O).otherwise(()=>{return}),X=!0,J}async function $(){let O=Z();return O?await O.getAddress():""}async function Q(O){let _=Z();if(!_)throw new N("toolbox_hypercore_no_signer");let I=jH(O.typedData),z=await _.signTypedData(I.domain,I.types,I.message);return{action:O.action,endpoint:O.endpoint,nonce:O.nonce,signature:WH(z),..."expiresAfter"in O?{expiresAfter:O.expiresAfter}:{},..."vaultAddress"in O?{vaultAddress:O.vaultAddress}:{}}}async function C(O){let _=L(O,"helpers_invalid_params"),I=await l(),[z,f,R]=await Promise.all([h.post(`${I}/info`,{json:{type:"spotClearinghouseState",user:_}}),h.post(`${I}/info`,{json:{type:"clearinghouseState",user:_}}),h.post(`${I}/info`,{json:{type:"spotMeta"}})]),V=(z.spotState?.balances||z.balances||[]).map(({coin:E,token:y,total:A})=>LH({coin:E,spotMeta:R,token:y,value:A})).filter((E)=>!!E),P=LH({coin:"USDC",spotMeta:R,value:f.withdrawable||f.marginSummary?.accountValue||f.marginSummary?.totalRawUsd});return UM(P?[...V,P]:V)}async function U(O,_=!0){let I=L(O,"helpers_invalid_params");try{let z=await HM.getChainBalance({address:I,chain:B,scamFilter:_});if(z.length){let f=z.map(({identifier:V,value:P,decimal:E})=>new g({decimal:E||e,identifier:V,value:P}));return f.some((V)=>V.isGasAsset)?f:[g.from({chain:B}),...f]}}catch{}return C(I)}async function K({sweep:O,..._}){let I=Z();if(!I)throw new N("toolbox_hypercore_no_signer");let z=_.sender||await I.getAddress(),f=await qH({..._,feeRate:0,sender:z,sweep:O}),R=await Q(f);return FH({kind:"transfer",lookup:VH({action:f.action,nonce:f.nonce,user:f.action.fromSubAccount||z}),signed:R})}async function j(O){let _=Z();if(!_)throw new N("toolbox_hypercore_no_signer");let{action:I,typedData:z,...f}=O,R=structuredClone(I),V=structuredClone(z),P=await _.getAddress(),E=await u(),y=[...new Set([E,JM??E])];IH({...f,action:R,allowedEndpoints:y,typedData:V});let A=R.fromSubAccount?L(R.fromSubAccount,"helpers_invalid_params"):P,p=await AH({destination:R.destination,sender:A});await kH({activationFee:p,amount:R.amount,sourceDex:R.sourceDex,token:R.token,user:A});let m=await Q({action:R,endpoint:E,nonce:R.nonce,typedData:V});return FH({kind:"payin",lookup:VH({action:R,nonce:R.nonce,user:A}),signed:m})}function q(){return g.from({chain:B,value:0})}return{broadcastTransaction:SH,createL1ActionRequest:IM,createSendAssetTransaction:qH,createTransaction:qM,createUserSignedActionRequest:TH,estimateTransactionFee:q,getAddress:$,getBalance:U,getBalanceFromChain:C,getState:{clearinghouse:HH,frontendOpenOrders:_M,openOrders:WM,orderStatus:CM,spotClearinghouse:wH,userFills:RM,userFillsByTime:NM},signAndBroadcastSendAsset:j,signTransaction:Q,transfer:K,validateAddress:xH}}export{xH as validateHyperCoreAddress,nM as getHyperCoreToolbox,TH as createUserSignedActionRequest,qM as createTransaction,qH as createSendAssetTransaction,IM as createL1ActionRequest,DM as buildUsdClassTransferAction,BM as buildUpdateLeverageAction,PM as buildUpdateIsolatedMarginAction,wM as buildTopUpIsolatedOnlyMarginAction,yM as buildTokenDelegateAction,XH as buildSendAssetAction,TM as buildScheduleCancelAction,zM as buildOrderAction,KM as buildModifyAction,VM as buildCancelByCloidAction,FM as buildCancelAction,EM as buildBatchModifyAction,bM as buildApproveBuilderFeeAction,AM as buildApproveAgentAction,x as HYPERCORE_USDC_TOKEN_ID};
@@ -122,7 +122,8 @@ export declare function getHyperCoreToolbox(toolboxParams?: HyperCoreToolboxPara
122
122
  createUserSignedActionRequest: typeof createUserSignedActionRequest;
123
123
  estimateTransactionFee: () => AssetValue;
124
124
  getAddress: () => Promise<string>;
125
- getBalance: (address: string) => Promise<AssetValue[]>;
125
+ getBalance: (address: string, scamFilter?: boolean) => Promise<AssetValue[]>;
126
+ getBalanceFromChain: (address: string) => Promise<AssetValue[]>;
126
127
  getState: {
127
128
  clearinghouse: typeof getClearinghouseState;
128
129
  frontendOpenOrders: typeof getFrontendOpenOrders;
package/package.json CHANGED
@@ -1,5 +1,5 @@
1
1
  {
2
- "dependencies": { "@swapkit/helpers": "5.0.0", "@swapkit/utxo-signer": "3.0.0" },
2
+ "dependencies": { "@swapkit/helpers": "5.0.1", "@swapkit/utxo-signer": "3.0.0" },
3
3
  "description": "SwapKit - Toolboxes",
4
4
  "devDependencies": {
5
5
  "@aptos-labs/ts-sdk": "7.0.1",
@@ -131,5 +131,5 @@
131
131
  "type-check:go": "tsgo"
132
132
  },
133
133
  "type": "module",
134
- "version": "5.0.0"
134
+ "version": "5.1.0"
135
135
  }