@swapkit/helpers 1.0.0-rc.14 → 1.0.0-rc.16

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 H=Object.defineProperty;var Se=Object.getOwnPropertyDescriptor;var ve=Object.getOwnPropertyNames;var Re=Object.getPrototypeOf,Ie=Object.prototype.hasOwnProperty;var $e=(s,e,t)=>e in s?H(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t;var Be=(s,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of ve(e))!Ie.call(s,n)&&n!==t&&H(s,n,{get:()=>e[n],enumerable:!(r=Se(e,n))||r.enumerable});return s};var Ee=(s,e,t)=>(t=s!=null?Te(Re(s)):{},Be(e||!s||!s.__esModule?H(t,"default",{value:s,enumerable:!0}):t,s));var p=(s,e,t)=>($e(s,typeof e!="symbol"?e+"":e,t),t),Oe=(s,e,t)=>{if(!e.has(s))throw TypeError("Cannot "+t)};var _=(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 m=(s,e,t)=>(Oe(s,e,"access private method"),t);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const i=require("@swapkit/types"),Me="0x313ce567",ne=async({chain:s,to:e})=>{try{const{result:t}=await ge.post(i.ChainToRPC[s],{headers:{accept:"*/*","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[s]}},Ve=async s=>{if(s===i.Chain.Ethereum)return i.BaseDecimal.ETH;const[,e]=s.split("-");return e!=null&&e.startsWith("0x")?ne({chain:i.Chain.Ethereum,to:e}):i.BaseDecimal.ETH},ke=async s=>{const[,e]=s.split("-");return e!=null&&e.startsWith("0x")?ne({chain:i.Chain.Avalanche,to:e.toLowerCase()}):i.BaseDecimal.AVAX},qe=async s=>(s===i.Chain.BinanceSmartChain,i.BaseDecimal.BSC),z=async({chain:s,symbol:e})=>{switch(s){case i.Chain.Ethereum:return Ve(e);case i.Chain.Avalanche:return ke(e);case i.Chain.BinanceSmartChain:return qe(e);default:return i.BaseDecimal[s]}},Pe={[i.FeeOption.Average]:1.2,[i.FeeOption.Fast]:1.5,[i.FeeOption.Fastest]:2},ie=({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"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[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"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:`${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"}},xe=s=>{var o;const[e,...t]=s.split("."),r=s.includes("/"),n=t.join("."),a=(o=n==null?void 0:n.split("-"))==null?void 0:o[0];return{chain:e,symbol:n,ticker:a,synth:r}},De=new RegExp(/(.)\1{6}|\.ORG|\.NET|\.FINANCE|\.COM|WWW|HTTP|\\\\|\/\/|[\s$%:[\]]/,"gmi"),Ne=s=>s.filter(e=>!De.test(e.toString())&&!e.toString().includes("undefined")),ce=({liquidityUnits:s,poolUnits:e,runeDepth:t})=>{const r=d(s),n=d(e),a=d(t),o=r.mul(a),c=n.mul(n).mul(2),u=n.mul(r).mul(2),l=r.mul(r),h=n.mul(n).mul(n);return o.mul(c.sub(u).add(l)).div(h)},ue=({liquidityUnits:s,poolUnits:e,assetDepth:t})=>{const r=d(s),n=d(e),a=d(t),o=r.mul(a),c=n.mul(n).mul(2),u=n.mul(r).mul(2),l=r.mul(r),h=o.mul(c.sub(u).add(l)),g=n.mul(n).mul(n);return h.div(g)},He=({percent:s,runeDepth:e,liquidityUnits:t,poolUnits:r})=>ce({runeDepth:e,liquidityUnits:t,poolUnits:r}).mul(s),je=({percent:s,assetDepth:e,liquidityUnits:t,poolUnits:r})=>ue({assetDepth:e,liquidityUnits:t,poolUnits:r}).mul(s),d=s=>new x({value:s,decimal:i.BaseDecimal.THOR}),le=({liquidityUnits:s,poolUnits:e,runeDepth:t,assetDepth:r})=>({assetAmount:d(r).mul(s).div(e),runeAmount:d(t).mul(s).div(e)}),Le=({liquidityUnits:s,poolUnits:e,runeDepth:t,assetDepth:r,percent:n})=>Object.fromEntries(Object.entries(le({liquidityUnits:s,poolUnits:e,runeDepth:t,assetDepth:r})).map(([a,o])=>[a,o.mul(n)])),Fe=({runeDepth:s,poolUnits:e,assetDepth:t,liquidityUnits:r,runeAmount:n,assetAmount:a})=>{const o=d(s),c=d(t),u=d(e),l=d(n),h=d(a),g=l.mul(c),C=h.mul(o),D=l.mul(h),ye=o.mul(c),Ce=u.mul(g.add(C.add(D.mul(2)))),we=g.add(C.add(ye.mul(2))),X=Ce.div(we),N=d(r).add(X);if(X.baseValueNumber===0)return N.div(u).baseValueNumber;const Ae=u.add(N);return N.div(Ae).baseValueNumber},Ue=({runeAmount:s,assetAmount:e,runeDepth:t,assetDepth:r})=>{const n=d(t),a=d(r),o=d(e),c=d(s),u=o.mul(n).sub(a.mul(c)),l=a.mul(c).add(n.mul(a));return Math.abs(u.div(l).baseValueNumber)},We=({symbol:s,ticker:e,chain:t})=>t==="ETH"&&e!=="ETH"?`${e}-${s.slice(-3)}`:s,Ge=(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:r}=e;return`${s}:${t}:${r*10**8}`}case i.MemoType.THORNAME_REGISTER:{const{name:t,chain:r,address:n,owner:a}=e;return`${s}:${t}:${r}:${n}${a?`:${a}`:""}`}case i.MemoType.DEPOSIT:{const{chain:t,symbol:r,address:n,singleSide:a}=e;return a?`${s}:${t}/${r}::t:0`:`${s}:${t}.${r}:${n||""}:t:0`}case i.MemoType.WITHDRAW:{const{chain:t,ticker:r,symbol:n,basisPoints:a,targetAssetString:o,singleSide:c}=e,u=!c&&o?`:${o}`:"",l=We({chain:t,symbol:n,ticker:r});return`${s}:${t}${c?"/":"."}${l}:${a}${u}`}case i.MemoType.OPEN_LOAN:case i.MemoType.CLOSE_LOAN:{const{asset:t,address:r}=e;return`${s}:${t}:${r}`}default:return""}},Ke=s=>{if(s<0)throw new Error("Invalid number of year");return 10+s},Ye=s=>{if(s.length>30)return!1;const e=/^[a-zA-Z0-9+_-]+$/g;return!!s.match(e)},ze=([s,e,t,r,n])=>`${s}'/${e}'/${t}'/${r}${typeof n!="number"?"":`/${n}`}`;class Z extends Error{constructor(e,t,r){const n=e.status||e.status===0?e.status:"",a=e.statusText||"",o=`${n} ${a}`.trim(),c=o?`status code ${o}`:"an unknown error";super(`Request failed with ${c}`),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=r}}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=s=>s!==null&&typeof s=="object",E=(...s)=>{for(const e of s)if((!O(e)||Array.isArray(e))&&e!==void 0)throw new TypeError("The `options` argument must be an object");return J({},...s)},de=(s={},e={})=>{const t=new globalThis.Headers(s),r=e instanceof globalThis.Headers,n=new globalThis.Headers(e);for(const[a,o]of n.entries())r&&o==="undefined"||o===void 0?t.delete(a):t.set(a,o);return t},J=(...s)=>{let e={},t={};for(const r of s)if(Array.isArray(r))Array.isArray(e)||(e=[]),e=[...e,...r];else if(O(r)){for(let[n,a]of Object.entries(r))O(a)&&n in e&&(a=J(e[n],a)),e={...e,[n]:a};O(r.headers)&&(t=de(t,r.headers),e.headers=t)}return e},Je=(()=>{let s=!1,e=!1;const t=typeof globalThis.ReadableStream=="function",r=typeof globalThis.Request=="function";return t&&r&&(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:"*/*"},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},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},st=s=>me.includes(s)?s.toUpperCase():s,nt=["get","put","head","delete","options","trace"],it=[408,413,429,500,502,503,504],fe=[413,429,503],ee={limit:2,methods:nt,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{...ee,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{...ee,...s,afterStatusCodes:fe}};async function ot(s,e,t,r){return new Promise((n,a)=>{const o=setTimeout(()=>{t&&t.abort(),a(new he(s))},r.timeout);r.fetch(s,e).then(n).catch(a).then(()=>{clearTimeout(o)})})}async function ct(s,{signal:e}){return new Promise((t,r)=>{e&&(e.throwIfAborted(),e.addEventListener("abort",n,{once:!0}));function n(){clearTimeout(a),r(e.reason)}const a=setTimeout(()=>{e==null||e.removeEventListener("abort",n),t()},s)})}const ut=(s,e)=>{const t={};for(const r in e)!(r in rt)&&!(r in tt)&&!(r in s)&&(t[r]=e[r]);return t};class V{static create(e,t){const r=new V(e,t),n=async()=>{if(typeof r._options.timeout=="number"&&r._options.timeout>j)throw new RangeError(`The \`timeout\` option cannot be greater than ${j}`);await Promise.resolve();let c=await r._fetch();for(const u of r._options.hooks.afterResponse){const l=await u(r.request,r._options,r._decorateResponse(c.clone()));l instanceof globalThis.Response&&(c=l)}if(r._decorateResponse(c),!c.ok&&r._options.throwHttpErrors){let u=new Z(c,r.request,r._options);for(const l of r._options.hooks.beforeError)u=await l(u);throw u}if(r._options.onDownloadProgress){if(typeof r._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 r._stream(c.clone(),r._options.onDownloadProgress)}return c},o=r._options.retry.methods.includes(r.request.method.toLowerCase())?r._retry(n):n();for(const[c,u]of Object.entries(et))o[c]=async()=>{r.request.headers.set("accept",r.request.headers.get("accept")||u);const h=(await o).clone();if(c==="json"){if(h.status===204||(await h.clone().arrayBuffer()).byteLength===0)return"";if(t.parseJson)return t.parseJson(await h.text())}return h[c]()};return o}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:J({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 r=this._options.signal;this._options.signal.addEventListener("abort",()=>{this.abortController.abort(r.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 Z){if(!this._options.retry.statusCodes.includes(e.response.status))return 0;const r=e.response.headers.get("Retry-After");if(r&&this._options.retry.afterStatusCodes.includes(e.response.status)){let n=Number(r);return Number.isNaN(n)?n=Date.parse(r)-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 r=Math.min(this._calculateRetryDelay(t),j);if(r!==0&&this._retryCount>0){await ct(r,{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 r=await t(this.request,this._options);if(r instanceof Request){this.request=r;break}if(r instanceof Response)return r}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 r=Number(e.headers.get("content-length"))||0;let n=0;return e.status===204?(t&&t({percent:1,totalBytes:r,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 o=e.body.getReader();t&&t({percent:0,transferredBytes:0,totalBytes:r},new Uint8Array);async function c(){const{done:u,value:l}=await o.read();if(u){a.close();return}if(t){n+=l.byteLength;const h=r===0?0:n/r;t({percent:h,transferredBytes:n,totalBytes:r},l)}a.enqueue(l),await c()}await c()}}),{status:e.status,statusText:e.statusText,headers:e.headers})}}/*! MIT License © Sindre Sorhus */const U=s=>{const e=(t,r)=>V.create(t,E(s,r));for(const t of me)e[t]=(r,n)=>V.create(r,E(s,n,{method:t}));return e.create=t=>U(E(t)),e.extend=t=>U(E(s,t)),e.stop=pe,e},lt=U(),ht=lt,te=ht.create({headers:{referrer:"https://sk.thorswap.net",referer:"https://sk.thorswap.net","Content-Type":"application/json"}}),ge={get:(s,e)=>te.get(s,e).json(),post:(s,e)=>te.post(s,e).json()},re=Object.values(i.Chain),dt=(s="")=>{const e=s.toUpperCase(),[t]=e.split(".");if(re.includes(t))return!0;const[r]=e.split("/");if(re.includes(r))return!0;throw new Error(`Invalid identifier: ${s}. Expected format: <Chain>.<Ticker> or <Chain>.<Ticker>-<ContractAddress>`)},R=8,w=s=>10n**BigInt(s),T=s=>Math.log10(parseFloat(s.toString()));function I({value:s,bigIntDecimal:e=R,decimal:t=R}){const r=s<0n;let n=s.toString().substring(r?1:0);const a=t-(n.length-1);a>0&&(n="0".repeat(a)+n);const o=n.length-t;let c=n.slice(-t);return parseInt(c[e])>=5?c=`${c.substring(0,e-1)}${(parseInt(c[e-1])+1).toString()}`:c=c.substring(0,e),`${r?"-":""}${n.slice(0,o)}.${c}`.replace(/\.?0*$/,"")}var b,S,k,_e,q,be,$,W,y,v,B,G;const P=class P{constructor(e){_(this,b);_(this,k);_(this,q);_(this,$);_(this,y);_(this,B);p(this,"decimalMultiplier",10n**8n);p(this,"bigIntValue",0n);p(this,"decimal");const t=L(e);this.decimal=typeof e=="object"?e.decimal:void 0,this.decimalMultiplier=w(Math.max(m(this,B,G).call(this,m(this,y,v).call(this,t)),this.decimal||0)),m(this,k,_e).call(this,t)}static fromBigInt(e,t){return new P({decimal:t,value:I({value:e,bigIntDecimal:t,decimal:t})})}static shiftDecimals({value:e,from:t,to:r}){return this.fromBigInt(new P(e).bigIntValue*w(r)/w(t),r)}get baseValue(){return this.getBaseValue("string")}get baseValueNumber(){return this.getBaseValue("number")}get baseValueBigInt(){return this.getBaseValue("bigint")}set(e){return new this.constructor({decimal:this.decimal,value:e,identifier:this.toString()})}add(...e){return m(this,b,S).call(this,"add",...e)}sub(...e){return m(this,b,S).call(this,"sub",...e)}mul(...e){return m(this,b,S).call(this,"mul",...e)}div(...e){return m(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||T(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/w(this.decimal||i.BaseDecimal.THOR),r=this.bigIntValue/t;switch(e){case"number":return Number(r);case"string":return r.toString();default:return r}}getBigIntValue(e,t){if(!t&&typeof e=="object")return e.bigIntValue;const r=L(e),n=m(this,y,v).call(this,r);return n==="0"||n==="undefined"?0n:m(this,$,W).call(this,n,t)}formatBigIntToSafeValue(e,t){const r=t||this.decimal||R,n=Math.max(r,T(this.decimalMultiplier)),a=e<0n,o=e.toString().substring(a?1:0),c=n-(o.length-1),u=c>0?"0".repeat(c)+o:o,l=u.length-n;let h=u.slice(-n);return parseInt(h[r])>=5?h=`${h.substring(0,r-1)}${(parseInt(h[r-1])+1).toString()}`:h=h.substring(0,r),`${a?"-":""}${u.slice(0,l)}.${h}`.replace(/\.?0*$/,"")}toSignificant(e=6){const[t,r]=this.getValue("string").split("."),n=t||"",a=r||"",o=parseInt(n)?n.length+a.length:a.length;if(o<=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(o-e,"0");const c=parseInt(a),u=`${c}`.slice(0,e);return`0.${u.padStart(a.length-`${c}`.length+u.length,"0")}`}toFixed(e=6){const[t,r]=this.getValue("string").split("."),n=t||"",a=r||"";if(parseInt(n))return`${n}.${a.slice(0,e)}`.padEnd(e,"0");const o=parseInt(a),c=`${o}`.slice(0,e);return`0.${c.padStart(a.length-`${o}`.length+c.length,"0")}`}toAbbreviation(e=2){const t=this.getValue("number"),r=["","K","M","B","T","Q","Qi","S"],n=Math.floor(Math.log10(Math.abs(t))/3),a=r[n];if(!a)return this.getValue("string");const o=10**(n*3);return`${(t/o).toFixed(e)}${a}`}};b=new WeakSet,S=function(e,...t){const r=m(this,q,be).call(this,this,...t),n=w(r),a=t.reduce((c,u)=>{const l=this.getBigIntValue(u,r);switch(e){case"add":return c+l;case"sub":return c-l;case"mul":return c*l/n;case"div":{if(l===0n)throw new RangeError("Division by zero");return c*n/l}default:return c}},this.bigIntValue*n/this.decimalMultiplier),o=I({bigIntDecimal:r,decimal:Math.max(r,T(this.decimalMultiplier)),value:a});return new this.constructor({decimal:this.decimal,value:o,identifier:this.toString()})},k=new WeakSet,_e=function(e){const t=m(this,y,v).call(this,e)||"0";this.bigIntValue=m(this,$,W).call(this,t)},q=new WeakSet,be=function(...e){const t=e.map(r=>typeof r=="object"?r.decimal||T(r.decimalMultiplier):m(this,B,G).call(this,m(this,y,v).call(this,r))).filter(Boolean);return Math.max(...t,R)},$=new WeakSet,W=function(e,t){const r=t?w(t):this.decimalMultiplier,n=T(r),[a="",o=""]=e.split(".");return BigInt(`${a}${o.padEnd(n,"0")}`)},y=new WeakSet,v=function(e){const r=`${typeof e=="number"?Number(e).toLocaleString("fullwide",{useGrouping:!1,maximumFractionDigits:20}):L(e)}`.replaceAll(",",".").split(".");return r.length>1?`${r.slice(0,-1).join("")}.${r.at(-1)}`:r[0]},B=new WeakSet,G=function(e){var r;const t=((r=e.split(".")[1])==null?void 0:r.length)||0;return Math.max(t,R)};let A=P;function L(s){return typeof s=="object"?"getValue"in s?s.getValue("string"):s.value:s}const M=(s,e)=>typeof s=="bigint"?I({value:s,bigIntDecimal:e,decimal:e}):s;let K;const F=s=>{if(!K)throw new Error("Static assets not loaded, call await AssetValue.loadStaticAssets() first");return K.get(s.toUpperCase())||{decimal:i.BaseDecimal.THOR,identifier:""}},se=async(s,e=0)=>{dt(s);const t=await z(Y(s)),r=M(e,t);return new f({decimal:t,value:r,identifier:s})};class f extends A{constructor(t){super(t.value instanceof A?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 r="identifier"in t?t.identifier:`${t.chain}.${t.symbol}`,n=Y(r);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 r=this.isSynthetic?this.ticker:`${this.chain}.${this.ticker}`;return t?r:`${this.chain}.${this.symbol}`}eq({chain:t,symbol:r}){return this.chain===t&&this.symbol===r}static async fromString(t,r=0){return se(t,r)}static fromStringSync(t,r=0){const{decimal:n,identifier:a}=F(t),o=M(r,n);return a?new f({decimal:n,identifier:a,value:o}):void 0}static async fromIdentifier(t,r=0){return se(t,r)}static fromIdentifierSync(t,r=0){const{decimal:n,identifier:a}=F(t),o=M(r,n);return new f({decimal:n,identifier:a,value:o})}static fromChainOrSignature(t,r=0){const{decimal:n,identifier:a}=ae(t),o=M(r,n);return new f({value:o,decimal:n,identifier:a})}static async fromTCQuote(t,r=0){const n=await z(Y(t)),a=this.shiftDecimals({value:r,from:i.BaseDecimal.THOR,to:n});return new f({value:a,identifier:t,decimal:n})}static fromTCQuoteStatic(t,r=0){const n=F(t),a=this.shiftDecimals({value:r,from:i.BaseDecimal.THOR,to:n.decimal});return new f({...n,value:a})}static async loadStaticAssets(){return new Promise(async(t,r)=>{try{const{ThorchainList:n,NativeList:a,...o}=await import("@swapkit/tokens");K=[a,...Object.values(o)].reduce((u,{tokens:l})=>(l.forEach(({identifier:h,chain:g,...C})=>{const D="decimals"in C?C.decimals:i.BaseDecimal[g];u.set(h,{identifier:h,decimal:D})}),u),new Map),t({ok:!0})}catch(n){console.error(n),r({ok:!1,error:n,message:"Couldn't load static assets. Ensure you have installed @swapkit/tokens package"})}})}}const mt=s=>{const e=f.fromChainOrSignature(s);switch(s){case i.Chain.Bitcoin:case i.Chain.Litecoin:case i.Chain.BitcoinCash:return e.add(10001);case i.Chain.Dogecoin:return e.add(100000001);case i.Chain.Avalanche:case i.Chain.Ethereum:return e.add(10*10**9);case i.Chain.THORChain:case i.Chain.Maya:return e.add(0);default:return e.add(1)}},Y=s=>{const e=s.slice(0,14).includes("/"),t=s.includes(".")?s:`${i.Chain.THORChain}.${s}`,[r,n]=t.split("."),[a,o]=n.split("-");return{address:o==null?void 0:o.toLowerCase(),chain:r,isGasAsset:ie({chain:r,symbol:n}),isSynthetic:e,symbol:o?`${a}-${(o==null?void 0:o.toLowerCase())??""}`:n,ticker:e?n:a}},pt={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 Q extends Error{constructor(e,t){console.error(t),super(e,{cause:{code:pt[e],message:e}}),Object.setPrototypeOf(this,Q.prototype)}}class x extends A{eq(e){return this.eqValue(e)}static fromBigInt(e,t){return new x({decimal:t,value:I({value:e,bigIntDecimal:t,decimal:t})})}}exports.AssetValue=f;exports.BigIntArithmetics=A;exports.RequestClient=ge;exports.SwapKitError=Q;exports.SwapKitNumber=x;exports.assetFromString=xe;exports.derivationPathToString=ze;exports.filterAssets=Ne;exports.formatBigIntToSafeValue=I;exports.gasFeeMultiplier=Pe;exports.getAssetType=oe;exports.getAsymmetricAssetShare=ue;exports.getAsymmetricAssetWithdrawAmount=je;exports.getAsymmetricRuneShare=ce;exports.getAsymmetricRuneWithdrawAmount=He;exports.getCommonAssetInfo=ae;exports.getDecimal=z;exports.getEstimatedPoolShare=Fe;exports.getLiquiditySlippage=Ue;exports.getMemoFor=Ge;exports.getMinAmountByChain=mt;exports.getSymmetricPoolShare=le;exports.getSymmetricWithdraw=Le;exports.getTHORNameCost=Ke;exports.isGasAsset=ie;exports.validateTHORName=Ye;
1
+ "use strict";var Tt=Object.create;var j=Object.defineProperty;var St=Object.getOwnPropertyDescriptor;var vt=Object.getOwnPropertyNames;var Rt=Object.getPrototypeOf,$t=Object.prototype.hasOwnProperty;var It=(r,t,e)=>t in r?j(r,t,{enumerable:!0,configurable:!0,writable:!0,value:e}):r[t]=e;var Bt=(r,t,e,s)=>{if(t&&typeof t=="object"||typeof t=="function")for(let n of vt(t))!$t.call(r,n)&&n!==e&&j(r,n,{get:()=>t[n],enumerable:!(s=St(t,n))||s.enumerable});return r};var Et=(r,t,e)=>(e=r!=null?Tt(Rt(r)):{},Bt(t||!r||!r.__esModule?j(e,"default",{value:r,enumerable:!0}):e,r));var p=(r,t,e)=>(It(r,typeof t!="symbol"?t+"":t,e),e),Ot=(r,t,e)=>{if(!t.has(r))throw TypeError("Cannot "+e)};var _=(r,t,e)=>{if(t.has(r))throw TypeError("Cannot add the same private member more than once");t instanceof WeakSet?t.add(r):t.set(r,e)};var m=(r,t,e)=>(Ot(r,t,"access private method"),e);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const i=require("@swapkit/types"),Mt="0x313ce567",nt=async({chain:r,to:t})=>{try{const{result:e}=await gt.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:t.toLowerCase(),data:Mt},"latest"]})});return parseInt(BigInt(e).toString())}catch(e){return console.error(e),i.BaseDecimal[r]}},Vt=async r=>{if(r===i.Chain.Ethereum)return i.BaseDecimal.ETH;const[,t]=r.split("-");return t!=null&&t.startsWith("0x")?nt({chain:i.Chain.Ethereum,to:t}):i.BaseDecimal.ETH},qt=async r=>{const[,t]=r.split("-");return t!=null&&t.startsWith("0x")?nt({chain:i.Chain.Avalanche,to:t.toLowerCase()}):i.BaseDecimal.AVAX},kt=async r=>(r===i.Chain.BinanceSmartChain,i.BaseDecimal.BSC),z=async({chain:r,symbol:t})=>{switch(r){case i.Chain.Ethereum:return Vt(t);case i.Chain.Avalanche:return qt(t);case i.Chain.BinanceSmartChain:return kt(t);default:return i.BaseDecimal[r]}},Pt={[i.FeeOption.Average]:1.2,[i.FeeOption.Fast]:1.5,[i.FeeOption.Fastest]:2},it=({chain:r,symbol:t})=>{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 t===r;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"}},at=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]}}},ot=({chain:r,symbol:t})=>{if(t.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 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"}},xt=r=>{var o;const[t,...e]=r.split("."),s=r.includes("/"),n=e.join("."),a=(o=n==null?void 0:n.split("-"))==null?void 0:o[0];return{chain:t,symbol:n,ticker:a,synth:s}},Dt=new RegExp(/(.)\1{6}|\.ORG|\.NET|\.FINANCE|\.COM|WWW|HTTP|\\\\|\/\/|[\s$%:[\]]/,"gmi"),Nt=r=>r.filter(t=>!Dt.test(t.toString())&&!t.toString().includes("undefined")),ct=({liquidityUnits:r,poolUnits:t,runeDepth:e})=>{const s=d(r),n=d(t),a=d(e),o=s.mul(a),c=n.mul(n).mul(2),u=n.mul(s).mul(2),l=s.mul(s),h=n.mul(n).mul(n);return o.mul(c.sub(u).add(l)).div(h)},ut=({liquidityUnits:r,poolUnits:t,assetDepth:e})=>{const s=d(r),n=d(t),a=d(e),o=s.mul(a),c=n.mul(n).mul(2),u=n.mul(s).mul(2),l=s.mul(s),h=o.mul(c.sub(u).add(l)),g=n.mul(n).mul(n);return h.div(g)},Ht=({percent:r,runeDepth:t,liquidityUnits:e,poolUnits:s})=>ct({runeDepth:t,liquidityUnits:e,poolUnits:s}).mul(r),jt=({percent:r,assetDepth:t,liquidityUnits:e,poolUnits:s})=>ut({assetDepth:t,liquidityUnits:e,poolUnits:s}).mul(r),d=r=>new D({value:r,decimal:i.BaseDecimal.THOR}),lt=({liquidityUnits:r,poolUnits:t,runeDepth:e,assetDepth:s})=>({assetAmount:d(s).mul(r).div(t),runeAmount:d(e).mul(r).div(t)}),Lt=({liquidityUnits:r,poolUnits:t,runeDepth:e,assetDepth:s,percent:n})=>Object.fromEntries(Object.entries(lt({liquidityUnits:r,poolUnits:t,runeDepth:e,assetDepth:s})).map(([a,o])=>[a,o.mul(n)])),Ft=({runeDepth:r,poolUnits:t,assetDepth:e,liquidityUnits:s,runeAmount:n,assetAmount:a})=>{const o=d(r),c=d(e),u=d(t),l=d(n),h=d(a),g=l.mul(c),C=h.mul(o),N=l.mul(h),yt=o.mul(c),Ct=u.mul(g.add(C.add(N.mul(2)))),wt=g.add(C.add(yt.mul(2))),X=Ct.div(wt),H=d(s).add(X);if(X.baseValueNumber===0)return H.div(u).baseValueNumber;const At=u.add(H);return H.div(At).baseValueNumber},Ut=({runeAmount:r,assetAmount:t,runeDepth:e,assetDepth:s})=>{const n=d(e),a=d(s),o=d(t),c=d(r),u=o.mul(n).sub(a.mul(c)),l=a.mul(c).add(n.mul(a));return Math.abs(u.div(l).baseValueNumber)},Wt=({symbol:r,ticker:t,chain:e})=>e==="ETH"&&t!=="ETH"?`${t}-${r.slice(-3)}`:r,Gt=(r,t)=>{switch(r){case i.MemoType.LEAVE:case i.MemoType.BOND:{const{address:e}=t;return`${r}:${e}`}case i.MemoType.UNBOND:{const{address:e,unbondAmount:s}=t;return`${r}:${e}:${s*10**8}`}case i.MemoType.THORNAME_REGISTER:{const{name:e,chain:s,address:n,owner:a}=t;return`${r}:${e}:${s}:${n}${a?`:${a}`:""}`}case i.MemoType.DEPOSIT:{const{chain:e,symbol:s,address:n,singleSide:a}=t;return a?`${r}:${e}/${s}::t:0`:`${r}:${e}.${s}:${n||""}:t:0`}case i.MemoType.WITHDRAW:{const{chain:e,ticker:s,symbol:n,basisPoints:a,targetAssetString:o,singleSide:c}=t,u=!c&&o?`:${o}`:"",l=Wt({chain:e,symbol:n,ticker:s});return`${r}:${e}${c?"/":"."}${l}:${a}${u}`}case i.MemoType.OPEN_LOAN:case i.MemoType.CLOSE_LOAN:{const{asset:e,address:s}=t;return`${r}:${e}:${s}`}default:return""}},Kt=r=>{if(r<0)throw new Error("Invalid number of year");return 10+r},Yt=r=>{if(r.length>30)return!1;const t=/^[a-zA-Z0-9+_-]+$/g;return!!r.match(t)},zt=([r,t,e,s,n])=>`${r}'/${t}'/${e}'/${s}${typeof n!="number"?"":`/${n}`}`;class Z extends Error{constructor(t,e,s){const n=t.status||t.status===0?t.status:"",a=t.statusText||"",o=`${n} ${a}`.trim(),c=o?`status code ${o}`:"an unknown error";super(`Request failed with ${c}`),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=e,this.options=s}}class ht 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 O=r=>r!==null&&typeof r=="object",E=(...r)=>{for(const t of r)if((!O(t)||Array.isArray(t))&&t!==void 0)throw new TypeError("The `options` argument must be an object");return J({},...r)},dt=(r={},t={})=>{const e=new globalThis.Headers(r),s=t instanceof globalThis.Headers,n=new globalThis.Headers(t);for(const[a,o]of n.entries())s&&o==="undefined"||o===void 0?e.delete(a):e.set(a,o);return e},J=(...r)=>{let t={},e={};for(const s of r)if(Array.isArray(s))Array.isArray(t)||(t=[]),t=[...t,...s];else if(O(s)){for(let[n,a]of Object.entries(s))O(a)&&n in t&&(a=J(t[n],a)),t={...t,[n]:a};O(s.headers)&&(e=dt(e,s.headers),t.headers=e)}return t},Jt=(()=>{let r=!1,t=!1;const e=typeof globalThis.ReadableStream=="function",s=typeof globalThis.Request=="function";return e&&s&&(t=new globalThis.Request("https://empty.invalid",{body:new globalThis.ReadableStream,method:"POST",get duplex(){return r=!0,"half"}}).headers.has("Content-Type")),r&&!t})(),Qt=typeof globalThis.AbortController=="function",Xt=typeof globalThis.ReadableStream=="function",Zt=typeof globalThis.FormData=="function",mt=["get","post","put","patch","head","delete"],te={json:"application/json",text:"text/*",formData:"multipart/form-data",arrayBuffer:"*/*",blob:"*/*"},L=2147483647,pt=Symbol("stop"),ee={json:!0,parseJson:!0,searchParams:!0,prefixUrl:!0,retry:!0,timeout:!0,hooks:!0,throwHttpErrors:!0,onDownloadProgress:!0,fetch:!0},se={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},re=r=>mt.includes(r)?r.toUpperCase():r,ne=["get","put","head","delete","options","trace"],ie=[408,413,429,500,502,503,504],ft=[413,429,503],tt={limit:2,methods:ne,statusCodes:ie,afterStatusCodes:ft,maxRetryAfter:Number.POSITIVE_INFINITY,backoffLimit:Number.POSITIVE_INFINITY,delay:r=>.3*2**(r-1)*1e3},ae=(r={})=>{if(typeof r=="number")return{...tt,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{...tt,...r,afterStatusCodes:ft}};async function oe(r,t,e,s){return new Promise((n,a)=>{const o=setTimeout(()=>{e&&e.abort(),a(new ht(r))},s.timeout);s.fetch(r,t).then(n).catch(a).then(()=>{clearTimeout(o)})})}async function ce(r,{signal:t}){return new Promise((e,s)=>{t&&(t.throwIfAborted(),t.addEventListener("abort",n,{once:!0}));function n(){clearTimeout(a),s(t.reason)}const a=setTimeout(()=>{t==null||t.removeEventListener("abort",n),e()},r)})}const ue=(r,t)=>{const e={};for(const s in t)!(s in se)&&!(s in ee)&&!(s in r)&&(e[s]=t[s]);return e};class q{static create(t,e){const s=new q(t,e),n=async()=>{if(typeof s._options.timeout=="number"&&s._options.timeout>L)throw new RangeError(`The \`timeout\` option cannot be greater than ${L}`);await Promise.resolve();let c=await s._fetch();for(const u of s._options.hooks.afterResponse){const l=await u(s.request,s._options,s._decorateResponse(c.clone()));l instanceof globalThis.Response&&(c=l)}if(s._decorateResponse(c),!c.ok&&s._options.throwHttpErrors){let u=new Z(c,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(!Xt)throw new Error("Streams are not supported in your environment. `ReadableStream` is missing.");return s._stream(c.clone(),s._options.onDownloadProgress)}return c},o=s._options.retry.methods.includes(s.request.method.toLowerCase())?s._retry(n):n();for(const[c,u]of Object.entries(te))o[c]=async()=>{s.request.headers.set("accept",s.request.headers.get("accept")||u);const h=(await o).clone();if(c==="json"){if(h.status===204||(await h.clone().arrayBuffer()).byteLength===0)return"";if(e.parseJson)return e.parseJson(await h.text())}return h[c]()};return o}constructor(t,e={}){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",...e,headers:dt(this._input.headers,e.headers),hooks:J({beforeRequest:[],beforeRetry:[],beforeError:[],afterResponse:[]},e.hooks),method:re(e.method??this._input.method),prefixUrl:String(e.prefixUrl||""),retry:ae(e.retry),throwHttpErrors:e.throwHttpErrors!==!1,timeout:e.timeout??1e4,fetch:e.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(Qt){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(Jt&&(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);(Zt&&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(t){if(this._retryCount++,this._retryCount<this._options.retry.limit&&!(t instanceof ht)){if(t instanceof Z){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 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(t.response.status===413)return 0}const e=this._options.retry.delay(this._retryCount);return Math.min(this._options.retry.backoffLimit,e)}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(e){const s=Math.min(this._calculateRetryDelay(e),L);if(s!==0&&this._retryCount>0){await ce(s,{signal:this._options.signal});for(const n of this._options.hooks.beforeRetry)if(await n({request:this.request,options:this._options,error:e,retryCount:this._retryCount})===pt)return;return this._retry(t)}throw e}}async _fetch(){for(const e of this._options.hooks.beforeRequest){const s=await e(this.request,this._options);if(s instanceof Request){this.request=s;break}if(s instanceof Response)return s}const t=ue(this.request,this._options);return this._options.timeout===!1?this._options.fetch(this.request.clone(),t):oe(this.request.clone(),t,this.abortController,this._options)}_stream(t,e){const s=Number(t.headers.get("content-length"))||0;let n=0;return t.status===204?(e&&e({percent:1,totalBytes:s,transferredBytes:n},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();e&&e({percent:0,transferredBytes:0,totalBytes:s},new Uint8Array);async function c(){const{done:u,value:l}=await o.read();if(u){a.close();return}if(e){n+=l.byteLength;const h=s===0?0:n/s;e({percent:h,transferredBytes:n,totalBytes:s},l)}a.enqueue(l),await c()}await c()}}),{status:t.status,statusText:t.statusText,headers:t.headers})}}/*! MIT License © Sindre Sorhus */const W=r=>{const t=(e,s)=>q.create(e,E(r,s));for(const e of mt)t[e]=(s,n)=>q.create(s,E(r,n,{method:e}));return t.create=e=>W(E(e)),t.extend=e=>W(E(r,e)),t.stop=pt,t},le=W(),he=le,de=typeof window<"u"?{}:{referrer:"https://sk.thorswap.net",referer:"https://sk.thorswap.net"},et=he.create({headers:de}),gt={get:(r,t)=>et.get(r,t).json(),post:(r,t)=>et.post(r,t).json()},st=Object.values(i.Chain),me=(r="")=>{const t=r.toUpperCase(),[e]=t.split(".");if(st.includes(e))return!0;const[s]=t.split("/");if(st.includes(s))return!0;throw new Error(`Invalid identifier: ${r}. Expected format: <Chain>.<Ticker> or <Chain>.<Ticker>-<ContractAddress>`)},R=8,w=r=>10n**BigInt(r),T=r=>Math.log10(parseFloat(r.toString()));function $({value:r,bigIntDecimal:t=R,decimal:e=R}){const s=r<0n;let n=r.toString().substring(s?1:0);const a=e-(n.length-1);a>0&&(n="0".repeat(a)+n);const o=n.length-e;let c=n.slice(-e);return parseInt(c[t])>=5?c=`${c.substring(0,t-1)}${(parseInt(c[t-1])+1).toString()}`:c=c.substring(0,t),`${s?"-":""}${n.slice(0,o)}.${c}`.replace(/\.?0*$/,"")}var b,S,k,_t,P,bt,I,G,y,v,B,K;const x=class x{constructor(t){_(this,b);_(this,k);_(this,P);_(this,I);_(this,y);_(this,B);p(this,"decimalMultiplier",10n**8n);p(this,"bigIntValue",0n);p(this,"decimal");const e=F(t);this.decimal=typeof t=="object"?t.decimal:void 0,this.decimalMultiplier=w(Math.max(m(this,B,K).call(this,m(this,y,v).call(this,e)),this.decimal||0)),m(this,k,_t).call(this,e)}static fromBigInt(t,e){return new x({decimal:e,value:$({value:t,bigIntDecimal:e,decimal:e})})}static shiftDecimals({value:t,from:e,to:s}){return this.fromBigInt(new x(t).bigIntValue*w(s)/w(e),s)}get baseValue(){return this.getBaseValue("string")}get baseValueNumber(){return this.getBaseValue("number")}get baseValueBigInt(){return this.getBaseValue("bigint")}set(t){return new this.constructor({decimal:this.decimal,value:t,identifier:this.toString()})}add(...t){return m(this,b,S).call(this,"add",...t)}sub(...t){return m(this,b,S).call(this,"sub",...t)}mul(...t){return m(this,b,S).call(this,"mul",...t)}div(...t){return m(this,b,S).call(this,"div",...t)}gt(t){return this.bigIntValue>this.getBigIntValue(t)}gte(t){return this.bigIntValue>=this.getBigIntValue(t)}lt(t){return this.bigIntValue<this.getBigIntValue(t)}lte(t){return this.bigIntValue<=this.getBigIntValue(t)}eqValue(t){return this.bigIntValue===this.getBigIntValue(t)}getValue(t){const e=this.formatBigIntToSafeValue(this.bigIntValue,this.decimal||T(this.decimalMultiplier));switch(t){case"number":return Number(e);case"string":return e;default:return this.bigIntValue*BigInt(this.decimal||8n)/this.decimalMultiplier}}getBaseValue(t){const e=this.decimalMultiplier/w(this.decimal||i.BaseDecimal.THOR),s=this.bigIntValue/e;switch(t){case"number":return Number(s);case"string":return s.toString();default:return s}}getBigIntValue(t,e){if(!e&&typeof t=="object")return t.bigIntValue;const s=F(t),n=m(this,y,v).call(this,s);return n==="0"||n==="undefined"?0n:m(this,I,G).call(this,n,e)}formatBigIntToSafeValue(t,e){const s=e||this.decimal||R,n=Math.max(s,T(this.decimalMultiplier)),a=t<0n,o=t.toString().substring(a?1:0),c=n-(o.length-1),u=c>0?"0".repeat(c)+o:o,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(t=6){const[e,s]=this.getValue("string").split("."),n=e||"",a=s||"",o=parseInt(n)?n.length+a.length:a.length;if(o<=t)return this.getValue("string");if(n.length>=t)return n.slice(0,t).padEnd(n.length,"0");if(parseInt(n))return`${n}.${a.slice(0,t-n.length)}`.padEnd(o-t,"0");const c=parseInt(a),u=`${c}`.slice(0,t);return`0.${u.padStart(a.length-`${c}`.length+u.length,"0")}`}toFixed(t=6){const[e,s]=this.getValue("string").split("."),n=e||"",a=s||"";if(parseInt(n))return`${n}.${a.slice(0,t)}`.padEnd(t,"0");const o=parseInt(a),c=`${o}`.slice(0,t);return`0.${c.padStart(a.length-`${o}`.length+c.length,"0")}`}toAbbreviation(t=2){const e=this.getValue("number"),s=["","K","M","B","T","Q","Qi","S"],n=Math.floor(Math.log10(Math.abs(e))/3),a=s[n];if(!a)return this.getValue("string");const o=10**(n*3);return`${(e/o).toFixed(t)}${a}`}};b=new WeakSet,S=function(t,...e){const s=m(this,P,bt).call(this,this,...e),n=w(s),a=e.reduce((c,u)=>{const l=this.getBigIntValue(u,s);switch(t){case"add":return c+l;case"sub":return c-l;case"mul":return c*l/n;case"div":{if(l===0n)throw new RangeError("Division by zero");return c*n/l}default:return c}},this.bigIntValue*n/this.decimalMultiplier),o=$({bigIntDecimal:s,decimal:Math.max(s,T(this.decimalMultiplier)),value:a});return new this.constructor({decimal:this.decimal,value:o,identifier:this.toString()})},k=new WeakSet,_t=function(t){const e=m(this,y,v).call(this,t)||"0";this.bigIntValue=m(this,I,G).call(this,e)},P=new WeakSet,bt=function(...t){const e=t.map(s=>typeof s=="object"?s.decimal||T(s.decimalMultiplier):m(this,B,K).call(this,m(this,y,v).call(this,s))).filter(Boolean);return Math.max(...e,R)},I=new WeakSet,G=function(t,e){const s=e?w(e):this.decimalMultiplier,n=T(s),[a="",o=""]=t.split(".");return BigInt(`${a}${o.padEnd(n,"0")}`)},y=new WeakSet,v=function(t){const s=`${typeof t=="number"?Number(t).toLocaleString("fullwide",{useGrouping:!1,maximumFractionDigits:20}):F(t)}`.replaceAll(",",".").split(".");return s.length>1?`${s.slice(0,-1).join("")}.${s.at(-1)}`:s[0]},B=new WeakSet,K=function(t){var s;const e=((s=t.split(".")[1])==null?void 0:s.length)||0;return Math.max(e,R)};let A=x;function F(r){return typeof r=="object"?"getValue"in r?r.getValue("string"):r.value:r}const M=(r,t)=>typeof r=="bigint"?$({value:r,bigIntDecimal:t,decimal:t}):r;let Y;const U=r=>{if(!Y)throw new Error("Static assets not loaded, call await AssetValue.loadStaticAssets() first");return Y.get(r.toUpperCase())||{decimal:i.BaseDecimal.THOR,identifier:""}},rt=async(r,t=0)=>{me(r);const e=await z(V(r)),s=M(t,e);return new f({decimal:e,value:s,identifier:r})};class f extends A{constructor(e){super(e.value instanceof A?e.value:{decimal:e.decimal,value:e.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 e?e.identifier:`${e.chain}.${e.symbol}`,n=V(s);this.type=ot(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(e=!1){const s=this.isSynthetic?this.symbol.split("-")[0]:`${this.chain}.${this.ticker}`;return e?s:`${this.chain}.${this.symbol}`}eq({chain:e,symbol:s}){return this.chain===e&&this.symbol===s}static async fromString(e,s=0){return rt(e,s)}static fromStringSync(e,s=0){const{isSynthetic:n}=V(e),{decimal:a,identifier:o}=U(e),c=M(s,a);return o?new f({decimal:a,identifier:o,value:c}):n?new f({decimal:8,identifier:e,value:c}):void 0}static async fromIdentifier(e,s=0){return rt(e,s)}static fromIdentifierSync(e,s=0){const{decimal:n,identifier:a}=U(e),o=M(s,n);return new f({decimal:n,identifier:a,value:o})}static fromChainOrSignature(e,s=0){const{decimal:n,identifier:a}=at(e),o=M(s,n);return new f({value:o,decimal:n,identifier:a})}static async fromTCQuote(e,s=0){const n=await z(V(e)),a=this.shiftDecimals({value:s,from:i.BaseDecimal.THOR,to:n});return new f({value:a,identifier:e,decimal:n})}static fromTCQuoteStatic(e,s=0){const n=U(e),a=this.shiftDecimals({value:s,from:i.BaseDecimal.THOR,to:n.decimal});return new f({...n,value:a})}static async loadStaticAssets(){return new Promise(async(e,s)=>{try{const{ThorchainList:n,NativeList:a,...o}=await import("@swapkit/tokens");Y=[a,...Object.values(o)].reduce((u,{tokens:l})=>(l.forEach(({identifier:h,chain:g,...C})=>{const N="decimals"in C?C.decimals:i.BaseDecimal[g];u.set(h,{identifier:h,decimal:N})}),u),new Map),e({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 pe=r=>{const t=f.fromChainOrSignature(r);switch(r){case i.Chain.Bitcoin:case i.Chain.Litecoin:case i.Chain.BitcoinCash:return t.add(10001);case i.Chain.Dogecoin:return t.add(100000001);case i.Chain.Avalanche:case i.Chain.Ethereum:return t.add(10*10**9);case i.Chain.THORChain:case i.Chain.Maya:return t.add(0);default:return t.add(1)}},V=r=>{const t=r.slice(0,14).includes("/"),[e,s]=r.split(".").pop().split("/"),n=r.includes(".")&&!t?r:`${i.Chain.THORChain}.${s}`,[a,o]=n.split("."),[c,u]=(t?s:o).split("-");return{address:u==null?void 0:u.toLowerCase(),chain:a,isGasAsset:it({chain:a,symbol:o}),isSynthetic:t,symbol:(t?`${e}/`:"")+(u?`${c}-${(u==null?void 0:u.toLowerCase())??""}`:o),ticker:c}},fe={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 Q extends Error{constructor(t,e){console.error(e),super(t,{cause:{code:fe[t],message:t}}),Object.setPrototypeOf(this,Q.prototype)}}class D extends A{eq(t){return this.eqValue(t)}static fromBigInt(t,e){return new D({decimal:e,value:$({value:t,bigIntDecimal:e,decimal:e})})}}exports.AssetValue=f;exports.BigIntArithmetics=A;exports.RequestClient=gt;exports.SwapKitError=Q;exports.SwapKitNumber=D;exports.assetFromString=xt;exports.derivationPathToString=zt;exports.filterAssets=Nt;exports.formatBigIntToSafeValue=$;exports.gasFeeMultiplier=Pt;exports.getAssetType=ot;exports.getAsymmetricAssetShare=ut;exports.getAsymmetricAssetWithdrawAmount=jt;exports.getAsymmetricRuneShare=ct;exports.getAsymmetricRuneWithdrawAmount=Ht;exports.getCommonAssetInfo=at;exports.getDecimal=z;exports.getEstimatedPoolShare=Ft;exports.getLiquiditySlippage=Ut;exports.getMemoFor=Gt;exports.getMinAmountByChain=pe;exports.getSymmetricPoolShare=lt;exports.getSymmetricWithdraw=Lt;exports.getTHORNameCost=Kt;exports.isGasAsset=it;exports.validateTHORName=Yt;
package/dist/index.es.js CHANGED
@@ -10,11 +10,15 @@ var y = (s, t, e) => {
10
10
  t instanceof WeakSet ? t.add(s) : t.set(s, e);
11
11
  };
12
12
  var f = (s, t, e) => (wt(s, t, "access private method"), e);
13
- import { FeeOption as D, BaseDecimal as m, Chain as o, ChainToRPC as At, MemoType as g } from "@swapkit/types";
13
+ import { FeeOption as L, BaseDecimal as m, Chain as o, ChainToRPC as At, MemoType as b } from "@swapkit/types";
14
14
  const Tt = "0x313ce567", nt = async ({ chain: s, to: t }) => {
15
15
  try {
16
- const { result: e } = await Kt.post(At[s], {
17
- headers: { accept: "*/*", "cache-control": "no-cache" },
16
+ const { result: e } = await Qt.post(At[s], {
17
+ headers: {
18
+ accept: "*/*",
19
+ "content-type": "application/json",
20
+ "cache-control": "no-cache"
21
+ },
18
22
  body: JSON.stringify({
19
23
  id: 44,
20
24
  jsonrpc: "2.0",
@@ -45,10 +49,10 @@ const Tt = "0x313ce567", nt = async ({ chain: s, to: t }) => {
45
49
  default:
46
50
  return m[s];
47
51
  }
48
- }, ee = {
49
- [D.Average]: 1.2,
50
- [D.Fast]: 1.5,
51
- [D.Fastest]: 2
52
+ }, re = {
53
+ [L.Average]: 1.2,
54
+ [L.Fast]: 1.5,
55
+ [L.Fastest]: 2
52
56
  }, $t = ({ chain: s, symbol: t }) => {
53
57
  switch (s) {
54
58
  case o.Bitcoin:
@@ -134,14 +138,14 @@ const Tt = "0x313ce567", nt = async ({ chain: s, to: t }) => {
134
138
  case o.Optimism:
135
139
  return [o.Ethereum, o.Optimism].includes(t) ? "Native" : "OPTIMISM";
136
140
  }
137
- }, re = (s) => {
141
+ }, se = (s) => {
138
142
  var a;
139
143
  const [t, ...e] = s.split("."), r = s.includes("/"), n = e.join("."), i = (a = n == null ? void 0 : n.split("-")) == null ? void 0 : a[0];
140
144
  return { chain: t, symbol: n, ticker: i, synth: r };
141
145
  }, Et = new RegExp(
142
146
  /(.)\1{6}|\.ORG|\.NET|\.FINANCE|\.COM|WWW|HTTP|\\\\|\/\/|[\s$%:[\]]/,
143
147
  "gmi"
144
- ), se = (s) => s.filter(
148
+ ), ne = (s) => s.filter(
145
149
  (t) => !Et.test(t.toString()) && !t.toString().includes("undefined")
146
150
  ), Ot = ({
147
151
  liquidityUnits: s,
@@ -155,14 +159,14 @@ const Tt = "0x313ce567", nt = async ({ chain: s, to: t }) => {
155
159
  poolUnits: t,
156
160
  assetDepth: e
157
161
  }) => {
158
- const r = d(s), n = d(t), i = d(e), a = r.mul(i), c = n.mul(n).mul(2), u = n.mul(r).mul(2), l = r.mul(r), h = a.mul(c.sub(u).add(l)), _ = n.mul(n).mul(n);
159
- return h.div(_);
160
- }, ne = ({
162
+ const r = d(s), n = d(t), i = d(e), a = r.mul(i), c = n.mul(n).mul(2), u = n.mul(r).mul(2), l = r.mul(r), h = a.mul(c.sub(u).add(l)), g = n.mul(n).mul(n);
163
+ return h.div(g);
164
+ }, ie = ({
161
165
  percent: s,
162
166
  runeDepth: t,
163
167
  liquidityUnits: e,
164
168
  poolUnits: r
165
- }) => Ot({ runeDepth: t, liquidityUnits: e, poolUnits: r }).mul(s), ie = ({
169
+ }) => Ot({ runeDepth: t, liquidityUnits: e, poolUnits: r }).mul(s), oe = ({
166
170
  percent: s,
167
171
  assetDepth: t,
168
172
  liquidityUnits: e,
@@ -175,7 +179,7 @@ const Tt = "0x313ce567", nt = async ({ chain: s, to: t }) => {
175
179
  }) => ({
176
180
  assetAmount: d(r).mul(s).div(t),
177
181
  runeAmount: d(e).mul(s).div(t)
178
- }), oe = ({
182
+ }), ae = ({
179
183
  liquidityUnits: s,
180
184
  poolUnits: t,
181
185
  runeDepth: e,
@@ -185,7 +189,7 @@ const Tt = "0x313ce567", nt = async ({ chain: s, to: t }) => {
185
189
  Object.entries(Bt({ liquidityUnits: s, poolUnits: t, runeDepth: e, assetDepth: r })).map(
186
190
  ([i, a]) => [i, a.mul(n)]
187
191
  )
188
- ), ae = ({
192
+ ), ce = ({
189
193
  runeDepth: s,
190
194
  poolUnits: t,
191
195
  assetDepth: e,
@@ -193,12 +197,12 @@ const Tt = "0x313ce567", nt = async ({ chain: s, to: t }) => {
193
197
  runeAmount: n,
194
198
  assetAmount: i
195
199
  }) => {
196
- const a = d(s), c = d(e), u = d(t), l = d(n), h = d(i), _ = l.mul(c), T = h.mul(a), H = l.mul(h), ft = a.mul(c), pt = u.mul(_.add(T.add(H.mul(2)))), _t = _.add(T.add(ft.mul(2))), X = pt.div(_t), j = d(r).add(X);
200
+ const a = d(s), c = d(e), u = d(t), l = d(n), h = d(i), g = l.mul(c), T = h.mul(a), j = l.mul(h), ft = a.mul(c), pt = u.mul(g.add(T.add(j.mul(2)))), _t = g.add(T.add(ft.mul(2))), X = pt.div(_t), D = d(r).add(X);
197
201
  if (X.baseValueNumber === 0)
198
- return j.div(u).baseValueNumber;
199
- const gt = u.add(j);
200
- return j.div(gt).baseValueNumber;
201
- }, ce = ({
202
+ return D.div(u).baseValueNumber;
203
+ const gt = u.add(D);
204
+ return D.div(gt).baseValueNumber;
205
+ }, ue = ({
202
206
  runeAmount: s,
203
207
  assetAmount: t,
204
208
  runeDepth: e,
@@ -210,47 +214,47 @@ const Tt = "0x313ce567", nt = async ({ chain: s, to: t }) => {
210
214
  symbol: s,
211
215
  ticker: t,
212
216
  chain: e
213
- }) => e === "ETH" && t !== "ETH" ? `${t}-${s.slice(-3)}` : s, ue = (s, t) => {
217
+ }) => e === "ETH" && t !== "ETH" ? `${t}-${s.slice(-3)}` : s, le = (s, t) => {
214
218
  switch (s) {
215
- case g.LEAVE:
216
- case g.BOND: {
219
+ case b.LEAVE:
220
+ case b.BOND: {
217
221
  const { address: e } = t;
218
222
  return `${s}:${e}`;
219
223
  }
220
- case g.UNBOND: {
224
+ case b.UNBOND: {
221
225
  const { address: e, unbondAmount: r } = t;
222
226
  return `${s}:${e}:${r * 10 ** 8}`;
223
227
  }
224
- case g.THORNAME_REGISTER: {
228
+ case b.THORNAME_REGISTER: {
225
229
  const { name: e, chain: r, address: n, owner: i } = t;
226
230
  return `${s}:${e}:${r}:${n}${i ? `:${i}` : ""}`;
227
231
  }
228
- case g.DEPOSIT: {
232
+ case b.DEPOSIT: {
229
233
  const { chain: e, symbol: r, address: n, singleSide: i } = t;
230
234
  return i ? `${s}:${e}/${r}::t:0` : `${s}:${e}.${r}:${n || ""}:t:0`;
231
235
  }
232
- case g.WITHDRAW: {
236
+ case b.WITHDRAW: {
233
237
  const { chain: e, ticker: r, symbol: n, basisPoints: i, targetAssetString: a, singleSide: c } = t, u = !c && a ? `:${a}` : "", l = Mt({ chain: e, symbol: n, ticker: r });
234
238
  return `${s}:${e}${c ? "/" : "."}${l}:${i}${u}`;
235
239
  }
236
- case g.OPEN_LOAN:
237
- case g.CLOSE_LOAN: {
240
+ case b.OPEN_LOAN:
241
+ case b.CLOSE_LOAN: {
238
242
  const { asset: e, address: r } = t;
239
243
  return `${s}:${e}:${r}`;
240
244
  }
241
245
  default:
242
246
  return "";
243
247
  }
244
- }, le = (s) => {
248
+ }, he = (s) => {
245
249
  if (s < 0)
246
250
  throw new Error("Invalid number of year");
247
251
  return 10 + s;
248
- }, he = (s) => {
252
+ }, de = (s) => {
249
253
  if (s.length > 30)
250
254
  return !1;
251
255
  const t = /^[a-zA-Z0-9+_-]+$/g;
252
256
  return !!s.match(t);
253
- }, de = ([s, t, e, r, n]) => `${s}'/${t}'/${e}'/${r}${typeof n != "number" ? "" : `/${n}`}`;
257
+ }, me = ([s, t, e, r, n]) => `${s}'/${t}'/${e}'/${r}${typeof n != "number" ? "" : `/${n}`}`;
254
258
  class Z extends Error {
255
259
  constructor(t, e, r) {
256
260
  const n = t.status || t.status === 0 ? t.status : "", i = t.statusText || "", a = `${n} ${i}`.trim(), c = a ? `status code ${a}` : "an unknown error";
@@ -320,7 +324,7 @@ const B = (s) => s !== null && typeof s == "object", V = (...s) => {
320
324
  formData: "multipart/form-data",
321
325
  arrayBuffer: "*/*",
322
326
  blob: "*/*"
323
- }, L = 2147483647, ut = Symbol("stop"), Ht = {
327
+ }, U = 2147483647, ut = Symbol("stop"), Ht = {
324
328
  json: !0,
325
329
  parseJson: !0,
326
330
  searchParams: !0,
@@ -398,11 +402,11 @@ const Yt = (s, t) => {
398
402
  !(r in jt) && !(r in Ht) && !(r in s) && (e[r] = t[r]);
399
403
  return e;
400
404
  };
401
- class k {
405
+ class q {
402
406
  static create(t, e) {
403
- const r = new k(t, e), n = async () => {
404
- if (typeof r._options.timeout == "number" && r._options.timeout > L)
405
- throw new RangeError(`The \`timeout\` option cannot be greater than ${L}`);
407
+ const r = new q(t, e), n = async () => {
408
+ if (typeof r._options.timeout == "number" && r._options.timeout > U)
409
+ throw new RangeError(`The \`timeout\` option cannot be greater than ${U}`);
406
410
  await Promise.resolve();
407
411
  let c = await r._fetch();
408
412
  for (const u of r._options.hooks.afterResponse) {
@@ -530,7 +534,7 @@ class k {
530
534
  try {
531
535
  return await t();
532
536
  } catch (e) {
533
- const r = Math.min(this._calculateRetryDelay(e), L);
537
+ const r = Math.min(this._calculateRetryDelay(e), U);
534
538
  if (r !== 0 && this._retryCount > 0) {
535
539
  await Gt(r, { signal: this._options.signal });
536
540
  for (const n of this._options.hooks.beforeRetry)
@@ -594,21 +598,15 @@ class k {
594
598
  }
595
599
  }
596
600
  /*! MIT License © Sindre Sorhus */
597
- const W = (s) => {
598
- const t = (e, r) => k.create(e, V(s, r));
601
+ const G = (s) => {
602
+ const t = (e, r) => q.create(e, V(s, r));
599
603
  for (const e of ct)
600
- t[e] = (r, n) => k.create(r, V(s, n, { method: e }));
601
- return t.create = (e) => W(V(e)), t.extend = (e) => W(V(s, e)), t.stop = ut, t;
602
- }, zt = W(), Jt = zt, et = Jt.create({
603
- headers: {
604
- referrer: "https://sk.thorswap.net",
605
- referer: "https://sk.thorswap.net",
606
- "Content-Type": "application/json"
607
- }
608
- }), Kt = {
604
+ t[e] = (r, n) => q.create(r, V(s, n, { method: e }));
605
+ return t.create = (e) => G(V(e)), t.extend = (e) => G(V(s, e)), t.stop = ut, t;
606
+ }, zt = G(), Jt = zt, Kt = typeof window < "u" ? {} : { referrer: "https://sk.thorswap.net", referer: "https://sk.thorswap.net" }, et = Jt.create({ headers: Kt }), Qt = {
609
607
  get: (s, t) => et.get(s, t).json(),
610
608
  post: (s, t) => et.post(s, t).json()
611
- }, rt = Object.values(o), Qt = (s = "") => {
609
+ }, rt = Object.values(o), Xt = (s = "") => {
612
610
  const t = s.toUpperCase(), [e] = t.split(".");
613
611
  if (rt.includes(e))
614
612
  return !0;
@@ -619,7 +617,7 @@ const W = (s) => {
619
617
  `Invalid identifier: ${s}. Expected format: <Chain>.<Ticker> or <Chain>.<Ticker>-<ContractAddress>`
620
618
  );
621
619
  }, C = 8, v = (s) => 10n ** BigInt(s), R = (s) => Math.log10(parseFloat(s.toString()));
622
- function q({
620
+ function x({
623
621
  value: s,
624
622
  bigIntDecimal: t = C,
625
623
  decimal: e = C
@@ -635,27 +633,27 @@ function q({
635
633
  ""
636
634
  );
637
635
  }
638
- var w, S, x, ht, P, dt, E, G, A, $, O, Y;
639
- const N = class N {
636
+ var w, S, P, ht, N, dt, E, Y, A, $, O, z;
637
+ const H = class H {
640
638
  constructor(t) {
641
639
  y(this, w);
642
- y(this, x);
643
640
  y(this, P);
641
+ y(this, N);
644
642
  y(this, E);
645
643
  y(this, A);
646
644
  y(this, O);
647
645
  p(this, "decimalMultiplier", 10n ** 8n);
648
646
  p(this, "bigIntValue", 0n);
649
647
  p(this, "decimal");
650
- const e = U(t);
648
+ const e = F(t);
651
649
  this.decimal = typeof t == "object" ? t.decimal : void 0, this.decimalMultiplier = v(
652
- Math.max(f(this, O, Y).call(this, f(this, A, $).call(this, e)), this.decimal || 0)
653
- ), f(this, x, ht).call(this, e);
650
+ Math.max(f(this, O, z).call(this, f(this, A, $).call(this, e)), this.decimal || 0)
651
+ ), f(this, P, ht).call(this, e);
654
652
  }
655
653
  static fromBigInt(t, e) {
656
- return new N({
654
+ return new H({
657
655
  decimal: e,
658
- value: q({ value: t, bigIntDecimal: e, decimal: e })
656
+ value: x({ value: t, bigIntDecimal: e, decimal: e })
659
657
  });
660
658
  }
661
659
  static shiftDecimals({
@@ -664,7 +662,7 @@ const N = class N {
664
662
  to: r
665
663
  }) {
666
664
  return this.fromBigInt(
667
- new N(t).bigIntValue * v(r) / v(e),
665
+ new H(t).bigIntValue * v(r) / v(e),
668
666
  r
669
667
  );
670
668
  }
@@ -744,8 +742,8 @@ const N = class N {
744
742
  getBigIntValue(t, e) {
745
743
  if (!e && typeof t == "object")
746
744
  return t.bigIntValue;
747
- const r = U(t), n = f(this, A, $).call(this, r);
748
- return n === "0" || n === "undefined" ? 0n : f(this, E, G).call(this, n, e);
745
+ const r = F(t), n = f(this, A, $).call(this, r);
746
+ return n === "0" || n === "undefined" ? 0n : f(this, E, Y).call(this, n, e);
749
747
  }
750
748
  formatBigIntToSafeValue(t, e) {
751
749
  const r = e || this.decimal || C, n = Math.max(
@@ -794,7 +792,7 @@ const N = class N {
794
792
  }
795
793
  };
796
794
  w = new WeakSet(), S = function(t, ...e) {
797
- const r = f(this, P, dt).call(this, this, ...e), n = v(r), i = e.reduce(
795
+ const r = f(this, N, dt).call(this, this, ...e), n = v(r), i = e.reduce(
798
796
  (c, u) => {
799
797
  const l = this.getBigIntValue(u, r);
800
798
  switch (t) {
@@ -815,50 +813,50 @@ w = new WeakSet(), S = function(t, ...e) {
815
813
  },
816
814
  //normalize is to precision multiplier base
817
815
  this.bigIntValue * n / this.decimalMultiplier
818
- ), a = q({
816
+ ), a = x({
819
817
  bigIntDecimal: r,
820
818
  decimal: Math.max(r, R(this.decimalMultiplier)),
821
819
  value: i
822
820
  });
823
821
  return new this.constructor({ decimal: this.decimal, value: a, identifier: this.toString() });
824
- }, x = new WeakSet(), ht = function(t) {
822
+ }, P = new WeakSet(), ht = function(t) {
825
823
  const e = f(this, A, $).call(this, t) || "0";
826
- this.bigIntValue = f(this, E, G).call(this, e);
827
- }, P = new WeakSet(), dt = function(...t) {
824
+ this.bigIntValue = f(this, E, Y).call(this, e);
825
+ }, N = new WeakSet(), dt = function(...t) {
828
826
  const e = t.map(
829
- (r) => typeof r == "object" ? r.decimal || R(r.decimalMultiplier) : f(this, O, Y).call(this, f(this, A, $).call(this, r))
827
+ (r) => typeof r == "object" ? r.decimal || R(r.decimalMultiplier) : f(this, O, z).call(this, f(this, A, $).call(this, r))
830
828
  ).filter(Boolean);
831
829
  return Math.max(...e, C);
832
- }, E = new WeakSet(), G = function(t, e) {
830
+ }, E = new WeakSet(), Y = function(t, e) {
833
831
  const r = e ? v(e) : this.decimalMultiplier, n = R(r), [i = "", a = ""] = t.split(".");
834
832
  return BigInt(`${i}${a.padEnd(n, "0")}`);
835
833
  }, A = new WeakSet(), $ = function(t) {
836
834
  const r = `${typeof t == "number" ? Number(t).toLocaleString("fullwide", {
837
835
  useGrouping: !1,
838
836
  maximumFractionDigits: 20
839
- }) : U(t)}`.replaceAll(",", ".").split(".");
837
+ }) : F(t)}`.replaceAll(",", ".").split(".");
840
838
  return r.length > 1 ? `${r.slice(0, -1).join("")}.${r.at(-1)}` : r[0];
841
- }, O = new WeakSet(), Y = function(t) {
839
+ }, O = new WeakSet(), z = function(t) {
842
840
  var r;
843
841
  const e = ((r = t.split(".")[1]) == null ? void 0 : r.length) || 0;
844
842
  return Math.max(e, C);
845
843
  };
846
- let I = N;
847
- function U(s) {
844
+ let I = H;
845
+ function F(s) {
848
846
  return typeof s == "object" ? "getValue" in s ? s.getValue("string") : s.value : s;
849
847
  }
850
- const M = (s, t) => typeof s == "bigint" ? q({ value: s, bigIntDecimal: t, decimal: t }) : s;
851
- let z;
852
- const F = (s) => {
853
- if (!z)
848
+ const M = (s, t) => typeof s == "bigint" ? x({ value: s, bigIntDecimal: t, decimal: t }) : s;
849
+ let J;
850
+ const W = (s) => {
851
+ if (!J)
854
852
  throw new Error("Static assets not loaded, call await AssetValue.loadStaticAssets() first");
855
- return z.get(s.toUpperCase()) || { decimal: m.THOR, identifier: "" };
853
+ return J.get(s.toUpperCase()) || { decimal: m.THOR, identifier: "" };
856
854
  }, st = async (s, t = 0) => {
857
- Qt(s);
858
- const e = await it(J(s)), r = M(t, e);
859
- return new b({ decimal: e, value: r, identifier: s });
855
+ Xt(s);
856
+ const e = await it(k(s)), r = M(t, e);
857
+ return new _({ decimal: e, value: r, identifier: s });
860
858
  };
861
- class b extends I {
859
+ class _ extends I {
862
860
  constructor(e) {
863
861
  super(
864
862
  e.value instanceof I ? e.value : { decimal: e.decimal, value: e.value }
@@ -870,14 +868,14 @@ class b extends I {
870
868
  p(this, "symbol");
871
869
  p(this, "ticker");
872
870
  p(this, "type");
873
- const r = "identifier" in e ? e.identifier : `${e.chain}.${e.symbol}`, n = J(r);
871
+ const r = "identifier" in e ? e.identifier : `${e.chain}.${e.symbol}`, n = k(r);
874
872
  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;
875
873
  }
876
874
  get assetValue() {
877
875
  return `${this.getValue("string")} ${this.ticker}`;
878
876
  }
879
877
  toString(e = !1) {
880
- const r = this.isSynthetic ? this.ticker : `${this.chain}.${this.ticker}`;
878
+ const r = this.isSynthetic ? this.symbol.split("-")[0] : `${this.chain}.${this.ticker}`;
881
879
  return e ? r : (
882
880
  // THOR.ETH/ETH | ETH.USDT-0x1234567890
883
881
  `${this.chain}.${this.symbol}`
@@ -890,33 +888,33 @@ class b extends I {
890
888
  return st(e, r);
891
889
  }
892
890
  static fromStringSync(e, r = 0) {
893
- const { decimal: n, identifier: i } = F(
891
+ const { isSynthetic: n } = k(e), { decimal: i, identifier: a } = W(
894
892
  e
895
- ), a = M(r, n);
896
- return i ? new b({ decimal: n, identifier: i, value: a }) : void 0;
893
+ ), c = M(r, i);
894
+ return a ? new _({ decimal: i, identifier: a, value: c }) : n ? new _({ decimal: 8, identifier: e, value: c }) : void 0;
897
895
  }
898
896
  static async fromIdentifier(e, r = 0) {
899
897
  return st(e, r);
900
898
  }
901
899
  static fromIdentifierSync(e, r = 0) {
902
- const { decimal: n, identifier: i } = F(e), a = M(r, n);
903
- return new b({ decimal: n, identifier: i, value: a });
900
+ const { decimal: n, identifier: i } = W(e), a = M(r, n);
901
+ return new _({ decimal: n, identifier: i, value: a });
904
902
  }
905
903
  static fromChainOrSignature(e, r = 0) {
906
904
  const { decimal: n, identifier: i } = Ct(e), a = M(r, n);
907
- return new b({ value: a, decimal: n, identifier: i });
905
+ return new _({ value: a, decimal: n, identifier: i });
908
906
  }
909
907
  static async fromTCQuote(e, r = 0) {
910
- const n = await it(J(e)), i = this.shiftDecimals({ value: r, from: m.THOR, to: n });
911
- return new b({ value: i, identifier: e, decimal: n });
908
+ const n = await it(k(e)), i = this.shiftDecimals({ value: r, from: m.THOR, to: n });
909
+ return new _({ value: i, identifier: e, decimal: n });
912
910
  }
913
911
  static fromTCQuoteStatic(e, r = 0) {
914
- const n = F(e), i = this.shiftDecimals({
912
+ const n = W(e), i = this.shiftDecimals({
915
913
  value: r,
916
914
  from: m.THOR,
917
915
  to: n.decimal
918
916
  });
919
- return new b({ ...n, value: i });
917
+ return new _({ ...n, value: i });
920
918
  }
921
919
  static async loadStaticAssets() {
922
920
  return new Promise(
@@ -929,10 +927,10 @@ class b extends I {
929
927
  NativeList: i,
930
928
  ...a
931
929
  } = await import("@swapkit/tokens");
932
- z = [i, ...Object.values(a)].reduce(
933
- (u, { tokens: l }) => (l.forEach(({ identifier: h, chain: _, ...T }) => {
934
- const H = "decimals" in T ? T.decimals : m[_];
935
- u.set(h, { identifier: h, decimal: H });
930
+ J = [i, ...Object.values(a)].reduce(
931
+ (u, { tokens: l }) => (l.forEach(({ identifier: h, chain: g, ...T }) => {
932
+ const j = "decimals" in T ? T.decimals : m[g];
933
+ u.set(h, { identifier: h, decimal: j });
936
934
  }), u),
937
935
  /* @__PURE__ */ new Map()
938
936
  ), e({ ok: !0 });
@@ -947,8 +945,8 @@ class b extends I {
947
945
  );
948
946
  }
949
947
  }
950
- const me = (s) => {
951
- const t = b.fromChainOrSignature(s);
948
+ const fe = (s) => {
949
+ const t = _.fromChainOrSignature(s);
952
950
  switch (s) {
953
951
  case o.Bitcoin:
954
952
  case o.Litecoin:
@@ -965,17 +963,17 @@ const me = (s) => {
965
963
  default:
966
964
  return t.add(1);
967
965
  }
968
- }, J = (s) => {
969
- const t = s.slice(0, 14).includes("/"), e = s.includes(".") ? s : `${o.THORChain}.${s}`, [r, n] = e.split("."), [i, a] = n.split("-");
966
+ }, k = (s) => {
967
+ const t = s.slice(0, 14).includes("/"), [e, r] = s.split(".").pop().split("/"), n = s.includes(".") && !t ? s : `${o.THORChain}.${r}`, [i, a] = n.split("."), [c, u] = (t ? r : a).split("-");
970
968
  return {
971
- address: a == null ? void 0 : a.toLowerCase(),
972
- chain: r,
973
- isGasAsset: $t({ chain: r, symbol: n }),
969
+ address: u == null ? void 0 : u.toLowerCase(),
970
+ chain: i,
971
+ isGasAsset: $t({ chain: i, symbol: a }),
974
972
  isSynthetic: t,
975
- symbol: a ? `${i}-${(a == null ? void 0 : a.toLowerCase()) ?? ""}` : n,
976
- ticker: t ? n : i
973
+ symbol: (t ? `${e}/` : "") + (u ? `${c}-${(u == null ? void 0 : u.toLowerCase()) ?? ""}` : a),
974
+ ticker: c
977
975
  };
978
- }, Xt = {
976
+ }, Zt = {
979
977
  /**
980
978
  * Core
981
979
  */
@@ -1034,7 +1032,7 @@ const me = (s) => {
1034
1032
  };
1035
1033
  class mt extends Error {
1036
1034
  constructor(t, e) {
1037
- console.error(e), super(t, { cause: { code: Xt[t], message: t } }), Object.setPrototypeOf(this, mt.prototype);
1035
+ console.error(e), super(t, { cause: { code: Zt[t], message: t } }), Object.setPrototypeOf(this, mt.prototype);
1038
1036
  }
1039
1037
  }
1040
1038
  class Q extends I {
@@ -1044,35 +1042,35 @@ class Q extends I {
1044
1042
  static fromBigInt(t, e) {
1045
1043
  return new Q({
1046
1044
  decimal: e,
1047
- value: q({ value: t, bigIntDecimal: e, decimal: e })
1045
+ value: x({ value: t, bigIntDecimal: e, decimal: e })
1048
1046
  });
1049
1047
  }
1050
1048
  }
1051
1049
  export {
1052
- b as AssetValue,
1050
+ _ as AssetValue,
1053
1051
  I as BigIntArithmetics,
1054
- Kt as RequestClient,
1052
+ Qt as RequestClient,
1055
1053
  mt as SwapKitError,
1056
1054
  Q as SwapKitNumber,
1057
- re as assetFromString,
1058
- de as derivationPathToString,
1059
- se as filterAssets,
1060
- q as formatBigIntToSafeValue,
1061
- ee as gasFeeMultiplier,
1055
+ se as assetFromString,
1056
+ me as derivationPathToString,
1057
+ ne as filterAssets,
1058
+ x as formatBigIntToSafeValue,
1059
+ re as gasFeeMultiplier,
1062
1060
  It as getAssetType,
1063
1061
  Vt as getAsymmetricAssetShare,
1064
- ie as getAsymmetricAssetWithdrawAmount,
1062
+ oe as getAsymmetricAssetWithdrawAmount,
1065
1063
  Ot as getAsymmetricRuneShare,
1066
- ne as getAsymmetricRuneWithdrawAmount,
1064
+ ie as getAsymmetricRuneWithdrawAmount,
1067
1065
  Ct as getCommonAssetInfo,
1068
1066
  it as getDecimal,
1069
- ae as getEstimatedPoolShare,
1070
- ce as getLiquiditySlippage,
1071
- ue as getMemoFor,
1072
- me as getMinAmountByChain,
1067
+ ce as getEstimatedPoolShare,
1068
+ ue as getLiquiditySlippage,
1069
+ le as getMemoFor,
1070
+ fe as getMinAmountByChain,
1073
1071
  Bt as getSymmetricPoolShare,
1074
- oe as getSymmetricWithdraw,
1075
- le as getTHORNameCost,
1072
+ ae as getSymmetricWithdraw,
1073
+ he as getTHORNameCost,
1076
1074
  $t as isGasAsset,
1077
- he as validateTHORName
1075
+ de as validateTHORName
1078
1076
  };
package/package.json CHANGED
@@ -10,14 +10,14 @@
10
10
  "vitest": "0.34.4",
11
11
  "@internal/config": "0.0.0-internal.0",
12
12
  "@swapkit/tokens": "1.0.0-rc.7",
13
- "@swapkit/types": "1.0.0-rc.6"
13
+ "@swapkit/types": "1.0.0-rc.7"
14
14
  },
15
15
  "eslintConfig": {
16
16
  "extends": "../../../internal/eslint-config"
17
17
  },
18
18
  "peerDependencies": {
19
19
  "@swapkit/tokens": "1.0.0-rc.7",
20
- "@swapkit/types": "1.0.0-rc.6"
20
+ "@swapkit/types": "1.0.0-rc.7"
21
21
  },
22
22
  "exports": {
23
23
  ".": {
@@ -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.14",
45
+ "version": "1.0.0-rc.16",
46
46
  "scripts": {
47
47
  "build": "vite build",
48
48
  "clean": "rm -rf dist vite.config.ts.* .turbo node_modules",
@@ -10,7 +10,11 @@ export type CommonAssetString = 'MAYA.MAYA' | 'ETH.THOR' | 'ETH.vTHOR' | Chain;
10
10
  const getContractDecimals = async ({ chain, to }: { chain: EVMChain; to: string }) => {
11
11
  try {
12
12
  const { result } = await RequestClient.post<{ result: string }>(ChainToRPC[chain], {
13
- headers: { accept: '*/*', 'cache-control': 'no-cache' },
13
+ headers: {
14
+ accept: '*/*',
15
+ 'content-type': 'application/json',
16
+ 'cache-control': 'no-cache',
17
+ },
14
18
  body: JSON.stringify({
15
19
  id: 44,
16
20
  jsonrpc: '2.0',
@@ -1,13 +1,12 @@
1
1
  import type { Options } from 'ky';
2
2
  import ky from 'ky';
3
3
 
4
- const kyClient = ky.create({
5
- headers: {
6
- referrer: 'https://sk.thorswap.net',
7
- referer: 'https://sk.thorswap.net',
8
- 'Content-Type': 'application/json',
9
- },
10
- });
4
+ const headers =
5
+ typeof window !== 'undefined'
6
+ ? {}
7
+ : { referrer: 'https://sk.thorswap.net', referer: 'https://sk.thorswap.net' };
8
+
9
+ const kyClient = ky.create({ headers });
11
10
 
12
11
  export const RequestClient = {
13
12
  get: <T>(url: string | URL | Request, options?: Options) => kyClient.get(url, options).json<T>(),
@@ -28,7 +28,7 @@ describe('AssetValue', () => {
28
28
  value: 1234567890,
29
29
  });
30
30
 
31
- expect(ethSynth.assetValue).toBe('1234567890 ETH/ETH');
31
+ expect(ethSynth.assetValue).toBe('1234567890 ETH');
32
32
  expect(ethSynth.toString()).toBe('THOR.ETH/ETH');
33
33
  expect(ethSynth.toString(true)).toBe('ETH/ETH');
34
34
  expect(ethSynth.mul(21.37).getValue('string')).toBe('26382715809.3');
@@ -101,7 +101,9 @@ export class AssetValue extends BigIntArithmetics {
101
101
 
102
102
  toString(short = false) {
103
103
  // THOR.RUNE | ETH/ETH
104
- const shortFormat = this.isSynthetic ? this.ticker : `${this.chain}.${this.ticker}`;
104
+ const shortFormat = this.isSynthetic
105
+ ? this.symbol.split('-')[0]
106
+ : `${this.chain}.${this.ticker}`;
105
107
 
106
108
  return short
107
109
  ? shortFormat
@@ -118,6 +120,7 @@ export class AssetValue extends BigIntArithmetics {
118
120
  }
119
121
 
120
122
  static fromStringSync(assetString: string, value: NumberPrimitives = 0) {
123
+ const { isSynthetic } = getAssetInfo(assetString);
121
124
  const { decimal, identifier: tokenIdentifier } = getStaticToken(
122
125
  assetString as unknown as TokenNames,
123
126
  );
@@ -126,6 +129,8 @@ export class AssetValue extends BigIntArithmetics {
126
129
 
127
130
  return tokenIdentifier
128
131
  ? new AssetValue({ decimal, identifier: tokenIdentifier, value: parsedValue })
132
+ : isSynthetic
133
+ ? new AssetValue({ decimal: 8, identifier: assetString, value: parsedValue })
129
134
  : undefined;
130
135
  }
131
136
 
@@ -236,19 +241,21 @@ export const getMinAmountByChain = (chain: Chain) => {
236
241
 
237
242
  const getAssetInfo = (identifier: string) => {
238
243
  const isSynthetic = identifier.slice(0, 14).includes('/');
239
- const adjustedIdentifier = identifier.includes('.')
240
- ? identifier
241
- : `${Chain.THORChain}.${identifier}`;
244
+ const [synthChain, synthSymbol] = identifier.split('.').pop()!.split('/');
245
+ const adjustedIdentifier =
246
+ identifier.includes('.') && !isSynthetic ? identifier : `${Chain.THORChain}.${synthSymbol}`;
242
247
 
243
248
  const [chain, symbol] = adjustedIdentifier.split('.') as [Chain, string];
244
- const [ticker, address] = symbol.split('-') as [string, string?];
249
+ const [ticker, address] = (isSynthetic ? synthSymbol : symbol).split('-') as [string, string?];
245
250
 
246
251
  return {
247
252
  address: address?.toLowerCase(),
248
253
  chain,
249
254
  isGasAsset: isGasAsset({ chain, symbol }),
250
255
  isSynthetic,
251
- symbol: address ? `${ticker}-${address?.toLowerCase() ?? ''}` : symbol,
252
- ticker: isSynthetic ? symbol : ticker,
256
+ symbol:
257
+ (isSynthetic ? `${synthChain}/` : '') +
258
+ (address ? `${ticker}-${address?.toLowerCase() ?? ''}` : symbol),
259
+ ticker: ticker,
253
260
  };
254
261
  };