@swapkit/helpers 1.0.0-rc.15 → 1.0.0-rc.17

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 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:"*/*","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,et=he.create({headers:{referrer:"https://sk.thorswap.net",referer:"https://sk.thorswap.net","Content-Type":"application/json"}}),gt={get:(r,t)=>et.get(r,t).json(),post:(r,t)=>et.post(r,t).json()},st=Object.values(i.Chain),de=(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)=>{de(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 me=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}},pe={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:pe[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=me;exports.getSymmetricPoolShare=lt;exports.getSymmetricWithdraw=Lt;exports.getTHORNameCost=Kt;exports.isGasAsset=it;exports.validateTHORName=Yt;
1
+ "use strict";var Te=Object.create;var j=Object.defineProperty;var Se=Object.getOwnPropertyDescriptor;var ve=Object.getOwnPropertyNames;var Re=Object.getPrototypeOf,Ie=Object.prototype.hasOwnProperty;var Be=(s,e,t)=>e in s?j(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t;var $e=(s,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of ve(e))!Ie.call(s,n)&&n!==t&&j(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)):{},$e(e||!s||!s.__esModule?j(t,"default",{value:s,enumerable:!0}):t,s));var p=(s,e,t)=>(Be(s,typeof e!="symbol"?e+"":e,t),t),Oe=(s,e,t)=>{if(!e.has(s))throw TypeError("Cannot "+t)};var y=(s,e,t)=>{if(e.has(s))throw TypeError("Cannot add the same private member more than once");e instanceof WeakSet?e.add(s):e.set(s,t)};var d=(s,e,t)=>(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:"*/*","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[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},qe=async s=>{const[,e]=s.split("-");return e!=null&&e.startsWith("0x")?ne({chain:i.Chain.Avalanche,to:e.toLowerCase()}):i.BaseDecimal.AVAX},ke=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 qe(e);case i.Chain.BinanceSmartChain:return ke(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=m(s),n=m(e),a=m(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=m(s),n=m(e),a=m(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)),_=n.mul(n).mul(n);return h.div(_)},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),m=s=>g.fromBigInt(BigInt(s),i.BaseDecimal.THOR),le=({liquidityUnits:s,poolUnits:e,runeDepth:t,assetDepth:r})=>({assetAmount:m(r).mul(s).div(e),runeAmount:m(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=new g({value:s,decimal:8}),c=new g({value:t,decimal:8}),u=new g({value:e,decimal:8}),l=new g({value:n,decimal:8}),h=new g({value:a,decimal:8}),_=l.mul(c),w=h.mul(o),N=l.mul(h),be=o.mul(c),Ce=u.mul(_.add(w.add(N.mul(2)))),we=_.add(w.add(be.mul(2))),X=Ce.div(we),H=m(r).add(X);if(X.getBaseValue("number")===0)return H.div(u).getBaseValue("number");const Ae=u.add(H);return H.div(Ae).getBaseValue("number")},Ue=({runeAmount:s,assetAmount:e,runeDepth:t,assetDepth:r})=>{if(s==="0"||e==="0"||t==="0"||r==="0")return 0;const n=m(t),a=m(r),o=m(e),c=m(s),u=o.mul(n).sub(a.mul(c)),l=a.mul(c).add(n.mul(a));return Math.abs(u.div(l).getBaseValue("number"))},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 M=s=>s!==null&&typeof s=="object",O=(...s)=>{for(const e of s)if((!M(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(M(r)){for(let[n,a]of Object.entries(r))M(a)&&n in e&&(a=J(e[n],a)),e={...e,[n]:a};M(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:"*/*"},L=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 k{static create(e,t){const r=new k(e,t),n=async()=>{if(typeof r._options.timeout=="number"&&r._options.timeout>L)throw new RangeError(`The \`timeout\` option cannot be greater than ${L}`);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),L);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 W=s=>{const e=(t,r)=>k.create(t,O(s,r));for(const t of me)e[t]=(r,n)=>k.create(r,O(s,n,{method:t}));return e.create=t=>W(O(t)),e.extend=t=>W(O(s,t)),e.stop=pe,e},lt=W(),ht=lt,dt=typeof window<"u"?{}:{referrer:"https://sk.thorswap.net",referer:"https://sk.thorswap.net"},te=ht.create({headers:dt}),ge={get:(s,e)=>te.get(s,e).json(),post:(s,e)=>te.post(s,e).json()},re=Object.values(i.Chain),mt=(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>`)},I=8,A=s=>10n**BigInt(s),S=s=>Math.log10(parseFloat(s.toString()));function B({value:s,bigIntDecimal:e=I,decimal:t=I}){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,v,P,_e,x,ye,$,G,C,R,E,K;const D=class D{constructor(e){y(this,b);y(this,P);y(this,x);y(this,$);y(this,C);y(this,E);p(this,"decimalMultiplier",10n**8n);p(this,"bigIntValue",0n);p(this,"decimal");const t=F(e);this.decimal=typeof e=="object"?e.decimal:void 0,this.decimalMultiplier=A(Math.max(d(this,E,K).call(this,d(this,C,R).call(this,t)),this.decimal||0)),d(this,P,_e).call(this,t)}static fromBigInt(e,t){return new D({decimal:t,value:B({value:e,bigIntDecimal:t,decimal:t})})}static shiftDecimals({value:e,from:t,to:r}){return this.fromBigInt(new D(e).bigIntValue*A(r)/A(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 d(this,b,v).call(this,"add",...e)}sub(...e){return d(this,b,v).call(this,"sub",...e)}mul(...e){return d(this,b,v).call(this,"mul",...e)}div(...e){return d(this,b,v).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||S(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),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=F(e),n=d(this,C,R).call(this,r);return n==="0"||n==="undefined"?0n:d(this,$,G).call(this,n,t)}formatBigIntToSafeValue(e,t){const r=t||this.decimal||I,n=Math.max(r,S(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||"";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 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,v=function(e,...t){const r=d(this,x,ye).call(this,this,...t),n=A(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=B({bigIntDecimal:r,decimal:Math.max(r,S(this.decimalMultiplier)),value:a});return new this.constructor({decimal:this.decimal,value:o,identifier:this.toString()})},P=new WeakSet,_e=function(e){const t=d(this,C,R).call(this,e)||"0";this.bigIntValue=d(this,$,G).call(this,t)},x=new WeakSet,ye=function(...e){const t=e.map(r=>typeof r=="object"?r.decimal||S(r.decimalMultiplier):d(this,E,K).call(this,d(this,C,R).call(this,r))).filter(Boolean);return Math.max(...t,I)},$=new WeakSet,G=function(e,t){const r=t?A(t):this.decimalMultiplier,n=S(r),[a="",o=""]=e.split(".");return BigInt(`${a}${o.padEnd(n,"0")}`)},C=new WeakSet,R=function(e){const r=`${typeof e=="number"?Number(e).toLocaleString("fullwide",{useGrouping:!1,maximumFractionDigits:20}):F(e)}`.replaceAll(",",".").split(".");return r.length>1?`${r.slice(0,-1).join("")}.${r.at(-1)}`:r[0]},E=new WeakSet,K=function(e){var r;const t=((r=e.split(".")[1])==null?void 0:r.length)||0;return Math.max(t,I)};let T=D;function F(s){return typeof s=="object"?"getValue"in s?s.getValue("string"):s.value:s}const V=(s,e)=>typeof s=="bigint"?B({value:s,bigIntDecimal:e,decimal:e}):s;let Y;const U=s=>{if(!Y)throw new Error("Static assets not loaded, call await AssetValue.loadStaticAssets() first");return Y.get(s.toUpperCase())||{decimal:i.BaseDecimal.THOR,identifier:""}},se=async(s,e=0)=>{mt(s);const t=await z(q(s)),r=V(e,t);return new f({decimal:t,value:r,identifier:s})};class f 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 r="identifier"in t?t.identifier:`${t.chain}.${t.symbol}`,n=q(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.symbol.split("-")[0]:`${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{isSynthetic:n}=q(t),{decimal:a,identifier:o}=U(t),c=V(r,a);return o?new f({decimal:a,identifier:o,value:c}):n?new f({decimal:8,identifier:t,value:c}):void 0}static async fromIdentifier(t,r=0){return se(t,r)}static fromIdentifierSync(t,r=0){const{decimal:n,identifier:a}=U(t),o=V(r,n);return new f({decimal:n,identifier:a,value:o})}static fromChainOrSignature(t,r=0){const{decimal:n,identifier:a}=ae(t),o=V(r,n);return new f({value:o,decimal:n,identifier:a})}static async fromTCQuote(t,r=0){const n=await z(q(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=U(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");Y=[a,...Object.values(o)].reduce((u,{tokens:l})=>(l.forEach(({identifier:h,chain:_,...w})=>{const N="decimals"in w?w.decimals:i.BaseDecimal[_];u.set(h,{identifier:h,decimal:N})}),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 pt=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)}},q=s=>{const e=s.slice(0,14).includes("/"),[t,r]=s.split(".").pop().split("/"),n=s.includes(".")&&!e?s:`${i.Chain.THORChain}.${r}`,[a,o]=n.split("."),[c,u]=(e?r:o).split("-");return{address:u==null?void 0:u.toLowerCase(),chain:a,isGasAsset:ie({chain:a,symbol:o}),isSynthetic:e,symbol:(e?`${t}/`:"")+(u?`${c}-${(u==null?void 0:u.toLowerCase())??""}`:o),ticker:c}},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 Q extends Error{constructor(e,t){console.error(t),super(e,{cause:{code:ft[e],message:e}}),Object.setPrototypeOf(this,Q.prototype)}}class g extends T{eq(e){return this.eqValue(e)}static fromBigInt(e,t){return new g({decimal:t,value:B({value:e,bigIntDecimal:t,decimal:t})})}}exports.AssetValue=f;exports.BigIntArithmetics=T;exports.RequestClient=ge;exports.SwapKitError=Q;exports.SwapKitNumber=g;exports.assetFromString=xe;exports.derivationPathToString=ze;exports.filterAssets=Ne;exports.formatBigIntToSafeValue=B;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=pt;exports.getSymmetricPoolShare=le;exports.getSymmetricWithdraw=Le;exports.getTHORNameCost=Ke;exports.isGasAsset=ie;exports.validateTHORName=Ye;
package/dist/index.es.js CHANGED
@@ -4,17 +4,21 @@ var p = (s, t, e) => (yt(s, typeof t != "symbol" ? t + "" : t, e), e), wt = (s,
4
4
  if (!t.has(s))
5
5
  throw TypeError("Cannot " + e);
6
6
  };
7
- var y = (s, t, e) => {
7
+ var w = (s, t, e) => {
8
8
  if (t.has(s))
9
9
  throw TypeError("Cannot add the same private member more than once");
10
10
  t instanceof WeakSet ? t.add(s) : t.set(s, e);
11
11
  };
12
- var f = (s, t, e) => (wt(s, t, "access private method"), e);
13
- import { FeeOption as L, BaseDecimal as m, Chain as o, ChainToRPC as At, MemoType as b } from "@swapkit/types";
12
+ var m = (s, t, e) => (wt(s, t, "access private method"), e);
13
+ import { FeeOption as U, BaseDecimal as d, 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",
@@ -24,17 +28,17 @@ const Tt = "0x313ce567", nt = async ({ chain: s, to: t }) => {
24
28
  });
25
29
  return parseInt(BigInt(e).toString());
26
30
  } catch (e) {
27
- return console.error(e), m[s];
31
+ return console.error(e), d[s];
28
32
  }
29
33
  }, vt = async (s) => {
30
34
  if (s === o.Ethereum)
31
- return m.ETH;
35
+ return d.ETH;
32
36
  const [, t] = s.split("-");
33
- return t != null && t.startsWith("0x") ? nt({ chain: o.Ethereum, to: t }) : m.ETH;
37
+ return t != null && t.startsWith("0x") ? nt({ chain: o.Ethereum, to: t }) : d.ETH;
34
38
  }, Rt = async (s) => {
35
39
  const [, t] = s.split("-");
36
- return t != null && t.startsWith("0x") ? nt({ chain: o.Avalanche, to: t.toLowerCase() }) : m.AVAX;
37
- }, St = async (s) => s === o.BinanceSmartChain ? m.BSC : m.BSC, it = async ({ chain: s, symbol: t }) => {
40
+ return t != null && t.startsWith("0x") ? nt({ chain: o.Avalanche, to: t.toLowerCase() }) : d.AVAX;
41
+ }, St = async (s) => s === o.BinanceSmartChain ? d.BSC : d.BSC, it = async ({ chain: s, symbol: t }) => {
38
42
  switch (s) {
39
43
  case o.Ethereum:
40
44
  return vt(t);
@@ -43,12 +47,12 @@ const Tt = "0x313ce567", nt = async ({ chain: s, to: t }) => {
43
47
  case o.BinanceSmartChain:
44
48
  return St(t);
45
49
  default:
46
- return m[s];
50
+ return d[s];
47
51
  }
48
- }, ee = {
49
- [L.Average]: 1.2,
50
- [L.Fast]: 1.5,
51
- [L.Fastest]: 2
52
+ }, re = {
53
+ [U.Average]: 1.2,
54
+ [U.Fast]: 1.5,
55
+ [U.Fastest]: 2
52
56
  }, $t = ({ chain: s, symbol: t }) => {
53
57
  switch (s) {
54
58
  case o.Bitcoin:
@@ -82,13 +86,13 @@ const Tt = "0x313ce567", nt = async ({ chain: s, to: t }) => {
82
86
  case "ETH.vTHOR":
83
87
  return { identifier: "ETH.vTHOR-0x815c23eca83261b6ec689b60cc4a58b54bc24d8d", decimal: 18 };
84
88
  case o.Cosmos:
85
- return { identifier: "GAIA.ATOM", decimal: m[s] };
89
+ return { identifier: "GAIA.ATOM", decimal: d[s] };
86
90
  case o.THORChain:
87
- return { identifier: "THOR.RUNE", decimal: m[s] };
91
+ return { identifier: "THOR.RUNE", decimal: d[s] };
88
92
  case o.BinanceSmartChain:
89
- return { identifier: "BSC.BNB", decimal: m[s] };
93
+ return { identifier: "BSC.BNB", decimal: d[s] };
90
94
  case o.Maya:
91
- return { identifier: "MAYA.CACAO", decimal: m.MAYA };
95
+ return { identifier: "MAYA.CACAO", decimal: d.MAYA };
92
96
  case "MAYA.MAYA":
93
97
  return { identifier: "MAYA.MAYA", decimal: 4 };
94
98
  case o.Kujira:
@@ -102,7 +106,7 @@ const Tt = "0x313ce567", nt = async ({ chain: s, to: t }) => {
102
106
  case o.Polygon:
103
107
  case o.Bitcoin:
104
108
  case o.Ethereum:
105
- return { identifier: `${s}.${s}`, decimal: m[s] };
109
+ return { identifier: `${s}.${s}`, decimal: d[s] };
106
110
  }
107
111
  }, It = ({ chain: s, symbol: t }) => {
108
112
  if (t.includes("/"))
@@ -134,58 +138,58 @@ 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,
148
152
  poolUnits: t,
149
153
  runeDepth: e
150
154
  }) => {
151
- 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 = n.mul(n).mul(n);
155
+ const r = f(s), n = f(t), i = f(e), a = r.mul(i), c = n.mul(n).mul(2), u = n.mul(r).mul(2), l = r.mul(r), h = n.mul(n).mul(n);
152
156
  return a.mul(c.sub(u).add(l)).div(h);
153
- }, Vt = ({
157
+ }, Bt = ({
154
158
  liquidityUnits: s,
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)), g = n.mul(n).mul(n);
162
+ const r = f(s), n = f(t), i = f(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);
159
163
  return h.div(g);
160
- }, ne = ({
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,
169
173
  poolUnits: r
170
- }) => Vt({ assetDepth: t, liquidityUnits: e, poolUnits: r }).mul(s), d = (s) => new Q({ value: s, decimal: m.THOR }), Bt = ({
174
+ }) => Bt({ assetDepth: t, liquidityUnits: e, poolUnits: r }).mul(s), f = (s) => y.fromBigInt(BigInt(s), d.THOR), Vt = ({
171
175
  liquidityUnits: s,
172
176
  poolUnits: t,
173
177
  runeDepth: e,
174
178
  assetDepth: r
175
179
  }) => ({
176
- assetAmount: d(r).mul(s).div(t),
177
- runeAmount: d(e).mul(s).div(t)
178
- }), oe = ({
180
+ assetAmount: f(r).mul(s).div(t),
181
+ runeAmount: f(e).mul(s).div(t)
182
+ }), ae = ({
179
183
  liquidityUnits: s,
180
184
  poolUnits: t,
181
185
  runeDepth: e,
182
186
  assetDepth: r,
183
187
  percent: n
184
188
  }) => Object.fromEntries(
185
- Object.entries(Bt({ liquidityUnits: s, poolUnits: t, runeDepth: e, assetDepth: r })).map(
189
+ Object.entries(Vt({ 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,24 +197,26 @@ 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), 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
- if (X.baseValueNumber === 0)
198
- return D.div(u).baseValueNumber;
200
+ const a = new y({ value: s, decimal: 8 }), c = new y({ value: e, decimal: 8 }), u = new y({ value: t, decimal: 8 }), l = new y({ value: n, decimal: 8 }), h = new y({ value: i, decimal: 8 }), g = l.mul(c), v = h.mul(a), L = l.mul(h), ft = a.mul(c), pt = u.mul(g.add(v.add(L.mul(2)))), _t = g.add(v.add(ft.mul(2))), X = pt.div(_t), D = f(r).add(X);
201
+ if (X.getBaseValue("number") === 0)
202
+ return D.div(u).getBaseValue("number");
199
203
  const gt = u.add(D);
200
- return D.div(gt).baseValueNumber;
201
- }, ce = ({
204
+ return D.div(gt).getBaseValue("number");
205
+ }, ue = ({
202
206
  runeAmount: s,
203
207
  assetAmount: t,
204
208
  runeDepth: e,
205
209
  assetDepth: r
206
210
  }) => {
207
- const n = d(e), i = d(r), a = d(t), c = d(s), u = a.mul(n).sub(i.mul(c)), l = i.mul(c).add(n.mul(i));
208
- return Math.abs(u.div(l).baseValueNumber);
211
+ if (s === "0" || t === "0" || e === "0" || r === "0")
212
+ return 0;
213
+ const n = f(e), i = f(r), a = f(t), c = f(s), u = a.mul(n).sub(i.mul(c)), l = i.mul(c).add(n.mul(i));
214
+ return Math.abs(u.div(l).getBaseValue("number"));
209
215
  }, Mt = ({
210
216
  symbol: s,
211
217
  ticker: t,
212
218
  chain: e
213
- }) => e === "ETH" && t !== "ETH" ? `${t}-${s.slice(-3)}` : s, ue = (s, t) => {
219
+ }) => e === "ETH" && t !== "ETH" ? `${t}-${s.slice(-3)}` : s, le = (s, t) => {
214
220
  switch (s) {
215
221
  case b.LEAVE:
216
222
  case b.BOND: {
@@ -241,16 +247,16 @@ const Tt = "0x313ce567", nt = async ({ chain: s, to: t }) => {
241
247
  default:
242
248
  return "";
243
249
  }
244
- }, le = (s) => {
250
+ }, he = (s) => {
245
251
  if (s < 0)
246
252
  throw new Error("Invalid number of year");
247
253
  return 10 + s;
248
- }, he = (s) => {
254
+ }, de = (s) => {
249
255
  if (s.length > 30)
250
256
  return !1;
251
257
  const t = /^[a-zA-Z0-9+_-]+$/g;
252
258
  return !!s.match(t);
253
- }, de = ([s, t, e, r, n]) => `${s}'/${t}'/${e}'/${r}${typeof n != "number" ? "" : `/${n}`}`;
259
+ }, me = ([s, t, e, r, n]) => `${s}'/${t}'/${e}'/${r}${typeof n != "number" ? "" : `/${n}`}`;
254
260
  class Z extends Error {
255
261
  constructor(t, e, r) {
256
262
  const n = t.status || t.status === 0 ? t.status : "", i = t.statusText || "", a = `${n} ${i}`.trim(), c = a ? `status code ${a}` : "an unknown error";
@@ -282,25 +288,25 @@ class ot extends Error {
282
288
  }), this.name = "TimeoutError", this.request = t;
283
289
  }
284
290
  }
285
- const B = (s) => s !== null && typeof s == "object", V = (...s) => {
291
+ const M = (s) => s !== null && typeof s == "object", V = (...s) => {
286
292
  for (const t of s)
287
- if ((!B(t) || Array.isArray(t)) && t !== void 0)
293
+ if ((!M(t) || Array.isArray(t)) && t !== void 0)
288
294
  throw new TypeError("The `options` argument must be an object");
289
- return K({}, ...s);
295
+ return Q({}, ...s);
290
296
  }, at = (s = {}, t = {}) => {
291
297
  const e = new globalThis.Headers(s), r = t instanceof globalThis.Headers, n = new globalThis.Headers(t);
292
298
  for (const [i, a] of n.entries())
293
299
  r && a === "undefined" || a === void 0 ? e.delete(i) : e.set(i, a);
294
300
  return e;
295
- }, K = (...s) => {
301
+ }, Q = (...s) => {
296
302
  let t = {}, e = {};
297
303
  for (const r of s)
298
304
  if (Array.isArray(r))
299
305
  Array.isArray(t) || (t = []), t = [...t, ...r];
300
- else if (B(r)) {
306
+ else if (M(r)) {
301
307
  for (let [n, i] of Object.entries(r))
302
- B(i) && n in t && (i = K(t[n], i)), t = { ...t, [n]: i };
303
- B(r.headers) && (e = at(e, r.headers), t.headers = e);
308
+ M(i) && n in t && (i = Q(t[n], i)), t = { ...t, [n]: i };
309
+ M(r.headers) && (e = at(e, r.headers), t.headers = e);
304
310
  }
305
311
  return t;
306
312
  }, kt = (() => {
@@ -320,7 +326,7 @@ const B = (s) => s !== null && typeof s == "object", V = (...s) => {
320
326
  formData: "multipart/form-data",
321
327
  arrayBuffer: "*/*",
322
328
  blob: "*/*"
323
- }, U = 2147483647, ut = Symbol("stop"), Ht = {
329
+ }, F = 2147483647, ut = Symbol("stop"), Ht = {
324
330
  json: !0,
325
331
  parseJson: !0,
326
332
  searchParams: !0,
@@ -347,9 +353,9 @@ const B = (s) => s !== null && typeof s == "object", V = (...s) => {
347
353
  window: !0,
348
354
  dispatcher: !0,
349
355
  duplex: !0
350
- }, Dt = (s) => ct.includes(s) ? s.toUpperCase() : s, Lt = ["get", "put", "head", "delete", "options", "trace"], Ut = [408, 413, 429, 500, 502, 503, 504], lt = [413, 429, 503], tt = {
356
+ }, Lt = (s) => ct.includes(s) ? s.toUpperCase() : s, Dt = ["get", "put", "head", "delete", "options", "trace"], Ut = [408, 413, 429, 500, 502, 503, 504], lt = [413, 429, 503], tt = {
351
357
  limit: 2,
352
- methods: Lt,
358
+ methods: Dt,
353
359
  statusCodes: Ut,
354
360
  afterStatusCodes: lt,
355
361
  maxRetryAfter: Number.POSITIVE_INFINITY,
@@ -398,11 +404,11 @@ const Yt = (s, t) => {
398
404
  !(r in jt) && !(r in Ht) && !(r in s) && (e[r] = t[r]);
399
405
  return e;
400
406
  };
401
- class q {
407
+ class x {
402
408
  static create(t, e) {
403
- const r = new q(t, e), n = async () => {
404
- if (typeof r._options.timeout == "number" && r._options.timeout > U)
405
- throw new RangeError(`The \`timeout\` option cannot be greater than ${U}`);
409
+ const r = new x(t, e), n = async () => {
410
+ if (typeof r._options.timeout == "number" && r._options.timeout > F)
411
+ throw new RangeError(`The \`timeout\` option cannot be greater than ${F}`);
406
412
  await Promise.resolve();
407
413
  let c = await r._fetch();
408
414
  for (const u of r._options.hooks.afterResponse) {
@@ -470,13 +476,13 @@ class q {
470
476
  credentials: this._input.credentials || "same-origin",
471
477
  ...e,
472
478
  headers: at(this._input.headers, e.headers),
473
- hooks: K({
479
+ hooks: Q({
474
480
  beforeRequest: [],
475
481
  beforeRetry: [],
476
482
  beforeError: [],
477
483
  afterResponse: []
478
484
  }, e.hooks),
479
- method: Dt(e.method ?? this._input.method),
485
+ method: Lt(e.method ?? this._input.method),
480
486
  // eslint-disable-next-line @typescript-eslint/prefer-nullish-coalescing
481
487
  prefixUrl: String(e.prefixUrl || ""),
482
488
  retry: Ft(e.retry),
@@ -530,7 +536,7 @@ class q {
530
536
  try {
531
537
  return await t();
532
538
  } catch (e) {
533
- const r = Math.min(this._calculateRetryDelay(e), U);
539
+ const r = Math.min(this._calculateRetryDelay(e), F);
534
540
  if (r !== 0 && this._retryCount > 0) {
535
541
  await Gt(r, { signal: this._options.signal });
536
542
  for (const n of this._options.hooks.beforeRetry)
@@ -594,21 +600,15 @@ class q {
594
600
  }
595
601
  }
596
602
  /*! MIT License © Sindre Sorhus */
597
- const G = (s) => {
598
- const t = (e, r) => q.create(e, V(s, r));
603
+ const Y = (s) => {
604
+ const t = (e, r) => x.create(e, V(s, r));
599
605
  for (const e of ct)
600
- t[e] = (r, n) => q.create(r, V(s, n, { method: e }));
601
- return t.create = (e) => G(V(e)), t.extend = (e) => G(V(s, e)), t.stop = ut, t;
602
- }, zt = G(), 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 = {
606
+ t[e] = (r, n) => x.create(r, V(s, n, { method: e }));
607
+ return t.create = (e) => Y(V(e)), t.extend = (e) => Y(V(s, e)), t.stop = ut, t;
608
+ }, zt = Y(), Jt = zt, Kt = typeof window < "u" ? {} : { referrer: "https://sk.thorswap.net", referer: "https://sk.thorswap.net" }, et = Jt.create({ headers: Kt }), Qt = {
609
609
  get: (s, t) => et.get(s, t).json(),
610
610
  post: (s, t) => et.post(s, t).json()
611
- }, rt = Object.values(o), Qt = (s = "") => {
611
+ }, rt = Object.values(o), Xt = (s = "") => {
612
612
  const t = s.toUpperCase(), [e] = t.split(".");
613
613
  if (rt.includes(e))
614
614
  return !0;
@@ -618,11 +618,11 @@ const G = (s) => {
618
618
  throw new Error(
619
619
  `Invalid identifier: ${s}. Expected format: <Chain>.<Ticker> or <Chain>.<Ticker>-<ContractAddress>`
620
620
  );
621
- }, C = 8, v = (s) => 10n ** BigInt(s), R = (s) => Math.log10(parseFloat(s.toString()));
622
- function x({
621
+ }, I = 8, R = (s) => 10n ** BigInt(s), S = (s) => Math.log10(parseFloat(s.toString()));
622
+ function P({
623
623
  value: s,
624
- bigIntDecimal: t = C,
625
- decimal: e = C
624
+ bigIntDecimal: t = I,
625
+ decimal: e = I
626
626
  }) {
627
627
  const r = s < 0n;
628
628
  let n = s.toString().substring(r ? 1 : 0);
@@ -635,27 +635,27 @@ function x({
635
635
  ""
636
636
  );
637
637
  }
638
- var w, S, P, ht, N, dt, E, Y, A, $, O, z;
639
- const H = class H {
638
+ var A, $, N, ht, H, dt, O, z, T, C, B, J;
639
+ const j = class j {
640
640
  constructor(t) {
641
- y(this, w);
642
- y(this, P);
643
- y(this, N);
644
- y(this, E);
645
- y(this, A);
646
- y(this, O);
641
+ w(this, A);
642
+ w(this, N);
643
+ w(this, H);
644
+ w(this, O);
645
+ w(this, T);
646
+ w(this, B);
647
647
  p(this, "decimalMultiplier", 10n ** 8n);
648
648
  p(this, "bigIntValue", 0n);
649
649
  p(this, "decimal");
650
- const e = F(t);
651
- this.decimal = typeof t == "object" ? t.decimal : void 0, this.decimalMultiplier = v(
652
- Math.max(f(this, O, z).call(this, f(this, A, $).call(this, e)), this.decimal || 0)
653
- ), f(this, P, ht).call(this, e);
650
+ const e = W(t);
651
+ this.decimal = typeof t == "object" ? t.decimal : void 0, this.decimalMultiplier = R(
652
+ Math.max(m(this, B, J).call(this, m(this, T, C).call(this, e)), this.decimal || 0)
653
+ ), m(this, N, ht).call(this, e);
654
654
  }
655
655
  static fromBigInt(t, e) {
656
- return new H({
656
+ return new j({
657
657
  decimal: e,
658
- value: x({ value: t, bigIntDecimal: e, decimal: e })
658
+ value: P({ value: t, bigIntDecimal: e, decimal: e })
659
659
  });
660
660
  }
661
661
  static shiftDecimals({
@@ -664,7 +664,7 @@ const H = class H {
664
664
  to: r
665
665
  }) {
666
666
  return this.fromBigInt(
667
- new H(t).bigIntValue * v(r) / v(e),
667
+ new j(t).bigIntValue * R(r) / R(e),
668
668
  r
669
669
  );
670
670
  }
@@ -690,16 +690,16 @@ const H = class H {
690
690
  return new this.constructor({ decimal: this.decimal, value: t, identifier: this.toString() });
691
691
  }
692
692
  add(...t) {
693
- return f(this, w, S).call(this, "add", ...t);
693
+ return m(this, A, $).call(this, "add", ...t);
694
694
  }
695
695
  sub(...t) {
696
- return f(this, w, S).call(this, "sub", ...t);
696
+ return m(this, A, $).call(this, "sub", ...t);
697
697
  }
698
698
  mul(...t) {
699
- return f(this, w, S).call(this, "mul", ...t);
699
+ return m(this, A, $).call(this, "mul", ...t);
700
700
  }
701
701
  div(...t) {
702
- return f(this, w, S).call(this, "div", ...t);
702
+ return m(this, A, $).call(this, "div", ...t);
703
703
  }
704
704
  gt(t) {
705
705
  return this.bigIntValue > this.getBigIntValue(t);
@@ -719,7 +719,7 @@ const H = class H {
719
719
  getValue(t) {
720
720
  const e = this.formatBigIntToSafeValue(
721
721
  this.bigIntValue,
722
- this.decimal || R(this.decimalMultiplier)
722
+ this.decimal || S(this.decimalMultiplier)
723
723
  );
724
724
  switch (t) {
725
725
  case "number":
@@ -731,7 +731,7 @@ const H = class H {
731
731
  }
732
732
  }
733
733
  getBaseValue(t) {
734
- const e = this.decimalMultiplier / v(this.decimal || m.THOR), r = this.bigIntValue / e;
734
+ const e = this.decimalMultiplier / R(this.decimal || d.THOR), r = this.bigIntValue / e;
735
735
  switch (t) {
736
736
  case "number":
737
737
  return Number(r);
@@ -744,13 +744,13 @@ const H = class H {
744
744
  getBigIntValue(t, e) {
745
745
  if (!e && typeof t == "object")
746
746
  return t.bigIntValue;
747
- const r = F(t), n = f(this, A, $).call(this, r);
748
- return n === "0" || n === "undefined" ? 0n : f(this, E, Y).call(this, n, e);
747
+ const r = W(t), n = m(this, T, C).call(this, r);
748
+ return n === "0" || n === "undefined" ? 0n : m(this, O, z).call(this, n, e);
749
749
  }
750
750
  formatBigIntToSafeValue(t, e) {
751
- const r = e || this.decimal || C, n = Math.max(
751
+ const r = e || this.decimal || I, n = Math.max(
752
752
  r,
753
- R(this.decimalMultiplier)
753
+ S(this.decimalMultiplier)
754
754
  ), i = t < 0n, a = t.toString().substring(i ? 1 : 0), c = n - (a.length - 1), u = c > 0 ? "0".repeat(c) + a : a, l = u.length - n;
755
755
  let h = u.slice(-n);
756
756
  return parseInt(h[r]) >= 5 ? h = `${h.substring(0, r - 1)}${(parseInt(h[r - 1]) + 1).toString()}` : h = h.substring(0, r), `${i ? "-" : ""}${u.slice(
@@ -759,14 +759,14 @@ const H = class H {
759
759
  )}.${h}`.replace(/\.?0*$/, "");
760
760
  }
761
761
  toSignificant(t = 6) {
762
- const [e, r] = this.getValue("string").split("."), n = e || "", i = r || "", a = parseInt(n) ? n.length + i.length : i.length;
763
- if (a <= t)
762
+ const [e, r] = this.getValue("string").split("."), n = e || "", i = r || "";
763
+ if ((parseInt(n) ? n.length + i.length : i.length) <= t)
764
764
  return this.getValue("string");
765
765
  if (n.length >= t)
766
766
  return n.slice(0, t).padEnd(n.length, "0");
767
767
  if (parseInt(n))
768
768
  return `${n}.${i.slice(0, t - n.length)}`.padEnd(
769
- a - t,
769
+ t - n.length,
770
770
  "0"
771
771
  );
772
772
  const c = parseInt(i), u = `${c}`.slice(0, t);
@@ -793,8 +793,8 @@ const H = class H {
793
793
  return `${(e / a).toFixed(t)}${i}`;
794
794
  }
795
795
  };
796
- w = new WeakSet(), S = function(t, ...e) {
797
- const r = f(this, N, dt).call(this, this, ...e), n = v(r), i = e.reduce(
796
+ A = new WeakSet(), $ = function(t, ...e) {
797
+ const r = m(this, H, dt).call(this, this, ...e), n = R(r), i = e.reduce(
798
798
  (c, u) => {
799
799
  const l = this.getBigIntValue(u, r);
800
800
  switch (t) {
@@ -815,53 +815,53 @@ w = new WeakSet(), S = function(t, ...e) {
815
815
  },
816
816
  //normalize is to precision multiplier base
817
817
  this.bigIntValue * n / this.decimalMultiplier
818
- ), a = x({
818
+ ), a = P({
819
819
  bigIntDecimal: r,
820
- decimal: Math.max(r, R(this.decimalMultiplier)),
820
+ decimal: Math.max(r, S(this.decimalMultiplier)),
821
821
  value: i
822
822
  });
823
823
  return new this.constructor({ decimal: this.decimal, value: a, identifier: this.toString() });
824
- }, P = new WeakSet(), ht = function(t) {
825
- const e = f(this, A, $).call(this, t) || "0";
826
- this.bigIntValue = f(this, E, Y).call(this, e);
827
- }, N = new WeakSet(), dt = function(...t) {
824
+ }, N = new WeakSet(), ht = function(t) {
825
+ const e = m(this, T, C).call(this, t) || "0";
826
+ this.bigIntValue = m(this, O, z).call(this, e);
827
+ }, H = new WeakSet(), dt = function(...t) {
828
828
  const e = t.map(
829
- (r) => typeof r == "object" ? r.decimal || R(r.decimalMultiplier) : f(this, O, z).call(this, f(this, A, $).call(this, r))
829
+ (r) => typeof r == "object" ? r.decimal || S(r.decimalMultiplier) : m(this, B, J).call(this, m(this, T, C).call(this, r))
830
830
  ).filter(Boolean);
831
- return Math.max(...e, C);
832
- }, E = new WeakSet(), Y = function(t, e) {
833
- const r = e ? v(e) : this.decimalMultiplier, n = R(r), [i = "", a = ""] = t.split(".");
831
+ return Math.max(...e, I);
832
+ }, O = new WeakSet(), z = function(t, e) {
833
+ const r = e ? R(e) : this.decimalMultiplier, n = S(r), [i = "", a = ""] = t.split(".");
834
834
  return BigInt(`${i}${a.padEnd(n, "0")}`);
835
- }, A = new WeakSet(), $ = function(t) {
835
+ }, T = new WeakSet(), C = function(t) {
836
836
  const r = `${typeof t == "number" ? Number(t).toLocaleString("fullwide", {
837
837
  useGrouping: !1,
838
838
  maximumFractionDigits: 20
839
- }) : F(t)}`.replaceAll(",", ".").split(".");
839
+ }) : W(t)}`.replaceAll(",", ".").split(".");
840
840
  return r.length > 1 ? `${r.slice(0, -1).join("")}.${r.at(-1)}` : r[0];
841
- }, O = new WeakSet(), z = function(t) {
841
+ }, B = new WeakSet(), J = function(t) {
842
842
  var r;
843
843
  const e = ((r = t.split(".")[1]) == null ? void 0 : r.length) || 0;
844
- return Math.max(e, C);
844
+ return Math.max(e, I);
845
845
  };
846
- let I = H;
847
- function F(s) {
846
+ let E = j;
847
+ function W(s) {
848
848
  return typeof s == "object" ? "getValue" in s ? s.getValue("string") : s.value : s;
849
849
  }
850
- const M = (s, t) => typeof s == "bigint" ? x({ value: s, bigIntDecimal: t, decimal: t }) : s;
851
- let J;
852
- const W = (s) => {
853
- if (!J)
850
+ const k = (s, t) => typeof s == "bigint" ? P({ value: s, bigIntDecimal: t, decimal: t }) : s;
851
+ let K;
852
+ const G = (s) => {
853
+ if (!K)
854
854
  throw new Error("Static assets not loaded, call await AssetValue.loadStaticAssets() first");
855
- return J.get(s.toUpperCase()) || { decimal: m.THOR, identifier: "" };
855
+ return K.get(s.toUpperCase()) || { decimal: d.THOR, identifier: "" };
856
856
  }, st = async (s, t = 0) => {
857
- Qt(s);
858
- const e = await it(k(s)), r = M(t, e);
857
+ Xt(s);
858
+ const e = await it(q(s)), r = k(t, e);
859
859
  return new _({ decimal: e, value: r, identifier: s });
860
860
  };
861
- class _ extends I {
861
+ class _ extends E {
862
862
  constructor(e) {
863
863
  super(
864
- e.value instanceof I ? e.value : { decimal: e.decimal, value: e.value }
864
+ e.value instanceof E ? e.value : { decimal: e.decimal, value: e.value }
865
865
  );
866
866
  p(this, "address");
867
867
  p(this, "chain");
@@ -870,7 +870,7 @@ class _ extends I {
870
870
  p(this, "symbol");
871
871
  p(this, "ticker");
872
872
  p(this, "type");
873
- const r = "identifier" in e ? e.identifier : `${e.chain}.${e.symbol}`, n = k(r);
873
+ const r = "identifier" in e ? e.identifier : `${e.chain}.${e.symbol}`, n = q(r);
874
874
  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
875
  }
876
876
  get assetValue() {
@@ -890,30 +890,30 @@ class _ extends I {
890
890
  return st(e, r);
891
891
  }
892
892
  static fromStringSync(e, r = 0) {
893
- const { isSynthetic: n } = k(e), { decimal: i, identifier: a } = W(
893
+ const { isSynthetic: n } = q(e), { decimal: i, identifier: a } = G(
894
894
  e
895
- ), c = M(r, i);
895
+ ), c = k(r, i);
896
896
  return a ? new _({ decimal: i, identifier: a, value: c }) : n ? new _({ decimal: 8, identifier: e, value: c }) : void 0;
897
897
  }
898
898
  static async fromIdentifier(e, r = 0) {
899
899
  return st(e, r);
900
900
  }
901
901
  static fromIdentifierSync(e, r = 0) {
902
- const { decimal: n, identifier: i } = W(e), a = M(r, n);
902
+ const { decimal: n, identifier: i } = G(e), a = k(r, n);
903
903
  return new _({ decimal: n, identifier: i, value: a });
904
904
  }
905
905
  static fromChainOrSignature(e, r = 0) {
906
- const { decimal: n, identifier: i } = Ct(e), a = M(r, n);
906
+ const { decimal: n, identifier: i } = Ct(e), a = k(r, n);
907
907
  return new _({ value: a, decimal: n, identifier: i });
908
908
  }
909
909
  static async fromTCQuote(e, r = 0) {
910
- const n = await it(k(e)), i = this.shiftDecimals({ value: r, from: m.THOR, to: n });
910
+ const n = await it(q(e)), i = this.shiftDecimals({ value: r, from: d.THOR, to: n });
911
911
  return new _({ value: i, identifier: e, decimal: n });
912
912
  }
913
913
  static fromTCQuoteStatic(e, r = 0) {
914
- const n = W(e), i = this.shiftDecimals({
914
+ const n = G(e), i = this.shiftDecimals({
915
915
  value: r,
916
- from: m.THOR,
916
+ from: d.THOR,
917
917
  to: n.decimal
918
918
  });
919
919
  return new _({ ...n, value: i });
@@ -929,10 +929,10 @@ class _ extends I {
929
929
  NativeList: i,
930
930
  ...a
931
931
  } = await import("@swapkit/tokens");
932
- J = [i, ...Object.values(a)].reduce(
933
- (u, { tokens: l }) => (l.forEach(({ identifier: h, chain: g, ...T }) => {
934
- const j = "decimals" in T ? T.decimals : m[g];
935
- u.set(h, { identifier: h, decimal: j });
932
+ K = [i, ...Object.values(a)].reduce(
933
+ (u, { tokens: l }) => (l.forEach(({ identifier: h, chain: g, ...v }) => {
934
+ const L = "decimals" in v ? v.decimals : d[g];
935
+ u.set(h, { identifier: h, decimal: L });
936
936
  }), u),
937
937
  /* @__PURE__ */ new Map()
938
938
  ), e({ ok: !0 });
@@ -947,7 +947,7 @@ class _ extends I {
947
947
  );
948
948
  }
949
949
  }
950
- const me = (s) => {
950
+ const fe = (s) => {
951
951
  const t = _.fromChainOrSignature(s);
952
952
  switch (s) {
953
953
  case o.Bitcoin:
@@ -965,7 +965,7 @@ const me = (s) => {
965
965
  default:
966
966
  return t.add(1);
967
967
  }
968
- }, k = (s) => {
968
+ }, q = (s) => {
969
969
  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
970
  return {
971
971
  address: u == null ? void 0 : u.toLowerCase(),
@@ -975,7 +975,7 @@ const me = (s) => {
975
975
  symbol: (t ? `${e}/` : "") + (u ? `${c}-${(u == null ? void 0 : u.toLowerCase()) ?? ""}` : a),
976
976
  ticker: c
977
977
  };
978
- }, Xt = {
978
+ }, Zt = {
979
979
  /**
980
980
  * Core
981
981
  */
@@ -1034,45 +1034,45 @@ const me = (s) => {
1034
1034
  };
1035
1035
  class mt extends Error {
1036
1036
  constructor(t, e) {
1037
- console.error(e), super(t, { cause: { code: Xt[t], message: t } }), Object.setPrototypeOf(this, mt.prototype);
1037
+ console.error(e), super(t, { cause: { code: Zt[t], message: t } }), Object.setPrototypeOf(this, mt.prototype);
1038
1038
  }
1039
1039
  }
1040
- class Q extends I {
1040
+ class y extends E {
1041
1041
  eq(t) {
1042
1042
  return this.eqValue(t);
1043
1043
  }
1044
1044
  static fromBigInt(t, e) {
1045
- return new Q({
1045
+ return new y({
1046
1046
  decimal: e,
1047
- value: x({ value: t, bigIntDecimal: e, decimal: e })
1047
+ value: P({ value: t, bigIntDecimal: e, decimal: e })
1048
1048
  });
1049
1049
  }
1050
1050
  }
1051
1051
  export {
1052
1052
  _ as AssetValue,
1053
- I as BigIntArithmetics,
1054
- Kt as RequestClient,
1053
+ E as BigIntArithmetics,
1054
+ Qt as RequestClient,
1055
1055
  mt as SwapKitError,
1056
- Q as SwapKitNumber,
1057
- re as assetFromString,
1058
- de as derivationPathToString,
1059
- se as filterAssets,
1060
- x as formatBigIntToSafeValue,
1061
- ee as gasFeeMultiplier,
1056
+ y as SwapKitNumber,
1057
+ se as assetFromString,
1058
+ me as derivationPathToString,
1059
+ ne as filterAssets,
1060
+ P as formatBigIntToSafeValue,
1061
+ re as gasFeeMultiplier,
1062
1062
  It as getAssetType,
1063
- Vt as getAsymmetricAssetShare,
1064
- ie as getAsymmetricAssetWithdrawAmount,
1063
+ Bt as getAsymmetricAssetShare,
1064
+ oe as getAsymmetricAssetWithdrawAmount,
1065
1065
  Ot as getAsymmetricRuneShare,
1066
- ne as getAsymmetricRuneWithdrawAmount,
1066
+ ie as getAsymmetricRuneWithdrawAmount,
1067
1067
  Ct as getCommonAssetInfo,
1068
1068
  it as getDecimal,
1069
- ae as getEstimatedPoolShare,
1070
- ce as getLiquiditySlippage,
1071
- ue as getMemoFor,
1072
- me as getMinAmountByChain,
1073
- Bt as getSymmetricPoolShare,
1074
- oe as getSymmetricWithdraw,
1075
- le as getTHORNameCost,
1069
+ ce as getEstimatedPoolShare,
1070
+ ue as getLiquiditySlippage,
1071
+ le as getMemoFor,
1072
+ fe as getMinAmountByChain,
1073
+ Vt as getSymmetricPoolShare,
1074
+ ae as getSymmetricWithdraw,
1075
+ he as getTHORNameCost,
1076
1076
  $t as isGasAsset,
1077
- he as validateTHORName
1077
+ de as validateTHORName
1078
1078
  };
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.15",
45
+ "version": "1.0.0-rc.17",
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',
@@ -81,7 +81,7 @@ export const getAsymmetricAssetWithdrawAmount = ({
81
81
  getAsymmetricAssetShare({ assetDepth, liquidityUnits, poolUnits }).mul(percent);
82
82
 
83
83
  const toTCSwapKitNumber = (value: string) =>
84
- new SwapKitNumber({ value, decimal: BaseDecimal.THOR });
84
+ SwapKitNumber.fromBigInt(BigInt(value), BaseDecimal.THOR);
85
85
 
86
86
  export const getSymmetricPoolShare = ({
87
87
  liquidityUnits,
@@ -126,11 +126,11 @@ export const getEstimatedPoolShare = ({
126
126
  runeDepth: string;
127
127
  assetDepth: string;
128
128
  }>) => {
129
- const R = toTCSwapKitNumber(runeDepth);
130
- const A = toTCSwapKitNumber(assetDepth);
131
- const P = toTCSwapKitNumber(poolUnits);
132
- const runeAddAmount = toTCSwapKitNumber(runeAmount);
133
- const assetAddAmount = toTCSwapKitNumber(assetAmount);
129
+ const R = new SwapKitNumber({ value: runeDepth, decimal: 8 });
130
+ const A = new SwapKitNumber({ value: assetDepth, decimal: 8 });
131
+ const P = new SwapKitNumber({ value: poolUnits, decimal: 8 });
132
+ const runeAddAmount = new SwapKitNumber({ value: runeAmount, decimal: 8 });
133
+ const assetAddAmount = new SwapKitNumber({ value: assetAmount, decimal: 8 });
134
134
 
135
135
  // liquidityUnits = P * (r*A + a*R + 2*r*a) / (r*A + a*R + 2*R*A)
136
136
  const rA = runeAddAmount.mul(A);
@@ -142,14 +142,14 @@ export const getEstimatedPoolShare = ({
142
142
  const liquidityUnitsAfterAdd = numerator.div(denominator);
143
143
  const estimatedLiquidityUnits = toTCSwapKitNumber(liquidityUnits).add(liquidityUnitsAfterAdd);
144
144
 
145
- if (liquidityUnitsAfterAdd.baseValueNumber === 0) {
146
- return estimatedLiquidityUnits.div(P).baseValueNumber;
145
+ if (liquidityUnitsAfterAdd.getBaseValue('number') === 0) {
146
+ return estimatedLiquidityUnits.div(P).getBaseValue('number');
147
147
  }
148
148
 
149
149
  // get pool units after add
150
150
  const newPoolUnits = P.add(estimatedLiquidityUnits);
151
151
 
152
- return estimatedLiquidityUnits.div(newPoolUnits).baseValueNumber;
152
+ return estimatedLiquidityUnits.div(newPoolUnits).getBaseValue('number');
153
153
  };
154
154
 
155
155
  export const getLiquiditySlippage = ({
@@ -158,6 +158,8 @@ export const getLiquiditySlippage = ({
158
158
  runeDepth,
159
159
  assetDepth,
160
160
  }: PoolParams) => {
161
+ if (runeAmount === '0' || assetAmount === '0' || runeDepth === '0' || assetDepth === '0')
162
+ return 0;
161
163
  // formula: (t * R - T * r)/ (T*r + R*T)
162
164
  const R = toTCSwapKitNumber(runeDepth);
163
165
  const T = toTCSwapKitNumber(assetDepth);
@@ -168,5 +170,5 @@ export const getLiquiditySlippage = ({
168
170
  const denominator = T.mul(runeAddAmount).add(R.mul(T));
169
171
 
170
172
  // set absolute value of percent, no negative allowed
171
- return Math.abs(numerator.div(denominator).baseValueNumber);
173
+ return Math.abs(numerator.div(denominator).getBaseValue('number'));
172
174
  };
@@ -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>(),
@@ -238,7 +238,7 @@ export class BigIntArithmetics {
238
238
 
239
239
  if (parseInt(integer)) {
240
240
  return `${integer}.${decimal.slice(0, significantDigits - integer.length)}`.padEnd(
241
- valueLength - significantDigits,
241
+ significantDigits - integer.length,
242
242
  '0',
243
243
  );
244
244
  }