@swapkit/helpers 1.0.0-rc.16 → 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:"*/*","content-type":"application/json","cache-control":"no-cache"},body:JSON.stringify({id:44,jsonrpc:"2.0",method:"eth_call",params:[{to:t.toLowerCase(),data:Mt},"latest"]})});return parseInt(BigInt(e).toString())}catch(e){return console.error(e),i.BaseDecimal[r]}},Vt=async r=>{if(r===i.Chain.Ethereum)return i.BaseDecimal.ETH;const[,t]=r.split("-");return t!=null&&t.startsWith("0x")?nt({chain:i.Chain.Ethereum,to:t}):i.BaseDecimal.ETH},qt=async r=>{const[,t]=r.split("-");return t!=null&&t.startsWith("0x")?nt({chain:i.Chain.Avalanche,to:t.toLowerCase()}):i.BaseDecimal.AVAX},kt=async r=>(r===i.Chain.BinanceSmartChain,i.BaseDecimal.BSC),z=async({chain:r,symbol:t})=>{switch(r){case i.Chain.Ethereum:return Vt(t);case i.Chain.Avalanche:return qt(t);case i.Chain.BinanceSmartChain:return kt(t);default:return i.BaseDecimal[r]}},Pt={[i.FeeOption.Average]:1.2,[i.FeeOption.Fast]:1.5,[i.FeeOption.Fastest]:2},it=({chain:r,symbol:t})=>{switch(r){case i.Chain.Bitcoin:case i.Chain.BitcoinCash:case i.Chain.Litecoin:case i.Chain.Dogecoin:case i.Chain.Binance:case i.Chain.Ethereum:case i.Chain.Avalanche:return t===r;case i.Chain.Arbitrum:case i.Chain.Optimism:return t==="ETH";case i.Chain.Maya:return t==="CACAO";case i.Chain.Kujira:return t==="KUJI";case i.Chain.Cosmos:return t==="ATOM";case i.Chain.Polygon:return t==="MATIC";case i.Chain.BinanceSmartChain:return t==="BNB";case i.Chain.THORChain:return t==="RUNE"}},at=r=>{switch(r){case"ETH.THOR":return{identifier:"ETH.THOR-0xa5f2211b9b8170f694421f2046281775e8468044",decimal:18};case"ETH.vTHOR":return{identifier:"ETH.vTHOR-0x815c23eca83261b6ec689b60cc4a58b54bc24d8d",decimal:18};case i.Chain.Cosmos:return{identifier:"GAIA.ATOM",decimal:i.BaseDecimal[r]};case i.Chain.THORChain:return{identifier:"THOR.RUNE",decimal:i.BaseDecimal[r]};case i.Chain.BinanceSmartChain:return{identifier:"BSC.BNB",decimal:i.BaseDecimal[r]};case i.Chain.Maya:return{identifier:"MAYA.CACAO",decimal:i.BaseDecimal.MAYA};case"MAYA.MAYA":return{identifier:"MAYA.MAYA",decimal:4};case i.Chain.Kujira:case i.Chain.Arbitrum:case i.Chain.Optimism:case i.Chain.BitcoinCash:case i.Chain.Litecoin:case i.Chain.Dogecoin:case i.Chain.Binance:case i.Chain.Avalanche:case i.Chain.Polygon:case i.Chain.Bitcoin:case i.Chain.Ethereum:return{identifier:`${r}.${r}`,decimal:i.BaseDecimal[r]}}},ot=({chain:r,symbol:t})=>{if(t.includes("/"))return"Synth";switch(r){case i.Chain.Bitcoin:case i.Chain.BitcoinCash:case i.Chain.Dogecoin:case i.Chain.Litecoin:case i.Chain.Maya:case i.Chain.THORChain:return"Native";case i.Chain.Cosmos:return t==="ATOM"?"Native":i.Chain.Cosmos;case i.Chain.Kujira:return t===i.Chain.Kujira?"Native":i.Chain.Kujira;case i.Chain.Binance:return t===i.Chain.Binance?"Native":"BEP2";case i.Chain.BinanceSmartChain:return t===i.Chain.Binance?"Native":"BEP20";case i.Chain.Ethereum:return t===i.Chain.Ethereum?"Native":"ERC20";case i.Chain.Avalanche:return t===i.Chain.Avalanche?"Native":i.Chain.Avalanche;case i.Chain.Polygon:return t===i.Chain.Polygon?"Native":"POLYGON";case i.Chain.Arbitrum:return[i.Chain.Ethereum,i.Chain.Arbitrum].includes(t)?"Native":"ARBITRUM";case i.Chain.Optimism:return[i.Chain.Ethereum,i.Chain.Optimism].includes(t)?"Native":"OPTIMISM"}},xt=r=>{var o;const[t,...e]=r.split("."),s=r.includes("/"),n=e.join("."),a=(o=n==null?void 0:n.split("-"))==null?void 0:o[0];return{chain:t,symbol:n,ticker:a,synth:s}},Dt=new RegExp(/(.)\1{6}|\.ORG|\.NET|\.FINANCE|\.COM|WWW|HTTP|\\\\|\/\/|[\s$%:[\]]/,"gmi"),Nt=r=>r.filter(t=>!Dt.test(t.toString())&&!t.toString().includes("undefined")),ct=({liquidityUnits:r,poolUnits:t,runeDepth:e})=>{const s=d(r),n=d(t),a=d(e),o=s.mul(a),c=n.mul(n).mul(2),u=n.mul(s).mul(2),l=s.mul(s),h=n.mul(n).mul(n);return o.mul(c.sub(u).add(l)).div(h)},ut=({liquidityUnits:r,poolUnits:t,assetDepth:e})=>{const s=d(r),n=d(t),a=d(e),o=s.mul(a),c=n.mul(n).mul(2),u=n.mul(s).mul(2),l=s.mul(s),h=o.mul(c.sub(u).add(l)),g=n.mul(n).mul(n);return h.div(g)},Ht=({percent:r,runeDepth:t,liquidityUnits:e,poolUnits:s})=>ct({runeDepth:t,liquidityUnits:e,poolUnits:s}).mul(r),jt=({percent:r,assetDepth:t,liquidityUnits:e,poolUnits:s})=>ut({assetDepth:t,liquidityUnits:e,poolUnits:s}).mul(r),d=r=>new D({value:r,decimal:i.BaseDecimal.THOR}),lt=({liquidityUnits:r,poolUnits:t,runeDepth:e,assetDepth:s})=>({assetAmount:d(s).mul(r).div(t),runeAmount:d(e).mul(r).div(t)}),Lt=({liquidityUnits:r,poolUnits:t,runeDepth:e,assetDepth:s,percent:n})=>Object.fromEntries(Object.entries(lt({liquidityUnits:r,poolUnits:t,runeDepth:e,assetDepth:s})).map(([a,o])=>[a,o.mul(n)])),Ft=({runeDepth:r,poolUnits:t,assetDepth:e,liquidityUnits:s,runeAmount:n,assetAmount:a})=>{const o=d(r),c=d(e),u=d(t),l=d(n),h=d(a),g=l.mul(c),C=h.mul(o),N=l.mul(h),yt=o.mul(c),Ct=u.mul(g.add(C.add(N.mul(2)))),wt=g.add(C.add(yt.mul(2))),X=Ct.div(wt),H=d(s).add(X);if(X.baseValueNumber===0)return H.div(u).baseValueNumber;const At=u.add(H);return H.div(At).baseValueNumber},Ut=({runeAmount:r,assetAmount:t,runeDepth:e,assetDepth:s})=>{const n=d(e),a=d(s),o=d(t),c=d(r),u=o.mul(n).sub(a.mul(c)),l=a.mul(c).add(n.mul(a));return Math.abs(u.div(l).baseValueNumber)},Wt=({symbol:r,ticker:t,chain:e})=>e==="ETH"&&t!=="ETH"?`${t}-${r.slice(-3)}`:r,Gt=(r,t)=>{switch(r){case i.MemoType.LEAVE:case i.MemoType.BOND:{const{address:e}=t;return`${r}:${e}`}case i.MemoType.UNBOND:{const{address:e,unbondAmount:s}=t;return`${r}:${e}:${s*10**8}`}case i.MemoType.THORNAME_REGISTER:{const{name:e,chain:s,address:n,owner:a}=t;return`${r}:${e}:${s}:${n}${a?`:${a}`:""}`}case i.MemoType.DEPOSIT:{const{chain:e,symbol:s,address:n,singleSide:a}=t;return a?`${r}:${e}/${s}::t:0`:`${r}:${e}.${s}:${n||""}:t:0`}case i.MemoType.WITHDRAW:{const{chain:e,ticker:s,symbol:n,basisPoints:a,targetAssetString:o,singleSide:c}=t,u=!c&&o?`:${o}`:"",l=Wt({chain:e,symbol:n,ticker:s});return`${r}:${e}${c?"/":"."}${l}:${a}${u}`}case i.MemoType.OPEN_LOAN:case i.MemoType.CLOSE_LOAN:{const{asset:e,address:s}=t;return`${r}:${e}:${s}`}default:return""}},Kt=r=>{if(r<0)throw new Error("Invalid number of year");return 10+r},Yt=r=>{if(r.length>30)return!1;const t=/^[a-zA-Z0-9+_-]+$/g;return!!r.match(t)},zt=([r,t,e,s,n])=>`${r}'/${t}'/${e}'/${s}${typeof n!="number"?"":`/${n}`}`;class Z extends Error{constructor(t,e,s){const n=t.status||t.status===0?t.status:"",a=t.statusText||"",o=`${n} ${a}`.trim(),c=o?`status code ${o}`:"an unknown error";super(`Request failed with ${c}`),Object.defineProperty(this,"response",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"request",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"options",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.name="HTTPError",this.response=t,this.request=e,this.options=s}}class ht extends Error{constructor(t){super("Request timed out"),Object.defineProperty(this,"request",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.name="TimeoutError",this.request=t}}const O=r=>r!==null&&typeof r=="object",E=(...r)=>{for(const t of r)if((!O(t)||Array.isArray(t))&&t!==void 0)throw new TypeError("The `options` argument must be an object");return J({},...r)},dt=(r={},t={})=>{const e=new globalThis.Headers(r),s=t instanceof globalThis.Headers,n=new globalThis.Headers(t);for(const[a,o]of n.entries())s&&o==="undefined"||o===void 0?e.delete(a):e.set(a,o);return e},J=(...r)=>{let t={},e={};for(const s of r)if(Array.isArray(s))Array.isArray(t)||(t=[]),t=[...t,...s];else if(O(s)){for(let[n,a]of Object.entries(s))O(a)&&n in t&&(a=J(t[n],a)),t={...t,[n]:a};O(s.headers)&&(e=dt(e,s.headers),t.headers=e)}return t},Jt=(()=>{let r=!1,t=!1;const e=typeof globalThis.ReadableStream=="function",s=typeof globalThis.Request=="function";return e&&s&&(t=new globalThis.Request("https://empty.invalid",{body:new globalThis.ReadableStream,method:"POST",get duplex(){return r=!0,"half"}}).headers.has("Content-Type")),r&&!t})(),Qt=typeof globalThis.AbortController=="function",Xt=typeof globalThis.ReadableStream=="function",Zt=typeof globalThis.FormData=="function",mt=["get","post","put","patch","head","delete"],te={json:"application/json",text:"text/*",formData:"multipart/form-data",arrayBuffer:"*/*",blob:"*/*"},L=2147483647,pt=Symbol("stop"),ee={json:!0,parseJson:!0,searchParams:!0,prefixUrl:!0,retry:!0,timeout:!0,hooks:!0,throwHttpErrors:!0,onDownloadProgress:!0,fetch:!0},se={method:!0,headers:!0,body:!0,mode:!0,credentials:!0,cache:!0,redirect:!0,referrer:!0,referrerPolicy:!0,integrity:!0,keepalive:!0,signal:!0,window:!0,dispatcher:!0,duplex:!0},re=r=>mt.includes(r)?r.toUpperCase():r,ne=["get","put","head","delete","options","trace"],ie=[408,413,429,500,502,503,504],ft=[413,429,503],tt={limit:2,methods:ne,statusCodes:ie,afterStatusCodes:ft,maxRetryAfter:Number.POSITIVE_INFINITY,backoffLimit:Number.POSITIVE_INFINITY,delay:r=>.3*2**(r-1)*1e3},ae=(r={})=>{if(typeof r=="number")return{...tt,limit:r};if(r.methods&&!Array.isArray(r.methods))throw new Error("retry.methods must be an array");if(r.statusCodes&&!Array.isArray(r.statusCodes))throw new Error("retry.statusCodes must be an array");return{...tt,...r,afterStatusCodes:ft}};async function oe(r,t,e,s){return new Promise((n,a)=>{const o=setTimeout(()=>{e&&e.abort(),a(new ht(r))},s.timeout);s.fetch(r,t).then(n).catch(a).then(()=>{clearTimeout(o)})})}async function ce(r,{signal:t}){return new Promise((e,s)=>{t&&(t.throwIfAborted(),t.addEventListener("abort",n,{once:!0}));function n(){clearTimeout(a),s(t.reason)}const a=setTimeout(()=>{t==null||t.removeEventListener("abort",n),e()},r)})}const ue=(r,t)=>{const e={};for(const s in t)!(s in se)&&!(s in ee)&&!(s in r)&&(e[s]=t[s]);return e};class q{static create(t,e){const s=new q(t,e),n=async()=>{if(typeof s._options.timeout=="number"&&s._options.timeout>L)throw new RangeError(`The \`timeout\` option cannot be greater than ${L}`);await Promise.resolve();let c=await s._fetch();for(const u of s._options.hooks.afterResponse){const l=await u(s.request,s._options,s._decorateResponse(c.clone()));l instanceof globalThis.Response&&(c=l)}if(s._decorateResponse(c),!c.ok&&s._options.throwHttpErrors){let u=new Z(c,s.request,s._options);for(const l of s._options.hooks.beforeError)u=await l(u);throw u}if(s._options.onDownloadProgress){if(typeof s._options.onDownloadProgress!="function")throw new TypeError("The `onDownloadProgress` option must be a function");if(!Xt)throw new Error("Streams are not supported in your environment. `ReadableStream` is missing.");return s._stream(c.clone(),s._options.onDownloadProgress)}return c},o=s._options.retry.methods.includes(s.request.method.toLowerCase())?s._retry(n):n();for(const[c,u]of Object.entries(te))o[c]=async()=>{s.request.headers.set("accept",s.request.headers.get("accept")||u);const h=(await o).clone();if(c==="json"){if(h.status===204||(await h.clone().arrayBuffer()).byteLength===0)return"";if(e.parseJson)return e.parseJson(await h.text())}return h[c]()};return o}constructor(t,e={}){if(Object.defineProperty(this,"request",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"abortController",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_retryCount",{enumerable:!0,configurable:!0,writable:!0,value:0}),Object.defineProperty(this,"_input",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_options",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this._input=t,this._options={credentials:this._input.credentials||"same-origin",...e,headers:dt(this._input.headers,e.headers),hooks:J({beforeRequest:[],beforeRetry:[],beforeError:[],afterResponse:[]},e.hooks),method:re(e.method??this._input.method),prefixUrl:String(e.prefixUrl||""),retry:ae(e.retry),throwHttpErrors:e.throwHttpErrors!==!1,timeout:e.timeout??1e4,fetch:e.fetch??globalThis.fetch.bind(globalThis)},typeof this._input!="string"&&!(this._input instanceof URL||this._input instanceof globalThis.Request))throw new TypeError("`input` must be a string, URL, or Request");if(this._options.prefixUrl&&typeof this._input=="string"){if(this._input.startsWith("/"))throw new Error("`input` must not begin with a slash when using `prefixUrl`");this._options.prefixUrl.endsWith("/")||(this._options.prefixUrl+="/"),this._input=this._options.prefixUrl+this._input}if(Qt){if(this.abortController=new globalThis.AbortController,this._options.signal){const s=this._options.signal;this._options.signal.addEventListener("abort",()=>{this.abortController.abort(s.reason)})}this._options.signal=this.abortController.signal}if(Jt&&(this._options.duplex="half"),this.request=new globalThis.Request(this._input,this._options),this._options.searchParams){const n="?"+(typeof this._options.searchParams=="string"?this._options.searchParams.replace(/^\?/,""):new URLSearchParams(this._options.searchParams).toString()),a=this.request.url.replace(/(?:\?.*?)?(?=#|$)/,n);(Zt&&this._options.body instanceof globalThis.FormData||this._options.body instanceof URLSearchParams)&&!(this._options.headers&&this._options.headers["content-type"])&&this.request.headers.delete("content-type"),this.request=new globalThis.Request(new globalThis.Request(a,{...this.request}),this._options)}this._options.json!==void 0&&(this._options.body=JSON.stringify(this._options.json),this.request.headers.set("content-type",this._options.headers.get("content-type")??"application/json"),this.request=new globalThis.Request(this.request,{body:this._options.body}))}_calculateRetryDelay(t){if(this._retryCount++,this._retryCount<this._options.retry.limit&&!(t instanceof ht)){if(t instanceof Z){if(!this._options.retry.statusCodes.includes(t.response.status))return 0;const s=t.response.headers.get("Retry-After");if(s&&this._options.retry.afterStatusCodes.includes(t.response.status)){let n=Number(s);return Number.isNaN(n)?n=Date.parse(s)-Date.now():n*=1e3,this._options.retry.maxRetryAfter!==void 0&&n>this._options.retry.maxRetryAfter?0:n}if(t.response.status===413)return 0}const e=this._options.retry.delay(this._retryCount);return Math.min(this._options.retry.backoffLimit,e)}return 0}_decorateResponse(t){return this._options.parseJson&&(t.json=async()=>this._options.parseJson(await t.text())),t}async _retry(t){try{return await t()}catch(e){const s=Math.min(this._calculateRetryDelay(e),L);if(s!==0&&this._retryCount>0){await ce(s,{signal:this._options.signal});for(const n of this._options.hooks.beforeRetry)if(await n({request:this.request,options:this._options,error:e,retryCount:this._retryCount})===pt)return;return this._retry(t)}throw e}}async _fetch(){for(const e of this._options.hooks.beforeRequest){const s=await e(this.request,this._options);if(s instanceof Request){this.request=s;break}if(s instanceof Response)return s}const t=ue(this.request,this._options);return this._options.timeout===!1?this._options.fetch(this.request.clone(),t):oe(this.request.clone(),t,this.abortController,this._options)}_stream(t,e){const s=Number(t.headers.get("content-length"))||0;let n=0;return t.status===204?(e&&e({percent:1,totalBytes:s,transferredBytes:n},new Uint8Array),new globalThis.Response(null,{status:t.status,statusText:t.statusText,headers:t.headers})):new globalThis.Response(new globalThis.ReadableStream({async start(a){const o=t.body.getReader();e&&e({percent:0,transferredBytes:0,totalBytes:s},new Uint8Array);async function c(){const{done:u,value:l}=await o.read();if(u){a.close();return}if(e){n+=l.byteLength;const h=s===0?0:n/s;e({percent:h,transferredBytes:n,totalBytes:s},l)}a.enqueue(l),await c()}await c()}}),{status:t.status,statusText:t.statusText,headers:t.headers})}}/*! MIT License © Sindre Sorhus */const W=r=>{const t=(e,s)=>q.create(e,E(r,s));for(const e of mt)t[e]=(s,n)=>q.create(s,E(r,n,{method:e}));return t.create=e=>W(E(e)),t.extend=e=>W(E(r,e)),t.stop=pt,t},le=W(),he=le,de=typeof window<"u"?{}:{referrer:"https://sk.thorswap.net",referer:"https://sk.thorswap.net"},et=he.create({headers:de}),gt={get:(r,t)=>et.get(r,t).json(),post:(r,t)=>et.post(r,t).json()},st=Object.values(i.Chain),me=(r="")=>{const t=r.toUpperCase(),[e]=t.split(".");if(st.includes(e))return!0;const[s]=t.split("/");if(st.includes(s))return!0;throw new Error(`Invalid identifier: ${r}. Expected format: <Chain>.<Ticker> or <Chain>.<Ticker>-<ContractAddress>`)},R=8,w=r=>10n**BigInt(r),T=r=>Math.log10(parseFloat(r.toString()));function $({value:r,bigIntDecimal:t=R,decimal:e=R}){const s=r<0n;let n=r.toString().substring(s?1:0);const a=e-(n.length-1);a>0&&(n="0".repeat(a)+n);const o=n.length-e;let c=n.slice(-e);return parseInt(c[t])>=5?c=`${c.substring(0,t-1)}${(parseInt(c[t-1])+1).toString()}`:c=c.substring(0,t),`${s?"-":""}${n.slice(0,o)}.${c}`.replace(/\.?0*$/,"")}var b,S,k,_t,P,bt,I,G,y,v,B,K;const x=class x{constructor(t){_(this,b);_(this,k);_(this,P);_(this,I);_(this,y);_(this,B);p(this,"decimalMultiplier",10n**8n);p(this,"bigIntValue",0n);p(this,"decimal");const e=F(t);this.decimal=typeof t=="object"?t.decimal:void 0,this.decimalMultiplier=w(Math.max(m(this,B,K).call(this,m(this,y,v).call(this,e)),this.decimal||0)),m(this,k,_t).call(this,e)}static fromBigInt(t,e){return new x({decimal:e,value:$({value:t,bigIntDecimal:e,decimal:e})})}static shiftDecimals({value:t,from:e,to:s}){return this.fromBigInt(new x(t).bigIntValue*w(s)/w(e),s)}get baseValue(){return this.getBaseValue("string")}get baseValueNumber(){return this.getBaseValue("number")}get baseValueBigInt(){return this.getBaseValue("bigint")}set(t){return new this.constructor({decimal:this.decimal,value:t,identifier:this.toString()})}add(...t){return m(this,b,S).call(this,"add",...t)}sub(...t){return m(this,b,S).call(this,"sub",...t)}mul(...t){return m(this,b,S).call(this,"mul",...t)}div(...t){return m(this,b,S).call(this,"div",...t)}gt(t){return this.bigIntValue>this.getBigIntValue(t)}gte(t){return this.bigIntValue>=this.getBigIntValue(t)}lt(t){return this.bigIntValue<this.getBigIntValue(t)}lte(t){return this.bigIntValue<=this.getBigIntValue(t)}eqValue(t){return this.bigIntValue===this.getBigIntValue(t)}getValue(t){const e=this.formatBigIntToSafeValue(this.bigIntValue,this.decimal||T(this.decimalMultiplier));switch(t){case"number":return Number(e);case"string":return e;default:return this.bigIntValue*BigInt(this.decimal||8n)/this.decimalMultiplier}}getBaseValue(t){const e=this.decimalMultiplier/w(this.decimal||i.BaseDecimal.THOR),s=this.bigIntValue/e;switch(t){case"number":return Number(s);case"string":return s.toString();default:return s}}getBigIntValue(t,e){if(!e&&typeof t=="object")return t.bigIntValue;const s=F(t),n=m(this,y,v).call(this,s);return n==="0"||n==="undefined"?0n:m(this,I,G).call(this,n,e)}formatBigIntToSafeValue(t,e){const s=e||this.decimal||R,n=Math.max(s,T(this.decimalMultiplier)),a=t<0n,o=t.toString().substring(a?1:0),c=n-(o.length-1),u=c>0?"0".repeat(c)+o:o,l=u.length-n;let h=u.slice(-n);return parseInt(h[s])>=5?h=`${h.substring(0,s-1)}${(parseInt(h[s-1])+1).toString()}`:h=h.substring(0,s),`${a?"-":""}${u.slice(0,l)}.${h}`.replace(/\.?0*$/,"")}toSignificant(t=6){const[e,s]=this.getValue("string").split("."),n=e||"",a=s||"",o=parseInt(n)?n.length+a.length:a.length;if(o<=t)return this.getValue("string");if(n.length>=t)return n.slice(0,t).padEnd(n.length,"0");if(parseInt(n))return`${n}.${a.slice(0,t-n.length)}`.padEnd(o-t,"0");const c=parseInt(a),u=`${c}`.slice(0,t);return`0.${u.padStart(a.length-`${c}`.length+u.length,"0")}`}toFixed(t=6){const[e,s]=this.getValue("string").split("."),n=e||"",a=s||"";if(parseInt(n))return`${n}.${a.slice(0,t)}`.padEnd(t,"0");const o=parseInt(a),c=`${o}`.slice(0,t);return`0.${c.padStart(a.length-`${o}`.length+c.length,"0")}`}toAbbreviation(t=2){const e=this.getValue("number"),s=["","K","M","B","T","Q","Qi","S"],n=Math.floor(Math.log10(Math.abs(e))/3),a=s[n];if(!a)return this.getValue("string");const o=10**(n*3);return`${(e/o).toFixed(t)}${a}`}};b=new WeakSet,S=function(t,...e){const s=m(this,P,bt).call(this,this,...e),n=w(s),a=e.reduce((c,u)=>{const l=this.getBigIntValue(u,s);switch(t){case"add":return c+l;case"sub":return c-l;case"mul":return c*l/n;case"div":{if(l===0n)throw new RangeError("Division by zero");return c*n/l}default:return c}},this.bigIntValue*n/this.decimalMultiplier),o=$({bigIntDecimal:s,decimal:Math.max(s,T(this.decimalMultiplier)),value:a});return new this.constructor({decimal:this.decimal,value:o,identifier:this.toString()})},k=new WeakSet,_t=function(t){const e=m(this,y,v).call(this,t)||"0";this.bigIntValue=m(this,I,G).call(this,e)},P=new WeakSet,bt=function(...t){const e=t.map(s=>typeof s=="object"?s.decimal||T(s.decimalMultiplier):m(this,B,K).call(this,m(this,y,v).call(this,s))).filter(Boolean);return Math.max(...e,R)},I=new WeakSet,G=function(t,e){const s=e?w(e):this.decimalMultiplier,n=T(s),[a="",o=""]=t.split(".");return BigInt(`${a}${o.padEnd(n,"0")}`)},y=new WeakSet,v=function(t){const s=`${typeof t=="number"?Number(t).toLocaleString("fullwide",{useGrouping:!1,maximumFractionDigits:20}):F(t)}`.replaceAll(",",".").split(".");return s.length>1?`${s.slice(0,-1).join("")}.${s.at(-1)}`:s[0]},B=new WeakSet,K=function(t){var s;const e=((s=t.split(".")[1])==null?void 0:s.length)||0;return Math.max(e,R)};let A=x;function F(r){return typeof r=="object"?"getValue"in r?r.getValue("string"):r.value:r}const M=(r,t)=>typeof r=="bigint"?$({value:r,bigIntDecimal:t,decimal:t}):r;let Y;const U=r=>{if(!Y)throw new Error("Static assets not loaded, call await AssetValue.loadStaticAssets() first");return Y.get(r.toUpperCase())||{decimal:i.BaseDecimal.THOR,identifier:""}},rt=async(r,t=0)=>{me(r);const e=await z(V(r)),s=M(t,e);return new f({decimal:e,value:s,identifier:r})};class f extends A{constructor(e){super(e.value instanceof A?e.value:{decimal:e.decimal,value:e.value});p(this,"address");p(this,"chain");p(this,"isSynthetic",!1);p(this,"isGasAsset",!1);p(this,"symbol");p(this,"ticker");p(this,"type");const s="identifier"in e?e.identifier:`${e.chain}.${e.symbol}`,n=V(s);this.type=ot(n),this.chain=n.chain,this.ticker=n.ticker,this.symbol=n.symbol,this.address=n.address,this.isSynthetic=n.isSynthetic,this.isGasAsset=n.isGasAsset}get assetValue(){return`${this.getValue("string")} ${this.ticker}`}toString(e=!1){const s=this.isSynthetic?this.symbol.split("-")[0]:`${this.chain}.${this.ticker}`;return e?s:`${this.chain}.${this.symbol}`}eq({chain:e,symbol:s}){return this.chain===e&&this.symbol===s}static async fromString(e,s=0){return rt(e,s)}static fromStringSync(e,s=0){const{isSynthetic:n}=V(e),{decimal:a,identifier:o}=U(e),c=M(s,a);return o?new f({decimal:a,identifier:o,value:c}):n?new f({decimal:8,identifier:e,value:c}):void 0}static async fromIdentifier(e,s=0){return rt(e,s)}static fromIdentifierSync(e,s=0){const{decimal:n,identifier:a}=U(e),o=M(s,n);return new f({decimal:n,identifier:a,value:o})}static fromChainOrSignature(e,s=0){const{decimal:n,identifier:a}=at(e),o=M(s,n);return new f({value:o,decimal:n,identifier:a})}static async fromTCQuote(e,s=0){const n=await z(V(e)),a=this.shiftDecimals({value:s,from:i.BaseDecimal.THOR,to:n});return new f({value:a,identifier:e,decimal:n})}static fromTCQuoteStatic(e,s=0){const n=U(e),a=this.shiftDecimals({value:s,from:i.BaseDecimal.THOR,to:n.decimal});return new f({...n,value:a})}static async loadStaticAssets(){return new Promise(async(e,s)=>{try{const{ThorchainList:n,NativeList:a,...o}=await import("@swapkit/tokens");Y=[a,...Object.values(o)].reduce((u,{tokens:l})=>(l.forEach(({identifier:h,chain:g,...C})=>{const N="decimals"in C?C.decimals:i.BaseDecimal[g];u.set(h,{identifier:h,decimal:N})}),u),new Map),e({ok:!0})}catch(n){console.error(n),s({ok:!1,error:n,message:"Couldn't load static assets. Ensure you have installed @swapkit/tokens package"})}})}}const pe=r=>{const t=f.fromChainOrSignature(r);switch(r){case i.Chain.Bitcoin:case i.Chain.Litecoin:case i.Chain.BitcoinCash:return t.add(10001);case i.Chain.Dogecoin:return t.add(100000001);case i.Chain.Avalanche:case i.Chain.Ethereum:return t.add(10*10**9);case i.Chain.THORChain:case i.Chain.Maya:return t.add(0);default:return t.add(1)}},V=r=>{const t=r.slice(0,14).includes("/"),[e,s]=r.split(".").pop().split("/"),n=r.includes(".")&&!t?r:`${i.Chain.THORChain}.${s}`,[a,o]=n.split("."),[c,u]=(t?s:o).split("-");return{address:u==null?void 0:u.toLowerCase(),chain:a,isGasAsset:it({chain:a,symbol:o}),isSynthetic:t,symbol:(t?`${e}/`:"")+(u?`${c}-${(u==null?void 0:u.toLowerCase())??""}`:o),ticker:c}},fe={core_wallet_connection_not_found:10001,core_estimated_max_spendable_chain_not_supported:10002,core_extend_error:10003,core_inbound_data_not_found:10004,core_approve_asset_address_or_from_not_found:10005,core_chain_halted:10099,core_wallet_xdefi_not_installed:10101,core_wallet_evmwallet_not_installed:10102,core_wallet_walletconnect_not_installed:10103,core_wallet_keystore_not_installed:10104,core_wallet_ledger_not_installed:10105,core_wallet_trezor_not_installed:10106,core_wallet_keplr_not_installed:10107,core_wallet_okx_not_installed:10108,core_swap_invalid_params:10200,core_swap_route_not_complete:10201,core_swap_asset_not_recognized:10202,core_swap_contract_not_found:10203,core_swap_route_transaction_not_found:10204,core_swap_contract_not_supported:10205,core_swap_transaction_error:10206,core_swap_quote_mode_not_supported:10207,core_transaction_deposit_error:10301,core_transaction_create_liquidity_rune_error:10302,core_transaction_create_liquidity_asset_error:10303,core_transaction_create_liquidity_invalid_params:10304,core_transaction_add_liquidity_invalid_params:10305,core_transaction_add_liquidity_no_rune_address:10306,core_transaction_add_liquidity_rune_error:10307,core_transaction_add_liquidity_asset_error:10308,core_transaction_withdraw_error:10309,core_transaction_deposit_to_pool_error:10310,core_transaction_deposit_insufficient_funds_error:10311,core_transaction_deposit_gas_error:10312,core_transaction_deposit_server_error:10313,wallet_ledger_connection_error:20001,helpers_number_different_decimals:99101};class Q extends Error{constructor(t,e){console.error(e),super(t,{cause:{code:fe[t],message:t}}),Object.setPrototypeOf(this,Q.prototype)}}class D extends A{eq(t){return this.eqValue(t)}static fromBigInt(t,e){return new D({decimal:e,value:$({value:t,bigIntDecimal:e,decimal:e})})}}exports.AssetValue=f;exports.BigIntArithmetics=A;exports.RequestClient=gt;exports.SwapKitError=Q;exports.SwapKitNumber=D;exports.assetFromString=xt;exports.derivationPathToString=zt;exports.filterAssets=Nt;exports.formatBigIntToSafeValue=$;exports.gasFeeMultiplier=Pt;exports.getAssetType=ot;exports.getAsymmetricAssetShare=ut;exports.getAsymmetricAssetWithdrawAmount=jt;exports.getAsymmetricRuneShare=ct;exports.getAsymmetricRuneWithdrawAmount=Ht;exports.getCommonAssetInfo=at;exports.getDecimal=z;exports.getEstimatedPoolShare=Ft;exports.getLiquiditySlippage=Ut;exports.getMemoFor=Gt;exports.getMinAmountByChain=pe;exports.getSymmetricPoolShare=lt;exports.getSymmetricWithdraw=Lt;exports.getTHORNameCost=Kt;exports.isGasAsset=it;exports.validateTHORName=Yt;
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,13 +4,13 @@ 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
16
  const { result: e } = await Qt.post(At[s], {
@@ -28,17 +28,17 @@ const Tt = "0x313ce567", nt = async ({ chain: s, to: t }) => {
28
28
  });
29
29
  return parseInt(BigInt(e).toString());
30
30
  } catch (e) {
31
- return console.error(e), m[s];
31
+ return console.error(e), d[s];
32
32
  }
33
33
  }, vt = async (s) => {
34
34
  if (s === o.Ethereum)
35
- return m.ETH;
35
+ return d.ETH;
36
36
  const [, t] = s.split("-");
37
- 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;
38
38
  }, Rt = async (s) => {
39
39
  const [, t] = s.split("-");
40
- return t != null && t.startsWith("0x") ? nt({ chain: o.Avalanche, to: t.toLowerCase() }) : m.AVAX;
41
- }, 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 }) => {
42
42
  switch (s) {
43
43
  case o.Ethereum:
44
44
  return vt(t);
@@ -47,12 +47,12 @@ const Tt = "0x313ce567", nt = async ({ chain: s, to: t }) => {
47
47
  case o.BinanceSmartChain:
48
48
  return St(t);
49
49
  default:
50
- return m[s];
50
+ return d[s];
51
51
  }
52
52
  }, re = {
53
- [L.Average]: 1.2,
54
- [L.Fast]: 1.5,
55
- [L.Fastest]: 2
53
+ [U.Average]: 1.2,
54
+ [U.Fast]: 1.5,
55
+ [U.Fastest]: 2
56
56
  }, $t = ({ chain: s, symbol: t }) => {
57
57
  switch (s) {
58
58
  case o.Bitcoin:
@@ -86,13 +86,13 @@ const Tt = "0x313ce567", nt = async ({ chain: s, to: t }) => {
86
86
  case "ETH.vTHOR":
87
87
  return { identifier: "ETH.vTHOR-0x815c23eca83261b6ec689b60cc4a58b54bc24d8d", decimal: 18 };
88
88
  case o.Cosmos:
89
- return { identifier: "GAIA.ATOM", decimal: m[s] };
89
+ return { identifier: "GAIA.ATOM", decimal: d[s] };
90
90
  case o.THORChain:
91
- return { identifier: "THOR.RUNE", decimal: m[s] };
91
+ return { identifier: "THOR.RUNE", decimal: d[s] };
92
92
  case o.BinanceSmartChain:
93
- return { identifier: "BSC.BNB", decimal: m[s] };
93
+ return { identifier: "BSC.BNB", decimal: d[s] };
94
94
  case o.Maya:
95
- return { identifier: "MAYA.CACAO", decimal: m.MAYA };
95
+ return { identifier: "MAYA.CACAO", decimal: d.MAYA };
96
96
  case "MAYA.MAYA":
97
97
  return { identifier: "MAYA.MAYA", decimal: 4 };
98
98
  case o.Kujira:
@@ -106,7 +106,7 @@ const Tt = "0x313ce567", nt = async ({ chain: s, to: t }) => {
106
106
  case o.Polygon:
107
107
  case o.Bitcoin:
108
108
  case o.Ethereum:
109
- return { identifier: `${s}.${s}`, decimal: m[s] };
109
+ return { identifier: `${s}.${s}`, decimal: d[s] };
110
110
  }
111
111
  }, It = ({ chain: s, symbol: t }) => {
112
112
  if (t.includes("/"))
@@ -152,14 +152,14 @@ const Tt = "0x313ce567", nt = async ({ chain: s, to: t }) => {
152
152
  poolUnits: t,
153
153
  runeDepth: e
154
154
  }) => {
155
- 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);
156
156
  return a.mul(c.sub(u).add(l)).div(h);
157
- }, Vt = ({
157
+ }, Bt = ({
158
158
  liquidityUnits: s,
159
159
  poolUnits: t,
160
160
  assetDepth: e
161
161
  }) => {
162
- const r = d(s), n = d(t), i = d(e), a = r.mul(i), c = n.mul(n).mul(2), u = n.mul(r).mul(2), l = r.mul(r), h = a.mul(c.sub(u).add(l)), g = n.mul(n).mul(n);
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);
163
163
  return h.div(g);
164
164
  }, ie = ({
165
165
  percent: s,
@@ -171,14 +171,14 @@ const Tt = "0x313ce567", nt = async ({ chain: s, to: t }) => {
171
171
  assetDepth: t,
172
172
  liquidityUnits: e,
173
173
  poolUnits: r
174
- }) => 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 = ({
175
175
  liquidityUnits: s,
176
176
  poolUnits: t,
177
177
  runeDepth: e,
178
178
  assetDepth: r
179
179
  }) => ({
180
- assetAmount: d(r).mul(s).div(t),
181
- runeAmount: d(e).mul(s).div(t)
180
+ assetAmount: f(r).mul(s).div(t),
181
+ runeAmount: f(e).mul(s).div(t)
182
182
  }), ae = ({
183
183
  liquidityUnits: s,
184
184
  poolUnits: t,
@@ -186,7 +186,7 @@ const Tt = "0x313ce567", nt = async ({ chain: s, to: t }) => {
186
186
  assetDepth: r,
187
187
  percent: n
188
188
  }) => Object.fromEntries(
189
- 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(
190
190
  ([i, a]) => [i, a.mul(n)]
191
191
  )
192
192
  ), ce = ({
@@ -197,19 +197,21 @@ const Tt = "0x313ce567", nt = async ({ chain: s, to: t }) => {
197
197
  runeAmount: n,
198
198
  assetAmount: i
199
199
  }) => {
200
- const a = d(s), c = d(e), u = d(t), l = d(n), h = d(i), g = l.mul(c), T = h.mul(a), j = l.mul(h), ft = a.mul(c), pt = u.mul(g.add(T.add(j.mul(2)))), _t = g.add(T.add(ft.mul(2))), X = pt.div(_t), D = d(r).add(X);
201
- if (X.baseValueNumber === 0)
202
- 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");
203
203
  const gt = u.add(D);
204
- return D.div(gt).baseValueNumber;
204
+ return D.div(gt).getBaseValue("number");
205
205
  }, ue = ({
206
206
  runeAmount: s,
207
207
  assetAmount: t,
208
208
  runeDepth: e,
209
209
  assetDepth: r
210
210
  }) => {
211
- 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));
212
- 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"));
213
215
  }, Mt = ({
214
216
  symbol: s,
215
217
  ticker: t,
@@ -286,25 +288,25 @@ class ot extends Error {
286
288
  }), this.name = "TimeoutError", this.request = t;
287
289
  }
288
290
  }
289
- const B = (s) => s !== null && typeof s == "object", V = (...s) => {
291
+ const M = (s) => s !== null && typeof s == "object", V = (...s) => {
290
292
  for (const t of s)
291
- if ((!B(t) || Array.isArray(t)) && t !== void 0)
293
+ if ((!M(t) || Array.isArray(t)) && t !== void 0)
292
294
  throw new TypeError("The `options` argument must be an object");
293
- return K({}, ...s);
295
+ return Q({}, ...s);
294
296
  }, at = (s = {}, t = {}) => {
295
297
  const e = new globalThis.Headers(s), r = t instanceof globalThis.Headers, n = new globalThis.Headers(t);
296
298
  for (const [i, a] of n.entries())
297
299
  r && a === "undefined" || a === void 0 ? e.delete(i) : e.set(i, a);
298
300
  return e;
299
- }, K = (...s) => {
301
+ }, Q = (...s) => {
300
302
  let t = {}, e = {};
301
303
  for (const r of s)
302
304
  if (Array.isArray(r))
303
305
  Array.isArray(t) || (t = []), t = [...t, ...r];
304
- else if (B(r)) {
306
+ else if (M(r)) {
305
307
  for (let [n, i] of Object.entries(r))
306
- B(i) && n in t && (i = K(t[n], i)), t = { ...t, [n]: i };
307
- 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);
308
310
  }
309
311
  return t;
310
312
  }, kt = (() => {
@@ -324,7 +326,7 @@ const B = (s) => s !== null && typeof s == "object", V = (...s) => {
324
326
  formData: "multipart/form-data",
325
327
  arrayBuffer: "*/*",
326
328
  blob: "*/*"
327
- }, U = 2147483647, ut = Symbol("stop"), Ht = {
329
+ }, F = 2147483647, ut = Symbol("stop"), Ht = {
328
330
  json: !0,
329
331
  parseJson: !0,
330
332
  searchParams: !0,
@@ -351,9 +353,9 @@ const B = (s) => s !== null && typeof s == "object", V = (...s) => {
351
353
  window: !0,
352
354
  dispatcher: !0,
353
355
  duplex: !0
354
- }, 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 = {
355
357
  limit: 2,
356
- methods: Lt,
358
+ methods: Dt,
357
359
  statusCodes: Ut,
358
360
  afterStatusCodes: lt,
359
361
  maxRetryAfter: Number.POSITIVE_INFINITY,
@@ -402,11 +404,11 @@ const Yt = (s, t) => {
402
404
  !(r in jt) && !(r in Ht) && !(r in s) && (e[r] = t[r]);
403
405
  return e;
404
406
  };
405
- class q {
407
+ class x {
406
408
  static create(t, e) {
407
- const r = new q(t, e), n = async () => {
408
- if (typeof r._options.timeout == "number" && r._options.timeout > U)
409
- throw new RangeError(`The \`timeout\` option cannot be greater than ${U}`);
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}`);
410
412
  await Promise.resolve();
411
413
  let c = await r._fetch();
412
414
  for (const u of r._options.hooks.afterResponse) {
@@ -474,13 +476,13 @@ class q {
474
476
  credentials: this._input.credentials || "same-origin",
475
477
  ...e,
476
478
  headers: at(this._input.headers, e.headers),
477
- hooks: K({
479
+ hooks: Q({
478
480
  beforeRequest: [],
479
481
  beforeRetry: [],
480
482
  beforeError: [],
481
483
  afterResponse: []
482
484
  }, e.hooks),
483
- method: Dt(e.method ?? this._input.method),
485
+ method: Lt(e.method ?? this._input.method),
484
486
  // eslint-disable-next-line @typescript-eslint/prefer-nullish-coalescing
485
487
  prefixUrl: String(e.prefixUrl || ""),
486
488
  retry: Ft(e.retry),
@@ -534,7 +536,7 @@ class q {
534
536
  try {
535
537
  return await t();
536
538
  } catch (e) {
537
- const r = Math.min(this._calculateRetryDelay(e), U);
539
+ const r = Math.min(this._calculateRetryDelay(e), F);
538
540
  if (r !== 0 && this._retryCount > 0) {
539
541
  await Gt(r, { signal: this._options.signal });
540
542
  for (const n of this._options.hooks.beforeRetry)
@@ -598,12 +600,12 @@ class q {
598
600
  }
599
601
  }
600
602
  /*! MIT License © Sindre Sorhus */
601
- const G = (s) => {
602
- 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));
603
605
  for (const e of ct)
604
- t[e] = (r, n) => q.create(r, V(s, n, { method: e }));
605
- return t.create = (e) => G(V(e)), t.extend = (e) => G(V(s, e)), t.stop = ut, t;
606
- }, zt = G(), Jt = zt, Kt = typeof window < "u" ? {} : { referrer: "https://sk.thorswap.net", referer: "https://sk.thorswap.net" }, et = Jt.create({ headers: Kt }), Qt = {
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 = {
607
609
  get: (s, t) => et.get(s, t).json(),
608
610
  post: (s, t) => et.post(s, t).json()
609
611
  }, rt = Object.values(o), Xt = (s = "") => {
@@ -616,11 +618,11 @@ const G = (s) => {
616
618
  throw new Error(
617
619
  `Invalid identifier: ${s}. Expected format: <Chain>.<Ticker> or <Chain>.<Ticker>-<ContractAddress>`
618
620
  );
619
- }, C = 8, v = (s) => 10n ** BigInt(s), R = (s) => Math.log10(parseFloat(s.toString()));
620
- function x({
621
+ }, I = 8, R = (s) => 10n ** BigInt(s), S = (s) => Math.log10(parseFloat(s.toString()));
622
+ function P({
621
623
  value: s,
622
- bigIntDecimal: t = C,
623
- decimal: e = C
624
+ bigIntDecimal: t = I,
625
+ decimal: e = I
624
626
  }) {
625
627
  const r = s < 0n;
626
628
  let n = s.toString().substring(r ? 1 : 0);
@@ -633,27 +635,27 @@ function x({
633
635
  ""
634
636
  );
635
637
  }
636
- var w, S, P, ht, N, dt, E, Y, A, $, O, z;
637
- const H = class H {
638
+ var A, $, N, ht, H, dt, O, z, T, C, B, J;
639
+ const j = class j {
638
640
  constructor(t) {
639
- y(this, w);
640
- y(this, P);
641
- y(this, N);
642
- y(this, E);
643
- y(this, A);
644
- 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);
645
647
  p(this, "decimalMultiplier", 10n ** 8n);
646
648
  p(this, "bigIntValue", 0n);
647
649
  p(this, "decimal");
648
- const e = F(t);
649
- this.decimal = typeof t == "object" ? t.decimal : void 0, this.decimalMultiplier = v(
650
- Math.max(f(this, O, z).call(this, f(this, A, $).call(this, e)), this.decimal || 0)
651
- ), f(this, P, ht).call(this, e);
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);
652
654
  }
653
655
  static fromBigInt(t, e) {
654
- return new H({
656
+ return new j({
655
657
  decimal: e,
656
- value: x({ value: t, bigIntDecimal: e, decimal: e })
658
+ value: P({ value: t, bigIntDecimal: e, decimal: e })
657
659
  });
658
660
  }
659
661
  static shiftDecimals({
@@ -662,7 +664,7 @@ const H = class H {
662
664
  to: r
663
665
  }) {
664
666
  return this.fromBigInt(
665
- new H(t).bigIntValue * v(r) / v(e),
667
+ new j(t).bigIntValue * R(r) / R(e),
666
668
  r
667
669
  );
668
670
  }
@@ -688,16 +690,16 @@ const H = class H {
688
690
  return new this.constructor({ decimal: this.decimal, value: t, identifier: this.toString() });
689
691
  }
690
692
  add(...t) {
691
- return f(this, w, S).call(this, "add", ...t);
693
+ return m(this, A, $).call(this, "add", ...t);
692
694
  }
693
695
  sub(...t) {
694
- return f(this, w, S).call(this, "sub", ...t);
696
+ return m(this, A, $).call(this, "sub", ...t);
695
697
  }
696
698
  mul(...t) {
697
- return f(this, w, S).call(this, "mul", ...t);
699
+ return m(this, A, $).call(this, "mul", ...t);
698
700
  }
699
701
  div(...t) {
700
- return f(this, w, S).call(this, "div", ...t);
702
+ return m(this, A, $).call(this, "div", ...t);
701
703
  }
702
704
  gt(t) {
703
705
  return this.bigIntValue > this.getBigIntValue(t);
@@ -717,7 +719,7 @@ const H = class H {
717
719
  getValue(t) {
718
720
  const e = this.formatBigIntToSafeValue(
719
721
  this.bigIntValue,
720
- this.decimal || R(this.decimalMultiplier)
722
+ this.decimal || S(this.decimalMultiplier)
721
723
  );
722
724
  switch (t) {
723
725
  case "number":
@@ -729,7 +731,7 @@ const H = class H {
729
731
  }
730
732
  }
731
733
  getBaseValue(t) {
732
- 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;
733
735
  switch (t) {
734
736
  case "number":
735
737
  return Number(r);
@@ -742,13 +744,13 @@ const H = class H {
742
744
  getBigIntValue(t, e) {
743
745
  if (!e && typeof t == "object")
744
746
  return t.bigIntValue;
745
- const r = F(t), n = f(this, A, $).call(this, r);
746
- return n === "0" || n === "undefined" ? 0n : f(this, E, Y).call(this, n, e);
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);
747
749
  }
748
750
  formatBigIntToSafeValue(t, e) {
749
- const r = e || this.decimal || C, n = Math.max(
751
+ const r = e || this.decimal || I, n = Math.max(
750
752
  r,
751
- R(this.decimalMultiplier)
753
+ S(this.decimalMultiplier)
752
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;
753
755
  let h = u.slice(-n);
754
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(
@@ -757,14 +759,14 @@ const H = class H {
757
759
  )}.${h}`.replace(/\.?0*$/, "");
758
760
  }
759
761
  toSignificant(t = 6) {
760
- const [e, r] = this.getValue("string").split("."), n = e || "", i = r || "", a = parseInt(n) ? n.length + i.length : i.length;
761
- 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)
762
764
  return this.getValue("string");
763
765
  if (n.length >= t)
764
766
  return n.slice(0, t).padEnd(n.length, "0");
765
767
  if (parseInt(n))
766
768
  return `${n}.${i.slice(0, t - n.length)}`.padEnd(
767
- a - t,
769
+ t - n.length,
768
770
  "0"
769
771
  );
770
772
  const c = parseInt(i), u = `${c}`.slice(0, t);
@@ -791,8 +793,8 @@ const H = class H {
791
793
  return `${(e / a).toFixed(t)}${i}`;
792
794
  }
793
795
  };
794
- w = new WeakSet(), S = function(t, ...e) {
795
- 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(
796
798
  (c, u) => {
797
799
  const l = this.getBigIntValue(u, r);
798
800
  switch (t) {
@@ -813,53 +815,53 @@ w = new WeakSet(), S = function(t, ...e) {
813
815
  },
814
816
  //normalize is to precision multiplier base
815
817
  this.bigIntValue * n / this.decimalMultiplier
816
- ), a = x({
818
+ ), a = P({
817
819
  bigIntDecimal: r,
818
- decimal: Math.max(r, R(this.decimalMultiplier)),
820
+ decimal: Math.max(r, S(this.decimalMultiplier)),
819
821
  value: i
820
822
  });
821
823
  return new this.constructor({ decimal: this.decimal, value: a, identifier: this.toString() });
822
- }, P = new WeakSet(), ht = function(t) {
823
- const e = f(this, A, $).call(this, t) || "0";
824
- this.bigIntValue = f(this, E, Y).call(this, e);
825
- }, 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) {
826
828
  const e = t.map(
827
- (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))
828
830
  ).filter(Boolean);
829
- return Math.max(...e, C);
830
- }, E = new WeakSet(), Y = function(t, e) {
831
- 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(".");
832
834
  return BigInt(`${i}${a.padEnd(n, "0")}`);
833
- }, A = new WeakSet(), $ = function(t) {
835
+ }, T = new WeakSet(), C = function(t) {
834
836
  const r = `${typeof t == "number" ? Number(t).toLocaleString("fullwide", {
835
837
  useGrouping: !1,
836
838
  maximumFractionDigits: 20
837
- }) : F(t)}`.replaceAll(",", ".").split(".");
839
+ }) : W(t)}`.replaceAll(",", ".").split(".");
838
840
  return r.length > 1 ? `${r.slice(0, -1).join("")}.${r.at(-1)}` : r[0];
839
- }, O = new WeakSet(), z = function(t) {
841
+ }, B = new WeakSet(), J = function(t) {
840
842
  var r;
841
843
  const e = ((r = t.split(".")[1]) == null ? void 0 : r.length) || 0;
842
- return Math.max(e, C);
844
+ return Math.max(e, I);
843
845
  };
844
- let I = H;
845
- function F(s) {
846
+ let E = j;
847
+ function W(s) {
846
848
  return typeof s == "object" ? "getValue" in s ? s.getValue("string") : s.value : s;
847
849
  }
848
- const M = (s, t) => typeof s == "bigint" ? x({ value: s, bigIntDecimal: t, decimal: t }) : s;
849
- let J;
850
- const W = (s) => {
851
- if (!J)
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)
852
854
  throw new Error("Static assets not loaded, call await AssetValue.loadStaticAssets() first");
853
- return J.get(s.toUpperCase()) || { decimal: m.THOR, identifier: "" };
855
+ return K.get(s.toUpperCase()) || { decimal: d.THOR, identifier: "" };
854
856
  }, st = async (s, t = 0) => {
855
857
  Xt(s);
856
- const e = await it(k(s)), r = M(t, e);
858
+ const e = await it(q(s)), r = k(t, e);
857
859
  return new _({ decimal: e, value: r, identifier: s });
858
860
  };
859
- class _ extends I {
861
+ class _ extends E {
860
862
  constructor(e) {
861
863
  super(
862
- 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 }
863
865
  );
864
866
  p(this, "address");
865
867
  p(this, "chain");
@@ -868,7 +870,7 @@ class _ extends I {
868
870
  p(this, "symbol");
869
871
  p(this, "ticker");
870
872
  p(this, "type");
871
- 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);
872
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;
873
875
  }
874
876
  get assetValue() {
@@ -888,30 +890,30 @@ class _ extends I {
888
890
  return st(e, r);
889
891
  }
890
892
  static fromStringSync(e, r = 0) {
891
- const { isSynthetic: n } = k(e), { decimal: i, identifier: a } = W(
893
+ const { isSynthetic: n } = q(e), { decimal: i, identifier: a } = G(
892
894
  e
893
- ), c = M(r, i);
895
+ ), c = k(r, i);
894
896
  return a ? new _({ decimal: i, identifier: a, value: c }) : n ? new _({ decimal: 8, identifier: e, value: c }) : void 0;
895
897
  }
896
898
  static async fromIdentifier(e, r = 0) {
897
899
  return st(e, r);
898
900
  }
899
901
  static fromIdentifierSync(e, r = 0) {
900
- const { decimal: n, identifier: i } = W(e), a = M(r, n);
902
+ const { decimal: n, identifier: i } = G(e), a = k(r, n);
901
903
  return new _({ decimal: n, identifier: i, value: a });
902
904
  }
903
905
  static fromChainOrSignature(e, r = 0) {
904
- const { decimal: n, identifier: i } = Ct(e), a = M(r, n);
906
+ const { decimal: n, identifier: i } = Ct(e), a = k(r, n);
905
907
  return new _({ value: a, decimal: n, identifier: i });
906
908
  }
907
909
  static async fromTCQuote(e, r = 0) {
908
- 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 });
909
911
  return new _({ value: i, identifier: e, decimal: n });
910
912
  }
911
913
  static fromTCQuoteStatic(e, r = 0) {
912
- const n = W(e), i = this.shiftDecimals({
914
+ const n = G(e), i = this.shiftDecimals({
913
915
  value: r,
914
- from: m.THOR,
916
+ from: d.THOR,
915
917
  to: n.decimal
916
918
  });
917
919
  return new _({ ...n, value: i });
@@ -927,10 +929,10 @@ class _ extends I {
927
929
  NativeList: i,
928
930
  ...a
929
931
  } = await import("@swapkit/tokens");
930
- J = [i, ...Object.values(a)].reduce(
931
- (u, { tokens: l }) => (l.forEach(({ identifier: h, chain: g, ...T }) => {
932
- const j = "decimals" in T ? T.decimals : m[g];
933
- u.set(h, { identifier: h, decimal: j });
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 });
934
936
  }), u),
935
937
  /* @__PURE__ */ new Map()
936
938
  ), e({ ok: !0 });
@@ -963,7 +965,7 @@ const fe = (s) => {
963
965
  default:
964
966
  return t.add(1);
965
967
  }
966
- }, k = (s) => {
968
+ }, q = (s) => {
967
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("-");
968
970
  return {
969
971
  address: u == null ? void 0 : u.toLowerCase(),
@@ -1035,30 +1037,30 @@ class mt extends Error {
1035
1037
  console.error(e), super(t, { cause: { code: Zt[t], message: t } }), Object.setPrototypeOf(this, mt.prototype);
1036
1038
  }
1037
1039
  }
1038
- class Q extends I {
1040
+ class y extends E {
1039
1041
  eq(t) {
1040
1042
  return this.eqValue(t);
1041
1043
  }
1042
1044
  static fromBigInt(t, e) {
1043
- return new Q({
1045
+ return new y({
1044
1046
  decimal: e,
1045
- value: x({ value: t, bigIntDecimal: e, decimal: e })
1047
+ value: P({ value: t, bigIntDecimal: e, decimal: e })
1046
1048
  });
1047
1049
  }
1048
1050
  }
1049
1051
  export {
1050
1052
  _ as AssetValue,
1051
- I as BigIntArithmetics,
1053
+ E as BigIntArithmetics,
1052
1054
  Qt as RequestClient,
1053
1055
  mt as SwapKitError,
1054
- Q as SwapKitNumber,
1056
+ y as SwapKitNumber,
1055
1057
  se as assetFromString,
1056
1058
  me as derivationPathToString,
1057
1059
  ne as filterAssets,
1058
- x as formatBigIntToSafeValue,
1060
+ P as formatBigIntToSafeValue,
1059
1061
  re as gasFeeMultiplier,
1060
1062
  It as getAssetType,
1061
- Vt as getAsymmetricAssetShare,
1063
+ Bt as getAsymmetricAssetShare,
1062
1064
  oe as getAsymmetricAssetWithdrawAmount,
1063
1065
  Ot as getAsymmetricRuneShare,
1064
1066
  ie as getAsymmetricRuneWithdrawAmount,
@@ -1068,7 +1070,7 @@ export {
1068
1070
  ue as getLiquiditySlippage,
1069
1071
  le as getMemoFor,
1070
1072
  fe as getMinAmountByChain,
1071
- Bt as getSymmetricPoolShare,
1073
+ Vt as getSymmetricPoolShare,
1072
1074
  ae as getSymmetricWithdraw,
1073
1075
  he as getTHORNameCost,
1074
1076
  $t as isGasAsset,
package/package.json CHANGED
@@ -42,7 +42,7 @@
42
42
  "repository": "https://github.com/thorswap/SwapKit.git",
43
43
  "type": "module",
44
44
  "types": "./dist/index.d.ts",
45
- "version": "1.0.0-rc.16",
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",
@@ -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
  };
@@ -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
  }