@swapkit/helpers 1.0.0-rc.22 → 1.0.0-rc.23

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 +1 @@
1
- "use strict";var Te=Object.create;var D=Object.defineProperty;var ve=Object.getOwnPropertyDescriptor;var Se=Object.getOwnPropertyNames;var $e=Object.getPrototypeOf,Re=Object.prototype.hasOwnProperty;var Ie=(r,e,t)=>e in r?D(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t;var Be=(r,e,t,s)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of Se(e))!Re.call(r,n)&&n!==t&&D(r,n,{get:()=>e[n],enumerable:!(s=ve(e,n))||s.enumerable});return r};var Ee=(r,e,t)=>(t=r!=null?Te($e(r)):{},Be(e||!r||!r.__esModule?D(t,"default",{value:r,enumerable:!0}):t,r));var p=(r,e,t)=>(Ie(r,typeof e!="symbol"?e+"":e,t),t),Oe=(r,e,t)=>{if(!e.has(r))throw TypeError("Cannot "+t)};var y=(r,e,t)=>{if(e.has(r))throw TypeError("Cannot add the same private member more than once");e instanceof WeakSet?e.add(r):e.set(r,t)};var d=(r,e,t)=>(Oe(r,e,"access private method"),t);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const i=require("@swapkit/types"),Me="0x313ce567",re=async({chain:r,to:e})=>{try{const{result:t}=await ge.post(i.ChainToRPC[r],{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:Me},"latest"]})});return parseInt(BigInt(t).toString())}catch(t){return console.error(t),i.BaseDecimal[r]}},Ve=async r=>{if(r===i.Chain.Ethereum)return i.BaseDecimal.ETH;const[,e]=r.split("-");return e!=null&&e.startsWith("0x")?re({chain:i.Chain.Ethereum,to:e}):i.BaseDecimal.ETH},qe=async r=>{const[,e]=r.split("-");return e!=null&&e.startsWith("0x")?re({chain:i.Chain.Avalanche,to:e.toLowerCase()}):i.BaseDecimal.AVAX},ke=async r=>(r===i.Chain.BinanceSmartChain,i.BaseDecimal.BSC),ne=async({chain:r,symbol:e})=>{switch(r){case i.Chain.Ethereum:return Ve(e);case i.Chain.Avalanche:return qe(e);case i.Chain.BinanceSmartChain:return ke(e);default:return i.BaseDecimal[r]}},Pe={[i.FeeOption.Average]:1.2,[i.FeeOption.Fast]:1.5,[i.FeeOption.Fastest]:2},ie=({chain:r,symbol:e})=>{switch(r){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===r;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=r=>{switch(r){case"ETH.THOR":return{identifier:"ETH.THOR-0xa5f2211b9b8170f694421f2046281775e8468044",decimal:18};case"ETH.vTHOR":return{identifier:"ETH.vTHOR-0x815c23eca83261b6ec689b60cc4a58b54bc24d8d",decimal:18};case i.Chain.Cosmos:return{identifier:"GAIA.ATOM",decimal:i.BaseDecimal[r]};case i.Chain.THORChain:return{identifier:"THOR.RUNE",decimal:i.BaseDecimal[r]};case i.Chain.BinanceSmartChain:return{identifier:"BSC.BNB",decimal:i.BaseDecimal[r]};case i.Chain.Maya:return{identifier:"MAYA.CACAO",decimal:i.BaseDecimal.MAYA};case"MAYA.MAYA":return{identifier:"MAYA.MAYA",decimal:4};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:`${r}.${r}`,decimal:i.BaseDecimal[r]}}},oe=({chain:r,symbol:e})=>{if(e.includes("/"))return"Synth";switch(r){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"}},xe=r=>{var c;const[e,...t]=r.split("."),s=r.includes("/"),n=t.join("."),a=(c=n==null?void 0:n.split("-"))==null?void 0:c[0];return{chain:e,symbol:n,ticker:a,synth:s}},Ne=new RegExp(/(.)\1{6}|\.ORG|\.NET|\.FINANCE|\.COM|WWW|HTTP|\\\\|\/\/|[\s$%:[\]]/,"gmi"),De=r=>r.filter(e=>!Ne.test(e.toString())&&!e.toString().includes("undefined")),ce=({liquidityUnits:r,poolUnits:e,runeDepth:t})=>{const s=m(r),n=m(e),a=m(t),c=s.mul(a),o=n.mul(n).mul(2),u=n.mul(s).mul(2),l=s.mul(s),h=n.mul(n).mul(n);return c.mul(o.sub(u).add(l)).div(h)},ue=({liquidityUnits:r,poolUnits:e,assetDepth:t})=>{const s=m(r),n=m(e),a=m(t),c=s.mul(a),o=n.mul(n).mul(2),u=n.mul(s).mul(2),l=s.mul(s),h=c.mul(o.sub(u).add(l)),g=n.mul(n).mul(n);return h.div(g)},je=({percent:r,runeDepth:e,liquidityUnits:t,poolUnits:s})=>ce({runeDepth:e,liquidityUnits:t,poolUnits:s}).mul(r),He=({percent:r,assetDepth:e,liquidityUnits:t,poolUnits:s})=>ue({assetDepth:e,liquidityUnits:t,poolUnits:s}).mul(r),m=r=>f.fromBigInt(BigInt(r),i.BaseDecimal.THOR),le=({liquidityUnits:r,poolUnits:e,runeDepth:t,assetDepth:s})=>({assetAmount:m(s).mul(r).div(e),runeAmount:m(t).mul(r).div(e)}),Le=({liquidityUnits:r,poolUnits:e,runeDepth:t,assetDepth:s,percent:n})=>Object.fromEntries(Object.entries(le({liquidityUnits:r,poolUnits:e,runeDepth:t,assetDepth:s})).map(([a,c])=>[a,c.mul(n)])),Fe=({runeDepth:r,poolUnits:e,assetDepth:t,liquidityUnits:s,runeAmount:n,assetAmount:a})=>{const c=new f({value:r,decimal:8}),o=new f({value:t,decimal:8}),u=new f({value:e,decimal:8}),l=new f({value:n,decimal:8}),h=new f({value:a,decimal:8}),g=l.mul(o),w=h.mul(c),x=l.mul(h),be=c.mul(o),Ce=u.mul(g.add(w.add(x.mul(2)))),we=g.add(w.add(be.mul(2))),J=Ce.div(we),N=m(s).add(J);if(J.getBaseValue("number")===0)return N.div(u).getBaseValue("number");const Ae=u.add(N);return N.div(Ae).getBaseValue("number")},Ue=({runeAmount:r,assetAmount:e,runeDepth:t,assetDepth:s})=>{if(r==="0"||e==="0"||t==="0"||s==="0")return 0;const n=m(t),a=m(s),c=m(e),o=m(r),u=c.mul(n).sub(a.mul(o)),l=a.mul(o).add(n.mul(a));return Math.abs(u.div(l).getBaseValue("number"))},We=({symbol:r,ticker:e,chain:t})=>t==="ETH"&&e!=="ETH"?`${e}-${r.slice(-3)}`:r,Ge=(r,e)=>{switch(r){case i.MemoType.LEAVE:case i.MemoType.BOND:{const{address:t}=e;return`${r}:${t}`}case i.MemoType.UNBOND:{const{address:t,unbondAmount:s}=e;return`${r}:${t}:${s*10**8}`}case i.MemoType.THORNAME_REGISTER:{const{name:t,chain:s,address:n,owner:a}=e;return`${r}:${t}:${s}:${n}${a?`:${a}`:""}`}case i.MemoType.DEPOSIT:{const{chain:t,symbol:s,address:n,singleSide:a}=e;return a?`${r}:${t}/${s}::t:0`:`${r}:${t}.${s}:${n||""}:t:0`}case i.MemoType.WITHDRAW:{const{chain:t,ticker:s,symbol:n,basisPoints:a,targetAssetString:c,singleSide:o}=e,u=!o&&c?`:${c}`:"",l=We({chain:t,symbol:n,ticker:s});return`${r}:${t}${o?"/":"."}${l}:${a}${u}`}case i.MemoType.OPEN_LOAN:case i.MemoType.CLOSE_LOAN:{const{asset:t,address:s}=e;return`${r}:${t}:${s}`}default:return""}},Ke=r=>{if(r<0)throw new Error("Invalid number of year");return 10+r},Ye=r=>{if(r.length>30)return!1;const e=/^[a-zA-Z0-9+_-]+$/g;return!!r.match(e)},ze=([r,e,t,s,n])=>`${r}'/${e}'/${t}'/${s}${typeof n!="number"?"":`/${n}`}`;class Q extends Error{constructor(e,t,s){const n=e.status||e.status===0?e.status:"",a=e.statusText||"",c=`${n} ${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=s}}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 M=r=>r!==null&&typeof r=="object",O=(...r)=>{for(const e of r)if((!M(e)||Array.isArray(e))&&e!==void 0)throw new TypeError("The `options` argument must be an object");return K({},...r)},de=(r={},e={})=>{const t=new globalThis.Headers(r),s=e instanceof globalThis.Headers,n=new globalThis.Headers(e);for(const[a,c]of n.entries())s&&c==="undefined"||c===void 0?t.delete(a):t.set(a,c);return t},K=(...r)=>{let e={},t={};for(const s of r)if(Array.isArray(s))Array.isArray(e)||(e=[]),e=[...e,...s];else if(M(s)){for(let[n,a]of Object.entries(s))M(a)&&n in e&&(a=K(e[n],a)),e={...e,[n]:a};M(s.headers)&&(t=de(t,s.headers),e.headers=t)}return e},Je=(()=>{let r=!1,e=!1;const t=typeof globalThis.ReadableStream=="function",s=typeof globalThis.Request=="function";return t&&s&&(e=new globalThis.Request("https://empty.invalid",{body:new globalThis.ReadableStream,method:"POST",get duplex(){return r=!0,"half"}}).headers.has("Content-Type")),r&&!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:"*/*"},j=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},st={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},rt=r=>me.includes(r)?r.toUpperCase():r,nt=["get","put","head","delete","options","trace"],it=[408,413,429,500,502,503,504],fe=[413,429,503],X={limit:2,methods:nt,statusCodes:it,afterStatusCodes:fe,maxRetryAfter:Number.POSITIVE_INFINITY,backoffLimit:Number.POSITIVE_INFINITY,delay:r=>.3*2**(r-1)*1e3},at=(r={})=>{if(typeof r=="number")return{...X,limit:r};if(r.methods&&!Array.isArray(r.methods))throw new Error("retry.methods must be an array");if(r.statusCodes&&!Array.isArray(r.statusCodes))throw new Error("retry.statusCodes must be an array");return{...X,...r,afterStatusCodes:fe}};async function ot(r,e,t,s){return new Promise((n,a)=>{const c=setTimeout(()=>{t&&t.abort(),a(new he(r))},s.timeout);s.fetch(r,e).then(n).catch(a).then(()=>{clearTimeout(c)})})}async function ct(r,{signal:e}){return new Promise((t,s)=>{e&&(e.throwIfAborted(),e.addEventListener("abort",n,{once:!0}));function n(){clearTimeout(a),s(e.reason)}const a=setTimeout(()=>{e==null||e.removeEventListener("abort",n),t()},r)})}const ut=(r,e)=>{const t={};for(const s in e)!(s in st)&&!(s in tt)&&!(s in r)&&(t[s]=e[s]);return t};class q{static create(e,t){const s=new q(e,t),n=async()=>{if(typeof s._options.timeout=="number"&&s._options.timeout>j)throw new RangeError(`The \`timeout\` option cannot be greater than ${j}`);await Promise.resolve();let o=await s._fetch();for(const u of s._options.hooks.afterResponse){const l=await u(s.request,s._options,s._decorateResponse(o.clone()));l instanceof globalThis.Response&&(o=l)}if(s._decorateResponse(o),!o.ok&&s._options.throwHttpErrors){let u=new Q(o,s.request,s._options);for(const l of s._options.hooks.beforeError)u=await l(u);throw u}if(s._options.onDownloadProgress){if(typeof s._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 s._stream(o.clone(),s._options.onDownloadProgress)}return o},c=s._options.retry.methods.includes(s.request.method.toLowerCase())?s._retry(n):n();for(const[o,u]of Object.entries(et))c[o]=async()=>{s.request.headers.set("accept",s.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:K({beforeRequest:[],beforeRetry:[],beforeError:[],afterResponse:[]},t.hooks),method:rt(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 s=this._options.signal;this._options.signal.addEventListener("abort",()=>{this.abortController.abort(s.reason)})}this._options.signal=this.abortController.signal}if(Je&&(this._options.duplex="half"),this.request=new globalThis.Request(this._input,this._options),this._options.searchParams){const n="?"+(typeof this._options.searchParams=="string"?this._options.searchParams.replace(/^\?/,""):new URLSearchParams(this._options.searchParams).toString()),a=this.request.url.replace(/(?:\?.*?)?(?=#|$)/,n);(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 Q){if(!this._options.retry.statusCodes.includes(e.response.status))return 0;const s=e.response.headers.get("Retry-After");if(s&&this._options.retry.afterStatusCodes.includes(e.response.status)){let n=Number(s);return Number.isNaN(n)?n=Date.parse(s)-Date.now():n*=1e3,this._options.retry.maxRetryAfter!==void 0&&n>this._options.retry.maxRetryAfter?0:n}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 s=Math.min(this._calculateRetryDelay(t),j);if(s!==0&&this._retryCount>0){await ct(s,{signal:this._options.signal});for(const n of this._options.hooks.beforeRetry)if(await n({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 s=await t(this.request,this._options);if(s instanceof Request){this.request=s;break}if(s instanceof Response)return s}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 s=Number(e.headers.get("content-length"))||0;let n=0;return e.status===204?(t&&t({percent:1,totalBytes:s,transferredBytes:n},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:s},new Uint8Array);async function o(){const{done:u,value:l}=await c.read();if(u){a.close();return}if(t){n+=l.byteLength;const h=s===0?0:n/s;t({percent:h,transferredBytes:n,totalBytes:s},l)}a.enqueue(l),await o()}await o()}}),{status:e.status,statusText:e.statusText,headers:e.headers})}}/*! MIT License © Sindre Sorhus */const L=r=>{const e=(t,s)=>q.create(t,O(r,s));for(const t of me)e[t]=(s,n)=>q.create(s,O(r,n,{method:t}));return e.create=t=>L(O(t)),e.extend=t=>L(O(r,t)),e.stop=pe,e},lt=L(),ht=lt,dt=typeof window<"u"?{}:{referrer:"https://sk.thorswap.net",referer:"https://sk.thorswap.net"},Z=ht.create({headers:dt}),ge={get:(r,e)=>Z.get(r,e).json(),post:(r,e)=>Z.post(r,e).json()},ee=Object.values(i.Chain),mt=(r="")=>{const e=r.toUpperCase(),[t]=e.split(".");if(ee.includes(t))return!0;const[s]=e.split("/");if(ee.includes(s))return!0;throw new Error(`Invalid identifier: ${r}. Expected format: <Chain>.<Ticker> or <Chain>.<Ticker>-<ContractAddress>`)},R=8,A=r=>10n**BigInt(r),v=r=>Math.log10(parseFloat(r.toString()));function I({value:r,bigIntDecimal:e=R,decimal:t=R}){const s=r<0n;let n=r.toString().substring(s?1:0);const a=t-(n.length-1);a>0&&(n="0".repeat(a)+n);const c=n.length-t;let o=n.slice(-t);return parseInt(o[e])>=5?o=`${o.substring(0,e-1)}${(parseInt(o[e-1])+1).toString()}`:o=o.substring(0,e),`${s?"-":""}${n.slice(0,c)}.${o}`.replace(/\.?0*$/,"")}var b,S,k,_e,P,ye,B,F,C,$,E,U;const z=class z{constructor(e){y(this,b);y(this,k);y(this,P);y(this,B);y(this,C);y(this,E);p(this,"decimalMultiplier",10n**8n);p(this,"bigIntValue",0n);p(this,"decimal");const t=H(e);this.decimal=typeof e=="object"?e.decimal:void 0,this.decimalMultiplier=A(Math.max(d(this,E,U).call(this,d(this,C,$).call(this,t)),this.decimal||0)),d(this,k,_e).call(this,t)}static fromBigInt(e,t){return new z({decimal:t,value:I({value:e,bigIntDecimal:t,decimal:t})})}static shiftDecimals({value:e,from:t,to:s}){return this.fromBigInt(e.getBaseValue("bigint")*A(s)/A(t),s)}set(e){return new this.constructor({decimal:this.decimal,value:e,identifier:this.toString()})}add(...e){return d(this,b,S).call(this,"add",...e)}sub(...e){return d(this,b,S).call(this,"sub",...e)}mul(...e){return d(this,b,S).call(this,"mul",...e)}div(...e){return d(this,b,S).call(this,"div",...e)}gt(e){return this.bigIntValue>this.getBigIntValue(e)}gte(e){return this.bigIntValue>=this.getBigIntValue(e)}lt(e){return this.bigIntValue<this.getBigIntValue(e)}lte(e){return this.bigIntValue<=this.getBigIntValue(e)}eqValue(e){return this.bigIntValue===this.getBigIntValue(e)}getValue(e){const t=this.formatBigIntToSafeValue(this.bigIntValue,this.decimal||v(this.decimalMultiplier));switch(e){case"number":return Number(t);case"string":return t;default:return this.bigIntValue*BigInt(this.decimal||8n)/this.decimalMultiplier}}getBaseValue(e){const t=this.decimalMultiplier/A(this.decimal||i.BaseDecimal.THOR),s=this.bigIntValue/t;switch(e){case"number":return Number(s);case"string":return s.toString();default:return s}}getBigIntValue(e,t){if(!t&&typeof e=="object")return e.bigIntValue;const s=H(e),n=d(this,C,$).call(this,s);return n==="0"||n==="undefined"?0n:d(this,B,F).call(this,n,t)}formatBigIntToSafeValue(e,t){const s=t||this.decimal||R,n=Math.max(s,v(this.decimalMultiplier)),a=e<0n,c=e.toString().substring(a?1:0),o=n-(c.length-1),u=o>0?"0".repeat(o)+c:c,l=u.length-n;let h=u.slice(-n);return parseInt(h[s])>=5?h=`${h.substring(0,s-1)}${(parseInt(h[s-1])+1).toString()}`:h=h.substring(0,s),`${a?"-":""}${u.slice(0,l)}.${h}`.replace(/\.?0*$/,"")}toSignificant(e=6){const[t,s]=this.getValue("string").split("."),n=t||"",a=s||"";if((parseInt(n)?n.length+a.length:a.length)<=e)return this.getValue("string");if(n.length>=e)return n.slice(0,e).padEnd(n.length,"0");if(parseInt(n))return`${n}.${a.slice(0,e-n.length)}`.padEnd(e-n.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,s]=this.getValue("string").split("."),n=t||"",a=s||"";if(parseInt(n))return`${n}.${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"),s=["","K","M","B","T","Q","Qi","S"],n=Math.floor(Math.log10(Math.abs(t))/3),a=s[n];if(!a)return this.getValue("string");const c=10**(n*3);return`${(t/c).toFixed(e)}${a}`}toCurrency(e="$",{currencyPosition:t="start",decimal:s=2,decimalSeparator:n=".",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(".",n):`${l}${u?`${n}${u.slice(0,s)}`:""}`;return`${t==="start"?e:""}${h}${t==="end"?e:""}`}};b=new WeakSet,S=function(e,...t){const s=d(this,P,ye).call(this,this,...t),n=A(s),a=t.reduce((o,u)=>{const l=this.getBigIntValue(u,s);switch(e){case"add":return o+l;case"sub":return o-l;case"mul":return o*l/n;case"div":{if(l===0n)throw new RangeError("Division by zero");return o*n/l}default:return o}},this.bigIntValue*n/this.decimalMultiplier),c=I({bigIntDecimal:s,decimal:Math.max(s,v(this.decimalMultiplier)),value:a});return new this.constructor({decimal:this.decimal,value:c,identifier:this.toString()})},k=new WeakSet,_e=function(e){const t=d(this,C,$).call(this,e)||"0";this.bigIntValue=d(this,B,F).call(this,t)},P=new WeakSet,ye=function(...e){const t=e.map(s=>typeof s=="object"?s.decimal||v(s.decimalMultiplier):d(this,E,U).call(this,d(this,C,$).call(this,s))).filter(Boolean);return Math.max(...t,R)},B=new WeakSet,F=function(e,t){const s=t?A(t):this.decimalMultiplier,n=v(s),[a="",c=""]=e.split(".");return BigInt(`${a}${c.padEnd(n,"0")}`)},C=new WeakSet,$=function(e){const s=`${typeof e=="number"?Number(e).toLocaleString("fullwide",{useGrouping:!1,maximumFractionDigits:20}):H(e)}`.replaceAll(",",".").split(".");return s.length>1?`${s.slice(0,-1).join("")}.${s.at(-1)}`:s[0]},E=new WeakSet,U=function(e){var s;const t=((s=e.split(".")[1])==null?void 0:s.length)||0;return Math.max(t,R)};let T=z;function H(r){return typeof r=="object"?"getValue"in r?r.getValue("string"):r.value:r}const V=(r,e)=>typeof r=="bigint"?I({value:r,bigIntDecimal:e,decimal:e}):r;let W;const te=r=>{if(!W)throw new Error("Static assets not loaded, call await AssetValue.loadStaticAssets() first");return W.get(r.toUpperCase())||{decimal:i.BaseDecimal.THOR,identifier:""}},se=async(r,e=0)=>{mt(r);const t=await ne(G(r)),s=V(e,t);return new _({decimal:t,value:s,identifier:r})};class _ extends T{constructor(t){super(t.value instanceof T?t.value:{decimal:t.decimal,value:t.value});p(this,"address");p(this,"chain");p(this,"isSynthetic",!1);p(this,"isGasAsset",!1);p(this,"symbol");p(this,"ticker");p(this,"type");const s="identifier"in t?t.identifier:`${t.chain}.${t.symbol}`,n=G(s);this.type=oe(n),this.chain=n.chain,this.ticker=n.ticker,this.symbol=n.symbol,this.address=n.address,this.isSynthetic=n.isSynthetic,this.isGasAsset=n.isGasAsset}get assetValue(){return`${this.getValue("string")} ${this.ticker}`}toString(t=!1){const s=this.isSynthetic?this.symbol.split("-")[0]:`${this.chain}.${this.ticker}`;return t?s:`${this.chain}.${this.symbol}`}eq({chain:t,symbol:s}){return this.chain===t&&this.symbol===s}static async fromString(t,s=0){return se(t,s)}static fromStringSync(t,s=0){const{isSynthetic:n}=G(t),{decimal:a,identifier:c}=te(t),o=V(s,a);return c?new _({decimal:a,identifier:c,value:o}):n?new _({decimal:8,identifier:t,value:o}):void 0}static async fromIdentifier(t,s=0){return se(t,s)}static fromIdentifierSync(t,s=0){const{decimal:n,identifier:a}=te(t),c=V(s,n);return new _({decimal:n,identifier:a,value:c})}static fromChainOrSignature(t,s=0){const{decimal:n,identifier:a}=ae(t),c=V(s,n);return new _({value:c,decimal:n,identifier:a})}static async loadStaticAssets(){return new Promise(async(t,s)=>{try{const{ThorchainList:n,NativeList:a,...c}=await import("@swapkit/tokens");W=[a,...Object.values(c)].reduce((u,{tokens:l})=>(l.forEach(({identifier:h,chain:g,...w})=>{const x="decimals"in w?w.decimals:i.BaseDecimal[g];u.set(h,{identifier:h,decimal:x})}),u),new Map),t({ok:!0})}catch(n){console.error(n),s({ok:!1,error:n,message:"Couldn't load static assets. Ensure you have installed @swapkit/tokens package"})}})}}const pt=r=>{const e=_.fromChainOrSignature(r);switch(r){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);default:return e.set(1e-8)}},G=r=>{const e=r.slice(0,14).includes("/"),[t,s]=r.split(".").pop().split("/"),n=r.includes(".")&&!e?r:`${i.Chain.THORChain}.${s}`,[a,c]=n.split("."),[o,u]=(e?s:c).split("-");return{address:u==null?void 0:u.toLowerCase(),chain:a,isGasAsset:ie({chain:a,symbol:c}),isSynthetic:e,symbol:(e?`${t}/`:"")+(u?`${o}-${(u==null?void 0:u.toLowerCase())??""}`:c),ticker:o}},ft={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_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_deposit_server_error:10313,wallet_ledger_connection_error:20001,helpers_number_different_decimals:99101};class Y extends Error{constructor(e,t){console.error(t),super(e,{cause:{code:ft[e],message:e}}),Object.setPrototypeOf(this,Y.prototype)}}class f extends T{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=_;exports.BigIntArithmetics=T;exports.RequestClient=ge;exports.SwapKitError=Y;exports.SwapKitNumber=f;exports.assetFromString=xe;exports.derivationPathToString=ze;exports.filterAssets=De;exports.formatBigIntToSafeValue=I;exports.gasFeeMultiplier=Pe;exports.getAssetType=oe;exports.getAsymmetricAssetShare=ue;exports.getAsymmetricAssetWithdrawAmount=He;exports.getAsymmetricRuneShare=ce;exports.getAsymmetricRuneWithdrawAmount=je;exports.getCommonAssetInfo=ae;exports.getDecimal=ne;exports.getEstimatedPoolShare=Fe;exports.getLiquiditySlippage=Ue;exports.getMemoFor=Ge;exports.getMinAmountByChain=pt;exports.getSymmetricPoolShare=le;exports.getSymmetricWithdraw=Le;exports.getTHORNameCost=Ke;exports.isGasAsset=ie;exports.validateTHORName=Ye;
1
+ "use strict";var Te=Object.create;var D=Object.defineProperty;var ve=Object.getOwnPropertyDescriptor;var Se=Object.getOwnPropertyNames;var $e=Object.getPrototypeOf,Re=Object.prototype.hasOwnProperty;var Ie=(r,e,t)=>e in r?D(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t;var Be=(r,e,t,s)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of Se(e))!Re.call(r,n)&&n!==t&&D(r,n,{get:()=>e[n],enumerable:!(s=ve(e,n))||s.enumerable});return r};var Ee=(r,e,t)=>(t=r!=null?Te($e(r)):{},Be(e||!r||!r.__esModule?D(t,"default",{value:r,enumerable:!0}):t,r));var p=(r,e,t)=>(Ie(r,typeof e!="symbol"?e+"":e,t),t),Me=(r,e,t)=>{if(!e.has(r))throw TypeError("Cannot "+t)};var y=(r,e,t)=>{if(e.has(r))throw TypeError("Cannot add the same private member more than once");e instanceof WeakSet?e.add(r):e.set(r,t)};var d=(r,e,t)=>(Me(r,e,"access private method"),t);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const i=require("@swapkit/types"),Oe="0x313ce567",re=async({chain:r,to:e})=>{try{const{result:t}=await ge.post(i.ChainToRPC[r],{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:Oe},"latest"]})});return parseInt(BigInt(t).toString())}catch(t){return console.error(t),i.BaseDecimal[r]}},Ve=async r=>{if(r===i.Chain.Ethereum)return i.BaseDecimal.ETH;const[,e]=r.split("-");return e!=null&&e.startsWith("0x")?re({chain:i.Chain.Ethereum,to:e}):i.BaseDecimal.ETH},qe=async r=>{const[,e]=r.split("-");return e!=null&&e.startsWith("0x")?re({chain:i.Chain.Avalanche,to:e.toLowerCase()}):i.BaseDecimal.AVAX},ke=async r=>(r===i.Chain.BinanceSmartChain,i.BaseDecimal.BSC),ne=async({chain:r,symbol:e})=>{switch(r){case i.Chain.Ethereum:return Ve(e);case i.Chain.Avalanche:return qe(e);case i.Chain.BinanceSmartChain:return ke(e);default:return i.BaseDecimal[r]}},Pe={[i.FeeOption.Average]:1.2,[i.FeeOption.Fast]:1.5,[i.FeeOption.Fastest]:2},ie=({chain:r,symbol:e})=>{switch(r){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===r;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=r=>{switch(r){case"ETH.THOR":return{identifier:"ETH.THOR-0xa5f2211b9b8170f694421f2046281775e8468044",decimal:18};case"ETH.vTHOR":return{identifier:"ETH.vTHOR-0x815c23eca83261b6ec689b60cc4a58b54bc24d8d",decimal:18};case i.Chain.Cosmos:return{identifier:"GAIA.ATOM",decimal:i.BaseDecimal[r]};case i.Chain.THORChain:return{identifier:"THOR.RUNE",decimal:i.BaseDecimal[r]};case i.Chain.BinanceSmartChain:return{identifier:"BSC.BNB",decimal:i.BaseDecimal[r]};case i.Chain.Maya:return{identifier:"MAYA.CACAO",decimal:i.BaseDecimal.MAYA};case"MAYA.MAYA":return{identifier:"MAYA.MAYA",decimal:4};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:`${r}.${r}`,decimal:i.BaseDecimal[r]}}},oe=({chain:r,symbol:e})=>{if(e.includes("/"))return"Synth";switch(r){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"}},xe=r=>{var c;const[e,...t]=r.split("."),s=r.includes("/"),n=t.join("."),a=(c=n==null?void 0:n.split("-"))==null?void 0:c[0];return{chain:e,symbol:n,ticker:a,synth:s}},Ne=new RegExp(/(.)\1{6}|\.ORG|\.NET|\.FINANCE|\.COM|WWW|HTTP|\\\\|\/\/|[\s$%:[\]]/,"gmi"),De=r=>i.EVMChainList.includes(r.chain)?!r.isGasAsset&&r.address&&!Number.isNaN(r.decimal):!0,He=r=>r.filter(e=>!e.toString().includes("undefined")&&!Ne.test(e.toString())&&De(e)),ce=({liquidityUnits:r,poolUnits:e,runeDepth:t})=>{const s=m(r),n=m(e),a=m(t),c=s.mul(a),o=n.mul(n).mul(2),u=n.mul(s).mul(2),l=s.mul(s),h=n.mul(n).mul(n);return c.mul(o.sub(u).add(l)).div(h)},ue=({liquidityUnits:r,poolUnits:e,assetDepth:t})=>{const s=m(r),n=m(e),a=m(t),c=s.mul(a),o=n.mul(n).mul(2),u=n.mul(s).mul(2),l=s.mul(s),h=c.mul(o.sub(u).add(l)),g=n.mul(n).mul(n);return h.div(g)},je=({percent:r,runeDepth:e,liquidityUnits:t,poolUnits:s})=>ce({runeDepth:e,liquidityUnits:t,poolUnits:s}).mul(r),Le=({percent:r,assetDepth:e,liquidityUnits:t,poolUnits:s})=>ue({assetDepth:e,liquidityUnits:t,poolUnits:s}).mul(r),m=r=>f.fromBigInt(BigInt(r),i.BaseDecimal.THOR),le=({liquidityUnits:r,poolUnits:e,runeDepth:t,assetDepth:s})=>({assetAmount:m(s).mul(r).div(e),runeAmount:m(t).mul(r).div(e)}),Fe=({liquidityUnits:r,poolUnits:e,runeDepth:t,assetDepth:s,percent:n})=>Object.fromEntries(Object.entries(le({liquidityUnits:r,poolUnits:e,runeDepth:t,assetDepth:s})).map(([a,c])=>[a,c.mul(n)])),Ue=({runeDepth:r,poolUnits:e,assetDepth:t,liquidityUnits:s,runeAmount:n,assetAmount:a})=>{const c=new f({value:r,decimal:8}),o=new f({value:t,decimal:8}),u=new f({value:e,decimal:8}),l=new f({value:n,decimal:8}),h=new f({value:a,decimal:8}),g=l.mul(o),w=h.mul(c),x=l.mul(h),be=c.mul(o),Ce=u.mul(g.add(w.add(x.mul(2)))),we=g.add(w.add(be.mul(2))),J=Ce.div(we),N=m(s).add(J);if(J.getBaseValue("number")===0)return N.div(u).getBaseValue("number");const Ae=u.add(N);return N.div(Ae).getBaseValue("number")},We=({runeAmount:r,assetAmount:e,runeDepth:t,assetDepth:s})=>{if(r==="0"||e==="0"||t==="0"||s==="0")return 0;const n=m(t),a=m(s),c=m(e),o=m(r),u=c.mul(n).sub(a.mul(o)),l=a.mul(o).add(n.mul(a));return Math.abs(u.div(l).getBaseValue("number"))},Ge=({symbol:r,ticker:e,chain:t})=>t==="ETH"&&e!=="ETH"?`${e}-${r.slice(-3)}`:r,Ke=(r,e)=>{switch(r){case i.MemoType.LEAVE:case i.MemoType.BOND:{const{address:t}=e;return`${r}:${t}`}case i.MemoType.UNBOND:{const{address:t,unbondAmount:s}=e;return`${r}:${t}:${s*10**8}`}case i.MemoType.THORNAME_REGISTER:{const{name:t,chain:s,address:n,owner:a}=e;return`${r}:${t}:${s}:${n}${a?`:${a}`:""}`}case i.MemoType.DEPOSIT:{const{chain:t,symbol:s,address:n,singleSide:a}=e;return a?`${r}:${t}/${s}::t:0`:`${r}:${t}.${s}:${n||""}:t:0`}case i.MemoType.WITHDRAW:{const{chain:t,ticker:s,symbol:n,basisPoints:a,targetAssetString:c,singleSide:o}=e,u=!o&&c?`:${c}`:"",l=Ge({chain:t,symbol:n,ticker:s});return`${r}:${t}${o?"/":"."}${l}:${a}${u}`}case i.MemoType.OPEN_LOAN:case i.MemoType.CLOSE_LOAN:{const{asset:t,address:s}=e;return`${r}:${t}:${s}`}default:return""}},Ye=r=>{if(r<0)throw new Error("Invalid number of year");return 10+r},ze=r=>{if(r.length>30)return!1;const e=/^[a-zA-Z0-9+_-]+$/g;return!!r.match(e)},Je=([r,e,t,s,n])=>`${r}'/${e}'/${t}'/${s}${typeof n!="number"?"":`/${n}`}`;class Q extends Error{constructor(e,t,s){const n=e.status||e.status===0?e.status:"",a=e.statusText||"",c=`${n} ${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=s}}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 O=r=>r!==null&&typeof r=="object",M=(...r)=>{for(const e of r)if((!O(e)||Array.isArray(e))&&e!==void 0)throw new TypeError("The `options` argument must be an object");return K({},...r)},de=(r={},e={})=>{const t=new globalThis.Headers(r),s=e instanceof globalThis.Headers,n=new globalThis.Headers(e);for(const[a,c]of n.entries())s&&c==="undefined"||c===void 0?t.delete(a):t.set(a,c);return t},K=(...r)=>{let e={},t={};for(const s of r)if(Array.isArray(s))Array.isArray(e)||(e=[]),e=[...e,...s];else if(O(s)){for(let[n,a]of Object.entries(s))O(a)&&n in e&&(a=K(e[n],a)),e={...e,[n]:a};O(s.headers)&&(t=de(t,s.headers),e.headers=t)}return e},Qe=(()=>{let r=!1,e=!1;const t=typeof globalThis.ReadableStream=="function",s=typeof globalThis.Request=="function";return t&&s&&(e=new globalThis.Request("https://empty.invalid",{body:new globalThis.ReadableStream,method:"POST",get duplex(){return r=!0,"half"}}).headers.has("Content-Type")),r&&!e})(),Xe=typeof globalThis.AbortController=="function",Ze=typeof globalThis.ReadableStream=="function",et=typeof globalThis.FormData=="function",me=["get","post","put","patch","head","delete"],tt={json:"application/json",text:"text/*",formData:"multipart/form-data",arrayBuffer:"*/*",blob:"*/*"},H=2147483647,pe=Symbol("stop"),st={json:!0,parseJson:!0,searchParams:!0,prefixUrl:!0,retry:!0,timeout:!0,hooks:!0,throwHttpErrors:!0,onDownloadProgress:!0,fetch:!0},rt={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},nt=r=>me.includes(r)?r.toUpperCase():r,it=["get","put","head","delete","options","trace"],at=[408,413,429,500,502,503,504],fe=[413,429,503],X={limit:2,methods:it,statusCodes:at,afterStatusCodes:fe,maxRetryAfter:Number.POSITIVE_INFINITY,backoffLimit:Number.POSITIVE_INFINITY,delay:r=>.3*2**(r-1)*1e3},ot=(r={})=>{if(typeof r=="number")return{...X,limit:r};if(r.methods&&!Array.isArray(r.methods))throw new Error("retry.methods must be an array");if(r.statusCodes&&!Array.isArray(r.statusCodes))throw new Error("retry.statusCodes must be an array");return{...X,...r,afterStatusCodes:fe}};async function ct(r,e,t,s){return new Promise((n,a)=>{const c=setTimeout(()=>{t&&t.abort(),a(new he(r))},s.timeout);s.fetch(r,e).then(n).catch(a).then(()=>{clearTimeout(c)})})}async function ut(r,{signal:e}){return new Promise((t,s)=>{e&&(e.throwIfAborted(),e.addEventListener("abort",n,{once:!0}));function n(){clearTimeout(a),s(e.reason)}const a=setTimeout(()=>{e==null||e.removeEventListener("abort",n),t()},r)})}const lt=(r,e)=>{const t={};for(const s in e)!(s in rt)&&!(s in st)&&!(s in r)&&(t[s]=e[s]);return t};class q{static create(e,t){const s=new q(e,t),n=async()=>{if(typeof s._options.timeout=="number"&&s._options.timeout>H)throw new RangeError(`The \`timeout\` option cannot be greater than ${H}`);await Promise.resolve();let o=await s._fetch();for(const u of s._options.hooks.afterResponse){const l=await u(s.request,s._options,s._decorateResponse(o.clone()));l instanceof globalThis.Response&&(o=l)}if(s._decorateResponse(o),!o.ok&&s._options.throwHttpErrors){let u=new Q(o,s.request,s._options);for(const l of s._options.hooks.beforeError)u=await l(u);throw u}if(s._options.onDownloadProgress){if(typeof s._options.onDownloadProgress!="function")throw new TypeError("The `onDownloadProgress` option must be a function");if(!Ze)throw new Error("Streams are not supported in your environment. `ReadableStream` is missing.");return s._stream(o.clone(),s._options.onDownloadProgress)}return o},c=s._options.retry.methods.includes(s.request.method.toLowerCase())?s._retry(n):n();for(const[o,u]of Object.entries(tt))c[o]=async()=>{s.request.headers.set("accept",s.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:K({beforeRequest:[],beforeRetry:[],beforeError:[],afterResponse:[]},t.hooks),method:nt(t.method??this._input.method),prefixUrl:String(t.prefixUrl||""),retry:ot(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(Xe){if(this.abortController=new globalThis.AbortController,this._options.signal){const s=this._options.signal;this._options.signal.addEventListener("abort",()=>{this.abortController.abort(s.reason)})}this._options.signal=this.abortController.signal}if(Qe&&(this._options.duplex="half"),this.request=new globalThis.Request(this._input,this._options),this._options.searchParams){const n="?"+(typeof this._options.searchParams=="string"?this._options.searchParams.replace(/^\?/,""):new URLSearchParams(this._options.searchParams).toString()),a=this.request.url.replace(/(?:\?.*?)?(?=#|$)/,n);(et&&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 Q){if(!this._options.retry.statusCodes.includes(e.response.status))return 0;const s=e.response.headers.get("Retry-After");if(s&&this._options.retry.afterStatusCodes.includes(e.response.status)){let n=Number(s);return Number.isNaN(n)?n=Date.parse(s)-Date.now():n*=1e3,this._options.retry.maxRetryAfter!==void 0&&n>this._options.retry.maxRetryAfter?0:n}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 s=Math.min(this._calculateRetryDelay(t),H);if(s!==0&&this._retryCount>0){await ut(s,{signal:this._options.signal});for(const n of this._options.hooks.beforeRetry)if(await n({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 s=await t(this.request,this._options);if(s instanceof Request){this.request=s;break}if(s instanceof Response)return s}const e=lt(this.request,this._options);return this._options.timeout===!1?this._options.fetch(this.request.clone(),e):ct(this.request.clone(),e,this.abortController,this._options)}_stream(e,t){const s=Number(e.headers.get("content-length"))||0;let n=0;return e.status===204?(t&&t({percent:1,totalBytes:s,transferredBytes:n},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:s},new Uint8Array);async function o(){const{done:u,value:l}=await c.read();if(u){a.close();return}if(t){n+=l.byteLength;const h=s===0?0:n/s;t({percent:h,transferredBytes:n,totalBytes:s},l)}a.enqueue(l),await o()}await o()}}),{status:e.status,statusText:e.statusText,headers:e.headers})}}/*! MIT License © Sindre Sorhus */const L=r=>{const e=(t,s)=>q.create(t,M(r,s));for(const t of me)e[t]=(s,n)=>q.create(s,M(r,n,{method:t}));return e.create=t=>L(M(t)),e.extend=t=>L(M(r,t)),e.stop=pe,e},ht=L(),dt=ht,mt=typeof window<"u"?{}:{referrer:"https://sk.thorswap.net",referer:"https://sk.thorswap.net"},Z=dt.create({headers:mt}),ge={get:(r,e)=>Z.get(r,e).json(),post:(r,e)=>Z.post(r,e).json()},ee=Object.values(i.Chain),pt=(r="")=>{const e=r.toUpperCase(),[t]=e.split(".");if(ee.includes(t))return!0;const[s]=e.split("/");if(ee.includes(s))return!0;throw new Error(`Invalid identifier: ${r}. Expected format: <Chain>.<Ticker> or <Chain>.<Ticker>-<ContractAddress>`)},R=8,A=r=>10n**BigInt(r),v=r=>Math.log10(parseFloat(r.toString()));function I({value:r,bigIntDecimal:e=R,decimal:t=R}){const s=r<0n;let n=r.toString().substring(s?1:0);const a=t-(n.length-1);a>0&&(n="0".repeat(a)+n);const c=n.length-t;let o=n.slice(-t);return parseInt(o[e])>=5?o=`${o.substring(0,e-1)}${(parseInt(o[e-1])+1).toString()}`:o=o.substring(0,e),`${s?"-":""}${n.slice(0,c)}.${o}`.replace(/\.?0*$/,"")}var b,S,k,_e,P,ye,B,F,C,$,E,U;const z=class z{constructor(e){y(this,b);y(this,k);y(this,P);y(this,B);y(this,C);y(this,E);p(this,"decimalMultiplier",10n**8n);p(this,"bigIntValue",0n);p(this,"decimal");const t=j(e);this.decimal=typeof e=="object"?e.decimal:void 0,this.decimalMultiplier=A(Math.max(d(this,E,U).call(this,d(this,C,$).call(this,t)),this.decimal||0)),d(this,k,_e).call(this,t)}static fromBigInt(e,t){return new z({decimal:t,value:I({value:e,bigIntDecimal:t,decimal:t})})}static shiftDecimals({value:e,from:t,to:s}){return this.fromBigInt(e.getBaseValue("bigint")*A(s)/A(t),s)}set(e){return new this.constructor({decimal:this.decimal,value:e,identifier:this.toString()})}add(...e){return d(this,b,S).call(this,"add",...e)}sub(...e){return d(this,b,S).call(this,"sub",...e)}mul(...e){return d(this,b,S).call(this,"mul",...e)}div(...e){return d(this,b,S).call(this,"div",...e)}gt(e){return this.bigIntValue>this.getBigIntValue(e)}gte(e){return this.bigIntValue>=this.getBigIntValue(e)}lt(e){return this.bigIntValue<this.getBigIntValue(e)}lte(e){return this.bigIntValue<=this.getBigIntValue(e)}eqValue(e){return this.bigIntValue===this.getBigIntValue(e)}getValue(e){const t=this.formatBigIntToSafeValue(this.bigIntValue,this.decimal||v(this.decimalMultiplier));switch(e){case"number":return Number(t);case"string":return t;default:return this.bigIntValue*BigInt(this.decimal||8n)/this.decimalMultiplier}}getBaseValue(e){const t=this.decimalMultiplier/A(this.decimal||i.BaseDecimal.THOR),s=this.bigIntValue/t;switch(e){case"number":return Number(s);case"string":return s.toString();default:return s}}getBigIntValue(e,t){if(!t&&typeof e=="object")return e.bigIntValue;const s=j(e),n=d(this,C,$).call(this,s);return n==="0"||n==="undefined"?0n:d(this,B,F).call(this,n,t)}formatBigIntToSafeValue(e,t){const s=t||this.decimal||R,n=Math.max(s,v(this.decimalMultiplier)),a=e<0n,c=e.toString().substring(a?1:0),o=n-(c.length-1),u=o>0?"0".repeat(o)+c:c,l=u.length-n;let h=u.slice(-n);return parseInt(h[s])>=5?h=`${h.substring(0,s-1)}${(parseInt(h[s-1])+1).toString()}`:h=h.substring(0,s),`${a?"-":""}${u.slice(0,l)}.${h}`.replace(/\.?0*$/,"")}toSignificant(e=6){const[t,s]=this.getValue("string").split("."),n=t||"",a=s||"";if((parseInt(n)?n.length+a.length:a.length)<=e)return this.getValue("string");if(n.length>=e)return n.slice(0,e).padEnd(n.length,"0");if(parseInt(n))return`${n}.${a.slice(0,e-n.length)}`.padEnd(e-n.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,s]=this.getValue("string").split("."),n=t||"",a=s||"";if(parseInt(n))return`${n}.${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"),s=["","K","M","B","T","Q","Qi","S"],n=Math.floor(Math.log10(Math.abs(t))/3),a=s[n];if(!a)return this.getValue("string");const c=10**(n*3);return`${(t/c).toFixed(e)}${a}`}toCurrency(e="$",{currencyPosition:t="start",decimal:s=2,decimalSeparator:n=".",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(".",n):`${l}${u?`${n}${u.slice(0,s)}`:""}`;return`${t==="start"?e:""}${h}${t==="end"?e:""}`}};b=new WeakSet,S=function(e,...t){const s=d(this,P,ye).call(this,this,...t),n=A(s),a=t.reduce((o,u)=>{const l=this.getBigIntValue(u,s);switch(e){case"add":return o+l;case"sub":return o-l;case"mul":return o*l/n;case"div":{if(l===0n)throw new RangeError("Division by zero");return o*n/l}default:return o}},this.bigIntValue*n/this.decimalMultiplier),c=I({bigIntDecimal:s,decimal:Math.max(s,v(this.decimalMultiplier)),value:a});return new this.constructor({decimal:this.decimal,value:c,identifier:this.toString()})},k=new WeakSet,_e=function(e){const t=d(this,C,$).call(this,e)||"0";this.bigIntValue=d(this,B,F).call(this,t)},P=new WeakSet,ye=function(...e){const t=e.map(s=>typeof s=="object"?s.decimal||v(s.decimalMultiplier):d(this,E,U).call(this,d(this,C,$).call(this,s))).filter(Boolean);return Math.max(...t,R)},B=new WeakSet,F=function(e,t){const s=t?A(t):this.decimalMultiplier,n=v(s),[a="",c=""]=e.split(".");return BigInt(`${a}${c.padEnd(n,"0")}`)},C=new WeakSet,$=function(e){const s=`${typeof e=="number"?Number(e).toLocaleString("fullwide",{useGrouping:!1,maximumFractionDigits:20}):j(e)}`.replaceAll(",",".").split(".");return s.length>1?`${s.slice(0,-1).join("")}.${s.at(-1)}`:s[0]},E=new WeakSet,U=function(e){var s;const t=((s=e.split(".")[1])==null?void 0:s.length)||0;return Math.max(t,R)};let T=z;function j(r){return typeof r=="object"?"getValue"in r?r.getValue("string"):r.value:r}const V=(r,e)=>typeof r=="bigint"?I({value:r,bigIntDecimal:e,decimal:e}):r;let W;const te=r=>{if(!W)throw new Error("Static assets not loaded, call await AssetValue.loadStaticAssets() first");return W.get(r.toUpperCase())||{decimal:i.BaseDecimal.THOR,identifier:""}},se=async(r,e=0)=>{pt(r);const t=await ne(G(r)),s=V(e,t);return new _({decimal:t,value:s,identifier:r})};class _ extends T{constructor(t){super(t.value instanceof T?t.value:{decimal:t.decimal,value:t.value});p(this,"address");p(this,"chain");p(this,"isSynthetic",!1);p(this,"isGasAsset",!1);p(this,"symbol");p(this,"ticker");p(this,"type");const s="identifier"in t?t.identifier:`${t.chain}.${t.symbol}`,n=G(s);this.type=oe(n),this.chain=n.chain,this.ticker=n.ticker,this.symbol=n.symbol,this.address=n.address,this.isSynthetic=n.isSynthetic,this.isGasAsset=n.isGasAsset}get assetValue(){return`${this.getValue("string")} ${this.ticker}`}toString(t=!1){const s=this.isSynthetic?this.symbol.split("-")[0]:`${this.chain}.${this.ticker}`;return t?s:`${this.chain}.${this.symbol}`}eq({chain:t,symbol:s}){return this.chain===t&&this.symbol===s}static async fromString(t,s=0){return se(t,s)}static fromStringSync(t,s=0){const{isSynthetic:n}=G(t),{decimal:a,identifier:c}=te(t),o=V(s,a);return c?new _({decimal:a,identifier:c,value:o}):n?new _({decimal:8,identifier:t,value:o}):void 0}static async fromIdentifier(t,s=0){return se(t,s)}static fromIdentifierSync(t,s=0){const{decimal:n,identifier:a}=te(t),c=V(s,n);return new _({decimal:n,identifier:a,value:c})}static fromChainOrSignature(t,s=0){const{decimal:n,identifier:a}=ae(t),c=V(s,n);return new _({value:c,decimal:n,identifier:a})}static async loadStaticAssets(){return new Promise(async(t,s)=>{try{const{ThorchainList:n,NativeList:a,...c}=await import("@swapkit/tokens");W=[a,...Object.values(c)].reduce((u,{tokens:l})=>(l.forEach(({identifier:h,chain:g,...w})=>{const x="decimals"in w?w.decimals:i.BaseDecimal[g];u.set(h,{identifier:h,decimal:x})}),u),new Map),t({ok:!0})}catch(n){console.error(n),s({ok:!1,error:n,message:"Couldn't load static assets. Ensure you have installed @swapkit/tokens package"})}})}}const ft=r=>{const e=_.fromChainOrSignature(r);switch(r){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);default:return e.set(1e-8)}},G=r=>{const e=r.slice(0,14).includes("/"),[t,s]=r.split(".").pop().split("/"),n=r.includes(".")&&!e?r:`${i.Chain.THORChain}.${s}`,[a,c]=n.split("."),[o,u]=(e?s:c).split("-");return{address:u==null?void 0:u.toLowerCase(),chain:a,isGasAsset:ie({chain:a,symbol:c}),isSynthetic:e,symbol:(e?`${t}/`:"")+(u?`${o}-${(u==null?void 0:u.toLowerCase())??""}`:c),ticker:o}},gt={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_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_deposit_server_error:10313,wallet_ledger_connection_error:20001,helpers_number_different_decimals:99101};class Y extends Error{constructor(e,t){console.error(t),super(e,{cause:{code:gt[e],message:e}}),Object.setPrototypeOf(this,Y.prototype)}}class f extends T{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=_;exports.BigIntArithmetics=T;exports.RequestClient=ge;exports.SwapKitError=Y;exports.SwapKitNumber=f;exports.assetFromString=xe;exports.derivationPathToString=Je;exports.filterAssets=He;exports.formatBigIntToSafeValue=I;exports.gasFeeMultiplier=Pe;exports.getAssetType=oe;exports.getAsymmetricAssetShare=ue;exports.getAsymmetricAssetWithdrawAmount=Le;exports.getAsymmetricRuneShare=ce;exports.getAsymmetricRuneWithdrawAmount=je;exports.getCommonAssetInfo=ae;exports.getDecimal=ne;exports.getEstimatedPoolShare=Ue;exports.getLiquiditySlippage=We;exports.getMemoFor=Ke;exports.getMinAmountByChain=ft;exports.getSymmetricPoolShare=le;exports.getSymmetricWithdraw=Fe;exports.getTHORNameCost=Ye;exports.isGasAsset=ie;exports.validateTHORName=ze;
package/dist/index.es.js CHANGED
@@ -10,10 +10,10 @@ var y = (s, t, e) => {
10
10
  t instanceof WeakSet ? t.add(s) : t.set(s, e);
11
11
  };
12
12
  var m = (s, t, e) => (yt(s, t, "access private method"), e);
13
- import { FeeOption as L, BaseDecimal as d, Chain as o, ChainToRPC as wt, MemoType as g } from "@swapkit/types";
14
- const At = "0x313ce567", nt = async ({ chain: s, to: t }) => {
13
+ import { FeeOption as L, BaseDecimal as d, Chain as o, EVMChainList as wt, ChainToRPC as At, MemoType as g } from "@swapkit/types";
14
+ const vt = "0x313ce567", nt = async ({ chain: s, to: t }) => {
15
15
  try {
16
- const { result: e } = await Qt.post(wt[s], {
16
+ const { result: e } = await Zt.post(At[s], {
17
17
  headers: {
18
18
  accept: "*/*",
19
19
  "content-type": "application/json",
@@ -23,7 +23,7 @@ const At = "0x313ce567", nt = async ({ chain: s, to: t }) => {
23
23
  id: 44,
24
24
  jsonrpc: "2.0",
25
25
  method: "eth_call",
26
- params: [{ to: t.toLowerCase(), data: At }, "latest"]
26
+ params: [{ to: t.toLowerCase(), data: vt }, "latest"]
27
27
  })
28
28
  });
29
29
  return parseInt(BigInt(e).toString());
@@ -35,25 +35,25 @@ const At = "0x313ce567", nt = async ({ chain: s, to: t }) => {
35
35
  return d.ETH;
36
36
  const [, t] = s.split("-");
37
37
  return t != null && t.startsWith("0x") ? nt({ chain: o.Ethereum, to: t }) : d.ETH;
38
- }, vt = async (s) => {
38
+ }, $t = async (s) => {
39
39
  const [, t] = s.split("-");
40
40
  return t != null && t.startsWith("0x") ? nt({ chain: o.Avalanche, to: t.toLowerCase() }) : d.AVAX;
41
- }, $t = async (s) => s === o.BinanceSmartChain ? d.BSC : d.BSC, Rt = async ({ chain: s, symbol: t }) => {
41
+ }, Rt = async (s) => s === o.BinanceSmartChain ? d.BSC : d.BSC, St = async ({ chain: s, symbol: t }) => {
42
42
  switch (s) {
43
43
  case o.Ethereum:
44
44
  return Tt(t);
45
45
  case o.Avalanche:
46
- return vt(t);
47
- case o.BinanceSmartChain:
48
46
  return $t(t);
47
+ case o.BinanceSmartChain:
48
+ return Rt(t);
49
49
  default:
50
50
  return d[s];
51
51
  }
52
- }, re = {
52
+ }, ne = {
53
53
  [L.Average]: 1.2,
54
54
  [L.Fast]: 1.5,
55
55
  [L.Fastest]: 2
56
- }, St = ({ chain: s, symbol: t }) => {
56
+ }, Ct = ({ chain: s, symbol: t }) => {
57
57
  switch (s) {
58
58
  case o.Bitcoin:
59
59
  case o.BitcoinCash:
@@ -79,7 +79,7 @@ const At = "0x313ce567", nt = async ({ chain: s, to: t }) => {
79
79
  case o.THORChain:
80
80
  return t === "RUNE";
81
81
  }
82
- }, Ct = (s) => {
82
+ }, It = (s) => {
83
83
  switch (s) {
84
84
  case "ETH.THOR":
85
85
  return { identifier: "ETH.THOR-0xa5f2211b9b8170f694421f2046281775e8468044", decimal: 18 };
@@ -108,7 +108,7 @@ const At = "0x313ce567", nt = async ({ chain: s, to: t }) => {
108
108
  case o.Ethereum:
109
109
  return { identifier: `${s}.${s}`, decimal: d[s] };
110
110
  }
111
- }, It = ({ chain: s, symbol: t }) => {
111
+ }, Et = ({ chain: s, symbol: t }) => {
112
112
  if (t.includes("/"))
113
113
  return "Synth";
114
114
  switch (s) {
@@ -138,40 +138,40 @@ const At = "0x313ce567", nt = async ({ chain: s, to: t }) => {
138
138
  case o.Optimism:
139
139
  return [o.Ethereum, o.Optimism].includes(t) ? "Native" : "OPTIMISM";
140
140
  }
141
- }, se = (s) => {
141
+ }, ie = (s) => {
142
142
  var c;
143
143
  const [t, ...e] = s.split("."), r = s.includes("/"), n = e.join("."), i = (c = n == null ? void 0 : n.split("-")) == null ? void 0 : c[0];
144
144
  return { chain: t, symbol: n, ticker: i, synth: r };
145
- }, Et = new RegExp(
145
+ }, Ot = new RegExp(
146
146
  /(.)\1{6}|\.ORG|\.NET|\.FINANCE|\.COM|WWW|HTTP|\\\\|\/\/|[\s$%:[\]]/,
147
147
  "gmi"
148
- ), ne = (s) => s.filter(
149
- (t) => !Et.test(t.toString()) && !t.toString().includes("undefined")
150
- ), Ot = ({
148
+ ), Bt = (s) => wt.includes(s.chain) ? !s.isGasAsset && s.address && !Number.isNaN(s.decimal) : !0, oe = (s) => s.filter(
149
+ (t) => !t.toString().includes("undefined") && !Ot.test(t.toString()) && Bt(t)
150
+ ), Mt = ({
151
151
  liquidityUnits: s,
152
152
  poolUnits: t,
153
153
  runeDepth: e
154
154
  }) => {
155
155
  const r = p(s), n = p(t), i = p(e), c = r.mul(i), a = n.mul(n).mul(2), u = n.mul(r).mul(2), l = r.mul(r), h = n.mul(n).mul(n);
156
156
  return c.mul(a.sub(u).add(l)).div(h);
157
- }, Bt = ({
157
+ }, Vt = ({
158
158
  liquidityUnits: s,
159
159
  poolUnits: t,
160
160
  assetDepth: e
161
161
  }) => {
162
162
  const r = p(s), n = p(t), i = p(e), c = r.mul(i), a = n.mul(n).mul(2), u = n.mul(r).mul(2), l = r.mul(r), h = c.mul(a.sub(u).add(l)), _ = n.mul(n).mul(n);
163
163
  return h.div(_);
164
- }, ie = ({
164
+ }, ae = ({
165
165
  percent: s,
166
166
  runeDepth: t,
167
167
  liquidityUnits: e,
168
168
  poolUnits: r
169
- }) => Ot({ runeDepth: t, liquidityUnits: e, poolUnits: r }).mul(s), oe = ({
169
+ }) => Mt({ runeDepth: t, liquidityUnits: e, poolUnits: r }).mul(s), ce = ({
170
170
  percent: s,
171
171
  assetDepth: t,
172
172
  liquidityUnits: e,
173
173
  poolUnits: r
174
- }) => Bt({ assetDepth: t, liquidityUnits: e, poolUnits: r }).mul(s), p = (s) => b.fromBigInt(BigInt(s), d.THOR), Mt = ({
174
+ }) => Vt({ assetDepth: t, liquidityUnits: e, poolUnits: r }).mul(s), p = (s) => b.fromBigInt(BigInt(s), d.THOR), kt = ({
175
175
  liquidityUnits: s,
176
176
  poolUnits: t,
177
177
  runeDepth: e,
@@ -179,17 +179,17 @@ const At = "0x313ce567", nt = async ({ chain: s, to: t }) => {
179
179
  }) => ({
180
180
  assetAmount: p(r).mul(s).div(t),
181
181
  runeAmount: p(e).mul(s).div(t)
182
- }), ae = ({
182
+ }), ue = ({
183
183
  liquidityUnits: s,
184
184
  poolUnits: t,
185
185
  runeDepth: e,
186
186
  assetDepth: r,
187
187
  percent: n
188
188
  }) => Object.fromEntries(
189
- Object.entries(Mt({ liquidityUnits: s, poolUnits: t, runeDepth: e, assetDepth: r })).map(
189
+ Object.entries(kt({ liquidityUnits: s, poolUnits: t, runeDepth: e, assetDepth: r })).map(
190
190
  ([i, c]) => [i, c.mul(n)]
191
191
  )
192
- ), ce = ({
192
+ ), le = ({
193
193
  runeDepth: s,
194
194
  poolUnits: t,
195
195
  assetDepth: e,
@@ -197,12 +197,12 @@ const At = "0x313ce567", nt = async ({ chain: s, to: t }) => {
197
197
  runeAmount: n,
198
198
  assetAmount: i
199
199
  }) => {
200
- const c = new b({ value: s, decimal: 8 }), a = new b({ value: e, decimal: 8 }), u = new b({ value: t, decimal: 8 }), l = new b({ value: n, decimal: 8 }), h = new b({ value: i, decimal: 8 }), _ = l.mul(a), v = h.mul(c), j = l.mul(h), mt = c.mul(a), pt = u.mul(_.add(v.add(j.mul(2)))), ft = _.add(v.add(mt.mul(2))), Q = pt.div(ft), H = p(r).add(Q);
200
+ const c = new b({ value: s, decimal: 8 }), a = new b({ value: e, decimal: 8 }), u = new b({ value: t, decimal: 8 }), l = new b({ value: n, decimal: 8 }), h = new b({ value: i, decimal: 8 }), _ = l.mul(a), T = h.mul(c), j = l.mul(h), mt = c.mul(a), pt = u.mul(_.add(T.add(j.mul(2)))), ft = _.add(T.add(mt.mul(2))), Q = pt.div(ft), H = p(r).add(Q);
201
201
  if (Q.getBaseValue("number") === 0)
202
202
  return H.div(u).getBaseValue("number");
203
203
  const _t = u.add(H);
204
204
  return H.div(_t).getBaseValue("number");
205
- }, ue = ({
205
+ }, he = ({
206
206
  runeAmount: s,
207
207
  assetAmount: t,
208
208
  runeDepth: e,
@@ -212,11 +212,11 @@ const At = "0x313ce567", nt = async ({ chain: s, to: t }) => {
212
212
  return 0;
213
213
  const n = p(e), i = p(r), c = p(t), a = p(s), u = c.mul(n).sub(i.mul(a)), l = i.mul(a).add(n.mul(i));
214
214
  return Math.abs(u.div(l).getBaseValue("number"));
215
- }, Vt = ({
215
+ }, qt = ({
216
216
  symbol: s,
217
217
  ticker: t,
218
218
  chain: e
219
- }) => e === "ETH" && t !== "ETH" ? `${t}-${s.slice(-3)}` : s, le = (s, t) => {
219
+ }) => e === "ETH" && t !== "ETH" ? `${t}-${s.slice(-3)}` : s, de = (s, t) => {
220
220
  switch (s) {
221
221
  case g.LEAVE:
222
222
  case g.BOND: {
@@ -236,7 +236,7 @@ const At = "0x313ce567", nt = async ({ chain: s, to: t }) => {
236
236
  return i ? `${s}:${e}/${r}::t:0` : `${s}:${e}.${r}:${n || ""}:t:0`;
237
237
  }
238
238
  case g.WITHDRAW: {
239
- const { chain: e, ticker: r, symbol: n, basisPoints: i, targetAssetString: c, singleSide: a } = t, u = !a && c ? `:${c}` : "", l = Vt({ chain: e, symbol: n, ticker: r });
239
+ const { chain: e, ticker: r, symbol: n, basisPoints: i, targetAssetString: c, singleSide: a } = t, u = !a && c ? `:${c}` : "", l = qt({ chain: e, symbol: n, ticker: r });
240
240
  return `${s}:${e}${a ? "/" : "."}${l}:${i}${u}`;
241
241
  }
242
242
  case g.OPEN_LOAN:
@@ -247,16 +247,16 @@ const At = "0x313ce567", nt = async ({ chain: s, to: t }) => {
247
247
  default:
248
248
  return "";
249
249
  }
250
- }, he = (s) => {
250
+ }, me = (s) => {
251
251
  if (s < 0)
252
252
  throw new Error("Invalid number of year");
253
253
  return 10 + s;
254
- }, de = (s) => {
254
+ }, pe = (s) => {
255
255
  if (s.length > 30)
256
256
  return !1;
257
257
  const t = /^[a-zA-Z0-9+_-]+$/g;
258
258
  return !!s.match(t);
259
- }, me = ([s, t, e, r, n]) => `${s}'/${t}'/${e}'/${r}${typeof n != "number" ? "" : `/${n}`}`;
259
+ }, fe = ([s, t, e, r, n]) => `${s}'/${t}'/${e}'/${r}${typeof n != "number" ? "" : `/${n}`}`;
260
260
  class X extends Error {
261
261
  constructor(t, e, r) {
262
262
  const n = t.status || t.status === 0 ? t.status : "", i = t.statusText || "", c = `${n} ${i}`.trim(), a = c ? `status code ${c}` : "an unknown error";
@@ -309,7 +309,7 @@ const V = (s) => s !== null && typeof s == "object", M = (...s) => {
309
309
  V(r.headers) && (e = ot(e, r.headers), t.headers = e);
310
310
  }
311
311
  return t;
312
- }, kt = (() => {
312
+ }, xt = (() => {
313
313
  let s = !1, t = !1;
314
314
  const e = typeof globalThis.ReadableStream == "function", r = typeof globalThis.Request == "function";
315
315
  return e && r && (t = new globalThis.Request("https://empty.invalid", {
@@ -320,13 +320,13 @@ const V = (s) => s !== null && typeof s == "object", M = (...s) => {
320
320
  return s = !0, "half";
321
321
  }
322
322
  }).headers.has("Content-Type")), s && !t;
323
- })(), qt = typeof globalThis.AbortController == "function", xt = typeof globalThis.ReadableStream == "function", Pt = typeof globalThis.FormData == "function", at = ["get", "post", "put", "patch", "head", "delete"], Nt = {
323
+ })(), Pt = typeof globalThis.AbortController == "function", Nt = typeof globalThis.ReadableStream == "function", jt = typeof globalThis.FormData == "function", at = ["get", "post", "put", "patch", "head", "delete"], Ht = {
324
324
  json: "application/json",
325
325
  text: "text/*",
326
326
  formData: "multipart/form-data",
327
327
  arrayBuffer: "*/*",
328
328
  blob: "*/*"
329
- }, D = 2147483647, ct = Symbol("stop"), jt = {
329
+ }, D = 2147483647, ct = Symbol("stop"), Lt = {
330
330
  json: !0,
331
331
  parseJson: !0,
332
332
  searchParams: !0,
@@ -337,7 +337,7 @@ const V = (s) => s !== null && typeof s == "object", M = (...s) => {
337
337
  throwHttpErrors: !0,
338
338
  onDownloadProgress: !0,
339
339
  fetch: !0
340
- }, Ht = {
340
+ }, Dt = {
341
341
  method: !0,
342
342
  headers: !0,
343
343
  body: !0,
@@ -353,15 +353,15 @@ const V = (s) => s !== null && typeof s == "object", M = (...s) => {
353
353
  window: !0,
354
354
  dispatcher: !0,
355
355
  duplex: !0
356
- }, Lt = (s) => at.includes(s) ? s.toUpperCase() : s, Dt = ["get", "put", "head", "delete", "options", "trace"], Ut = [408, 413, 429, 500, 502, 503, 504], ut = [413, 429, 503], Z = {
356
+ }, Ut = (s) => at.includes(s) ? s.toUpperCase() : s, Ft = ["get", "put", "head", "delete", "options", "trace"], Wt = [408, 413, 429, 500, 502, 503, 504], ut = [413, 429, 503], Z = {
357
357
  limit: 2,
358
- methods: Dt,
359
- statusCodes: Ut,
358
+ methods: Ft,
359
+ statusCodes: Wt,
360
360
  afterStatusCodes: ut,
361
361
  maxRetryAfter: Number.POSITIVE_INFINITY,
362
362
  backoffLimit: Number.POSITIVE_INFINITY,
363
363
  delay: (s) => 0.3 * 2 ** (s - 1) * 1e3
364
- }, Ft = (s = {}) => {
364
+ }, Gt = (s = {}) => {
365
365
  if (typeof s == "number")
366
366
  return {
367
367
  ...Z,
@@ -377,7 +377,7 @@ const V = (s) => s !== null && typeof s == "object", M = (...s) => {
377
377
  afterStatusCodes: ut
378
378
  };
379
379
  };
380
- async function Wt(s, t, e, r) {
380
+ async function Yt(s, t, e, r) {
381
381
  return new Promise((n, i) => {
382
382
  const c = setTimeout(() => {
383
383
  e && e.abort(), i(new it(s));
@@ -387,7 +387,7 @@ async function Wt(s, t, e, r) {
387
387
  });
388
388
  });
389
389
  }
390
- async function Gt(s, { signal: t }) {
390
+ async function zt(s, { signal: t }) {
391
391
  return new Promise((e, r) => {
392
392
  t && (t.throwIfAborted(), t.addEventListener("abort", n, { once: !0 }));
393
393
  function n() {
@@ -398,10 +398,10 @@ async function Gt(s, { signal: t }) {
398
398
  }, s);
399
399
  });
400
400
  }
401
- const Yt = (s, t) => {
401
+ const Jt = (s, t) => {
402
402
  const e = {};
403
403
  for (const r in t)
404
- !(r in Ht) && !(r in jt) && !(r in s) && (e[r] = t[r]);
404
+ !(r in Dt) && !(r in Lt) && !(r in s) && (e[r] = t[r]);
405
405
  return e;
406
406
  };
407
407
  class q {
@@ -424,13 +424,13 @@ class q {
424
424
  if (r._options.onDownloadProgress) {
425
425
  if (typeof r._options.onDownloadProgress != "function")
426
426
  throw new TypeError("The `onDownloadProgress` option must be a function");
427
- if (!xt)
427
+ if (!Nt)
428
428
  throw new Error("Streams are not supported in your environment. `ReadableStream` is missing.");
429
429
  return r._stream(a.clone(), r._options.onDownloadProgress);
430
430
  }
431
431
  return a;
432
432
  }, c = r._options.retry.methods.includes(r.request.method.toLowerCase()) ? r._retry(n) : n();
433
- for (const [a, u] of Object.entries(Nt))
433
+ for (const [a, u] of Object.entries(Ht))
434
434
  c[a] = async () => {
435
435
  r.request.headers.set("accept", r.request.headers.get("accept") || u);
436
436
  const h = (await c).clone();
@@ -482,10 +482,10 @@ class q {
482
482
  beforeError: [],
483
483
  afterResponse: []
484
484
  }, e.hooks),
485
- method: Lt(e.method ?? this._input.method),
485
+ method: Ut(e.method ?? this._input.method),
486
486
  // eslint-disable-next-line @typescript-eslint/prefer-nullish-coalescing
487
487
  prefixUrl: String(e.prefixUrl || ""),
488
- retry: Ft(e.retry),
488
+ retry: Gt(e.retry),
489
489
  throwHttpErrors: e.throwHttpErrors !== !1,
490
490
  timeout: e.timeout ?? 1e4,
491
491
  fetch: e.fetch ?? globalThis.fetch.bind(globalThis)
@@ -496,7 +496,7 @@ class q {
496
496
  throw new Error("`input` must not begin with a slash when using `prefixUrl`");
497
497
  this._options.prefixUrl.endsWith("/") || (this._options.prefixUrl += "/"), this._input = this._options.prefixUrl + this._input;
498
498
  }
499
- if (qt) {
499
+ if (Pt) {
500
500
  if (this.abortController = new globalThis.AbortController(), this._options.signal) {
501
501
  const r = this._options.signal;
502
502
  this._options.signal.addEventListener("abort", () => {
@@ -505,9 +505,9 @@ class q {
505
505
  }
506
506
  this._options.signal = this.abortController.signal;
507
507
  }
508
- if (kt && (this._options.duplex = "half"), this.request = new globalThis.Request(this._input, this._options), this._options.searchParams) {
508
+ if (xt && (this._options.duplex = "half"), this.request = new globalThis.Request(this._input, this._options), this._options.searchParams) {
509
509
  const n = "?" + (typeof this._options.searchParams == "string" ? this._options.searchParams.replace(/^\?/, "") : new URLSearchParams(this._options.searchParams).toString()), i = this.request.url.replace(/(?:\?.*?)?(?=#|$)/, n);
510
- (Pt && this._options.body instanceof globalThis.FormData || this._options.body instanceof URLSearchParams) && !(this._options.headers && this._options.headers["content-type"]) && this.request.headers.delete("content-type"), this.request = new globalThis.Request(new globalThis.Request(i, { ...this.request }), this._options);
510
+ (jt && this._options.body instanceof globalThis.FormData || this._options.body instanceof URLSearchParams) && !(this._options.headers && this._options.headers["content-type"]) && this.request.headers.delete("content-type"), this.request = new globalThis.Request(new globalThis.Request(i, { ...this.request }), this._options);
511
511
  }
512
512
  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 }));
513
513
  }
@@ -538,7 +538,7 @@ class q {
538
538
  } catch (e) {
539
539
  const r = Math.min(this._calculateRetryDelay(e), D);
540
540
  if (r !== 0 && this._retryCount > 0) {
541
- await Gt(r, { signal: this._options.signal });
541
+ await zt(r, { signal: this._options.signal });
542
542
  for (const n of this._options.hooks.beforeRetry)
543
543
  if (await n({
544
544
  request: this.request,
@@ -562,8 +562,8 @@ class q {
562
562
  if (r instanceof Response)
563
563
  return r;
564
564
  }
565
- const t = Yt(this.request, this._options);
566
- return this._options.timeout === !1 ? this._options.fetch(this.request.clone(), t) : Wt(this.request.clone(), t, this.abortController, this._options);
565
+ const t = Jt(this.request, this._options);
566
+ return this._options.timeout === !1 ? this._options.fetch(this.request.clone(), t) : Yt(this.request.clone(), t, this.abortController, this._options);
567
567
  }
568
568
  /* istanbul ignore next */
569
569
  _stream(t, e) {
@@ -605,10 +605,10 @@ const F = (s) => {
605
605
  for (const e of at)
606
606
  t[e] = (r, n) => q.create(r, M(s, n, { method: e }));
607
607
  return t.create = (e) => F(M(e)), t.extend = (e) => F(M(s, e)), t.stop = ct, t;
608
- }, zt = F(), Jt = zt, Kt = typeof window < "u" ? {} : { referrer: "https://sk.thorswap.net", referer: "https://sk.thorswap.net" }, tt = Jt.create({ headers: Kt }), Qt = {
608
+ }, Kt = F(), Qt = Kt, Xt = typeof window < "u" ? {} : { referrer: "https://sk.thorswap.net", referer: "https://sk.thorswap.net" }, tt = Qt.create({ headers: Xt }), Zt = {
609
609
  get: (s, t) => tt.get(s, t).json(),
610
610
  post: (s, t) => tt.post(s, t).json()
611
- }, et = Object.values(o), Xt = (s = "") => {
611
+ }, et = Object.values(o), te = (s = "") => {
612
612
  const t = s.toUpperCase(), [e] = t.split(".");
613
613
  if (et.includes(e))
614
614
  return !0;
@@ -635,21 +635,21 @@ function x({
635
635
  ""
636
636
  );
637
637
  }
638
- var A, S, P, lt, N, ht, O, W, T, C, B, G;
638
+ var A, S, P, lt, N, ht, O, W, v, C, B, G;
639
639
  const K = class K {
640
640
  constructor(t) {
641
641
  y(this, A);
642
642
  y(this, P);
643
643
  y(this, N);
644
644
  y(this, O);
645
- y(this, T);
645
+ y(this, v);
646
646
  y(this, B);
647
647
  f(this, "decimalMultiplier", 10n ** 8n);
648
648
  f(this, "bigIntValue", 0n);
649
649
  f(this, "decimal");
650
650
  const e = U(t);
651
651
  this.decimal = typeof t == "object" ? t.decimal : void 0, this.decimalMultiplier = $(
652
- Math.max(m(this, B, G).call(this, m(this, T, C).call(this, e)), this.decimal || 0)
652
+ Math.max(m(this, B, G).call(this, m(this, v, C).call(this, e)), this.decimal || 0)
653
653
  ), m(this, P, lt).call(this, e);
654
654
  }
655
655
  static fromBigInt(t, e) {
@@ -726,7 +726,7 @@ const K = class K {
726
726
  getBigIntValue(t, e) {
727
727
  if (!e && typeof t == "object")
728
728
  return t.bigIntValue;
729
- const r = U(t), n = m(this, T, C).call(this, r);
729
+ const r = U(t), n = m(this, v, C).call(this, r);
730
730
  return n === "0" || n === "undefined" ? 0n : m(this, O, W).call(this, n, e);
731
731
  }
732
732
  formatBigIntToSafeValue(t, e) {
@@ -813,17 +813,17 @@ A = new WeakSet(), S = function(t, ...e) {
813
813
  });
814
814
  return new this.constructor({ decimal: this.decimal, value: c, identifier: this.toString() });
815
815
  }, P = new WeakSet(), lt = function(t) {
816
- const e = m(this, T, C).call(this, t) || "0";
816
+ const e = m(this, v, C).call(this, t) || "0";
817
817
  this.bigIntValue = m(this, O, W).call(this, e);
818
818
  }, N = new WeakSet(), ht = function(...t) {
819
819
  const e = t.map(
820
- (r) => typeof r == "object" ? r.decimal || R(r.decimalMultiplier) : m(this, B, G).call(this, m(this, T, C).call(this, r))
820
+ (r) => typeof r == "object" ? r.decimal || R(r.decimalMultiplier) : m(this, B, G).call(this, m(this, v, C).call(this, r))
821
821
  ).filter(Boolean);
822
822
  return Math.max(...e, I);
823
823
  }, O = new WeakSet(), W = function(t, e) {
824
824
  const r = e ? $(e) : this.decimalMultiplier, n = R(r), [i = "", c = ""] = t.split(".");
825
825
  return BigInt(`${i}${c.padEnd(n, "0")}`);
826
- }, T = new WeakSet(), C = function(t) {
826
+ }, v = new WeakSet(), C = function(t) {
827
827
  const r = `${typeof t == "number" ? Number(t).toLocaleString("fullwide", {
828
828
  useGrouping: !1,
829
829
  maximumFractionDigits: 20
@@ -845,8 +845,8 @@ const rt = (s) => {
845
845
  throw new Error("Static assets not loaded, call await AssetValue.loadStaticAssets() first");
846
846
  return Y.get(s.toUpperCase()) || { decimal: d.THOR, identifier: "" };
847
847
  }, st = async (s, t = 0) => {
848
- Xt(s);
849
- const e = await Rt(z(s)), r = k(t, e);
848
+ te(s);
849
+ const e = await St(z(s)), r = k(t, e);
850
850
  return new w({ decimal: e, value: r, identifier: s });
851
851
  };
852
852
  class w extends E {
@@ -862,7 +862,7 @@ class w extends E {
862
862
  f(this, "ticker");
863
863
  f(this, "type");
864
864
  const r = "identifier" in e ? e.identifier : `${e.chain}.${e.symbol}`, n = z(r);
865
- this.type = It(n), this.chain = n.chain, this.ticker = n.ticker, this.symbol = n.symbol, this.address = n.address, this.isSynthetic = n.isSynthetic, this.isGasAsset = n.isGasAsset;
865
+ this.type = Et(n), this.chain = n.chain, this.ticker = n.ticker, this.symbol = n.symbol, this.address = n.address, this.isSynthetic = n.isSynthetic, this.isGasAsset = n.isGasAsset;
866
866
  }
867
867
  get assetValue() {
868
868
  return `${this.getValue("string")} ${this.ticker}`;
@@ -894,7 +894,7 @@ class w extends E {
894
894
  return new w({ decimal: n, identifier: i, value: c });
895
895
  }
896
896
  static fromChainOrSignature(e, r = 0) {
897
- const { decimal: n, identifier: i } = Ct(e), c = k(r, n);
897
+ const { decimal: n, identifier: i } = It(e), c = k(r, n);
898
898
  return new w({ value: c, decimal: n, identifier: i });
899
899
  }
900
900
  static async loadStaticAssets() {
@@ -909,8 +909,8 @@ class w extends E {
909
909
  ...c
910
910
  } = await import("@swapkit/tokens");
911
911
  Y = [i, ...Object.values(c)].reduce(
912
- (u, { tokens: l }) => (l.forEach(({ identifier: h, chain: _, ...v }) => {
913
- const j = "decimals" in v ? v.decimals : d[_];
912
+ (u, { tokens: l }) => (l.forEach(({ identifier: h, chain: _, ...T }) => {
913
+ const j = "decimals" in T ? T.decimals : d[_];
914
914
  u.set(h, { identifier: h, decimal: j });
915
915
  }), u),
916
916
  /* @__PURE__ */ new Map()
@@ -926,7 +926,7 @@ class w extends E {
926
926
  );
927
927
  }
928
928
  }
929
- const pe = (s) => {
929
+ const _e = (s) => {
930
930
  const t = w.fromChainOrSignature(s);
931
931
  switch (s) {
932
932
  case o.Bitcoin:
@@ -949,12 +949,12 @@ const pe = (s) => {
949
949
  return {
950
950
  address: u == null ? void 0 : u.toLowerCase(),
951
951
  chain: i,
952
- isGasAsset: St({ chain: i, symbol: c }),
952
+ isGasAsset: Ct({ chain: i, symbol: c }),
953
953
  isSynthetic: t,
954
954
  symbol: (t ? `${e}/` : "") + (u ? `${a}-${(u == null ? void 0 : u.toLowerCase()) ?? ""}` : c),
955
955
  ticker: a
956
956
  };
957
- }, Zt = {
957
+ }, ee = {
958
958
  /**
959
959
  * Core
960
960
  */
@@ -1013,7 +1013,7 @@ const pe = (s) => {
1013
1013
  };
1014
1014
  class dt extends Error {
1015
1015
  constructor(t, e) {
1016
- console.error(e), super(t, { cause: { code: Zt[t], message: t } }), Object.setPrototypeOf(this, dt.prototype);
1016
+ console.error(e), super(t, { cause: { code: ee[t], message: t } }), Object.setPrototypeOf(this, dt.prototype);
1017
1017
  }
1018
1018
  }
1019
1019
  class b extends E {
@@ -1030,28 +1030,28 @@ class b extends E {
1030
1030
  export {
1031
1031
  w as AssetValue,
1032
1032
  E as BigIntArithmetics,
1033
- Qt as RequestClient,
1033
+ Zt as RequestClient,
1034
1034
  dt as SwapKitError,
1035
1035
  b as SwapKitNumber,
1036
- se as assetFromString,
1037
- me as derivationPathToString,
1038
- ne as filterAssets,
1036
+ ie as assetFromString,
1037
+ fe as derivationPathToString,
1038
+ oe as filterAssets,
1039
1039
  x as formatBigIntToSafeValue,
1040
- re as gasFeeMultiplier,
1041
- It as getAssetType,
1042
- Bt as getAsymmetricAssetShare,
1043
- oe as getAsymmetricAssetWithdrawAmount,
1044
- Ot as getAsymmetricRuneShare,
1045
- ie as getAsymmetricRuneWithdrawAmount,
1046
- Ct as getCommonAssetInfo,
1047
- Rt as getDecimal,
1048
- ce as getEstimatedPoolShare,
1049
- ue as getLiquiditySlippage,
1050
- le as getMemoFor,
1051
- pe as getMinAmountByChain,
1052
- Mt as getSymmetricPoolShare,
1053
- ae as getSymmetricWithdraw,
1054
- he as getTHORNameCost,
1055
- St as isGasAsset,
1056
- de as validateTHORName
1040
+ ne as gasFeeMultiplier,
1041
+ Et as getAssetType,
1042
+ Vt as getAsymmetricAssetShare,
1043
+ ce as getAsymmetricAssetWithdrawAmount,
1044
+ Mt as getAsymmetricRuneShare,
1045
+ ae as getAsymmetricRuneWithdrawAmount,
1046
+ It as getCommonAssetInfo,
1047
+ St as getDecimal,
1048
+ le as getEstimatedPoolShare,
1049
+ he as getLiquiditySlippage,
1050
+ de as getMemoFor,
1051
+ _e as getMinAmountByChain,
1052
+ kt as getSymmetricPoolShare,
1053
+ ue as getSymmetricWithdraw,
1054
+ me as getTHORNameCost,
1055
+ Ct as isGasAsset,
1056
+ pe as validateTHORName
1057
1057
  };
package/package.json CHANGED
@@ -42,7 +42,7 @@
42
42
  "repository": "https://github.com/thorswap/SwapKit.git",
43
43
  "type": "module",
44
44
  "types": "./dist/index.d.ts",
45
- "version": "1.0.0-rc.22",
45
+ "version": "1.0.0-rc.23",
46
46
  "scripts": {
47
47
  "build": "vite build",
48
48
  "clean": "rm -rf dist vite.config.ts.* .turbo node_modules",
@@ -1,5 +1,5 @@
1
1
  import type { EVMChain } from '@swapkit/types';
2
- import { BaseDecimal, Chain, ChainToRPC, FeeOption } from '@swapkit/types';
2
+ import { BaseDecimal, Chain, ChainToRPC, EVMChainList, FeeOption } from '@swapkit/types';
3
3
 
4
4
  import { type AssetValue, RequestClient } from '../index.ts';
5
5
 
@@ -186,8 +186,17 @@ const potentialScamRegex = new RegExp(
186
186
  /(.)\1{6}|\.ORG|\.NET|\.FINANCE|\.COM|WWW|HTTP|\\\\|\/\/|[\s$%:[\]]/,
187
187
  'gmi',
188
188
  );
189
+
190
+ const evmAssetHasAddress = (asset: AssetValue) => {
191
+ if (!EVMChainList.includes(asset.chain as EVMChain)) return true;
192
+
193
+ return !asset.isGasAsset && asset.address && !Number.isNaN(asset.decimal);
194
+ };
195
+
189
196
  export const filterAssets = (assets: AssetValue[]) =>
190
197
  assets.filter(
191
198
  (asset) =>
192
- !potentialScamRegex.test(asset.toString()) && !asset.toString().includes('undefined'),
199
+ !asset.toString().includes('undefined') &&
200
+ !potentialScamRegex.test(asset.toString()) &&
201
+ evmAssetHasAddress(asset),
193
202
  );