@swapkit/helpers 1.0.0-rc.77 → 1.0.0-rc.79
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/dist/index.cjs +1 -1
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.ts +8 -0
- package/dist/index.es.js +60 -52
- package/dist/index.es.js.map +1 -1
- package/package.json +6 -6
- package/src/helpers/__tests__/others.test.ts +27 -0
- package/src/helpers/asset.ts +25 -0
package/dist/index.cjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
"use strict";var Ve=Object.create;var G=Object.defineProperty;var He=Object.getOwnPropertyDescriptor;var xe=Object.getOwnPropertyNames;var ke=Object.getPrototypeOf,We=Object.prototype.hasOwnProperty;var Le=(e,t,n)=>t in e?G(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n;var Ue=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let s of xe(t))!We.call(e,s)&&s!==n&&G(e,s,{get:()=>t[s],enumerable:!(r=He(t,s))||r.enumerable});return e};var qe=(e,t,n)=>(n=e!=null?Ve(ke(e)):{},Ue(t||!e||!e.__esModule?G(n,"default",{value:e,enumerable:!0}):n,e));var p=(e,t,n)=>(Le(e,typeof t!="symbol"?t+"":t,n),n),je=(e,t,n)=>{if(!t.has(e))throw TypeError("Cannot "+n)};var y=(e,t,n)=>{if(t.has(e))throw TypeError("Cannot add the same private member more than once");t instanceof WeakSet?t.add(e):t.set(e,n)};var d=(e,t,n)=>(je(e,t,"access private method"),n);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const a=require("@swapkit/types");var q=(e=>(e.Arbitrum="ARB",e.Avalanche="AVAX",e.Binance="BNB",e.BinanceSmartChain="BSC",e.Bitcoin="BTC",e.BitcoinCash="BCH",e.Cosmos="GAIA",e.Dash="DASH",e.Dogecoin="DOGE",e.Ethereum="ETH",e.Kujira="KUJI",e.Litecoin="LTC",e.Maya="MAYA",e.Optimism="OP",e.Polkadot="DOT",e.Chainflip="FLIP",e.Polygon="MATIC",e.THORChain="THOR",e))(q||{}),ee=(e=>(e.Arbitrum="42161",e.ArbitrumHex="0xa4b1",e.Avalanche="43114",e.AvalancheHex="0xa86a",e.Binance="Binance-Chain-Tigris",e.BinanceSmartChain="56",e.BinanceSmartChainHex="0x38",e.Bitcoin="bitcoin",e.BitcoinCash="bitcoincash",e.Chainflip="chainflip",e.Cosmos="cosmoshub-4",e.Dash="dash",e.Dogecoin="dogecoin",e.Kujira="kaiyo-1",e.Ethereum="1",e.EthereumHex="0x1",e.Litecoin="litecoin",e.Maya="mayachain-mainnet-v1",e.MayaStagenet="mayachain-stagenet-v1",e.Optimism="10",e.OptimismHex="0xa",e.Polkadot="polkadot",e.Polygon="137",e.PolygonHex="0x89",e.THORChain="thorchain-mainnet-v1",e.THORChainStagenet="thorchain-stagenet-v2",e))(ee||{}),me=(e=>(e.Arbitrum="https://arb1.arbitrum.io/rpc",e.Avalanche="https://node-router.thorswap.net/avalanche-c",e.Binance="",e.BinanceSmartChain="https://bsc-dataseed.binance.org",e.Bitcoin="https://node-router.thorswap.net/bitcoin",e.BitcoinCash="https://node-router.thorswap.net/bitcoin-cash",e.Chainflip="wss://mainnet-archive.chainflip.io",e.Cosmos="https://node-router.thorswap.net/cosmos/rpc",e.Dash="https://node-router.thorswap.net/dash",e.Dogecoin="https://node-router.thorswap.net/dogecoin",e.Ethereum="https://node-router.thorswap.net/ethereum",e.Kujira="https://rpc-kujira.synergynodes.com/",e.Litecoin="https://node-router.thorswap.net/litecoin",e.Maya="https://tendermint.mayachain.info",e.MayaStagenet="https://stagenet.tendermint.mayachain.info",e.Optimism="https://mainnet.optimism.io",e.Polkadot="wss://rpc.polkadot.io",e.Polygon="https://polygon-rpc.com",e.THORChain="https://rpc.thorswap.net",e.THORChainStagenet="https://stagenet-rpc.ninerealms.com",e))(me||{}),A=(e=>(e.Cosmos="https://node-router.thorswap.net/cosmos/rest",e.Kujira="https://lcd-kujira.synergynodes.com/",e.MayanodeMainnet="https://mayanode.mayachain.info",e.MayanodeStagenet="https://stagenet.mayanode.mayachain.info",e.ThornodeMainnet="https://thornode.thorswap.net",e.ThornodeStagenet="https://stagenet-thornode.ninerealms.com",e.ThorswapApi="https://api.thorswap.net",e.ThorswapStatic="https://static.thorswap.net",e))(A||{});const j=Object.values(q),Fe=Object.keys(q),te=j.reduce((e,t)=>{const n=Fe.find(r=>q[r]===t);return n&&(e[t]=n),e},{});j.reduce((e,t)=>(e[t]=ee[te[t]],e),{});j.reduce((e,t)=>(e[t]=me[te[t]],e),{});j.reduce((e,t)=>{const n=`${te[t]}Hex`;return e[t]=ee[n],e},{});class ce extends Error{constructor(t,n,r){const s=t.status||t.status===0?t.status:"",i=t.statusText||"",o=`${s} ${i}`.trim(),l=o?`status code ${o}`:"an unknown error";super(`Request failed with ${l}`),Object.defineProperty(this,"response",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"request",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"options",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.name="HTTPError",this.response=t,this.request=n,this.options=r}}class pe extends Error{constructor(t){super("Request timed out"),Object.defineProperty(this,"request",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.name="TimeoutError",this.request=t}}const x=e=>e!==null&&typeof e=="object",V=(...e)=>{for(const t of e)if((!x(t)||Array.isArray(t))&&t!==void 0)throw new TypeError("The `options` argument must be an object");return ne({},...e)},_e=(e={},t={})=>{const n=new globalThis.Headers(e),r=t instanceof globalThis.Headers,s=new globalThis.Headers(t);for(const[i,o]of s.entries())r&&o==="undefined"||o===void 0?n.delete(i):n.set(i,o);return n},ne=(...e)=>{let t={},n={};for(const r of e)if(Array.isArray(r))Array.isArray(t)||(t=[]),t=[...t,...r];else if(x(r)){for(let[s,i]of Object.entries(r))x(i)&&s in t&&(i=ne(t[s],i)),t={...t,[s]:i};x(r.headers)&&(n=_e(n,r.headers),t.headers=n)}return t},Ge=(()=>{let e=!1,t=!1;const n=typeof globalThis.ReadableStream=="function",r=typeof globalThis.Request=="function";return n&&r&&(t=new globalThis.Request("https://empty.invalid",{body:new globalThis.ReadableStream,method:"POST",get duplex(){return e=!0,"half"}}).headers.has("Content-Type")),e&&!t})(),Xe=typeof globalThis.AbortController=="function",Ke=typeof globalThis.ReadableStream=="function",Ye=typeof globalThis.FormData=="function",Te=["get","post","put","patch","head","delete"],Je={json:"application/json",text:"text/*",formData:"multipart/form-data",arrayBuffer:"*/*",blob:"*/*"},X=2147483647,fe=Symbol("stop"),Qe={json:!0,parseJson:!0,searchParams:!0,prefixUrl:!0,retry:!0,timeout:!0,hooks:!0,throwHttpErrors:!0,onDownloadProgress:!0,fetch:!0},ze={method:!0,headers:!0,body:!0,mode:!0,credentials:!0,cache:!0,redirect:!0,referrer:!0,referrerPolicy:!0,integrity:!0,keepalive:!0,signal:!0,window:!0,dispatcher:!0,duplex:!0},Ze=e=>Te.includes(e)?e.toUpperCase():e,et=["get","put","head","delete","options","trace"],tt=[408,413,429,500,502,503,504],ge=[413,429,503],le={limit:2,methods:et,statusCodes:tt,afterStatusCodes:ge,maxRetryAfter:Number.POSITIVE_INFINITY,backoffLimit:Number.POSITIVE_INFINITY,delay:e=>.3*2**(e-1)*1e3},nt=(e={})=>{if(typeof e=="number")return{...le,limit:e};if(e.methods&&!Array.isArray(e.methods))throw new Error("retry.methods must be an array");if(e.statusCodes&&!Array.isArray(e.statusCodes))throw new Error("retry.statusCodes must be an array");return{...le,...e,afterStatusCodes:ge}};async function rt(e,t,n,r){return new Promise((s,i)=>{const o=setTimeout(()=>{n&&n.abort(),i(new pe(e))},r.timeout);r.fetch(e,t).then(s).catch(i).then(()=>{clearTimeout(o)})})}async function st(e,{signal:t}){return new Promise((n,r)=>{t&&(t.throwIfAborted(),t.addEventListener("abort",s,{once:!0}));function s(){clearTimeout(i),r(t.reason)}const i=setTimeout(()=>{t==null||t.removeEventListener("abort",s),n()},e)})}const it=(e,t)=>{const n={};for(const r in t)!(r in ze)&&!(r in Qe)&&!(r in e)&&(n[r]=t[r]);return n};class W{static create(t,n){const r=new W(t,n),s=async()=>{if(typeof r._options.timeout=="number"&&r._options.timeout>X)throw new RangeError(`The \`timeout\` option cannot be greater than ${X}`);await Promise.resolve();let o=await r._fetch();for(const l of r._options.hooks.afterResponse){const c=await l(r.request,r._options,r._decorateResponse(o.clone()));c instanceof globalThis.Response&&(o=c)}if(r._decorateResponse(o),!o.ok&&r._options.throwHttpErrors){let l=new ce(o,r.request,r._options);for(const c of r._options.hooks.beforeError)l=await c(l);throw l}if(r._options.onDownloadProgress){if(typeof r._options.onDownloadProgress!="function")throw new TypeError("The `onDownloadProgress` option must be a function");if(!Ke)throw new Error("Streams are not supported in your environment. `ReadableStream` is missing.");return r._stream(o.clone(),r._options.onDownloadProgress)}return o},i=r._options.retry.methods.includes(r.request.method.toLowerCase())?r._retry(s):s();for(const[o,l]of Object.entries(Je))i[o]=async()=>{r.request.headers.set("accept",r.request.headers.get("accept")||l);const c=(await i).clone();if(o==="json"){if(c.status===204||(await c.clone().arrayBuffer()).byteLength===0)return"";if(n.parseJson)return n.parseJson(await c.text())}return c[o]()};return i}constructor(t,n={}){Object.defineProperty(this,"request",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"abortController",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_retryCount",{enumerable:!0,configurable:!0,writable:!0,value:0}),Object.defineProperty(this,"_input",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_options",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this._input=t;const r="credentials"in Request.prototype;if(this._options={credentials:r?this._input.credentials:void 0,...n,headers:_e(this._input.headers,n.headers),hooks:ne({beforeRequest:[],beforeRetry:[],beforeError:[],afterResponse:[]},n.hooks),method:Ze(n.method??this._input.method),prefixUrl:String(n.prefixUrl||""),retry:nt(n.retry),throwHttpErrors:n.throwHttpErrors!==!1,timeout:n.timeout??1e4,fetch:n.fetch??globalThis.fetch.bind(globalThis)},typeof this._input!="string"&&!(this._input instanceof URL||this._input instanceof globalThis.Request))throw new TypeError("`input` must be a string, URL, or Request");if(this._options.prefixUrl&&typeof this._input=="string"){if(this._input.startsWith("/"))throw new Error("`input` must not begin with a slash when using `prefixUrl`");this._options.prefixUrl.endsWith("/")||(this._options.prefixUrl+="/"),this._input=this._options.prefixUrl+this._input}if(Xe){if(this.abortController=new globalThis.AbortController,this._options.signal){const s=this._options.signal;this._options.signal.addEventListener("abort",()=>{this.abortController.abort(s.reason)})}this._options.signal=this.abortController.signal}if(Ge&&(this._options.duplex="half"),this.request=new globalThis.Request(this._input,this._options),this._options.searchParams){const s="?"+(typeof this._options.searchParams=="string"?this._options.searchParams.replace(/^\?/,""):new URLSearchParams(this._options.searchParams).toString()),i=this.request.url.replace(/(?:\?.*?)?(?=#|$)/,s);(Ye&&this._options.body instanceof globalThis.FormData||this._options.body instanceof URLSearchParams)&&!(this._options.headers&&this._options.headers["content-type"])&&this.request.headers.delete("content-type"),this.request=new globalThis.Request(new globalThis.Request(i,{...this.request}),this._options)}this._options.json!==void 0&&(this._options.body=JSON.stringify(this._options.json),this.request.headers.set("content-type",this._options.headers.get("content-type")??"application/json"),this.request=new globalThis.Request(this.request,{body:this._options.body}))}_calculateRetryDelay(t){if(this._retryCount++,this._retryCount<=this._options.retry.limit&&!(t instanceof pe)){if(t instanceof ce){if(!this._options.retry.statusCodes.includes(t.response.status))return 0;const r=t.response.headers.get("Retry-After");if(r&&this._options.retry.afterStatusCodes.includes(t.response.status)){let s=Number(r);return Number.isNaN(s)?s=Date.parse(r)-Date.now():s*=1e3,this._options.retry.maxRetryAfter!==void 0&&s>this._options.retry.maxRetryAfter?0:s}if(t.response.status===413)return 0}const n=this._options.retry.delay(this._retryCount);return Math.min(this._options.retry.backoffLimit,n)}return 0}_decorateResponse(t){return this._options.parseJson&&(t.json=async()=>this._options.parseJson(await t.text())),t}async _retry(t){try{return await t()}catch(n){const r=Math.min(this._calculateRetryDelay(n),X);if(r!==0&&this._retryCount>0){await st(r,{signal:this._options.signal});for(const s of this._options.hooks.beforeRetry)if(await s({request:this.request,options:this._options,error:n,retryCount:this._retryCount})===fe)return;return this._retry(t)}throw n}}async _fetch(){for(const n of this._options.hooks.beforeRequest){const r=await n(this.request,this._options);if(r instanceof Request){this.request=r;break}if(r instanceof Response)return r}const t=it(this.request,this._options);return this._options.timeout===!1?this._options.fetch(this.request.clone(),t):rt(this.request.clone(),t,this.abortController,this._options)}_stream(t,n){const r=Number(t.headers.get("content-length"))||0;let s=0;return t.status===204?(n&&n({percent:1,totalBytes:r,transferredBytes:s},new Uint8Array),new globalThis.Response(null,{status:t.status,statusText:t.statusText,headers:t.headers})):new globalThis.Response(new globalThis.ReadableStream({async start(i){const o=t.body.getReader();n&&n({percent:0,transferredBytes:0,totalBytes:r},new Uint8Array);async function l(){const{done:c,value:u}=await o.read();if(c){i.close();return}if(n){s+=u.byteLength;const h=r===0?0:s/r;n({percent:h,transferredBytes:s,totalBytes:r},u)}i.enqueue(u),await l()}await l()}}),{status:t.status,statusText:t.statusText,headers:t.headers})}}/*! MIT License © Sindre Sorhus */const J=e=>{const t=(n,r)=>W.create(n,V(e,r));for(const n of Te)t[n]=(r,s)=>W.create(r,V(e,s,{method:n}));return t.create=n=>J(V(n)),t.extend=n=>J(V(e,n)),t.stop=fe,t},Ae=J();let k;const T={CachedPrices:`${A.ThorswapApi}/tokenlist/cached-price`,GasRates:`${A.ThorswapApi}/resource-worker/gasPrice/getAll`,Quote:`${A.ThorswapApi}/aggregator/tokens/quote`,Txn:`${A.ThorswapApi}/apiusage/v2/txn`,TokenlistProviders:`${A.ThorswapApi}/tokenlist/providers`,TokenList:`${A.ThorswapStatic}/token-list`,Thorname:`${A.ThorswapApi}/thorname`},re=typeof window<"u"?{}:{referrer:"https://sk.thorswap.net",referer:"https://sk.thorswap.net"},ue=()=>k||(k=Ae.create({headers:re}),k),at=({apiKey:e,...t})=>{k=Ae.create({...t,headers:{...re,...t.headers,"x-api-key":e}})},_={get:(e,t)=>ue().get(e,t).json(),post:(e,t)=>ue().post(e,t).json()},ot=({tokens:e,...t})=>{const n=new URLSearchParams,r=e.filter((s,i,o)=>o.findIndex(l=>l===s)===i);for(const s of r)n.append("tokens",JSON.stringify(s));return t.metadata&&n.append("metadata","true"),t.lookup&&n.append("lookup","true"),t.sparkline&&n.append("sparkline","true"),_.post(T.CachedPrices,{body:n.toString(),headers:{"Content-Type":"application/x-www-form-urlencoded"}})},ct={getCachedPrices:ot,getQuote:e=>_.get(T.Quote,{searchParams:e}),getGasRates:()=>_.get(T.GasRates),getTxnDetails:e=>_.get(T.Txn,{searchParams:e}),getTokenlistProviders:()=>_.get(T.TokenlistProviders),getTokenList:e=>_.get(`${T.TokenList}/${e}.json`),getThornameAddresses:e=>_.get(`${T.Thorname}/${e}`),getThornameRegisteredChains:e=>_.get(`${T.Thorname}/chains/${e}`),getThornameRlookup:(e,t)=>_.get(`${T.Thorname}/rlookup`,{searchParams:{address:e,chain:t}})};var Ce=(e=>(e.SWAP_TC_TO_TC="SWAP:TC-TC",e.SWAP_ETH_TO_TC="SWAP:ERC20-TC",e.SWAP_TC_TO_ETH="SWAP:TC-ERC20",e.SWAP_ETH_TO_ETH="SWAP:ERC20-ERC20",e.SWAP_AVAX_TO_TC="SWAP:AVAX-TC",e.SWAP_TC_TO_AVAX="SWAP:TC-AVAX",e.SWAP_AVAX_TO_AVAX="SWAP:AVAX-AVAX",e.SWAP_ETH_TO_AVAX="SWAP:ETH-AVAX",e.SWAP_AVAX_TO_ETH="SWAP:AVAX-ETH",e.SWAP_TC_TO_GAIA="SWAP:TC-GAIA",e.SWAP_GAIA_TO_TC="SWAP:GAIA-TC",e.SWAP_TC_TO_BNB="SWAP:TC-BNB",e.SWAP_BNB_TO_TC="SWAP:BNB-TC",e.SWAP_TC_TO_BTC="SWAP:TC-BTC",e.SWAP_BTC_TO_TC="SWAP:BTC-TC",e.SWAP_TC_TO_BCH="SWAP:TC-BCH",e.SWAP_BCH_TO_TC="SWAP:BCH-TC",e.SWAP_TC_TO_LTC="SWAP:TC-LTC",e.SWAP_LTC_TO_TC="SWAP:LTC-TC",e.SWAP_TC_TO_DOGE="SWAP:TC-DOGE",e.SWAP_DOGE_TO_TC="SWAP:DOGE-TC",e.TC_STATUS="TC:STATUS",e.TC_TRANSFER="TC:TRANSFER",e.TC_DEPOSIT="TC:DEPOSIT",e.TC_SEND="TC:SEND",e.TC_SWITCH="TC:SWITCH",e.TC_LP_ADD="TC:ADDLIQUIDITY",e.TC_LP_WITHDRAW="TC:WITHDRAW",e.TC_TNS_CREATE="TC:TNS-CREATE",e.TC_TNS_EXTEND="TC:TNS-EXTEND",e.TC_TNS_UPDATE="TC:TNS-UPDATE",e.TC_SAVINGS_ADD="TC:ADDSAVINGS",e.TC_SAVINGS_WITHDRAW="TC:WITHDRAWSAVINGS",e.TC_LENDING_OPEN="TC:LENDINGOPEN",e.TC_LENDING_CLOSE="TC:LENDINGCLOSE",e.ETH_APPROVAL="ETH:APPROVAL",e.ETH_STATUS="ETH:STATUS",e.ETH_TRANSFER_TO_TC="ETH:TRANSFER:IN",e.ETH_TRANSFER_FROM_TC="ETH:TRANSFER:OUT",e.AVAX_APPROVAL="AVAX:APPROVAL",e.AVAX_STATUS="AVAX:STATUS",e.AVAX_TRANSFER_TO_TC="AVAX:TRANSFER:IN",e.AVAX_TRANSFER_FROM_TC="AVAX:TRANSFER:OUT",e.BSC_APPROVAL="BSC:APPROVAL",e.BSC_STATUS="BSC:STATUS",e.BSC_TRANSFER_TO_TC="BSC:TRANSFER:IN",e.BSC_TRANSFER_FROM_TC="BSC:TRANSFER:OUT",e.APPROVAL="APPROVAL",e.STATUS="STATUS",e.TRANSFER_TO_TC="TRANSFER:IN",e.TRANSFER_FROM_TC="TRANSFER:OUT",e.UNSUPPORTED="UNSUPPORTED",e.TC_LENDING="TC:LENDING",e))(Ce||{}),Se=(e=>(e.PENDING="pending",e.SUCCESS="success",e.CANCELLED="cancelled",e.REFUNDED="refunded",e.REPLACED="replaced",e.ERROR="error",e.UNKNOWN="unknown",e.NOT_STARTED="not_started",e.NOT_FOUND="not_found",e.RETRIES_EXCEEDED="retries_exceeded",e.STREAMING="streaming",e))(Se||{}),be=(e=>(e[e.NOT_STARTED=0]="NOT_STARTED",e[e.SUCCESS=1]="SUCCESS",e[e.REFUNDED=2]="REFUNDED",e))(be||{});const lt="0x313ce567",ye=async({chain:e,to:t})=>{try{const{result:n}=await _.post(a.ChainToRPC[e],{headers:{accept:"*/*","content-type":"application/json","cache-control":"no-cache"},body:JSON.stringify({id:44,jsonrpc:"2.0",method:"eth_call",params:[{to:t.toLowerCase(),data:lt},"latest"]})});return Number.parseInt(BigInt(n).toString())}catch(n){return console.error(n),a.BaseDecimal[e]}},ut=e=>{if(e===a.Chain.Ethereum)return a.BaseDecimal.ETH;const[,t]=e.split("-");return t!=null&&t.startsWith("0x")?ye({chain:a.Chain.Ethereum,to:t}):a.BaseDecimal.ETH},ht=e=>{const[,t]=e.split("-");return t!=null&&t.startsWith("0x")?ye({chain:a.Chain.Avalanche,to:t.toLowerCase()}):a.BaseDecimal.AVAX},dt=e=>(e===a.Chain.BinanceSmartChain,a.BaseDecimal.BSC),we=({chain:e,symbol:t})=>{switch(e){case a.Chain.Ethereum:return ut(t);case a.Chain.Avalanche:return ht(t);case a.Chain.BinanceSmartChain:return dt(t);default:return a.BaseDecimal[e]}},mt={[a.FeeOption.Average]:1.2,[a.FeeOption.Fast]:1.5,[a.FeeOption.Fastest]:2},se=({chain:e,symbol:t})=>{switch(e){case a.Chain.Arbitrum:case a.Chain.Optimism:return t==="ETH";case a.Chain.Maya:return t==="CACAO";case a.Chain.Kujira:return t==="KUJI";case a.Chain.Cosmos:return t==="ATOM";case a.Chain.Polygon:return t==="MATIC";case a.Chain.BinanceSmartChain:return t==="BNB";case a.Chain.THORChain:return t==="RUNE";default:return t===e}},Re=e=>{switch(e){case`${a.Chain.Ethereum}.THOR`:return{identifier:"ETH.THOR-0xa5f2211b9b8170f694421f2046281775e8468044",decimal:18};case`${a.Chain.Ethereum}.vTHOR`:return{identifier:"ETH.vTHOR-0x815c23eca83261b6ec689b60cc4a58b54bc24d8d",decimal:18};case a.Chain.Cosmos:return{identifier:"GAIA.ATOM",decimal:a.BaseDecimal[e]};case a.Chain.THORChain:return{identifier:"THOR.RUNE",decimal:a.BaseDecimal[e]};case a.Chain.BinanceSmartChain:return{identifier:"BSC.BNB",decimal:a.BaseDecimal[e]};case a.Chain.Maya:return{identifier:"MAYA.CACAO",decimal:a.BaseDecimal.MAYA};case`${a.Chain.Maya}.MAYA`:return{identifier:"MAYA.MAYA",decimal:4};case`${a.Chain.Kujira}.USK`:return{identifier:`${a.Chain.Kujira}.USK`,decimal:6};default:return{identifier:`${e}.${e}`,decimal:a.BaseDecimal[e]}}},Ee=({chain:e,symbol:t})=>{if(t.includes("/"))return"Synth";switch(e){case a.Chain.Cosmos:return t==="ATOM"?"Native":a.Chain.Cosmos;case a.Chain.Kujira:return t===a.Chain.Kujira?"Native":a.Chain.Kujira;case a.Chain.Binance:return t===a.Chain.Binance?"Native":"BEP2";case a.Chain.BinanceSmartChain:return t===a.Chain.Binance?"Native":"BEP20";case a.Chain.Ethereum:return t===a.Chain.Ethereum?"Native":"ERC20";case a.Chain.Avalanche:return t===a.Chain.Avalanche?"Native":a.Chain.Avalanche;case a.Chain.Polygon:return t===a.Chain.Polygon?"Native":"POLYGON";case a.Chain.Arbitrum:return[a.Chain.Ethereum,a.Chain.Arbitrum].includes(t)?"Native":"ARBITRUM";case a.Chain.Optimism:return[a.Chain.Ethereum,a.Chain.Optimism].includes(t)?"Native":"OPTIMISM";default:return"Native"}},pt=e=>{var o;const[t,...n]=e.split("."),r=e.includes("/"),s=n.join("."),i=(o=s==null?void 0:s.split("-"))==null?void 0:o[0];return{chain:t,symbol:s,ticker:i,synth:r}},_t=new RegExp(/(.)\1{6}|\.ORG|\.NET|\.FINANCE|\.COM|WWW|HTTP|\\\\|\/\/|[\s$%:[\]]/,"gmi"),Tt=e=>{const[t,n]=e.split(".");if(!a.EVMChains.includes(t))return!0;const[,r]=n.split("-");return se({chain:t,symbol:n})||!!r},ft=e=>e.filter(({chain:t,value:n,symbol:r})=>{const s=`${t}.${r}`;return!_t.test(s)&&Tt(s)&&n!=="0"});function Pe({liquidityUnits:e,poolUnits:t,runeDepth:n}){const r=m(e),s=m(t),i=m(n),o=r.mul(i),l=s.mul(s).mul(2),c=s.mul(r).mul(2),u=r.mul(r),h=s.mul(s).mul(s);return o.mul(l.sub(c).add(u)).div(h)}function Oe({liquidityUnits:e,poolUnits:t,assetDepth:n}){const r=m(e),s=m(t),i=m(n),o=r.mul(i),l=s.mul(s).mul(2),c=s.mul(r).mul(2),u=r.mul(r),h=o.mul(l.sub(c).add(u)),O=s.mul(s).mul(s);return h.div(O)}function gt({percent:e,runeDepth:t,liquidityUnits:n,poolUnits:r}){return Pe({runeDepth:t,liquidityUnits:n,poolUnits:r}).mul(e)}function At({percent:e,assetDepth:t,liquidityUnits:n,poolUnits:r}){return Oe({assetDepth:t,liquidityUnits:n,poolUnits:r}).mul(e)}function m(e){return f.fromBigInt(BigInt(e),a.BaseDecimal.THOR)}function Ne({liquidityUnits:e,poolUnits:t,runeDepth:n,assetDepth:r}){return{assetAmount:m(r).mul(e).div(t),runeAmount:m(n).mul(e).div(t)}}function Ct({liquidityUnits:e,poolUnits:t,runeDepth:n,assetDepth:r,percent:s}){return Object.fromEntries(Object.entries(Ne({liquidityUnits:e,poolUnits:t,runeDepth:n,assetDepth:r})).map(([i,o])=>[i,o.mul(s)]))}function St({runeDepth:e,poolUnits:t,assetDepth:n,liquidityUnits:r,runeAmount:s,assetAmount:i}){const o=new f({value:e,decimal:8}),l=new f({value:n,decimal:8}),c=new f({value:t,decimal:8}),u=new f({value:s,decimal:8}),h=new f({value:i,decimal:8}),O=u.mul(l),ae=h.mul(o),Be=u.mul(h),$e=o.mul(l),Ie=c.mul(O.add(ae.add(Be.mul(2)))),De=O.add(ae.add($e.mul(2))),oe=Ie.div(De),F=m(r).add(oe);if(oe.getBaseValue("number")===0)return F.div(c).getBaseValue("number");const Me=c.add(F);return F.div(Me).getBaseValue("number")}function bt({runeAmount:e,assetAmount:t,runeDepth:n,assetDepth:r}){if(e==="0"||t==="0"||n==="0"||r==="0")return 0;const s=m(n),i=m(r),o=m(t),l=m(e),c=o.mul(s).sub(i.mul(l)),u=i.mul(l).add(s.mul(i));return Math.abs(c.div(u).getBaseValue("number"))}const yt=(e,t)=>{switch(e){case a.MemoType.LEAVE:case a.MemoType.BOND:{const{address:n}=t;return`${e}:${n}`}case a.MemoType.UNBOND:{const{address:n,unbondAmount:r}=t;return`${e}:${n}:${r}`}case a.MemoType.THORNAME_REGISTER:{const{name:n,chain:r,address:s,owner:i}=t;return`${e}:${n}:${r}:${s}${i?`:${i}`:""}`}case a.MemoType.DEPOSIT:{const{chain:n,symbol:r,address:s,singleSide:i}=t;return i?`${e}:${n}/${r}`:`${e}:${((l,c)=>{switch(l){case a.Chain.Litecoin:return"l";case a.Chain.Dogecoin:return"d";case a.Chain.BitcoinCash:return"c";default:return`${l}.${c}`}})(n,r)}:${s||""}`}case a.MemoType.WITHDRAW:{const{chain:n,ticker:r,symbol:s,basisPoints:i,targetAssetString:o,singleSide:l}=t,c=n==="ETH"&&r!=="ETH"?`${r}-${s.slice(-3)}`:s,u=!l&&o?`:${o}`:"";return`${e}:${n}${l?"/":"."}${c}:${i}${u}`}case a.MemoType.OPEN_LOAN:case a.MemoType.CLOSE_LOAN:{const{asset:n,address:r}=t;return`${e}:${n}:${r}`}default:return""}};function wt(e){if(e<0)throw new Error("Invalid number of year");return 10+e}function Rt(e){if(e<0)throw new Error("Invalid number of year");return Math.round((10+e*1.0512)*1e10)/1e10}function Et(e){if(e.length>30)return!1;const t=/^[a-zA-Z0-9+_-]+$/g;return!!e.match(t)}function Pt(e){if(e.length>30)return!1;const t=/^[a-zA-Z0-9+_-]+$/g;return!!e.match(t)}function Ot([e,t,n,r,s]){return`${e}'/${t}'/${n}'/${r}${typeof s!="number"?"":`/${s}`}`}const he=[...Object.values(a.Chain),"TERRA"];function Nt(e=""){const t=e.toUpperCase(),[n]=t.split(".");if(he.includes(n))return!0;const[r]=t.split("/");if(he.includes(r))return!0;throw new Error(`Invalid identifier: ${e}. Expected format: <Chain>.<Ticker> or <Chain>.<Ticker>-<ContractAddress>`)}const $=8,S=e=>10n**BigInt(e),N=e=>Math.log10(Number.parseFloat(e.toString()));function I({value:e,bigIntDecimal:t=$,decimal:n=$}){if(n===0)return e.toString();const r=e<0n;let s=e.toString().substring(r?1:0);const i=n-(s.length-1);i>0&&(s="0".repeat(i)+s);const o=s.length-n;let l=s.slice(-n);return Number.parseInt(l[t])>=5?l=`${l.substring(0,t-1)}${(Number.parseInt(l[t-1])+1).toString()}`:l=l.substring(0,t),`${r?"-":""}${s.slice(0,o)}.${l}`.replace(/\.?0*$/,"")}var b,v,C,w,L,ve,D,Q,M,z;const U=class U{constructor(t){y(this,b);y(this,C);y(this,L);y(this,D);y(this,M);p(this,"decimalMultiplier",10n**8n);p(this,"bigIntValue",0n);p(this,"decimal");const n=Z(t),r=typeof t=="object";this.decimal=r?t.decimal:void 0,this.decimalMultiplier=r&&"decimalMultiplier"in t?t.decimalMultiplier:S(Math.max(de(H(n)),this.decimal||0)),d(this,L,ve).call(this,n)}static fromBigInt(t,n){return new U({decimal:n,value:I({value:t,bigIntDecimal:n,decimal:n})})}static shiftDecimals({value:t,from:n,to:r}){return U.fromBigInt(t.getBaseValue("bigint")*S(r)/S(n),r)}set(t){return new this.constructor({decimal:this.decimal,value:t,identifier:this.toString()})}add(...t){return d(this,b,v).call(this,"add",...t)}sub(...t){return d(this,b,v).call(this,"sub",...t)}mul(...t){return d(this,b,v).call(this,"mul",...t)}div(...t){return d(this,b,v).call(this,"div",...t)}gt(t){return d(this,C,w).call(this,"gt",t)}gte(t){return d(this,C,w).call(this,"gte",t)}lt(t){return d(this,C,w).call(this,"lt",t)}lte(t){return d(this,C,w).call(this,"lte",t)}eqValue(t){return d(this,C,w).call(this,"eqValue",t)}getValue(t){const n=this.formatBigIntToSafeValue(this.bigIntValue,this.decimal||N(this.decimalMultiplier));switch(t){case"number":return Number(n);case"string":return n;case"bigint":return this.bigIntValue*10n**BigInt(this.decimal||8n)/this.decimalMultiplier}}getBaseValue(t){const n=this.decimalMultiplier/S(this.decimal||a.BaseDecimal.THOR),r=this.bigIntValue/n;switch(t){case"number":return Number(r);case"string":return r.toString();case"bigint":return r}}getBigIntValue(t,n){if(!n&&typeof t=="object")return t.bigIntValue;const r=Z(t),s=H(r);return s==="0"||s==="undefined"?0n:d(this,M,z).call(this,s,n)}toSignificant(t=6){const[n,r]=this.getValue("string").split("."),s=n||"",i=r||"";if((Number.parseInt(s)?s.length+i.length:i.length)<=t)return this.getValue("string");if(s.length>=t)return s.slice(0,t).padEnd(s.length,"0");if(Number.parseInt(s))return`${s}.${i.slice(0,t-s.length)}`.padEnd(t-s.length,"0");const l=Number.parseInt(i),c=`${l}`.slice(0,t);return`0.${c.padStart(i.length-`${l}`.length+c.length,"0")}`}toFixed(t=6){const[n,r]=this.getValue("string").split("."),s=n||"",i=r||"";if(Number.parseInt(s))return`${s}.${i.slice(0,t)}`.padEnd(t,"0");const o=Number.parseInt(i),l=`${o}`.slice(0,t);return`0.${l.padStart(i.length-`${o}`.length+l.length,"0")}`}toAbbreviation(t=2){const n=this.getValue("number"),r=["","K","M","B","T","Q","Qi","S"],s=Math.floor(Math.log10(Math.abs(n))/3),i=r[s];if(!i)return this.getValue("string");const o=10**(s*3);return`${(n/o).toFixed(t)}${i}`}toCurrency(t="$",{currencyPosition:n="start",decimal:r=2,decimalSeparator:s=".",thousandSeparator:i=","}={}){const o=this.getValue("number"),[l,c=""]=o.toFixed(6).split("."),u=l.replace(/\B(?=(\d{3})+(?!\d))/g,i),h=l||c?l==="0"?`${Number.parseFloat(`0.${c}`)}`.replace(".",s):`${u}${Number.parseInt(c)?`${s}${c.slice(0,r)}`:""}`:"0.00";return`${n==="start"?t:""}${h}${n==="end"?t:""}`}formatBigIntToSafeValue(t,n){const r=n||this.decimal||$,s=Math.max(r,N(this.decimalMultiplier)),i=t<0n,o=t.toString().substring(i?1:0),l=s-(o.length-1),c=l>0?"0".repeat(l)+o:o,u=c.length-s;let h=c.slice(-s);return Number.parseInt(h[r])>=5?h=`${h.substring(0,r-1)}${(Number.parseInt(h[r-1])+1).toString()}`:h=h.substring(0,r),`${i?"-":""}${c.slice(0,u)}.${h}`.replace(/\.?0*$/,"")}};b=new WeakSet,v=function(t,...n){const r=d(this,D,Q).call(this,this,...n),s=Math.max(r,N(this.decimalMultiplier)),i=S(s),o=n.reduce((c,u)=>{const h=this.getBigIntValue(u,s);switch(t){case"add":return c+h;case"sub":return c-h;case"mul":return c*h/i;case"div":{if(h===0n)throw new RangeError("Division by zero");return c*i/h}default:return c}},this.bigIntValue*i/this.decimalMultiplier),l=I({bigIntDecimal:s,decimal:s,value:o});return new this.constructor({decimalMultiplier:S(s),decimal:this.decimal,value:l,identifier:this.toString()})},C=new WeakSet,w=function(t,...n){const r=d(this,D,Q).call(this,this,...n),s=this.getBigIntValue(n[0],r),i=this.getBigIntValue(this,r);switch(t){case"gt":return i>s;case"gte":return i>=s;case"lt":return i<s;case"lte":return i<=s;case"eqValue":return i===s}},L=new WeakSet,ve=function(t){const n=H(t)||"0";this.bigIntValue=d(this,M,z).call(this,n)},D=new WeakSet,Q=function(...t){const n=t.map(r=>typeof r=="object"?r.decimal||N(r.decimalMultiplier):de(H(r))).filter(Boolean);return Math.max(...n,$)},M=new WeakSet,z=function(t,n){const r=n?S(n):this.decimalMultiplier,s=N(r),[i="",o=""]=t.split(".");return BigInt(`${i}${o.padEnd(s,"0")}`)};let P=U;const vt=Intl.NumberFormat("fullwide",{useGrouping:!1,maximumFractionDigits:20});function H(e){const n=`${typeof e=="number"?vt.format(e):Z(e)}`.replaceAll(",",".").split(".");return n.length>1?`${n.slice(0,-1).join("")}.${n.at(-1)}`:n[0]}function de(e){var n;const t=((n=e.split(".")[1])==null?void 0:n.length)||0;return Math.max(t,$)}function Z(e){return typeof e=="object"?"getValue"in e?e.getValue("string"):e.value:e}class f extends P{eq(t){return this.eqValue(t)}static fromBigInt(t,n){return new f({decimal:n,value:I({value:t,bigIntDecimal:n,decimal:n})})}}const R=new Map;class g extends P{constructor({value:n,decimal:r,tax:s,chain:i,symbol:o,identifier:l}){super(typeof n=="object"?n:{decimal:r,value:n});p(this,"address");p(this,"chain");p(this,"isGasAsset",!1);p(this,"isSynthetic",!1);p(this,"symbol");p(this,"tax");p(this,"ticker");p(this,"type");const c=B(l||`${i}.${o}`);this.type=Ee(c),this.tax=s,this.chain=c.chain,this.ticker=c.ticker,this.symbol=c.symbol,this.address=c.address,this.isSynthetic=c.isSynthetic,this.isGasAsset=c.isGasAsset}toString(){return this.isSynthetic?this.symbol:`${this.chain}.${this.symbol}`}toUrl(){return this.isSynthetic?`${this.chain}.${this.symbol.replace("/",".")}`:this.toString()}eq({chain:n,symbol:r}){return this.chain===n&&this.symbol===r}chainId(){return a.ChainToChainId[this.chain]}static fromUrl(n,r=0){const[s,i,o]=n.split(".");if(!(s&&i))throw new Error("Invalid asset url");const l=s===a.Chain.THORChain&&o?`${s}.${i}/${o}`:n;return K(l,r)}static fromString(n,r=0){return K(n,r)}static fromIdentifier(n,r=0){return K(n,r)}static fromStringSync(n,r=0){const{chain:s,isSynthetic:i}=B(n),o=R.get(n.toUpperCase());if(i)return Y(n,r);const{tax:l,decimal:c,identifier:u}=o||{decimal:a.BaseDecimal[s],identifier:n};return new g({tax:l,value:E(r,c),identifier:i?n:u,decimal:i?8:c})}static async fromStringWithBase(n,r=0,s=a.BaseDecimal.THOR){const i=P.shiftDecimals({value:f.fromBigInt(BigInt(r)),from:0,to:s}).getBaseValue("string");return(await g.fromString(n,r)).set(i)}static fromStringWithBaseSync(n,r=0,s=a.BaseDecimal.THOR){const{chain:i,isSynthetic:o}=B(n),l=R.get(n.toUpperCase());if(o)return Y(n,r);const{tax:c,decimal:u,identifier:h}=l||{decimal:a.BaseDecimal[i],identifier:n};return new g({tax:c,value:E(BigInt(r),s),identifier:h,decimal:u})}static fromIdentifierSync(n,r=0){const{chain:s,isSynthetic:i}=B(n),o=R.get(n);if(i)return Y(n,r);const{tax:l,decimal:c,identifier:u}=o||{decimal:a.BaseDecimal[s],identifier:n};return new g({tax:l,decimal:c,identifier:u,value:E(r,c)})}static fromChainOrSignature(n,r=0){const{decimal:s,identifier:i}=Re(n);return new g({value:E(r,s),decimal:s,identifier:i})}static loadStaticAssets(){return new Promise((n,r)=>{try{import("@swapkit/tokens").then(s=>{for(const i of Object.values(s))for(const{identifier:o,chain:l,...c}of i.tokens)R.set(o.toUpperCase(),{identifier:o,decimal:"decimals"in c?c.decimals:a.BaseDecimal[l]});n({ok:!0})})}catch(s){console.error(s),r({ok:!1,error:s,message:"Couldn't load static assets. Ensure you have installed @swapkit/tokens package"})}})}}function Bt(e){const t=g.fromChainOrSignature(e);switch(e){case a.Chain.Bitcoin:case a.Chain.Litecoin:case a.Chain.BitcoinCash:return t.set(10001e-8);case a.Chain.Dogecoin:return t.set(1.00000001);case a.Chain.Avalanche:case a.Chain.Ethereum:return t.set(1e-8);case a.Chain.THORChain:case a.Chain.Maya:return t.set(0);case a.Chain.Cosmos:return t.set(1e-6);default:return t.set(1e-8)}}async function K(e,t=0){Nt(e);const n=R.get(e.toUpperCase()),r=(n==null?void 0:n.decimal)||await we(B(e));return n||R.set(e.toUpperCase(),{identifier:e,decimal:r}),new g({decimal:r,value:E(t,r),identifier:e})}function Y(e,t=0){const[n,r]=e.split(".")[0].toUpperCase()===a.Chain.THORChain?e.split(".").slice(1).join().split("/"):e.split("/");if(!(n&&r))throw new Error("Invalid asset identifier");return new g({decimal:8,value:E(t,8),identifier:`${a.Chain.THORChain}.${n}/${r}`})}function E(e,t){return typeof e=="bigint"?I({value:e,bigIntDecimal:t,decimal:t}):e}function B(e){const t=e.slice(0,14).includes("/"),[n,r]=e.split(".")[0].toUpperCase()===a.Chain.THORChain?e.split(".").slice(1).join().split("/"):e.split("/");if(t&&!(n&&r))throw new Error("Invalid asset identifier");const s=e.includes(".")&&!t?e:`${a.Chain.THORChain}.${r}`,[i,...o]=s.split("."),[l,c]=(t?r:o.join(".")).split("-"),u=t?r:o.join(".");return{address:c==null?void 0:c.toLowerCase(),chain:i,isGasAsset:se({chain:i,symbol:u}),isSynthetic:t,symbol:(t?`${n}/`:"")+(c?`${l}-${(c==null?void 0:c.toLowerCase())??""}`:u),ticker:l}}const $t={core_wallet_connection_not_found:10001,core_estimated_max_spendable_chain_not_supported:10002,core_extend_error:10003,core_inbound_data_not_found:10004,core_approve_asset_address_or_from_not_found:10005,core_plugin_not_found:10006,core_chain_halted:10099,core_wallet_xdefi_not_installed:10101,core_wallet_evmwallet_not_installed:10102,core_wallet_walletconnect_not_installed:10103,core_wallet_keystore_not_installed:10104,core_wallet_ledger_not_installed:10105,core_wallet_trezor_not_installed:10106,core_wallet_keplr_not_installed:10107,core_wallet_okx_not_installed:10108,core_wallet_keepkey_not_installed:10109,core_swap_invalid_params:10200,core_swap_route_not_complete:10201,core_swap_asset_not_recognized:10202,core_swap_contract_not_found:10203,core_swap_route_transaction_not_found:10204,core_swap_contract_not_supported:10205,core_swap_transaction_error:10206,core_swap_quote_mode_not_supported:10207,core_transaction_deposit_error:10301,core_transaction_create_liquidity_rune_error:10302,core_transaction_create_liquidity_asset_error:10303,core_transaction_create_liquidity_invalid_params:10304,core_transaction_add_liquidity_invalid_params:10305,core_transaction_add_liquidity_no_rune_address:10306,core_transaction_add_liquidity_rune_error:10307,core_transaction_add_liquidity_asset_error:10308,core_transaction_withdraw_error:10309,core_transaction_deposit_to_pool_error:10310,core_transaction_deposit_insufficient_funds_error:10311,core_transaction_deposit_gas_error:10312,core_transaction_invalid_sender_address:10313,core_transaction_deposit_server_error:10314,core_transaction_user_rejected:10315,wallet_ledger_connection_error:20001,wallet_ledger_connection_claimed:20002,wallet_ledger_get_address_error:20003,wallet_ledger_device_not_found:20004,wallet_ledger_device_locked:20005,chainflip_channel_error:30001,chainflip_broker_recipient_error:30002,helpers_number_different_decimals:99101};class ie extends Error{constructor(t,n){n&&console.error(n,{stack:n==null?void 0:n.stack,message:n==null?void 0:n.message}),super(t,{cause:{code:$t[t],message:t}}),Object.setPrototypeOf(this,ie.prototype)}}exports.ApiEndpoints=T;exports.AssetValue=g;exports.BigIntArithmetics=P;exports.RequestClient=_;exports.StreamingSwapProgressStatus=be;exports.SwapKitApi=ct;exports.SwapKitError=ie;exports.SwapKitNumber=f;exports.TransactionType=Ce;exports.TxStatus=Se;exports.assetFromString=pt;exports.defaultRequestHeaders=re;exports.derivationPathToString=Ot;exports.filterAssets=ft;exports.formatBigIntToSafeValue=I;exports.gasFeeMultiplier=mt;exports.getAssetType=Ee;exports.getAsymmetricAssetShare=Oe;exports.getAsymmetricAssetWithdrawAmount=At;exports.getAsymmetricRuneShare=Pe;exports.getAsymmetricRuneWithdrawAmount=gt;exports.getCommonAssetInfo=Re;exports.getDecimal=we;exports.getEstimatedPoolShare=St;exports.getLiquiditySlippage=bt;exports.getMAYANameCost=Rt;exports.getMemoFor=yt;exports.getMinAmountByChain=Bt;exports.getSymmetricPoolShare=Ne;exports.getSymmetricWithdraw=Ct;exports.getTHORNameCost=wt;exports.isGasAsset=se;exports.setRequestClientConfig=at;exports.validateMAYAName=Pt;exports.validateTHORName=Et;
|
|
1
|
+
"use strict";var He=Object.create;var G=Object.defineProperty;var xe=Object.getOwnPropertyDescriptor;var ke=Object.getOwnPropertyNames;var Le=Object.getPrototypeOf,We=Object.prototype.hasOwnProperty;var Ue=(e,t,n)=>t in e?G(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n;var je=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let s of ke(t))!We.call(e,s)&&s!==n&&G(e,s,{get:()=>t[s],enumerable:!(r=xe(t,s))||r.enumerable});return e};var ce=(e,t,n)=>(n=e!=null?He(Le(e)):{},je(t||!e||!e.__esModule?G(n,"default",{value:e,enumerable:!0}):n,e));var p=(e,t,n)=>(Ue(e,typeof t!="symbol"?t+"":t,n),n),qe=(e,t,n)=>{if(!t.has(e))throw TypeError("Cannot "+n)};var y=(e,t,n)=>{if(t.has(e))throw TypeError("Cannot add the same private member more than once");t instanceof WeakSet?t.add(e):t.set(e,n)};var d=(e,t,n)=>(qe(e,t,"access private method"),n);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const a=require("@swapkit/types");var j=(e=>(e.Arbitrum="ARB",e.Avalanche="AVAX",e.Binance="BNB",e.BinanceSmartChain="BSC",e.Bitcoin="BTC",e.BitcoinCash="BCH",e.Cosmos="GAIA",e.Dash="DASH",e.Dogecoin="DOGE",e.Ethereum="ETH",e.Kujira="KUJI",e.Litecoin="LTC",e.Maya="MAYA",e.Optimism="OP",e.Polkadot="DOT",e.Chainflip="FLIP",e.Polygon="MATIC",e.THORChain="THOR",e))(j||{}),ee=(e=>(e.Arbitrum="42161",e.ArbitrumHex="0xa4b1",e.Avalanche="43114",e.AvalancheHex="0xa86a",e.Binance="Binance-Chain-Tigris",e.BinanceSmartChain="56",e.BinanceSmartChainHex="0x38",e.Bitcoin="bitcoin",e.BitcoinCash="bitcoincash",e.Chainflip="chainflip",e.Cosmos="cosmoshub-4",e.Dash="dash",e.Dogecoin="dogecoin",e.Kujira="kaiyo-1",e.Ethereum="1",e.EthereumHex="0x1",e.Litecoin="litecoin",e.Maya="mayachain-mainnet-v1",e.MayaStagenet="mayachain-stagenet-v1",e.Optimism="10",e.OptimismHex="0xa",e.Polkadot="polkadot",e.Polygon="137",e.PolygonHex="0x89",e.THORChain="thorchain-mainnet-v1",e.THORChainStagenet="thorchain-stagenet-v2",e))(ee||{}),pe=(e=>(e.Arbitrum="https://arb1.arbitrum.io/rpc",e.Avalanche="https://node-router.thorswap.net/avalanche-c",e.Binance="",e.BinanceSmartChain="https://bsc-dataseed.binance.org",e.Bitcoin="https://node-router.thorswap.net/bitcoin",e.BitcoinCash="https://node-router.thorswap.net/bitcoin-cash",e.Chainflip="wss://mainnet-archive.chainflip.io",e.Cosmos="https://node-router.thorswap.net/cosmos/rpc",e.Dash="https://node-router.thorswap.net/dash",e.Dogecoin="https://node-router.thorswap.net/dogecoin",e.Ethereum="https://node-router.thorswap.net/ethereum",e.Kujira="https://rpc-kujira.synergynodes.com/",e.Litecoin="https://node-router.thorswap.net/litecoin",e.Maya="https://tendermint.mayachain.info",e.MayaStagenet="https://stagenet.tendermint.mayachain.info",e.Optimism="https://mainnet.optimism.io",e.Polkadot="wss://rpc.polkadot.io",e.Polygon="https://polygon-rpc.com",e.THORChain="https://rpc.thorswap.net",e.THORChainStagenet="https://stagenet-rpc.ninerealms.com",e))(pe||{}),A=(e=>(e.Cosmos="https://node-router.thorswap.net/cosmos/rest",e.Kujira="https://lcd-kujira.synergynodes.com/",e.MayanodeMainnet="https://mayanode.mayachain.info",e.MayanodeStagenet="https://stagenet.mayanode.mayachain.info",e.ThornodeMainnet="https://thornode.thorswap.net",e.ThornodeStagenet="https://stagenet-thornode.ninerealms.com",e.ThorswapApi="https://api.thorswap.net",e.ThorswapStatic="https://static.thorswap.net",e))(A||{});const q=Object.values(j),Fe=Object.keys(j),te=q.reduce((e,t)=>{const n=Fe.find(r=>j[r]===t);return n&&(e[t]=n),e},{});q.reduce((e,t)=>(e[t]=ee[te[t]],e),{});q.reduce((e,t)=>(e[t]=pe[te[t]],e),{});q.reduce((e,t)=>{const n=`${te[t]}Hex`;return e[t]=ee[n],e},{});class le extends Error{constructor(t,n,r){const s=t.status||t.status===0?t.status:"",i=t.statusText||"",o=`${s} ${i}`.trim(),l=o?`status code ${o}`:"an unknown error";super(`Request failed with ${l}`),Object.defineProperty(this,"response",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"request",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"options",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.name="HTTPError",this.response=t,this.request=n,this.options=r}}class _e extends Error{constructor(t){super("Request timed out"),Object.defineProperty(this,"request",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.name="TimeoutError",this.request=t}}const x=e=>e!==null&&typeof e=="object",V=(...e)=>{for(const t of e)if((!x(t)||Array.isArray(t))&&t!==void 0)throw new TypeError("The `options` argument must be an object");return ne({},...e)},fe=(e={},t={})=>{const n=new globalThis.Headers(e),r=t instanceof globalThis.Headers,s=new globalThis.Headers(t);for(const[i,o]of s.entries())r&&o==="undefined"||o===void 0?n.delete(i):n.set(i,o);return n},ne=(...e)=>{let t={},n={};for(const r of e)if(Array.isArray(r))Array.isArray(t)||(t=[]),t=[...t,...r];else if(x(r)){for(let[s,i]of Object.entries(r))x(i)&&s in t&&(i=ne(t[s],i)),t={...t,[s]:i};x(r.headers)&&(n=fe(n,r.headers),t.headers=n)}return t},Ge=(()=>{let e=!1,t=!1;const n=typeof globalThis.ReadableStream=="function",r=typeof globalThis.Request=="function";return n&&r&&(t=new globalThis.Request("https://empty.invalid",{body:new globalThis.ReadableStream,method:"POST",get duplex(){return e=!0,"half"}}).headers.has("Content-Type")),e&&!t})(),Xe=typeof globalThis.AbortController=="function",Ke=typeof globalThis.ReadableStream=="function",Ye=typeof globalThis.FormData=="function",Te=["get","post","put","patch","head","delete"],Je={json:"application/json",text:"text/*",formData:"multipart/form-data",arrayBuffer:"*/*",blob:"*/*"},X=2147483647,ge=Symbol("stop"),Qe={json:!0,parseJson:!0,searchParams:!0,prefixUrl:!0,retry:!0,timeout:!0,hooks:!0,throwHttpErrors:!0,onDownloadProgress:!0,fetch:!0},ze={method:!0,headers:!0,body:!0,mode:!0,credentials:!0,cache:!0,redirect:!0,referrer:!0,referrerPolicy:!0,integrity:!0,keepalive:!0,signal:!0,window:!0,dispatcher:!0,duplex:!0},Ze=e=>Te.includes(e)?e.toUpperCase():e,et=["get","put","head","delete","options","trace"],tt=[408,413,429,500,502,503,504],Ae=[413,429,503],ue={limit:2,methods:et,statusCodes:tt,afterStatusCodes:Ae,maxRetryAfter:Number.POSITIVE_INFINITY,backoffLimit:Number.POSITIVE_INFINITY,delay:e=>.3*2**(e-1)*1e3},nt=(e={})=>{if(typeof e=="number")return{...ue,limit:e};if(e.methods&&!Array.isArray(e.methods))throw new Error("retry.methods must be an array");if(e.statusCodes&&!Array.isArray(e.statusCodes))throw new Error("retry.statusCodes must be an array");return{...ue,...e,afterStatusCodes:Ae}};async function rt(e,t,n,r){return new Promise((s,i)=>{const o=setTimeout(()=>{n&&n.abort(),i(new _e(e))},r.timeout);r.fetch(e,t).then(s).catch(i).then(()=>{clearTimeout(o)})})}async function st(e,{signal:t}){return new Promise((n,r)=>{t&&(t.throwIfAborted(),t.addEventListener("abort",s,{once:!0}));function s(){clearTimeout(i),r(t.reason)}const i=setTimeout(()=>{t==null||t.removeEventListener("abort",s),n()},e)})}const it=(e,t)=>{const n={};for(const r in t)!(r in ze)&&!(r in Qe)&&!(r in e)&&(n[r]=t[r]);return n};class L{static create(t,n){const r=new L(t,n),s=async()=>{if(typeof r._options.timeout=="number"&&r._options.timeout>X)throw new RangeError(`The \`timeout\` option cannot be greater than ${X}`);await Promise.resolve();let o=await r._fetch();for(const l of r._options.hooks.afterResponse){const c=await l(r.request,r._options,r._decorateResponse(o.clone()));c instanceof globalThis.Response&&(o=c)}if(r._decorateResponse(o),!o.ok&&r._options.throwHttpErrors){let l=new le(o,r.request,r._options);for(const c of r._options.hooks.beforeError)l=await c(l);throw l}if(r._options.onDownloadProgress){if(typeof r._options.onDownloadProgress!="function")throw new TypeError("The `onDownloadProgress` option must be a function");if(!Ke)throw new Error("Streams are not supported in your environment. `ReadableStream` is missing.");return r._stream(o.clone(),r._options.onDownloadProgress)}return o},i=r._options.retry.methods.includes(r.request.method.toLowerCase())?r._retry(s):s();for(const[o,l]of Object.entries(Je))i[o]=async()=>{r.request.headers.set("accept",r.request.headers.get("accept")||l);const c=(await i).clone();if(o==="json"){if(c.status===204||(await c.clone().arrayBuffer()).byteLength===0)return"";if(n.parseJson)return n.parseJson(await c.text())}return c[o]()};return i}constructor(t,n={}){Object.defineProperty(this,"request",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"abortController",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_retryCount",{enumerable:!0,configurable:!0,writable:!0,value:0}),Object.defineProperty(this,"_input",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_options",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this._input=t;const r="credentials"in Request.prototype;if(this._options={credentials:r?this._input.credentials:void 0,...n,headers:fe(this._input.headers,n.headers),hooks:ne({beforeRequest:[],beforeRetry:[],beforeError:[],afterResponse:[]},n.hooks),method:Ze(n.method??this._input.method),prefixUrl:String(n.prefixUrl||""),retry:nt(n.retry),throwHttpErrors:n.throwHttpErrors!==!1,timeout:n.timeout??1e4,fetch:n.fetch??globalThis.fetch.bind(globalThis)},typeof this._input!="string"&&!(this._input instanceof URL||this._input instanceof globalThis.Request))throw new TypeError("`input` must be a string, URL, or Request");if(this._options.prefixUrl&&typeof this._input=="string"){if(this._input.startsWith("/"))throw new Error("`input` must not begin with a slash when using `prefixUrl`");this._options.prefixUrl.endsWith("/")||(this._options.prefixUrl+="/"),this._input=this._options.prefixUrl+this._input}if(Xe){if(this.abortController=new globalThis.AbortController,this._options.signal){const s=this._options.signal;this._options.signal.addEventListener("abort",()=>{this.abortController.abort(s.reason)})}this._options.signal=this.abortController.signal}if(Ge&&(this._options.duplex="half"),this.request=new globalThis.Request(this._input,this._options),this._options.searchParams){const s="?"+(typeof this._options.searchParams=="string"?this._options.searchParams.replace(/^\?/,""):new URLSearchParams(this._options.searchParams).toString()),i=this.request.url.replace(/(?:\?.*?)?(?=#|$)/,s);(Ye&&this._options.body instanceof globalThis.FormData||this._options.body instanceof URLSearchParams)&&!(this._options.headers&&this._options.headers["content-type"])&&this.request.headers.delete("content-type"),this.request=new globalThis.Request(new globalThis.Request(i,{...this.request}),this._options)}this._options.json!==void 0&&(this._options.body=JSON.stringify(this._options.json),this.request.headers.set("content-type",this._options.headers.get("content-type")??"application/json"),this.request=new globalThis.Request(this.request,{body:this._options.body}))}_calculateRetryDelay(t){if(this._retryCount++,this._retryCount<=this._options.retry.limit&&!(t instanceof _e)){if(t instanceof le){if(!this._options.retry.statusCodes.includes(t.response.status))return 0;const r=t.response.headers.get("Retry-After");if(r&&this._options.retry.afterStatusCodes.includes(t.response.status)){let s=Number(r);return Number.isNaN(s)?s=Date.parse(r)-Date.now():s*=1e3,this._options.retry.maxRetryAfter!==void 0&&s>this._options.retry.maxRetryAfter?0:s}if(t.response.status===413)return 0}const n=this._options.retry.delay(this._retryCount);return Math.min(this._options.retry.backoffLimit,n)}return 0}_decorateResponse(t){return this._options.parseJson&&(t.json=async()=>this._options.parseJson(await t.text())),t}async _retry(t){try{return await t()}catch(n){const r=Math.min(this._calculateRetryDelay(n),X);if(r!==0&&this._retryCount>0){await st(r,{signal:this._options.signal});for(const s of this._options.hooks.beforeRetry)if(await s({request:this.request,options:this._options,error:n,retryCount:this._retryCount})===ge)return;return this._retry(t)}throw n}}async _fetch(){for(const n of this._options.hooks.beforeRequest){const r=await n(this.request,this._options);if(r instanceof Request){this.request=r;break}if(r instanceof Response)return r}const t=it(this.request,this._options);return this._options.timeout===!1?this._options.fetch(this.request.clone(),t):rt(this.request.clone(),t,this.abortController,this._options)}_stream(t,n){const r=Number(t.headers.get("content-length"))||0;let s=0;return t.status===204?(n&&n({percent:1,totalBytes:r,transferredBytes:s},new Uint8Array),new globalThis.Response(null,{status:t.status,statusText:t.statusText,headers:t.headers})):new globalThis.Response(new globalThis.ReadableStream({async start(i){const o=t.body.getReader();n&&n({percent:0,transferredBytes:0,totalBytes:r},new Uint8Array);async function l(){const{done:c,value:u}=await o.read();if(c){i.close();return}if(n){s+=u.byteLength;const h=r===0?0:s/r;n({percent:h,transferredBytes:s,totalBytes:r},u)}i.enqueue(u),await l()}await l()}}),{status:t.status,statusText:t.statusText,headers:t.headers})}}/*! MIT License © Sindre Sorhus */const J=e=>{const t=(n,r)=>L.create(n,V(e,r));for(const n of Te)t[n]=(r,s)=>L.create(r,V(e,s,{method:n}));return t.create=n=>J(V(n)),t.extend=n=>J(V(e,n)),t.stop=ge,t},Ce=J();let k;const f={CachedPrices:`${A.ThorswapApi}/tokenlist/cached-price`,GasRates:`${A.ThorswapApi}/resource-worker/gasPrice/getAll`,Quote:`${A.ThorswapApi}/aggregator/tokens/quote`,Txn:`${A.ThorswapApi}/apiusage/v2/txn`,TokenlistProviders:`${A.ThorswapApi}/tokenlist/providers`,TokenList:`${A.ThorswapStatic}/token-list`,Thorname:`${A.ThorswapApi}/thorname`},re=typeof window<"u"?{}:{referrer:"https://sk.thorswap.net",referer:"https://sk.thorswap.net"},he=()=>k||(k=Ce.create({headers:re}),k),at=({apiKey:e,...t})=>{k=Ce.create({...t,headers:{...re,...t.headers,"x-api-key":e}})},_={get:(e,t)=>he().get(e,t).json(),post:(e,t)=>he().post(e,t).json()},ot=({tokens:e,...t})=>{const n=new URLSearchParams,r=e.filter((s,i,o)=>o.findIndex(l=>l===s)===i);for(const s of r)n.append("tokens",JSON.stringify(s));return t.metadata&&n.append("metadata","true"),t.lookup&&n.append("lookup","true"),t.sparkline&&n.append("sparkline","true"),_.post(f.CachedPrices,{body:n.toString(),headers:{"Content-Type":"application/x-www-form-urlencoded"}})},ct={getCachedPrices:ot,getQuote:e=>_.get(f.Quote,{searchParams:e}),getGasRates:()=>_.get(f.GasRates),getTxnDetails:e=>_.get(f.Txn,{searchParams:e}),getTokenlistProviders:()=>_.get(f.TokenlistProviders),getTokenList:e=>_.get(`${f.TokenList}/${e}.json`),getThornameAddresses:e=>_.get(`${f.Thorname}/${e}`),getThornameRegisteredChains:e=>_.get(`${f.Thorname}/chains/${e}`),getThornameRlookup:(e,t)=>_.get(`${f.Thorname}/rlookup`,{searchParams:{address:e,chain:t}})};var Se=(e=>(e.SWAP_TC_TO_TC="SWAP:TC-TC",e.SWAP_ETH_TO_TC="SWAP:ERC20-TC",e.SWAP_TC_TO_ETH="SWAP:TC-ERC20",e.SWAP_ETH_TO_ETH="SWAP:ERC20-ERC20",e.SWAP_AVAX_TO_TC="SWAP:AVAX-TC",e.SWAP_TC_TO_AVAX="SWAP:TC-AVAX",e.SWAP_AVAX_TO_AVAX="SWAP:AVAX-AVAX",e.SWAP_ETH_TO_AVAX="SWAP:ETH-AVAX",e.SWAP_AVAX_TO_ETH="SWAP:AVAX-ETH",e.SWAP_TC_TO_GAIA="SWAP:TC-GAIA",e.SWAP_GAIA_TO_TC="SWAP:GAIA-TC",e.SWAP_TC_TO_BNB="SWAP:TC-BNB",e.SWAP_BNB_TO_TC="SWAP:BNB-TC",e.SWAP_TC_TO_BTC="SWAP:TC-BTC",e.SWAP_BTC_TO_TC="SWAP:BTC-TC",e.SWAP_TC_TO_BCH="SWAP:TC-BCH",e.SWAP_BCH_TO_TC="SWAP:BCH-TC",e.SWAP_TC_TO_LTC="SWAP:TC-LTC",e.SWAP_LTC_TO_TC="SWAP:LTC-TC",e.SWAP_TC_TO_DOGE="SWAP:TC-DOGE",e.SWAP_DOGE_TO_TC="SWAP:DOGE-TC",e.TC_STATUS="TC:STATUS",e.TC_TRANSFER="TC:TRANSFER",e.TC_DEPOSIT="TC:DEPOSIT",e.TC_SEND="TC:SEND",e.TC_SWITCH="TC:SWITCH",e.TC_LP_ADD="TC:ADDLIQUIDITY",e.TC_LP_WITHDRAW="TC:WITHDRAW",e.TC_TNS_CREATE="TC:TNS-CREATE",e.TC_TNS_EXTEND="TC:TNS-EXTEND",e.TC_TNS_UPDATE="TC:TNS-UPDATE",e.TC_SAVINGS_ADD="TC:ADDSAVINGS",e.TC_SAVINGS_WITHDRAW="TC:WITHDRAWSAVINGS",e.TC_LENDING_OPEN="TC:LENDINGOPEN",e.TC_LENDING_CLOSE="TC:LENDINGCLOSE",e.ETH_APPROVAL="ETH:APPROVAL",e.ETH_STATUS="ETH:STATUS",e.ETH_TRANSFER_TO_TC="ETH:TRANSFER:IN",e.ETH_TRANSFER_FROM_TC="ETH:TRANSFER:OUT",e.AVAX_APPROVAL="AVAX:APPROVAL",e.AVAX_STATUS="AVAX:STATUS",e.AVAX_TRANSFER_TO_TC="AVAX:TRANSFER:IN",e.AVAX_TRANSFER_FROM_TC="AVAX:TRANSFER:OUT",e.BSC_APPROVAL="BSC:APPROVAL",e.BSC_STATUS="BSC:STATUS",e.BSC_TRANSFER_TO_TC="BSC:TRANSFER:IN",e.BSC_TRANSFER_FROM_TC="BSC:TRANSFER:OUT",e.APPROVAL="APPROVAL",e.STATUS="STATUS",e.TRANSFER_TO_TC="TRANSFER:IN",e.TRANSFER_FROM_TC="TRANSFER:OUT",e.UNSUPPORTED="UNSUPPORTED",e.TC_LENDING="TC:LENDING",e))(Se||{}),be=(e=>(e.PENDING="pending",e.SUCCESS="success",e.CANCELLED="cancelled",e.REFUNDED="refunded",e.REPLACED="replaced",e.ERROR="error",e.UNKNOWN="unknown",e.NOT_STARTED="not_started",e.NOT_FOUND="not_found",e.RETRIES_EXCEEDED="retries_exceeded",e.STREAMING="streaming",e))(be||{}),ye=(e=>(e[e.NOT_STARTED=0]="NOT_STARTED",e[e.SUCCESS=1]="SUCCESS",e[e.REFUNDED=2]="REFUNDED",e))(ye||{});const lt="0x313ce567",we=async({chain:e,to:t})=>{try{const{result:n}=await _.post(a.ChainToRPC[e],{headers:{accept:"*/*","content-type":"application/json","cache-control":"no-cache"},body:JSON.stringify({id:44,jsonrpc:"2.0",method:"eth_call",params:[{to:t.toLowerCase(),data:lt},"latest"]})});return Number.parseInt(BigInt(n).toString())}catch(n){return console.error(n),a.BaseDecimal[e]}},ut=e=>{if(e===a.Chain.Ethereum)return a.BaseDecimal.ETH;const[,t]=e.split("-");return t!=null&&t.startsWith("0x")?we({chain:a.Chain.Ethereum,to:t}):a.BaseDecimal.ETH},ht=e=>{const[,t]=e.split("-");return t!=null&&t.startsWith("0x")?we({chain:a.Chain.Avalanche,to:t.toLowerCase()}):a.BaseDecimal.AVAX},dt=e=>(e===a.Chain.BinanceSmartChain,a.BaseDecimal.BSC),Re=({chain:e,symbol:t})=>{switch(e){case a.Chain.Ethereum:return ut(t);case a.Chain.Avalanche:return ht(t);case a.Chain.BinanceSmartChain:return dt(t);default:return a.BaseDecimal[e]}},mt={[a.FeeOption.Average]:1.2,[a.FeeOption.Fast]:1.5,[a.FeeOption.Fastest]:2},se=({chain:e,symbol:t})=>{switch(e){case a.Chain.Arbitrum:case a.Chain.Optimism:return t==="ETH";case a.Chain.Maya:return t==="CACAO";case a.Chain.Kujira:return t==="KUJI";case a.Chain.Cosmos:return t==="ATOM";case a.Chain.Polygon:return t==="MATIC";case a.Chain.BinanceSmartChain:return t==="BNB";case a.Chain.THORChain:return t==="RUNE";default:return t===e}},Ee=e=>{switch(e){case`${a.Chain.Ethereum}.THOR`:return{identifier:"ETH.THOR-0xa5f2211b9b8170f694421f2046281775e8468044",decimal:18};case`${a.Chain.Ethereum}.vTHOR`:return{identifier:"ETH.vTHOR-0x815c23eca83261b6ec689b60cc4a58b54bc24d8d",decimal:18};case a.Chain.Cosmos:return{identifier:"GAIA.ATOM",decimal:a.BaseDecimal[e]};case a.Chain.THORChain:return{identifier:"THOR.RUNE",decimal:a.BaseDecimal[e]};case a.Chain.BinanceSmartChain:return{identifier:"BSC.BNB",decimal:a.BaseDecimal[e]};case a.Chain.Maya:return{identifier:"MAYA.CACAO",decimal:a.BaseDecimal.MAYA};case`${a.Chain.Maya}.MAYA`:return{identifier:"MAYA.MAYA",decimal:4};case`${a.Chain.Kujira}.USK`:return{identifier:`${a.Chain.Kujira}.USK`,decimal:6};default:return{identifier:`${e}.${e}`,decimal:a.BaseDecimal[e]}}},Pe=({chain:e,symbol:t})=>{if(t.includes("/"))return"Synth";switch(e){case a.Chain.Cosmos:return t==="ATOM"?"Native":a.Chain.Cosmos;case a.Chain.Kujira:return t===a.Chain.Kujira?"Native":a.Chain.Kujira;case a.Chain.Binance:return t===a.Chain.Binance?"Native":"BEP2";case a.Chain.BinanceSmartChain:return t===a.Chain.Binance?"Native":"BEP20";case a.Chain.Ethereum:return t===a.Chain.Ethereum?"Native":"ERC20";case a.Chain.Avalanche:return t===a.Chain.Avalanche?"Native":a.Chain.Avalanche;case a.Chain.Polygon:return t===a.Chain.Polygon?"Native":"POLYGON";case a.Chain.Arbitrum:return[a.Chain.Ethereum,a.Chain.Arbitrum].includes(t)?"Native":"ARBITRUM";case a.Chain.Optimism:return[a.Chain.Ethereum,a.Chain.Optimism].includes(t)?"Native":"OPTIMISM";default:return"Native"}},pt=e=>{var o;const[t,...n]=e.split("."),r=e.includes("/"),s=n.join("."),i=(o=s==null?void 0:s.split("-"))==null?void 0:o[0];return{chain:t,symbol:s,ticker:i,synth:r}},_t=new RegExp(/(.)\1{6}|\.ORG|\.NET|\.FINANCE|\.COM|WWW|HTTP|\\\\|\/\/|[\s$%:[\]]/,"gmi"),ft=e=>{const[t,n]=e.split(".");if(!a.EVMChains.includes(t))return!0;const[,r]=n.split("-");return se({chain:t,symbol:n})||!!r},Tt=e=>e.filter(({chain:t,value:n,symbol:r})=>{const s=`${t}.${r}`;return!_t.test(s)&&ft(s)&&n!=="0"});async function gt(e){const t=await import("@swapkit/tokens");for(const n of Object.values(t))for(const{identifier:r,chain:s,...i}of n.tokens)if("identifier"in e&&r===e.identifier||"address"in i&&"chain"in e&&s===e.chain&&i.address.toLowerCase()===e.contract.toLowerCase())return r}function Oe({liquidityUnits:e,poolUnits:t,runeDepth:n}){const r=m(e),s=m(t),i=m(n),o=r.mul(i),l=s.mul(s).mul(2),c=s.mul(r).mul(2),u=r.mul(r),h=s.mul(s).mul(s);return o.mul(l.sub(c).add(u)).div(h)}function Ne({liquidityUnits:e,poolUnits:t,assetDepth:n}){const r=m(e),s=m(t),i=m(n),o=r.mul(i),l=s.mul(s).mul(2),c=s.mul(r).mul(2),u=r.mul(r),h=o.mul(l.sub(c).add(u)),O=s.mul(s).mul(s);return h.div(O)}function At({percent:e,runeDepth:t,liquidityUnits:n,poolUnits:r}){return Oe({runeDepth:t,liquidityUnits:n,poolUnits:r}).mul(e)}function Ct({percent:e,assetDepth:t,liquidityUnits:n,poolUnits:r}){return Ne({assetDepth:t,liquidityUnits:n,poolUnits:r}).mul(e)}function m(e){return T.fromBigInt(BigInt(e),a.BaseDecimal.THOR)}function Be({liquidityUnits:e,poolUnits:t,runeDepth:n,assetDepth:r}){return{assetAmount:m(r).mul(e).div(t),runeAmount:m(n).mul(e).div(t)}}function St({liquidityUnits:e,poolUnits:t,runeDepth:n,assetDepth:r,percent:s}){return Object.fromEntries(Object.entries(Be({liquidityUnits:e,poolUnits:t,runeDepth:n,assetDepth:r})).map(([i,o])=>[i,o.mul(s)]))}function bt({runeDepth:e,poolUnits:t,assetDepth:n,liquidityUnits:r,runeAmount:s,assetAmount:i}){const o=new T({value:e,decimal:8}),l=new T({value:n,decimal:8}),c=new T({value:t,decimal:8}),u=new T({value:s,decimal:8}),h=new T({value:i,decimal:8}),O=u.mul(l),ae=h.mul(o),$e=u.mul(h),Ie=o.mul(l),De=c.mul(O.add(ae.add($e.mul(2)))),Me=O.add(ae.add(Ie.mul(2))),oe=De.div(Me),F=m(r).add(oe);if(oe.getBaseValue("number")===0)return F.div(c).getBaseValue("number");const Ve=c.add(F);return F.div(Ve).getBaseValue("number")}function yt({runeAmount:e,assetAmount:t,runeDepth:n,assetDepth:r}){if(e==="0"||t==="0"||n==="0"||r==="0")return 0;const s=m(n),i=m(r),o=m(t),l=m(e),c=o.mul(s).sub(i.mul(l)),u=i.mul(l).add(s.mul(i));return Math.abs(c.div(u).getBaseValue("number"))}const wt=(e,t)=>{switch(e){case a.MemoType.LEAVE:case a.MemoType.BOND:{const{address:n}=t;return`${e}:${n}`}case a.MemoType.UNBOND:{const{address:n,unbondAmount:r}=t;return`${e}:${n}:${r}`}case a.MemoType.THORNAME_REGISTER:{const{name:n,chain:r,address:s,owner:i}=t;return`${e}:${n}:${r}:${s}${i?`:${i}`:""}`}case a.MemoType.DEPOSIT:{const{chain:n,symbol:r,address:s,singleSide:i}=t;return i?`${e}:${n}/${r}`:`${e}:${((l,c)=>{switch(l){case a.Chain.Litecoin:return"l";case a.Chain.Dogecoin:return"d";case a.Chain.BitcoinCash:return"c";default:return`${l}.${c}`}})(n,r)}:${s||""}`}case a.MemoType.WITHDRAW:{const{chain:n,ticker:r,symbol:s,basisPoints:i,targetAssetString:o,singleSide:l}=t,c=n==="ETH"&&r!=="ETH"?`${r}-${s.slice(-3)}`:s,u=!l&&o?`:${o}`:"";return`${e}:${n}${l?"/":"."}${c}:${i}${u}`}case a.MemoType.OPEN_LOAN:case a.MemoType.CLOSE_LOAN:{const{asset:n,address:r}=t;return`${e}:${n}:${r}`}default:return""}};function Rt(e){if(e<0)throw new Error("Invalid number of year");return 10+e}function Et(e){if(e<0)throw new Error("Invalid number of year");return Math.round((10+e*1.0512)*1e10)/1e10}function Pt(e){if(e.length>30)return!1;const t=/^[a-zA-Z0-9+_-]+$/g;return!!e.match(t)}function Ot(e){if(e.length>30)return!1;const t=/^[a-zA-Z0-9+_-]+$/g;return!!e.match(t)}function Nt([e,t,n,r,s]){return`${e}'/${t}'/${n}'/${r}${typeof s!="number"?"":`/${s}`}`}const de=[...Object.values(a.Chain),"TERRA"];function Bt(e=""){const t=e.toUpperCase(),[n]=t.split(".");if(de.includes(n))return!0;const[r]=t.split("/");if(de.includes(r))return!0;throw new Error(`Invalid identifier: ${e}. Expected format: <Chain>.<Ticker> or <Chain>.<Ticker>-<ContractAddress>`)}const $=8,S=e=>10n**BigInt(e),N=e=>Math.log10(Number.parseFloat(e.toString()));function I({value:e,bigIntDecimal:t=$,decimal:n=$}){if(n===0)return e.toString();const r=e<0n;let s=e.toString().substring(r?1:0);const i=n-(s.length-1);i>0&&(s="0".repeat(i)+s);const o=s.length-n;let l=s.slice(-n);return Number.parseInt(l[t])>=5?l=`${l.substring(0,t-1)}${(Number.parseInt(l[t-1])+1).toString()}`:l=l.substring(0,t),`${r?"-":""}${s.slice(0,o)}.${l}`.replace(/\.?0*$/,"")}var b,B,C,w,W,ve,D,Q,M,z;const U=class U{constructor(t){y(this,b);y(this,C);y(this,W);y(this,D);y(this,M);p(this,"decimalMultiplier",10n**8n);p(this,"bigIntValue",0n);p(this,"decimal");const n=Z(t),r=typeof t=="object";this.decimal=r?t.decimal:void 0,this.decimalMultiplier=r&&"decimalMultiplier"in t?t.decimalMultiplier:S(Math.max(me(H(n)),this.decimal||0)),d(this,W,ve).call(this,n)}static fromBigInt(t,n){return new U({decimal:n,value:I({value:t,bigIntDecimal:n,decimal:n})})}static shiftDecimals({value:t,from:n,to:r}){return U.fromBigInt(t.getBaseValue("bigint")*S(r)/S(n),r)}set(t){return new this.constructor({decimal:this.decimal,value:t,identifier:this.toString()})}add(...t){return d(this,b,B).call(this,"add",...t)}sub(...t){return d(this,b,B).call(this,"sub",...t)}mul(...t){return d(this,b,B).call(this,"mul",...t)}div(...t){return d(this,b,B).call(this,"div",...t)}gt(t){return d(this,C,w).call(this,"gt",t)}gte(t){return d(this,C,w).call(this,"gte",t)}lt(t){return d(this,C,w).call(this,"lt",t)}lte(t){return d(this,C,w).call(this,"lte",t)}eqValue(t){return d(this,C,w).call(this,"eqValue",t)}getValue(t){const n=this.formatBigIntToSafeValue(this.bigIntValue,this.decimal||N(this.decimalMultiplier));switch(t){case"number":return Number(n);case"string":return n;case"bigint":return this.bigIntValue*10n**BigInt(this.decimal||8n)/this.decimalMultiplier}}getBaseValue(t){const n=this.decimalMultiplier/S(this.decimal||a.BaseDecimal.THOR),r=this.bigIntValue/n;switch(t){case"number":return Number(r);case"string":return r.toString();case"bigint":return r}}getBigIntValue(t,n){if(!n&&typeof t=="object")return t.bigIntValue;const r=Z(t),s=H(r);return s==="0"||s==="undefined"?0n:d(this,M,z).call(this,s,n)}toSignificant(t=6){const[n,r]=this.getValue("string").split("."),s=n||"",i=r||"";if((Number.parseInt(s)?s.length+i.length:i.length)<=t)return this.getValue("string");if(s.length>=t)return s.slice(0,t).padEnd(s.length,"0");if(Number.parseInt(s))return`${s}.${i.slice(0,t-s.length)}`.padEnd(t-s.length,"0");const l=Number.parseInt(i),c=`${l}`.slice(0,t);return`0.${c.padStart(i.length-`${l}`.length+c.length,"0")}`}toFixed(t=6){const[n,r]=this.getValue("string").split("."),s=n||"",i=r||"";if(Number.parseInt(s))return`${s}.${i.slice(0,t)}`.padEnd(t,"0");const o=Number.parseInt(i),l=`${o}`.slice(0,t);return`0.${l.padStart(i.length-`${o}`.length+l.length,"0")}`}toAbbreviation(t=2){const n=this.getValue("number"),r=["","K","M","B","T","Q","Qi","S"],s=Math.floor(Math.log10(Math.abs(n))/3),i=r[s];if(!i)return this.getValue("string");const o=10**(s*3);return`${(n/o).toFixed(t)}${i}`}toCurrency(t="$",{currencyPosition:n="start",decimal:r=2,decimalSeparator:s=".",thousandSeparator:i=","}={}){const o=this.getValue("number"),[l,c=""]=o.toFixed(6).split("."),u=l.replace(/\B(?=(\d{3})+(?!\d))/g,i),h=l||c?l==="0"?`${Number.parseFloat(`0.${c}`)}`.replace(".",s):`${u}${Number.parseInt(c)?`${s}${c.slice(0,r)}`:""}`:"0.00";return`${n==="start"?t:""}${h}${n==="end"?t:""}`}formatBigIntToSafeValue(t,n){const r=n||this.decimal||$,s=Math.max(r,N(this.decimalMultiplier)),i=t<0n,o=t.toString().substring(i?1:0),l=s-(o.length-1),c=l>0?"0".repeat(l)+o:o,u=c.length-s;let h=c.slice(-s);return Number.parseInt(h[r])>=5?h=`${h.substring(0,r-1)}${(Number.parseInt(h[r-1])+1).toString()}`:h=h.substring(0,r),`${i?"-":""}${c.slice(0,u)}.${h}`.replace(/\.?0*$/,"")}};b=new WeakSet,B=function(t,...n){const r=d(this,D,Q).call(this,this,...n),s=Math.max(r,N(this.decimalMultiplier)),i=S(s),o=n.reduce((c,u)=>{const h=this.getBigIntValue(u,s);switch(t){case"add":return c+h;case"sub":return c-h;case"mul":return c*h/i;case"div":{if(h===0n)throw new RangeError("Division by zero");return c*i/h}default:return c}},this.bigIntValue*i/this.decimalMultiplier),l=I({bigIntDecimal:s,decimal:s,value:o});return new this.constructor({decimalMultiplier:S(s),decimal:this.decimal,value:l,identifier:this.toString()})},C=new WeakSet,w=function(t,...n){const r=d(this,D,Q).call(this,this,...n),s=this.getBigIntValue(n[0],r),i=this.getBigIntValue(this,r);switch(t){case"gt":return i>s;case"gte":return i>=s;case"lt":return i<s;case"lte":return i<=s;case"eqValue":return i===s}},W=new WeakSet,ve=function(t){const n=H(t)||"0";this.bigIntValue=d(this,M,z).call(this,n)},D=new WeakSet,Q=function(...t){const n=t.map(r=>typeof r=="object"?r.decimal||N(r.decimalMultiplier):me(H(r))).filter(Boolean);return Math.max(...n,$)},M=new WeakSet,z=function(t,n){const r=n?S(n):this.decimalMultiplier,s=N(r),[i="",o=""]=t.split(".");return BigInt(`${i}${o.padEnd(s,"0")}`)};let P=U;const vt=Intl.NumberFormat("fullwide",{useGrouping:!1,maximumFractionDigits:20});function H(e){const n=`${typeof e=="number"?vt.format(e):Z(e)}`.replaceAll(",",".").split(".");return n.length>1?`${n.slice(0,-1).join("")}.${n.at(-1)}`:n[0]}function me(e){var n;const t=((n=e.split(".")[1])==null?void 0:n.length)||0;return Math.max(t,$)}function Z(e){return typeof e=="object"?"getValue"in e?e.getValue("string"):e.value:e}class T extends P{eq(t){return this.eqValue(t)}static fromBigInt(t,n){return new T({decimal:n,value:I({value:t,bigIntDecimal:n,decimal:n})})}}const R=new Map;class g extends P{constructor({value:n,decimal:r,tax:s,chain:i,symbol:o,identifier:l}){super(typeof n=="object"?n:{decimal:r,value:n});p(this,"address");p(this,"chain");p(this,"isGasAsset",!1);p(this,"isSynthetic",!1);p(this,"symbol");p(this,"tax");p(this,"ticker");p(this,"type");const c=v(l||`${i}.${o}`);this.type=Pe(c),this.tax=s,this.chain=c.chain,this.ticker=c.ticker,this.symbol=c.symbol,this.address=c.address,this.isSynthetic=c.isSynthetic,this.isGasAsset=c.isGasAsset}toString(){return this.isSynthetic?this.symbol:`${this.chain}.${this.symbol}`}toUrl(){return this.isSynthetic?`${this.chain}.${this.symbol.replace("/",".")}`:this.toString()}eq({chain:n,symbol:r}){return this.chain===n&&this.symbol===r}chainId(){return a.ChainToChainId[this.chain]}static fromUrl(n,r=0){const[s,i,o]=n.split(".");if(!(s&&i))throw new Error("Invalid asset url");const l=s===a.Chain.THORChain&&o?`${s}.${i}/${o}`:n;return K(l,r)}static fromString(n,r=0){return K(n,r)}static fromIdentifier(n,r=0){return K(n,r)}static fromStringSync(n,r=0){const{chain:s,isSynthetic:i}=v(n),o=R.get(n.toUpperCase());if(i)return Y(n,r);const{tax:l,decimal:c,identifier:u}=o||{decimal:a.BaseDecimal[s],identifier:n};return new g({tax:l,value:E(r,c),identifier:i?n:u,decimal:i?8:c})}static async fromStringWithBase(n,r=0,s=a.BaseDecimal.THOR){const i=P.shiftDecimals({value:T.fromBigInt(BigInt(r)),from:0,to:s}).getBaseValue("string");return(await g.fromString(n,r)).set(i)}static fromStringWithBaseSync(n,r=0,s=a.BaseDecimal.THOR){const{chain:i,isSynthetic:o}=v(n),l=R.get(n.toUpperCase());if(o)return Y(n,r);const{tax:c,decimal:u,identifier:h}=l||{decimal:a.BaseDecimal[i],identifier:n};return new g({tax:c,value:E(BigInt(r),s),identifier:h,decimal:u})}static fromIdentifierSync(n,r=0){const{chain:s,isSynthetic:i}=v(n),o=R.get(n);if(i)return Y(n,r);const{tax:l,decimal:c,identifier:u}=o||{decimal:a.BaseDecimal[s],identifier:n};return new g({tax:l,decimal:c,identifier:u,value:E(r,c)})}static fromChainOrSignature(n,r=0){const{decimal:s,identifier:i}=Ee(n);return new g({value:E(r,s),decimal:s,identifier:i})}static loadStaticAssets(){return new Promise((n,r)=>{try{import("@swapkit/tokens").then(s=>{for(const i of Object.values(s))for(const{identifier:o,chain:l,...c}of i.tokens)R.set(o.toUpperCase(),{identifier:o,decimal:"decimals"in c?c.decimals:a.BaseDecimal[l]});n({ok:!0})})}catch(s){console.error(s),r({ok:!1,error:s,message:"Couldn't load static assets. Ensure you have installed @swapkit/tokens package"})}})}}function $t(e){const t=g.fromChainOrSignature(e);switch(e){case a.Chain.Bitcoin:case a.Chain.Litecoin:case a.Chain.BitcoinCash:return t.set(10001e-8);case a.Chain.Dogecoin:return t.set(1.00000001);case a.Chain.Avalanche:case a.Chain.Ethereum:return t.set(1e-8);case a.Chain.THORChain:case a.Chain.Maya:return t.set(0);case a.Chain.Cosmos:return t.set(1e-6);default:return t.set(1e-8)}}async function K(e,t=0){Bt(e);const n=R.get(e.toUpperCase()),r=(n==null?void 0:n.decimal)||await Re(v(e));return n||R.set(e.toUpperCase(),{identifier:e,decimal:r}),new g({decimal:r,value:E(t,r),identifier:e})}function Y(e,t=0){const[n,r]=e.split(".")[0].toUpperCase()===a.Chain.THORChain?e.split(".").slice(1).join().split("/"):e.split("/");if(!(n&&r))throw new Error("Invalid asset identifier");return new g({decimal:8,value:E(t,8),identifier:`${a.Chain.THORChain}.${n}/${r}`})}function E(e,t){return typeof e=="bigint"?I({value:e,bigIntDecimal:t,decimal:t}):e}function v(e){const t=e.slice(0,14).includes("/"),[n,r]=e.split(".")[0].toUpperCase()===a.Chain.THORChain?e.split(".").slice(1).join().split("/"):e.split("/");if(t&&!(n&&r))throw new Error("Invalid asset identifier");const s=e.includes(".")&&!t?e:`${a.Chain.THORChain}.${r}`,[i,...o]=s.split("."),[l,c]=(t?r:o.join(".")).split("-"),u=t?r:o.join(".");return{address:c==null?void 0:c.toLowerCase(),chain:i,isGasAsset:se({chain:i,symbol:u}),isSynthetic:t,symbol:(t?`${n}/`:"")+(c?`${l}-${(c==null?void 0:c.toLowerCase())??""}`:u),ticker:l}}const It={core_wallet_connection_not_found:10001,core_estimated_max_spendable_chain_not_supported:10002,core_extend_error:10003,core_inbound_data_not_found:10004,core_approve_asset_address_or_from_not_found:10005,core_plugin_not_found:10006,core_chain_halted:10099,core_wallet_xdefi_not_installed:10101,core_wallet_evmwallet_not_installed:10102,core_wallet_walletconnect_not_installed:10103,core_wallet_keystore_not_installed:10104,core_wallet_ledger_not_installed:10105,core_wallet_trezor_not_installed:10106,core_wallet_keplr_not_installed:10107,core_wallet_okx_not_installed:10108,core_wallet_keepkey_not_installed:10109,core_swap_invalid_params:10200,core_swap_route_not_complete:10201,core_swap_asset_not_recognized:10202,core_swap_contract_not_found:10203,core_swap_route_transaction_not_found:10204,core_swap_contract_not_supported:10205,core_swap_transaction_error:10206,core_swap_quote_mode_not_supported:10207,core_transaction_deposit_error:10301,core_transaction_create_liquidity_rune_error:10302,core_transaction_create_liquidity_asset_error:10303,core_transaction_create_liquidity_invalid_params:10304,core_transaction_add_liquidity_invalid_params:10305,core_transaction_add_liquidity_no_rune_address:10306,core_transaction_add_liquidity_rune_error:10307,core_transaction_add_liquidity_asset_error:10308,core_transaction_withdraw_error:10309,core_transaction_deposit_to_pool_error:10310,core_transaction_deposit_insufficient_funds_error:10311,core_transaction_deposit_gas_error:10312,core_transaction_invalid_sender_address:10313,core_transaction_deposit_server_error:10314,core_transaction_user_rejected:10315,wallet_ledger_connection_error:20001,wallet_ledger_connection_claimed:20002,wallet_ledger_get_address_error:20003,wallet_ledger_device_not_found:20004,wallet_ledger_device_locked:20005,chainflip_channel_error:30001,chainflip_broker_recipient_error:30002,helpers_number_different_decimals:99101};class ie extends Error{constructor(t,n){n&&console.error(n,{stack:n==null?void 0:n.stack,message:n==null?void 0:n.message}),super(t,{cause:{code:It[t],message:t}}),Object.setPrototypeOf(this,ie.prototype)}}exports.ApiEndpoints=f;exports.AssetValue=g;exports.BigIntArithmetics=P;exports.RequestClient=_;exports.StreamingSwapProgressStatus=ye;exports.SwapKitApi=ct;exports.SwapKitError=ie;exports.SwapKitNumber=T;exports.TransactionType=Se;exports.TxStatus=be;exports.assetFromString=pt;exports.defaultRequestHeaders=re;exports.derivationPathToString=Nt;exports.filterAssets=Tt;exports.findAssetBy=gt;exports.formatBigIntToSafeValue=I;exports.gasFeeMultiplier=mt;exports.getAssetType=Pe;exports.getAsymmetricAssetShare=Ne;exports.getAsymmetricAssetWithdrawAmount=Ct;exports.getAsymmetricRuneShare=Oe;exports.getAsymmetricRuneWithdrawAmount=At;exports.getCommonAssetInfo=Ee;exports.getDecimal=Re;exports.getEstimatedPoolShare=bt;exports.getLiquiditySlippage=yt;exports.getMAYANameCost=Et;exports.getMemoFor=wt;exports.getMinAmountByChain=$t;exports.getSymmetricPoolShare=Be;exports.getSymmetricWithdraw=St;exports.getTHORNameCost=Rt;exports.isGasAsset=se;exports.setRequestClientConfig=at;exports.validateMAYAName=Ot;exports.validateTHORName=Pt;
|
|
2
2
|
//# sourceMappingURL=index.cjs.map
|