@swapkit/helpers 1.0.0-rc.69 → 1.0.0-rc.70

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 CHANGED
@@ -1,2 +1,2 @@
1
- "use strict";var ve=Object.create;var q=Object.defineProperty;var $e=Object.getOwnPropertyDescriptor;var He=Object.getOwnPropertyNames;var Fe=Object.getPrototypeOf,Ge=Object.prototype.hasOwnProperty;var We=(e,t,n)=>t in e?q(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n;var xe=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let s of He(t))!Ge.call(e,s)&&s!==n&&q(e,s,{get:()=>t[s],enumerable:!(r=$e(t,s))||r.enumerable});return e};var ke=(e,t,n)=>(n=e!=null?ve(Fe(e)):{},xe(t||!e||!e.__esModule?q(n,"default",{value:e,enumerable:!0}):n,e));var A=(e,t,n)=>(We(e,typeof t!="symbol"?t+"":t,n),n),je=(e,t,n)=>{if(!t.has(e))throw TypeError("Cannot "+n)};var g=(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 u=(e=>(e.INVALID_INPUT_PARAMETERS="1000",e.UNKNOWN_PROVIDERS="1001",e.CANNOT_FIND_INBOUND_ADDRESS="1002",e.NO_INBOUND_ADDRESSES="1003",e.CHAIN_HALTED_OR_UNSUPPORTED="1004",e.MISSING_INPUT_PARAMETER="1005",e.INVALID_TYPE_GENERIC="1100",e.INVALID_NUMBER_STRING="1101",e.INVALID_NUMBER="1102",e.INVALID_BOOLEAN="1103",e.INVALID_OBJECT="1104",e.INVALID_ARRAY="1105",e.SELL_AMOUNT_MUST_BE_POSITIVE_INTEGER="2000",e.SELL_BUY_ASSETS_ARE_THE_SAME="2001",e.MISSING_SOURCE_ADDRESS_FOR_SYNTH="2002",e.AFF_ADDRESS_AND_BPS_OR_NEITHER="2003",e.AFF_ADDRESS_TOO_LONG="2004",e.AFF_BPS_INTEGER_MAX_500="2005",e.SOURCE_ADDRESS_INVALID_FOR_SELL_CHAIN="2006",e.DESTINATION_ADDRESS_INVALID_FOR_BUY_CHAIN="2007",e.PREFERRED_PROVIDER_NOT_SUPPORTED="2008",e.DESTINATION_ADDRESS_SMART_CONTRACT="2009",e.BUY_AMOUNT_MUST_BE_POSITIVE_INTEGER="2010",e.SOURCE_ADDRESS_SMART_CONTRACT="2011",e.SWAP_AMOUNT_TOO_LOW="2012",e.INVALID_PROVIDER="2100",e.MISSING_CROSS_CHAIN_PROVIDER="2101",e.MISSING_AVAX_PROVIDER="2102",e.MISSING_BSC_PROVIDER="2103",e.MISSING_ETH_PROVIDER="2104",e.INVALID_PROVIDER_FOR_SWAP_OUT="2105",e.MISSING_ARB_PROVIDER="2106",e.INVALID_CHAIN="2200",e.INVALID_ASSET="2201",e.INVALID_ASSET_IDENTIFIER="2202",e.UNSUPPORTED_CHAIN="2204",e.UNSUPPORTED_ASSET="2203",e.UNSUPPORTED_ASSET_FOR_SWAPOUT="2205",e.INVALID_SOURCE_ADDRESS="2300",e.INVALID_DESTINATION_ADDRESS="2301",e.THORNODE_QUOTE_GENERIC_ERROR="3000",e.NOT_ENOUGH_SYNTH_BALANCE="3001",e.SYNTH_MINTING_CAP_REACHED="3002",e.INVALID_QUOTE_MODE="4000",e.NO_QUOTES="4001",e.SERVICE_UNAVAILABLE_GENERIC="5000",e.MISSING_GAS_DATA_GENERIC="5100",e.MISSING_TOKEN_INFO_GENERIC="5200",e.CANT_FIND_TOKEN_LIST="5201",e.NO_PRICE="5202",e.PRICE_IS_STALE="5203",e.ADDRESS_NOT_WHITELISTED="6000",e.ADDRESS_ALREADY_CLAIMED="6001",e.TEMPORARY_ERROR="9999",e))(u||{});u.INVALID_INPUT_PARAMETERS+"",u.UNKNOWN_PROVIDERS+"",u.CANNOT_FIND_INBOUND_ADDRESS+"",u.NO_INBOUND_ADDRESSES+"",u.CHAIN_HALTED_OR_UNSUPPORTED+"",u.MISSING_INPUT_PARAMETER+"",u.INVALID_TYPE_GENERIC+"",u.INVALID_NUMBER_STRING+"",u.INVALID_NUMBER+"",u.INVALID_BOOLEAN+"",u.INVALID_OBJECT+"",u.INVALID_ARRAY+"",u.SELL_AMOUNT_MUST_BE_POSITIVE_INTEGER+"",u.SELL_BUY_ASSETS_ARE_THE_SAME+"",u.MISSING_SOURCE_ADDRESS_FOR_SYNTH+"",u.AFF_ADDRESS_AND_BPS_OR_NEITHER+"",u.AFF_ADDRESS_TOO_LONG+"",u.AFF_BPS_INTEGER_MAX_500+"",u.SOURCE_ADDRESS_INVALID_FOR_SELL_CHAIN+"",u.DESTINATION_ADDRESS_INVALID_FOR_BUY_CHAIN+"",u.PREFERRED_PROVIDER_NOT_SUPPORTED+"",u.SOURCE_ADDRESS_SMART_CONTRACT+"",u.SWAP_AMOUNT_TOO_LOW+"",u.DESTINATION_ADDRESS_SMART_CONTRACT+"",u.BUY_AMOUNT_MUST_BE_POSITIVE_INTEGER+"",u.INVALID_PROVIDER+"",u.MISSING_CROSS_CHAIN_PROVIDER+"",u.MISSING_AVAX_PROVIDER+"",u.MISSING_BSC_PROVIDER+"",u.MISSING_ETH_PROVIDER+"",u.MISSING_ARB_PROVIDER+"",u.INVALID_PROVIDER_FOR_SWAP_OUT+"",u.INVALID_CHAIN+"",u.INVALID_ASSET+"",u.UNSUPPORTED_CHAIN+"",u.UNSUPPORTED_ASSET+"",u.UNSUPPORTED_ASSET_FOR_SWAPOUT+"",u.THORNODE_QUOTE_GENERIC_ERROR+"",u.INVALID_SOURCE_ADDRESS+"",u.INVALID_DESTINATION_ADDRESS+"",u.NOT_ENOUGH_SYNTH_BALANCE+"",u.SYNTH_MINTING_CAP_REACHED+"",u.INVALID_QUOTE_MODE+"",u.NO_QUOTES+"",u.SERVICE_UNAVAILABLE_GENERIC+"",u.MISSING_GAS_DATA_GENERIC+"",u.MISSING_TOKEN_INFO_GENERIC+"",u.CANT_FIND_TOKEN_LIST+"",u.NO_PRICE+"",u.PRICE_IS_STALE+"",u.ADDRESS_NOT_WHITELISTED+"",u.ADDRESS_ALREADY_CLAIMED+"";var x=(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))(x||{}),Z=(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))(Z||{}),Te=(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))(Te||{}),E=(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))(E||{});const k=Object.values(x),qe=Object.keys(x),ee=k.reduce((e,t)=>{const n=qe.find(r=>x[r]===t);return n&&(e[t]=n),e},{});k.reduce((e,t)=>(e[t]=Z[ee[t]],e),{});k.reduce((e,t)=>(e[t]=Te[ee[t]],e),{});k.reduce((e,t)=>{const n=`${ee[t]}Hex`;return e[t]=Z[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 Ae 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 $=e=>e!==null&&typeof e=="object",L=(...e)=>{for(const t of e)if((!$(t)||Array.isArray(t))&&t!==void 0)throw new TypeError("The `options` argument must be an object");return te({},...e)},pe=(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},te=(...e)=>{let t={},n={};for(const r of e)if(Array.isArray(r))Array.isArray(t)||(t=[]),t=[...t,...r];else if($(r)){for(let[s,i]of Object.entries(r))$(i)&&s in t&&(i=te(t[s],i)),t={...t,[s]:i};$(r.headers)&&(n=pe(n,r.headers),t.headers=n)}return t},Xe=(()=>{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})(),Ye=typeof globalThis.AbortController=="function",Ke=typeof globalThis.ReadableStream=="function",Je=typeof globalThis.FormData=="function",me=["get","post","put","patch","head","delete"],Qe={json:"application/json",text:"text/*",formData:"multipart/form-data",arrayBuffer:"*/*",blob:"*/*"},X=2147483647,Se=Symbol("stop"),ze={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},et=e=>me.includes(e)?e.toUpperCase():e,tt=["get","put","head","delete","options","trace"],nt=[408,413,429,500,502,503,504],Ee=[413,429,503],le={limit:2,methods:tt,statusCodes:nt,afterStatusCodes:Ee,maxRetryAfter:Number.POSITIVE_INFINITY,backoffLimit:Number.POSITIVE_INFINITY,delay:e=>.3*2**(e-1)*1e3},rt=(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:Ee}};async function st(e,t,n,r){return new Promise((s,i)=>{const o=setTimeout(()=>{n&&n.abort(),i(new Ae(e))},r.timeout);r.fetch(e,t).then(s).catch(i).then(()=>{clearTimeout(o)})})}async function it(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 at=(e,t)=>{const n={};for(const r in t)!(r in Ze)&&!(r in ze)&&!(r in e)&&(n[r]=t[r]);return n};class G{static create(t,n){const r=new G(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(Qe))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={}){if(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,this._options={credentials:this._input.credentials||"same-origin",...n,headers:pe(this._input.headers,n.headers),hooks:te({beforeRequest:[],beforeRetry:[],beforeError:[],afterResponse:[]},n.hooks),method:et(n.method??this._input.method),prefixUrl:String(n.prefixUrl||""),retry:rt(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(Ye){if(this.abortController=new globalThis.AbortController,this._options.signal){const r=this._options.signal;this._options.signal.addEventListener("abort",()=>{this.abortController.abort(r.reason)})}this._options.signal=this.abortController.signal}if(Xe&&(this._options.duplex="half"),this.request=new globalThis.Request(this._input,this._options),this._options.searchParams){const r="?"+(typeof this._options.searchParams=="string"?this._options.searchParams.replace(/^\?/,""):new URLSearchParams(this._options.searchParams).toString()),s=this.request.url.replace(/(?:\?.*?)?(?=#|$)/,r);(Je&&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(s,{...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 Ae)){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 it(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})===Se)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=at(this.request,this._options);return this._options.timeout===!1?this._options.fetch(this.request.clone(),t):st(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:_}=await o.read();if(c){i.close();return}if(n){s+=_.byteLength;const h=r===0?0:s/r;n({percent:h,transferredBytes:s,totalBytes:r},_)}i.enqueue(_),await l()}await l()}}),{status:t.status,statusText:t.statusText,headers:t.headers})}}/*! MIT License © Sindre Sorhus */const K=e=>{const t=(n,r)=>G.create(n,L(e,r));for(const n of me)t[n]=(r,s)=>G.create(r,L(e,s,{method:n}));return t.create=n=>K(L(n)),t.extend=n=>K(L(e,n)),t.stop=Se,t},Ce=K();let H;const m={CachedPrices:`${E.ThorswapApi}/tokenlist/cached-price`,GasRates:`${E.ThorswapApi}/resource-worker/gasPrice/getAll`,Quote:`${E.ThorswapApi}/aggregator/tokens/quote`,Txn:`${E.ThorswapApi}/apiusage/v2/txn`,TokenlistProviders:`${E.ThorswapApi}/tokenlist/providers`,TokenList:`${E.ThorswapStatic}/token-list`,Thorname:`${E.ThorswapApi}/thorname`},ne=typeof window<"u"?{}:{referrer:"https://sk.thorswap.net",referer:"https://sk.thorswap.net"},ue=()=>H||(H=Ce.create({headers:ne}),H),ot=({apiKey:e,...t})=>{H=Ce.create({...t,headers:{...ne,...t.headers,"x-api-key":e}})},p={get:(e,t)=>ue().get(e,t).json(),post:(e,t)=>ue().post(e,t).json()},ct=({tokens:e,...t})=>{const n=new URLSearchParams;return e.filter((r,s,i)=>i.findIndex(o=>o===r)===s).forEach(r=>n.append("tokens",JSON.stringify(r))),t.metadata&&n.append("metadata","true"),t.lookup&&n.append("lookup","true"),t.sparkline&&n.append("sparkline","true"),p.post(m.CachedPrices,{body:n.toString(),headers:{"Content-Type":"application/x-www-form-urlencoded"}})},lt={getCachedPrices:ct,getQuote:e=>p.get(m.Quote,{searchParams:e}),getGasRates:()=>p.get(m.GasRates),getTxnDetails:e=>p.get(m.Txn,{searchParams:e}),getTokenlistProviders:()=>p.get(m.TokenlistProviders),getTokenList:e=>p.get(`${m.TokenList}/${e}.json`),getThornameAddresses:e=>p.get(`${m.Thorname}/${e}`),getThornameRegisteredChains:e=>p.get(`${m.Thorname}/chains/${e}`),getThornameRlookup:(e,t)=>p.get(`${m.Thorname}/rlookup`,{searchParams:{address:e,chain:t}})};var Re=(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))(Re||{}),Ie=(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))(Ie||{}),fe=(e=>(e[e.NOT_STARTED=0]="NOT_STARTED",e[e.SUCCESS=1]="SUCCESS",e[e.REFUNDED=2]="REFUNDED",e))(fe||{});const ut="0x313ce567",ge=async({chain:e,to:t})=>{try{const{result:n}=await p.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:ut},"latest"]})});return parseInt(BigInt(n).toString())}catch(n){return console.error(n),a.BaseDecimal[e]}},_t=async e=>{if(e===a.Chain.Ethereum)return a.BaseDecimal.ETH;const[,t]=e.split("-");return t!=null&&t.startsWith("0x")?ge({chain:a.Chain.Ethereum,to:t}):a.BaseDecimal.ETH},ht=async e=>{const[,t]=e.split("-");return t!=null&&t.startsWith("0x")?ge({chain:a.Chain.Avalanche,to:t.toLowerCase()}):a.BaseDecimal.AVAX},dt=async e=>(e===a.Chain.BinanceSmartChain,a.BaseDecimal.BSC),Ne=async({chain:e,symbol:t})=>{switch(e){case a.Chain.Ethereum:return _t(t);case a.Chain.Avalanche:return ht(t);case a.Chain.BinanceSmartChain:return dt(t);default:return a.BaseDecimal[e]}},Tt={[a.FeeOption.Average]:1.2,[a.FeeOption.Fast]:1.5,[a.FeeOption.Fastest]:2},re=({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}},Oe=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]}}},De=({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"}},At=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}},pt=new RegExp(/(.)\1{6}|\.ORG|\.NET|\.FINANCE|\.COM|WWW|HTTP|\\\\|\/\/|[\s$%:[\]]/,"gmi"),mt=e=>{const[t,n]=e.split(".");if(!a.EVMChainList.includes(t))return!0;const[,r]=n.split("-");return re({chain:t,symbol:n})||!!r},St=e=>e.filter(({chain:t,value:n,symbol:r})=>{const s=`${t}.${r}`;return!pt.test(s)&&mt(s)&&n!=="0"});function Pe({liquidityUnits:e,poolUnits:t,runeDepth:n}){const r=T(e),s=T(t),i=T(n),o=r.mul(i),l=s.mul(s).mul(2),c=s.mul(r).mul(2),_=r.mul(r),h=s.mul(s).mul(s);return o.mul(l.sub(c).add(_)).div(h)}function ye({liquidityUnits:e,poolUnits:t,assetDepth:n}){const r=T(e),s=T(t),i=T(n),o=r.mul(i),l=s.mul(s).mul(2),c=s.mul(r).mul(2),_=r.mul(r),h=o.mul(l.sub(c).add(_)),O=s.mul(s).mul(s);return h.div(O)}function Et({percent:e,runeDepth:t,liquidityUnits:n,poolUnits:r}){return Pe({runeDepth:t,liquidityUnits:n,poolUnits:r}).mul(e)}function Ct({percent:e,assetDepth:t,liquidityUnits:n,poolUnits:r}){return ye({assetDepth:t,liquidityUnits:n,poolUnits:r}).mul(e)}function T(e){return S.fromBigInt(BigInt(e),a.BaseDecimal.THOR)}function be({liquidityUnits:e,poolUnits:t,runeDepth:n,assetDepth:r}){return{assetAmount:T(r).mul(e).div(t),runeAmount:T(n).mul(e).div(t)}}function Rt({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 It({runeDepth:e,poolUnits:t,assetDepth:n,liquidityUnits:r,runeAmount:s,assetAmount:i}){const o=new S({value:e,decimal:8}),l=new S({value:n,decimal:8}),c=new S({value:t,decimal:8}),_=new S({value:s,decimal:8}),h=new S({value:i,decimal:8}),O=_.mul(l),ae=h.mul(o),Be=_.mul(h),Ve=o.mul(l),Me=c.mul(O.add(ae.add(Be.mul(2)))),Ue=O.add(ae.add(Ve.mul(2))),oe=Me.div(Ue),j=T(r).add(oe);if(oe.getBaseValue("number")===0)return j.div(c).getBaseValue("number");const Le=c.add(j);return j.div(Le).getBaseValue("number")}function ft({runeAmount:e,assetAmount:t,runeDepth:n,assetDepth:r}){if(e==="0"||t==="0"||n==="0"||r==="0")return 0;const s=T(n),i=T(r),o=T(t),l=T(e),c=o.mul(s).sub(i.mul(l)),_=i.mul(l).add(s.mul(i));return Math.abs(c.div(_).getBaseValue("number"))}const gt=(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}::t:0`:`${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||""}:t:0`}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,_=!l&&o?`:${o}`:"";return`${e}:${n}${l?"/":"."}${c}:${i}${_}`}case a.MemoType.OPEN_LOAN:case a.MemoType.CLOSE_LOAN:{const{asset:n,address:r}=t;return`${e}:${n}:${r}`}default:return""}};function Nt(e){if(e<0)throw new Error("Invalid number of year");return 10+e}function Ot(e){if(e.length>30)return!1;const t=/^[a-zA-Z0-9+_-]+$/g;return!!e.match(t)}function Dt([e,t,n,r,s]){return`${e}'/${t}'/${n}'/${r}${typeof s!="number"?"":`/${s}`}`}const _e=[...Object.values(a.Chain),"TERRA"];function Pt(e=""){const t=e.toUpperCase(),[n]=t.split(".");if(_e.includes(n))return!0;const[r]=t.split("/");if(_e.includes(r))return!0;throw new Error(`Invalid identifier: ${e}. Expected format: <Chain>.<Ticker> or <Chain>.<Ticker>-<ContractAddress>`)}const w=8,I=e=>10n**BigInt(e),D=e=>Math.log10(parseFloat(e.toString()));function B({value:e,bigIntDecimal:t=w,decimal:n=w}){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 parseInt(l[t])>=5?l=`${l.substring(0,t-1)}${(parseInt(l[t-1])+1).toString()}`:l=l.substring(0,t),`${r?"-":""}${s.slice(0,o)}.${l}`.replace(/\.?0*$/,"")}var f,P,C,N,W,we,M,J,U,Q;const ie=class ie{constructor(t){g(this,f);g(this,C);g(this,W);g(this,M);g(this,U);A(this,"decimalMultiplier",10n**8n);A(this,"bigIntValue",0n);A(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:I(Math.max(he(v(n)),this.decimal||0)),d(this,W,we).call(this,n)}static fromBigInt(t,n){return new ie({decimal:n,value:B({value:t,bigIntDecimal:n,decimal:n})})}static shiftDecimals({value:t,from:n,to:r}){return this.fromBigInt(t.getBaseValue("bigint")*I(r)/I(n),r)}set(t){return new this.constructor({decimal:this.decimal,value:t,identifier:this.toString()})}add(...t){return d(this,f,P).call(this,"add",...t)}sub(...t){return d(this,f,P).call(this,"sub",...t)}mul(...t){return d(this,f,P).call(this,"mul",...t)}div(...t){return d(this,f,P).call(this,"div",...t)}gt(t){return d(this,C,N).call(this,"gt",t)}gte(t){return d(this,C,N).call(this,"gte",t)}lt(t){return d(this,C,N).call(this,"lt",t)}lte(t){return d(this,C,N).call(this,"lte",t)}eqValue(t){return d(this,C,N).call(this,"eqValue",t)}getValue(t){const n=this.formatBigIntToSafeValue(this.bigIntValue,this.decimal||D(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/I(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=v(r);return s==="0"||s==="undefined"?0n:d(this,U,Q).call(this,s,n)}toSignificant(t=6){const[n,r]=this.getValue("string").split("."),s=n||"",i=r||"";if((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(parseInt(s))return`${s}.${i.slice(0,t-s.length)}`.padEnd(t-s.length,"0");const l=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(parseInt(s))return`${s}.${i.slice(0,t)}`.padEnd(t,"0");const o=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("."),_=l.replace(/\B(?=(\d{3})+(?!\d))/g,i),h=!l&&!c?"0.00":l==="0"?`${parseFloat(`0.${c}`)}`.replace(".",s):`${_}${parseInt(c)?`${s}${c.slice(0,r)}`:""}`;return`${n==="start"?t:""}${h}${n==="end"?t:""}`}formatBigIntToSafeValue(t,n){const r=n||this.decimal||w,s=Math.max(r,D(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,_=c.length-s;let h=c.slice(-s);return parseInt(h[r])>=5?h=`${h.substring(0,r-1)}${(parseInt(h[r-1])+1).toString()}`:h=h.substring(0,r),`${i?"-":""}${c.slice(0,_)}.${h}`.replace(/\.?0*$/,"")}};f=new WeakSet,P=function(t,...n){const r=d(this,M,J).call(this,this,...n),s=Math.max(r,D(this.decimalMultiplier)),i=I(s),o=n.reduce((c,_)=>{const h=this.getBigIntValue(_,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=B({bigIntDecimal:s,decimal:s,value:o});return new this.constructor({decimalMultiplier:I(s),decimal:this.decimal,value:l,identifier:this.toString()})},C=new WeakSet,N=function(t,...n){const r=d(this,M,J).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,we=function(t){const n=v(t)||"0";this.bigIntValue=d(this,U,Q).call(this,n)},M=new WeakSet,J=function(...t){const n=t.map(r=>typeof r=="object"?r.decimal||D(r.decimalMultiplier):he(v(r))).filter(Boolean);return Math.max(...n,w)},U=new WeakSet,Q=function(t,n){const r=n?I(n):this.decimalMultiplier,s=D(r),[i="",o=""]=t.split(".");return BigInt(`${i}${o.padEnd(s,"0")}`)};let V=ie;const yt=Intl.NumberFormat("fullwide",{useGrouping:!1,maximumFractionDigits:20});function v(e){const n=`${typeof e=="number"?yt.format(e):z(e)}`.replaceAll(",",".").split(".");return n.length>1?`${n.slice(0,-1).join("")}.${n.at(-1)}`:n[0]}function he(e){var n;const t=((n=e.split(".")[1])==null?void 0:n.length)||0;return Math.max(t,w)}function z(e){return typeof e=="object"?"getValue"in e?e.getValue("string"):e.value:e}const y=new Map;class R extends V{constructor({value:n,decimal:r,tax:s,chain:i,symbol:o,identifier:l}){super(typeof n=="object"?n:{decimal:r,value:n});A(this,"address");A(this,"chain");A(this,"isGasAsset",!1);A(this,"isSynthetic",!1);A(this,"symbol");A(this,"tax");A(this,"ticker");A(this,"type");const c=F(l||`${i}.${o}`);this.type=De(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 Y(l,r)}static fromString(n,r=0){return Y(n,r)}static fromIdentifier(n,r=0){return Y(n,r)}static fromStringSync(n,r=0){const{chain:s,isSynthetic:i}=F(n),o=y.get(n.toUpperCase());if(i)return de(n,r);const{tax:l,decimal:c,identifier:_}=o||{decimal:a.BaseDecimal[s],identifier:n};return new R({tax:l,value:b(r,c),identifier:i?n:_,decimal:i?8:c})}static fromIdentifierSync(n,r=0){const{chain:s,isSynthetic:i}=F(n),o=y.get(n);if(i)return de(n,r);const{tax:l,decimal:c,identifier:_}=o||{decimal:a.BaseDecimal[s],identifier:n};return new R({tax:l,decimal:c,identifier:_,value:b(r,c)})}static fromChainOrSignature(n,r=0){const{decimal:s,identifier:i}=Oe(n);return new R({value:b(r,s),decimal:s,identifier:i})}static loadStaticAssets(){return new Promise(async(n,r)=>{try{const s=await import("@swapkit/tokens");Object.values(s).forEach(i=>{var o;(o=i==null?void 0:i.tokens)==null||o.forEach(({identifier:l,chain:c,..._})=>{y.set(l.toUpperCase(),{identifier:l,decimal:"decimals"in _?_.decimals:a.BaseDecimal[c]})})}),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=R.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 Y(e,t=0){Pt(e);const n=y.get(e.toUpperCase()),r=(n==null?void 0:n.decimal)||await Ne(F(e));return n||y.set(e.toUpperCase(),{identifier:e,decimal:r}),new R({decimal:r,value:b(t,r),identifier:e})}function de(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 R({decimal:8,value:b(t,8),identifier:`${a.Chain.THORChain}.${n}/${r}`})}function b(e,t){return typeof e=="bigint"?B({value:e,bigIntDecimal:t,decimal:t}):e}function F(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("-"),_=t?r:o.join(".");return{address:c==null?void 0:c.toLowerCase(),chain:i,isGasAsset:re({chain:i,symbol:_}),isSynthetic:t,symbol:(t?`${n}/`:"")+(c?`${l}-${(c==null?void 0:c.toLowerCase())??""}`:_),ticker:l}}const wt={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_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,helpers_number_different_decimals:99101};class se 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:wt[t],message:t}}),Object.setPrototypeOf(this,se.prototype)}}class S extends V{eq(t){return this.eqValue(t)}static fromBigInt(t,n){return new S({decimal:n,value:B({value:t,bigIntDecimal:n,decimal:n})})}}exports.ApiEndpoints=m;exports.AssetValue=R;exports.BigIntArithmetics=V;exports.RequestClient=p;exports.StreamingSwapProgressStatus=fe;exports.SwapKitApi=lt;exports.SwapKitError=se;exports.SwapKitNumber=S;exports.TransactionType=Re;exports.TxStatus=Ie;exports.assetFromString=At;exports.defaultRequestHeaders=ne;exports.derivationPathToString=Dt;exports.filterAssets=St;exports.formatBigIntToSafeValue=B;exports.gasFeeMultiplier=Tt;exports.getAssetType=De;exports.getAsymmetricAssetShare=ye;exports.getAsymmetricAssetWithdrawAmount=Ct;exports.getAsymmetricRuneShare=Pe;exports.getAsymmetricRuneWithdrawAmount=Et;exports.getCommonAssetInfo=Oe;exports.getDecimal=Ne;exports.getEstimatedPoolShare=It;exports.getLiquiditySlippage=ft;exports.getMemoFor=gt;exports.getMinAmountByChain=bt;exports.getSymmetricPoolShare=be;exports.getSymmetricWithdraw=Rt;exports.getTHORNameCost=Nt;exports.isGasAsset=re;exports.setRequestClientConfig=ot;exports.validateTHORName=Ot;
1
+ "use strict";var ve=Object.create;var q=Object.defineProperty;var $e=Object.getOwnPropertyDescriptor;var He=Object.getOwnPropertyNames;var Fe=Object.getPrototypeOf,Ge=Object.prototype.hasOwnProperty;var We=(e,t,n)=>t in e?q(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n;var xe=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let s of He(t))!Ge.call(e,s)&&s!==n&&q(e,s,{get:()=>t[s],enumerable:!(r=$e(t,s))||r.enumerable});return e};var ke=(e,t,n)=>(n=e!=null?ve(Fe(e)):{},xe(t||!e||!e.__esModule?q(n,"default",{value:e,enumerable:!0}):n,e));var A=(e,t,n)=>(We(e,typeof t!="symbol"?t+"":t,n),n),je=(e,t,n)=>{if(!t.has(e))throw TypeError("Cannot "+n)};var g=(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 u=(e=>(e.INVALID_INPUT_PARAMETERS="1000",e.UNKNOWN_PROVIDERS="1001",e.CANNOT_FIND_INBOUND_ADDRESS="1002",e.NO_INBOUND_ADDRESSES="1003",e.CHAIN_HALTED_OR_UNSUPPORTED="1004",e.MISSING_INPUT_PARAMETER="1005",e.INVALID_TYPE_GENERIC="1100",e.INVALID_NUMBER_STRING="1101",e.INVALID_NUMBER="1102",e.INVALID_BOOLEAN="1103",e.INVALID_OBJECT="1104",e.INVALID_ARRAY="1105",e.SELL_AMOUNT_MUST_BE_POSITIVE_INTEGER="2000",e.SELL_BUY_ASSETS_ARE_THE_SAME="2001",e.MISSING_SOURCE_ADDRESS_FOR_SYNTH="2002",e.AFF_ADDRESS_AND_BPS_OR_NEITHER="2003",e.AFF_ADDRESS_TOO_LONG="2004",e.AFF_BPS_INTEGER_MAX_500="2005",e.SOURCE_ADDRESS_INVALID_FOR_SELL_CHAIN="2006",e.DESTINATION_ADDRESS_INVALID_FOR_BUY_CHAIN="2007",e.PREFERRED_PROVIDER_NOT_SUPPORTED="2008",e.DESTINATION_ADDRESS_SMART_CONTRACT="2009",e.BUY_AMOUNT_MUST_BE_POSITIVE_INTEGER="2010",e.SOURCE_ADDRESS_SMART_CONTRACT="2011",e.SWAP_AMOUNT_TOO_LOW="2012",e.INVALID_PROVIDER="2100",e.MISSING_CROSS_CHAIN_PROVIDER="2101",e.MISSING_AVAX_PROVIDER="2102",e.MISSING_BSC_PROVIDER="2103",e.MISSING_ETH_PROVIDER="2104",e.INVALID_PROVIDER_FOR_SWAP_OUT="2105",e.MISSING_ARB_PROVIDER="2106",e.INVALID_CHAIN="2200",e.INVALID_ASSET="2201",e.INVALID_ASSET_IDENTIFIER="2202",e.UNSUPPORTED_CHAIN="2204",e.UNSUPPORTED_ASSET="2203",e.UNSUPPORTED_ASSET_FOR_SWAPOUT="2205",e.INVALID_SOURCE_ADDRESS="2300",e.INVALID_DESTINATION_ADDRESS="2301",e.THORNODE_QUOTE_GENERIC_ERROR="3000",e.NOT_ENOUGH_SYNTH_BALANCE="3001",e.SYNTH_MINTING_CAP_REACHED="3002",e.INVALID_QUOTE_MODE="4000",e.NO_QUOTES="4001",e.SERVICE_UNAVAILABLE_GENERIC="5000",e.MISSING_GAS_DATA_GENERIC="5100",e.MISSING_TOKEN_INFO_GENERIC="5200",e.CANT_FIND_TOKEN_LIST="5201",e.NO_PRICE="5202",e.PRICE_IS_STALE="5203",e.ADDRESS_NOT_WHITELISTED="6000",e.ADDRESS_ALREADY_CLAIMED="6001",e.TEMPORARY_ERROR="9999",e))(u||{});u.INVALID_INPUT_PARAMETERS+"",u.UNKNOWN_PROVIDERS+"",u.CANNOT_FIND_INBOUND_ADDRESS+"",u.NO_INBOUND_ADDRESSES+"",u.CHAIN_HALTED_OR_UNSUPPORTED+"",u.MISSING_INPUT_PARAMETER+"",u.INVALID_TYPE_GENERIC+"",u.INVALID_NUMBER_STRING+"",u.INVALID_NUMBER+"",u.INVALID_BOOLEAN+"",u.INVALID_OBJECT+"",u.INVALID_ARRAY+"",u.SELL_AMOUNT_MUST_BE_POSITIVE_INTEGER+"",u.SELL_BUY_ASSETS_ARE_THE_SAME+"",u.MISSING_SOURCE_ADDRESS_FOR_SYNTH+"",u.AFF_ADDRESS_AND_BPS_OR_NEITHER+"",u.AFF_ADDRESS_TOO_LONG+"",u.AFF_BPS_INTEGER_MAX_500+"",u.SOURCE_ADDRESS_INVALID_FOR_SELL_CHAIN+"",u.DESTINATION_ADDRESS_INVALID_FOR_BUY_CHAIN+"",u.PREFERRED_PROVIDER_NOT_SUPPORTED+"",u.SOURCE_ADDRESS_SMART_CONTRACT+"",u.SWAP_AMOUNT_TOO_LOW+"",u.DESTINATION_ADDRESS_SMART_CONTRACT+"",u.BUY_AMOUNT_MUST_BE_POSITIVE_INTEGER+"",u.INVALID_PROVIDER+"",u.MISSING_CROSS_CHAIN_PROVIDER+"",u.MISSING_AVAX_PROVIDER+"",u.MISSING_BSC_PROVIDER+"",u.MISSING_ETH_PROVIDER+"",u.MISSING_ARB_PROVIDER+"",u.INVALID_PROVIDER_FOR_SWAP_OUT+"",u.INVALID_CHAIN+"",u.INVALID_ASSET+"",u.UNSUPPORTED_CHAIN+"",u.UNSUPPORTED_ASSET+"",u.UNSUPPORTED_ASSET_FOR_SWAPOUT+"",u.THORNODE_QUOTE_GENERIC_ERROR+"",u.INVALID_SOURCE_ADDRESS+"",u.INVALID_DESTINATION_ADDRESS+"",u.NOT_ENOUGH_SYNTH_BALANCE+"",u.SYNTH_MINTING_CAP_REACHED+"",u.INVALID_QUOTE_MODE+"",u.NO_QUOTES+"",u.SERVICE_UNAVAILABLE_GENERIC+"",u.MISSING_GAS_DATA_GENERIC+"",u.MISSING_TOKEN_INFO_GENERIC+"",u.CANT_FIND_TOKEN_LIST+"",u.NO_PRICE+"",u.PRICE_IS_STALE+"",u.ADDRESS_NOT_WHITELISTED+"",u.ADDRESS_ALREADY_CLAIMED+"";var x=(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))(x||{}),Z=(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))(Z||{}),Te=(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))(Te||{}),E=(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))(E||{});const k=Object.values(x),qe=Object.keys(x),ee=k.reduce((e,t)=>{const n=qe.find(r=>x[r]===t);return n&&(e[t]=n),e},{});k.reduce((e,t)=>(e[t]=Z[ee[t]],e),{});k.reduce((e,t)=>(e[t]=Te[ee[t]],e),{});k.reduce((e,t)=>{const n=`${ee[t]}Hex`;return e[t]=Z[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 Ae 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 $=e=>e!==null&&typeof e=="object",L=(...e)=>{for(const t of e)if((!$(t)||Array.isArray(t))&&t!==void 0)throw new TypeError("The `options` argument must be an object");return te({},...e)},pe=(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},te=(...e)=>{let t={},n={};for(const r of e)if(Array.isArray(r))Array.isArray(t)||(t=[]),t=[...t,...r];else if($(r)){for(let[s,i]of Object.entries(r))$(i)&&s in t&&(i=te(t[s],i)),t={...t,[s]:i};$(r.headers)&&(n=pe(n,r.headers),t.headers=n)}return t},Xe=(()=>{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})(),Ye=typeof globalThis.AbortController=="function",Ke=typeof globalThis.ReadableStream=="function",Je=typeof globalThis.FormData=="function",me=["get","post","put","patch","head","delete"],Qe={json:"application/json",text:"text/*",formData:"multipart/form-data",arrayBuffer:"*/*",blob:"*/*"},X=2147483647,Se=Symbol("stop"),ze={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},et=e=>me.includes(e)?e.toUpperCase():e,tt=["get","put","head","delete","options","trace"],nt=[408,413,429,500,502,503,504],Ee=[413,429,503],le={limit:2,methods:tt,statusCodes:nt,afterStatusCodes:Ee,maxRetryAfter:Number.POSITIVE_INFINITY,backoffLimit:Number.POSITIVE_INFINITY,delay:e=>.3*2**(e-1)*1e3},rt=(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:Ee}};async function st(e,t,n,r){return new Promise((s,i)=>{const o=setTimeout(()=>{n&&n.abort(),i(new Ae(e))},r.timeout);r.fetch(e,t).then(s).catch(i).then(()=>{clearTimeout(o)})})}async function it(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 at=(e,t)=>{const n={};for(const r in t)!(r in Ze)&&!(r in ze)&&!(r in e)&&(n[r]=t[r]);return n};class G{static create(t,n){const r=new G(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(Qe))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={}){if(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,this._options={credentials:this._input.credentials||"same-origin",...n,headers:pe(this._input.headers,n.headers),hooks:te({beforeRequest:[],beforeRetry:[],beforeError:[],afterResponse:[]},n.hooks),method:et(n.method??this._input.method),prefixUrl:String(n.prefixUrl||""),retry:rt(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(Ye){if(this.abortController=new globalThis.AbortController,this._options.signal){const r=this._options.signal;this._options.signal.addEventListener("abort",()=>{this.abortController.abort(r.reason)})}this._options.signal=this.abortController.signal}if(Xe&&(this._options.duplex="half"),this.request=new globalThis.Request(this._input,this._options),this._options.searchParams){const r="?"+(typeof this._options.searchParams=="string"?this._options.searchParams.replace(/^\?/,""):new URLSearchParams(this._options.searchParams).toString()),s=this.request.url.replace(/(?:\?.*?)?(?=#|$)/,r);(Je&&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(s,{...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 Ae)){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 it(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})===Se)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=at(this.request,this._options);return this._options.timeout===!1?this._options.fetch(this.request.clone(),t):st(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:_}=await o.read();if(c){i.close();return}if(n){s+=_.byteLength;const h=r===0?0:s/r;n({percent:h,transferredBytes:s,totalBytes:r},_)}i.enqueue(_),await l()}await l()}}),{status:t.status,statusText:t.statusText,headers:t.headers})}}/*! MIT License © Sindre Sorhus */const K=e=>{const t=(n,r)=>G.create(n,L(e,r));for(const n of me)t[n]=(r,s)=>G.create(r,L(e,s,{method:n}));return t.create=n=>K(L(n)),t.extend=n=>K(L(e,n)),t.stop=Se,t},Ce=K();let H;const m={CachedPrices:`${E.ThorswapApi}/tokenlist/cached-price`,GasRates:`${E.ThorswapApi}/resource-worker/gasPrice/getAll`,Quote:`${E.ThorswapApi}/aggregator/tokens/quote`,Txn:`${E.ThorswapApi}/apiusage/v2/txn`,TokenlistProviders:`${E.ThorswapApi}/tokenlist/providers`,TokenList:`${E.ThorswapStatic}/token-list`,Thorname:`${E.ThorswapApi}/thorname`},ne=typeof window<"u"?{}:{referrer:"https://sk.thorswap.net",referer:"https://sk.thorswap.net"},ue=()=>H||(H=Ce.create({headers:ne}),H),ot=({apiKey:e,...t})=>{H=Ce.create({...t,headers:{...ne,...t.headers,"x-api-key":e}})},p={get:(e,t)=>ue().get(e,t).json(),post:(e,t)=>ue().post(e,t).json()},ct=({tokens:e,...t})=>{const n=new URLSearchParams;return e.filter((r,s,i)=>i.findIndex(o=>o===r)===s).forEach(r=>n.append("tokens",JSON.stringify(r))),t.metadata&&n.append("metadata","true"),t.lookup&&n.append("lookup","true"),t.sparkline&&n.append("sparkline","true"),p.post(m.CachedPrices,{body:n.toString(),headers:{"Content-Type":"application/x-www-form-urlencoded"}})},lt={getCachedPrices:ct,getQuote:e=>p.get(m.Quote,{searchParams:e}),getGasRates:()=>p.get(m.GasRates),getTxnDetails:e=>p.get(m.Txn,{searchParams:e}),getTokenlistProviders:()=>p.get(m.TokenlistProviders),getTokenList:e=>p.get(`${m.TokenList}/${e}.json`),getThornameAddresses:e=>p.get(`${m.Thorname}/${e}`),getThornameRegisteredChains:e=>p.get(`${m.Thorname}/chains/${e}`),getThornameRlookup:(e,t)=>p.get(`${m.Thorname}/rlookup`,{searchParams:{address:e,chain:t}})};var Re=(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))(Re||{}),Ie=(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))(Ie||{}),fe=(e=>(e[e.NOT_STARTED=0]="NOT_STARTED",e[e.SUCCESS=1]="SUCCESS",e[e.REFUNDED=2]="REFUNDED",e))(fe||{});const ut="0x313ce567",ge=async({chain:e,to:t})=>{try{const{result:n}=await p.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:ut},"latest"]})});return parseInt(BigInt(n).toString())}catch(n){return console.error(n),a.BaseDecimal[e]}},_t=async e=>{if(e===a.Chain.Ethereum)return a.BaseDecimal.ETH;const[,t]=e.split("-");return t!=null&&t.startsWith("0x")?ge({chain:a.Chain.Ethereum,to:t}):a.BaseDecimal.ETH},ht=async e=>{const[,t]=e.split("-");return t!=null&&t.startsWith("0x")?ge({chain:a.Chain.Avalanche,to:t.toLowerCase()}):a.BaseDecimal.AVAX},dt=async e=>(e===a.Chain.BinanceSmartChain,a.BaseDecimal.BSC),Ne=async({chain:e,symbol:t})=>{switch(e){case a.Chain.Ethereum:return _t(t);case a.Chain.Avalanche:return ht(t);case a.Chain.BinanceSmartChain:return dt(t);default:return a.BaseDecimal[e]}},Tt={[a.FeeOption.Average]:1.2,[a.FeeOption.Fast]:1.5,[a.FeeOption.Fastest]:2},re=({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}},Oe=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]}}},De=({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"}},At=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}},pt=new RegExp(/(.)\1{6}|\.ORG|\.NET|\.FINANCE|\.COM|WWW|HTTP|\\\\|\/\/|[\s$%:[\]]/,"gmi"),mt=e=>{const[t,n]=e.split(".");if(!a.EVMChainList.includes(t))return!0;const[,r]=n.split("-");return re({chain:t,symbol:n})||!!r},St=e=>e.filter(({chain:t,value:n,symbol:r})=>{const s=`${t}.${r}`;return!pt.test(s)&&mt(s)&&n!=="0"});function Pe({liquidityUnits:e,poolUnits:t,runeDepth:n}){const r=T(e),s=T(t),i=T(n),o=r.mul(i),l=s.mul(s).mul(2),c=s.mul(r).mul(2),_=r.mul(r),h=s.mul(s).mul(s);return o.mul(l.sub(c).add(_)).div(h)}function ye({liquidityUnits:e,poolUnits:t,assetDepth:n}){const r=T(e),s=T(t),i=T(n),o=r.mul(i),l=s.mul(s).mul(2),c=s.mul(r).mul(2),_=r.mul(r),h=o.mul(l.sub(c).add(_)),O=s.mul(s).mul(s);return h.div(O)}function Et({percent:e,runeDepth:t,liquidityUnits:n,poolUnits:r}){return Pe({runeDepth:t,liquidityUnits:n,poolUnits:r}).mul(e)}function Ct({percent:e,assetDepth:t,liquidityUnits:n,poolUnits:r}){return ye({assetDepth:t,liquidityUnits:n,poolUnits:r}).mul(e)}function T(e){return S.fromBigInt(BigInt(e),a.BaseDecimal.THOR)}function be({liquidityUnits:e,poolUnits:t,runeDepth:n,assetDepth:r}){return{assetAmount:T(r).mul(e).div(t),runeAmount:T(n).mul(e).div(t)}}function Rt({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 It({runeDepth:e,poolUnits:t,assetDepth:n,liquidityUnits:r,runeAmount:s,assetAmount:i}){const o=new S({value:e,decimal:8}),l=new S({value:n,decimal:8}),c=new S({value:t,decimal:8}),_=new S({value:s,decimal:8}),h=new S({value:i,decimal:8}),O=_.mul(l),ae=h.mul(o),Be=_.mul(h),Ve=o.mul(l),Me=c.mul(O.add(ae.add(Be.mul(2)))),Ue=O.add(ae.add(Ve.mul(2))),oe=Me.div(Ue),j=T(r).add(oe);if(oe.getBaseValue("number")===0)return j.div(c).getBaseValue("number");const Le=c.add(j);return j.div(Le).getBaseValue("number")}function ft({runeAmount:e,assetAmount:t,runeDepth:n,assetDepth:r}){if(e==="0"||t==="0"||n==="0"||r==="0")return 0;const s=T(n),i=T(r),o=T(t),l=T(e),c=o.mul(s).sub(i.mul(l)),_=i.mul(l).add(s.mul(i));return Math.abs(c.div(_).getBaseValue("number"))}const gt=(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,_=!l&&o?`:${o}`:"";return`${e}:${n}${l?"/":"."}${c}:${i}${_}`}case a.MemoType.OPEN_LOAN:case a.MemoType.CLOSE_LOAN:{const{asset:n,address:r}=t;return`${e}:${n}:${r}`}default:return""}};function Nt(e){if(e<0)throw new Error("Invalid number of year");return 10+e}function Ot(e){if(e.length>30)return!1;const t=/^[a-zA-Z0-9+_-]+$/g;return!!e.match(t)}function Dt([e,t,n,r,s]){return`${e}'/${t}'/${n}'/${r}${typeof s!="number"?"":`/${s}`}`}const _e=[...Object.values(a.Chain),"TERRA"];function Pt(e=""){const t=e.toUpperCase(),[n]=t.split(".");if(_e.includes(n))return!0;const[r]=t.split("/");if(_e.includes(r))return!0;throw new Error(`Invalid identifier: ${e}. Expected format: <Chain>.<Ticker> or <Chain>.<Ticker>-<ContractAddress>`)}const w=8,I=e=>10n**BigInt(e),D=e=>Math.log10(parseFloat(e.toString()));function B({value:e,bigIntDecimal:t=w,decimal:n=w}){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 parseInt(l[t])>=5?l=`${l.substring(0,t-1)}${(parseInt(l[t-1])+1).toString()}`:l=l.substring(0,t),`${r?"-":""}${s.slice(0,o)}.${l}`.replace(/\.?0*$/,"")}var f,P,C,N,W,we,M,J,U,Q;const ie=class ie{constructor(t){g(this,f);g(this,C);g(this,W);g(this,M);g(this,U);A(this,"decimalMultiplier",10n**8n);A(this,"bigIntValue",0n);A(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:I(Math.max(he(v(n)),this.decimal||0)),d(this,W,we).call(this,n)}static fromBigInt(t,n){return new ie({decimal:n,value:B({value:t,bigIntDecimal:n,decimal:n})})}static shiftDecimals({value:t,from:n,to:r}){return this.fromBigInt(t.getBaseValue("bigint")*I(r)/I(n),r)}set(t){return new this.constructor({decimal:this.decimal,value:t,identifier:this.toString()})}add(...t){return d(this,f,P).call(this,"add",...t)}sub(...t){return d(this,f,P).call(this,"sub",...t)}mul(...t){return d(this,f,P).call(this,"mul",...t)}div(...t){return d(this,f,P).call(this,"div",...t)}gt(t){return d(this,C,N).call(this,"gt",t)}gte(t){return d(this,C,N).call(this,"gte",t)}lt(t){return d(this,C,N).call(this,"lt",t)}lte(t){return d(this,C,N).call(this,"lte",t)}eqValue(t){return d(this,C,N).call(this,"eqValue",t)}getValue(t){const n=this.formatBigIntToSafeValue(this.bigIntValue,this.decimal||D(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/I(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=v(r);return s==="0"||s==="undefined"?0n:d(this,U,Q).call(this,s,n)}toSignificant(t=6){const[n,r]=this.getValue("string").split("."),s=n||"",i=r||"";if((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(parseInt(s))return`${s}.${i.slice(0,t-s.length)}`.padEnd(t-s.length,"0");const l=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(parseInt(s))return`${s}.${i.slice(0,t)}`.padEnd(t,"0");const o=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("."),_=l.replace(/\B(?=(\d{3})+(?!\d))/g,i),h=!l&&!c?"0.00":l==="0"?`${parseFloat(`0.${c}`)}`.replace(".",s):`${_}${parseInt(c)?`${s}${c.slice(0,r)}`:""}`;return`${n==="start"?t:""}${h}${n==="end"?t:""}`}formatBigIntToSafeValue(t,n){const r=n||this.decimal||w,s=Math.max(r,D(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,_=c.length-s;let h=c.slice(-s);return parseInt(h[r])>=5?h=`${h.substring(0,r-1)}${(parseInt(h[r-1])+1).toString()}`:h=h.substring(0,r),`${i?"-":""}${c.slice(0,_)}.${h}`.replace(/\.?0*$/,"")}};f=new WeakSet,P=function(t,...n){const r=d(this,M,J).call(this,this,...n),s=Math.max(r,D(this.decimalMultiplier)),i=I(s),o=n.reduce((c,_)=>{const h=this.getBigIntValue(_,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=B({bigIntDecimal:s,decimal:s,value:o});return new this.constructor({decimalMultiplier:I(s),decimal:this.decimal,value:l,identifier:this.toString()})},C=new WeakSet,N=function(t,...n){const r=d(this,M,J).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,we=function(t){const n=v(t)||"0";this.bigIntValue=d(this,U,Q).call(this,n)},M=new WeakSet,J=function(...t){const n=t.map(r=>typeof r=="object"?r.decimal||D(r.decimalMultiplier):he(v(r))).filter(Boolean);return Math.max(...n,w)},U=new WeakSet,Q=function(t,n){const r=n?I(n):this.decimalMultiplier,s=D(r),[i="",o=""]=t.split(".");return BigInt(`${i}${o.padEnd(s,"0")}`)};let V=ie;const yt=Intl.NumberFormat("fullwide",{useGrouping:!1,maximumFractionDigits:20});function v(e){const n=`${typeof e=="number"?yt.format(e):z(e)}`.replaceAll(",",".").split(".");return n.length>1?`${n.slice(0,-1).join("")}.${n.at(-1)}`:n[0]}function he(e){var n;const t=((n=e.split(".")[1])==null?void 0:n.length)||0;return Math.max(t,w)}function z(e){return typeof e=="object"?"getValue"in e?e.getValue("string"):e.value:e}const y=new Map;class R extends V{constructor({value:n,decimal:r,tax:s,chain:i,symbol:o,identifier:l}){super(typeof n=="object"?n:{decimal:r,value:n});A(this,"address");A(this,"chain");A(this,"isGasAsset",!1);A(this,"isSynthetic",!1);A(this,"symbol");A(this,"tax");A(this,"ticker");A(this,"type");const c=F(l||`${i}.${o}`);this.type=De(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 Y(l,r)}static fromString(n,r=0){return Y(n,r)}static fromIdentifier(n,r=0){return Y(n,r)}static fromStringSync(n,r=0){const{chain:s,isSynthetic:i}=F(n),o=y.get(n.toUpperCase());if(i)return de(n,r);const{tax:l,decimal:c,identifier:_}=o||{decimal:a.BaseDecimal[s],identifier:n};return new R({tax:l,value:b(r,c),identifier:i?n:_,decimal:i?8:c})}static fromIdentifierSync(n,r=0){const{chain:s,isSynthetic:i}=F(n),o=y.get(n);if(i)return de(n,r);const{tax:l,decimal:c,identifier:_}=o||{decimal:a.BaseDecimal[s],identifier:n};return new R({tax:l,decimal:c,identifier:_,value:b(r,c)})}static fromChainOrSignature(n,r=0){const{decimal:s,identifier:i}=Oe(n);return new R({value:b(r,s),decimal:s,identifier:i})}static loadStaticAssets(){return new Promise(async(n,r)=>{try{const s=await import("@swapkit/tokens");Object.values(s).forEach(i=>{var o;(o=i==null?void 0:i.tokens)==null||o.forEach(({identifier:l,chain:c,..._})=>{y.set(l.toUpperCase(),{identifier:l,decimal:"decimals"in _?_.decimals:a.BaseDecimal[c]})})}),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=R.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 Y(e,t=0){Pt(e);const n=y.get(e.toUpperCase()),r=(n==null?void 0:n.decimal)||await Ne(F(e));return n||y.set(e.toUpperCase(),{identifier:e,decimal:r}),new R({decimal:r,value:b(t,r),identifier:e})}function de(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 R({decimal:8,value:b(t,8),identifier:`${a.Chain.THORChain}.${n}/${r}`})}function b(e,t){return typeof e=="bigint"?B({value:e,bigIntDecimal:t,decimal:t}):e}function F(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("-"),_=t?r:o.join(".");return{address:c==null?void 0:c.toLowerCase(),chain:i,isGasAsset:re({chain:i,symbol:_}),isSynthetic:t,symbol:(t?`${n}/`:"")+(c?`${l}-${(c==null?void 0:c.toLowerCase())??""}`:_),ticker:l}}const wt={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_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,helpers_number_different_decimals:99101};class se 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:wt[t],message:t}}),Object.setPrototypeOf(this,se.prototype)}}class S extends V{eq(t){return this.eqValue(t)}static fromBigInt(t,n){return new S({decimal:n,value:B({value:t,bigIntDecimal:n,decimal:n})})}}exports.ApiEndpoints=m;exports.AssetValue=R;exports.BigIntArithmetics=V;exports.RequestClient=p;exports.StreamingSwapProgressStatus=fe;exports.SwapKitApi=lt;exports.SwapKitError=se;exports.SwapKitNumber=S;exports.TransactionType=Re;exports.TxStatus=Ie;exports.assetFromString=At;exports.defaultRequestHeaders=ne;exports.derivationPathToString=Dt;exports.filterAssets=St;exports.formatBigIntToSafeValue=B;exports.gasFeeMultiplier=Tt;exports.getAssetType=De;exports.getAsymmetricAssetShare=ye;exports.getAsymmetricAssetWithdrawAmount=Ct;exports.getAsymmetricRuneShare=Pe;exports.getAsymmetricRuneWithdrawAmount=Et;exports.getCommonAssetInfo=Oe;exports.getDecimal=Ne;exports.getEstimatedPoolShare=It;exports.getLiquiditySlippage=ft;exports.getMemoFor=gt;exports.getMinAmountByChain=bt;exports.getSymmetricPoolShare=be;exports.getSymmetricWithdraw=Rt;exports.getTHORNameCost=Nt;exports.isGasAsset=re;exports.setRequestClientConfig=ot;exports.validateTHORName=Ot;
2
2
  //# sourceMappingURL=index.cjs.map