@swapkit/helpers 1.0.0-rc.63 → 1.0.0-rc.64
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 +3 -6
- package/dist/index.es.js +788 -723
- package/dist/index.es.js.map +1 -1
- package/package.json +10 -10
- package/src/helpers/asset.ts +1 -2
- package/src/index.ts +2 -1
- package/src/helpers/request.ts +0 -15
package/dist/index.cjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
"use strict";var Te=Object.create;var N=Object.defineProperty;var $e=Object.getOwnPropertyDescriptor;var ve=Object.getOwnPropertyNames;var Se=Object.getPrototypeOf,Re=Object.prototype.hasOwnProperty;var Ie=(s,e,t)=>e in s?N(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t;var Be=(s,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of ve(e))!Re.call(s,r)&&r!==t&&N(s,r,{get:()=>e[r],enumerable:!(n=$e(e,r))||n.enumerable});return s};var Oe=(s,e,t)=>(t=s!=null?Te(Se(s)):{},Be(e||!s||!s.__esModule?N(t,"default",{value:s,enumerable:!0}):t,s));var p=(s,e,t)=>(Ie(s,typeof e!="symbol"?e+"":e,t),t),Me=(s,e,t)=>{if(!e.has(s))throw TypeError("Cannot "+t)};var w=(s,e,t)=>{if(e.has(s))throw TypeError("Cannot add the same private member more than once");e instanceof WeakSet?e.add(s):e.set(s,t)};var d=(s,e,t)=>(Me(s,e,"access private method"),t);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const i=require("@swapkit/types"),Ee="0x313ce567",re=async({chain:s,to:e})=>{try{const{result:t}=await _e.post(i.ChainToRPC[s],{headers:{accept:"*/*","content-type":"application/json","cache-control":"no-cache"},body:JSON.stringify({id:44,jsonrpc:"2.0",method:"eth_call",params:[{to:e.toLowerCase(),data:Ee},"latest"]})});return parseInt(BigInt(t).toString())}catch(t){return console.error(t),i.BaseDecimal[s]}},qe=async s=>{if(s===i.Chain.Ethereum)return i.BaseDecimal.ETH;const[,e]=s.split("-");return e!=null&&e.startsWith("0x")?re({chain:i.Chain.Ethereum,to:e}):i.BaseDecimal.ETH},xe=async s=>{const[,e]=s.split("-");return e!=null&&e.startsWith("0x")?re({chain:i.Chain.Avalanche,to:e.toLowerCase()}):i.BaseDecimal.AVAX},Pe=async s=>(s===i.Chain.BinanceSmartChain,i.BaseDecimal.BSC),ie=async({chain:s,symbol:e})=>{switch(s){case i.Chain.Ethereum:return qe(e);case i.Chain.Avalanche:return xe(e);case i.Chain.BinanceSmartChain:return Pe(e);default:return i.BaseDecimal[s]}},Ve={[i.FeeOption.Average]:1.2,[i.FeeOption.Fast]:1.5,[i.FeeOption.Fastest]:2},G=({chain:s,symbol:e})=>{switch(s){case i.Chain.Bitcoin:case i.Chain.BitcoinCash:case i.Chain.Litecoin:case i.Chain.Dogecoin:case i.Chain.Binance:case i.Chain.Ethereum:case i.Chain.Avalanche:return e===s;case i.Chain.Arbitrum:case i.Chain.Optimism:return e==="ETH";case i.Chain.Maya:return e==="CACAO";case i.Chain.Kujira:return e==="KUJI";case i.Chain.Cosmos:return e==="ATOM";case i.Chain.Polygon:return e==="MATIC";case i.Chain.BinanceSmartChain:return e==="BNB";case i.Chain.THORChain:return e==="RUNE"}},ae=s=>{switch(s){case`${i.Chain.Ethereum}.THOR`:return{identifier:"ETH.THOR-0xa5f2211b9b8170f694421f2046281775e8468044",decimal:18};case`${i.Chain.Ethereum}.vTHOR`:return{identifier:"ETH.vTHOR-0x815c23eca83261b6ec689b60cc4a58b54bc24d8d",decimal:18};case i.Chain.Cosmos:return{identifier:"GAIA.ATOM",decimal:i.BaseDecimal[s]};case i.Chain.THORChain:return{identifier:"THOR.RUNE",decimal:i.BaseDecimal[s]};case i.Chain.BinanceSmartChain:return{identifier:"BSC.BNB",decimal:i.BaseDecimal[s]};case i.Chain.Maya:return{identifier:"MAYA.CACAO",decimal:i.BaseDecimal.MAYA};case`${i.Chain.Maya}.MAYA`:return{identifier:"MAYA.MAYA",decimal:4};case`${i.Chain.Kujira}.USK`:return{identifier:`${i.Chain.Kujira}.USK`,decimal:6};case i.Chain.Kujira:case i.Chain.Arbitrum:case i.Chain.Optimism:case i.Chain.BitcoinCash:case i.Chain.Litecoin:case i.Chain.Dogecoin:case i.Chain.Binance:case i.Chain.Avalanche:case i.Chain.Polygon:case i.Chain.Bitcoin:case i.Chain.Ethereum:return{identifier:`${s}.${s}`,decimal:i.BaseDecimal[s]}}},oe=({chain:s,symbol:e})=>{if(e.includes("/"))return"Synth";switch(s){case i.Chain.Bitcoin:case i.Chain.BitcoinCash:case i.Chain.Dogecoin:case i.Chain.Litecoin:case i.Chain.Maya:case i.Chain.THORChain:return"Native";case i.Chain.Cosmos:return e==="ATOM"?"Native":i.Chain.Cosmos;case i.Chain.Kujira:return e===i.Chain.Kujira?"Native":i.Chain.Kujira;case i.Chain.Binance:return e===i.Chain.Binance?"Native":"BEP2";case i.Chain.BinanceSmartChain:return e===i.Chain.Binance?"Native":"BEP20";case i.Chain.Ethereum:return e===i.Chain.Ethereum?"Native":"ERC20";case i.Chain.Avalanche:return e===i.Chain.Avalanche?"Native":i.Chain.Avalanche;case i.Chain.Polygon:return e===i.Chain.Polygon?"Native":"POLYGON";case i.Chain.Arbitrum:return[i.Chain.Ethereum,i.Chain.Arbitrum].includes(e)?"Native":"ARBITRUM";case i.Chain.Optimism:return[i.Chain.Ethereum,i.Chain.Optimism].includes(e)?"Native":"OPTIMISM"}},ke=s=>{var c;const[e,...t]=s.split("."),n=s.includes("/"),r=t.join("."),a=(c=r==null?void 0:r.split("-"))==null?void 0:c[0];return{chain:e,symbol:r,ticker:a,synth:n}},De=new RegExp(/(.)\1{6}|\.ORG|\.NET|\.FINANCE|\.COM|WWW|HTTP|\\\\|\/\/|[\s$%:[\]]/,"gmi"),je=s=>{const[e,t]=s.split(".");if(!i.EVMChainList.includes(e))return!0;const[,n]=t.split("-");return G({chain:e,symbol:t})||!!n},Ne=s=>s.filter(e=>{const t=`${e.chain}.${e.symbol}`;return!De.test(t)&&je(t)&&e.value!=="0"});function ce({liquidityUnits:s,poolUnits:e,runeDepth:t}){const n=m(s),r=m(e),a=m(t),c=n.mul(a),o=r.mul(r).mul(2),u=r.mul(n).mul(2),l=n.mul(n),h=r.mul(r).mul(r);return c.mul(o.sub(u).add(l)).div(h)}function ue({liquidityUnits:s,poolUnits:e,assetDepth:t}){const n=m(s),r=m(e),a=m(t),c=n.mul(a),o=r.mul(r).mul(2),u=r.mul(n).mul(2),l=n.mul(n),h=c.mul(o.sub(u).add(l)),C=r.mul(r).mul(r);return h.div(C)}function He({percent:s,runeDepth:e,liquidityUnits:t,poolUnits:n}){return ce({runeDepth:e,liquidityUnits:t,poolUnits:n}).mul(s)}function Ue({percent:s,assetDepth:e,liquidityUnits:t,poolUnits:n}){return ue({assetDepth:e,liquidityUnits:t,poolUnits:n}).mul(s)}function m(s){return f.fromBigInt(BigInt(s),i.BaseDecimal.THOR)}function le({liquidityUnits:s,poolUnits:e,runeDepth:t,assetDepth:n}){return{assetAmount:m(n).mul(s).div(e),runeAmount:m(t).mul(s).div(e)}}function Le({liquidityUnits:s,poolUnits:e,runeDepth:t,assetDepth:n,percent:r}){return Object.fromEntries(Object.entries(le({liquidityUnits:s,poolUnits:e,runeDepth:t,assetDepth:n})).map(([a,c])=>[a,c.mul(r)]))}function Fe({runeDepth:s,poolUnits:e,assetDepth:t,liquidityUnits:n,runeAmount:r,assetAmount:a}){const c=new f({value:s,decimal:8}),o=new f({value:t,decimal:8}),u=new f({value:e,decimal:8}),l=new f({value:r,decimal:8}),h=new f({value:a,decimal:8}),C=l.mul(o),D=h.mul(c),ye=l.mul(h),be=c.mul(o),Ce=u.mul(C.add(D.add(ye.mul(2)))),we=C.add(D.add(be.mul(2))),Q=Ce.div(we),j=m(n).add(Q);if(Q.getBaseValue("number")===0)return j.div(u).getBaseValue("number");const Ae=u.add(j);return j.div(Ae).getBaseValue("number")}function We({runeAmount:s,assetAmount:e,runeDepth:t,assetDepth:n}){if(s==="0"||e==="0"||t==="0"||n==="0")return 0;const r=m(t),a=m(n),c=m(e),o=m(s),u=c.mul(r).sub(a.mul(o)),l=a.mul(o).add(r.mul(a));return Math.abs(u.div(l).getBaseValue("number"))}const Ke=(s,e)=>{switch(s){case i.MemoType.LEAVE:case i.MemoType.BOND:{const{address:t}=e;return`${s}:${t}`}case i.MemoType.UNBOND:{const{address:t,unbondAmount:n}=e;return`${s}:${t}:${n}`}case i.MemoType.THORNAME_REGISTER:{const{name:t,chain:n,address:r,owner:a}=e;return`${s}:${t}:${n}:${r}${a?`:${a}`:""}`}case i.MemoType.DEPOSIT:{const{chain:t,symbol:n,address:r,singleSide:a}=e;return a?`${s}:${t}/${n}::t:0`:`${s}:${((o,u)=>{switch(o){case i.Chain.Litecoin:return"l";case i.Chain.Dogecoin:return"d";case i.Chain.BitcoinCash:return"c";default:return`${o}.${u}`}})(t,n)}:${r||""}:t:0`}case i.MemoType.WITHDRAW:{const{chain:t,ticker:n,symbol:r,basisPoints:a,targetAssetString:c,singleSide:o}=e,u=t==="ETH"&&n!=="ETH"?`${n}-${r.slice(-3)}`:r,l=!o&&c?`:${c}`:"";return`${s}:${t}${o?"/":"."}${u}:${a}${l}`}case i.MemoType.OPEN_LOAN:case i.MemoType.CLOSE_LOAN:{const{asset:t,address:n}=e;return`${s}:${t}:${n}`}default:return""}};function Ge(s){if(s<0)throw new Error("Invalid number of year");return 10+s}function ze(s){if(s.length>30)return!1;const e=/^[a-zA-Z0-9+_-]+$/g;return!!s.match(e)}function Je([s,e,t,n,r]){return`${s}'/${e}'/${t}'/${n}${typeof r!="number"?"":`/${r}`}`}class X extends Error{constructor(e,t,n){const r=e.status||e.status===0?e.status:"",a=e.statusText||"",c=`${r} ${a}`.trim(),o=c?`status code ${c}`:"an unknown error";super(`Request failed with ${o}`),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=e,this.request=t,this.options=n}}class he extends Error{constructor(e){super("Request timed out"),Object.defineProperty(this,"request",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.name="TimeoutError",this.request=e}}const x=s=>s!==null&&typeof s=="object",E=(...s)=>{for(const e of s)if((!x(e)||Array.isArray(e))&&e!==void 0)throw new TypeError("The `options` argument must be an object");return z({},...s)},de=(s={},e={})=>{const t=new globalThis.Headers(s),n=e instanceof globalThis.Headers,r=new globalThis.Headers(e);for(const[a,c]of r.entries())n&&c==="undefined"||c===void 0?t.delete(a):t.set(a,c);return t},z=(...s)=>{let e={},t={};for(const n of s)if(Array.isArray(n))Array.isArray(e)||(e=[]),e=[...e,...n];else if(x(n)){for(let[r,a]of Object.entries(n))x(a)&&r in e&&(a=z(e[r],a)),e={...e,[r]:a};x(n.headers)&&(t=de(t,n.headers),e.headers=t)}return e},Ye=(()=>{let s=!1,e=!1;const t=typeof globalThis.ReadableStream=="function",n=typeof globalThis.Request=="function";return t&&n&&(e=new globalThis.Request("https://empty.invalid",{body:new globalThis.ReadableStream,method:"POST",get duplex(){return s=!0,"half"}}).headers.has("Content-Type")),s&&!e})(),Qe=typeof globalThis.AbortController=="function",Xe=typeof globalThis.ReadableStream=="function",Ze=typeof globalThis.FormData=="function",me=["get","post","put","patch","head","delete"],et={json:"application/json",text:"text/*",formData:"multipart/form-data",arrayBuffer:"*/*",blob:"*/*"},H=2147483647,pe=Symbol("stop"),tt={json:!0,parseJson:!0,searchParams:!0,prefixUrl:!0,retry:!0,timeout:!0,hooks:!0,throwHttpErrors:!0,onDownloadProgress:!0,fetch:!0},nt={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},st=s=>me.includes(s)?s.toUpperCase():s,rt=["get","put","head","delete","options","trace"],it=[408,413,429,500,502,503,504],fe=[413,429,503],Z={limit:2,methods:rt,statusCodes:it,afterStatusCodes:fe,maxRetryAfter:Number.POSITIVE_INFINITY,backoffLimit:Number.POSITIVE_INFINITY,delay:s=>.3*2**(s-1)*1e3},at=(s={})=>{if(typeof s=="number")return{...Z,limit:s};if(s.methods&&!Array.isArray(s.methods))throw new Error("retry.methods must be an array");if(s.statusCodes&&!Array.isArray(s.statusCodes))throw new Error("retry.statusCodes must be an array");return{...Z,...s,afterStatusCodes:fe}};async function ot(s,e,t,n){return new Promise((r,a)=>{const c=setTimeout(()=>{t&&t.abort(),a(new he(s))},n.timeout);n.fetch(s,e).then(r).catch(a).then(()=>{clearTimeout(c)})})}async function ct(s,{signal:e}){return new Promise((t,n)=>{e&&(e.throwIfAborted(),e.addEventListener("abort",r,{once:!0}));function r(){clearTimeout(a),n(e.reason)}const a=setTimeout(()=>{e==null||e.removeEventListener("abort",r),t()},s)})}const ut=(s,e)=>{const t={};for(const n in e)!(n in nt)&&!(n in tt)&&!(n in s)&&(t[n]=e[n]);return t};class V{static create(e,t){const n=new V(e,t),r=async()=>{if(typeof n._options.timeout=="number"&&n._options.timeout>H)throw new RangeError(`The \`timeout\` option cannot be greater than ${H}`);await Promise.resolve();let o=await n._fetch();for(const u of n._options.hooks.afterResponse){const l=await u(n.request,n._options,n._decorateResponse(o.clone()));l instanceof globalThis.Response&&(o=l)}if(n._decorateResponse(o),!o.ok&&n._options.throwHttpErrors){let u=new X(o,n.request,n._options);for(const l of n._options.hooks.beforeError)u=await l(u);throw u}if(n._options.onDownloadProgress){if(typeof n._options.onDownloadProgress!="function")throw new TypeError("The `onDownloadProgress` option must be a function");if(!Xe)throw new Error("Streams are not supported in your environment. `ReadableStream` is missing.");return n._stream(o.clone(),n._options.onDownloadProgress)}return o},c=n._options.retry.methods.includes(n.request.method.toLowerCase())?n._retry(r):r();for(const[o,u]of Object.entries(et))c[o]=async()=>{n.request.headers.set("accept",n.request.headers.get("accept")||u);const h=(await c).clone();if(o==="json"){if(h.status===204||(await h.clone().arrayBuffer()).byteLength===0)return"";if(t.parseJson)return t.parseJson(await h.text())}return h[o]()};return c}constructor(e,t={}){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=e,this._options={credentials:this._input.credentials||"same-origin",...t,headers:de(this._input.headers,t.headers),hooks:z({beforeRequest:[],beforeRetry:[],beforeError:[],afterResponse:[]},t.hooks),method:st(t.method??this._input.method),prefixUrl:String(t.prefixUrl||""),retry:at(t.retry),throwHttpErrors:t.throwHttpErrors!==!1,timeout:t.timeout??1e4,fetch:t.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(Qe){if(this.abortController=new globalThis.AbortController,this._options.signal){const n=this._options.signal;this._options.signal.addEventListener("abort",()=>{this.abortController.abort(n.reason)})}this._options.signal=this.abortController.signal}if(Ye&&(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()),a=this.request.url.replace(/(?:\?.*?)?(?=#|$)/,r);(Ze&&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(a,{...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(e){if(this._retryCount++,this._retryCount<this._options.retry.limit&&!(e instanceof he)){if(e instanceof X){if(!this._options.retry.statusCodes.includes(e.response.status))return 0;const n=e.response.headers.get("Retry-After");if(n&&this._options.retry.afterStatusCodes.includes(e.response.status)){let r=Number(n);return Number.isNaN(r)?r=Date.parse(n)-Date.now():r*=1e3,this._options.retry.maxRetryAfter!==void 0&&r>this._options.retry.maxRetryAfter?0:r}if(e.response.status===413)return 0}const t=this._options.retry.delay(this._retryCount);return Math.min(this._options.retry.backoffLimit,t)}return 0}_decorateResponse(e){return this._options.parseJson&&(e.json=async()=>this._options.parseJson(await e.text())),e}async _retry(e){try{return await e()}catch(t){const n=Math.min(this._calculateRetryDelay(t),H);if(n!==0&&this._retryCount>0){await ct(n,{signal:this._options.signal});for(const r of this._options.hooks.beforeRetry)if(await r({request:this.request,options:this._options,error:t,retryCount:this._retryCount})===pe)return;return this._retry(e)}throw t}}async _fetch(){for(const t of this._options.hooks.beforeRequest){const n=await t(this.request,this._options);if(n instanceof Request){this.request=n;break}if(n instanceof Response)return n}const e=ut(this.request,this._options);return this._options.timeout===!1?this._options.fetch(this.request.clone(),e):ot(this.request.clone(),e,this.abortController,this._options)}_stream(e,t){const n=Number(e.headers.get("content-length"))||0;let r=0;return e.status===204?(t&&t({percent:1,totalBytes:n,transferredBytes:r},new Uint8Array),new globalThis.Response(null,{status:e.status,statusText:e.statusText,headers:e.headers})):new globalThis.Response(new globalThis.ReadableStream({async start(a){const c=e.body.getReader();t&&t({percent:0,transferredBytes:0,totalBytes:n},new Uint8Array);async function o(){const{done:u,value:l}=await c.read();if(u){a.close();return}if(t){r+=l.byteLength;const h=n===0?0:r/n;t({percent:h,transferredBytes:r,totalBytes:n},l)}a.enqueue(l),await o()}await o()}}),{status:e.status,statusText:e.statusText,headers:e.headers})}}/*! MIT License © Sindre Sorhus */const L=s=>{const e=(t,n)=>V.create(t,E(s,n));for(const t of me)e[t]=(n,r)=>V.create(n,E(s,r,{method:t}));return e.create=t=>L(E(t)),e.extend=t=>L(E(s,t)),e.stop=pe,e},lt=L(),ht=lt,dt=typeof window<"u"?{}:{referrer:"https://sk.thorswap.net",referer:"https://sk.thorswap.net"},ee=ht.create({headers:dt}),_e={get:(s,e)=>ee.get(s,e).json(),post:(s,e)=>ee.post(s,e).json()},te=[...Object.values(i.Chain),"TERRA"];function mt(s=""){const e=s.toUpperCase(),[t]=e.split(".");if(te.includes(t))return!0;const[n]=e.split("/");if(te.includes(n))return!0;throw new Error(`Invalid identifier: ${s}. Expected format: <Chain>.<Ticker> or <Chain>.<Ticker>-<ContractAddress>`)}const R=8,y=s=>10n**BigInt(s),T=s=>Math.log10(parseFloat(s.toString()));function I({value:s,bigIntDecimal:e=R,decimal:t=R}){if(t===0)return s.toString();const n=s<0n;let r=s.toString().substring(n?1:0);const a=t-(r.length-1);a>0&&(r="0".repeat(a)+r);const c=r.length-t;let o=r.slice(-t);return parseInt(o[e])>=5?o=`${o.substring(0,e-1)}${(parseInt(o[e-1])+1).toString()}`:o=o.substring(0,e),`${n?"-":""}${r.slice(0,c)}.${o}`.replace(/\.?0*$/,"")}var b,$,_,A,k,ge,O,F,M,W;const Y=class Y{constructor(e){w(this,b);w(this,_);w(this,k);w(this,O);w(this,M);p(this,"decimalMultiplier",10n**8n);p(this,"bigIntValue",0n);p(this,"decimal");const t=K(e),n=typeof e=="object";this.decimal=n?e.decimal:void 0,this.decimalMultiplier=n&&"decimalMultiplier"in e?e.decimalMultiplier:y(Math.max(ne(q(t)),this.decimal||0)),d(this,k,ge).call(this,t)}static fromBigInt(e,t){return new Y({decimal:t,value:I({value:e,bigIntDecimal:t,decimal:t})})}static shiftDecimals({value:e,from:t,to:n}){return this.fromBigInt(e.getBaseValue("bigint")*y(n)/y(t),n)}set(e){return new this.constructor({decimal:this.decimal,value:e,identifier:this.toString()})}add(...e){return d(this,b,$).call(this,"add",...e)}sub(...e){return d(this,b,$).call(this,"sub",...e)}mul(...e){return d(this,b,$).call(this,"mul",...e)}div(...e){return d(this,b,$).call(this,"div",...e)}gt(e){return d(this,_,A).call(this,"gt",e)}gte(e){return d(this,_,A).call(this,"gte",e)}lt(e){return d(this,_,A).call(this,"lt",e)}lte(e){return d(this,_,A).call(this,"lte",e)}eqValue(e){return d(this,_,A).call(this,"eqValue",e)}getValue(e){const t=this.formatBigIntToSafeValue(this.bigIntValue,this.decimal||T(this.decimalMultiplier));switch(e){case"number":return Number(t);case"string":return t;case"bigint":return this.bigIntValue*10n**BigInt(this.decimal||8n)/this.decimalMultiplier}}getBaseValue(e){const t=this.decimalMultiplier/y(this.decimal||i.BaseDecimal.THOR),n=this.bigIntValue/t;switch(e){case"number":return Number(n);case"string":return n.toString();case"bigint":return n}}getBigIntValue(e,t){if(!t&&typeof e=="object")return e.bigIntValue;const n=K(e),r=q(n);return r==="0"||r==="undefined"?0n:d(this,M,W).call(this,r,t)}toSignificant(e=6){const[t,n]=this.getValue("string").split("."),r=t||"",a=n||"";if((parseInt(r)?r.length+a.length:a.length)<=e)return this.getValue("string");if(r.length>=e)return r.slice(0,e).padEnd(r.length,"0");if(parseInt(r))return`${r}.${a.slice(0,e-r.length)}`.padEnd(e-r.length,"0");const o=parseInt(a),u=`${o}`.slice(0,e);return`0.${u.padStart(a.length-`${o}`.length+u.length,"0")}`}toFixed(e=6){const[t,n]=this.getValue("string").split("."),r=t||"",a=n||"";if(parseInt(r))return`${r}.${a.slice(0,e)}`.padEnd(e,"0");const c=parseInt(a),o=`${c}`.slice(0,e);return`0.${o.padStart(a.length-`${c}`.length+o.length,"0")}`}toAbbreviation(e=2){const t=this.getValue("number"),n=["","K","M","B","T","Q","Qi","S"],r=Math.floor(Math.log10(Math.abs(t))/3),a=n[r];if(!a)return this.getValue("string");const c=10**(r*3);return`${(t/c).toFixed(e)}${a}`}toCurrency(e="$",{currencyPosition:t="start",decimal:n=2,decimalSeparator:r=".",thousandSeparator:a=","}={}){const c=this.getValue("number"),[o,u=""]=c.toFixed(6).split("."),l=o.replace(/\B(?=(\d{3})+(?!\d))/g,a),h=!o&&!u?"0.00":o==="0"?`${parseFloat(`0.${u}`)}`.replace(".",r):`${l}${parseInt(u)?`${r}${u.slice(0,n)}`:""}`;return`${t==="start"?e:""}${h}${t==="end"?e:""}`}formatBigIntToSafeValue(e,t){const n=t||this.decimal||R,r=Math.max(n,T(this.decimalMultiplier)),a=e<0n,c=e.toString().substring(a?1:0),o=r-(c.length-1),u=o>0?"0".repeat(o)+c:c,l=u.length-r;let h=u.slice(-r);return parseInt(h[n])>=5?h=`${h.substring(0,n-1)}${(parseInt(h[n-1])+1).toString()}`:h=h.substring(0,n),`${a?"-":""}${u.slice(0,l)}.${h}`.replace(/\.?0*$/,"")}};b=new WeakSet,$=function(e,...t){const n=d(this,O,F).call(this,this,...t),r=Math.max(n,T(this.decimalMultiplier)),a=y(r),c=t.reduce((u,l)=>{const h=this.getBigIntValue(l,r);switch(e){case"add":return u+h;case"sub":return u-h;case"mul":return u*h/a;case"div":{if(h===0n)throw new RangeError("Division by zero");return u*a/h}default:return u}},this.bigIntValue*a/this.decimalMultiplier),o=I({bigIntDecimal:r,decimal:r,value:c});return new this.constructor({decimalMultiplier:y(r),decimal:this.decimal,value:o,identifier:this.toString()})},_=new WeakSet,A=function(e,...t){const n=d(this,O,F).call(this,this,...t),r=this.getBigIntValue(t[0],n),a=this.getBigIntValue(this,n);switch(e){case"gt":return a>r;case"gte":return a>=r;case"lt":return a<r;case"lte":return a<=r;case"eqValue":return a===r}},k=new WeakSet,ge=function(e){const t=q(e)||"0";this.bigIntValue=d(this,M,W).call(this,t)},O=new WeakSet,F=function(...e){const t=e.map(n=>typeof n=="object"?n.decimal||T(n.decimalMultiplier):ne(q(n))).filter(Boolean);return Math.max(...t,R)},M=new WeakSet,W=function(e,t){const n=t?y(t):this.decimalMultiplier,r=T(n),[a="",c=""]=e.split(".");return BigInt(`${a}${c.padEnd(r,"0")}`)};let B=Y;const pt=Intl.NumberFormat("fullwide",{useGrouping:!1,maximumFractionDigits:20});function q(s){const t=`${typeof s=="number"?pt.format(s):K(s)}`.replaceAll(",",".").split(".");return t.length>1?`${t.slice(0,-1).join("")}.${t.at(-1)}`:t[0]}function ne(s){var t;const e=((t=s.split(".")[1])==null?void 0:t.length)||0;return Math.max(e,R)}function K(s){return typeof s=="object"?"getValue"in s?s.getValue("string"):s.value:s}const v=new Map;class g extends B{constructor({value:t,decimal:n,tax:r,chain:a,symbol:c,identifier:o}){super(typeof t=="object"?t:{decimal:n,value:t});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 u=P(o||`${a}.${c}`);this.type=oe(u),this.tax=r,this.chain=u.chain,this.ticker=u.ticker,this.symbol=u.symbol,this.address=u.address,this.isSynthetic=u.isSynthetic,this.isGasAsset=u.isGasAsset}toString(){return this.isSynthetic?this.symbol:`${this.chain}.${this.symbol}`}toUrl(){return this.isSynthetic?`${this.chain}.${this.symbol.replace("/",".")}`:this.toString()}eq({chain:t,symbol:n}){return this.chain===t&&this.symbol===n}chainId(){return i.ChainToChainId[this.chain]}static fromUrl(t,n=0){const[r,a,c]=t.split(".");if(!r||!a)throw new Error("Invalid asset url");const o=r===i.Chain.THORChain&&c?`${r}.${a}/${c}`:t;return U(o,n)}static fromString(t,n=0){return U(t,n)}static fromIdentifier(t,n=0){return U(t,n)}static fromStringSync(t,n=0){const{chain:r,isSynthetic:a}=P(t),c=v.get(t.toUpperCase());if(a)return se(t,n);const{tax:o,decimal:u,identifier:l}=c||{decimal:i.BaseDecimal[r],identifier:t};return new g({tax:o,value:S(n,u),identifier:a?t:l,decimal:a?8:u})}static fromIdentifierSync(t,n=0){const{chain:r,isSynthetic:a}=P(t),c=v.get(t);if(a)return se(t,n);const{tax:o,decimal:u,identifier:l}=c||{decimal:i.BaseDecimal[r],identifier:t};return new g({tax:o,decimal:u,identifier:l,value:S(n,u)})}static fromChainOrSignature(t,n=0){const{decimal:r,identifier:a}=ae(t);return new g({value:S(n,r),decimal:r,identifier:a})}static loadStaticAssets(){return new Promise(async(t,n)=>{try{const r=await import("@swapkit/tokens");Object.values(r).forEach(a=>{var c;(c=a==null?void 0:a.tokens)==null||c.forEach(({identifier:o,chain:u,...l})=>{v.set(o.toUpperCase(),{identifier:o,decimal:"decimals"in l?l.decimals:i.BaseDecimal[u]})})}),t({ok:!0})}catch(r){console.error(r),n({ok:!1,error:r,message:"Couldn't load static assets. Ensure you have installed @swapkit/tokens package"})}})}}function ft(s){const e=g.fromChainOrSignature(s);switch(s){case i.Chain.Bitcoin:case i.Chain.Litecoin:case i.Chain.BitcoinCash:return e.set(10001e-8);case i.Chain.Dogecoin:return e.set(1.00000001);case i.Chain.Avalanche:case i.Chain.Ethereum:return e.set(1e-8);case i.Chain.THORChain:case i.Chain.Maya:return e.set(0);case i.Chain.Cosmos:return e.set(1e-6);default:return e.set(1e-8)}}async function U(s,e=0){mt(s);const t=v.get(s.toUpperCase()),n=(t==null?void 0:t.decimal)||await ie(P(s));return t||v.set(s.toUpperCase(),{identifier:s,decimal:n}),new g({decimal:n,value:S(e,n),identifier:s})}function se(s,e=0){const[t,n]=s.split(".")[0].toUpperCase()===i.Chain.THORChain?s.split(".").slice(1).join().split("/"):s.split("/");if(!t||!n)throw new Error("Invalid asset identifier");return new g({decimal:8,value:S(e,8),identifier:`${i.Chain.THORChain}.${t}/${n}`})}function S(s,e){return typeof s=="bigint"?I({value:s,bigIntDecimal:e,decimal:e}):s}function P(s){const e=s.slice(0,14).includes("/"),[t,n]=s.split(".")[0].toUpperCase()===i.Chain.THORChain?s.split(".").slice(1).join().split("/"):s.split("/");if(e&&(!t||!n))throw new Error("Invalid asset identifier");const r=s.includes(".")&&!e?s:`${i.Chain.THORChain}.${n}`,[a,c]=r.split("."),[o,u]=(e?n:c).split("-");return{address:u==null?void 0:u.toLowerCase(),chain:a,isGasAsset:G({chain:a,symbol:c}),isSynthetic:e,symbol:(e?`${t}/`:"")+(u?`${o}-${(u==null?void 0:u.toLowerCase())??""}`:c),ticker:o}}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_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:10313,wallet_ledger_connection_error:20001,helpers_number_different_decimals:99101};class J extends Error{constructor(e,t){console.error(t,{stack:t==null?void 0:t.stack,message:t==null?void 0:t.message}),super(e,{cause:{code:_t[e],message:e}}),Object.setPrototypeOf(this,J.prototype)}}class f extends B{eq(e){return this.eqValue(e)}static fromBigInt(e,t){return new f({decimal:t,value:I({value:e,bigIntDecimal:t,decimal:t})})}}exports.AssetValue=g;exports.BigIntArithmetics=B;exports.RequestClient=_e;exports.SwapKitError=J;exports.SwapKitNumber=f;exports.assetFromString=ke;exports.derivationPathToString=Je;exports.filterAssets=Ne;exports.formatBigIntToSafeValue=I;exports.gasFeeMultiplier=Ve;exports.getAssetType=oe;exports.getAsymmetricAssetShare=ue;exports.getAsymmetricAssetWithdrawAmount=Ue;exports.getAsymmetricRuneShare=ce;exports.getAsymmetricRuneWithdrawAmount=He;exports.getCommonAssetInfo=ae;exports.getDecimal=ie;exports.getEstimatedPoolShare=Fe;exports.getLiquiditySlippage=We;exports.getMemoFor=Ke;exports.getMinAmountByChain=ft;exports.getSymmetricPoolShare=le;exports.getSymmetricWithdraw=Le;exports.getTHORNameCost=Ge;exports.isGasAsset=G;exports.validateTHORName=ze;
|
|
1
|
+
"use strict";var ve=Object.create;var j=Object.defineProperty;var $e=Object.getOwnPropertyDescriptor;var He=Object.getOwnPropertyNames;var Fe=Object.getPrototypeOf,Ge=Object.prototype.hasOwnProperty;var xe=(e,t,n)=>t in e?j(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n;var We=(e,t,n,s)=>{if(t&&typeof t=="object"||typeof t=="function")for(let r of He(t))!Ge.call(e,r)&&r!==n&&j(e,r,{get:()=>t[r],enumerable:!(s=$e(t,r))||s.enumerable});return e};var qe=(e,t,n)=>(n=e!=null?ve(Fe(e)):{},We(t||!e||!e.__esModule?j(n,"default",{value:e,enumerable:!0}):n,e));var A=(e,t,n)=>(xe(e,typeof t!="symbol"?t+"":t,n),n),ke=(e,t,n)=>{if(!t.has(e))throw TypeError("Cannot "+n)};var f=(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)=>(ke(e,t,"access private method"),n);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const i=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.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.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 W=(e=>(e.Arbitrum="ARB",e.Avalanche="AVAX",e.Binance="BNB",e.BinanceSmartChain="BSC",e.Bitcoin="BTC",e.BitcoinCash="BCH",e.Cosmos="GAIA",e.Dogecoin="DOGE",e.Ethereum="ETH",e.Kujira="KUJI",e.Litecoin="LTC",e.Maya="MAYA",e.Optimism="OP",e.Polygon="MATIC",e.THORChain="THOR",e))(W||{}),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.Cosmos="cosmoshub-4",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.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.Cosmos="https://node-router.thorswap.net/cosmos/rpc",e.Kujira="https://rpc-kujira.synergynodes.com/",e.Dogecoin="https://node-router.thorswap.net/dogecoin",e.Ethereum="https://node-router.thorswap.net/ethereum",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.Polygon="https://polygon-rpc.com",e.THORChain="https://rpc.thorswap.net",e.THORChainStagenet="https://stagenet-rpc.ninerealms.com",e))(Te||{}),C=(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))(C||{});const q=Object.values(W),je=Object.keys(W),ee=q.reduce((e,t)=>{const n=je.find(s=>W[s]===t);return n&&(e[t]=n),e},{});q.reduce((e,t)=>(e[t]=Z[ee[t]],e),{});q.reduce((e,t)=>(e[t]=Te[ee[t]],e),{});q.reduce((e,t)=>{const n=`${ee[t]}Hex`;return e[t]=Z[n],e},{});class ce extends Error{constructor(t,n,s){const r=t.status||t.status===0?t.status:"",a=t.statusText||"",o=`${r} ${a}`.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=s}}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",U=(...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),s=t instanceof globalThis.Headers,r=new globalThis.Headers(t);for(const[a,o]of r.entries())s&&o==="undefined"||o===void 0?n.delete(a):n.set(a,o);return n},te=(...e)=>{let t={},n={};for(const s of e)if(Array.isArray(s))Array.isArray(t)||(t=[]),t=[...t,...s];else if($(s)){for(let[r,a]of Object.entries(s))$(a)&&r in t&&(a=te(t[r],a)),t={...t,[r]:a};$(s.headers)&&(n=pe(n,s.headers),t.headers=n)}return t},Xe=(()=>{let e=!1,t=!1;const n=typeof globalThis.ReadableStream=="function",s=typeof globalThis.Request=="function";return n&&s&&(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],Ce=[413,429,503],le={limit:2,methods:tt,statusCodes:nt,afterStatusCodes:Ce,maxRetryAfter:Number.POSITIVE_INFINITY,backoffLimit:Number.POSITIVE_INFINITY,delay:e=>.3*2**(e-1)*1e3},st=(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:Ce}};async function rt(e,t,n,s){return new Promise((r,a)=>{const o=setTimeout(()=>{n&&n.abort(),a(new Ae(e))},s.timeout);s.fetch(e,t).then(r).catch(a).then(()=>{clearTimeout(o)})})}async function it(e,{signal:t}){return new Promise((n,s)=>{t&&(t.throwIfAborted(),t.addEventListener("abort",r,{once:!0}));function r(){clearTimeout(a),s(t.reason)}const a=setTimeout(()=>{t==null||t.removeEventListener("abort",r),n()},e)})}const at=(e,t)=>{const n={};for(const s in t)!(s in Ze)&&!(s in ze)&&!(s in e)&&(n[s]=t[s]);return n};class G{static create(t,n){const s=new G(t,n),r=async()=>{if(typeof s._options.timeout=="number"&&s._options.timeout>X)throw new RangeError(`The \`timeout\` option cannot be greater than ${X}`);await Promise.resolve();let o=await s._fetch();for(const l of s._options.hooks.afterResponse){const c=await l(s.request,s._options,s._decorateResponse(o.clone()));c instanceof globalThis.Response&&(o=c)}if(s._decorateResponse(o),!o.ok&&s._options.throwHttpErrors){let l=new ce(o,s.request,s._options);for(const c of s._options.hooks.beforeError)l=await c(l);throw l}if(s._options.onDownloadProgress){if(typeof s._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 s._stream(o.clone(),s._options.onDownloadProgress)}return o},a=s._options.retry.methods.includes(s.request.method.toLowerCase())?s._retry(r):r();for(const[o,l]of Object.entries(Qe))a[o]=async()=>{s.request.headers.set("accept",s.request.headers.get("accept")||l);const c=(await a).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 a}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:st(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 s=this._options.signal;this._options.signal.addEventListener("abort",()=>{this.abortController.abort(s.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 s="?"+(typeof this._options.searchParams=="string"?this._options.searchParams.replace(/^\?/,""):new URLSearchParams(this._options.searchParams).toString()),r=this.request.url.replace(/(?:\?.*?)?(?=#|$)/,s);(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(r,{...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 s=t.response.headers.get("Retry-After");if(s&&this._options.retry.afterStatusCodes.includes(t.response.status)){let r=Number(s);return Number.isNaN(r)?r=Date.parse(s)-Date.now():r*=1e3,this._options.retry.maxRetryAfter!==void 0&&r>this._options.retry.maxRetryAfter?0:r}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 s=Math.min(this._calculateRetryDelay(n),X);if(s!==0&&this._retryCount>0){await it(s,{signal:this._options.signal});for(const r of this._options.hooks.beforeRetry)if(await r({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 s=await n(this.request,this._options);if(s instanceof Request){this.request=s;break}if(s instanceof Response)return s}const t=at(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 s=Number(t.headers.get("content-length"))||0;let r=0;return t.status===204?(n&&n({percent:1,totalBytes:s,transferredBytes:r},new Uint8Array),new globalThis.Response(null,{status:t.status,statusText:t.statusText,headers:t.headers})):new globalThis.Response(new globalThis.ReadableStream({async start(a){const o=t.body.getReader();n&&n({percent:0,transferredBytes:0,totalBytes:s},new Uint8Array);async function l(){const{done:c,value:h}=await o.read();if(c){a.close();return}if(n){r+=h.byteLength;const _=s===0?0:r/s;n({percent:_,transferredBytes:r,totalBytes:s},h)}a.enqueue(h),await l()}await l()}}),{status:t.status,statusText:t.statusText,headers:t.headers})}}/*! MIT License © Sindre Sorhus */const K=e=>{const t=(n,s)=>G.create(n,U(e,s));for(const n of me)t[n]=(s,r)=>G.create(s,U(e,r,{method:n}));return t.create=n=>K(U(n)),t.extend=n=>K(U(e,n)),t.stop=Se,t},Ee=K();let H;const m={CachedPrices:`${C.ThorswapApi}/tokenlist/cached-price`,GasRates:`${C.ThorswapApi}/resource-worker/gasPrice/getAll`,Quote:`${C.ThorswapApi}/aggregator/tokens/quote`,Txn:`${C.ThorswapApi}/apiusage/v2/txn`,TokenlistProviders:`${C.ThorswapApi}/tokenlist/providers`,TokenList:`${C.ThorswapStatic}/token-list`,Thorname:`${C.ThorswapApi}/thorname`},ne=typeof window<"u"?{}:{referrer:"https://sk.thorswap.net",referer:"https://sk.thorswap.net"},ue=()=>H||(H=Ee.create({headers:ne}),H),ot=({apiKey:e,...t})=>{H=Ee.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((s,r,a)=>a.findIndex(o=>o===s)===r).forEach(s=>n.append("tokens",JSON.stringify(s))),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||{}),ge=(e=>(e[e.NOT_STARTED=0]="NOT_STARTED",e[e.SUCCESS=1]="SUCCESS",e[e.REFUNDED=2]="REFUNDED",e))(ge||{});const ut="0x313ce567",fe=async({chain:e,to:t})=>{try{const{result:n}=await p.post(i.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),i.BaseDecimal[e]}},ht=async e=>{if(e===i.Chain.Ethereum)return i.BaseDecimal.ETH;const[,t]=e.split("-");return t!=null&&t.startsWith("0x")?fe({chain:i.Chain.Ethereum,to:t}):i.BaseDecimal.ETH},_t=async e=>{const[,t]=e.split("-");return t!=null&&t.startsWith("0x")?fe({chain:i.Chain.Avalanche,to:t.toLowerCase()}):i.BaseDecimal.AVAX},dt=async e=>(e===i.Chain.BinanceSmartChain,i.BaseDecimal.BSC),Ne=async({chain:e,symbol:t})=>{switch(e){case i.Chain.Ethereum:return ht(t);case i.Chain.Avalanche:return _t(t);case i.Chain.BinanceSmartChain:return dt(t);default:return i.BaseDecimal[e]}},Tt={[i.FeeOption.Average]:1.2,[i.FeeOption.Fast]:1.5,[i.FeeOption.Fastest]:2},se=({chain:e,symbol:t})=>{switch(e){case i.Chain.Bitcoin:case i.Chain.BitcoinCash:case i.Chain.Litecoin:case i.Chain.Dogecoin:case i.Chain.Binance:case i.Chain.Ethereum:case i.Chain.Avalanche:return t===e;case i.Chain.Arbitrum:case i.Chain.Optimism:return t==="ETH";case i.Chain.Maya:return t==="CACAO";case i.Chain.Kujira:return t==="KUJI";case i.Chain.Cosmos:return t==="ATOM";case i.Chain.Polygon:return t==="MATIC";case i.Chain.BinanceSmartChain:return t==="BNB";case i.Chain.THORChain:return t==="RUNE"}},Oe=e=>{switch(e){case`${i.Chain.Ethereum}.THOR`:return{identifier:"ETH.THOR-0xa5f2211b9b8170f694421f2046281775e8468044",decimal:18};case`${i.Chain.Ethereum}.vTHOR`:return{identifier:"ETH.vTHOR-0x815c23eca83261b6ec689b60cc4a58b54bc24d8d",decimal:18};case i.Chain.Cosmos:return{identifier:"GAIA.ATOM",decimal:i.BaseDecimal[e]};case i.Chain.THORChain:return{identifier:"THOR.RUNE",decimal:i.BaseDecimal[e]};case i.Chain.BinanceSmartChain:return{identifier:"BSC.BNB",decimal:i.BaseDecimal[e]};case i.Chain.Maya:return{identifier:"MAYA.CACAO",decimal:i.BaseDecimal.MAYA};case`${i.Chain.Maya}.MAYA`:return{identifier:"MAYA.MAYA",decimal:4};case`${i.Chain.Kujira}.USK`:return{identifier:`${i.Chain.Kujira}.USK`,decimal:6};case i.Chain.Kujira:case i.Chain.Arbitrum:case i.Chain.Optimism:case i.Chain.BitcoinCash:case i.Chain.Litecoin:case i.Chain.Dogecoin:case i.Chain.Binance:case i.Chain.Avalanche:case i.Chain.Polygon:case i.Chain.Bitcoin:case i.Chain.Ethereum:return{identifier:`${e}.${e}`,decimal:i.BaseDecimal[e]}}},De=({chain:e,symbol:t})=>{if(t.includes("/"))return"Synth";switch(e){case i.Chain.Bitcoin:case i.Chain.BitcoinCash:case i.Chain.Dogecoin:case i.Chain.Litecoin:case i.Chain.Maya:case i.Chain.THORChain:return"Native";case i.Chain.Cosmos:return t==="ATOM"?"Native":i.Chain.Cosmos;case i.Chain.Kujira:return t===i.Chain.Kujira?"Native":i.Chain.Kujira;case i.Chain.Binance:return t===i.Chain.Binance?"Native":"BEP2";case i.Chain.BinanceSmartChain:return t===i.Chain.Binance?"Native":"BEP20";case i.Chain.Ethereum:return t===i.Chain.Ethereum?"Native":"ERC20";case i.Chain.Avalanche:return t===i.Chain.Avalanche?"Native":i.Chain.Avalanche;case i.Chain.Polygon:return t===i.Chain.Polygon?"Native":"POLYGON";case i.Chain.Arbitrum:return[i.Chain.Ethereum,i.Chain.Arbitrum].includes(t)?"Native":"ARBITRUM";case i.Chain.Optimism:return[i.Chain.Ethereum,i.Chain.Optimism].includes(t)?"Native":"OPTIMISM"}},At=e=>{var o;const[t,...n]=e.split("."),s=e.includes("/"),r=n.join("."),a=(o=r==null?void 0:r.split("-"))==null?void 0:o[0];return{chain:t,symbol:r,ticker:a,synth:s}},pt=new RegExp(/(.)\1{6}|\.ORG|\.NET|\.FINANCE|\.COM|WWW|HTTP|\\\\|\/\/|[\s$%:[\]]/,"gmi"),mt=e=>{const[t,n]=e.split(".");if(!i.EVMChainList.includes(t))return!0;const[,s]=n.split("-");return se({chain:t,symbol:n})||!!s},St=e=>e.filter(t=>{const n=`${t.chain}.${t.symbol}`;return!pt.test(n)&&mt(n)&&t.value!=="0"});function ye({liquidityUnits:e,poolUnits:t,runeDepth:n}){const s=T(e),r=T(t),a=T(n),o=s.mul(a),l=r.mul(r).mul(2),c=r.mul(s).mul(2),h=s.mul(s),_=r.mul(r).mul(r);return o.mul(l.sub(c).add(h)).div(_)}function Pe({liquidityUnits:e,poolUnits:t,assetDepth:n}){const s=T(e),r=T(t),a=T(n),o=s.mul(a),l=r.mul(r).mul(2),c=r.mul(s).mul(2),h=s.mul(s),_=o.mul(l.sub(c).add(h)),O=r.mul(r).mul(r);return _.div(O)}function Ct({percent:e,runeDepth:t,liquidityUnits:n,poolUnits:s}){return ye({runeDepth:t,liquidityUnits:n,poolUnits:s}).mul(e)}function Et({percent:e,assetDepth:t,liquidityUnits:n,poolUnits:s}){return Pe({assetDepth:t,liquidityUnits:n,poolUnits:s}).mul(e)}function T(e){return S.fromBigInt(BigInt(e),i.BaseDecimal.THOR)}function be({liquidityUnits:e,poolUnits:t,runeDepth:n,assetDepth:s}){return{assetAmount:T(s).mul(e).div(t),runeAmount:T(n).mul(e).div(t)}}function Rt({liquidityUnits:e,poolUnits:t,runeDepth:n,assetDepth:s,percent:r}){return Object.fromEntries(Object.entries(be({liquidityUnits:e,poolUnits:t,runeDepth:n,assetDepth:s})).map(([a,o])=>[a,o.mul(r)]))}function It({runeDepth:e,poolUnits:t,assetDepth:n,liquidityUnits:s,runeAmount:r,assetAmount:a}){const o=new S({value:e,decimal:8}),l=new S({value:n,decimal:8}),c=new S({value:t,decimal:8}),h=new S({value:r,decimal:8}),_=new S({value:a,decimal:8}),O=h.mul(l),ae=_.mul(o),Be=h.mul(_),Ve=o.mul(l),Me=c.mul(O.add(ae.add(Be.mul(2)))),Le=O.add(ae.add(Ve.mul(2))),oe=Me.div(Le),k=T(s).add(oe);if(oe.getBaseValue("number")===0)return k.div(c).getBaseValue("number");const Ue=c.add(k);return k.div(Ue).getBaseValue("number")}function gt({runeAmount:e,assetAmount:t,runeDepth:n,assetDepth:s}){if(e==="0"||t==="0"||n==="0"||s==="0")return 0;const r=T(n),a=T(s),o=T(t),l=T(e),c=o.mul(r).sub(a.mul(l)),h=a.mul(l).add(r.mul(a));return Math.abs(c.div(h).getBaseValue("number"))}const ft=(e,t)=>{switch(e){case i.MemoType.LEAVE:case i.MemoType.BOND:{const{address:n}=t;return`${e}:${n}`}case i.MemoType.UNBOND:{const{address:n,unbondAmount:s}=t;return`${e}:${n}:${s}`}case i.MemoType.THORNAME_REGISTER:{const{name:n,chain:s,address:r,owner:a}=t;return`${e}:${n}:${s}:${r}${a?`:${a}`:""}`}case i.MemoType.DEPOSIT:{const{chain:n,symbol:s,address:r,singleSide:a}=t;return a?`${e}:${n}/${s}::t:0`:`${e}:${((l,c)=>{switch(l){case i.Chain.Litecoin:return"l";case i.Chain.Dogecoin:return"d";case i.Chain.BitcoinCash:return"c";default:return`${l}.${c}`}})(n,s)}:${r||""}:t:0`}case i.MemoType.WITHDRAW:{const{chain:n,ticker:s,symbol:r,basisPoints:a,targetAssetString:o,singleSide:l}=t,c=n==="ETH"&&s!=="ETH"?`${s}-${r.slice(-3)}`:r,h=!l&&o?`:${o}`:"";return`${e}:${n}${l?"/":"."}${c}:${a}${h}`}case i.MemoType.OPEN_LOAN:case i.MemoType.CLOSE_LOAN:{const{asset:n,address:s}=t;return`${e}:${n}:${s}`}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,s,r]){return`${e}'/${t}'/${n}'/${s}${typeof r!="number"?"":`/${r}`}`}const he=[...Object.values(i.Chain),"TERRA"];function yt(e=""){const t=e.toUpperCase(),[n]=t.split(".");if(he.includes(n))return!0;const[s]=t.split("/");if(he.includes(s))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 s=e<0n;let r=e.toString().substring(s?1:0);const a=n-(r.length-1);a>0&&(r="0".repeat(a)+r);const o=r.length-n;let l=r.slice(-n);return parseInt(l[t])>=5?l=`${l.substring(0,t-1)}${(parseInt(l[t-1])+1).toString()}`:l=l.substring(0,t),`${s?"-":""}${r.slice(0,o)}.${l}`.replace(/\.?0*$/,"")}var g,y,E,N,x,we,M,J,L,Q;const ie=class ie{constructor(t){f(this,g);f(this,E);f(this,x);f(this,M);f(this,L);A(this,"decimalMultiplier",10n**8n);A(this,"bigIntValue",0n);A(this,"decimal");const n=z(t),s=typeof t=="object";this.decimal=s?t.decimal:void 0,this.decimalMultiplier=s&&"decimalMultiplier"in t?t.decimalMultiplier:I(Math.max(_e(v(n)),this.decimal||0)),d(this,x,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:s}){return this.fromBigInt(t.getBaseValue("bigint")*I(s)/I(n),s)}set(t){return new this.constructor({decimal:this.decimal,value:t,identifier:this.toString()})}add(...t){return d(this,g,y).call(this,"add",...t)}sub(...t){return d(this,g,y).call(this,"sub",...t)}mul(...t){return d(this,g,y).call(this,"mul",...t)}div(...t){return d(this,g,y).call(this,"div",...t)}gt(t){return d(this,E,N).call(this,"gt",t)}gte(t){return d(this,E,N).call(this,"gte",t)}lt(t){return d(this,E,N).call(this,"lt",t)}lte(t){return d(this,E,N).call(this,"lte",t)}eqValue(t){return d(this,E,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||i.BaseDecimal.THOR),s=this.bigIntValue/n;switch(t){case"number":return Number(s);case"string":return s.toString();case"bigint":return s}}getBigIntValue(t,n){if(!n&&typeof t=="object")return t.bigIntValue;const s=z(t),r=v(s);return r==="0"||r==="undefined"?0n:d(this,L,Q).call(this,r,n)}toSignificant(t=6){const[n,s]=this.getValue("string").split("."),r=n||"",a=s||"";if((parseInt(r)?r.length+a.length:a.length)<=t)return this.getValue("string");if(r.length>=t)return r.slice(0,t).padEnd(r.length,"0");if(parseInt(r))return`${r}.${a.slice(0,t-r.length)}`.padEnd(t-r.length,"0");const l=parseInt(a),c=`${l}`.slice(0,t);return`0.${c.padStart(a.length-`${l}`.length+c.length,"0")}`}toFixed(t=6){const[n,s]=this.getValue("string").split("."),r=n||"",a=s||"";if(parseInt(r))return`${r}.${a.slice(0,t)}`.padEnd(t,"0");const o=parseInt(a),l=`${o}`.slice(0,t);return`0.${l.padStart(a.length-`${o}`.length+l.length,"0")}`}toAbbreviation(t=2){const n=this.getValue("number"),s=["","K","M","B","T","Q","Qi","S"],r=Math.floor(Math.log10(Math.abs(n))/3),a=s[r];if(!a)return this.getValue("string");const o=10**(r*3);return`${(n/o).toFixed(t)}${a}`}toCurrency(t="$",{currencyPosition:n="start",decimal:s=2,decimalSeparator:r=".",thousandSeparator:a=","}={}){const o=this.getValue("number"),[l,c=""]=o.toFixed(6).split("."),h=l.replace(/\B(?=(\d{3})+(?!\d))/g,a),_=!l&&!c?"0.00":l==="0"?`${parseFloat(`0.${c}`)}`.replace(".",r):`${h}${parseInt(c)?`${r}${c.slice(0,s)}`:""}`;return`${n==="start"?t:""}${_}${n==="end"?t:""}`}formatBigIntToSafeValue(t,n){const s=n||this.decimal||w,r=Math.max(s,D(this.decimalMultiplier)),a=t<0n,o=t.toString().substring(a?1:0),l=r-(o.length-1),c=l>0?"0".repeat(l)+o:o,h=c.length-r;let _=c.slice(-r);return parseInt(_[s])>=5?_=`${_.substring(0,s-1)}${(parseInt(_[s-1])+1).toString()}`:_=_.substring(0,s),`${a?"-":""}${c.slice(0,h)}.${_}`.replace(/\.?0*$/,"")}};g=new WeakSet,y=function(t,...n){const s=d(this,M,J).call(this,this,...n),r=Math.max(s,D(this.decimalMultiplier)),a=I(r),o=n.reduce((c,h)=>{const _=this.getBigIntValue(h,r);switch(t){case"add":return c+_;case"sub":return c-_;case"mul":return c*_/a;case"div":{if(_===0n)throw new RangeError("Division by zero");return c*a/_}default:return c}},this.bigIntValue*a/this.decimalMultiplier),l=B({bigIntDecimal:r,decimal:r,value:o});return new this.constructor({decimalMultiplier:I(r),decimal:this.decimal,value:l,identifier:this.toString()})},E=new WeakSet,N=function(t,...n){const s=d(this,M,J).call(this,this,...n),r=this.getBigIntValue(n[0],s),a=this.getBigIntValue(this,s);switch(t){case"gt":return a>r;case"gte":return a>=r;case"lt":return a<r;case"lte":return a<=r;case"eqValue":return a===r}},x=new WeakSet,we=function(t){const n=v(t)||"0";this.bigIntValue=d(this,L,Q).call(this,n)},M=new WeakSet,J=function(...t){const n=t.map(s=>typeof s=="object"?s.decimal||D(s.decimalMultiplier):_e(v(s))).filter(Boolean);return Math.max(...n,w)},L=new WeakSet,Q=function(t,n){const s=n?I(n):this.decimalMultiplier,r=D(s),[a="",o=""]=t.split(".");return BigInt(`${a}${o.padEnd(r,"0")}`)};let V=ie;const Pt=Intl.NumberFormat("fullwide",{useGrouping:!1,maximumFractionDigits:20});function v(e){const n=`${typeof e=="number"?Pt.format(e):z(e)}`.replaceAll(",",".").split(".");return n.length>1?`${n.slice(0,-1).join("")}.${n.at(-1)}`:n[0]}function _e(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 P=new Map;class R extends V{constructor({value:n,decimal:s,tax:r,chain:a,symbol:o,identifier:l}){super(typeof n=="object"?n:{decimal:s,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||`${a}.${o}`);this.type=De(c),this.tax=r,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:s}){return this.chain===n&&this.symbol===s}chainId(){return i.ChainToChainId[this.chain]}static fromUrl(n,s=0){const[r,a,o]=n.split(".");if(!r||!a)throw new Error("Invalid asset url");const l=r===i.Chain.THORChain&&o?`${r}.${a}/${o}`:n;return Y(l,s)}static fromString(n,s=0){return Y(n,s)}static fromIdentifier(n,s=0){return Y(n,s)}static fromStringSync(n,s=0){const{chain:r,isSynthetic:a}=F(n),o=P.get(n.toUpperCase());if(a)return de(n,s);const{tax:l,decimal:c,identifier:h}=o||{decimal:i.BaseDecimal[r],identifier:n};return new R({tax:l,value:b(s,c),identifier:a?n:h,decimal:a?8:c})}static fromIdentifierSync(n,s=0){const{chain:r,isSynthetic:a}=F(n),o=P.get(n);if(a)return de(n,s);const{tax:l,decimal:c,identifier:h}=o||{decimal:i.BaseDecimal[r],identifier:n};return new R({tax:l,decimal:c,identifier:h,value:b(s,c)})}static fromChainOrSignature(n,s=0){const{decimal:r,identifier:a}=Oe(n);return new R({value:b(s,r),decimal:r,identifier:a})}static loadStaticAssets(){return new Promise(async(n,s)=>{try{const r=await import("@swapkit/tokens");Object.values(r).forEach(a=>{var o;(o=a==null?void 0:a.tokens)==null||o.forEach(({identifier:l,chain:c,...h})=>{P.set(l.toUpperCase(),{identifier:l,decimal:"decimals"in h?h.decimals:i.BaseDecimal[c]})})}),n({ok:!0})}catch(r){console.error(r),s({ok:!1,error:r,message:"Couldn't load static assets. Ensure you have installed @swapkit/tokens package"})}})}}function bt(e){const t=R.fromChainOrSignature(e);switch(e){case i.Chain.Bitcoin:case i.Chain.Litecoin:case i.Chain.BitcoinCash:return t.set(10001e-8);case i.Chain.Dogecoin:return t.set(1.00000001);case i.Chain.Avalanche:case i.Chain.Ethereum:return t.set(1e-8);case i.Chain.THORChain:case i.Chain.Maya:return t.set(0);case i.Chain.Cosmos:return t.set(1e-6);default:return t.set(1e-8)}}async function Y(e,t=0){yt(e);const n=P.get(e.toUpperCase()),s=(n==null?void 0:n.decimal)||await Ne(F(e));return n||P.set(e.toUpperCase(),{identifier:e,decimal:s}),new R({decimal:s,value:b(t,s),identifier:e})}function de(e,t=0){const[n,s]=e.split(".")[0].toUpperCase()===i.Chain.THORChain?e.split(".").slice(1).join().split("/"):e.split("/");if(!n||!s)throw new Error("Invalid asset identifier");return new R({decimal:8,value:b(t,8),identifier:`${i.Chain.THORChain}.${n}/${s}`})}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,s]=e.split(".")[0].toUpperCase()===i.Chain.THORChain?e.split(".").slice(1).join().split("/"):e.split("/");if(t&&(!n||!s))throw new Error("Invalid asset identifier");const r=e.includes(".")&&!t?e:`${i.Chain.THORChain}.${s}`,[a,o]=r.split("."),[l,c]=(t?s:o).split("-");return{address:c==null?void 0:c.toLowerCase(),chain:a,isGasAsset:se({chain:a,symbol:o}),isSynthetic:t,symbol:(t?`${n}/`:"")+(c?`${l}-${(c==null?void 0:c.toLowerCase())??""}`:o),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:10313,wallet_ledger_connection_error:20001,helpers_number_different_decimals:99101};class re extends Error{constructor(t,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,re.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=ge;exports.SwapKitApi=lt;exports.SwapKitError=re;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=Pe;exports.getAsymmetricAssetWithdrawAmount=Et;exports.getAsymmetricRuneShare=ye;exports.getAsymmetricRuneWithdrawAmount=Ct;exports.getCommonAssetInfo=Oe;exports.getDecimal=Ne;exports.getEstimatedPoolShare=It;exports.getLiquiditySlippage=gt;exports.getMemoFor=ft;exports.getMinAmountByChain=bt;exports.getSymmetricPoolShare=be;exports.getSymmetricWithdraw=Rt;exports.getTHORNameCost=Nt;exports.isGasAsset=se;exports.setRequestClientConfig=ot;exports.validateTHORName=Ot;
|
|
2
2
|
//# sourceMappingURL=index.cjs.map
|