@swapkit/toolboxes 5.1.1 → 5.2.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 +14 -0
- package/dist/chunk-ye1j5pz2.js +2 -0
- package/dist/{chunk-v9dcj9m7.js → chunk-zhn86hw6.js} +1 -1
- package/dist/src/cardano/index.js +1 -1
- package/dist/src/cosmos/index.js +1 -1
- 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/near/index.js +1 -1
- package/dist/src/ripple/index.js +1 -1
- package/dist/src/stellar/index.js +1 -1
- package/dist/src/sui/index.js +1 -1
- package/dist/src/ton/index.js +1 -1
- package/dist/src/utxo/index.js +1 -1
- package/dist/types/index.d.ts +1 -1
- package/dist/types/ripple/index.d.ts +4 -2
- package/dist/types/stellar/types.d.ts +1 -0
- package/dist/types/sui/types.d.ts +3 -1
- package/dist/types/utxo/hdWallet.d.ts +1 -1
- package/package.json +2 -2
- package/dist/chunk-55jkfkar.js +0 -2
|
@@ -1 +1 @@
|
|
|
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};
|
|
1
|
+
import"../../chunk-44m22jy1.js";import{q as KH}from"../../chunk-ye1j5pz2.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};
|
package/dist/src/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{ga as t}from"../chunk-xbdjxeqd.js";import{AssetValue as W,Chain as o,CosmosChains as x,EVMChains as c,FeeOption as k,SwapKitError as v,UTXOChains as b}from"@swapkit/helpers";async function E(){let{match:l}=await import("ts-pattern"),{validateAleoAddress:r}=await import("./aleo/index.js"),{validateAptosAddress:i}=await import("./aptos/index.js"),{validateEVMAddress:e}=await import("./evm/index.js"),{validateCardanoAddress:a}=await import("./cardano/index.js"),{getCosmosAddressValidator:s}=await import("./cosmos/index.js"),{validateHyperCoreAddress:T}=await import("./hypercore/index.js"),{validateSolanaAddress:p}=await import("./solana/index.js"),{validateStarknetAddress:C}=await import("./starknet/index.js"),{validateSuiAddress:h}=await import("./sui/index.js"),{validateTonAddress:u}=await import("./ton/index.js"),{getUTXOAddressValidator:d}=await import("./utxo/index.js"),{validateNearAddress:f}=await import("./near/index.js"),{validateRadixAddress:g}=await import("./radix/index.js"),{validateRippleAddress:w}=await import("./ripple/index.js"),{validateTronAddress:S}=await import("./tron/index.js"),{validateStellarAddress:P}=await import("./stellar/index.js");return function({address:n,chain:A}){return l(A).with(...c,()=>e(n)).with(...b,(m)=>{return d(m)(n)}).with(...x,(m)=>{return s(m)(n)}).with(o.Aleo,()=>r(n)).with(o.Aptos,()=>i(n)).with(o.Radix,()=>g(n)).with(o.Hype,()=>T(n)).with(o.Near,()=>f(n)).with(o.Ripple,()=>w(n)).with(o.Solana,()=>p(n)).with(o.Stellar,()=>P(n)).with(o.Starknet,()=>C(n)).with(o.Sui,()=>h(n)).with(o.Ton,()=>u(n)).with(o.Tron,()=>S(n)).with(o.Cardano,()=>a(n)).otherwise(()=>!1)}}function
|
|
1
|
+
import{ga as t}from"../chunk-xbdjxeqd.js";import{AssetValue as W,Chain as o,CosmosChains as x,EVMChains as c,FeeOption as k,SwapKitError as v,UTXOChains as b}from"@swapkit/helpers";async function E(){let{match:l}=await import("ts-pattern"),{validateAleoAddress:r}=await import("./aleo/index.js"),{validateAptosAddress:i}=await import("./aptos/index.js"),{validateEVMAddress:e}=await import("./evm/index.js"),{validateCardanoAddress:a}=await import("./cardano/index.js"),{getCosmosAddressValidator:s}=await import("./cosmos/index.js"),{validateHyperCoreAddress:T}=await import("./hypercore/index.js"),{validateSolanaAddress:p}=await import("./solana/index.js"),{validateStarknetAddress:C}=await import("./starknet/index.js"),{validateSuiAddress:h}=await import("./sui/index.js"),{validateTonAddress:u}=await import("./ton/index.js"),{getUTXOAddressValidator:d}=await import("./utxo/index.js"),{validateNearAddress:f}=await import("./near/index.js"),{validateRadixAddress:g}=await import("./radix/index.js"),{validateRippleAddress:w}=await import("./ripple/index.js"),{validateTronAddress:S}=await import("./tron/index.js"),{validateStellarAddress:P}=await import("./stellar/index.js");return function({address:n,chain:A}){return l(A).with(...c,()=>e(n)).with(...b,(m)=>{return d(m)(n)}).with(...x,(m)=>{return s(m)(n)}).with(o.Aleo,()=>r(n)).with(o.Aptos,()=>i(n)).with(o.Radix,()=>g(n)).with(o.Hype,()=>T(n)).with(o.Near,()=>f(n)).with(o.Ripple,()=>w(n)).with(o.Solana,()=>p(n)).with(o.Stellar,()=>P(n)).with(o.Starknet,()=>C(n)).with(o.Sui,()=>h(n)).with(o.Ton,()=>u(n)).with(o.Tron,()=>S(n)).with(o.Cardano,()=>a(n)).otherwise(()=>!1)}}function U(l){return async function(i){let{match:e}=await import("ts-pattern");return e(l).returnType().with(...c,async(a)=>{let s=await y(a),T=await s.createTransaction(i),p="feeOptionKey"in i?i.feeOptionKey:k.Fast;return s.estimateTransactionFee({...T,feeOption:p})}).with(o.Bitcoin,o.BitcoinCash,o.Dogecoin,o.Dash,o.Litecoin,o.Solana,o.Ripple,o.Tron,o.Near,o.Cardano,o.Hype,async(a)=>{return(await y(a)).estimateTransactionFee(i)}).with(o.Aptos,async()=>{let{getAptosToolbox:a}=await import("./aptos/index.js");return a().estimateTransactionFee(i)}).with(o.Aleo,async()=>{let{getAleoToolbox:a}=await import("./aleo/index.js");return a().estimateTransactionFee(i)}).with(o.Starknet,async()=>{let{getStarknetToolbox:a}=await import("./starknet/index.js");return(await a()).estimateTransactionFee(i)}).with(o.Stellar,async()=>{let{getStellarToolbox:a}=await import("./stellar/index.js");return a().estimateTransactionFee()}).with(o.Sui,async()=>{let{getSuiToolbox:a}=await import("./sui/index.js");return a().estimateTransactionFee(i)}).with(o.Ton,async()=>{let{getTONToolbox:a}=await import("./ton/index.js");return a().estimateTransactionFee(i)}).with(...x,async()=>{let{estimateTransactionFee:a}=await import("./cosmos/index.js");return a(i)}).otherwise(async()=>W.from({chain:l}))}}async function y(l,r){let{match:i}=await import("ts-pattern");return i(l).returnType().with(...c,async()=>{let{getEvmToolboxAsync:e}=await import("../chunk-zhn86hw6.js");return await e(l,r)}).with(...b,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(o.Aleo,async()=>{let{getAleoToolbox:e}=await import("./aleo/index.js");return e(r)}).with(o.Aptos,async()=>{let{getAptosToolbox:e}=await import("./aptos/index.js");return e(r)}).with(o.Hype,async()=>{let{getHyperCoreToolbox:e}=await import("./hypercore/index.js");return e(r)}).with(o.Radix,async()=>{let{getRadixToolbox:e}=await import("./radix/index.js");return e(r)}).with(o.Ripple,async()=>{let{getRippleToolbox:e}=await import("./ripple/index.js");return e(r)}).with(o.Solana,async()=>{let{getSolanaToolbox:e}=await import("./solana/index.js");return e(r)}).with(o.Stellar,async()=>{let{getStellarToolbox:e}=await import("./stellar/index.js");return e(r)}).with(o.Starknet,async()=>{let{getStarknetToolbox:e}=await import("./starknet/index.js");return e(r)}).with(o.Sui,async()=>{let{getSuiToolbox:e}=await import("./sui/index.js");return e(r)}).with(o.Tron,async()=>{let{getTronToolbox:e}=await import("./tron/index.js");return e(r)}).with(o.Near,async()=>{let{getNearToolbox:e}=await import("./near/index.js");return e(r)}).with(o.Cardano,async()=>{let{getCardanoToolbox:e}=await import("./cardano/index.js");return e(r)}).with(o.Ton,async()=>{let{getTONToolbox:e}=await import("./ton/index.js");return e(r)}).otherwise(()=>{throw new v("toolbox_not_supported",{chain:l})})}export{y as getToolbox,U as getFeeEstimator,E as getAddressValidator};
|
package/dist/src/near/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{fa as qE}from"../../chunk-nvfkjbyq.js";import{ga as X}from"../../chunk-xbdjxeqd.js";import{derivationPathToString as VE,SwapKitError as bE}from"@swapkit/helpers";function y(x){return x.length>=2&&x.length<=64&&/^(([a-z\d]+[-_])*[a-z\d]+\.)*([a-z\d]+[-_])*[a-z\d]+$/.test(x)}async function l(x){let{KeyPair:M}=await import("@near-js/crypto"),R=x.index||0,T=x.derivationPath?VE(x.derivationPath.slice(0,3)):`m/44'/397'/${R}'`,{parseSeedPhrase:J}=await import("near-seed-phrase"),{secretKey:U}=J(x.phrase,T),w=M.fromString(U);return NE(w)}async function OE(x){let{KeyPair:M}=await import("@near-js/crypto"),R=M.fromString(x);return NE(R)}async function NE(x){let{KeyPairSigner:M}=await import("@near-js/signers");class R extends M{#E;constructor(T){super(T);this.#E=T}getAddress(){let T=this.#E.getPublicKey(),J=Buffer.from(T.data).toString("hex");return Promise.resolve(J)}}return new R(x)}async function g(x,M){let T=(await x.query({account_id:M,finality:"final",request_type:"view_access_key_list"})).keys.find((S)=>S.access_key.permission==="FullAccess");if(!T)throw new bE("toolbox_near_no_public_key_found");let{PublicKey:J}=await import("@near-js/crypto"),U=J.fromString(T.public_key);return{nonce:T.access_key.nonce||0,publicKey:U}}var $={ACCESS_KEY_ADDITION:"5",ACCESS_KEY_DELETION:"5",ACCOUNT_CREATION:"30",CONTRACT_CALL:"150",CONTRACT_DEPLOYMENT:"200",SIMPLE_TRANSFER:"1",STAKE:"10",STORAGE_DEPOSIT:"150",TOKEN_TRANSFER:"150"};function _E(x){return"recipient"in x&&"amount"in x&&!("contractId"in x)}function CE(x){return"contractId"in x&&"methodName"in x}function xE(x){return"actions"in x}function LE(x){return"newAccountId"in x}function ME(x){return"contractCode"in x}function RE(x){return"customEstimator"in x}function TE(x){let M=0;for(let R of x)switch(R.enum){case"transfer":M+=Number($.SIMPLE_TRANSFER);break;case"functionCall":M+=Number($.CONTRACT_CALL);break;case"createAccount":M+=Number($.ACCOUNT_CREATION);break;case"deployContract":M+=Number($.CONTRACT_DEPLOYMENT);break;case"addKey":M+=Number($.ACCESS_KEY_ADDITION);break;case"deleteKey":M+=Number($.ACCESS_KEY_DELETION);break;case"stake":M+=Number($.STAKE);break;default:M+=Number($.CONTRACT_CALL)}return M.toString()}function YE(x){if(x==="ft_transfer"||x==="ft_transfer_call")return $.TOKEN_TRANSFER;if(x==="storage_deposit")return $.STORAGE_DEPOSIT;return $.CONTRACT_CALL}function uE(x){return(BigInt(x)*BigInt(1000000000000)).toString()}function lE(x){return(BigInt(x)/BigInt(1000000000000)).toString()}async function QE({account:x,contractId:M,viewMethods:R,changeMethods:T}){let{Contract:J}=await import("@near-js/accounts");return new J(x,M,{changeMethods:T,useLocalViewExecution:!0,viewMethods:R})}import{AssetValue as WE,Chain as G,getRPCUrl as KE,SwapKitError as Q}from"@swapkit/helpers";import{match as XE,P as ZE}from"ts-pattern";var $E=1250000000000000000000n,JE=150000000000000n,yE=150000000000000n,SE=250000000000000n,PE=250000000000000n,hE=500n,p=10000n;function tE(x){let M;async function R(){if(M)return M;return M=await XE(x).with({phrase:ZE.string},async(E)=>{return await l(E)}).with({signer:ZE.any},({signer:E})=>E).otherwise(()=>{return}),M}async function T(){let{JsonRpcProvider:E}=await import("@near-js/providers"),O=await KE(G.Near);return new E({url:O})}async function J(E){let{Account:O}=await import("@near-js/accounts"),N=await T(),_=await R(),C=E||await U();return new O(C,N,_)}async function U(){let E=await R();if(!E)throw new Q("toolbox_near_no_signer");return await E.getAddress()}async function w(E,O){return(O||await T()).callFunction(E.contractId,"storage_balance_of",{account_id:E.accountId},{finality:"final"})}async function S(E,O){try{let N=await O.callFunction(E,"storage_balance_bounds",{},{finality:"final"});return N?.min?BigInt(N.min):$E}catch{return $E}}function P(E){return(E*(p+hE)+p-1n)/p}function d(E,O){return BigInt(E)*BigInt(O.runtime_config.storage_amount_per_byte)}function n(E,O){if(E<=0n)throw new Q({errorKey:"toolbox_sweep_amount_too_low",info:O});return E}async function h(E){return await(E||await T()).experimental_protocolConfig({finality:"final"})}async function UE(E,O,N){let C=await(N||await T()).callFunction(E,"ft_balance_of",{account_id:O},{finality:"final"});return BigInt(C||"0")}async function jE(E){if(!await R())throw new Q("toolbox_near_no_signer");let{assetValue:N,recipient:_,memo:C,sweep:L}=E,Y=await U(),W=await o({assetValue:N,memo:C,recipient:_,sender:Y,sweep:L});return r(W)}async function zE({assetValue:E,attachedDeposit:O,memo:N,provider:_,recipient:C,sender:L,sweep:Y}){let W=E.address;if(!W)throw new Q("toolbox_near_missing_contract_address");let Z=await w({accountId:C,contractId:W},_),q=Z?0n:await S(W,_),j=Z?SE:yE,z=BigInt(O||"1"),I=E.getBaseValue("bigint");if(Y){let[F,f,H,V]=await Promise.all([UE(W,L,_),_.viewAccount(L,{finality:"final"}),h(_),u(_)]);I=n(F,{asset:E.toString(),balance:F.toString()});let b=d(f.storage_usage,H),A=f.amount-b,K=q,EE=(j+(Z?0n:JE))*P(V)+K+z;if(A<EE)throw new Q("toolbox_sweep_amount_too_low",{asset:E.toString(),availableNear:A.toString(),reason:"Insufficient NEAR to cover token transfer gas and storage deposit",requiredNear:EE.toString()})}let B=[];if(!Z)B.push(await k({args:{account_id:C},attachedDeposit:q.toString(),gas:JE.toString(),methodName:"storage_deposit"}));return B.push(await k({args:{amount:I.toString(),memo:N||null,receiver_id:C},attachedDeposit:z.toString(),gas:j.toString(),methodName:"ft_transfer"})),c({actions:B,receiverId:W,sender:L})}async function BE({assetValue:E,attachedDeposit:O,memo:N,provider:_,recipient:C,sender:L,sweep:Y}){let W=E.getBaseValue("bigint");if(Y){let[H,V]=await Promise.all([_.viewAccount(L,{finality:"final"}),h(_)]),b=await a({assetValue:E,memo:N,recipient:C,sweep:Y},V),A=d(H.storage_usage,V),K=0n;if(N&&O){let e=await u(_);K=PE*P(e)+BigInt(O)}W=n(H.amount-b.getBaseValue("bigint")-A-K,{asset:E.toString(),balance:H.amount.toString(),fee:b.getBaseValue("bigint").toString(),storageStakeReserve:A.toString()})}let[{publicKey:Z,nonce:q},j,{actionCreators:z,createTransaction:I},{baseDecode:B}]=await Promise.all([g(_,L),_.block({finality:"final"}),import("@near-js/transactions"),import("@near-js/utils")]),F=[z.transfer(W)];if(N&&O)F.push(z.functionCall("memo",{memo:N},BigInt("250000000000000"),BigInt(O)));let f=B(j.header.hash);return I(L,Z,C,q+1,F,f)}async function o({recipient:E,assetValue:O,memo:N,attachedDeposit:_,sender:C,functionCall:L,sweep:Y}){if(!y(E))throw new Q("toolbox_near_invalid_address",{recipient:E});if(!y(C))throw new Q("toolbox_near_invalid_address",{sender:C});if(L)return i({...L,sender:C});if(Y&&!await R())throw new Q("toolbox_near_no_signer");let W=await T(),Z={assetValue:O,attachedDeposit:_,memo:N,provider:W,recipient:E,sender:C,sweep:Y};return O.isGasAsset?BE(Z):zE(Z)}function FE(E){let O=E.encode();return Buffer.from(O).toString("base64")}async function i({args:E,attachedDeposit:O,contractId:N,gas:_,methodName:C,sender:L}){let Y=await k({args:E,attachedDeposit:O,gas:_,methodName:C});return c({actions:[Y],receiverId:N,sender:L})}async function c({actions:E,receiverId:O,sender:N}){let _=await T(),[{publicKey:C,nonce:L},Y,{createTransaction:W},{baseDecode:Z}]=await Promise.all([g(_,N),_.block({finality:"final"}),import("@near-js/transactions"),import("@near-js/utils")]),q=Z(Y.header.hash);return W(N,C,O,L+1,E,q)}async function k(E){let{actionCreators:O}=await import("@near-js/transactions");return O.functionCall(E.methodName,Buffer.from(JSON.stringify(E.args)),BigInt(E.gas),BigInt(E.attachedDeposit))}async function s(E){let O=await R();if(!O)throw new Q("toolbox_near_no_signer");await IE(E);let[N,_]=await O.signTransaction(E);return _}async function IE(E){let O=E.publicKey;if(O.toString?.().startsWith("ed25519:")||O.toString?.().startsWith("secp256k1:"))return;let{KeyType:N,PublicKey:_}=await import("@near-js/crypto"),C=O.data||O.ed25519Key?.data,L=O.secp256k1Key?.data;if(C){E.publicKey=new _({data:Uint8Array.from(C),keyType:N.ED25519});return}if(L)E.publicKey=new _({data:Uint8Array.from(L),keyType:N.SECP256K1})}function m(E){if(typeof E==="string")return E;if(Array.isArray(E))return E.map(m).find(Boolean);if(!(E&&typeof E==="object"))return;let O=E;return O.transaction?.hash||O.transaction_outcome?.id}function v(E){return E instanceof Error?E.message:String(E)}async function t(E){let N=await(await T()).sendTransaction(E),_=m(N);if(!_)throw new Q("toolbox_near_transfer_failed",{result:N});return _}async function r(E){let O=await R();if(!O)throw new Q("toolbox_near_no_signer");let N;try{N=await s(E)}catch(_){let C;try{C=O.signAndSendTransaction?await O.signAndSendTransaction({actions:E.actions,receiverId:E.receiverId,signerId:E.signerId}):await O.signAndSendTransactions?.({transactions:[E]})}catch(Y){throw new Q({errorKey:"toolbox_near_sign_transaction_failed",info:{directSignError:v(_),signAndSendError:v(Y)}},Y)}let L=m(C);if(L)return L;throw _}return t(N)}async function a(E,O){let N=await R();if("assetValue"in E){if(E.sweep&&!N)throw new Q("toolbox_near_no_signer");try{let[C,L]=await Promise.all([u(),O?Promise.resolve(O):h()]),{runtime_config:Y}=L,{execution:W,send_sir:Z}=Y.transaction_costs.action_receipt_creation_config,{execution:q,send_sir:j}=Y.transaction_costs.action_creation_config.transfer_cost,z=BigInt(j)+BigInt(q),I=BigInt(Z)+BigInt(W),B=z+I,F=E.sweep?P(C):C,f=B*F;return WE.from({chain:G.Near,value:f})}catch(C){throw new Q({errorKey:"toolbox_fee_estimation_failed",info:{chain:G.Near,message:v(C)}},C)}}let _=N?await J():void 0;return D(E,_)}async function u(E){let N=await(E||await T()).gasPrice(null);return BigInt(N.gas_price)}async function fE(E,O,N){if(!await R())throw new Q("toolbox_near_no_signer");let C=await J(),{formatNearAmount:L}=await import("@near-js/utils"),{PublicKey:Y}=await import("@near-js/crypto"),W=L(N)||"0";return(await C.createAccount(E,Y.fromString(O),BigInt(W))).transaction.hash}async function HE(E){let O=await R();try{if(!O)throw new Q("toolbox_near_no_signer");let{actionCreators:N}=await import("@near-js/transactions"),{contractId:_,methodName:C,args:L,deposit:Y}=E,W=await J(),Z=await D({args:L||{},contractId:_,methodName:C}),q=N.functionCall(C,L||{},Z.getBaseValue("bigint"),BigInt(Y||"1"));return(await W.signAndSendTransaction({actions:[q],receiverId:_})).transaction_outcome.id}catch(N){throw new Q("toolbox_near_transfer_failed",{error:N})}}async function AE(E){let O=await J();return QE({account:O,changeMethods:E.changeMethods,contractId:E.contractId,viewMethods:E.viewMethods})}async function GE(E){if(!await R())throw new Q("toolbox_near_no_signer");if(E.actions.length===0)throw new Q("toolbox_near_empty_batch");return(await(await J()).signAndSendTransaction({actions:E.actions,receiverId:E.receiverId})).transaction.hash}async function D(E,O){let N=await XE(E).when(_E,()=>$.SIMPLE_TRANSFER).when(CE,(C)=>YE(C.methodName)).when(xE,(C)=>TE(C.actions)).when(LE,()=>$.ACCOUNT_CREATION).when(ME,()=>$.CONTRACT_DEPLOYMENT).when(RE,(C)=>{if(!O)throw new Q("toolbox_near_no_account");return C.customEstimator(O)}).otherwise(()=>{throw new Q("toolbox_near_invalid_gas_params")}),_=BigInt(N)*BigInt(1000000000000);return WE.from({chain:G.Near,value:_})}function wE(E,O){return console.warn("NEAR toolbox: estimateGas is deprecated, use estimateGasLimit instead"),D(E,O)}async function kE(){let E=await T();try{return(await E.gasPrice(null)).gas_price||"100000000"}catch{return"100000000"}}async function DE(){let E=await R();return E?(await E.getPublicKey()).toString():""}return{broadcastTransaction:t,callFunction:HE,createAction:k,createContract:AE,createContractFunctionCall:i,createSubAccount:fE,createTransaction:o,estimateGas:wE,estimateGasLimit:D,estimateTransactionFee:a,executeBatchTransaction:GE,getAddress:U,getBalance:qE(G.Near),getGasPrice:kE,getNearProvider:T,getPublicKey:DE,getSignerFromPhrase:l,getSignerFromPrivateKey:OE,serializeTransaction:FE,signAndBroadcastTransaction:r,signTransaction:s,transfer:jE,validateAddress:y}}export{y as validateNearAddress,uE as tgasToGas,_E as isSimpleTransfer,RE as isCustomEstimator,ME as isContractDeployment,CE as isContractCall,xE as isBatchTransaction,LE as isAccountCreation,tE as getNearToolbox,OE as getNearSignerFromPrivateKey,l as getNearSignerFromPhrase,g as getFullAccessPublicKey,YE as getContractMethodGas,lE as gasToTGas,TE as estimateBatchGas,QE as createNearContract,$ as GAS_COSTS};
|
|
1
|
+
import{fa as qE}from"../../chunk-nvfkjbyq.js";import{ga as Z}from"../../chunk-xbdjxeqd.js";import{Chain as bE,derivationPathToString as KE,SwapKitError as OE}from"@swapkit/helpers";function K(N){return N.length>=2&&N.length<=64&&/^(([a-z\d]+[-_])*[a-z\d]+\.)*([a-z\d]+[-_])*[a-z\d]+$/.test(N)}async function u(N){if(N.derivationPath&&(N.derivationPath[3]||N.derivationPath[4]))throw new OE("toolbox_derivation_slot_unsupported",{chain:bE.Near,derivationPath:N.derivationPath});let{KeyPair:M}=await import("@near-js/crypto"),T=N.derivationPath?KE(N.derivationPath.slice(0,3)):`m/44'/397'/${N.index??0}'`,{parseSeedPhrase:R}=await import("near-seed-phrase"),{secretKey:W}=R(N.phrase,T),q=M.fromString(W);return NE(q)}async function _E(N){let{KeyPair:M}=await import("@near-js/crypto"),T=M.fromString(N);return NE(T)}async function NE(N){let{KeyPairSigner:M}=await import("@near-js/signers");class T extends M{#E;constructor(R){super(R);this.#E=R}getAddress(){let R=this.#E.getPublicKey(),W=Buffer.from(R.data).toString("hex");return Promise.resolve(W)}}return new T(N)}async function l(N,M){let R=(await N.query({account_id:M,finality:"final",request_type:"view_access_key_list"})).keys.find((y)=>y.access_key.permission==="FullAccess");if(!R)throw new OE("toolbox_near_no_public_key_found");let{PublicKey:W}=await import("@near-js/crypto"),q=W.fromString(R.public_key);return{nonce:R.access_key.nonce||0,publicKey:q}}var J={ACCESS_KEY_ADDITION:"5",ACCESS_KEY_DELETION:"5",ACCOUNT_CREATION:"30",CONTRACT_CALL:"150",CONTRACT_DEPLOYMENT:"200",SIMPLE_TRANSFER:"1",STAKE:"10",STORAGE_DEPOSIT:"150",TOKEN_TRANSFER:"150"};function CE(N){return"recipient"in N&&"amount"in N&&!("contractId"in N)}function xE(N){return"contractId"in N&&"methodName"in N}function LE(N){return"actions"in N}function ME(N){return"newAccountId"in N}function TE(N){return"contractCode"in N}function RE(N){return"customEstimator"in N}function YE(N){let M=0;for(let T of N)switch(T.enum){case"transfer":M+=Number(J.SIMPLE_TRANSFER);break;case"functionCall":M+=Number(J.CONTRACT_CALL);break;case"createAccount":M+=Number(J.ACCOUNT_CREATION);break;case"deployContract":M+=Number(J.CONTRACT_DEPLOYMENT);break;case"addKey":M+=Number(J.ACCESS_KEY_ADDITION);break;case"deleteKey":M+=Number(J.ACCESS_KEY_DELETION);break;case"stake":M+=Number(J.STAKE);break;default:M+=Number(J.CONTRACT_CALL)}return M.toString()}function QE(N){if(N==="ft_transfer"||N==="ft_transfer_call")return J.TOKEN_TRANSFER;if(N==="storage_deposit")return J.STORAGE_DEPOSIT;return J.CONTRACT_CALL}function lE(N){return(BigInt(N)*BigInt(1000000000000)).toString()}function gE(N){return(BigInt(N)/BigInt(1000000000000)).toString()}async function XE({account:N,contractId:M,viewMethods:T,changeMethods:R}){let{Contract:W}=await import("@near-js/accounts");return new W(N,M,{changeMethods:R,useLocalViewExecution:!0,viewMethods:T})}import{AssetValue as ZE,Chain as G,getRPCUrl as yE,SwapKitError as Q}from"@swapkit/helpers";import{match as $E,P as JE}from"ts-pattern";var WE=1250000000000000000000n,jE=150000000000000n,SE=150000000000000n,PE=250000000000000n,hE=250000000000000n,mE=500n,g=10000n;function rE(N){let M;async function T(){if(M)return M;return M=await $E(N).with({phrase:JE.string},async(E)=>{return await u(E)}).with({signer:JE.any},({signer:E})=>E).otherwise(()=>{return}),M}async function R(){let{JsonRpcProvider:E}=await import("@near-js/providers"),O=await yE(G.Near);return new E({url:O})}async function W(E){let{Account:O}=await import("@near-js/accounts"),_=await R(),C=await T(),x=E||await q();return new O(x,_,C)}async function q(){let E=await T();if(!E)throw new Q("toolbox_near_no_signer");return await E.getAddress()}async function p(E,O){return(O||await R()).callFunction(E.contractId,"storage_balance_of",{account_id:E.accountId},{finality:"final"})}async function y(E,O){try{let _=await O.callFunction(E,"storage_balance_bounds",{},{finality:"final"});return _?.min?BigInt(_.min):WE}catch{return WE}}function S(E){return(E*(g+mE)+g-1n)/g}function d(E,O){return BigInt(E)*BigInt(O.runtime_config.storage_amount_per_byte)}function n(E,O){if(E<=0n)throw new Q({errorKey:"toolbox_sweep_amount_too_low",info:O});return E}async function P(E){return await(E||await R()).experimental_protocolConfig({finality:"final"})}async function UE(E,O,_){let x=await(_||await R()).callFunction(E,"ft_balance_of",{account_id:O},{finality:"final"});return BigInt(x||"0")}async function zE(E){if(!await T())throw new Q("toolbox_near_no_signer");let{assetValue:_,recipient:C,memo:x,sweep:L}=E,Y=await q(),X=await o({assetValue:_,memo:x,recipient:C,sender:Y,sweep:L});return r(X)}async function BE({assetValue:E,attachedDeposit:O,memo:_,provider:C,recipient:x,sender:L,sweep:Y}){let X=E.address;if(!X)throw new Q("toolbox_near_missing_contract_address");let $=await p({accountId:x,contractId:X},C),j=$?0n:await y(X,C),U=$?PE:SE,z=BigInt(O||"1"),F=E.getBaseValue("bigint");if(Y){let[I,f,H,D]=await Promise.all([UE(X,L,C),C.viewAccount(L,{finality:"final"}),P(C),v(C)]);F=n(I,{asset:E.toString(),balance:I.toString()});let V=d(f.storage_usage,H),A=f.amount-V,b=j,EE=(U+($?0n:jE))*S(D)+b+z;if(A<EE)throw new Q("toolbox_sweep_amount_too_low",{asset:E.toString(),availableNear:A.toString(),reason:"Insufficient NEAR to cover token transfer gas and storage deposit",requiredNear:EE.toString()})}let B=[];if(!$)B.push(await k({args:{account_id:x},attachedDeposit:j.toString(),gas:jE.toString(),methodName:"storage_deposit"}));return B.push(await k({args:{amount:F.toString(),memo:_||null,receiver_id:x},attachedDeposit:z.toString(),gas:U.toString(),methodName:"ft_transfer"})),c({actions:B,receiverId:X,sender:L})}async function IE({assetValue:E,attachedDeposit:O,memo:_,provider:C,recipient:x,sender:L,sweep:Y}){let X=E.getBaseValue("bigint");if(Y){let[H,D]=await Promise.all([C.viewAccount(L,{finality:"final"}),P(C)]),V=await a({assetValue:E,memo:_,recipient:x,sweep:Y},D),A=d(H.storage_usage,D),b=0n;if(_&&O){let e=await v(C);b=hE*S(e)+BigInt(O)}X=n(H.amount-V.getBaseValue("bigint")-A-b,{asset:E.toString(),balance:H.amount.toString(),fee:V.getBaseValue("bigint").toString(),storageStakeReserve:A.toString()})}let[{publicKey:$,nonce:j},U,{actionCreators:z,createTransaction:F},{baseDecode:B}]=await Promise.all([l(C,L),C.block({finality:"final"}),import("@near-js/transactions"),import("@near-js/utils")]),I=[z.transfer(X)];if(_&&O)I.push(z.functionCall("memo",{memo:_},BigInt("250000000000000"),BigInt(O)));let f=B(U.header.hash);return F(L,$,x,j+1,I,f)}async function o({recipient:E,assetValue:O,memo:_,attachedDeposit:C,sender:x,functionCall:L,sweep:Y}){if(!K(E))throw new Q("toolbox_near_invalid_address",{recipient:E});if(!K(x))throw new Q("toolbox_near_invalid_address",{sender:x});if(L)return i({...L,sender:x});if(Y&&!await T())throw new Q("toolbox_near_no_signer");let X=await R(),$={assetValue:O,attachedDeposit:C,memo:_,provider:X,recipient:E,sender:x,sweep:Y};return O.isGasAsset?IE($):BE($)}function FE(E){let O=E.encode();return Buffer.from(O).toString("base64")}async function i({args:E,attachedDeposit:O,contractId:_,gas:C,methodName:x,sender:L}){let Y=await k({args:E,attachedDeposit:O,gas:C,methodName:x});return c({actions:[Y],receiverId:_,sender:L})}async function c({actions:E,receiverId:O,sender:_}){let C=await R(),[{publicKey:x,nonce:L},Y,{createTransaction:X},{baseDecode:$}]=await Promise.all([l(C,_),C.block({finality:"final"}),import("@near-js/transactions"),import("@near-js/utils")]),j=$(Y.header.hash);return X(_,x,O,L+1,E,j)}async function k(E){let{actionCreators:O}=await import("@near-js/transactions");return O.functionCall(E.methodName,Buffer.from(JSON.stringify(E.args)),BigInt(E.gas),BigInt(E.attachedDeposit))}async function t(E){let O=await T();if(!O)throw new Q("toolbox_near_no_signer");await fE(E);let[_,C]=await O.signTransaction(E);return C}async function fE(E){let O=E.publicKey;if(O.toString?.().startsWith("ed25519:")||O.toString?.().startsWith("secp256k1:"))return;let{KeyType:_,PublicKey:C}=await import("@near-js/crypto"),x=O.data||O.ed25519Key?.data,L=O.secp256k1Key?.data;if(x){E.publicKey=new C({data:Uint8Array.from(x),keyType:_.ED25519});return}if(L)E.publicKey=new C({data:Uint8Array.from(L),keyType:_.SECP256K1})}function h(E){if(typeof E==="string")return E;if(Array.isArray(E))return E.map(h).find(Boolean);if(!(E&&typeof E==="object"))return;let O=E;return O.transaction?.hash||O.transaction_outcome?.id}function m(E){return E instanceof Error?E.message:String(E)}async function s(E){let _=await(await R()).sendTransaction(E),C=h(_);if(!C)throw new Q("toolbox_near_transfer_failed",{result:_});return C}async function r(E){let O=await T();if(!O)throw new Q("toolbox_near_no_signer");let _;try{_=await t(E)}catch(C){let x;try{x=O.signAndSendTransaction?await O.signAndSendTransaction({actions:E.actions,receiverId:E.receiverId,signerId:E.signerId}):await O.signAndSendTransactions?.({transactions:[E]})}catch(Y){throw new Q({errorKey:"toolbox_near_sign_transaction_failed",info:{directSignError:m(C),signAndSendError:m(Y)}},Y)}let L=h(x);if(L)return L;throw C}return s(_)}async function a(E,O){let _=await T();if("assetValue"in E){if(E.sweep&&!_)throw new Q("toolbox_near_no_signer");try{let[x,L]=await Promise.all([v(),O?Promise.resolve(O):P()]),{runtime_config:Y}=L,{execution:X,send_sir:$}=Y.transaction_costs.action_receipt_creation_config,{execution:j,send_sir:U}=Y.transaction_costs.action_creation_config.transfer_cost,z=BigInt(U)+BigInt(j),F=BigInt($)+BigInt(X),B=z+F,I=E.sweep?S(x):x,f=B*I;return ZE.from({chain:G.Near,value:f})}catch(x){throw new Q({errorKey:"toolbox_fee_estimation_failed",info:{chain:G.Near,message:m(x)}},x)}}let C=_?await W():void 0;return w(E,C)}async function v(E){let _=await(E||await R()).gasPrice(null);return BigInt(_.gas_price)}async function HE(E,O,_){if(!await T())throw new Q("toolbox_near_no_signer");let x=await W(),{formatNearAmount:L}=await import("@near-js/utils"),{PublicKey:Y}=await import("@near-js/crypto"),X=L(_)||"0";return(await x.createAccount(E,Y.fromString(O),BigInt(X))).transaction.hash}async function AE(E){let O=await T();try{if(!O)throw new Q("toolbox_near_no_signer");let{actionCreators:_}=await import("@near-js/transactions"),{contractId:C,methodName:x,args:L,deposit:Y}=E,X=await W(),$=await w({args:L||{},contractId:C,methodName:x}),j=_.functionCall(x,L||{},$.getBaseValue("bigint"),BigInt(Y||"1"));return(await X.signAndSendTransaction({actions:[j],receiverId:C})).transaction_outcome.id}catch(_){throw new Q("toolbox_near_transfer_failed",{error:_})}}async function GE(E){let O=await W();return XE({account:O,changeMethods:E.changeMethods,contractId:E.contractId,viewMethods:E.viewMethods})}async function kE(E){if(!await T())throw new Q("toolbox_near_no_signer");if(E.actions.length===0)throw new Q("toolbox_near_empty_batch");return(await(await W()).signAndSendTransaction({actions:E.actions,receiverId:E.receiverId})).transaction.hash}async function w(E,O){let _=await $E(E).when(CE,()=>J.SIMPLE_TRANSFER).when(xE,(x)=>QE(x.methodName)).when(LE,(x)=>YE(x.actions)).when(ME,()=>J.ACCOUNT_CREATION).when(TE,()=>J.CONTRACT_DEPLOYMENT).when(RE,(x)=>{if(!O)throw new Q("toolbox_near_no_account");return x.customEstimator(O)}).otherwise(()=>{throw new Q("toolbox_near_invalid_gas_params")}),C=BigInt(_)*BigInt(1000000000000);return ZE.from({chain:G.Near,value:C})}function wE(E,O){return console.warn("NEAR toolbox: estimateGas is deprecated, use estimateGasLimit instead"),w(E,O)}async function DE(){let E=await R();try{return(await E.gasPrice(null)).gas_price||"100000000"}catch{return"100000000"}}async function VE(){let E=await T();return E?(await E.getPublicKey()).toString():""}return{broadcastTransaction:s,callFunction:AE,createAction:k,createContract:GE,createContractFunctionCall:i,createSubAccount:HE,createTransaction:o,estimateGas:wE,estimateGasLimit:w,estimateTransactionFee:a,executeBatchTransaction:kE,getAddress:q,getBalance:qE(G.Near),getGasPrice:DE,getNearProvider:R,getPublicKey:VE,getSignerFromPhrase:u,getSignerFromPrivateKey:_E,serializeTransaction:FE,signAndBroadcastTransaction:r,signTransaction:t,transfer:zE,validateAddress:K}}export{K as validateNearAddress,lE as tgasToGas,CE as isSimpleTransfer,RE as isCustomEstimator,TE as isContractDeployment,xE as isContractCall,LE as isBatchTransaction,ME as isAccountCreation,rE as getNearToolbox,_E as getNearSignerFromPrivateKey,u as getNearSignerFromPhrase,l as getFullAccessPublicKey,QE as getContractMethodGas,gE as gasToTGas,YE as estimateBatchGas,XE as createNearContract,J as GAS_COSTS};
|
package/dist/src/ripple/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{ga as A}from"../../chunk-xbdjxeqd.js";import{AssetValue as R,Chain as _,getChainConfig as y,getRPCUrl as $5,SwapKitError as J}from"@swapkit/helpers";import{isValidClassicAddress as W5,isValidXAddress as w}from"ripple-address-codec";import{match as g,P as x}from"ts-pattern";import{SwapKitError as G5}from"@swapkit/helpers";function L(U){return/^[0-9A-Fa-f]{40}$/.test(U)}function D(U){if(L(U))return U.toUpperCase();if(U.length<=3){let f=Buffer.from(U.padEnd(3,"\x00")).toString("hex");return`00${"0".repeat(22)}${f}${"0".repeat(10)}`.toUpperCase()}let m=Buffer.from(U).toString("hex").toUpperCase();if(m.length>40)throw new G5({errorKey:"toolbox_ripple_asset_not_supported",info:{asset:U,reason:"Currency exceeds maximum length (20 bytes)"}});return m.padEnd(40,"0")}function Y5(U){if(!L(U))return U;if(U.toUpperCase().startsWith("00")){let m=U.slice(24,30);try{let f=Buffer.from(m,"hex").toString("ascii").replace(/\0/g,"");if(/^[A-Za-z0-9?!@#$%^&*<>(){}[\]|]+$/.test(f)&&f.length>0)return f}catch{}return U.toUpperCase()}try{let m=U.replace(/0+$/,""),f=m.length%2===0?m:`${m}0`,j=Buffer.from(f,"hex").toString("utf8");if(/^[\x20-\x7E]+$/.test(j))return j}catch{}return U.toUpperCase()}function k(U){if(L(U))return U.toUpperCase();if(U.length<=3)return U;return D(U)}import{RequestClient as m5,warnOnce as z5}from"@swapkit/helpers";var E=[{currency:"USD",decimals:15,domain:"circle.com",issuer:"rcEGREd8NmkKRE8GE424sksyt1tJVFZwu",name:"Circle USDC",verified:!0},{currency:"RLUSD",decimals:15,domain:"ripple.com",issuer:"rMxCKbEDwqr76QuheSUMdEGf4B9xJ8m5De",name:"Ripple USD",verified:!0},{currency:"USD",decimals:15,domain:"bitstamp.net",issuer:"rvYAfWj5gh67oV6fW32ZzP3Aw4Eubs59B",name:"Bitstamp USD",verified:!0},{currency:"BTC",decimals:15,domain:"bitstamp.net",issuer:"rvYAfWj5gh67oV6fW32ZzP3Aw4Eubs59B",name:"Bitstamp BTC",verified:!0},{currency:"EUR",decimals:15,domain:"bitstamp.net",issuer:"rvYAfWj5gh67oV6fW32ZzP3Aw4Eubs59B",name:"Bitstamp EUR",verified:!0},{currency:"USD",decimals:15,domain:"gatehub.net",issuer:"rhub8VRN55s94qWKDv6jmDy1pUykJzF3wq",name:"GateHub USD",verified:!0},{currency:"EUR",decimals:15,domain:"gatehub.net",issuer:"rhub8VRN55s94qWKDv6jmDy1pUykJzF3wq",name:"GateHub EUR",verified:!0},{currency:"BTC",decimals:15,domain:"gatehub.net",issuer:"rchGBxcD1A1C2tdxF6papQYZ8kjRKMYcL",name:"GateHub BTC",verified:!0},{currency:"ETH",decimals:15,domain:"gatehub.net",issuer:"rcA8X3TVMST1n3CJeAdGk1RdRCHii7N2h",name:"GateHub ETH",verified:!0},{currency:"SOLO",decimals:15,domain:"sologenic.com",issuer:"rsoLo2S1kiGeCcn6hCUXVrCpGMWLrRrLZz",name:"Sologenic",verified:!0}];async function _5(U,m){let f=k(U),j=E.find((Q)=>k(Q.currency)===f&&Q.issuer===m);if(j)return j;try{let Q=await m5.get(`https://api.xrplmeta.org/token/${U}:${m}`);if(Q)return{currency:U,decimals:15,description:Q.desc,domain:Q.domain,icon:Q.icon,issuer:m,name:Q.name,verified:Q.self_assessment?.is_regulated||Q.self_assessment?.is_licensed}}catch(Q){z5({condition:!0,id:`xrpl_token_lookup_${U}_${m}`,warning:`Failed to fetch XRPL token info for ${U}:${m}: ${Q}`})}return{currency:U,decimals:15,issuer:m,verified:!1}}function N5(U){return E.filter((m)=>m.issuer===U)}function X5(U,m){let f=k(U);return E.some((j)=>k(j.currency)===f&&j.issuer===m)}var Z5={ACCOUNT_NOT_FOUND:19};function p(U){if(typeof U!=="object"||U===null||!("data"in U))return!1;let{data:m}=U;return typeof m==="object"&&m!==null&&"error_code"in m&&m.error_code===Z5.ACCOUNT_NOT_FOUND}var C={tecFROZEN:"tecFROZEN",tecNO_AUTH:"tecNO_AUTH",tecNO_DST:"tecNO_DST",tecNO_LINE:"tecNO_LINE",tecPATH_DRY:"tecPATH_DRY",tecUNFUNDED_OFFER:"tecUNFUNDED_OFFER"};function c(U){let m=U.match(/^XRP\.([A-Fa-f0-9]{40}|[\x20-\x7E]{1,20})-([a-zA-Z0-9]{25,34})$/);if(!m?.[1]||!m?.[2])return null;if(!P(m[2]))return null;return{currency:m[1],issuer:m[2]}}function f5(U,m){return`${_.Ripple}.${U}-${m}`}async function u(U){if(U.isGasAsset){let{xrpToDrops:f}=await import("xrpl");return f(U.getValue("string"))}let m=c(U.toString());if(!m)throw new J({errorKey:"toolbox_ripple_asset_not_supported",info:{asset:U.toString()}});return{currency:m.currency,issuer:m.issuer,value:U.getValue("string")}}function j5({fee:U,lastLedgerSequence:m,sequence:f,transaction:j}){return f!==void 0&&U!==void 0&&m!==void 0&&!w(j.Account)&&!w(j.Destination)}function o(U){let m,f=()=>{return m??=import("xrpl").then(({Wallet:j})=>j.fromMnemonic(U)),m};return{getAddress:async()=>(await f()).address,signTransaction:async(j)=>(await f()).sign(j)}}function P(U){return W5(U)||w(U)}function O5(U={}){let m;async function f(){if(m)return m;return m=await g(U).with({phrase:x.string},({phrase:G})=>o(G)).with({signer:x.any},({signer:G})=>G).otherwise(()=>{return}),m}let j;async function Q(){let G=await $5(_.Ripple);if(!G)throw new J({errorKey:"toolbox_ripple_rpc_not_configured",info:{chain:_.Ripple}});let{Client:z}=await import("xrpl"),W=new z(G);return await W.connect(),W}async function X(){if(j){let G=await j.catch(()=>null);if(G?.isConnected())return G}return j=Q(),j}async function d(G){let z=await G.request({command:"server_state"}),W=z.result.state.validated_ledger??z.result.state.closed_ledger;if(!W||!Number.isSafeInteger(W.reserve_base)||W.reserve_base<0||!Number.isSafeInteger(W.reserve_inc)||W.reserve_inc<0)throw new J({errorKey:"toolbox_ripple_get_balance_error",info:{reason:"XRPL reserve data is unavailable or invalid"}});return{baseReserveDrops:BigInt(W.reserve_base),ownerReserveDrops:BigInt(W.reserve_inc)}}let b=async()=>{let G=await f();if(!G)throw new J({errorKey:"toolbox_ripple_signer_not_found"});return G.getAddress()},i=async(G)=>{let z=G||await b(),{baseDecimal:W}=y(_.Ripple),Z=await X();try{let[$,v]=await Promise.all([Z.request({account:z,command:"account_info"}),Z.request({account:z,command:"account_lines"})]),B=$.result.account_data.Balance,Y=[R.from({chain:_.Ripple,fromBaseDecimal:W,value:B})];for(let M of v.result.lines){let N=f5(M.currency,M.account);if(Number.parseFloat(M.balance)!==0)Y.push(R.from({asset:N,asyncTokenLookup:!1,value:M.balance}))}return Y}catch($){if(p($))return[R.from({chain:_.Ripple,value:0})];throw new J({errorKey:"toolbox_ripple_get_balance_error",info:{address:z,error:$}})}},T=async()=>{let{baseDecimal:G}=y(_.Ripple),Z=(await(await X()).request({command:"fee"})).result.drops.open_ledger_fee;return R.from({chain:_.Ripple,fromBaseDecimal:G,value:Z})};async function V(G){let z=G||await b(),W=await X();try{return(await W.request({account:z,command:"account_lines"})).result.lines.map(($)=>({account:$.account,authorized:$.authorized??!1,balance:$.balance,currency:$.currency,freeze:$.freeze??!1,freezePeer:$.freeze_peer??!1,limit:$.limit,limitPeer:$.limit_peer,noRipple:$.no_ripple??!1,noRipplePeer:$.no_ripple_peer??!1,peerAuthorized:$.peer_authorized??!1,qualityIn:$.quality_in??0,qualityOut:$.quality_out??0}))}catch(Z){if(p(Z))return[];throw new J({errorKey:"toolbox_ripple_get_trust_lines_error",info:{address:z,error:Z}})}}async function l({address:G,currency:z,issuer:W}){let Z=await V(G),$=D(z);return Z.some((v)=>{return D(v.currency)===$&&v.account===W})}async function S({currency:G,issuer:z,limit:W,sender:Z}){let $=Z||await b();if(!P(z))throw new J({errorKey:"core_transaction_invalid_recipient_address",info:{address:z}});let v=Number.parseFloat(W);if(Number.isNaN(v)||v<0)throw new J({errorKey:"toolbox_ripple_invalid_trust_line_limit",info:{limit:W}});let B=await X(),Y={Account:$,LimitAmount:{currency:G,issuer:z,value:W},TransactionType:"TrustSet"};return B.autofill(Y)}async function t(G,z){let[W,Z,$]=await Promise.all([G.request({account:z,command:"account_info"}),d(G),T()]),{Balance:v,OwnerCount:B}=W.result.account_data,Y=$.getBaseValue("bigint"),M=BigInt(v)-Z.baseReserveDrops-BigInt(B)*Z.ownerReserveDrops-Y;if(M<=0n)throw new J({errorKey:"toolbox_sweep_amount_too_low",info:{asset:_.Ripple,balance:v,baseReserve:Z.baseReserveDrops.toString(),fee:Y.toString(),ownerCount:B,ownerReserve:Z.ownerReserveDrops.toString()}});let{baseDecimal:N}=y(_.Ripple),F=R.from({chain:_.Ripple,fromBaseDecimal:N,value:M.toString()});return{amount:await u(F),fee:Y.toString()}}async function n(G,z){let W=c(G.toString());if(!W)throw new J({errorKey:"toolbox_ripple_asset_not_supported",info:{asset:G.toString()}});let Z=await X(),$="0",v;while(!0){let B=await Z.request({account:z,command:"account_lines",peer:W.issuer,...v!==void 0&&{marker:v}}),Y=B.result.lines.find((N)=>N.account===W.issuer&&D(N.currency)===D(W.currency));if(Y){$=Y.balance;break}let M=B.result.marker;if(M===void 0||M===null)break;v=M}if(!Number.isFinite(Number($))||Number($)<=0)throw new J({errorKey:"toolbox_sweep_amount_too_low",info:{asset:G.toString(),balance:$}});return{currency:W.currency,issuer:W.issuer,value:$}}async function h({assetValue:G,recipient:z,memo:W,sender:Z,sweep:$,destinationTag:v,extendBySeconds:B=150,sequence:Y,fee:M,lastLedgerSequence:N}){if(!P(z))throw new J({errorKey:"core_transaction_invalid_recipient_address"});let F=Z||await b();if(G.chain!==_.Ripple)throw new J({errorKey:"toolbox_ripple_asset_not_supported",info:{asset:G.toString()}});let q=$&&G.isGasAsset?await t(await X(),F):void 0,U5=q?q.amount:$?await n(G,F):await u(G),I={Account:F,Amount:U5,Destination:z,TransactionType:"Payment",...q&&{Fee:q.fee},...v!==void 0&&{DestinationTag:v},...Y!==void 0&&{Sequence:Y},...M!==void 0&&{Fee:M},...N!==void 0&&{LastLedgerSequence:N}};if(W)I.Memos=[{Memo:{MemoData:Buffer.from(W).toString("hex")}}];if(j5({fee:M,lastLedgerSequence:N,sequence:Y,transaction:I}))return I;let K=await(await X()).autofill(I);if(N===void 0&&K.LastLedgerSequence&&B>0)K.LastLedgerSequence+=Math.ceil(B/4);return K}async function O(G){let z=await f();if(!z)throw new J({errorKey:"toolbox_ripple_signer_not_found"});return z.signTransaction(G)}async function H(G){let W=await(await X()).submitAndWait(G),{result:Z}=W;if(Z.validated)return Z.hash;let $=Z.meta?.TransactionResult,v=g($).with(C.tecNO_LINE,()=>"No trust line exists for this token").with(C.tecPATH_DRY,()=>"Payment path could not deliver funds").with(C.tecFROZEN,()=>"Token is frozen").otherwise(()=>{return});throw new J({errorKey:"toolbox_ripple_broadcast_error",info:{chain:_.Ripple,...v?{reason:v}:{txResult:$}}})}let a=async(G)=>{try{let z=await O(G);return H(z.tx_blob)}catch(z){if(z instanceof J)throw z;throw new J({errorKey:"toolbox_ripple_broadcast_error",info:{chain:_.Ripple,error:z}})}};async function s({assetValue:G,memo:z,recipient:W,sweep:Z}){let $=await f();if(!$)throw new J({errorKey:"toolbox_ripple_signer_not_found"});let v=await $.getAddress(),B=await h({assetValue:G,memo:z,recipient:W,sender:v,sweep:Z}),Y=await O(B);return H(Y.tx_blob)}async function r(G){let z=await f();if(!z)throw new J({errorKey:"toolbox_ripple_signer_not_found"});let W=await z.getAddress(),Z=await S({...G,sender:W}),$=await O(Z);return H($.tx_blob)}function e(){let G=j;if(j=null,G)G.then((z)=>{if(z?.isConnected())return z.disconnect();return}).catch((z)=>{console.warn("XRPL Cleanup failed silently:",z)})}return{broadcastTransaction:H,createSigner:o,createTransaction:h,disconnect:e,estimateTransactionFee:T,getAddress:b,getBalance:i,getTrustLines:V,hasTrustLine:l,setTrustLine:S,setTrustLineAndBroadcast:r,signAndBroadcastTransaction:a,signTransaction:O,transfer:s,validateAddress:P}}export{P as validateRippleAddress,c as parseXrplTokenIdentifier,k as normalizeCurrency,X5 as isKnownToken,L as isHexCurrency,Y5 as hexToCurrency,_5 as getXrplTokenInfo,O5 as getRippleToolbox,N5 as getKnownTokensByIssuer,f5 as formatXrplTokenIdentifier,D as currencyToHex,C as XRPL_TOKEN_ERROR_CODES,E as XRPL_KNOWN_TOKENS};
|
|
1
|
+
import{ga as C}from"../../chunk-xbdjxeqd.js";import{AssetValue as R,Chain as N,derivationPathToString as $5,getChainConfig as y,getRPCUrl as W5,resolveDerivationPath as Z5,SwapKitError as Y}from"@swapkit/helpers";import{isValidClassicAddress as f5,isValidXAddress as A}from"ripple-address-codec";import{match as g,P as x}from"ts-pattern";import{SwapKitError as G5}from"@swapkit/helpers";function E(U){return/^[0-9A-Fa-f]{40}$/.test(U)}function D(U){if(E(U))return U.toUpperCase();if(U.length<=3){let f=Buffer.from(U.padEnd(3,"\x00")).toString("hex");return`00${"0".repeat(22)}${f}${"0".repeat(10)}`.toUpperCase()}let z=Buffer.from(U).toString("hex").toUpperCase();if(z.length>40)throw new G5({errorKey:"toolbox_ripple_asset_not_supported",info:{asset:U,reason:"Currency exceeds maximum length (20 bytes)"}});return z.padEnd(40,"0")}function Q5(U){if(!E(U))return U;if(U.toUpperCase().startsWith("00")){let z=U.slice(24,30);try{let f=Buffer.from(z,"hex").toString("ascii").replace(/\0/g,"");if(/^[A-Za-z0-9?!@#$%^&*<>(){}[\]|]+$/.test(f)&&f.length>0)return f}catch{}return U.toUpperCase()}try{let z=U.replace(/0+$/,""),f=z.length%2===0?z:`${z}0`,J=Buffer.from(f,"hex").toString("utf8");if(/^[\x20-\x7E]+$/.test(J))return J}catch{}return U.toUpperCase()}function k(U){if(E(U))return U.toUpperCase();if(U.length<=3)return U;return D(U)}import{RequestClient as m5,warnOnce as z5}from"@swapkit/helpers";var P=[{currency:"USD",decimals:15,domain:"circle.com",issuer:"rcEGREd8NmkKRE8GE424sksyt1tJVFZwu",name:"Circle USDC",verified:!0},{currency:"RLUSD",decimals:15,domain:"ripple.com",issuer:"rMxCKbEDwqr76QuheSUMdEGf4B9xJ8m5De",name:"Ripple USD",verified:!0},{currency:"USD",decimals:15,domain:"bitstamp.net",issuer:"rvYAfWj5gh67oV6fW32ZzP3Aw4Eubs59B",name:"Bitstamp USD",verified:!0},{currency:"BTC",decimals:15,domain:"bitstamp.net",issuer:"rvYAfWj5gh67oV6fW32ZzP3Aw4Eubs59B",name:"Bitstamp BTC",verified:!0},{currency:"EUR",decimals:15,domain:"bitstamp.net",issuer:"rvYAfWj5gh67oV6fW32ZzP3Aw4Eubs59B",name:"Bitstamp EUR",verified:!0},{currency:"USD",decimals:15,domain:"gatehub.net",issuer:"rhub8VRN55s94qWKDv6jmDy1pUykJzF3wq",name:"GateHub USD",verified:!0},{currency:"EUR",decimals:15,domain:"gatehub.net",issuer:"rhub8VRN55s94qWKDv6jmDy1pUykJzF3wq",name:"GateHub EUR",verified:!0},{currency:"BTC",decimals:15,domain:"gatehub.net",issuer:"rchGBxcD1A1C2tdxF6papQYZ8kjRKMYcL",name:"GateHub BTC",verified:!0},{currency:"ETH",decimals:15,domain:"gatehub.net",issuer:"rcA8X3TVMST1n3CJeAdGk1RdRCHii7N2h",name:"GateHub ETH",verified:!0},{currency:"SOLO",decimals:15,domain:"sologenic.com",issuer:"rsoLo2S1kiGeCcn6hCUXVrCpGMWLrRrLZz",name:"Sologenic",verified:!0}];async function b5(U,z){let f=k(U),J=P.find((B)=>k(B.currency)===f&&B.issuer===z);if(J)return J;try{let B=await m5.get(`https://api.xrplmeta.org/token/${U}:${z}`);if(B)return{currency:U,decimals:15,description:B.desc,domain:B.domain,icon:B.icon,issuer:z,name:B.name,verified:B.self_assessment?.is_regulated||B.self_assessment?.is_licensed}}catch(B){z5({condition:!0,id:`xrpl_token_lookup_${U}_${z}`,warning:`Failed to fetch XRPL token info for ${U}:${z}: ${B}`})}return{currency:U,decimals:15,issuer:z,verified:!1}}function D5(U){return P.filter((z)=>z.issuer===U)}function F5(U,z){let f=k(U);return P.some((J)=>k(J.currency)===f&&J.issuer===z)}var j5={ACCOUNT_NOT_FOUND:19};function p(U){if(typeof U!=="object"||U===null||!("data"in U))return!1;let{data:z}=U;return typeof z==="object"&&z!==null&&"error_code"in z&&z.error_code===j5.ACCOUNT_NOT_FOUND}var w={tecFROZEN:"tecFROZEN",tecNO_AUTH:"tecNO_AUTH",tecNO_DST:"tecNO_DST",tecNO_LINE:"tecNO_LINE",tecPATH_DRY:"tecPATH_DRY",tecUNFUNDED_OFFER:"tecUNFUNDED_OFFER"};function c(U){let z=U.match(/^XRP\.([A-Fa-f0-9]{40}|[\x20-\x7E]{1,20})-([a-zA-Z0-9]{25,34})$/);if(!z?.[1]||!z?.[2])return null;if(!K(z[2]))return null;return{currency:z[1],issuer:z[2]}}function J5(U,z){return`${N.Ripple}.${U}-${z}`}async function u(U){if(U.isGasAsset){let{xrpToDrops:f}=await import("xrpl");return f(U.getValue("string"))}let z=c(U.toString());if(!z)throw new Y({errorKey:"toolbox_ripple_asset_not_supported",info:{asset:U.toString()}});return{currency:z.currency,issuer:z.issuer,value:U.getValue("string")}}function Y5({fee:U,lastLedgerSequence:z,sequence:f,transaction:J}){return f!==void 0&&U!==void 0&&z!==void 0&&!A(J.Account)&&!A(J.Destination)}function o(U,z){let f,J=()=>{return f??=import("xrpl").then(({Wallet:B})=>B.fromMnemonic(U,z?{derivationPath:z}:void 0)),f};return{getAddress:async()=>(await J()).address,signTransaction:async(B)=>(await J()).sign(B)}}function K(U){return f5(U)||A(U)}function q5(U={}){let z;async function f(){if(z)return z;return z=await g(U).with({phrase:x.string},({phrase:G,derivationPath:m,index:$=0})=>o(G,$5(Z5({chain:N.Ripple,derivationPath:m,index:$})))).with({signer:x.any},({signer:G})=>G).otherwise(()=>{return}),z}let J;async function B(){let G=await W5(N.Ripple);if(!G)throw new Y({errorKey:"toolbox_ripple_rpc_not_configured",info:{chain:N.Ripple}});let{Client:m}=await import("xrpl"),$=new m(G);return await $.connect(),$}async function b(){if(J){let G=await J.catch(()=>null);if(G?.isConnected())return G}return J=B(),J}async function d(G){let m=await G.request({command:"server_state"}),$=m.result.state.validated_ledger??m.result.state.closed_ledger;if(!$||!Number.isSafeInteger($.reserve_base)||$.reserve_base<0||!Number.isSafeInteger($.reserve_inc)||$.reserve_inc<0)throw new Y({errorKey:"toolbox_ripple_get_balance_error",info:{reason:"XRPL reserve data is unavailable or invalid"}});return{baseReserveDrops:BigInt($.reserve_base),ownerReserveDrops:BigInt($.reserve_inc)}}let F=async()=>{let G=await f();if(!G)throw new Y({errorKey:"toolbox_ripple_signer_not_found"});return G.getAddress()},l=async(G)=>{let m=G||await F(),{baseDecimal:$}=y(N.Ripple),Z=await b();try{let[W,j]=await Promise.all([Z.request({account:m,command:"account_info"}),Z.request({account:m,command:"account_lines"})]),Q=W.result.account_data.Balance,M=[R.from({chain:N.Ripple,fromBaseDecimal:$,value:Q})];for(let _ of j.result.lines){let X=J5(_.currency,_.account);if(Number.parseFloat(_.balance)!==0)M.push(R.from({asset:X,asyncTokenLookup:!1,value:_.balance}))}return M}catch(W){if(p(W))return[R.from({chain:N.Ripple,value:0})];throw new Y({errorKey:"toolbox_ripple_get_balance_error",info:{address:m,error:W}})}},T=async()=>{let{baseDecimal:G}=y(N.Ripple),Z=(await(await b()).request({command:"fee"})).result.drops.open_ledger_fee;return R.from({chain:N.Ripple,fromBaseDecimal:G,value:Z})};async function V(G){let m=G||await F(),$=await b();try{return(await $.request({account:m,command:"account_lines"})).result.lines.map((W)=>({account:W.account,authorized:W.authorized??!1,balance:W.balance,currency:W.currency,freeze:W.freeze??!1,freezePeer:W.freeze_peer??!1,limit:W.limit,limitPeer:W.limit_peer,noRipple:W.no_ripple??!1,noRipplePeer:W.no_ripple_peer??!1,peerAuthorized:W.peer_authorized??!1,qualityIn:W.quality_in??0,qualityOut:W.quality_out??0}))}catch(Z){if(p(Z))return[];throw new Y({errorKey:"toolbox_ripple_get_trust_lines_error",info:{address:m,error:Z}})}}async function i({address:G,currency:m,issuer:$}){let Z=await V(G),W=D(m);return Z.some((j)=>{return D(j.currency)===W&&j.account===$})}async function S({currency:G,issuer:m,limit:$,sender:Z}){let W=Z||await F();if(!K(m))throw new Y({errorKey:"core_transaction_invalid_recipient_address",info:{address:m}});let j=Number.parseFloat($);if(Number.isNaN(j)||j<0)throw new Y({errorKey:"toolbox_ripple_invalid_trust_line_limit",info:{limit:$}});let Q=await b(),M={Account:W,LimitAmount:{currency:G,issuer:m,value:$},TransactionType:"TrustSet"};return Q.autofill(M)}async function n(G,m){let[$,Z,W]=await Promise.all([G.request({account:m,command:"account_info"}),d(G),T()]),{Balance:j,OwnerCount:Q}=$.result.account_data,M=W.getBaseValue("bigint"),_=BigInt(j)-Z.baseReserveDrops-BigInt(Q)*Z.ownerReserveDrops-M;if(_<=0n)throw new Y({errorKey:"toolbox_sweep_amount_too_low",info:{asset:N.Ripple,balance:j,baseReserve:Z.baseReserveDrops.toString(),fee:M.toString(),ownerCount:Q,ownerReserve:Z.ownerReserveDrops.toString()}});let{baseDecimal:X}=y(N.Ripple),v=R.from({chain:N.Ripple,fromBaseDecimal:X,value:_.toString()});return{amount:await u(v),fee:M.toString()}}async function t(G,m){let $=c(G.toString());if(!$)throw new Y({errorKey:"toolbox_ripple_asset_not_supported",info:{asset:G.toString()}});let Z=await b(),W="0",j;while(!0){let Q=await Z.request({account:m,command:"account_lines",peer:$.issuer,...j!==void 0&&{marker:j}}),M=Q.result.lines.find((X)=>X.account===$.issuer&&D(X.currency)===D($.currency));if(M){W=M.balance;break}let _=Q.result.marker;if(_===void 0||_===null)break;j=_}if(!Number.isFinite(Number(W))||Number(W)<=0)throw new Y({errorKey:"toolbox_sweep_amount_too_low",info:{asset:G.toString(),balance:W}});return{currency:$.currency,issuer:$.issuer,value:W}}async function h({assetValue:G,recipient:m,memo:$,sender:Z,sweep:W,destinationTag:j,extendBySeconds:Q=150,sequence:M,fee:_,lastLedgerSequence:X}){if(!K(m))throw new Y({errorKey:"core_transaction_invalid_recipient_address"});let v=Z||await F();if(G.chain!==N.Ripple)throw new Y({errorKey:"toolbox_ripple_asset_not_supported",info:{asset:G.toString()}});let q=W&&G.isGasAsset?await n(await b(),v):void 0,U5=q?q.amount:W?await t(G,v):await u(G),I={Account:v,Amount:U5,Destination:m,TransactionType:"Payment",...q&&{Fee:q.fee},...j!==void 0&&{DestinationTag:j},...M!==void 0&&{Sequence:M},..._!==void 0&&{Fee:_},...X!==void 0&&{LastLedgerSequence:X}};if($)I.Memos=[{Memo:{MemoData:Buffer.from($).toString("hex")}}];if(Y5({fee:_,lastLedgerSequence:X,sequence:M,transaction:I}))return I;let L=await(await b()).autofill(I);if(X===void 0&&L.LastLedgerSequence&&Q>0)L.LastLedgerSequence+=Math.ceil(Q/4);return L}async function O(G){let m=await f();if(!m)throw new Y({errorKey:"toolbox_ripple_signer_not_found"});return m.signTransaction(G)}async function H(G){let $=await(await b()).submitAndWait(G),{result:Z}=$;if(Z.validated)return Z.hash;let W=Z.meta?.TransactionResult,j=g(W).with(w.tecNO_LINE,()=>"No trust line exists for this token").with(w.tecPATH_DRY,()=>"Payment path could not deliver funds").with(w.tecFROZEN,()=>"Token is frozen").otherwise(()=>{return});throw new Y({errorKey:"toolbox_ripple_broadcast_error",info:{chain:N.Ripple,...j?{reason:j}:{txResult:W}}})}let a=async(G)=>{try{let m=await O(G);return H(m.tx_blob)}catch(m){if(m instanceof Y)throw m;throw new Y({errorKey:"toolbox_ripple_broadcast_error",info:{chain:N.Ripple,error:m}})}};async function s({assetValue:G,memo:m,recipient:$,sweep:Z}){let W=await f();if(!W)throw new Y({errorKey:"toolbox_ripple_signer_not_found"});let j=await W.getAddress(),Q=await h({assetValue:G,memo:m,recipient:$,sender:j,sweep:Z}),M=await O(Q);return H(M.tx_blob)}async function r(G){let m=await f();if(!m)throw new Y({errorKey:"toolbox_ripple_signer_not_found"});let $=await m.getAddress(),Z=await S({...G,sender:$}),W=await O(Z);return H(W.tx_blob)}function e(){let G=J;if(J=null,G)G.then((m)=>{if(m?.isConnected())return m.disconnect();return}).catch((m)=>{console.warn("XRPL Cleanup failed silently:",m)})}return{broadcastTransaction:H,createSigner:o,createTransaction:h,disconnect:e,estimateTransactionFee:T,getAddress:F,getBalance:l,getTrustLines:V,hasTrustLine:i,setTrustLine:S,setTrustLineAndBroadcast:r,signAndBroadcastTransaction:a,signTransaction:O,transfer:s,validateAddress:K}}export{K as validateRippleAddress,c as parseXrplTokenIdentifier,k as normalizeCurrency,F5 as isKnownToken,E as isHexCurrency,Q5 as hexToCurrency,b5 as getXrplTokenInfo,q5 as getRippleToolbox,D5 as getKnownTokensByIssuer,J5 as formatXrplTokenIdentifier,D as currencyToHex,w as XRPL_TOKEN_ERROR_CODES,P as XRPL_KNOWN_TOKENS};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{ga as
|
|
1
|
+
import{ga as x}from"../../chunk-xbdjxeqd.js";import{AssetValue as z,Chain as $,derivationPathToString as e,getChainConfig as A,getRPCUrl as d,SKConfig as PP,SwapKitError as M}from"@swapkit/helpers";import{match as jP,P as qP}from"ts-pattern";var GP=/^G[A-Z2-7]{55}$/,JP=/^[A-Za-z0-9]{1,12}$/,c=2,QP=600000,T;async function l(P){if(T&&Date.now()-T.timestamp<QP)return T.value;let Z=(await P.ledgers().order("desc").limit(1).call()).records[0]?.base_reserve_in_stroops;if(Z===void 0)throw new M({errorKey:"toolbox_stellar_balance_error",info:{reason:"base_reserve_unavailable"}});return T={timestamp:Date.now(),value:Z},Z}function S(P){return z.from({chain:$.Stellar,value:P}).getBaseValue("bigint")}function XP(P){let{baseDecimal:J}=A($.Stellar);return z.from({chain:$.Stellar,fromBaseDecimal:J,value:P}).getValue("string")}function i({balance:P,baseReserveInStroops:J,numSponsored:Z,numSponsoring:D,sellingLiabilities:W,subentryCount:N}){let f=S(P),U=S(W),I=c+N+D-Z,R=BigInt(I)*BigInt(J),k=f-R-U;return k>0n?k:0n}function YP({account:P,assetValue:J,baseReserveInStroops:Z,fee:D}){let W=P.balances.find((U)=>U.asset_type==="native"),f=(W?i({balance:W.balance,baseReserveInStroops:Z,numSponsored:P.num_sponsored,numSponsoring:P.num_sponsoring,sellingLiabilities:W.selling_liabilities,subentryCount:P.subentry_count}):0n)-BigInt(D);if(f<=0n)throw new M({errorKey:"toolbox_sweep_amount_too_low",info:{asset:J.toString(),reason:"spendable balance does not cover the transaction fee"}});return f}function ZP({baseReserveInStroops:P,sweepAmountInStroops:J}){if(J===void 0||P===void 0)return;let Z=BigInt(c)*BigInt(P);if(J<Z)throw new M({errorKey:"toolbox_sweep_amount_too_low",info:{amountInStroops:J,minimumStartingBalanceInStroops:Z,reason:"starting balance is below the Stellar account minimum"}})}function $P({account:P,assetCode:J,assetValue:Z,issuer:D,sweep:W}){if(!W)return Z.getValue("string");let N=P.balances.find((f)=>("asset_code"in f)&&f.asset_code===J&&f.asset_issuer===D)?.balance??"0";if(S(N)<=0n)throw new M({errorKey:"toolbox_sweep_amount_too_low",info:{asset:Z.toString(),balance:N,reason:"trust-line balance is not positive"}});return N}function MP(P){if(!P)return;if(new TextEncoder().encode(P).length>28)throw new M("helpers_invalid_memo_type")}function V(P){if(!P||typeof P!=="string"||!P.startsWith("G")||P.length!==56)return!1;return GP.test(P)}function v(P){if(typeof P!=="object"||P===null)return;let J="response"in P?P.response:void 0;return typeof J?.status==="number"?J.status:void 0}function WP(P){return v(P)===504}function FP(P){return P.hash?.().toString("hex")}function LP(P){return[...new Set([P,...PP.get("rpcUrls")[$.Stellar]])].filter(Boolean)}async function o(P){if(!V(P))return!1;try{let{StrKey:J}=await import("@stellar/stellar-sdk");return J.isValidEd25519PublicKey(P)}catch{return!1}}async function u(P){let{address:J,ticker:Z}=P,D=J?await o(J):!1;if(P.chain!==$.Stellar||P.isGasAsset||!JP.test(Z)||!J||!D)throw new M({errorKey:"helpers_invalid_asset_identifier",info:{identifier:P.toString()}});return{assetCode:Z,issuer:J}}function DP(P={}){let J;async function Z({phrase:j,path:q}){let{HDKey:Q}=await import("micro-key-producer/slip10.js"),{mnemonicToSeedSync:G}=await import("@scure/bip39"),{Keypair:X}=await import("@stellar/stellar-sdk"),Y=G(j),L=Q.fromMasterSeed(Y).derive(q,!0);return X.fromRawEd25519Seed(Buffer.from(L.privateKey))}async function D(){if(J)return J;let j=jP(P).with({phrase:qP.string},({phrase:G})=>G).otherwise(()=>{return});if(!j)throw new M("toolbox_stellar_no_signer");if(P.derivationPath&&(P.derivationPath[3]||P.derivationPath[4]))throw new M("toolbox_derivation_slot_unsupported",{chain:$.Stellar,derivationPath:P.derivationPath});let q=P.index??0;if(!P.derivationPath&&(!Number.isInteger(q)||q<0))throw new M("toolbox_derivation_slot_unsupported",{chain:$.Stellar,index:q});let Q=P.derivationPath?e(P.derivationPath.slice(0,3)):`m/44'/148'/${q}'`;return J=await Z({path:Q,phrase:j}),J}async function W(j){let{Horizon:q}=await import("@stellar/stellar-sdk"),Q=j||await d($.Stellar);return new q.Server(Q)}async function N(j,q){for(let Q of q)try{return(await(await W(Q)).transactions().transaction(j).call()).hash||j}catch{}return}async function f(j,q){let Q=await d($.Stellar),G=LP(Q),X=FP(j),Y;for(let F of G)try{let L=await W(F),{hash:_}=await L.submitTransaction(j);return _}catch(L){if(Y=L,!WP(L))break;let _=X?await N(X,G):void 0;if(_)return _}throw new M(q,Y)}async function U(){try{return(await D()).publicKey()}catch(j){if(j instanceof M&&j.errorKey==="toolbox_derivation_slot_unsupported")throw j;return""}}async function I(j){let q=j||await U();if(!q)throw new M("toolbox_stellar_account_not_found");let Q=await W(),[G,X]=await Promise.allSettled([Q.loadAccount(q),l(Q)]);if(G.status==="rejected"){let Y=G.reason;if(v(Y)===404)return[z.from({chain:$.Stellar,value:0})];throw Y}if(X.status==="rejected")throw X.reason;return G.value.balances.map((Y)=>{if(Y.asset_type==="native"){let _=i({balance:Y.balance,baseReserveInStroops:X.value,numSponsored:G.value.num_sponsored,numSponsoring:G.value.num_sponsoring,sellingLiabilities:Y.selling_liabilities,subentryCount:G.value.subentry_count}),{baseDecimal:B}=A($.Stellar);return z.from({chain:$.Stellar,fromBaseDecimal:B,value:_})}let F="asset_code"in Y?Y.asset_code:"",L="asset_issuer"in Y?Y.asset_issuer:"";return z.from({asset:`${$.Stellar}.${F}-${L}`,asyncTokenLookup:!1,value:Y.balance})})}async function R({address:j,assetValue:q}){if(q.chain!==$.Stellar)throw new M({errorKey:"toolbox_stellar_trustline_asset_invalid",info:{asset:q.toString()}});if(q.isGasAsset)return!0;if(!q.address)throw new M({errorKey:"toolbox_stellar_trustline_asset_invalid",info:{asset:q.toString(),reason:"missing issuer"}});let Q=await W(),G;try{G=await Q.loadAccount(j)}catch(X){if(v(X)===404)return!1;throw X}return G.balances.some((X)=>("asset_code"in X)&&X.asset_code===q.ticker&&X.asset_issuer===q.address)}async function k({recipient:j,assetValue:q,memo:Q,sender:G,sweep:X}){if(MP(Q),!await o(j))throw new M("core_transaction_invalid_recipient_address");let F=G||await U();if(!F)throw new M("toolbox_stellar_no_signer");let{Asset:L,Memo:_,Networks:B,Operation:O,TransactionBuilder:h}=await import("@stellar/stellar-sdk"),K=await W(),[H,y,g]=await Promise.all([K.fetchBaseFee(),K.loadAccount(F),X&&q.isGasAsset?l(K):Promise.resolve(void 0)]),w=new h(y,{fee:String(H),networkPassphrase:B.PUBLIC});if(q.isGasAsset){let E=X&&g!==void 0?YP({account:y,assetValue:q,baseReserveInStroops:g,fee:H}):void 0,C=E===void 0?q.getValue("string"):XP(E);try{await K.loadAccount(j),w.addOperation(O.payment({amount:C,asset:L.native(),destination:j}))}catch{ZP({baseReserveInStroops:g,sweepAmountInStroops:E}),w.addOperation(O.createAccount({destination:j,startingBalance:C}))}}else{let{assetCode:E,issuer:C}=await u(q),s=$P({account:y,assetCode:E,assetValue:q,issuer:C,sweep:X});w.addOperation(O.payment({amount:s,asset:new L(E,C),destination:j}))}if(Q)w.addMemo(_.text(Q));return w.setTimeout(30).build()}async function b({assetValue:j,limit:q,sender:Q}){let G=Q||await U();if(!G)throw new M("toolbox_stellar_no_signer");let{Asset:X,Networks:Y,Operation:F,TransactionBuilder:L}=await import("@stellar/stellar-sdk"),{assetCode:_,issuer:B}=await u(j),O=await W(),[h,K]=await Promise.all([O.fetchBaseFee(),O.loadAccount(G)]),H=new X(_,B),y=q!==void 0?F.changeTrust({asset:H,limit:q}):F.changeTrust({asset:H});return new L(K,{fee:String(h),networkPassphrase:Y.PUBLIC}).addOperation(y).setTimeout(30).build()}async function m(j){let{TransactionBuilder:q,Networks:Q}=await import("@stellar/stellar-sdk"),G=await D(),X=q.fromXDR(j.toXDR(),Q.PUBLIC);return X.sign(G),X}function p(j){return f(j,"toolbox_stellar_broadcast_error")}async function n({recipient:j,assetValue:q,memo:Q,sweep:G}){let X=await D(),Y=X.publicKey(),F=await k({assetValue:q,memo:Q,recipient:j,sender:Y,sweep:G});return F.sign(X),f(F,"toolbox_stellar_transaction_failed")}async function t({assetValue:j,limit:q}){let Q=await D(),G=await b({assetValue:j,limit:q,sender:Q.publicKey()});return G.sign(Q),f(G,"toolbox_stellar_transaction_failed")}async function r(j){let q=await m(j);return p(q)}async function a(){let{baseDecimal:j}=A($.Stellar);try{let G=(await(await W()).feeStats()).fee_charged.p50;return z.from({chain:$.Stellar,fromBaseDecimal:j,value:G})}catch{return z.from({chain:$.Stellar,fromBaseDecimal:j,value:"100"})}}return{broadcastTransaction:p,createTransaction:k,createTrustline:t,createTrustlineTransaction:b,estimateTransactionFee:a,getAddress:U,getBalance:I,hasTrustline:R,signAndBroadcastTransaction:r,signTransaction:m,transfer:n,validateAddress:V}}export{V as validateStellarAddress,DP as getStellarToolbox};
|
package/dist/src/sui/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{ga as V}from"../../chunk-xbdjxeqd.js";import{isValidSuiAddress as d}from"@mysten/sui/utils";import{AssetValue as
|
|
1
|
+
import{ga as V}from"../../chunk-xbdjxeqd.js";import{isValidSuiAddress as d}from"@mysten/sui/utils";import{AssetValue as P,Chain as y,derivationPathToString as u,getChainConfig as w,getRPCUrlSync as c,resolveDerivationPath as o,SwapKitError as Y}from"@swapkit/helpers";import{match as r,P as T}from"ts-pattern";var f="0x2::sui::SUI",x=256,i=50000000;async function m(W,b,$,L){let J=[],Q,M=0n;while(!0){let X=await W.getCoins({coinType:$,cursor:Q,owner:b});if(J.push(...X.data),M+=X.data.reduce((U,q)=>U+BigInt(q.balance),0n),!X.hasNextPage||L!==void 0&&M>=L)return J;Q=X.nextCursor}}async function C(W){return BigInt(await W.getReferenceGasPrice())}function E({coinObjectId:W,digest:b,version:$}){return{digest:b,objectId:W,version:$}}function n(W,b,$,L=!1){let J=b.reduce((H,G)=>H+BigInt(G.balance),0n);if(J<$)throw new Y("toolbox_sui_insufficient_balance",{available:J.toString(),required:$.toString()});let{selectedCoins:Q}=b.reduce((H,G)=>{if(H.total>=$)return H;return{selectedCoins:[...H.selectedCoins,G],total:H.total+BigInt(G.balance)}},{selectedCoins:[],total:0n}),M=Q[0],X=W.objectRef(E(M)),U=Q.slice(1).map((H)=>W.objectRef(E(H)));if(U.length>0)W.mergeCoins(X,U);if(L)return X;let[q]=W.splitCoins(X,[$]);return q}function p(W,b){let $=W.reduce((L,J)=>L+BigInt(J.balance),0n);if($<=0n)throw new Y({errorKey:"toolbox_sweep_amount_too_low",info:{asset:b,available:$.toString()}});return $}function g(W){if(W.length>x)throw new Y({errorKey:"toolbox_sui_transaction_creation_error",info:{coinCount:W.length,maxGasPaymentCoins:x,reason:`SUI transactions support at most ${x} gas payment coins`}})}function t(W,b,$,L,J,Q){let M=$.getBaseValue("bigint");if(Q)p(b,$.toString()),g(b);else l(b,M+BigInt(L));if(W.setGasPayment(b.map(E)),Q)W.transferObjects([W.gas],J);else{let[X]=W.splitCoins(W.gas,[$.getBaseValue("string")]);W.transferObjects([X],J)}}function l(W,b){let $=W.reduce((L,J)=>L+BigInt(J.balance),0n);if($<b)throw new Y("toolbox_sui_insufficient_balance",{available:$.toString(),required:b.toString()})}async function a({assetValue:W,gasBudget:b,recipient:$,sender:L,suiClient:J,sweep:Q,tx:M}){let X=W.getBaseValue("bigint"),[U,q]=await Promise.all([C(J),m(J,L,f,Q?void 0:X+BigInt(b))]);if(M.setGasPrice(U),t(M,q,W,b,$,Q),Q){let H=q.reduce((G,_)=>G+BigInt(_.balance),0n);return H<BigInt(b)?H:b}return b}async function s({assetValue:W,gasBudget:b,recipient:$,sender:L,suiClient:J,sweep:Q,tx:M}){let X=W.address;if(!X)throw new Y("toolbox_sui_missing_coin_type");let U=W.getBaseValue("bigint"),[q,H,G]=await Promise.all([C(J),m(J,L,f,BigInt(b)),m(J,L,X,Q?void 0:U)]);if(!G.length&&!Q)throw new Y("toolbox_sui_no_coins_found",{coinType:X});let _=Q?p(G,W.toString()):U;if(l(H,BigInt(b)),Q)g(H);M.setGasPrice(q),M.setGasPayment(H.map(E));let h=n(M,G,_,Q);M.transferObjects([h],$)}function e(W){try{return d(W)}catch{return!1}}function B(W){return"signWithIntent"in W}function $5({provider:W,...b}={}){let $;async function L(){if($)return $;return $=await r(b).with({phrase:T.string},async({phrase:z,derivationPath:Z,index:F=0})=>{let{Ed25519Keypair:D}=await import("@mysten/sui/keypairs/ed25519"),k=o({chain:y.Sui,derivationPath:Z,index:F});if(k.length!==5||k[3]!==0||k[4]!==0)throw new Y("toolbox_derivation_slot_unsupported",{chain:y.Sui,derivationPath:k});let R=u(k,{allHardened:!0});return D.deriveKeypair(z,R)}).with({signer:T.any},({signer:z})=>z).otherwise(()=>{return}),$}async function J(z=W){let{SuiJsonRpcClient:Z}=await import("@mysten/sui/jsonRpc");return new Z({network:"mainnet",url:z||c(y.Sui)})}async function Q(){return(await L())?.toSuiAddress()||""}function M(z){try{let Z=P.from({address:z,chain:y.Sui});return{asset:Z.toString(),decimals:Z.decimal}}catch{}return null}async function X(z){let Z=z||await Q();if(!Z)throw new Y("toolbox_sui_address_required");let{baseDecimal:F,chain:D}=w(y.Sui);try{let R=await(await J()).getAllBalances({owner:Z}),O=R.find(({coinType:j})=>j===f)?.totalBalance||"0",v=[P.from({chain:D,fromBaseDecimal:F,value:O})];for(let{coinType:j,totalBalance:N}of R){if(j===f||Number(N)<=0)continue;let K=M(j);if(K)v.push(P.from({asset:K.asset,fromBaseDecimal:K.decimals,value:N}))}return v}catch{return[P.from({chain:D})]}}async function U(z){let Z=P.from({chain:y.Sui,value:"0.01"});if(!z)return Z;try{let F=await J(),{txBytes:D}=await q(z),{effects:{status:k,gasUsed:R}}=await F.dryRunTransactionBlock({transactionBlock:D});if(k.status!=="success")return Z;let{baseDecimal:O}=w(y.Sui),v=BigInt(R.computationCost)+BigInt(R.storageCost)-BigInt(R.storageRebate);return P.from({chain:y.Sui,fromBaseDecimal:O,value:v.toString()})}catch{return Z}}async function q({recipient:z,assetValue:Z,gasBudget:F,sender:D,sweep:k}){let{Transaction:R}=await import("@mysten/sui/transactions"),O=D||await Q(),v=F||i;if(!O)throw new Y("toolbox_sui_no_sender");try{let j=await J(),N=new R;N.setSender(O);let K={assetValue:Z,gasBudget:v,recipient:z,sender:O,suiClient:j,sweep:k,tx:N},A;if(Z.isGasAsset||Z.symbol==="SUI"){let I=await a(K);if(BigInt(I)<BigInt(v))A=BigInt(I);N.setGasBudget(I)}else await s(K),N.setGasBudget(v);let S=await N.build({client:j});if(A!==void 0){let{effects:{status:I}}=await j.dryRunTransactionBlock({transactionBlock:S});if(I.status!=="success")throw new Y({errorKey:"toolbox_sweep_amount_too_low",info:{asset:Z.toString(),budget:A.toString(),error:I.error}})}return{tx:N,txBytes:S}}catch(j){if(j instanceof Y)throw j;throw new Y("toolbox_sui_transaction_creation_error",{error:j})}}async function H(z){let Z=await L();if(!Z)throw new Y("toolbox_sui_no_signer");if(z instanceof Uint8Array)return Z.signTransaction(z);let{txBytes:F}="tx"in z?z:await q(z);return Z.signTransaction(F)}async function G({assetValue:z,gasBudget:Z,recipient:F,sweep:D}){let k=await L();if(!k)throw new Y("toolbox_sui_no_signer");let R=k.toSuiAddress()||await Q();if(!R)throw new Y("toolbox_sui_no_sender");let{txBytes:O}=await q({assetValue:z,gasBudget:Z,recipient:F,sender:R,sweep:D}),v=await J();if(!B(k)){let N=await k.signTransaction(O),{digest:K}=await v.executeTransactionBlock({signature:N.signature,transactionBlock:N.bytes});return K}let{digest:j}=await v.signAndExecuteTransaction({signer:k,transaction:O});return j}async function _(z){let Z=await J(),{digest:F}=await Z.executeTransactionBlock({signature:z.signature,transactionBlock:z.bytes});return F}async function h(z){let Z=await L();if(!Z)throw new Y("toolbox_sui_no_signer");let F=await J(),D;if(typeof z==="string")D=Uint8Array.from(Buffer.from(z,"base64"));else if(z instanceof Uint8Array)D=z;else D=await z.build({client:F});if(!B(Z)){let R=await Z.signTransaction(D),{digest:O}=await F.executeTransactionBlock({signature:R.signature,transactionBlock:R.bytes});return O}let{digest:k}=await F.signAndExecuteTransaction({signer:Z,transaction:D});return k}return{broadcastTransaction:_,createTransaction:q,estimateTransactionFee:U,getAddress:Q,getBalance:X,signAndBroadcastTransaction:h,signTransaction:H,transfer:G,validateAddress:e}}export{e as validateSuiAddress,$5 as getSuiToolbox};
|
package/dist/src/ton/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{fa as m}from"../../chunk-nvfkjbyq.js";import{ga as
|
|
1
|
+
import{fa as m}from"../../chunk-nvfkjbyq.js";import{ga as x}from"../../chunk-xbdjxeqd.js";import{AssetValue as QQ,Chain as B,getChainConfig as XQ,NetworkDerivationPath as YQ,SKConfig as ZQ,SwapKitError as L,SwapKitNumber as $Q}from"@swapkit/helpers";import{Address as H,beginCell as M,Cell as u,external as zQ,internal as GQ,loadStateInit as HQ,SendMode as V,storeMessage as qQ,toNano as c}from"@ton/core";import{match as w,P as T}from"ts-pattern";var kQ=260734629,LQ=c("0.01"),RQ=c("0.05"),A=V.PAY_GAS_SEPARATELY+V.IGNORE_ERRORS,IQ=V.CARRY_ALL_REMAINING_BALANCE+V.IGNORE_ERRORS,BQ=60000,D,p=0;async function UQ(){let q=Date.now();if(D&&q-p<BQ)return D;let{getHttpEndpoint:F}=await import("@orbs-network/ton-access");return D=await F(),p=q,D}async function xQ(){let[q]=ZQ.get("rpcUrls")[B.Ton]??[];if(q)return q;return await UQ()}function DQ(q={}){let F,_,N;async function I(){if(!F){let{TonClient:Q}=await import("@ton/ton"),X=q.provider??await xQ();F=new Q({endpoint:X})}return F}async function j(){return(await J()).address.toString()}async function y(){if(N)return N;return N=await w(q).with({phrase:T.string},async({phrase:Q,derivationPath:X,index:Y=0})=>{let $=YQ[B.Ton],Z=X?.some((G,k)=>G!==$[k]);if(Y||Z)throw new L("toolbox_derivation_slot_unsupported",{chain:B.Ton,derivationPath:X,index:Y});let{mnemonicToWalletKey:z}=await import("@ton/crypto");return z(Q.split(" "))}).with({signer:T.any},({signer:Q})=>Q).otherwise(()=>{return}),N}async function J(Q){if(!_||Q){let X=await y(),Y=await I(),$=Q||X;if(!$)throw new L("core_wallet_connection_not_found");let{WalletContractV4:Z}=await import("@ton/ton"),z=Z.create({publicKey:$.publicKey,workchain:0});_=Y.open(z)}return _}let g=m(B.Ton);async function i({assetValue:Q,recipient:X,memo:Y,sender:$,sweep:Z,jettonWalletAddress:z}){if(Q.isGasAsset){if(Z){let e=$||await j(),S=await(await I()).getBalance(H.parse(e));if(S<=0n)throw new L("toolbox_sweep_amount_too_low",{asset:Q.toString(),balance:S.toString()})}let t=Y?C(Y).toBoc().toString("base64"):void 0;return[{address:X,amount:Q.getBaseValue("string"),payload:t}]}let G=Q.address;if(!G)throw new L({errorKey:"core_swap_contract_not_found",info:{asset:Q.toString()}});let k=$??await j(),R=z?H.parse(z):await h({jettonMasterAddress:G,ownerAddress:k}),O=R.toString(),v=H.parse(X),U=H.parse(k),K=Z?await r(R):Q.getBaseValue("bigint");if(Z&&K<=0n)throw new L("toolbox_sweep_amount_too_low",{asset:Q.toString(),balance:K.toString()});let a=Y?C(Y):void 0,s=n({destinationAddress:v,forwardPayload:a,jettonAmount:K,responseAddress:U});return[{address:O,amount:RQ.toString(),payload:s.toBoc().toString("base64")}]}async function P({sender:Q,sweep:X,...Y}){let $=X&&Y.assetValue.isGasAsset?IQ:A;return{messages:await i({...Y,sender:Q,sweep:X}),sendMode:$}}function l(Q){if(!Array.isArray(Q))return Q;let[X]=Q;return{messages:Q.map(({sendMode:$,...Z})=>Z),sendMode:X?.sendMode??A}}function b(Q){return Q.map((X)=>{let Y=X.payload?u.fromBase64(X.payload):void 0,$=X.stateInit?HQ(u.fromBase64(X.stateInit).asSlice()):void 0,Z=H.parse(X.address),z=H.isFriendly(X.address)?H.parseFriendly(X.address).isBounceable:!0;return GQ({body:Y,bounce:z,init:$,to:Z,value:BigInt(X.amount)})})}async function E(Q){let X=await y(),Y=await J();if(!Y||!X)throw new L("core_wallet_connection_not_found");let $=await I(),{state:Z}=await $.getContractState(Y.address),z=Z==="active",G=z?await Y.getSeqno():0,{messages:k,sendMode:R}=l(Q),O=Y.createTransfer({messages:b(k),secretKey:X.secretKey,sendMode:R,seqno:G}),v=zQ({body:O,init:z?void 0:Y.init,to:Y.address});return M().store(qQ(v)).endCell()}async function f(Q){return await(await I()).sendFile(Q.toBoc()),Q.hash().toString("hex")}async function W(Q){let X=await E(Q);return f(X)}async function d({assetValue:Q,recipient:X,memo:Y,sweep:$}){let Z=await P({assetValue:Q,memo:Y,recipient:X,sweep:$});return W(Z)}async function o({sender:Q,...X}){let{baseDecimal:Y}=XQ(B.Ton),$=await w(Q).with(T.string,(G)=>{return H.parseFriendly(G).address}).otherwise(async()=>{return(await J()).address});if(!$)throw new L("toolbox_fee_estimation_failed",{chain:B.Ton});let Z=QQ.from({chain:B.Ton,value:"0.01"}),z=await I();try{let G=await P({sender:Q,...X}),k=await y(),R=await J();if(!R||!k)return Z;let O=await R.getSeqno(),v=R.createTransfer({messages:b(G.messages),secretKey:k.secretKey,sendMode:G.sendMode,seqno:O}),{source_fees:U}=await z.estimateExternalMessageFee($,{body:v,ignoreSignature:!0,initCode:null,initData:null}),K=U.in_fwd_fee+U.storage_fee+U.gas_fee+U.fwd_fee;return Z.set($Q.fromBigInt(BigInt(K),Y))}catch{return Z}}async function h({jettonMasterAddress:Q,ownerAddress:X}){try{let Y=await I(),$=H.parse(Q),Z=H.parse(X),{JettonMaster:z}=await import("@ton/ton");return await Y.open(z.create($)).getWalletAddress(Z)}catch{throw new L({errorKey:"core_swap_contract_not_found",info:{jettonMasterAddress:Q,ownerAddress:X}})}}async function r(Q){try{let X=await I(),{JettonWallet:Y}=await import("@ton/ton");return await X.open(Y.create(Q)).getBalance()}catch{throw new L({errorKey:"core_swap_contract_not_found",info:{jettonWalletAddress:Q.toString()}})}}function n({jettonAmount:Q,destinationAddress:X,responseAddress:Y,forwardAmount:$=LQ,forwardPayload:Z}){let z=M().storeUint(kQ,32).storeUint(0,64).storeCoins(Q).storeAddress(X).storeAddress(Y).storeBit(0).storeCoins($);if(Z)z.storeBit(1).storeRef(Z);else z.storeBit(0);return z.endCell()}function C(Q){return M().storeUint(0,32).storeStringTail(Q).endCell()}return{broadcastTransaction:f,createTransaction:P,estimateTransactionFee:o,getAddress:j,getBalance:g,getJettonWalletAddress:h,sign:E,signAndBroadcastTransaction:W,transfer:d,validateAddress:FQ}}function FQ(q){try{return H.parse(q),!0}catch{return!1}}export{FQ as validateTonAddress,DQ as getTONToolbox};
|