@swapkit/helpers 1.0.0-rc.29 → 1.0.0-rc.30
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.cjs +1 -1
- package/dist/index.es.js +136 -136
- package/package.json +5 -5
- package/src/modules/bigIntArithmetics.ts +2 -2
package/dist/index.cjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";var we=Object.create;var N=Object.defineProperty;var Ae=Object.getOwnPropertyDescriptor;var Te=Object.getOwnPropertyNames;var ve=Object.getPrototypeOf,Se=Object.prototype.hasOwnProperty;var Re=(s,e,t)=>e in s?N(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 Te(e))!Se.call(s,n)&&n!==t&&N(s,n,{get:()=>e[n],enumerable:!(r=Ae(e,n))||r.enumerable});return s};var Ie=(s,e,t)=>(t=s!=null?we(ve(s)):{},$e(e||!s||!s.__esModule?N(t,"default",{value:s,enumerable:!0}):t,s));var m=(s,e,t)=>(Re(s,typeof e!="symbol"?e+"":e,t),t),Be=(s,e,t)=>{if(!e.has(s))throw TypeError("Cannot "+t)};var A=(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 p=(s,e,t)=>(Be(s,e,"access private method"),t);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const i=require("@swapkit/types"),Ee="0x313ce567",re=async({chain:s,to:e})=>{try{const{result:t}=await fe.post(i.ChainToRPC[s],{headers:{accept:"*/*","content-type":"application/json","cache-control":"no-cache"},body:JSON.stringify({id:44,jsonrpc:"2.0",method:"eth_call",params:[{to:e.toLowerCase(),data:Ee},"latest"]})});return parseInt(BigInt(t).toString())}catch(t){return console.error(t),i.BaseDecimal[s]}},Me=async s=>{if(s===i.Chain.Ethereum)return i.BaseDecimal.ETH;const[,e]=s.split("-");return e!=null&&e.startsWith("0x")?re({chain:i.Chain.Ethereum,to:e}):i.BaseDecimal.ETH},Oe=async s=>{const[,e]=s.split("-");return e!=null&&e.startsWith("0x")?re({chain:i.Chain.Avalanche,to:e.toLowerCase()}):i.BaseDecimal.AVAX},Ve=async s=>(s===i.Chain.BinanceSmartChain,i.BaseDecimal.BSC),ne=async({chain:s,symbol:e})=>{switch(s){case i.Chain.Ethereum:return Me(e);case i.Chain.Avalanche:return Oe(e);case i.Chain.BinanceSmartChain:return Ve(e);default:return i.BaseDecimal[s]}},qe={[i.FeeOption.Average]:1.2,[i.FeeOption.Fast]:1.5,[i.FeeOption.Fastest]:2},W=({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"}},ie=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]}}},ae=({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"}},Pe=s=>{var c;const[e,...t]=s.split("."),r=s.includes("/"),n=t.join("."),a=(c=n==null?void 0:n.split("-"))==null?void 0:c[0];return{chain:e,symbol:n,ticker:a,synth:r}},ke=new RegExp(/(.)\1{6}|\.ORG|\.NET|\.FINANCE|\.COM|WWW|HTTP|\\\\|\/\/|[\s$%:[\]]/,"gmi"),xe=s=>{const[e,t]=s.split(".");if(!i.EVMChainList.includes(e))return!0;const[,r]=t.split("-");return W({chain:e,symbol:t})||!!r},Ne=s=>s.filter(e=>{const t=`${e.chain}.${e.symbol}`;return!ke.test(t)&&xe(t)&&e.value!=="0"}),oe=({liquidityUnits:s,poolUnits:e,runeDepth:t})=>{const r=d(s),n=d(e),a=d(t),c=r.mul(a),o=n.mul(n).mul(2),u=n.mul(r).mul(2),l=r.mul(r),h=n.mul(n).mul(n);return c.mul(o.sub(u).add(l)).div(h)},ce=({liquidityUnits:s,poolUnits:e,assetDepth:t})=>{const r=d(s),n=d(e),a=d(t),c=r.mul(a),o=n.mul(n).mul(2),u=n.mul(r).mul(2),l=r.mul(r),h=c.mul(o.sub(u).add(l)),g=n.mul(n).mul(n);return h.div(g)},De=({percent:s,runeDepth:e,liquidityUnits:t,poolUnits:r})=>oe({runeDepth:e,liquidityUnits:t,poolUnits:r}).mul(s),He=({percent:s,assetDepth:e,liquidityUnits:t,poolUnits:r})=>ce({assetDepth:e,liquidityUnits:t,poolUnits:r}).mul(s),d=s=>f.fromBigInt(BigInt(s),i.BaseDecimal.THOR),ue=({liquidityUnits:s,poolUnits:e,runeDepth:t,assetDepth:r})=>({assetAmount:d(r).mul(s).div(e),runeAmount:d(t).mul(s).div(e)}),je=({liquidityUnits:s,poolUnits:e,runeDepth:t,assetDepth:r,percent:n})=>Object.fromEntries(Object.entries(ue({liquidityUnits:s,poolUnits:e,runeDepth:t,assetDepth:r})).map(([a,c])=>[a,c.mul(n)])),Le=({runeDepth:s,poolUnits:e,assetDepth:t,liquidityUnits:r,runeAmount:n,assetAmount:a})=>{const c=new f({value:s,decimal:8}),o=new f({value:t,decimal:8}),u=new f({value:e,decimal:8}),l=new f({value:n,decimal:8}),h=new f({value:a,decimal:8}),g=l.mul(o),b=h.mul(c),k=l.mul(h),_e=c.mul(o),ye=u.mul(g.add(b.add(k.mul(2)))),be=g.add(b.add(_e.mul(2))),z=ye.div(be),x=d(r).add(z);if(z.getBaseValue("number")===0)return x.div(u).getBaseValue("number");const Ce=u.add(x);return x.div(Ce).getBaseValue("number")},Fe=({runeAmount:s,assetAmount:e,runeDepth:t,assetDepth:r})=>{if(s==="0"||e==="0"||t==="0"||r==="0")return 0;const n=d(t),a=d(r),c=d(e),o=d(s),u=c.mul(n).sub(a.mul(o)),l=a.mul(o).add(n.mul(a));return Math.abs(u.div(l).getBaseValue("number"))},Ue=({symbol:s,ticker:e,chain:t})=>t==="ETH"&&e!=="ETH"?`${e}-${s.slice(-3)}`:s,We=(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:c,singleSide:o}=e,u=!o&&c?`:${c}`:"",l=Ue({chain:t,symbol:n,ticker:r});return`${s}:${t}${o?"/":"."}${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""}},Ge=s=>{if(s<0)throw new Error("Invalid number of year");return 10+s},Ke=s=>{if(s.length>30)return!1;const e=/^[a-zA-Z0-9+_-]+$/g;return!!s.match(e)},Ye=([s,e,t,r,n])=>`${s}'/${e}'/${t}'/${r}${typeof n!="number"?"":`/${n}`}`;class J extends Error{constructor(e,t,r){const n=e.status||e.status===0?e.status:"",a=e.statusText||"",c=`${n} ${a}`.trim(),o=c?`status code ${c}`:"an unknown error";super(`Request failed with ${o}`),Object.defineProperty(this,"response",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"request",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"options",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.name="HTTPError",this.response=e,this.request=t,this.options=r}}class le 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",B=(...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 G({},...s)},he=(s={},e={})=>{const t=new globalThis.Headers(s),r=e instanceof globalThis.Headers,n=new globalThis.Headers(e);for(const[a,c]of n.entries())r&&c==="undefined"||c===void 0?t.delete(a):t.set(a,c);return t},G=(...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=G(e[n],a)),e={...e,[n]:a};M(r.headers)&&(t=he(t,r.headers),e.headers=t)}return e},ze=(()=>{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})(),Je=typeof globalThis.AbortController=="function",Qe=typeof globalThis.ReadableStream=="function",Xe=typeof globalThis.FormData=="function",de=["get","post","put","patch","head","delete"],Ze={json:"application/json",text:"text/*",formData:"multipart/form-data",arrayBuffer:"*/*",blob:"*/*"},D=2147483647,me=Symbol("stop"),et={json:!0,parseJson:!0,searchParams:!0,prefixUrl:!0,retry:!0,timeout:!0,hooks:!0,throwHttpErrors:!0,onDownloadProgress:!0,fetch:!0},tt={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=>de.includes(s)?s.toUpperCase():s,rt=["get","put","head","delete","options","trace"],nt=[408,413,429,500,502,503,504],pe=[413,429,503],Q={limit:2,methods:rt,statusCodes:nt,afterStatusCodes:pe,maxRetryAfter:Number.POSITIVE_INFINITY,backoffLimit:Number.POSITIVE_INFINITY,delay:s=>.3*2**(s-1)*1e3},it=(s={})=>{if(typeof s=="number")return{...Q,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{...Q,...s,afterStatusCodes:pe}};async function at(s,e,t,r){return new Promise((n,a)=>{const c=setTimeout(()=>{t&&t.abort(),a(new le(s))},r.timeout);r.fetch(s,e).then(n).catch(a).then(()=>{clearTimeout(c)})})}async function ot(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 ct=(s,e)=>{const t={};for(const r in e)!(r in tt)&&!(r in et)&&!(r in s)&&(t[r]=e[r]);return t};class q{static create(e,t){const r=new q(e,t),n=async()=>{if(typeof r._options.timeout=="number"&&r._options.timeout>D)throw new RangeError(`The \`timeout\` option cannot be greater than ${D}`);await Promise.resolve();let o=await r._fetch();for(const u of r._options.hooks.afterResponse){const l=await u(r.request,r._options,r._decorateResponse(o.clone()));l instanceof globalThis.Response&&(o=l)}if(r._decorateResponse(o),!o.ok&&r._options.throwHttpErrors){let u=new J(o,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(!Qe)throw new Error("Streams are not supported in your environment. `ReadableStream` is missing.");return r._stream(o.clone(),r._options.onDownloadProgress)}return o},c=r._options.retry.methods.includes(r.request.method.toLowerCase())?r._retry(n):n();for(const[o,u]of Object.entries(Ze))c[o]=async()=>{r.request.headers.set("accept",r.request.headers.get("accept")||u);const h=(await c).clone();if(o==="json"){if(h.status===204||(await h.clone().arrayBuffer()).byteLength===0)return"";if(t.parseJson)return t.parseJson(await h.text())}return h[o]()};return c}constructor(e,t={}){if(Object.defineProperty(this,"request",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"abortController",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_retryCount",{enumerable:!0,configurable:!0,writable:!0,value:0}),Object.defineProperty(this,"_input",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_options",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this._input=e,this._options={credentials:this._input.credentials||"same-origin",...t,headers:he(this._input.headers,t.headers),hooks:G({beforeRequest:[],beforeRetry:[],beforeError:[],afterResponse:[]},t.hooks),method:st(t.method??this._input.method),prefixUrl:String(t.prefixUrl||""),retry:it(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(Je){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(ze&&(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);(Xe&&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 le)){if(e instanceof J){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),D);if(r!==0&&this._retryCount>0){await ot(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})===me)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=ct(this.request,this._options);return this._options.timeout===!1?this._options.fetch(this.request.clone(),e):at(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 c=e.body.getReader();t&&t({percent:0,transferredBytes:0,totalBytes:r},new Uint8Array);async function o(){const{done:u,value:l}=await c.read();if(u){a.close();return}if(t){n+=l.byteLength;const h=r===0?0:n/r;t({percent:h,transferredBytes:n,totalBytes:r},l)}a.enqueue(l),await o()}await o()}}),{status:e.status,statusText:e.statusText,headers:e.headers})}}/*! MIT License © Sindre Sorhus */const H=s=>{const e=(t,r)=>q.create(t,B(s,r));for(const t of de)e[t]=(r,n)=>q.create(r,B(s,n,{method:t}));return e.create=t=>H(B(t)),e.extend=t=>H(B(s,t)),e.stop=me,e},ut=H(),lt=ut,ht=typeof window<"u"?{}:{referrer:"https://sk.thorswap.net",referer:"https://sk.thorswap.net"},X=lt.create({headers:ht}),fe={get:(s,e)=>X.get(s,e).json(),post:(s,e)=>X.post(s,e).json()},Z=Object.values(i.Chain),dt=(s="")=>{const e=s.toUpperCase(),[t]=e.split(".");if(Z.includes(t))return!0;const[r]=e.split("/");if(Z.includes(r))return!0;throw new Error(`Invalid identifier: ${s}. Expected format: <Chain>.<Ticker> or <Chain>.<Ticker>-<ContractAddress>`)},S=8,C=s=>10n**BigInt(s),T=s=>Math.log10(parseFloat(s.toString()));function R({value:s,bigIntDecimal:e=S,decimal:t=S}){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 c=n.length-t;let o=n.slice(-t);return parseInt(o[e])>=5?o=`${o.substring(0,e-1)}${(parseInt(o[e-1])+1).toString()}`:o=o.substring(0,e),`${r?"-":""}${n.slice(0,c)}.${o}`.replace(/\.?0*$/,"")}var y,v,$,j,P,ge,I,L;const Y=class Y{constructor(e){A(this,y);A(this,$);A(this,P);A(this,I);m(this,"decimalMultiplier",10n**8n);m(this,"bigIntValue",0n);m(this,"decimal");const t=O(e);this.decimal=typeof e=="object"?e.decimal:void 0,this.decimalMultiplier=C(Math.max(ee(E(t)),this.decimal||0)),p(this,$,j).call(this,t)}static fromBigInt(e,t){return new Y({decimal:t,value:R({value:e,bigIntDecimal:t,decimal:t})})}static shiftDecimals({value:e,from:t,to:r}){return this.fromBigInt(e.getBaseValue("bigint")*C(r)/C(t),r)}set(e){return p(this,$,j).call(this,O(e)),this}add(...e){return p(this,y,v).call(this,"add",...e)}sub(...e){return p(this,y,v).call(this,"sub",...e)}mul(...e){return p(this,y,v).call(this,"mul",...e)}div(...e){return p(this,y,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||T(this.decimalMultiplier));switch(e){case"number":return Number(t);case"string":return t;default:return this.bigIntValue*BigInt(this.decimal||8n)/this.decimalMultiplier}}getBaseValue(e){const t=this.decimalMultiplier/C(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=O(e),n=E(r);return n==="0"||n==="undefined"?0n:p(this,I,L).call(this,n,t)}formatBigIntToSafeValue(e,t){const r=t||this.decimal||S,n=Math.max(r,T(this.decimalMultiplier)),a=e<0n,c=e.toString().substring(a?1:0),o=n-(c.length-1),u=o>0?"0".repeat(o)+c:c,l=u.length-n;let h=u.slice(-n);return parseInt(h[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 o=parseInt(a),u=`${o}`.slice(0,e);return`0.${u.padStart(a.length-`${o}`.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 c=parseInt(a),o=`${c}`.slice(0,e);return`0.${o.padStart(a.length-`${c}`.length+o.length,"0")}`}toAbbreviation(e=2){const t=this.getValue("number"),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 c=10**(n*3);return`${(t/c).toFixed(e)}${a}`}toCurrency(e="$",{currencyPosition:t="start",decimal:r=2,decimalSeparator:n=".",thousandSeparator:a=","}={}){const c=this.getValue("number"),[o,u=""]=c.toFixed(6).split("."),l=o.replace(/\B(?=(\d{3})+(?!\d))/g,a),h=!o&&!u?"0.00":o==="0"?`${parseFloat(`0.${u}`)}`.replace(".",n):`${l}${parseInt(u)?`${n}${u.slice(0,r)}`:""}`;return`${t==="start"?e:""}${h}${t==="end"?e:""}`}};y=new WeakSet,v=function(e,...t){const r=p(this,P,ge).call(this,this,...t),n=C(r),a=t.reduce((o,u)=>{const l=this.getBigIntValue(u,r);switch(e){case"add":return o+l;case"sub":return o-l;case"mul":return o*l/n;case"div":{if(l===0n)throw new RangeError("Division by zero");return o*n/l}default:return o}},this.bigIntValue*n/this.decimalMultiplier),c=R({bigIntDecimal:r,decimal:Math.max(r,T(this.decimalMultiplier)),value:a});return new this.constructor({decimal:this.decimal,value:c,identifier:this.toString()})},$=new WeakSet,j=function(e){const t=E(e)||"0";this.bigIntValue=p(this,I,L).call(this,t)},P=new WeakSet,ge=function(...e){const t=e.map(r=>typeof r=="object"?r.decimal||T(r.decimalMultiplier):ee(E(r))).filter(Boolean);return Math.max(...t,S)},I=new WeakSet,L=function(e,t){const r=t?C(t):this.decimalMultiplier,n=T(r),[a="",c=""]=e.split(".");return BigInt(`${a}${c.padEnd(n,"0")}`)};let w=Y;const mt=Intl.NumberFormat("fullwide",{useGrouping:!1,maximumFractionDigits:20});function E(s){const t=`${typeof s=="number"?mt.format(s):O(s)}`.replaceAll(",",".").split(".");return t.length>1?`${t.slice(0,-1).join("")}.${t.at(-1)}`:t[0]}function ee(s){var t;const e=((t=s.split(".")[1])==null?void 0:t.length)||0;return Math.max(e,S)}function O(s){return typeof s=="object"?"getValue"in s?s.getValue("string"):s.value:s}const V=(s,e)=>typeof s=="bigint"?R({value:s,bigIntDecimal:e,decimal:e}):s;let F;const te=s=>{if(!F)throw new Error("Static assets not loaded, call await AssetValue.loadStaticAssets() first");return F.get(s.toUpperCase())||{decimal:i.BaseDecimal.THOR,identifier:""}},se=async(s,e=0)=>{dt(s);const t=await ne(U(s)),r=V(e,t);return new _({decimal:t,value:r,identifier:s})};class _ extends w{constructor(t){const r="identifier"in t?t.identifier:`${t.chain}.${t.symbol}`;super(t.value instanceof w?t.value:{decimal:t.decimal,value:t.value});m(this,"address");m(this,"isSynthetic",!1);m(this,"isGasAsset",!1);m(this,"chain");m(this,"symbol");m(this,"ticker");m(this,"type");const n=U(r);this.type=ae(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}toString(t=!1){const r=this.isSynthetic?this.symbol.split("-")[0]: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}=U(t),{decimal:a,identifier:c}=te(t),o=V(r,a);return c?new _({decimal:a,identifier:c,value:o}):n?new _({decimal:8,identifier:t,value:o}):void 0}static async fromIdentifier(t,r=0){return se(t,r)}static fromIdentifierSync(t,r=0){const{decimal:n,identifier:a}=te(t),c=V(r,n);return new _({decimal:n,identifier:a,value:c})}static fromChainOrSignature(t,r=0){const{decimal:n,identifier:a}=ie(t),c=V(r,n);return new _({value:c,decimal:n,identifier:a})}static async loadStaticAssets(){return new Promise(async(t,r)=>{try{const{ThorchainList:n,NativeList:a,...c}=await import("@swapkit/tokens");F=[a,...Object.values(c)].reduce((u,{tokens:l})=>(l.forEach(({identifier:h,chain:g,...b})=>{const k="decimals"in b?b.decimals:i.BaseDecimal[g];u.set(h,{identifier:h,decimal:k})}),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=_.fromChainOrSignature(s);switch(s){case i.Chain.Bitcoin:case i.Chain.Litecoin:case i.Chain.BitcoinCash:return e.set(10001e-8);case i.Chain.Dogecoin:return e.set(1.00000001);case i.Chain.Avalanche:case i.Chain.Ethereum:return e.set(1e-8);case i.Chain.THORChain:case i.Chain.Maya:return e.set(0);default:return e.set(1e-8)}},U=s=>{const e=s.slice(0,14).includes("/"),[t,r]=s.split(".").pop().split("/"),n=s.includes(".")&&!e?s:`${i.Chain.THORChain}.${r}`,[a,c]=n.split("."),[o,u]=(e?r:c).split("-");return{address:u==null?void 0:u.toLowerCase(),chain:a,isGasAsset:W({chain:a,symbol:c}),isSynthetic:e,symbol:(e?`${t}/`:"")+(u?`${o}-${(u==null?void 0:u.toLowerCase())??""}`:c),ticker:o}},ft={core_wallet_connection_not_found:10001,core_estimated_max_spendable_chain_not_supported:10002,core_extend_error:10003,core_inbound_data_not_found:10004,core_approve_asset_address_or_from_not_found:10005,core_chain_halted:10099,core_wallet_xdefi_not_installed:10101,core_wallet_evmwallet_not_installed:10102,core_wallet_walletconnect_not_installed:10103,core_wallet_keystore_not_installed:10104,core_wallet_ledger_not_installed:10105,core_wallet_trezor_not_installed:10106,core_wallet_keplr_not_installed:10107,core_wallet_okx_not_installed:10108,core_swap_invalid_params:10200,core_swap_route_not_complete:10201,core_swap_asset_not_recognized:10202,core_swap_contract_not_found:10203,core_swap_route_transaction_not_found:10204,core_swap_contract_not_supported:10205,core_swap_transaction_error:10206,core_swap_quote_mode_not_supported:10207,core_transaction_deposit_error:10301,core_transaction_create_liquidity_rune_error:10302,core_transaction_create_liquidity_asset_error:10303,core_transaction_create_liquidity_invalid_params:10304,core_transaction_add_liquidity_invalid_params:10305,core_transaction_add_liquidity_no_rune_address:10306,core_transaction_add_liquidity_rune_error:10307,core_transaction_add_liquidity_asset_error:10308,core_transaction_withdraw_error:10309,core_transaction_deposit_to_pool_error:10310,core_transaction_deposit_insufficient_funds_error:10311,core_transaction_deposit_gas_error:10312,core_transaction_deposit_server_error:10313,wallet_ledger_connection_error:20001,helpers_number_different_decimals:99101};class K extends Error{constructor(e,t){console.error(t),super(e,{cause:{code:ft[e],message:e}}),Object.setPrototypeOf(this,K.prototype)}}class f extends w{eq(e){return this.eqValue(e)}static fromBigInt(e,t){return new f({decimal:t,value:R({value:e,bigIntDecimal:t,decimal:t})})}}exports.AssetValue=_;exports.BigIntArithmetics=w;exports.RequestClient=fe;exports.SwapKitError=K;exports.SwapKitNumber=f;exports.assetFromString=Pe;exports.derivationPathToString=Ye;exports.filterAssets=Ne;exports.formatBigIntToSafeValue=R;exports.gasFeeMultiplier=qe;exports.getAssetType=ae;exports.getAsymmetricAssetShare=ce;exports.getAsymmetricAssetWithdrawAmount=He;exports.getAsymmetricRuneShare=oe;exports.getAsymmetricRuneWithdrawAmount=De;exports.getCommonAssetInfo=ie;exports.getDecimal=ne;exports.getEstimatedPoolShare=Le;exports.getLiquiditySlippage=Fe;exports.getMemoFor=We;exports.getMinAmountByChain=pt;exports.getSymmetricPoolShare=ue;exports.getSymmetricWithdraw=je;exports.getTHORNameCost=Ge;exports.isGasAsset=W;exports.validateTHORName=Ke;
|
|
1
|
+
"use strict";var we=Object.create;var x=Object.defineProperty;var Ae=Object.getOwnPropertyDescriptor;var Te=Object.getOwnPropertyNames;var ve=Object.getPrototypeOf,Se=Object.prototype.hasOwnProperty;var Re=(s,e,t)=>e in s?x(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 Te(e))!Se.call(s,n)&&n!==t&&x(s,n,{get:()=>e[n],enumerable:!(r=Ae(e,n))||r.enumerable});return s};var Ie=(s,e,t)=>(t=s!=null?we(ve(s)):{},$e(e||!s||!s.__esModule?x(t,"default",{value:s,enumerable:!0}):t,s));var m=(s,e,t)=>(Re(s,typeof e!="symbol"?e+"":e,t),t),Be=(s,e,t)=>{if(!e.has(s))throw TypeError("Cannot "+t)};var A=(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 p=(s,e,t)=>(Be(s,e,"access private method"),t);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const i=require("@swapkit/types"),Ee="0x313ce567",se=async({chain:s,to:e})=>{try{const{result:t}=await pe.post(i.ChainToRPC[s],{headers:{accept:"*/*","content-type":"application/json","cache-control":"no-cache"},body:JSON.stringify({id:44,jsonrpc:"2.0",method:"eth_call",params:[{to:e.toLowerCase(),data:Ee},"latest"]})});return parseInt(BigInt(t).toString())}catch(t){return console.error(t),i.BaseDecimal[s]}},Me=async s=>{if(s===i.Chain.Ethereum)return i.BaseDecimal.ETH;const[,e]=s.split("-");return e!=null&&e.startsWith("0x")?se({chain:i.Chain.Ethereum,to:e}):i.BaseDecimal.ETH},Oe=async s=>{const[,e]=s.split("-");return e!=null&&e.startsWith("0x")?se({chain:i.Chain.Avalanche,to:e.toLowerCase()}):i.BaseDecimal.AVAX},Ve=async s=>(s===i.Chain.BinanceSmartChain,i.BaseDecimal.BSC),re=async({chain:s,symbol:e})=>{switch(s){case i.Chain.Ethereum:return Me(e);case i.Chain.Avalanche:return Oe(e);case i.Chain.BinanceSmartChain:return Ve(e);default:return i.BaseDecimal[s]}},qe={[i.FeeOption.Average]:1.2,[i.FeeOption.Fast]:1.5,[i.FeeOption.Fastest]:2},U=({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"}},ne=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]}}},ie=({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"}},Pe=s=>{var c;const[e,...t]=s.split("."),r=s.includes("/"),n=t.join("."),a=(c=n==null?void 0:n.split("-"))==null?void 0:c[0];return{chain:e,symbol:n,ticker:a,synth:r}},ke=new RegExp(/(.)\1{6}|\.ORG|\.NET|\.FINANCE|\.COM|WWW|HTTP|\\\\|\/\/|[\s$%:[\]]/,"gmi"),xe=s=>{const[e,t]=s.split(".");if(!i.EVMChainList.includes(e))return!0;const[,r]=t.split("-");return U({chain:e,symbol:t})||!!r},Ne=s=>s.filter(e=>{const t=`${e.chain}.${e.symbol}`;return!ke.test(t)&&xe(t)&&e.value!=="0"}),ae=({liquidityUnits:s,poolUnits:e,runeDepth:t})=>{const r=d(s),n=d(e),a=d(t),c=r.mul(a),o=n.mul(n).mul(2),u=n.mul(r).mul(2),l=r.mul(r),h=n.mul(n).mul(n);return c.mul(o.sub(u).add(l)).div(h)},oe=({liquidityUnits:s,poolUnits:e,assetDepth:t})=>{const r=d(s),n=d(e),a=d(t),c=r.mul(a),o=n.mul(n).mul(2),u=n.mul(r).mul(2),l=r.mul(r),h=c.mul(o.sub(u).add(l)),g=n.mul(n).mul(n);return h.div(g)},De=({percent:s,runeDepth:e,liquidityUnits:t,poolUnits:r})=>ae({runeDepth:e,liquidityUnits:t,poolUnits:r}).mul(s),He=({percent:s,assetDepth:e,liquidityUnits:t,poolUnits:r})=>oe({assetDepth:e,liquidityUnits:t,poolUnits:r}).mul(s),d=s=>f.fromBigInt(BigInt(s),i.BaseDecimal.THOR),ce=({liquidityUnits:s,poolUnits:e,runeDepth:t,assetDepth:r})=>({assetAmount:d(r).mul(s).div(e),runeAmount:d(t).mul(s).div(e)}),je=({liquidityUnits:s,poolUnits:e,runeDepth:t,assetDepth:r,percent:n})=>Object.fromEntries(Object.entries(ce({liquidityUnits:s,poolUnits:e,runeDepth:t,assetDepth:r})).map(([a,c])=>[a,c.mul(n)])),Le=({runeDepth:s,poolUnits:e,assetDepth:t,liquidityUnits:r,runeAmount:n,assetAmount:a})=>{const c=new f({value:s,decimal:8}),o=new f({value:t,decimal:8}),u=new f({value:e,decimal:8}),l=new f({value:n,decimal:8}),h=new f({value:a,decimal:8}),g=l.mul(o),b=h.mul(c),P=l.mul(h),_e=c.mul(o),ye=u.mul(g.add(b.add(P.mul(2)))),be=g.add(b.add(_e.mul(2))),Y=ye.div(be),k=d(r).add(Y);if(Y.getBaseValue("number")===0)return k.div(u).getBaseValue("number");const Ce=u.add(k);return k.div(Ce).getBaseValue("number")},Fe=({runeAmount:s,assetAmount:e,runeDepth:t,assetDepth:r})=>{if(s==="0"||e==="0"||t==="0"||r==="0")return 0;const n=d(t),a=d(r),c=d(e),o=d(s),u=c.mul(n).sub(a.mul(o)),l=a.mul(o).add(n.mul(a));return Math.abs(u.div(l).getBaseValue("number"))},Ue=({symbol:s,ticker:e,chain:t})=>t==="ETH"&&e!=="ETH"?`${e}-${s.slice(-3)}`:s,We=(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:c,singleSide:o}=e,u=!o&&c?`:${c}`:"",l=Ue({chain:t,symbol:n,ticker:r});return`${s}:${t}${o?"/":"."}${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""}},Ge=s=>{if(s<0)throw new Error("Invalid number of year");return 10+s},Ke=s=>{if(s.length>30)return!1;const e=/^[a-zA-Z0-9+_-]+$/g;return!!s.match(e)},Ye=([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||"",c=`${n} ${a}`.trim(),o=c?`status code ${c}`:"an unknown error";super(`Request failed with ${o}`),Object.defineProperty(this,"response",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"request",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"options",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.name="HTTPError",this.response=e,this.request=t,this.options=r}}class ue 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 E=s=>s!==null&&typeof s=="object",I=(...s)=>{for(const e of s)if((!E(e)||Array.isArray(e))&&e!==void 0)throw new TypeError("The `options` argument must be an object");return W({},...s)},le=(s={},e={})=>{const t=new globalThis.Headers(s),r=e instanceof globalThis.Headers,n=new globalThis.Headers(e);for(const[a,c]of n.entries())r&&c==="undefined"||c===void 0?t.delete(a):t.set(a,c);return t},W=(...s)=>{let e={},t={};for(const r of s)if(Array.isArray(r))Array.isArray(e)||(e=[]),e=[...e,...r];else if(E(r)){for(let[n,a]of Object.entries(r))E(a)&&n in e&&(a=W(e[n],a)),e={...e,[n]:a};E(r.headers)&&(t=le(t,r.headers),e.headers=t)}return e},ze=(()=>{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})(),Je=typeof globalThis.AbortController=="function",Qe=typeof globalThis.ReadableStream=="function",Xe=typeof globalThis.FormData=="function",he=["get","post","put","patch","head","delete"],Ze={json:"application/json",text:"text/*",formData:"multipart/form-data",arrayBuffer:"*/*",blob:"*/*"},N=2147483647,de=Symbol("stop"),et={json:!0,parseJson:!0,searchParams:!0,prefixUrl:!0,retry:!0,timeout:!0,hooks:!0,throwHttpErrors:!0,onDownloadProgress:!0,fetch:!0},tt={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=>he.includes(s)?s.toUpperCase():s,rt=["get","put","head","delete","options","trace"],nt=[408,413,429,500,502,503,504],me=[413,429,503],J={limit:2,methods:rt,statusCodes:nt,afterStatusCodes:me,maxRetryAfter:Number.POSITIVE_INFINITY,backoffLimit:Number.POSITIVE_INFINITY,delay:s=>.3*2**(s-1)*1e3},it=(s={})=>{if(typeof s=="number")return{...J,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{...J,...s,afterStatusCodes:me}};async function at(s,e,t,r){return new Promise((n,a)=>{const c=setTimeout(()=>{t&&t.abort(),a(new ue(s))},r.timeout);r.fetch(s,e).then(n).catch(a).then(()=>{clearTimeout(c)})})}async function ot(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 ct=(s,e)=>{const t={};for(const r in e)!(r in tt)&&!(r in et)&&!(r in s)&&(t[r]=e[r]);return t};class O{static create(e,t){const r=new O(e,t),n=async()=>{if(typeof r._options.timeout=="number"&&r._options.timeout>N)throw new RangeError(`The \`timeout\` option cannot be greater than ${N}`);await Promise.resolve();let o=await r._fetch();for(const u of r._options.hooks.afterResponse){const l=await u(r.request,r._options,r._decorateResponse(o.clone()));l instanceof globalThis.Response&&(o=l)}if(r._decorateResponse(o),!o.ok&&r._options.throwHttpErrors){let u=new z(o,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(!Qe)throw new Error("Streams are not supported in your environment. `ReadableStream` is missing.");return r._stream(o.clone(),r._options.onDownloadProgress)}return o},c=r._options.retry.methods.includes(r.request.method.toLowerCase())?r._retry(n):n();for(const[o,u]of Object.entries(Ze))c[o]=async()=>{r.request.headers.set("accept",r.request.headers.get("accept")||u);const h=(await c).clone();if(o==="json"){if(h.status===204||(await h.clone().arrayBuffer()).byteLength===0)return"";if(t.parseJson)return t.parseJson(await h.text())}return h[o]()};return c}constructor(e,t={}){if(Object.defineProperty(this,"request",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"abortController",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_retryCount",{enumerable:!0,configurable:!0,writable:!0,value:0}),Object.defineProperty(this,"_input",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_options",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this._input=e,this._options={credentials:this._input.credentials||"same-origin",...t,headers:le(this._input.headers,t.headers),hooks:W({beforeRequest:[],beforeRetry:[],beforeError:[],afterResponse:[]},t.hooks),method:st(t.method??this._input.method),prefixUrl:String(t.prefixUrl||""),retry:it(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(Je){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(ze&&(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);(Xe&&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 ue)){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),N);if(r!==0&&this._retryCount>0){await ot(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})===de)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=ct(this.request,this._options);return this._options.timeout===!1?this._options.fetch(this.request.clone(),e):at(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 c=e.body.getReader();t&&t({percent:0,transferredBytes:0,totalBytes:r},new Uint8Array);async function o(){const{done:u,value:l}=await c.read();if(u){a.close();return}if(t){n+=l.byteLength;const h=r===0?0:n/r;t({percent:h,transferredBytes:n,totalBytes:r},l)}a.enqueue(l),await o()}await o()}}),{status:e.status,statusText:e.statusText,headers:e.headers})}}/*! MIT License © Sindre Sorhus */const D=s=>{const e=(t,r)=>O.create(t,I(s,r));for(const t of he)e[t]=(r,n)=>O.create(r,I(s,n,{method:t}));return e.create=t=>D(I(t)),e.extend=t=>D(I(s,t)),e.stop=de,e},ut=D(),lt=ut,ht=typeof window<"u"?{}:{referrer:"https://sk.thorswap.net",referer:"https://sk.thorswap.net"},Q=lt.create({headers:ht}),pe={get:(s,e)=>Q.get(s,e).json(),post:(s,e)=>Q.post(s,e).json()},X=Object.values(i.Chain),dt=(s="")=>{const e=s.toUpperCase(),[t]=e.split(".");if(X.includes(t))return!0;const[r]=e.split("/");if(X.includes(r))return!0;throw new Error(`Invalid identifier: ${s}. Expected format: <Chain>.<Ticker> or <Chain>.<Ticker>-<ContractAddress>`)},S=8,C=s=>10n**BigInt(s),T=s=>Math.log10(parseFloat(s.toString()));function R({value:s,bigIntDecimal:e=S,decimal:t=S}){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 c=n.length-t;let o=n.slice(-t);return parseInt(o[e])>=5?o=`${o.substring(0,e-1)}${(parseInt(o[e-1])+1).toString()}`:o=o.substring(0,e),`${r?"-":""}${n.slice(0,c)}.${o}`.replace(/\.?0*$/,"")}var y,v,V,fe,q,ge,$,H;const K=class K{constructor(e){A(this,y);A(this,V);A(this,q);A(this,$);m(this,"decimalMultiplier",10n**8n);m(this,"bigIntValue",0n);m(this,"decimal");const t=j(e);this.decimal=typeof e=="object"?e.decimal:void 0,this.decimalMultiplier=C(Math.max(Z(B(t)),this.decimal||0)),p(this,V,fe).call(this,t)}static fromBigInt(e,t){return new K({decimal:t,value:R({value:e,bigIntDecimal:t,decimal:t})})}static shiftDecimals({value:e,from:t,to:r}){return this.fromBigInt(e.getBaseValue("bigint")*C(r)/C(t),r)}set(e){return new this.constructor({decimal:this.decimal,value:e,identifier:this.toString()})}add(...e){return p(this,y,v).call(this,"add",...e)}sub(...e){return p(this,y,v).call(this,"sub",...e)}mul(...e){return p(this,y,v).call(this,"mul",...e)}div(...e){return p(this,y,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||T(this.decimalMultiplier));switch(e){case"number":return Number(t);case"string":return t;default:return this.bigIntValue*BigInt(this.decimal||8n)/this.decimalMultiplier}}getBaseValue(e){const t=this.decimalMultiplier/C(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=j(e),n=B(r);return n==="0"||n==="undefined"?0n:p(this,$,H).call(this,n,t)}formatBigIntToSafeValue(e,t){const r=t||this.decimal||S,n=Math.max(r,T(this.decimalMultiplier)),a=e<0n,c=e.toString().substring(a?1:0),o=n-(c.length-1),u=o>0?"0".repeat(o)+c:c,l=u.length-n;let h=u.slice(-n);return parseInt(h[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 o=parseInt(a),u=`${o}`.slice(0,e);return`0.${u.padStart(a.length-`${o}`.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 c=parseInt(a),o=`${c}`.slice(0,e);return`0.${o.padStart(a.length-`${c}`.length+o.length,"0")}`}toAbbreviation(e=2){const t=this.getValue("number"),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 c=10**(n*3);return`${(t/c).toFixed(e)}${a}`}toCurrency(e="$",{currencyPosition:t="start",decimal:r=2,decimalSeparator:n=".",thousandSeparator:a=","}={}){const c=this.getValue("number"),[o,u=""]=c.toFixed(6).split("."),l=o.replace(/\B(?=(\d{3})+(?!\d))/g,a),h=!o&&!u?"0.00":o==="0"?`${parseFloat(`0.${u}`)}`.replace(".",n):`${l}${parseInt(u)?`${n}${u.slice(0,r)}`:""}`;return`${t==="start"?e:""}${h}${t==="end"?e:""}`}};y=new WeakSet,v=function(e,...t){const r=p(this,q,ge).call(this,this,...t),n=C(r),a=t.reduce((o,u)=>{const l=this.getBigIntValue(u,r);switch(e){case"add":return o+l;case"sub":return o-l;case"mul":return o*l/n;case"div":{if(l===0n)throw new RangeError("Division by zero");return o*n/l}default:return o}},this.bigIntValue*n/this.decimalMultiplier),c=R({bigIntDecimal:r,decimal:Math.max(r,T(this.decimalMultiplier)),value:a});return new this.constructor({decimal:this.decimal,value:c,identifier:this.toString()})},V=new WeakSet,fe=function(e){const t=B(e)||"0";this.bigIntValue=p(this,$,H).call(this,t)},q=new WeakSet,ge=function(...e){const t=e.map(r=>typeof r=="object"?r.decimal||T(r.decimalMultiplier):Z(B(r))).filter(Boolean);return Math.max(...t,S)},$=new WeakSet,H=function(e,t){const r=t?C(t):this.decimalMultiplier,n=T(r),[a="",c=""]=e.split(".");return BigInt(`${a}${c.padEnd(n,"0")}`)};let w=K;const mt=Intl.NumberFormat("fullwide",{useGrouping:!1,maximumFractionDigits:20});function B(s){const t=`${typeof s=="number"?mt.format(s):j(s)}`.replaceAll(",",".").split(".");return t.length>1?`${t.slice(0,-1).join("")}.${t.at(-1)}`:t[0]}function Z(s){var t;const e=((t=s.split(".")[1])==null?void 0:t.length)||0;return Math.max(e,S)}function j(s){return typeof s=="object"?"getValue"in s?s.getValue("string"):s.value:s}const M=(s,e)=>typeof s=="bigint"?R({value:s,bigIntDecimal:e,decimal:e}):s;let L;const ee=s=>{if(!L)throw new Error("Static assets not loaded, call await AssetValue.loadStaticAssets() first");return L.get(s.toUpperCase())||{decimal:i.BaseDecimal.THOR,identifier:""}},te=async(s,e=0)=>{dt(s);const t=await re(F(s)),r=M(e,t);return new _({decimal:t,value:r,identifier:s})};class _ extends w{constructor(t){const r="identifier"in t?t.identifier:`${t.chain}.${t.symbol}`;super(t.value instanceof w?t.value:{decimal:t.decimal,value:t.value});m(this,"address");m(this,"isSynthetic",!1);m(this,"isGasAsset",!1);m(this,"chain");m(this,"symbol");m(this,"ticker");m(this,"type");const n=F(r);this.type=ie(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}toString(t=!1){const r=this.isSynthetic?this.symbol.split("-")[0]: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 te(t,r)}static fromStringSync(t,r=0){const{isSynthetic:n}=F(t),{decimal:a,identifier:c}=ee(t),o=M(r,a);return c?new _({decimal:a,identifier:c,value:o}):n?new _({decimal:8,identifier:t,value:o}):void 0}static async fromIdentifier(t,r=0){return te(t,r)}static fromIdentifierSync(t,r=0){const{decimal:n,identifier:a}=ee(t),c=M(r,n);return new _({decimal:n,identifier:a,value:c})}static fromChainOrSignature(t,r=0){const{decimal:n,identifier:a}=ne(t),c=M(r,n);return new _({value:c,decimal:n,identifier:a})}static async loadStaticAssets(){return new Promise(async(t,r)=>{try{const{ThorchainList:n,NativeList:a,...c}=await import("@swapkit/tokens");L=[a,...Object.values(c)].reduce((u,{tokens:l})=>(l.forEach(({identifier:h,chain:g,...b})=>{const P="decimals"in b?b.decimals:i.BaseDecimal[g];u.set(h,{identifier:h,decimal:P})}),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=_.fromChainOrSignature(s);switch(s){case i.Chain.Bitcoin:case i.Chain.Litecoin:case i.Chain.BitcoinCash:return e.set(10001e-8);case i.Chain.Dogecoin:return e.set(1.00000001);case i.Chain.Avalanche:case i.Chain.Ethereum:return e.set(1e-8);case i.Chain.THORChain:case i.Chain.Maya:return e.set(0);default:return e.set(1e-8)}},F=s=>{const e=s.slice(0,14).includes("/"),[t,r]=s.split(".").pop().split("/"),n=s.includes(".")&&!e?s:`${i.Chain.THORChain}.${r}`,[a,c]=n.split("."),[o,u]=(e?r:c).split("-");return{address:u==null?void 0:u.toLowerCase(),chain:a,isGasAsset:U({chain:a,symbol:c}),isSynthetic:e,symbol:(e?`${t}/`:"")+(u?`${o}-${(u==null?void 0:u.toLowerCase())??""}`:c),ticker:o}},ft={core_wallet_connection_not_found:10001,core_estimated_max_spendable_chain_not_supported:10002,core_extend_error:10003,core_inbound_data_not_found:10004,core_approve_asset_address_or_from_not_found:10005,core_chain_halted:10099,core_wallet_xdefi_not_installed:10101,core_wallet_evmwallet_not_installed:10102,core_wallet_walletconnect_not_installed:10103,core_wallet_keystore_not_installed:10104,core_wallet_ledger_not_installed:10105,core_wallet_trezor_not_installed:10106,core_wallet_keplr_not_installed:10107,core_wallet_okx_not_installed:10108,core_swap_invalid_params:10200,core_swap_route_not_complete:10201,core_swap_asset_not_recognized:10202,core_swap_contract_not_found:10203,core_swap_route_transaction_not_found:10204,core_swap_contract_not_supported:10205,core_swap_transaction_error:10206,core_swap_quote_mode_not_supported:10207,core_transaction_deposit_error:10301,core_transaction_create_liquidity_rune_error:10302,core_transaction_create_liquidity_asset_error:10303,core_transaction_create_liquidity_invalid_params:10304,core_transaction_add_liquidity_invalid_params:10305,core_transaction_add_liquidity_no_rune_address:10306,core_transaction_add_liquidity_rune_error:10307,core_transaction_add_liquidity_asset_error:10308,core_transaction_withdraw_error:10309,core_transaction_deposit_to_pool_error:10310,core_transaction_deposit_insufficient_funds_error:10311,core_transaction_deposit_gas_error:10312,core_transaction_deposit_server_error:10313,wallet_ledger_connection_error:20001,helpers_number_different_decimals:99101};class G extends Error{constructor(e,t){console.error(t),super(e,{cause:{code:ft[e],message:e}}),Object.setPrototypeOf(this,G.prototype)}}class f extends w{eq(e){return this.eqValue(e)}static fromBigInt(e,t){return new f({decimal:t,value:R({value:e,bigIntDecimal:t,decimal:t})})}}exports.AssetValue=_;exports.BigIntArithmetics=w;exports.RequestClient=pe;exports.SwapKitError=G;exports.SwapKitNumber=f;exports.assetFromString=Pe;exports.derivationPathToString=Ye;exports.filterAssets=Ne;exports.formatBigIntToSafeValue=R;exports.gasFeeMultiplier=qe;exports.getAssetType=ie;exports.getAsymmetricAssetShare=oe;exports.getAsymmetricAssetWithdrawAmount=He;exports.getAsymmetricRuneShare=ae;exports.getAsymmetricRuneWithdrawAmount=De;exports.getCommonAssetInfo=ne;exports.getDecimal=re;exports.getEstimatedPoolShare=Le;exports.getLiquiditySlippage=Fe;exports.getMemoFor=We;exports.getMinAmountByChain=pt;exports.getSymmetricPoolShare=ce;exports.getSymmetricWithdraw=je;exports.getTHORNameCost=Ge;exports.isGasAsset=U;exports.validateTHORName=Ke;
|
package/dist/index.es.js
CHANGED
|
@@ -10,8 +10,8 @@ var T = (s, t, e) => {
|
|
|
10
10
|
t instanceof WeakSet ? t.add(s) : t.set(s, e);
|
|
11
11
|
};
|
|
12
12
|
var f = (s, t, e) => (bt(s, t, "access private method"), e);
|
|
13
|
-
import { FeeOption as
|
|
14
|
-
const At = "0x313ce567",
|
|
13
|
+
import { FeeOption as j, BaseDecimal as h, Chain as o, EVMChainList as yt, ChainToRPC as wt, MemoType as g } from "@swapkit/types";
|
|
14
|
+
const At = "0x313ce567", rt = async ({ chain: s, to: t }) => {
|
|
15
15
|
try {
|
|
16
16
|
const { result: e } = await Qt.post(wt[s], {
|
|
17
17
|
headers: {
|
|
@@ -28,17 +28,17 @@ const At = "0x313ce567", st = async ({ chain: s, to: t }) => {
|
|
|
28
28
|
});
|
|
29
29
|
return parseInt(BigInt(e).toString());
|
|
30
30
|
} catch (e) {
|
|
31
|
-
return console.error(e),
|
|
31
|
+
return console.error(e), h[s];
|
|
32
32
|
}
|
|
33
33
|
}, vt = async (s) => {
|
|
34
34
|
if (s === o.Ethereum)
|
|
35
|
-
return
|
|
35
|
+
return h.ETH;
|
|
36
36
|
const [, t] = s.split("-");
|
|
37
|
-
return t != null && t.startsWith("0x") ?
|
|
37
|
+
return t != null && t.startsWith("0x") ? rt({ chain: o.Ethereum, to: t }) : h.ETH;
|
|
38
38
|
}, Tt = async (s) => {
|
|
39
39
|
const [, t] = s.split("-");
|
|
40
|
-
return t != null && t.startsWith("0x") ?
|
|
41
|
-
}, $t = async (s) => s === o.BinanceSmartChain ?
|
|
40
|
+
return t != null && t.startsWith("0x") ? rt({ chain: o.Avalanche, to: t.toLowerCase() }) : h.AVAX;
|
|
41
|
+
}, $t = async (s) => s === o.BinanceSmartChain ? h.BSC : h.BSC, Rt = async ({ chain: s, symbol: t }) => {
|
|
42
42
|
switch (s) {
|
|
43
43
|
case o.Ethereum:
|
|
44
44
|
return vt(t);
|
|
@@ -47,13 +47,13 @@ const At = "0x313ce567", st = async ({ chain: s, to: t }) => {
|
|
|
47
47
|
case o.BinanceSmartChain:
|
|
48
48
|
return $t(t);
|
|
49
49
|
default:
|
|
50
|
-
return
|
|
50
|
+
return h[s];
|
|
51
51
|
}
|
|
52
52
|
}, se = {
|
|
53
|
-
[
|
|
54
|
-
[
|
|
55
|
-
[
|
|
56
|
-
},
|
|
53
|
+
[j.Average]: 1.2,
|
|
54
|
+
[j.Fast]: 1.5,
|
|
55
|
+
[j.Fastest]: 2
|
|
56
|
+
}, st = ({ chain: s, symbol: t }) => {
|
|
57
57
|
switch (s) {
|
|
58
58
|
case o.Bitcoin:
|
|
59
59
|
case o.BitcoinCash:
|
|
@@ -86,13 +86,13 @@ const At = "0x313ce567", st = 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:
|
|
89
|
+
return { identifier: "GAIA.ATOM", decimal: h[s] };
|
|
90
90
|
case o.THORChain:
|
|
91
|
-
return { identifier: "THOR.RUNE", decimal:
|
|
91
|
+
return { identifier: "THOR.RUNE", decimal: h[s] };
|
|
92
92
|
case o.BinanceSmartChain:
|
|
93
|
-
return { identifier: "BSC.BNB", decimal:
|
|
93
|
+
return { identifier: "BSC.BNB", decimal: h[s] };
|
|
94
94
|
case o.Maya:
|
|
95
|
-
return { identifier: "MAYA.CACAO", decimal:
|
|
95
|
+
return { identifier: "MAYA.CACAO", decimal: h.MAYA };
|
|
96
96
|
case "MAYA.MAYA":
|
|
97
97
|
return { identifier: "MAYA.MAYA", decimal: 4 };
|
|
98
98
|
case o.Kujira:
|
|
@@ -106,7 +106,7 @@ const At = "0x313ce567", st = 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:
|
|
109
|
+
return { identifier: `${s}.${s}`, decimal: h[s] };
|
|
110
110
|
}
|
|
111
111
|
}, Ct = ({ chain: s, symbol: t }) => {
|
|
112
112
|
if (t.includes("/"))
|
|
@@ -150,7 +150,7 @@ const At = "0x313ce567", st = async ({ chain: s, to: t }) => {
|
|
|
150
150
|
if (!yt.includes(t))
|
|
151
151
|
return !0;
|
|
152
152
|
const [, r] = e.split("-");
|
|
153
|
-
return
|
|
153
|
+
return st({ chain: t, symbol: e }) || !!r;
|
|
154
154
|
}, ie = (s) => s.filter((t) => {
|
|
155
155
|
const e = `${t.chain}.${t.symbol}`;
|
|
156
156
|
return !It.test(e) && Et(e) && t.value !== "0";
|
|
@@ -159,15 +159,15 @@ const At = "0x313ce567", st = async ({ chain: s, to: t }) => {
|
|
|
159
159
|
poolUnits: t,
|
|
160
160
|
runeDepth: e
|
|
161
161
|
}) => {
|
|
162
|
-
const r = m(s), n = m(t), i = m(e), c = r.mul(i), a = n.mul(n).mul(2), u = n.mul(r).mul(2), l = r.mul(r),
|
|
163
|
-
return c.mul(a.sub(u).add(l)).div(
|
|
162
|
+
const r = m(s), n = m(t), i = m(e), c = r.mul(i), a = n.mul(n).mul(2), u = n.mul(r).mul(2), l = r.mul(r), d = n.mul(n).mul(n);
|
|
163
|
+
return c.mul(a.sub(u).add(l)).div(d);
|
|
164
164
|
}, Bt = ({
|
|
165
165
|
liquidityUnits: s,
|
|
166
166
|
poolUnits: t,
|
|
167
167
|
assetDepth: e
|
|
168
168
|
}) => {
|
|
169
|
-
const r = m(s), n = m(t), i = m(e), c = r.mul(i), a = n.mul(n).mul(2), u = n.mul(r).mul(2), l = r.mul(r),
|
|
170
|
-
return
|
|
169
|
+
const r = m(s), n = m(t), i = m(e), c = r.mul(i), a = n.mul(n).mul(2), u = n.mul(r).mul(2), l = r.mul(r), d = c.mul(a.sub(u).add(l)), _ = n.mul(n).mul(n);
|
|
170
|
+
return d.div(_);
|
|
171
171
|
}, oe = ({
|
|
172
172
|
percent: s,
|
|
173
173
|
runeDepth: t,
|
|
@@ -178,7 +178,7 @@ const At = "0x313ce567", st = async ({ chain: s, to: t }) => {
|
|
|
178
178
|
assetDepth: t,
|
|
179
179
|
liquidityUnits: e,
|
|
180
180
|
poolUnits: r
|
|
181
|
-
}) => Bt({ assetDepth: t, liquidityUnits: e, poolUnits: r }).mul(s), m = (s) => b.fromBigInt(BigInt(s),
|
|
181
|
+
}) => Bt({ assetDepth: t, liquidityUnits: e, poolUnits: r }).mul(s), m = (s) => b.fromBigInt(BigInt(s), h.THOR), Mt = ({
|
|
182
182
|
liquidityUnits: s,
|
|
183
183
|
poolUnits: t,
|
|
184
184
|
runeDepth: e,
|
|
@@ -204,11 +204,11 @@ const At = "0x313ce567", st = async ({ chain: s, to: t }) => {
|
|
|
204
204
|
runeAmount: n,
|
|
205
205
|
assetAmount: i
|
|
206
206
|
}) => {
|
|
207
|
-
const c = new b({ value: s, decimal: 8 }), a = new b({ value: e, decimal: 8 }), u = new b({ value: t, decimal: 8 }), l = new b({ value: n, decimal: 8 }),
|
|
208
|
-
if (
|
|
209
|
-
return
|
|
210
|
-
const ft = u.add(
|
|
211
|
-
return
|
|
207
|
+
const c = new b({ value: s, decimal: 8 }), a = new b({ value: e, decimal: 8 }), u = new b({ value: t, decimal: 8 }), l = new b({ value: n, decimal: 8 }), d = new b({ value: i, decimal: 8 }), _ = l.mul(a), A = d.mul(c), P = l.mul(d), ht = c.mul(a), mt = u.mul(_.add(A.add(P.mul(2)))), pt = _.add(A.add(ht.mul(2))), z = mt.div(pt), N = m(r).add(z);
|
|
208
|
+
if (z.getBaseValue("number") === 0)
|
|
209
|
+
return N.div(u).getBaseValue("number");
|
|
210
|
+
const ft = u.add(N);
|
|
211
|
+
return N.div(ft).getBaseValue("number");
|
|
212
212
|
}, le = ({
|
|
213
213
|
runeAmount: s,
|
|
214
214
|
assetAmount: t,
|
|
@@ -223,7 +223,7 @@ const At = "0x313ce567", st = async ({ chain: s, to: t }) => {
|
|
|
223
223
|
symbol: s,
|
|
224
224
|
ticker: t,
|
|
225
225
|
chain: e
|
|
226
|
-
}) => e === "ETH" && t !== "ETH" ? `${t}-${s.slice(-3)}` : s,
|
|
226
|
+
}) => e === "ETH" && t !== "ETH" ? `${t}-${s.slice(-3)}` : s, de = (s, t) => {
|
|
227
227
|
switch (s) {
|
|
228
228
|
case g.LEAVE:
|
|
229
229
|
case g.BOND: {
|
|
@@ -254,7 +254,7 @@ const At = "0x313ce567", st = async ({ chain: s, to: t }) => {
|
|
|
254
254
|
default:
|
|
255
255
|
return "";
|
|
256
256
|
}
|
|
257
|
-
},
|
|
257
|
+
}, he = (s) => {
|
|
258
258
|
if (s < 0)
|
|
259
259
|
throw new Error("Invalid number of year");
|
|
260
260
|
return 10 + s;
|
|
@@ -264,7 +264,7 @@ const At = "0x313ce567", st = async ({ chain: s, to: t }) => {
|
|
|
264
264
|
const t = /^[a-zA-Z0-9+_-]+$/g;
|
|
265
265
|
return !!s.match(t);
|
|
266
266
|
}, pe = ([s, t, e, r, n]) => `${s}'/${t}'/${e}'/${r}${typeof n != "number" ? "" : `/${n}`}`;
|
|
267
|
-
class
|
|
267
|
+
class J extends Error {
|
|
268
268
|
constructor(t, e, r) {
|
|
269
269
|
const n = t.status || t.status === 0 ? t.status : "", i = t.statusText || "", c = `${n} ${i}`.trim(), a = c ? `status code ${c}` : "an unknown error";
|
|
270
270
|
super(`Request failed with ${a}`), Object.defineProperty(this, "response", {
|
|
@@ -285,7 +285,7 @@ class K extends Error {
|
|
|
285
285
|
}), this.name = "HTTPError", this.response = t, this.request = e, this.options = r;
|
|
286
286
|
}
|
|
287
287
|
}
|
|
288
|
-
class
|
|
288
|
+
class nt extends Error {
|
|
289
289
|
constructor(t) {
|
|
290
290
|
super("Request timed out"), Object.defineProperty(this, "request", {
|
|
291
291
|
enumerable: !0,
|
|
@@ -295,25 +295,25 @@ class it extends Error {
|
|
|
295
295
|
}), this.name = "TimeoutError", this.request = t;
|
|
296
296
|
}
|
|
297
297
|
}
|
|
298
|
-
const
|
|
298
|
+
const B = (s) => s !== null && typeof s == "object", E = (...s) => {
|
|
299
299
|
for (const t of s)
|
|
300
|
-
if ((!
|
|
300
|
+
if ((!B(t) || Array.isArray(t)) && t !== void 0)
|
|
301
301
|
throw new TypeError("The `options` argument must be an object");
|
|
302
|
-
return
|
|
303
|
-
},
|
|
302
|
+
return G({}, ...s);
|
|
303
|
+
}, it = (s = {}, t = {}) => {
|
|
304
304
|
const e = new globalThis.Headers(s), r = t instanceof globalThis.Headers, n = new globalThis.Headers(t);
|
|
305
305
|
for (const [i, c] of n.entries())
|
|
306
306
|
r && c === "undefined" || c === void 0 ? e.delete(i) : e.set(i, c);
|
|
307
307
|
return e;
|
|
308
|
-
},
|
|
308
|
+
}, G = (...s) => {
|
|
309
309
|
let t = {}, e = {};
|
|
310
310
|
for (const r of s)
|
|
311
311
|
if (Array.isArray(r))
|
|
312
312
|
Array.isArray(t) || (t = []), t = [...t, ...r];
|
|
313
|
-
else if (
|
|
313
|
+
else if (B(r)) {
|
|
314
314
|
for (let [n, i] of Object.entries(r))
|
|
315
|
-
|
|
316
|
-
|
|
315
|
+
B(i) && n in t && (i = G(t[n], i)), t = { ...t, [n]: i };
|
|
316
|
+
B(r.headers) && (e = it(e, r.headers), t.headers = e);
|
|
317
317
|
}
|
|
318
318
|
return t;
|
|
319
319
|
}, qt = (() => {
|
|
@@ -327,13 +327,13 @@ const M = (s) => s !== null && typeof s == "object", O = (...s) => {
|
|
|
327
327
|
return s = !0, "half";
|
|
328
328
|
}
|
|
329
329
|
}).headers.has("Content-Type")), s && !t;
|
|
330
|
-
})(), xt = typeof globalThis.AbortController == "function", kt = typeof globalThis.ReadableStream == "function", Pt = typeof globalThis.FormData == "function",
|
|
330
|
+
})(), xt = typeof globalThis.AbortController == "function", kt = typeof globalThis.ReadableStream == "function", Pt = typeof globalThis.FormData == "function", ot = ["get", "post", "put", "patch", "head", "delete"], Nt = {
|
|
331
331
|
json: "application/json",
|
|
332
332
|
text: "text/*",
|
|
333
333
|
formData: "multipart/form-data",
|
|
334
334
|
arrayBuffer: "*/*",
|
|
335
335
|
blob: "*/*"
|
|
336
|
-
},
|
|
336
|
+
}, H = 2147483647, at = Symbol("stop"), jt = {
|
|
337
337
|
json: !0,
|
|
338
338
|
parseJson: !0,
|
|
339
339
|
searchParams: !0,
|
|
@@ -360,18 +360,18 @@ const M = (s) => s !== null && typeof s == "object", O = (...s) => {
|
|
|
360
360
|
window: !0,
|
|
361
361
|
dispatcher: !0,
|
|
362
362
|
duplex: !0
|
|
363
|
-
}, Lt = (s) =>
|
|
363
|
+
}, Lt = (s) => ot.includes(s) ? s.toUpperCase() : s, Dt = ["get", "put", "head", "delete", "options", "trace"], Ut = [408, 413, 429, 500, 502, 503, 504], ct = [413, 429, 503], K = {
|
|
364
364
|
limit: 2,
|
|
365
365
|
methods: Dt,
|
|
366
366
|
statusCodes: Ut,
|
|
367
|
-
afterStatusCodes:
|
|
367
|
+
afterStatusCodes: ct,
|
|
368
368
|
maxRetryAfter: Number.POSITIVE_INFINITY,
|
|
369
369
|
backoffLimit: Number.POSITIVE_INFINITY,
|
|
370
370
|
delay: (s) => 0.3 * 2 ** (s - 1) * 1e3
|
|
371
371
|
}, Ft = (s = {}) => {
|
|
372
372
|
if (typeof s == "number")
|
|
373
373
|
return {
|
|
374
|
-
...
|
|
374
|
+
...K,
|
|
375
375
|
limit: s
|
|
376
376
|
};
|
|
377
377
|
if (s.methods && !Array.isArray(s.methods))
|
|
@@ -379,15 +379,15 @@ const M = (s) => s !== null && typeof s == "object", O = (...s) => {
|
|
|
379
379
|
if (s.statusCodes && !Array.isArray(s.statusCodes))
|
|
380
380
|
throw new Error("retry.statusCodes must be an array");
|
|
381
381
|
return {
|
|
382
|
-
...
|
|
382
|
+
...K,
|
|
383
383
|
...s,
|
|
384
|
-
afterStatusCodes:
|
|
384
|
+
afterStatusCodes: ct
|
|
385
385
|
};
|
|
386
386
|
};
|
|
387
387
|
async function Wt(s, t, e, r) {
|
|
388
388
|
return new Promise((n, i) => {
|
|
389
389
|
const c = setTimeout(() => {
|
|
390
|
-
e && e.abort(), i(new
|
|
390
|
+
e && e.abort(), i(new nt(s));
|
|
391
391
|
}, r.timeout);
|
|
392
392
|
r.fetch(s, t).then(n).catch(i).then(() => {
|
|
393
393
|
clearTimeout(c);
|
|
@@ -411,11 +411,11 @@ const Yt = (s, t) => {
|
|
|
411
411
|
!(r in Ht) && !(r in jt) && !(r in s) && (e[r] = t[r]);
|
|
412
412
|
return e;
|
|
413
413
|
};
|
|
414
|
-
class
|
|
414
|
+
class V {
|
|
415
415
|
static create(t, e) {
|
|
416
|
-
const r = new
|
|
417
|
-
if (typeof r._options.timeout == "number" && r._options.timeout >
|
|
418
|
-
throw new RangeError(`The \`timeout\` option cannot be greater than ${
|
|
416
|
+
const r = new V(t, e), n = async () => {
|
|
417
|
+
if (typeof r._options.timeout == "number" && r._options.timeout > H)
|
|
418
|
+
throw new RangeError(`The \`timeout\` option cannot be greater than ${H}`);
|
|
419
419
|
await Promise.resolve();
|
|
420
420
|
let a = await r._fetch();
|
|
421
421
|
for (const u of r._options.hooks.afterResponse) {
|
|
@@ -423,7 +423,7 @@ class x {
|
|
|
423
423
|
l instanceof globalThis.Response && (a = l);
|
|
424
424
|
}
|
|
425
425
|
if (r._decorateResponse(a), !a.ok && r._options.throwHttpErrors) {
|
|
426
|
-
let u = new
|
|
426
|
+
let u = new J(a, r.request, r._options);
|
|
427
427
|
for (const l of r._options.hooks.beforeError)
|
|
428
428
|
u = await l(u);
|
|
429
429
|
throw u;
|
|
@@ -440,14 +440,14 @@ class x {
|
|
|
440
440
|
for (const [a, u] of Object.entries(Nt))
|
|
441
441
|
c[a] = async () => {
|
|
442
442
|
r.request.headers.set("accept", r.request.headers.get("accept") || u);
|
|
443
|
-
const
|
|
443
|
+
const d = (await c).clone();
|
|
444
444
|
if (a === "json") {
|
|
445
|
-
if (
|
|
445
|
+
if (d.status === 204 || (await d.clone().arrayBuffer()).byteLength === 0)
|
|
446
446
|
return "";
|
|
447
447
|
if (e.parseJson)
|
|
448
|
-
return e.parseJson(await
|
|
448
|
+
return e.parseJson(await d.text());
|
|
449
449
|
}
|
|
450
|
-
return
|
|
450
|
+
return d[a]();
|
|
451
451
|
};
|
|
452
452
|
return c;
|
|
453
453
|
}
|
|
@@ -482,8 +482,8 @@ class x {
|
|
|
482
482
|
// TODO: credentials can be removed when the spec change is implemented in all browsers. Context: https://www.chromestatus.com/feature/4539473312350208
|
|
483
483
|
credentials: this._input.credentials || "same-origin",
|
|
484
484
|
...e,
|
|
485
|
-
headers:
|
|
486
|
-
hooks:
|
|
485
|
+
headers: it(this._input.headers, e.headers),
|
|
486
|
+
hooks: G({
|
|
487
487
|
beforeRequest: [],
|
|
488
488
|
beforeRetry: [],
|
|
489
489
|
beforeError: [],
|
|
@@ -519,8 +519,8 @@ class x {
|
|
|
519
519
|
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 }));
|
|
520
520
|
}
|
|
521
521
|
_calculateRetryDelay(t) {
|
|
522
|
-
if (this._retryCount++, this._retryCount < this._options.retry.limit && !(t instanceof
|
|
523
|
-
if (t instanceof
|
|
522
|
+
if (this._retryCount++, this._retryCount < this._options.retry.limit && !(t instanceof nt)) {
|
|
523
|
+
if (t instanceof J) {
|
|
524
524
|
if (!this._options.retry.statusCodes.includes(t.response.status))
|
|
525
525
|
return 0;
|
|
526
526
|
const r = t.response.headers.get("Retry-After");
|
|
@@ -543,7 +543,7 @@ class x {
|
|
|
543
543
|
try {
|
|
544
544
|
return await t();
|
|
545
545
|
} catch (e) {
|
|
546
|
-
const r = Math.min(this._calculateRetryDelay(e),
|
|
546
|
+
const r = Math.min(this._calculateRetryDelay(e), H);
|
|
547
547
|
if (r !== 0 && this._retryCount > 0) {
|
|
548
548
|
await Gt(r, { signal: this._options.signal });
|
|
549
549
|
for (const n of this._options.hooks.beforeRetry)
|
|
@@ -552,7 +552,7 @@ class x {
|
|
|
552
552
|
options: this._options,
|
|
553
553
|
error: e,
|
|
554
554
|
retryCount: this._retryCount
|
|
555
|
-
}) ===
|
|
555
|
+
}) === at)
|
|
556
556
|
return;
|
|
557
557
|
return this._retry(t);
|
|
558
558
|
}
|
|
@@ -592,8 +592,8 @@ class x {
|
|
|
592
592
|
}
|
|
593
593
|
if (e) {
|
|
594
594
|
n += l.byteLength;
|
|
595
|
-
const
|
|
596
|
-
e({ percent:
|
|
595
|
+
const d = r === 0 ? 0 : n / r;
|
|
596
|
+
e({ percent: d, transferredBytes: n, totalBytes: r }, l);
|
|
597
597
|
}
|
|
598
598
|
i.enqueue(l), await a();
|
|
599
599
|
}
|
|
@@ -607,26 +607,26 @@ class x {
|
|
|
607
607
|
}
|
|
608
608
|
}
|
|
609
609
|
/*! MIT License © Sindre Sorhus */
|
|
610
|
-
const
|
|
611
|
-
const t = (e, r) =>
|
|
612
|
-
for (const e of
|
|
613
|
-
t[e] = (r, n) =>
|
|
614
|
-
return t.create = (e) =>
|
|
615
|
-
}, zt =
|
|
616
|
-
get: (s, t) =>
|
|
617
|
-
post: (s, t) =>
|
|
618
|
-
},
|
|
610
|
+
const L = (s) => {
|
|
611
|
+
const t = (e, r) => V.create(e, E(s, r));
|
|
612
|
+
for (const e of ot)
|
|
613
|
+
t[e] = (r, n) => V.create(r, E(s, n, { method: e }));
|
|
614
|
+
return t.create = (e) => L(E(e)), t.extend = (e) => L(E(s, e)), t.stop = at, t;
|
|
615
|
+
}, zt = L(), Jt = zt, Kt = typeof window < "u" ? {} : { referrer: "https://sk.thorswap.net", referer: "https://sk.thorswap.net" }, Q = Jt.create({ headers: Kt }), Qt = {
|
|
616
|
+
get: (s, t) => Q.get(s, t).json(),
|
|
617
|
+
post: (s, t) => Q.post(s, t).json()
|
|
618
|
+
}, X = Object.values(o), Xt = (s = "") => {
|
|
619
619
|
const t = s.toUpperCase(), [e] = t.split(".");
|
|
620
|
-
if (
|
|
620
|
+
if (X.includes(e))
|
|
621
621
|
return !0;
|
|
622
622
|
const [r] = t.split("/");
|
|
623
|
-
if (
|
|
623
|
+
if (X.includes(r))
|
|
624
624
|
return !0;
|
|
625
625
|
throw new Error(
|
|
626
626
|
`Invalid identifier: ${s}. Expected format: <Chain>.<Ticker> or <Chain>.<Ticker>-<ContractAddress>`
|
|
627
627
|
);
|
|
628
628
|
}, S = 8, v = (s) => 10n ** BigInt(s), $ = (s) => Math.log10(parseFloat(s.toString()));
|
|
629
|
-
function
|
|
629
|
+
function q({
|
|
630
630
|
value: s,
|
|
631
631
|
bigIntDecimal: t = S,
|
|
632
632
|
decimal: e = S
|
|
@@ -642,25 +642,25 @@ function k({
|
|
|
642
642
|
""
|
|
643
643
|
);
|
|
644
644
|
}
|
|
645
|
-
var w, R,
|
|
646
|
-
const
|
|
645
|
+
var w, R, x, ut, k, lt, I, D;
|
|
646
|
+
const Y = class Y {
|
|
647
647
|
constructor(t) {
|
|
648
648
|
T(this, w);
|
|
649
|
+
T(this, x);
|
|
650
|
+
T(this, k);
|
|
649
651
|
T(this, I);
|
|
650
|
-
T(this, P);
|
|
651
|
-
T(this, E);
|
|
652
652
|
p(this, "decimalMultiplier", 10n ** 8n);
|
|
653
653
|
p(this, "bigIntValue", 0n);
|
|
654
654
|
p(this, "decimal");
|
|
655
|
-
const e =
|
|
655
|
+
const e = U(t);
|
|
656
656
|
this.decimal = typeof t == "object" ? t.decimal : void 0, this.decimalMultiplier = v(
|
|
657
|
-
Math.max(
|
|
658
|
-
), f(this,
|
|
657
|
+
Math.max(Z(O(e)), this.decimal || 0)
|
|
658
|
+
), f(this, x, ut).call(this, e);
|
|
659
659
|
}
|
|
660
660
|
static fromBigInt(t, e) {
|
|
661
|
-
return new
|
|
661
|
+
return new Y({
|
|
662
662
|
decimal: e,
|
|
663
|
-
value:
|
|
663
|
+
value: q({ value: t, bigIntDecimal: e, decimal: e })
|
|
664
664
|
});
|
|
665
665
|
}
|
|
666
666
|
static shiftDecimals({
|
|
@@ -674,7 +674,7 @@ const z = class z {
|
|
|
674
674
|
);
|
|
675
675
|
}
|
|
676
676
|
set(t) {
|
|
677
|
-
return
|
|
677
|
+
return new this.constructor({ decimal: this.decimal, value: t, identifier: this.toString() });
|
|
678
678
|
}
|
|
679
679
|
add(...t) {
|
|
680
680
|
return f(this, w, R).call(this, "add", ...t);
|
|
@@ -718,7 +718,7 @@ const z = class z {
|
|
|
718
718
|
}
|
|
719
719
|
}
|
|
720
720
|
getBaseValue(t) {
|
|
721
|
-
const e = this.decimalMultiplier / v(this.decimal ||
|
|
721
|
+
const e = this.decimalMultiplier / v(this.decimal || h.THOR), r = this.bigIntValue / e;
|
|
722
722
|
switch (t) {
|
|
723
723
|
case "number":
|
|
724
724
|
return Number(r);
|
|
@@ -731,19 +731,19 @@ const z = class z {
|
|
|
731
731
|
getBigIntValue(t, e) {
|
|
732
732
|
if (!e && typeof t == "object")
|
|
733
733
|
return t.bigIntValue;
|
|
734
|
-
const r =
|
|
735
|
-
return n === "0" || n === "undefined" ? 0n : f(this,
|
|
734
|
+
const r = U(t), n = O(r);
|
|
735
|
+
return n === "0" || n === "undefined" ? 0n : f(this, I, D).call(this, n, e);
|
|
736
736
|
}
|
|
737
737
|
formatBigIntToSafeValue(t, e) {
|
|
738
738
|
const r = e || this.decimal || S, n = Math.max(
|
|
739
739
|
r,
|
|
740
740
|
$(this.decimalMultiplier)
|
|
741
741
|
), i = t < 0n, c = t.toString().substring(i ? 1 : 0), a = n - (c.length - 1), u = a > 0 ? "0".repeat(a) + c : c, l = u.length - n;
|
|
742
|
-
let
|
|
743
|
-
return parseInt(
|
|
742
|
+
let d = u.slice(-n);
|
|
743
|
+
return parseInt(d[r]) >= 5 ? d = `${d.substring(0, r - 1)}${(parseInt(d[r - 1]) + 1).toString()}` : d = d.substring(0, r), `${i ? "-" : ""}${u.slice(
|
|
744
744
|
0,
|
|
745
745
|
l
|
|
746
|
-
)}.${
|
|
746
|
+
)}.${d}`.replace(/\.?0*$/, "");
|
|
747
747
|
}
|
|
748
748
|
toSignificant(t = 6) {
|
|
749
749
|
const [e, r] = this.getValue("string").split("."), n = e || "", i = r || "";
|
|
@@ -785,12 +785,12 @@ const z = class z {
|
|
|
785
785
|
decimalSeparator: n = ".",
|
|
786
786
|
thousandSeparator: i = ","
|
|
787
787
|
} = {}) {
|
|
788
|
-
const c = this.getValue("number"), [a, u = ""] = c.toFixed(6).split("."), l = a.replace(/\B(?=(\d{3})+(?!\d))/g, i),
|
|
789
|
-
return `${e === "start" ? t : ""}${
|
|
788
|
+
const c = this.getValue("number"), [a, u = ""] = c.toFixed(6).split("."), l = a.replace(/\B(?=(\d{3})+(?!\d))/g, i), d = !a && !u ? "0.00" : a === "0" ? `${parseFloat(`0.${u}`)}`.replace(".", n) : `${l}${parseInt(u) ? `${n}${u.slice(0, r)}` : ""}`;
|
|
789
|
+
return `${e === "start" ? t : ""}${d}${e === "end" ? t : ""}`;
|
|
790
790
|
}
|
|
791
791
|
};
|
|
792
792
|
w = new WeakSet(), R = function(t, ...e) {
|
|
793
|
-
const r = f(this,
|
|
793
|
+
const r = f(this, k, lt).call(this, this, ...e), n = v(r), i = e.reduce(
|
|
794
794
|
(a, u) => {
|
|
795
795
|
const l = this.getBigIntValue(u, r);
|
|
796
796
|
switch (t) {
|
|
@@ -811,50 +811,50 @@ w = new WeakSet(), R = function(t, ...e) {
|
|
|
811
811
|
},
|
|
812
812
|
//normalize is to precision multiplier base
|
|
813
813
|
this.bigIntValue * n / this.decimalMultiplier
|
|
814
|
-
), c =
|
|
814
|
+
), c = q({
|
|
815
815
|
bigIntDecimal: r,
|
|
816
816
|
decimal: Math.max(r, $(this.decimalMultiplier)),
|
|
817
817
|
value: i
|
|
818
818
|
});
|
|
819
819
|
return new this.constructor({ decimal: this.decimal, value: c, identifier: this.toString() });
|
|
820
|
-
},
|
|
821
|
-
const e =
|
|
822
|
-
this.bigIntValue = f(this,
|
|
823
|
-
},
|
|
820
|
+
}, x = new WeakSet(), ut = function(t) {
|
|
821
|
+
const e = O(t) || "0";
|
|
822
|
+
this.bigIntValue = f(this, I, D).call(this, e);
|
|
823
|
+
}, k = new WeakSet(), lt = function(...t) {
|
|
824
824
|
const e = t.map(
|
|
825
|
-
(r) => typeof r == "object" ? r.decimal || $(r.decimalMultiplier) :
|
|
825
|
+
(r) => typeof r == "object" ? r.decimal || $(r.decimalMultiplier) : Z(O(r))
|
|
826
826
|
).filter(Boolean);
|
|
827
827
|
return Math.max(...e, S);
|
|
828
|
-
},
|
|
828
|
+
}, I = new WeakSet(), D = function(t, e) {
|
|
829
829
|
const r = e ? v(e) : this.decimalMultiplier, n = $(r), [i = "", c = ""] = t.split(".");
|
|
830
830
|
return BigInt(`${i}${c.padEnd(n, "0")}`);
|
|
831
831
|
};
|
|
832
|
-
let C =
|
|
832
|
+
let C = Y;
|
|
833
833
|
const Zt = Intl.NumberFormat("fullwide", {
|
|
834
834
|
useGrouping: !1,
|
|
835
835
|
maximumFractionDigits: 20
|
|
836
836
|
});
|
|
837
|
-
function
|
|
838
|
-
const e = `${typeof s == "number" ? Zt.format(s) :
|
|
837
|
+
function O(s) {
|
|
838
|
+
const e = `${typeof s == "number" ? Zt.format(s) : U(s)}`.replaceAll(",", ".").split(".");
|
|
839
839
|
return e.length > 1 ? `${e.slice(0, -1).join("")}.${e.at(-1)}` : e[0];
|
|
840
840
|
}
|
|
841
|
-
function
|
|
841
|
+
function Z(s) {
|
|
842
842
|
var e;
|
|
843
843
|
const t = ((e = s.split(".")[1]) == null ? void 0 : e.length) || 0;
|
|
844
844
|
return Math.max(t, S);
|
|
845
845
|
}
|
|
846
|
-
function
|
|
846
|
+
function U(s) {
|
|
847
847
|
return typeof s == "object" ? "getValue" in s ? s.getValue("string") : s.value : s;
|
|
848
848
|
}
|
|
849
|
-
const
|
|
850
|
-
let
|
|
851
|
-
const
|
|
852
|
-
if (!
|
|
849
|
+
const M = (s, t) => typeof s == "bigint" ? q({ value: s, bigIntDecimal: t, decimal: t }) : s;
|
|
850
|
+
let F;
|
|
851
|
+
const tt = (s) => {
|
|
852
|
+
if (!F)
|
|
853
853
|
throw new Error("Static assets not loaded, call await AssetValue.loadStaticAssets() first");
|
|
854
|
-
return
|
|
855
|
-
},
|
|
854
|
+
return F.get(s.toUpperCase()) || { decimal: h.THOR, identifier: "" };
|
|
855
|
+
}, et = async (s, t = 0) => {
|
|
856
856
|
Xt(s);
|
|
857
|
-
const e = await Rt(
|
|
857
|
+
const e = await Rt(W(s)), r = M(t, e);
|
|
858
858
|
return new y({ decimal: e, value: r, identifier: s });
|
|
859
859
|
};
|
|
860
860
|
class y extends C {
|
|
@@ -870,7 +870,7 @@ class y extends C {
|
|
|
870
870
|
p(this, "symbol");
|
|
871
871
|
p(this, "ticker");
|
|
872
872
|
p(this, "type");
|
|
873
|
-
const n =
|
|
873
|
+
const n = W(r);
|
|
874
874
|
this.type = Ct(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
|
toString(e = !1) {
|
|
@@ -884,23 +884,23 @@ class y extends C {
|
|
|
884
884
|
return this.chain === e && this.symbol === r;
|
|
885
885
|
}
|
|
886
886
|
static async fromString(e, r = 0) {
|
|
887
|
-
return
|
|
887
|
+
return et(e, r);
|
|
888
888
|
}
|
|
889
889
|
static fromStringSync(e, r = 0) {
|
|
890
|
-
const { isSynthetic: n } =
|
|
890
|
+
const { isSynthetic: n } = W(e), { decimal: i, identifier: c } = tt(
|
|
891
891
|
e
|
|
892
|
-
), a =
|
|
892
|
+
), a = M(r, i);
|
|
893
893
|
return c ? new y({ decimal: i, identifier: c, value: a }) : n ? new y({ decimal: 8, identifier: e, value: a }) : void 0;
|
|
894
894
|
}
|
|
895
895
|
static async fromIdentifier(e, r = 0) {
|
|
896
|
-
return
|
|
896
|
+
return et(e, r);
|
|
897
897
|
}
|
|
898
898
|
static fromIdentifierSync(e, r = 0) {
|
|
899
|
-
const { decimal: n, identifier: i } =
|
|
899
|
+
const { decimal: n, identifier: i } = tt(e), c = M(r, n);
|
|
900
900
|
return new y({ decimal: n, identifier: i, value: c });
|
|
901
901
|
}
|
|
902
902
|
static fromChainOrSignature(e, r = 0) {
|
|
903
|
-
const { decimal: n, identifier: i } = St(e), c =
|
|
903
|
+
const { decimal: n, identifier: i } = St(e), c = M(r, n);
|
|
904
904
|
return new y({ value: c, decimal: n, identifier: i });
|
|
905
905
|
}
|
|
906
906
|
static async loadStaticAssets() {
|
|
@@ -914,10 +914,10 @@ class y extends C {
|
|
|
914
914
|
NativeList: i,
|
|
915
915
|
...c
|
|
916
916
|
} = await import("@swapkit/tokens");
|
|
917
|
-
|
|
918
|
-
(u, { tokens: l }) => (l.forEach(({ identifier:
|
|
919
|
-
const
|
|
920
|
-
u.set(
|
|
917
|
+
F = [i, ...Object.values(c)].reduce(
|
|
918
|
+
(u, { tokens: l }) => (l.forEach(({ identifier: d, chain: _, ...A }) => {
|
|
919
|
+
const P = "decimals" in A ? A.decimals : h[_];
|
|
920
|
+
u.set(d, { identifier: d, decimal: P });
|
|
921
921
|
}), u),
|
|
922
922
|
/* @__PURE__ */ new Map()
|
|
923
923
|
), e({ ok: !0 });
|
|
@@ -950,12 +950,12 @@ const fe = (s) => {
|
|
|
950
950
|
default:
|
|
951
951
|
return t.set(1e-8);
|
|
952
952
|
}
|
|
953
|
-
},
|
|
953
|
+
}, W = (s) => {
|
|
954
954
|
const t = s.slice(0, 14).includes("/"), [e, r] = s.split(".").pop().split("/"), n = s.includes(".") && !t ? s : `${o.THORChain}.${r}`, [i, c] = n.split("."), [a, u] = (t ? r : c).split("-");
|
|
955
955
|
return {
|
|
956
956
|
address: u == null ? void 0 : u.toLowerCase(),
|
|
957
957
|
chain: i,
|
|
958
|
-
isGasAsset:
|
|
958
|
+
isGasAsset: st({ chain: i, symbol: c }),
|
|
959
959
|
isSynthetic: t,
|
|
960
960
|
symbol: (t ? `${e}/` : "") + (u ? `${a}-${(u == null ? void 0 : u.toLowerCase()) ?? ""}` : c),
|
|
961
961
|
ticker: a
|
|
@@ -1017,9 +1017,9 @@ const fe = (s) => {
|
|
|
1017
1017
|
*/
|
|
1018
1018
|
helpers_number_different_decimals: 99101
|
|
1019
1019
|
};
|
|
1020
|
-
class
|
|
1020
|
+
class dt extends Error {
|
|
1021
1021
|
constructor(t, e) {
|
|
1022
|
-
console.error(e), super(t, { cause: { code: te[t], message: t } }), Object.setPrototypeOf(this,
|
|
1022
|
+
console.error(e), super(t, { cause: { code: te[t], message: t } }), Object.setPrototypeOf(this, dt.prototype);
|
|
1023
1023
|
}
|
|
1024
1024
|
}
|
|
1025
1025
|
class b extends C {
|
|
@@ -1029,7 +1029,7 @@ class b extends C {
|
|
|
1029
1029
|
static fromBigInt(t, e) {
|
|
1030
1030
|
return new b({
|
|
1031
1031
|
decimal: e,
|
|
1032
|
-
value:
|
|
1032
|
+
value: q({ value: t, bigIntDecimal: e, decimal: e })
|
|
1033
1033
|
});
|
|
1034
1034
|
}
|
|
1035
1035
|
}
|
|
@@ -1037,12 +1037,12 @@ export {
|
|
|
1037
1037
|
y as AssetValue,
|
|
1038
1038
|
C as BigIntArithmetics,
|
|
1039
1039
|
Qt as RequestClient,
|
|
1040
|
-
|
|
1040
|
+
dt as SwapKitError,
|
|
1041
1041
|
b as SwapKitNumber,
|
|
1042
1042
|
ne as assetFromString,
|
|
1043
1043
|
pe as derivationPathToString,
|
|
1044
1044
|
ie as filterAssets,
|
|
1045
|
-
|
|
1045
|
+
q as formatBigIntToSafeValue,
|
|
1046
1046
|
se as gasFeeMultiplier,
|
|
1047
1047
|
Ct as getAssetType,
|
|
1048
1048
|
Bt as getAsymmetricAssetShare,
|
|
@@ -1053,11 +1053,11 @@ export {
|
|
|
1053
1053
|
Rt as getDecimal,
|
|
1054
1054
|
ue as getEstimatedPoolShare,
|
|
1055
1055
|
le as getLiquiditySlippage,
|
|
1056
|
-
|
|
1056
|
+
de as getMemoFor,
|
|
1057
1057
|
fe as getMinAmountByChain,
|
|
1058
1058
|
Mt as getSymmetricPoolShare,
|
|
1059
1059
|
ce as getSymmetricWithdraw,
|
|
1060
|
-
|
|
1061
|
-
|
|
1060
|
+
he as getTHORNameCost,
|
|
1061
|
+
st as isGasAsset,
|
|
1062
1062
|
me as validateTHORName
|
|
1063
1063
|
};
|
package/package.json
CHANGED
|
@@ -9,15 +9,15 @@
|
|
|
9
9
|
"vite": "4.4.9",
|
|
10
10
|
"vitest": "0.34.4",
|
|
11
11
|
"@internal/config": "0.0.0-rc.1",
|
|
12
|
-
"@swapkit/tokens": "1.0.0-rc.
|
|
13
|
-
"@swapkit/types": "1.0.0-rc.
|
|
12
|
+
"@swapkit/tokens": "1.0.0-rc.12",
|
|
13
|
+
"@swapkit/types": "1.0.0-rc.12"
|
|
14
14
|
},
|
|
15
15
|
"eslintConfig": {
|
|
16
16
|
"extends": "../../../internal/eslint-config"
|
|
17
17
|
},
|
|
18
18
|
"peerDependencies": {
|
|
19
|
-
"@swapkit/tokens": "1.0.0-rc.
|
|
20
|
-
"@swapkit/types": "1.0.0-rc.
|
|
19
|
+
"@swapkit/tokens": "1.0.0-rc.12",
|
|
20
|
+
"@swapkit/types": "1.0.0-rc.12"
|
|
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.
|
|
45
|
+
"version": "1.0.0-rc.30",
|
|
46
46
|
"scripts": {
|
|
47
47
|
"build": "vite build",
|
|
48
48
|
"clean": "rm -rf dist vite.config.ts.* .turbo node_modules",
|
|
@@ -93,8 +93,8 @@ export class BigIntArithmetics {
|
|
|
93
93
|
}
|
|
94
94
|
|
|
95
95
|
set(value: SKBigIntParams): this {
|
|
96
|
-
|
|
97
|
-
return this;
|
|
96
|
+
// @ts-expect-error False positive
|
|
97
|
+
return new this.constructor({ decimal: this.decimal, value, identifier: this.toString() });
|
|
98
98
|
}
|
|
99
99
|
add(...args: InitialisationValueType[]) {
|
|
100
100
|
return this.#arithmetics('add', ...args);
|