@swapkit/helpers 1.0.0-rc.21 → 1.0.0-rc.22
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.d.ts +6 -12
- package/dist/index.es.js +118 -127
- package/package.json +1 -1
- package/src/modules/__tests__/swapKitNumber.test.ts +33 -0
- package/src/modules/bigIntArithmetics.ts +25 -19
package/dist/index.cjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";var Te=Object.create;var D=Object.defineProperty;var Se=Object.getOwnPropertyDescriptor;var ve=Object.getOwnPropertyNames;var Re=Object.getPrototypeOf,$e=Object.prototype.hasOwnProperty;var Be=(s,e,t)=>e in s?D(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t;var Ie=(s,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of ve(e))!$e.call(s,n)&&n!==t&&D(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)):{},Ie(e||!s||!s.__esModule?D(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",se=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")?se({chain:i.Chain.Ethereum,to:e}):i.BaseDecimal.ETH},qe=async s=>{const[,e]=s.split("-");return e!=null&&e.startsWith("0x")?se({chain:i.Chain.Avalanche,to:e.toLowerCase()}):i.BaseDecimal.AVAX},ke=async s=>(s===i.Chain.BinanceSmartChain,i.BaseDecimal.BSC),ne=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}},Ne=new RegExp(/(.)\1{6}|\.ORG|\.NET|\.FINANCE|\.COM|WWW|HTTP|\\\\|\/\/|[\s$%:[\]]/,"gmi"),De=s=>s.filter(e=>!Ne.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)),g=n.mul(n).mul(n);return h.div(g)},je=({percent:s,runeDepth:e,liquidityUnits:t,poolUnits:r})=>ce({runeDepth:e,liquidityUnits:t,poolUnits:r}).mul(s),He=({percent:s,assetDepth:e,liquidityUnits:t,poolUnits:r})=>ue({assetDepth:e,liquidityUnits:t,poolUnits:r}).mul(s),m=s=>f.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 f({value:s,decimal:8}),c=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(c),w=h.mul(o),x=l.mul(h),be=o.mul(c),Ce=u.mul(g.add(w.add(x.mul(2)))),we=g.add(w.add(be.mul(2))),J=Ce.div(we),N=m(r).add(J);if(J.getBaseValue("number")===0)return N.div(u).getBaseValue("number");const Ae=u.add(N);return N.div(Ae).getBaseValue("number")},Ue=({runeAmount: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 Q 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 K({},...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},K=(...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=K(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:"*/*"},j=2147483647,pe=Symbol("stop"),tt={json:!0,parseJson:!0,searchParams:!0,prefixUrl:!0,retry:!0,timeout:!0,hooks:!0,throwHttpErrors:!0,onDownloadProgress:!0,fetch:!0},rt={method:!0,headers:!0,body:!0,mode:!0,credentials:!0,cache:!0,redirect:!0,referrer:!0,referrerPolicy:!0,integrity:!0,keepalive:!0,signal:!0,window:!0,dispatcher:!0,duplex:!0},st=s=>me.includes(s)?s.toUpperCase():s,nt=["get","put","head","delete","options","trace"],it=[408,413,429,500,502,503,504],fe=[413,429,503],X={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{...X,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{...X,...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 q{static create(e,t){const r=new q(e,t),n=async()=>{if(typeof r._options.timeout=="number"&&r._options.timeout>j)throw new RangeError(`The \`timeout\` option cannot be greater than ${j}`);await Promise.resolve();let c=await r._fetch();for(const u of r._options.hooks.afterResponse){const l=await u(r.request,r._options,r._decorateResponse(c.clone()));l instanceof globalThis.Response&&(c=l)}if(r._decorateResponse(c),!c.ok&&r._options.throwHttpErrors){let u=new Q(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:K({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 Q){if(!this._options.retry.statusCodes.includes(e.response.status))return 0;const r=e.response.headers.get("Retry-After");if(r&&this._options.retry.afterStatusCodes.includes(e.response.status)){let n=Number(r);return Number.isNaN(n)?n=Date.parse(r)-Date.now():n*=1e3,this._options.retry.maxRetryAfter!==void 0&&n>this._options.retry.maxRetryAfter?0:n}if(e.response.status===413)return 0}const t=this._options.retry.delay(this._retryCount);return Math.min(this._options.retry.backoffLimit,t)}return 0}_decorateResponse(e){return this._options.parseJson&&(e.json=async()=>this._options.parseJson(await e.text())),e}async _retry(e){try{return await e()}catch(t){const r=Math.min(this._calculateRetryDelay(t),j);if(r!==0&&this._retryCount>0){await ct(r,{signal:this._options.signal});for(const n of this._options.hooks.beforeRetry)if(await n({request:this.request,options:this._options,error:t,retryCount:this._retryCount})===pe)return;return this._retry(e)}throw t}}async _fetch(){for(const t of this._options.hooks.beforeRequest){const r=await t(this.request,this._options);if(r instanceof Request){this.request=r;break}if(r instanceof Response)return r}const e=ut(this.request,this._options);return this._options.timeout===!1?this._options.fetch(this.request.clone(),e):ot(this.request.clone(),e,this.abortController,this._options)}_stream(e,t){const r=Number(e.headers.get("content-length"))||0;let n=0;return e.status===204?(t&&t({percent:1,totalBytes:r,transferredBytes:n},new Uint8Array),new globalThis.Response(null,{status:e.status,statusText:e.statusText,headers:e.headers})):new globalThis.Response(new globalThis.ReadableStream({async start(a){const o=e.body.getReader();t&&t({percent:0,transferredBytes:0,totalBytes:r},new Uint8Array);async function c(){const{done:u,value:l}=await o.read();if(u){a.close();return}if(t){n+=l.byteLength;const h=r===0?0:n/r;t({percent:h,transferredBytes:n,totalBytes:r},l)}a.enqueue(l),await c()}await c()}}),{status:e.status,statusText:e.statusText,headers:e.headers})}}/*! MIT License © Sindre Sorhus */const L=s=>{const e=(t,r)=>q.create(t,O(s,r));for(const t of me)e[t]=(r,n)=>q.create(r,O(s,n,{method:t}));return e.create=t=>L(O(t)),e.extend=t=>L(O(s,t)),e.stop=pe,e},lt=L(),ht=lt,dt=typeof window<"u"?{}:{referrer:"https://sk.thorswap.net",referer:"https://sk.thorswap.net"},Z=ht.create({headers:dt}),ge={get:(s,e)=>Z.get(s,e).json(),post:(s,e)=>Z.post(s,e).json()},ee=Object.values(i.Chain),mt=(s="")=>{const e=s.toUpperCase(),[t]=e.split(".");if(ee.includes(t))return!0;const[r]=e.split("/");if(ee.includes(r))return!0;throw new Error(`Invalid identifier: ${s}. Expected format: <Chain>.<Ticker> or <Chain>.<Ticker>-<ContractAddress>`)},$=8,A=s=>10n**BigInt(s),S=s=>Math.log10(parseFloat(s.toString()));function B({value:s,bigIntDecimal:e=$,decimal:t=$}){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,k,_e,P,ye,I,F,C,R,E,U;const z=class z{constructor(e){y(this,b);y(this,k);y(this,P);y(this,I);y(this,C);y(this,E);p(this,"decimalMultiplier",10n**8n);p(this,"bigIntValue",0n);p(this,"decimal");const t=H(e);this.decimal=typeof e=="object"?e.decimal:void 0,this.decimalMultiplier=A(Math.max(d(this,E,U).call(this,d(this,C,R).call(this,t)),this.decimal||0)),d(this,k,_e).call(this,t)}static fromBigInt(e,t){return new z({decimal:t,value:B({value:e,bigIntDecimal:t,decimal:t})})}static shiftDecimals({value:e,from:t,to:r}){return this.fromBigInt(e.getBaseValue("bigint")*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=H(e),n=d(this,C,R).call(this,r);return n==="0"||n==="undefined"?0n:d(this,I,F).call(this,n,t)}formatBigIntToSafeValue(e,t){const r=t||this.decimal||$,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,P,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()})},k=new WeakSet,_e=function(e){const t=d(this,C,R).call(this,e)||"0";this.bigIntValue=d(this,I,F).call(this,t)},P=new WeakSet,ye=function(...e){const t=e.map(r=>typeof r=="object"?r.decimal||S(r.decimalMultiplier):d(this,E,U).call(this,d(this,C,R).call(this,r))).filter(Boolean);return Math.max(...t,$)},I=new WeakSet,F=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}):H(e)}`.replaceAll(",",".").split(".");return r.length>1?`${r.slice(0,-1).join("")}.${r.at(-1)}`:r[0]},E=new WeakSet,U=function(e){var r;const t=((r=e.split(".")[1])==null?void 0:r.length)||0;return Math.max(t,$)};let T=z;function H(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 W;const te=s=>{if(!W)throw new Error("Static assets not loaded, call await AssetValue.loadStaticAssets() first");return W.get(s.toUpperCase())||{decimal:i.BaseDecimal.THOR,identifier:""}},re=async(s,e=0)=>{mt(s);const t=await ne(G(s)),r=V(e,t);return new _({decimal:t,value:r,identifier:s})};class _ extends T{constructor(t){super(t.value instanceof T?t.value:{decimal:t.decimal,value:t.value});p(this,"address");p(this,"chain");p(this,"isSynthetic",!1);p(this,"isGasAsset",!1);p(this,"symbol");p(this,"ticker");p(this,"type");const r="identifier"in t?t.identifier:`${t.chain}.${t.symbol}`,n=G(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 re(t,r)}static fromStringSync(t,r=0){const{isSynthetic:n}=G(t),{decimal:a,identifier:o}=te(t),c=V(r,a);return o?new _({decimal:a,identifier:o,value:c}):n?new _({decimal:8,identifier:t,value:c}):void 0}static async fromIdentifier(t,r=0){return re(t,r)}static fromIdentifierSync(t,r=0){const{decimal:n,identifier:a}=te(t),o=V(r,n);return new _({decimal:n,identifier:a,value:o})}static fromChainOrSignature(t,r=0){const{decimal:n,identifier:a}=ae(t),o=V(r,n);return new _({value:o,decimal:n,identifier:a})}static async loadStaticAssets(){return new Promise(async(t,r)=>{try{const{ThorchainList:n,NativeList:a,...o}=await import("@swapkit/tokens");W=[a,...Object.values(o)].reduce((u,{tokens:l})=>(l.forEach(({identifier:h,chain:g,...w})=>{const x="decimals"in w?w.decimals:i.BaseDecimal[g];u.set(h,{identifier:h,decimal:x})}),u),new Map),t({ok:!0})}catch(n){console.error(n),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)}},G=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 Y extends Error{constructor(e,t){console.error(t),super(e,{cause:{code:ft[e],message:e}}),Object.setPrototypeOf(this,Y.prototype)}}class f extends T{eq(e){return this.eqValue(e)}static fromBigInt(e,t){return new f({decimal:t,value:B({value:e,bigIntDecimal:t,decimal:t})})}}exports.AssetValue=_;exports.BigIntArithmetics=T;exports.RequestClient=ge;exports.SwapKitError=Y;exports.SwapKitNumber=f;exports.assetFromString=xe;exports.derivationPathToString=ze;exports.filterAssets=De;exports.formatBigIntToSafeValue=B;exports.gasFeeMultiplier=Pe;exports.getAssetType=oe;exports.getAsymmetricAssetShare=ue;exports.getAsymmetricAssetWithdrawAmount=He;exports.getAsymmetricRuneShare=ce;exports.getAsymmetricRuneWithdrawAmount=je;exports.getCommonAssetInfo=ae;exports.getDecimal=ne;exports.getEstimatedPoolShare=Fe;exports.getLiquiditySlippage=Ue;exports.getMemoFor=Ge;exports.getMinAmountByChain=pt;exports.getSymmetricPoolShare=le;exports.getSymmetricWithdraw=Le;exports.getTHORNameCost=Ke;exports.isGasAsset=ie;exports.validateTHORName=Ye;
|
|
1
|
+
"use strict";var Te=Object.create;var D=Object.defineProperty;var ve=Object.getOwnPropertyDescriptor;var Se=Object.getOwnPropertyNames;var $e=Object.getPrototypeOf,Re=Object.prototype.hasOwnProperty;var Ie=(r,e,t)=>e in r?D(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t;var Be=(r,e,t,s)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of Se(e))!Re.call(r,n)&&n!==t&&D(r,n,{get:()=>e[n],enumerable:!(s=ve(e,n))||s.enumerable});return r};var Ee=(r,e,t)=>(t=r!=null?Te($e(r)):{},Be(e||!r||!r.__esModule?D(t,"default",{value:r,enumerable:!0}):t,r));var p=(r,e,t)=>(Ie(r,typeof e!="symbol"?e+"":e,t),t),Oe=(r,e,t)=>{if(!e.has(r))throw TypeError("Cannot "+t)};var y=(r,e,t)=>{if(e.has(r))throw TypeError("Cannot add the same private member more than once");e instanceof WeakSet?e.add(r):e.set(r,t)};var d=(r,e,t)=>(Oe(r,e,"access private method"),t);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const i=require("@swapkit/types"),Me="0x313ce567",re=async({chain:r,to:e})=>{try{const{result:t}=await ge.post(i.ChainToRPC[r],{headers:{accept:"*/*","content-type":"application/json","cache-control":"no-cache"},body:JSON.stringify({id:44,jsonrpc:"2.0",method:"eth_call",params:[{to:e.toLowerCase(),data:Me},"latest"]})});return parseInt(BigInt(t).toString())}catch(t){return console.error(t),i.BaseDecimal[r]}},Ve=async r=>{if(r===i.Chain.Ethereum)return i.BaseDecimal.ETH;const[,e]=r.split("-");return e!=null&&e.startsWith("0x")?re({chain:i.Chain.Ethereum,to:e}):i.BaseDecimal.ETH},qe=async r=>{const[,e]=r.split("-");return e!=null&&e.startsWith("0x")?re({chain:i.Chain.Avalanche,to:e.toLowerCase()}):i.BaseDecimal.AVAX},ke=async r=>(r===i.Chain.BinanceSmartChain,i.BaseDecimal.BSC),ne=async({chain:r,symbol:e})=>{switch(r){case i.Chain.Ethereum:return Ve(e);case i.Chain.Avalanche:return qe(e);case i.Chain.BinanceSmartChain:return ke(e);default:return i.BaseDecimal[r]}},Pe={[i.FeeOption.Average]:1.2,[i.FeeOption.Fast]:1.5,[i.FeeOption.Fastest]:2},ie=({chain:r,symbol:e})=>{switch(r){case i.Chain.Bitcoin:case i.Chain.BitcoinCash:case i.Chain.Litecoin:case i.Chain.Dogecoin:case i.Chain.Binance:case i.Chain.Ethereum:case i.Chain.Avalanche:return e===r;case i.Chain.Arbitrum:case i.Chain.Optimism:return e==="ETH";case i.Chain.Maya:return e==="CACAO";case i.Chain.Kujira:return e==="KUJI";case i.Chain.Cosmos:return e==="ATOM";case i.Chain.Polygon:return e==="MATIC";case i.Chain.BinanceSmartChain:return e==="BNB";case i.Chain.THORChain:return e==="RUNE"}},ae=r=>{switch(r){case"ETH.THOR":return{identifier:"ETH.THOR-0xa5f2211b9b8170f694421f2046281775e8468044",decimal:18};case"ETH.vTHOR":return{identifier:"ETH.vTHOR-0x815c23eca83261b6ec689b60cc4a58b54bc24d8d",decimal:18};case i.Chain.Cosmos:return{identifier:"GAIA.ATOM",decimal:i.BaseDecimal[r]};case i.Chain.THORChain:return{identifier:"THOR.RUNE",decimal:i.BaseDecimal[r]};case i.Chain.BinanceSmartChain:return{identifier:"BSC.BNB",decimal:i.BaseDecimal[r]};case i.Chain.Maya:return{identifier:"MAYA.CACAO",decimal:i.BaseDecimal.MAYA};case"MAYA.MAYA":return{identifier:"MAYA.MAYA",decimal:4};case i.Chain.Kujira:case i.Chain.Arbitrum:case i.Chain.Optimism:case i.Chain.BitcoinCash:case i.Chain.Litecoin:case i.Chain.Dogecoin:case i.Chain.Binance:case i.Chain.Avalanche:case i.Chain.Polygon:case i.Chain.Bitcoin:case i.Chain.Ethereum:return{identifier:`${r}.${r}`,decimal:i.BaseDecimal[r]}}},oe=({chain:r,symbol:e})=>{if(e.includes("/"))return"Synth";switch(r){case i.Chain.Bitcoin:case i.Chain.BitcoinCash:case i.Chain.Dogecoin:case i.Chain.Litecoin:case i.Chain.Maya:case i.Chain.THORChain:return"Native";case i.Chain.Cosmos:return e==="ATOM"?"Native":i.Chain.Cosmos;case i.Chain.Kujira:return e===i.Chain.Kujira?"Native":i.Chain.Kujira;case i.Chain.Binance:return e===i.Chain.Binance?"Native":"BEP2";case i.Chain.BinanceSmartChain:return e===i.Chain.Binance?"Native":"BEP20";case i.Chain.Ethereum:return e===i.Chain.Ethereum?"Native":"ERC20";case i.Chain.Avalanche:return e===i.Chain.Avalanche?"Native":i.Chain.Avalanche;case i.Chain.Polygon:return e===i.Chain.Polygon?"Native":"POLYGON";case i.Chain.Arbitrum:return[i.Chain.Ethereum,i.Chain.Arbitrum].includes(e)?"Native":"ARBITRUM";case i.Chain.Optimism:return[i.Chain.Ethereum,i.Chain.Optimism].includes(e)?"Native":"OPTIMISM"}},xe=r=>{var c;const[e,...t]=r.split("."),s=r.includes("/"),n=t.join("."),a=(c=n==null?void 0:n.split("-"))==null?void 0:c[0];return{chain:e,symbol:n,ticker:a,synth:s}},Ne=new RegExp(/(.)\1{6}|\.ORG|\.NET|\.FINANCE|\.COM|WWW|HTTP|\\\\|\/\/|[\s$%:[\]]/,"gmi"),De=r=>r.filter(e=>!Ne.test(e.toString())&&!e.toString().includes("undefined")),ce=({liquidityUnits:r,poolUnits:e,runeDepth:t})=>{const s=m(r),n=m(e),a=m(t),c=s.mul(a),o=n.mul(n).mul(2),u=n.mul(s).mul(2),l=s.mul(s),h=n.mul(n).mul(n);return c.mul(o.sub(u).add(l)).div(h)},ue=({liquidityUnits:r,poolUnits:e,assetDepth:t})=>{const s=m(r),n=m(e),a=m(t),c=s.mul(a),o=n.mul(n).mul(2),u=n.mul(s).mul(2),l=s.mul(s),h=c.mul(o.sub(u).add(l)),g=n.mul(n).mul(n);return h.div(g)},je=({percent:r,runeDepth:e,liquidityUnits:t,poolUnits:s})=>ce({runeDepth:e,liquidityUnits:t,poolUnits:s}).mul(r),He=({percent:r,assetDepth:e,liquidityUnits:t,poolUnits:s})=>ue({assetDepth:e,liquidityUnits:t,poolUnits:s}).mul(r),m=r=>f.fromBigInt(BigInt(r),i.BaseDecimal.THOR),le=({liquidityUnits:r,poolUnits:e,runeDepth:t,assetDepth:s})=>({assetAmount:m(s).mul(r).div(e),runeAmount:m(t).mul(r).div(e)}),Le=({liquidityUnits:r,poolUnits:e,runeDepth:t,assetDepth:s,percent:n})=>Object.fromEntries(Object.entries(le({liquidityUnits:r,poolUnits:e,runeDepth:t,assetDepth:s})).map(([a,c])=>[a,c.mul(n)])),Fe=({runeDepth:r,poolUnits:e,assetDepth:t,liquidityUnits:s,runeAmount:n,assetAmount:a})=>{const c=new f({value:r,decimal:8}),o=new f({value:t,decimal:8}),u=new f({value:e,decimal:8}),l=new f({value:n,decimal:8}),h=new f({value:a,decimal:8}),g=l.mul(o),w=h.mul(c),x=l.mul(h),be=c.mul(o),Ce=u.mul(g.add(w.add(x.mul(2)))),we=g.add(w.add(be.mul(2))),J=Ce.div(we),N=m(s).add(J);if(J.getBaseValue("number")===0)return N.div(u).getBaseValue("number");const Ae=u.add(N);return N.div(Ae).getBaseValue("number")},Ue=({runeAmount:r,assetAmount:e,runeDepth:t,assetDepth:s})=>{if(r==="0"||e==="0"||t==="0"||s==="0")return 0;const n=m(t),a=m(s),c=m(e),o=m(r),u=c.mul(n).sub(a.mul(o)),l=a.mul(o).add(n.mul(a));return Math.abs(u.div(l).getBaseValue("number"))},We=({symbol:r,ticker:e,chain:t})=>t==="ETH"&&e!=="ETH"?`${e}-${r.slice(-3)}`:r,Ge=(r,e)=>{switch(r){case i.MemoType.LEAVE:case i.MemoType.BOND:{const{address:t}=e;return`${r}:${t}`}case i.MemoType.UNBOND:{const{address:t,unbondAmount:s}=e;return`${r}:${t}:${s*10**8}`}case i.MemoType.THORNAME_REGISTER:{const{name:t,chain:s,address:n,owner:a}=e;return`${r}:${t}:${s}:${n}${a?`:${a}`:""}`}case i.MemoType.DEPOSIT:{const{chain:t,symbol:s,address:n,singleSide:a}=e;return a?`${r}:${t}/${s}::t:0`:`${r}:${t}.${s}:${n||""}:t:0`}case i.MemoType.WITHDRAW:{const{chain:t,ticker:s,symbol:n,basisPoints:a,targetAssetString:c,singleSide:o}=e,u=!o&&c?`:${c}`:"",l=We({chain:t,symbol:n,ticker:s});return`${r}:${t}${o?"/":"."}${l}:${a}${u}`}case i.MemoType.OPEN_LOAN:case i.MemoType.CLOSE_LOAN:{const{asset:t,address:s}=e;return`${r}:${t}:${s}`}default:return""}},Ke=r=>{if(r<0)throw new Error("Invalid number of year");return 10+r},Ye=r=>{if(r.length>30)return!1;const e=/^[a-zA-Z0-9+_-]+$/g;return!!r.match(e)},ze=([r,e,t,s,n])=>`${r}'/${e}'/${t}'/${s}${typeof n!="number"?"":`/${n}`}`;class Q extends Error{constructor(e,t,s){const n=e.status||e.status===0?e.status:"",a=e.statusText||"",c=`${n} ${a}`.trim(),o=c?`status code ${c}`:"an unknown error";super(`Request failed with ${o}`),Object.defineProperty(this,"response",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"request",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"options",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.name="HTTPError",this.response=e,this.request=t,this.options=s}}class he extends Error{constructor(e){super("Request timed out"),Object.defineProperty(this,"request",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.name="TimeoutError",this.request=e}}const M=r=>r!==null&&typeof r=="object",O=(...r)=>{for(const e of r)if((!M(e)||Array.isArray(e))&&e!==void 0)throw new TypeError("The `options` argument must be an object");return K({},...r)},de=(r={},e={})=>{const t=new globalThis.Headers(r),s=e instanceof globalThis.Headers,n=new globalThis.Headers(e);for(const[a,c]of n.entries())s&&c==="undefined"||c===void 0?t.delete(a):t.set(a,c);return t},K=(...r)=>{let e={},t={};for(const s of r)if(Array.isArray(s))Array.isArray(e)||(e=[]),e=[...e,...s];else if(M(s)){for(let[n,a]of Object.entries(s))M(a)&&n in e&&(a=K(e[n],a)),e={...e,[n]:a};M(s.headers)&&(t=de(t,s.headers),e.headers=t)}return e},Je=(()=>{let r=!1,e=!1;const t=typeof globalThis.ReadableStream=="function",s=typeof globalThis.Request=="function";return t&&s&&(e=new globalThis.Request("https://empty.invalid",{body:new globalThis.ReadableStream,method:"POST",get duplex(){return r=!0,"half"}}).headers.has("Content-Type")),r&&!e})(),Qe=typeof globalThis.AbortController=="function",Xe=typeof globalThis.ReadableStream=="function",Ze=typeof globalThis.FormData=="function",me=["get","post","put","patch","head","delete"],et={json:"application/json",text:"text/*",formData:"multipart/form-data",arrayBuffer:"*/*",blob:"*/*"},j=2147483647,pe=Symbol("stop"),tt={json:!0,parseJson:!0,searchParams:!0,prefixUrl:!0,retry:!0,timeout:!0,hooks:!0,throwHttpErrors:!0,onDownloadProgress:!0,fetch:!0},st={method:!0,headers:!0,body:!0,mode:!0,credentials:!0,cache:!0,redirect:!0,referrer:!0,referrerPolicy:!0,integrity:!0,keepalive:!0,signal:!0,window:!0,dispatcher:!0,duplex:!0},rt=r=>me.includes(r)?r.toUpperCase():r,nt=["get","put","head","delete","options","trace"],it=[408,413,429,500,502,503,504],fe=[413,429,503],X={limit:2,methods:nt,statusCodes:it,afterStatusCodes:fe,maxRetryAfter:Number.POSITIVE_INFINITY,backoffLimit:Number.POSITIVE_INFINITY,delay:r=>.3*2**(r-1)*1e3},at=(r={})=>{if(typeof r=="number")return{...X,limit:r};if(r.methods&&!Array.isArray(r.methods))throw new Error("retry.methods must be an array");if(r.statusCodes&&!Array.isArray(r.statusCodes))throw new Error("retry.statusCodes must be an array");return{...X,...r,afterStatusCodes:fe}};async function ot(r,e,t,s){return new Promise((n,a)=>{const c=setTimeout(()=>{t&&t.abort(),a(new he(r))},s.timeout);s.fetch(r,e).then(n).catch(a).then(()=>{clearTimeout(c)})})}async function ct(r,{signal:e}){return new Promise((t,s)=>{e&&(e.throwIfAborted(),e.addEventListener("abort",n,{once:!0}));function n(){clearTimeout(a),s(e.reason)}const a=setTimeout(()=>{e==null||e.removeEventListener("abort",n),t()},r)})}const ut=(r,e)=>{const t={};for(const s in e)!(s in st)&&!(s in tt)&&!(s in r)&&(t[s]=e[s]);return t};class q{static create(e,t){const s=new q(e,t),n=async()=>{if(typeof s._options.timeout=="number"&&s._options.timeout>j)throw new RangeError(`The \`timeout\` option cannot be greater than ${j}`);await Promise.resolve();let o=await s._fetch();for(const u of s._options.hooks.afterResponse){const l=await u(s.request,s._options,s._decorateResponse(o.clone()));l instanceof globalThis.Response&&(o=l)}if(s._decorateResponse(o),!o.ok&&s._options.throwHttpErrors){let u=new Q(o,s.request,s._options);for(const l of s._options.hooks.beforeError)u=await l(u);throw u}if(s._options.onDownloadProgress){if(typeof s._options.onDownloadProgress!="function")throw new TypeError("The `onDownloadProgress` option must be a function");if(!Xe)throw new Error("Streams are not supported in your environment. `ReadableStream` is missing.");return s._stream(o.clone(),s._options.onDownloadProgress)}return o},c=s._options.retry.methods.includes(s.request.method.toLowerCase())?s._retry(n):n();for(const[o,u]of Object.entries(et))c[o]=async()=>{s.request.headers.set("accept",s.request.headers.get("accept")||u);const h=(await c).clone();if(o==="json"){if(h.status===204||(await h.clone().arrayBuffer()).byteLength===0)return"";if(t.parseJson)return t.parseJson(await h.text())}return h[o]()};return c}constructor(e,t={}){if(Object.defineProperty(this,"request",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"abortController",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_retryCount",{enumerable:!0,configurable:!0,writable:!0,value:0}),Object.defineProperty(this,"_input",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_options",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this._input=e,this._options={credentials:this._input.credentials||"same-origin",...t,headers:de(this._input.headers,t.headers),hooks:K({beforeRequest:[],beforeRetry:[],beforeError:[],afterResponse:[]},t.hooks),method:rt(t.method??this._input.method),prefixUrl:String(t.prefixUrl||""),retry:at(t.retry),throwHttpErrors:t.throwHttpErrors!==!1,timeout:t.timeout??1e4,fetch:t.fetch??globalThis.fetch.bind(globalThis)},typeof this._input!="string"&&!(this._input instanceof URL||this._input instanceof globalThis.Request))throw new TypeError("`input` must be a string, URL, or Request");if(this._options.prefixUrl&&typeof this._input=="string"){if(this._input.startsWith("/"))throw new Error("`input` must not begin with a slash when using `prefixUrl`");this._options.prefixUrl.endsWith("/")||(this._options.prefixUrl+="/"),this._input=this._options.prefixUrl+this._input}if(Qe){if(this.abortController=new globalThis.AbortController,this._options.signal){const s=this._options.signal;this._options.signal.addEventListener("abort",()=>{this.abortController.abort(s.reason)})}this._options.signal=this.abortController.signal}if(Je&&(this._options.duplex="half"),this.request=new globalThis.Request(this._input,this._options),this._options.searchParams){const n="?"+(typeof this._options.searchParams=="string"?this._options.searchParams.replace(/^\?/,""):new URLSearchParams(this._options.searchParams).toString()),a=this.request.url.replace(/(?:\?.*?)?(?=#|$)/,n);(Ze&&this._options.body instanceof globalThis.FormData||this._options.body instanceof URLSearchParams)&&!(this._options.headers&&this._options.headers["content-type"])&&this.request.headers.delete("content-type"),this.request=new globalThis.Request(new globalThis.Request(a,{...this.request}),this._options)}this._options.json!==void 0&&(this._options.body=JSON.stringify(this._options.json),this.request.headers.set("content-type",this._options.headers.get("content-type")??"application/json"),this.request=new globalThis.Request(this.request,{body:this._options.body}))}_calculateRetryDelay(e){if(this._retryCount++,this._retryCount<this._options.retry.limit&&!(e instanceof he)){if(e instanceof Q){if(!this._options.retry.statusCodes.includes(e.response.status))return 0;const s=e.response.headers.get("Retry-After");if(s&&this._options.retry.afterStatusCodes.includes(e.response.status)){let n=Number(s);return Number.isNaN(n)?n=Date.parse(s)-Date.now():n*=1e3,this._options.retry.maxRetryAfter!==void 0&&n>this._options.retry.maxRetryAfter?0:n}if(e.response.status===413)return 0}const t=this._options.retry.delay(this._retryCount);return Math.min(this._options.retry.backoffLimit,t)}return 0}_decorateResponse(e){return this._options.parseJson&&(e.json=async()=>this._options.parseJson(await e.text())),e}async _retry(e){try{return await e()}catch(t){const s=Math.min(this._calculateRetryDelay(t),j);if(s!==0&&this._retryCount>0){await ct(s,{signal:this._options.signal});for(const n of this._options.hooks.beforeRetry)if(await n({request:this.request,options:this._options,error:t,retryCount:this._retryCount})===pe)return;return this._retry(e)}throw t}}async _fetch(){for(const t of this._options.hooks.beforeRequest){const s=await t(this.request,this._options);if(s instanceof Request){this.request=s;break}if(s instanceof Response)return s}const e=ut(this.request,this._options);return this._options.timeout===!1?this._options.fetch(this.request.clone(),e):ot(this.request.clone(),e,this.abortController,this._options)}_stream(e,t){const s=Number(e.headers.get("content-length"))||0;let n=0;return e.status===204?(t&&t({percent:1,totalBytes:s,transferredBytes:n},new Uint8Array),new globalThis.Response(null,{status:e.status,statusText:e.statusText,headers:e.headers})):new globalThis.Response(new globalThis.ReadableStream({async start(a){const c=e.body.getReader();t&&t({percent:0,transferredBytes:0,totalBytes:s},new Uint8Array);async function o(){const{done:u,value:l}=await c.read();if(u){a.close();return}if(t){n+=l.byteLength;const h=s===0?0:n/s;t({percent:h,transferredBytes:n,totalBytes:s},l)}a.enqueue(l),await o()}await o()}}),{status:e.status,statusText:e.statusText,headers:e.headers})}}/*! MIT License © Sindre Sorhus */const L=r=>{const e=(t,s)=>q.create(t,O(r,s));for(const t of me)e[t]=(s,n)=>q.create(s,O(r,n,{method:t}));return e.create=t=>L(O(t)),e.extend=t=>L(O(r,t)),e.stop=pe,e},lt=L(),ht=lt,dt=typeof window<"u"?{}:{referrer:"https://sk.thorswap.net",referer:"https://sk.thorswap.net"},Z=ht.create({headers:dt}),ge={get:(r,e)=>Z.get(r,e).json(),post:(r,e)=>Z.post(r,e).json()},ee=Object.values(i.Chain),mt=(r="")=>{const e=r.toUpperCase(),[t]=e.split(".");if(ee.includes(t))return!0;const[s]=e.split("/");if(ee.includes(s))return!0;throw new Error(`Invalid identifier: ${r}. Expected format: <Chain>.<Ticker> or <Chain>.<Ticker>-<ContractAddress>`)},R=8,A=r=>10n**BigInt(r),v=r=>Math.log10(parseFloat(r.toString()));function I({value:r,bigIntDecimal:e=R,decimal:t=R}){const s=r<0n;let n=r.toString().substring(s?1:0);const a=t-(n.length-1);a>0&&(n="0".repeat(a)+n);const c=n.length-t;let o=n.slice(-t);return parseInt(o[e])>=5?o=`${o.substring(0,e-1)}${(parseInt(o[e-1])+1).toString()}`:o=o.substring(0,e),`${s?"-":""}${n.slice(0,c)}.${o}`.replace(/\.?0*$/,"")}var b,S,k,_e,P,ye,B,F,C,$,E,U;const z=class z{constructor(e){y(this,b);y(this,k);y(this,P);y(this,B);y(this,C);y(this,E);p(this,"decimalMultiplier",10n**8n);p(this,"bigIntValue",0n);p(this,"decimal");const t=H(e);this.decimal=typeof e=="object"?e.decimal:void 0,this.decimalMultiplier=A(Math.max(d(this,E,U).call(this,d(this,C,$).call(this,t)),this.decimal||0)),d(this,k,_e).call(this,t)}static fromBigInt(e,t){return new z({decimal:t,value:I({value:e,bigIntDecimal:t,decimal:t})})}static shiftDecimals({value:e,from:t,to:s}){return this.fromBigInt(e.getBaseValue("bigint")*A(s)/A(t),s)}set(e){return new this.constructor({decimal:this.decimal,value:e,identifier:this.toString()})}add(...e){return d(this,b,S).call(this,"add",...e)}sub(...e){return d(this,b,S).call(this,"sub",...e)}mul(...e){return d(this,b,S).call(this,"mul",...e)}div(...e){return d(this,b,S).call(this,"div",...e)}gt(e){return this.bigIntValue>this.getBigIntValue(e)}gte(e){return this.bigIntValue>=this.getBigIntValue(e)}lt(e){return this.bigIntValue<this.getBigIntValue(e)}lte(e){return this.bigIntValue<=this.getBigIntValue(e)}eqValue(e){return this.bigIntValue===this.getBigIntValue(e)}getValue(e){const t=this.formatBigIntToSafeValue(this.bigIntValue,this.decimal||v(this.decimalMultiplier));switch(e){case"number":return Number(t);case"string":return t;default:return this.bigIntValue*BigInt(this.decimal||8n)/this.decimalMultiplier}}getBaseValue(e){const t=this.decimalMultiplier/A(this.decimal||i.BaseDecimal.THOR),s=this.bigIntValue/t;switch(e){case"number":return Number(s);case"string":return s.toString();default:return s}}getBigIntValue(e,t){if(!t&&typeof e=="object")return e.bigIntValue;const s=H(e),n=d(this,C,$).call(this,s);return n==="0"||n==="undefined"?0n:d(this,B,F).call(this,n,t)}formatBigIntToSafeValue(e,t){const s=t||this.decimal||R,n=Math.max(s,v(this.decimalMultiplier)),a=e<0n,c=e.toString().substring(a?1:0),o=n-(c.length-1),u=o>0?"0".repeat(o)+c:c,l=u.length-n;let h=u.slice(-n);return parseInt(h[s])>=5?h=`${h.substring(0,s-1)}${(parseInt(h[s-1])+1).toString()}`:h=h.substring(0,s),`${a?"-":""}${u.slice(0,l)}.${h}`.replace(/\.?0*$/,"")}toSignificant(e=6){const[t,s]=this.getValue("string").split("."),n=t||"",a=s||"";if((parseInt(n)?n.length+a.length:a.length)<=e)return this.getValue("string");if(n.length>=e)return n.slice(0,e).padEnd(n.length,"0");if(parseInt(n))return`${n}.${a.slice(0,e-n.length)}`.padEnd(e-n.length,"0");const o=parseInt(a),u=`${o}`.slice(0,e);return`0.${u.padStart(a.length-`${o}`.length+u.length,"0")}`}toFixed(e=6){const[t,s]=this.getValue("string").split("."),n=t||"",a=s||"";if(parseInt(n))return`${n}.${a.slice(0,e)}`.padEnd(e,"0");const c=parseInt(a),o=`${c}`.slice(0,e);return`0.${o.padStart(a.length-`${c}`.length+o.length,"0")}`}toAbbreviation(e=2){const t=this.getValue("number"),s=["","K","M","B","T","Q","Qi","S"],n=Math.floor(Math.log10(Math.abs(t))/3),a=s[n];if(!a)return this.getValue("string");const c=10**(n*3);return`${(t/c).toFixed(e)}${a}`}toCurrency(e="$",{currencyPosition:t="start",decimal:s=2,decimalSeparator:n=".",thousandSeparator:a=","}={}){const c=this.getValue("number"),[o,u=""]=c.toFixed(6).split("."),l=o.replace(/\B(?=(\d{3})+(?!\d))/g,a),h=!o&&!u?"0.00":o==="0"?`${parseFloat(`0.${u}`)}`.replace(".",n):`${l}${u?`${n}${u.slice(0,s)}`:""}`;return`${t==="start"?e:""}${h}${t==="end"?e:""}`}};b=new WeakSet,S=function(e,...t){const s=d(this,P,ye).call(this,this,...t),n=A(s),a=t.reduce((o,u)=>{const l=this.getBigIntValue(u,s);switch(e){case"add":return o+l;case"sub":return o-l;case"mul":return o*l/n;case"div":{if(l===0n)throw new RangeError("Division by zero");return o*n/l}default:return o}},this.bigIntValue*n/this.decimalMultiplier),c=I({bigIntDecimal:s,decimal:Math.max(s,v(this.decimalMultiplier)),value:a});return new this.constructor({decimal:this.decimal,value:c,identifier:this.toString()})},k=new WeakSet,_e=function(e){const t=d(this,C,$).call(this,e)||"0";this.bigIntValue=d(this,B,F).call(this,t)},P=new WeakSet,ye=function(...e){const t=e.map(s=>typeof s=="object"?s.decimal||v(s.decimalMultiplier):d(this,E,U).call(this,d(this,C,$).call(this,s))).filter(Boolean);return Math.max(...t,R)},B=new WeakSet,F=function(e,t){const s=t?A(t):this.decimalMultiplier,n=v(s),[a="",c=""]=e.split(".");return BigInt(`${a}${c.padEnd(n,"0")}`)},C=new WeakSet,$=function(e){const s=`${typeof e=="number"?Number(e).toLocaleString("fullwide",{useGrouping:!1,maximumFractionDigits:20}):H(e)}`.replaceAll(",",".").split(".");return s.length>1?`${s.slice(0,-1).join("")}.${s.at(-1)}`:s[0]},E=new WeakSet,U=function(e){var s;const t=((s=e.split(".")[1])==null?void 0:s.length)||0;return Math.max(t,R)};let T=z;function H(r){return typeof r=="object"?"getValue"in r?r.getValue("string"):r.value:r}const V=(r,e)=>typeof r=="bigint"?I({value:r,bigIntDecimal:e,decimal:e}):r;let W;const te=r=>{if(!W)throw new Error("Static assets not loaded, call await AssetValue.loadStaticAssets() first");return W.get(r.toUpperCase())||{decimal:i.BaseDecimal.THOR,identifier:""}},se=async(r,e=0)=>{mt(r);const t=await ne(G(r)),s=V(e,t);return new _({decimal:t,value:s,identifier:r})};class _ extends T{constructor(t){super(t.value instanceof T?t.value:{decimal:t.decimal,value:t.value});p(this,"address");p(this,"chain");p(this,"isSynthetic",!1);p(this,"isGasAsset",!1);p(this,"symbol");p(this,"ticker");p(this,"type");const s="identifier"in t?t.identifier:`${t.chain}.${t.symbol}`,n=G(s);this.type=oe(n),this.chain=n.chain,this.ticker=n.ticker,this.symbol=n.symbol,this.address=n.address,this.isSynthetic=n.isSynthetic,this.isGasAsset=n.isGasAsset}get assetValue(){return`${this.getValue("string")} ${this.ticker}`}toString(t=!1){const s=this.isSynthetic?this.symbol.split("-")[0]:`${this.chain}.${this.ticker}`;return t?s:`${this.chain}.${this.symbol}`}eq({chain:t,symbol:s}){return this.chain===t&&this.symbol===s}static async fromString(t,s=0){return se(t,s)}static fromStringSync(t,s=0){const{isSynthetic:n}=G(t),{decimal:a,identifier:c}=te(t),o=V(s,a);return c?new _({decimal:a,identifier:c,value:o}):n?new _({decimal:8,identifier:t,value:o}):void 0}static async fromIdentifier(t,s=0){return se(t,s)}static fromIdentifierSync(t,s=0){const{decimal:n,identifier:a}=te(t),c=V(s,n);return new _({decimal:n,identifier:a,value:c})}static fromChainOrSignature(t,s=0){const{decimal:n,identifier:a}=ae(t),c=V(s,n);return new _({value:c,decimal:n,identifier:a})}static async loadStaticAssets(){return new Promise(async(t,s)=>{try{const{ThorchainList:n,NativeList:a,...c}=await import("@swapkit/tokens");W=[a,...Object.values(c)].reduce((u,{tokens:l})=>(l.forEach(({identifier:h,chain:g,...w})=>{const x="decimals"in w?w.decimals:i.BaseDecimal[g];u.set(h,{identifier:h,decimal:x})}),u),new Map),t({ok:!0})}catch(n){console.error(n),s({ok:!1,error:n,message:"Couldn't load static assets. Ensure you have installed @swapkit/tokens package"})}})}}const pt=r=>{const e=_.fromChainOrSignature(r);switch(r){case i.Chain.Bitcoin:case i.Chain.Litecoin:case i.Chain.BitcoinCash:return e.set(10001e-8);case i.Chain.Dogecoin:return e.set(1.00000001);case i.Chain.Avalanche:case i.Chain.Ethereum:return e.set(1e-8);case i.Chain.THORChain:case i.Chain.Maya:return e.set(0);default:return e.set(1e-8)}},G=r=>{const e=r.slice(0,14).includes("/"),[t,s]=r.split(".").pop().split("/"),n=r.includes(".")&&!e?r:`${i.Chain.THORChain}.${s}`,[a,c]=n.split("."),[o,u]=(e?s:c).split("-");return{address:u==null?void 0:u.toLowerCase(),chain:a,isGasAsset:ie({chain:a,symbol:c}),isSynthetic:e,symbol:(e?`${t}/`:"")+(u?`${o}-${(u==null?void 0:u.toLowerCase())??""}`:c),ticker:o}},ft={core_wallet_connection_not_found:10001,core_estimated_max_spendable_chain_not_supported:10002,core_extend_error:10003,core_inbound_data_not_found:10004,core_approve_asset_address_or_from_not_found:10005,core_chain_halted:10099,core_wallet_xdefi_not_installed:10101,core_wallet_evmwallet_not_installed:10102,core_wallet_walletconnect_not_installed:10103,core_wallet_keystore_not_installed:10104,core_wallet_ledger_not_installed:10105,core_wallet_trezor_not_installed:10106,core_wallet_keplr_not_installed:10107,core_wallet_okx_not_installed:10108,core_swap_invalid_params:10200,core_swap_route_not_complete:10201,core_swap_asset_not_recognized:10202,core_swap_contract_not_found:10203,core_swap_route_transaction_not_found:10204,core_swap_contract_not_supported:10205,core_swap_transaction_error:10206,core_swap_quote_mode_not_supported:10207,core_transaction_deposit_error:10301,core_transaction_create_liquidity_rune_error:10302,core_transaction_create_liquidity_asset_error:10303,core_transaction_create_liquidity_invalid_params:10304,core_transaction_add_liquidity_invalid_params:10305,core_transaction_add_liquidity_no_rune_address:10306,core_transaction_add_liquidity_rune_error:10307,core_transaction_add_liquidity_asset_error:10308,core_transaction_withdraw_error:10309,core_transaction_deposit_to_pool_error:10310,core_transaction_deposit_insufficient_funds_error:10311,core_transaction_deposit_gas_error:10312,core_transaction_deposit_server_error:10313,wallet_ledger_connection_error:20001,helpers_number_different_decimals:99101};class Y extends Error{constructor(e,t){console.error(t),super(e,{cause:{code:ft[e],message:e}}),Object.setPrototypeOf(this,Y.prototype)}}class f extends T{eq(e){return this.eqValue(e)}static fromBigInt(e,t){return new f({decimal:t,value:I({value:e,bigIntDecimal:t,decimal:t})})}}exports.AssetValue=_;exports.BigIntArithmetics=T;exports.RequestClient=ge;exports.SwapKitError=Y;exports.SwapKitNumber=f;exports.assetFromString=xe;exports.derivationPathToString=ze;exports.filterAssets=De;exports.formatBigIntToSafeValue=I;exports.gasFeeMultiplier=Pe;exports.getAssetType=oe;exports.getAsymmetricAssetShare=ue;exports.getAsymmetricAssetWithdrawAmount=He;exports.getAsymmetricRuneShare=ce;exports.getAsymmetricRuneWithdrawAmount=je;exports.getCommonAssetInfo=ae;exports.getDecimal=ne;exports.getEstimatedPoolShare=Fe;exports.getLiquiditySlippage=Ue;exports.getMemoFor=Ge;exports.getMinAmountByChain=pt;exports.getSymmetricPoolShare=le;exports.getSymmetricWithdraw=Le;exports.getTHORNameCost=Ke;exports.isGasAsset=ie;exports.validateTHORName=Ye;
|
package/dist/index.d.ts
CHANGED
|
@@ -72,18 +72,6 @@ export declare class BigIntArithmetics {
|
|
|
72
72
|
to: number;
|
|
73
73
|
}): BigIntArithmetics;
|
|
74
74
|
constructor(params: SKBigIntParams);
|
|
75
|
-
/**
|
|
76
|
-
* @deprecated Use `getBaseValue('string')` instead
|
|
77
|
-
*/
|
|
78
|
-
get baseValue(): string;
|
|
79
|
-
/**
|
|
80
|
-
* @deprecated Use `getBaseValue('number')` instead
|
|
81
|
-
*/
|
|
82
|
-
get baseValueNumber(): number;
|
|
83
|
-
/**
|
|
84
|
-
* @deprecated Use `getBaseValue('bigint')` instead
|
|
85
|
-
*/
|
|
86
|
-
get baseValueBigInt(): bigint;
|
|
87
75
|
set(value: SKBigIntParams): this;
|
|
88
76
|
add(...args: InitialisationValueType[]): this;
|
|
89
77
|
sub(...args: InitialisationValueType[]): this;
|
|
@@ -101,6 +89,12 @@ export declare class BigIntArithmetics {
|
|
|
101
89
|
toSignificant(significantDigits?: number): string;
|
|
102
90
|
toFixed(fixedDigits?: number): string;
|
|
103
91
|
toAbbreviation(digits?: number): string;
|
|
92
|
+
toCurrency(currency?: string, { currencyPosition, decimal, decimalSeparator, thousandSeparator, }?: {
|
|
93
|
+
currencyPosition?: string | undefined;
|
|
94
|
+
decimal?: number | undefined;
|
|
95
|
+
decimalSeparator?: string | undefined;
|
|
96
|
+
thousandSeparator?: string | undefined;
|
|
97
|
+
}): string;
|
|
104
98
|
}
|
|
105
99
|
|
|
106
100
|
export declare type CommonAssetString = 'MAYA.MAYA' | 'ETH.THOR' | 'ETH.vTHOR' | Chain;
|
package/dist/index.es.js
CHANGED
|
@@ -38,14 +38,14 @@ const At = "0x313ce567", nt = async ({ chain: s, to: t }) => {
|
|
|
38
38
|
}, vt = async (s) => {
|
|
39
39
|
const [, t] = s.split("-");
|
|
40
40
|
return t != null && t.startsWith("0x") ? nt({ chain: o.Avalanche, to: t.toLowerCase() }) : d.AVAX;
|
|
41
|
-
},
|
|
41
|
+
}, $t = async (s) => s === o.BinanceSmartChain ? d.BSC : d.BSC, Rt = async ({ chain: s, symbol: t }) => {
|
|
42
42
|
switch (s) {
|
|
43
43
|
case o.Ethereum:
|
|
44
44
|
return Tt(t);
|
|
45
45
|
case o.Avalanche:
|
|
46
46
|
return vt(t);
|
|
47
47
|
case o.BinanceSmartChain:
|
|
48
|
-
return
|
|
48
|
+
return $t(t);
|
|
49
49
|
default:
|
|
50
50
|
return d[s];
|
|
51
51
|
}
|
|
@@ -53,7 +53,7 @@ const At = "0x313ce567", nt = async ({ chain: s, to: t }) => {
|
|
|
53
53
|
[L.Average]: 1.2,
|
|
54
54
|
[L.Fast]: 1.5,
|
|
55
55
|
[L.Fastest]: 2
|
|
56
|
-
},
|
|
56
|
+
}, St = ({ chain: s, symbol: t }) => {
|
|
57
57
|
switch (s) {
|
|
58
58
|
case o.Bitcoin:
|
|
59
59
|
case o.BitcoinCash:
|
|
@@ -139,39 +139,39 @@ const At = "0x313ce567", nt = async ({ chain: s, to: t }) => {
|
|
|
139
139
|
return [o.Ethereum, o.Optimism].includes(t) ? "Native" : "OPTIMISM";
|
|
140
140
|
}
|
|
141
141
|
}, se = (s) => {
|
|
142
|
-
var
|
|
143
|
-
const [t, ...e] = s.split("."), r = s.includes("/"), n = e.join("."), i = (
|
|
142
|
+
var c;
|
|
143
|
+
const [t, ...e] = s.split("."), r = s.includes("/"), n = e.join("."), i = (c = n == null ? void 0 : n.split("-")) == null ? void 0 : c[0];
|
|
144
144
|
return { chain: t, symbol: n, ticker: i, synth: r };
|
|
145
145
|
}, Et = new RegExp(
|
|
146
146
|
/(.)\1{6}|\.ORG|\.NET|\.FINANCE|\.COM|WWW|HTTP|\\\\|\/\/|[\s$%:[\]]/,
|
|
147
147
|
"gmi"
|
|
148
148
|
), ne = (s) => s.filter(
|
|
149
149
|
(t) => !Et.test(t.toString()) && !t.toString().includes("undefined")
|
|
150
|
-
),
|
|
150
|
+
), Ot = ({
|
|
151
151
|
liquidityUnits: s,
|
|
152
152
|
poolUnits: t,
|
|
153
153
|
runeDepth: e
|
|
154
154
|
}) => {
|
|
155
|
-
const r = p(s), n = p(t), i = p(e),
|
|
156
|
-
return
|
|
157
|
-
},
|
|
155
|
+
const r = p(s), n = p(t), i = p(e), c = r.mul(i), a = n.mul(n).mul(2), u = n.mul(r).mul(2), l = r.mul(r), h = n.mul(n).mul(n);
|
|
156
|
+
return c.mul(a.sub(u).add(l)).div(h);
|
|
157
|
+
}, Bt = ({
|
|
158
158
|
liquidityUnits: s,
|
|
159
159
|
poolUnits: t,
|
|
160
160
|
assetDepth: e
|
|
161
161
|
}) => {
|
|
162
|
-
const r = p(s), n = p(t), i = p(e),
|
|
162
|
+
const r = p(s), n = p(t), i = p(e), c = r.mul(i), a = n.mul(n).mul(2), u = n.mul(r).mul(2), l = r.mul(r), h = c.mul(a.sub(u).add(l)), _ = n.mul(n).mul(n);
|
|
163
163
|
return h.div(_);
|
|
164
164
|
}, ie = ({
|
|
165
165
|
percent: s,
|
|
166
166
|
runeDepth: t,
|
|
167
167
|
liquidityUnits: e,
|
|
168
168
|
poolUnits: r
|
|
169
|
-
}) =>
|
|
169
|
+
}) => Ot({ runeDepth: t, liquidityUnits: e, poolUnits: r }).mul(s), oe = ({
|
|
170
170
|
percent: s,
|
|
171
171
|
assetDepth: t,
|
|
172
172
|
liquidityUnits: e,
|
|
173
173
|
poolUnits: r
|
|
174
|
-
}) =>
|
|
174
|
+
}) => Bt({ assetDepth: t, liquidityUnits: e, poolUnits: r }).mul(s), p = (s) => b.fromBigInt(BigInt(s), d.THOR), Mt = ({
|
|
175
175
|
liquidityUnits: s,
|
|
176
176
|
poolUnits: t,
|
|
177
177
|
runeDepth: e,
|
|
@@ -186,8 +186,8 @@ const At = "0x313ce567", nt = async ({ chain: s, to: t }) => {
|
|
|
186
186
|
assetDepth: r,
|
|
187
187
|
percent: n
|
|
188
188
|
}) => Object.fromEntries(
|
|
189
|
-
Object.entries(
|
|
190
|
-
([i,
|
|
189
|
+
Object.entries(Mt({ liquidityUnits: s, poolUnits: t, runeDepth: e, assetDepth: r })).map(
|
|
190
|
+
([i, c]) => [i, c.mul(n)]
|
|
191
191
|
)
|
|
192
192
|
), ce = ({
|
|
193
193
|
runeDepth: s,
|
|
@@ -197,7 +197,7 @@ const At = "0x313ce567", nt = async ({ chain: s, to: t }) => {
|
|
|
197
197
|
runeAmount: n,
|
|
198
198
|
assetAmount: i
|
|
199
199
|
}) => {
|
|
200
|
-
const
|
|
200
|
+
const c = new b({ value: s, decimal: 8 }), a = new b({ value: e, decimal: 8 }), u = new b({ value: t, decimal: 8 }), l = new b({ value: n, decimal: 8 }), h = new b({ value: i, decimal: 8 }), _ = l.mul(a), v = h.mul(c), j = l.mul(h), mt = c.mul(a), pt = u.mul(_.add(v.add(j.mul(2)))), ft = _.add(v.add(mt.mul(2))), Q = pt.div(ft), H = p(r).add(Q);
|
|
201
201
|
if (Q.getBaseValue("number") === 0)
|
|
202
202
|
return H.div(u).getBaseValue("number");
|
|
203
203
|
const _t = u.add(H);
|
|
@@ -210,9 +210,9 @@ const At = "0x313ce567", nt = async ({ chain: s, to: t }) => {
|
|
|
210
210
|
}) => {
|
|
211
211
|
if (s === "0" || t === "0" || e === "0" || r === "0")
|
|
212
212
|
return 0;
|
|
213
|
-
const n = p(e), i = p(r),
|
|
213
|
+
const n = p(e), i = p(r), c = p(t), a = p(s), u = c.mul(n).sub(i.mul(a)), l = i.mul(a).add(n.mul(i));
|
|
214
214
|
return Math.abs(u.div(l).getBaseValue("number"));
|
|
215
|
-
},
|
|
215
|
+
}, Vt = ({
|
|
216
216
|
symbol: s,
|
|
217
217
|
ticker: t,
|
|
218
218
|
chain: e
|
|
@@ -236,8 +236,8 @@ const At = "0x313ce567", nt = async ({ chain: s, to: t }) => {
|
|
|
236
236
|
return i ? `${s}:${e}/${r}::t:0` : `${s}:${e}.${r}:${n || ""}:t:0`;
|
|
237
237
|
}
|
|
238
238
|
case g.WITHDRAW: {
|
|
239
|
-
const { chain: e, ticker: r, symbol: n, basisPoints: i, targetAssetString:
|
|
240
|
-
return `${s}:${e}${
|
|
239
|
+
const { chain: e, ticker: r, symbol: n, basisPoints: i, targetAssetString: c, singleSide: a } = t, u = !a && c ? `:${c}` : "", l = Vt({ chain: e, symbol: n, ticker: r });
|
|
240
|
+
return `${s}:${e}${a ? "/" : "."}${l}:${i}${u}`;
|
|
241
241
|
}
|
|
242
242
|
case g.OPEN_LOAN:
|
|
243
243
|
case g.CLOSE_LOAN: {
|
|
@@ -259,8 +259,8 @@ const At = "0x313ce567", nt = async ({ chain: s, to: t }) => {
|
|
|
259
259
|
}, me = ([s, t, e, r, n]) => `${s}'/${t}'/${e}'/${r}${typeof n != "number" ? "" : `/${n}`}`;
|
|
260
260
|
class X extends Error {
|
|
261
261
|
constructor(t, e, r) {
|
|
262
|
-
const n = t.status || t.status === 0 ? t.status : "", i = t.statusText || "",
|
|
263
|
-
super(`Request failed with ${
|
|
262
|
+
const n = t.status || t.status === 0 ? t.status : "", i = t.statusText || "", c = `${n} ${i}`.trim(), a = c ? `status code ${c}` : "an unknown error";
|
|
263
|
+
super(`Request failed with ${a}`), Object.defineProperty(this, "response", {
|
|
264
264
|
enumerable: !0,
|
|
265
265
|
configurable: !0,
|
|
266
266
|
writable: !0,
|
|
@@ -288,25 +288,25 @@ class it extends Error {
|
|
|
288
288
|
}), this.name = "TimeoutError", this.request = t;
|
|
289
289
|
}
|
|
290
290
|
}
|
|
291
|
-
const
|
|
291
|
+
const V = (s) => s !== null && typeof s == "object", M = (...s) => {
|
|
292
292
|
for (const t of s)
|
|
293
|
-
if ((!
|
|
293
|
+
if ((!V(t) || Array.isArray(t)) && t !== void 0)
|
|
294
294
|
throw new TypeError("The `options` argument must be an object");
|
|
295
295
|
return J({}, ...s);
|
|
296
296
|
}, ot = (s = {}, t = {}) => {
|
|
297
297
|
const e = new globalThis.Headers(s), r = t instanceof globalThis.Headers, n = new globalThis.Headers(t);
|
|
298
|
-
for (const [i,
|
|
299
|
-
r &&
|
|
298
|
+
for (const [i, c] of n.entries())
|
|
299
|
+
r && c === "undefined" || c === void 0 ? e.delete(i) : e.set(i, c);
|
|
300
300
|
return e;
|
|
301
301
|
}, J = (...s) => {
|
|
302
302
|
let t = {}, e = {};
|
|
303
303
|
for (const r of s)
|
|
304
304
|
if (Array.isArray(r))
|
|
305
305
|
Array.isArray(t) || (t = []), t = [...t, ...r];
|
|
306
|
-
else if (
|
|
306
|
+
else if (V(r)) {
|
|
307
307
|
for (let [n, i] of Object.entries(r))
|
|
308
|
-
|
|
309
|
-
|
|
308
|
+
V(i) && n in t && (i = J(t[n], i)), t = { ...t, [n]: i };
|
|
309
|
+
V(r.headers) && (e = ot(e, r.headers), t.headers = e);
|
|
310
310
|
}
|
|
311
311
|
return t;
|
|
312
312
|
}, kt = (() => {
|
|
@@ -379,11 +379,11 @@ const M = (s) => s !== null && typeof s == "object", V = (...s) => {
|
|
|
379
379
|
};
|
|
380
380
|
async function Wt(s, t, e, r) {
|
|
381
381
|
return new Promise((n, i) => {
|
|
382
|
-
const
|
|
382
|
+
const c = setTimeout(() => {
|
|
383
383
|
e && e.abort(), i(new it(s));
|
|
384
384
|
}, r.timeout);
|
|
385
385
|
r.fetch(s, t).then(n).catch(i).then(() => {
|
|
386
|
-
clearTimeout(
|
|
386
|
+
clearTimeout(c);
|
|
387
387
|
});
|
|
388
388
|
});
|
|
389
389
|
}
|
|
@@ -410,13 +410,13 @@ class q {
|
|
|
410
410
|
if (typeof r._options.timeout == "number" && r._options.timeout > D)
|
|
411
411
|
throw new RangeError(`The \`timeout\` option cannot be greater than ${D}`);
|
|
412
412
|
await Promise.resolve();
|
|
413
|
-
let
|
|
413
|
+
let a = await r._fetch();
|
|
414
414
|
for (const u of r._options.hooks.afterResponse) {
|
|
415
|
-
const l = await u(r.request, r._options, r._decorateResponse(
|
|
416
|
-
l instanceof globalThis.Response && (
|
|
415
|
+
const l = await u(r.request, r._options, r._decorateResponse(a.clone()));
|
|
416
|
+
l instanceof globalThis.Response && (a = l);
|
|
417
417
|
}
|
|
418
|
-
if (r._decorateResponse(
|
|
419
|
-
let u = new X(
|
|
418
|
+
if (r._decorateResponse(a), !a.ok && r._options.throwHttpErrors) {
|
|
419
|
+
let u = new X(a, r.request, r._options);
|
|
420
420
|
for (const l of r._options.hooks.beforeError)
|
|
421
421
|
u = await l(u);
|
|
422
422
|
throw u;
|
|
@@ -426,23 +426,23 @@ class q {
|
|
|
426
426
|
throw new TypeError("The `onDownloadProgress` option must be a function");
|
|
427
427
|
if (!xt)
|
|
428
428
|
throw new Error("Streams are not supported in your environment. `ReadableStream` is missing.");
|
|
429
|
-
return r._stream(
|
|
429
|
+
return r._stream(a.clone(), r._options.onDownloadProgress);
|
|
430
430
|
}
|
|
431
|
-
return
|
|
432
|
-
},
|
|
433
|
-
for (const [
|
|
434
|
-
a
|
|
431
|
+
return a;
|
|
432
|
+
}, c = r._options.retry.methods.includes(r.request.method.toLowerCase()) ? r._retry(n) : n();
|
|
433
|
+
for (const [a, u] of Object.entries(Nt))
|
|
434
|
+
c[a] = async () => {
|
|
435
435
|
r.request.headers.set("accept", r.request.headers.get("accept") || u);
|
|
436
|
-
const h = (await
|
|
437
|
-
if (
|
|
436
|
+
const h = (await c).clone();
|
|
437
|
+
if (a === "json") {
|
|
438
438
|
if (h.status === 204 || (await h.clone().arrayBuffer()).byteLength === 0)
|
|
439
439
|
return "";
|
|
440
440
|
if (e.parseJson)
|
|
441
441
|
return e.parseJson(await h.text());
|
|
442
442
|
}
|
|
443
|
-
return h[
|
|
443
|
+
return h[a]();
|
|
444
444
|
};
|
|
445
|
-
return
|
|
445
|
+
return c;
|
|
446
446
|
}
|
|
447
447
|
// eslint-disable-next-line complexity
|
|
448
448
|
constructor(t, e = {}) {
|
|
@@ -575,10 +575,10 @@ class q {
|
|
|
575
575
|
headers: t.headers
|
|
576
576
|
})) : new globalThis.Response(new globalThis.ReadableStream({
|
|
577
577
|
async start(i) {
|
|
578
|
-
const
|
|
578
|
+
const c = t.body.getReader();
|
|
579
579
|
e && e({ percent: 0, transferredBytes: 0, totalBytes: r }, new Uint8Array());
|
|
580
|
-
async function
|
|
581
|
-
const { done: u, value: l } = await
|
|
580
|
+
async function a() {
|
|
581
|
+
const { done: u, value: l } = await c.read();
|
|
582
582
|
if (u) {
|
|
583
583
|
i.close();
|
|
584
584
|
return;
|
|
@@ -588,9 +588,9 @@ class q {
|
|
|
588
588
|
const h = r === 0 ? 0 : n / r;
|
|
589
589
|
e({ percent: h, transferredBytes: n, totalBytes: r }, l);
|
|
590
590
|
}
|
|
591
|
-
i.enqueue(l), await
|
|
591
|
+
i.enqueue(l), await a();
|
|
592
592
|
}
|
|
593
|
-
await
|
|
593
|
+
await a();
|
|
594
594
|
}
|
|
595
595
|
}), {
|
|
596
596
|
status: t.status,
|
|
@@ -601,10 +601,10 @@ class q {
|
|
|
601
601
|
}
|
|
602
602
|
/*! MIT License © Sindre Sorhus */
|
|
603
603
|
const F = (s) => {
|
|
604
|
-
const t = (e, r) => q.create(e,
|
|
604
|
+
const t = (e, r) => q.create(e, M(s, r));
|
|
605
605
|
for (const e of at)
|
|
606
|
-
t[e] = (r, n) => q.create(r,
|
|
607
|
-
return t.create = (e) => F(
|
|
606
|
+
t[e] = (r, n) => q.create(r, M(s, n, { method: e }));
|
|
607
|
+
return t.create = (e) => F(M(e)), t.extend = (e) => F(M(s, e)), t.stop = ct, t;
|
|
608
608
|
}, zt = F(), Jt = zt, Kt = typeof window < "u" ? {} : { referrer: "https://sk.thorswap.net", referer: "https://sk.thorswap.net" }, tt = Jt.create({ headers: Kt }), Qt = {
|
|
609
609
|
get: (s, t) => tt.get(s, t).json(),
|
|
610
610
|
post: (s, t) => tt.post(s, t).json()
|
|
@@ -618,7 +618,7 @@ const F = (s) => {
|
|
|
618
618
|
throw new Error(
|
|
619
619
|
`Invalid identifier: ${s}. Expected format: <Chain>.<Ticker> or <Chain>.<Ticker>-<ContractAddress>`
|
|
620
620
|
);
|
|
621
|
-
}, I = 8,
|
|
621
|
+
}, I = 8, $ = (s) => 10n ** BigInt(s), R = (s) => Math.log10(parseFloat(s.toString()));
|
|
622
622
|
function x({
|
|
623
623
|
value: s,
|
|
624
624
|
bigIntDecimal: t = I,
|
|
@@ -628,28 +628,28 @@ function x({
|
|
|
628
628
|
let n = s.toString().substring(r ? 1 : 0);
|
|
629
629
|
const i = e - (n.length - 1);
|
|
630
630
|
i > 0 && (n = "0".repeat(i) + n);
|
|
631
|
-
const
|
|
632
|
-
let
|
|
633
|
-
return parseInt(
|
|
631
|
+
const c = n.length - e;
|
|
632
|
+
let a = n.slice(-e);
|
|
633
|
+
return parseInt(a[t]) >= 5 ? a = `${a.substring(0, t - 1)}${(parseInt(a[t - 1]) + 1).toString()}` : a = a.substring(0, t), `${r ? "-" : ""}${n.slice(0, c)}.${a}`.replace(
|
|
634
634
|
/\.?0*$/,
|
|
635
635
|
""
|
|
636
636
|
);
|
|
637
637
|
}
|
|
638
|
-
var A,
|
|
638
|
+
var A, S, P, lt, N, ht, O, W, T, C, B, G;
|
|
639
639
|
const K = class K {
|
|
640
640
|
constructor(t) {
|
|
641
641
|
y(this, A);
|
|
642
642
|
y(this, P);
|
|
643
643
|
y(this, N);
|
|
644
|
-
y(this, B);
|
|
645
|
-
y(this, T);
|
|
646
644
|
y(this, O);
|
|
645
|
+
y(this, T);
|
|
646
|
+
y(this, B);
|
|
647
647
|
f(this, "decimalMultiplier", 10n ** 8n);
|
|
648
648
|
f(this, "bigIntValue", 0n);
|
|
649
649
|
f(this, "decimal");
|
|
650
650
|
const e = U(t);
|
|
651
|
-
this.decimal = typeof t == "object" ? t.decimal : void 0, this.decimalMultiplier =
|
|
652
|
-
Math.max(m(this,
|
|
651
|
+
this.decimal = typeof t == "object" ? t.decimal : void 0, this.decimalMultiplier = $(
|
|
652
|
+
Math.max(m(this, B, G).call(this, m(this, T, C).call(this, e)), this.decimal || 0)
|
|
653
653
|
), m(this, P, lt).call(this, e);
|
|
654
654
|
}
|
|
655
655
|
static fromBigInt(t, e) {
|
|
@@ -664,42 +664,24 @@ const K = class K {
|
|
|
664
664
|
to: r
|
|
665
665
|
}) {
|
|
666
666
|
return this.fromBigInt(
|
|
667
|
-
t.getBaseValue("bigint") *
|
|
667
|
+
t.getBaseValue("bigint") * $(r) / $(e),
|
|
668
668
|
r
|
|
669
669
|
);
|
|
670
670
|
}
|
|
671
|
-
/**
|
|
672
|
-
* @deprecated Use `getBaseValue('string')` instead
|
|
673
|
-
*/
|
|
674
|
-
get baseValue() {
|
|
675
|
-
return this.getBaseValue("string");
|
|
676
|
-
}
|
|
677
|
-
/**
|
|
678
|
-
* @deprecated Use `getBaseValue('number')` instead
|
|
679
|
-
*/
|
|
680
|
-
get baseValueNumber() {
|
|
681
|
-
return this.getBaseValue("number");
|
|
682
|
-
}
|
|
683
|
-
/**
|
|
684
|
-
* @deprecated Use `getBaseValue('bigint')` instead
|
|
685
|
-
*/
|
|
686
|
-
get baseValueBigInt() {
|
|
687
|
-
return this.getBaseValue("bigint");
|
|
688
|
-
}
|
|
689
671
|
set(t) {
|
|
690
672
|
return new this.constructor({ decimal: this.decimal, value: t, identifier: this.toString() });
|
|
691
673
|
}
|
|
692
674
|
add(...t) {
|
|
693
|
-
return m(this, A,
|
|
675
|
+
return m(this, A, S).call(this, "add", ...t);
|
|
694
676
|
}
|
|
695
677
|
sub(...t) {
|
|
696
|
-
return m(this, A,
|
|
678
|
+
return m(this, A, S).call(this, "sub", ...t);
|
|
697
679
|
}
|
|
698
680
|
mul(...t) {
|
|
699
|
-
return m(this, A,
|
|
681
|
+
return m(this, A, S).call(this, "mul", ...t);
|
|
700
682
|
}
|
|
701
683
|
div(...t) {
|
|
702
|
-
return m(this, A,
|
|
684
|
+
return m(this, A, S).call(this, "div", ...t);
|
|
703
685
|
}
|
|
704
686
|
gt(t) {
|
|
705
687
|
return this.bigIntValue > this.getBigIntValue(t);
|
|
@@ -731,7 +713,7 @@ const K = class K {
|
|
|
731
713
|
}
|
|
732
714
|
}
|
|
733
715
|
getBaseValue(t) {
|
|
734
|
-
const e = this.decimalMultiplier /
|
|
716
|
+
const e = this.decimalMultiplier / $(this.decimal || d.THOR), r = this.bigIntValue / e;
|
|
735
717
|
switch (t) {
|
|
736
718
|
case "number":
|
|
737
719
|
return Number(r);
|
|
@@ -745,13 +727,13 @@ const K = class K {
|
|
|
745
727
|
if (!e && typeof t == "object")
|
|
746
728
|
return t.bigIntValue;
|
|
747
729
|
const r = U(t), n = m(this, T, C).call(this, r);
|
|
748
|
-
return n === "0" || n === "undefined" ? 0n : m(this,
|
|
730
|
+
return n === "0" || n === "undefined" ? 0n : m(this, O, W).call(this, n, e);
|
|
749
731
|
}
|
|
750
732
|
formatBigIntToSafeValue(t, e) {
|
|
751
733
|
const r = e || this.decimal || I, n = Math.max(
|
|
752
734
|
r,
|
|
753
735
|
R(this.decimalMultiplier)
|
|
754
|
-
), i = t < 0n,
|
|
736
|
+
), 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;
|
|
755
737
|
let h = u.slice(-n);
|
|
756
738
|
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
739
|
0,
|
|
@@ -769,9 +751,9 @@ const K = class K {
|
|
|
769
751
|
t - n.length,
|
|
770
752
|
"0"
|
|
771
753
|
);
|
|
772
|
-
const
|
|
754
|
+
const a = parseInt(i), u = `${a}`.slice(0, t);
|
|
773
755
|
return `0.${u.padStart(
|
|
774
|
-
i.length - `${
|
|
756
|
+
i.length - `${a}`.length + u.length,
|
|
775
757
|
"0"
|
|
776
758
|
)}`;
|
|
777
759
|
}
|
|
@@ -779,9 +761,9 @@ const K = class K {
|
|
|
779
761
|
const [e, r] = this.getValue("string").split("."), n = e || "", i = r || "";
|
|
780
762
|
if (parseInt(n))
|
|
781
763
|
return `${n}.${i.slice(0, t)}`.padEnd(t, "0");
|
|
782
|
-
const
|
|
783
|
-
return `0.${
|
|
784
|
-
i.length - `${
|
|
764
|
+
const c = parseInt(i), a = `${c}`.slice(0, t);
|
|
765
|
+
return `0.${a.padStart(
|
|
766
|
+
i.length - `${c}`.length + a.length,
|
|
785
767
|
"0"
|
|
786
768
|
)}`;
|
|
787
769
|
}
|
|
@@ -789,56 +771,65 @@ const K = class K {
|
|
|
789
771
|
const e = this.getValue("number"), r = ["", "K", "M", "B", "T", "Q", "Qi", "S"], n = Math.floor(Math.log10(Math.abs(e)) / 3), i = r[n];
|
|
790
772
|
if (!i)
|
|
791
773
|
return this.getValue("string");
|
|
792
|
-
const
|
|
793
|
-
return `${(e /
|
|
774
|
+
const c = 10 ** (n * 3);
|
|
775
|
+
return `${(e / c).toFixed(t)}${i}`;
|
|
776
|
+
}
|
|
777
|
+
toCurrency(t = "$", {
|
|
778
|
+
currencyPosition: e = "start",
|
|
779
|
+
decimal: r = 2,
|
|
780
|
+
decimalSeparator: n = ".",
|
|
781
|
+
thousandSeparator: i = ","
|
|
782
|
+
} = {}) {
|
|
783
|
+
const c = this.getValue("number"), [a, u = ""] = c.toFixed(6).split("."), l = a.replace(/\B(?=(\d{3})+(?!\d))/g, i), h = !a && !u ? "0.00" : a === "0" ? `${parseFloat(`0.${u}`)}`.replace(".", n) : `${l}${u ? `${n}${u.slice(0, r)}` : ""}`;
|
|
784
|
+
return `${e === "start" ? t : ""}${h}${e === "end" ? t : ""}`;
|
|
794
785
|
}
|
|
795
786
|
};
|
|
796
|
-
A = new WeakSet(),
|
|
797
|
-
const r = m(this, N, ht).call(this, this, ...e), n =
|
|
798
|
-
(
|
|
787
|
+
A = new WeakSet(), S = function(t, ...e) {
|
|
788
|
+
const r = m(this, N, ht).call(this, this, ...e), n = $(r), i = e.reduce(
|
|
789
|
+
(a, u) => {
|
|
799
790
|
const l = this.getBigIntValue(u, r);
|
|
800
791
|
switch (t) {
|
|
801
792
|
case "add":
|
|
802
|
-
return
|
|
793
|
+
return a + l;
|
|
803
794
|
case "sub":
|
|
804
|
-
return
|
|
795
|
+
return a - l;
|
|
805
796
|
case "mul":
|
|
806
|
-
return
|
|
797
|
+
return a * l / n;
|
|
807
798
|
case "div": {
|
|
808
799
|
if (l === 0n)
|
|
809
800
|
throw new RangeError("Division by zero");
|
|
810
|
-
return
|
|
801
|
+
return a * n / l;
|
|
811
802
|
}
|
|
812
803
|
default:
|
|
813
|
-
return
|
|
804
|
+
return a;
|
|
814
805
|
}
|
|
815
806
|
},
|
|
816
807
|
//normalize is to precision multiplier base
|
|
817
808
|
this.bigIntValue * n / this.decimalMultiplier
|
|
818
|
-
),
|
|
809
|
+
), c = x({
|
|
819
810
|
bigIntDecimal: r,
|
|
820
811
|
decimal: Math.max(r, R(this.decimalMultiplier)),
|
|
821
812
|
value: i
|
|
822
813
|
});
|
|
823
|
-
return new this.constructor({ decimal: this.decimal, value:
|
|
814
|
+
return new this.constructor({ decimal: this.decimal, value: c, identifier: this.toString() });
|
|
824
815
|
}, P = new WeakSet(), lt = function(t) {
|
|
825
816
|
const e = m(this, T, C).call(this, t) || "0";
|
|
826
|
-
this.bigIntValue = m(this,
|
|
817
|
+
this.bigIntValue = m(this, O, W).call(this, e);
|
|
827
818
|
}, N = new WeakSet(), ht = function(...t) {
|
|
828
819
|
const e = t.map(
|
|
829
|
-
(r) => typeof r == "object" ? r.decimal || R(r.decimalMultiplier) : m(this,
|
|
820
|
+
(r) => typeof r == "object" ? r.decimal || R(r.decimalMultiplier) : m(this, B, G).call(this, m(this, T, C).call(this, r))
|
|
830
821
|
).filter(Boolean);
|
|
831
822
|
return Math.max(...e, I);
|
|
832
|
-
},
|
|
833
|
-
const r = e ?
|
|
834
|
-
return BigInt(`${i}${
|
|
823
|
+
}, O = new WeakSet(), W = function(t, e) {
|
|
824
|
+
const r = e ? $(e) : this.decimalMultiplier, n = R(r), [i = "", c = ""] = t.split(".");
|
|
825
|
+
return BigInt(`${i}${c.padEnd(n, "0")}`);
|
|
835
826
|
}, T = new WeakSet(), C = function(t) {
|
|
836
827
|
const r = `${typeof t == "number" ? Number(t).toLocaleString("fullwide", {
|
|
837
828
|
useGrouping: !1,
|
|
838
829
|
maximumFractionDigits: 20
|
|
839
830
|
}) : U(t)}`.replaceAll(",", ".").split(".");
|
|
840
831
|
return r.length > 1 ? `${r.slice(0, -1).join("")}.${r.at(-1)}` : r[0];
|
|
841
|
-
},
|
|
832
|
+
}, B = new WeakSet(), G = function(t) {
|
|
842
833
|
var r;
|
|
843
834
|
const e = ((r = t.split(".")[1]) == null ? void 0 : r.length) || 0;
|
|
844
835
|
return Math.max(e, I);
|
|
@@ -890,21 +881,21 @@ class w extends E {
|
|
|
890
881
|
return st(e, r);
|
|
891
882
|
}
|
|
892
883
|
static fromStringSync(e, r = 0) {
|
|
893
|
-
const { isSynthetic: n } = z(e), { decimal: i, identifier:
|
|
884
|
+
const { isSynthetic: n } = z(e), { decimal: i, identifier: c } = rt(
|
|
894
885
|
e
|
|
895
|
-
),
|
|
896
|
-
return
|
|
886
|
+
), a = k(r, i);
|
|
887
|
+
return c ? new w({ decimal: i, identifier: c, value: a }) : n ? new w({ decimal: 8, identifier: e, value: a }) : void 0;
|
|
897
888
|
}
|
|
898
889
|
static async fromIdentifier(e, r = 0) {
|
|
899
890
|
return st(e, r);
|
|
900
891
|
}
|
|
901
892
|
static fromIdentifierSync(e, r = 0) {
|
|
902
|
-
const { decimal: n, identifier: i } = rt(e),
|
|
903
|
-
return new w({ decimal: n, identifier: i, value:
|
|
893
|
+
const { decimal: n, identifier: i } = rt(e), c = k(r, n);
|
|
894
|
+
return new w({ decimal: n, identifier: i, value: c });
|
|
904
895
|
}
|
|
905
896
|
static fromChainOrSignature(e, r = 0) {
|
|
906
|
-
const { decimal: n, identifier: i } = Ct(e),
|
|
907
|
-
return new w({ value:
|
|
897
|
+
const { decimal: n, identifier: i } = Ct(e), c = k(r, n);
|
|
898
|
+
return new w({ value: c, decimal: n, identifier: i });
|
|
908
899
|
}
|
|
909
900
|
static async loadStaticAssets() {
|
|
910
901
|
return new Promise(
|
|
@@ -915,9 +906,9 @@ class w extends E {
|
|
|
915
906
|
// eslint-disable-next-line @typescript-eslint/no-unused-vars
|
|
916
907
|
ThorchainList: n,
|
|
917
908
|
NativeList: i,
|
|
918
|
-
...
|
|
909
|
+
...c
|
|
919
910
|
} = await import("@swapkit/tokens");
|
|
920
|
-
Y = [i, ...Object.values(
|
|
911
|
+
Y = [i, ...Object.values(c)].reduce(
|
|
921
912
|
(u, { tokens: l }) => (l.forEach(({ identifier: h, chain: _, ...v }) => {
|
|
922
913
|
const j = "decimals" in v ? v.decimals : d[_];
|
|
923
914
|
u.set(h, { identifier: h, decimal: j });
|
|
@@ -954,14 +945,14 @@ const pe = (s) => {
|
|
|
954
945
|
return t.set(1e-8);
|
|
955
946
|
}
|
|
956
947
|
}, z = (s) => {
|
|
957
|
-
const t = s.slice(0, 14).includes("/"), [e, r] = s.split(".").pop().split("/"), n = s.includes(".") && !t ? s : `${o.THORChain}.${r}`, [i,
|
|
948
|
+
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("-");
|
|
958
949
|
return {
|
|
959
950
|
address: u == null ? void 0 : u.toLowerCase(),
|
|
960
951
|
chain: i,
|
|
961
|
-
isGasAsset:
|
|
952
|
+
isGasAsset: St({ chain: i, symbol: c }),
|
|
962
953
|
isSynthetic: t,
|
|
963
|
-
symbol: (t ? `${e}/` : "") + (u ? `${
|
|
964
|
-
ticker:
|
|
954
|
+
symbol: (t ? `${e}/` : "") + (u ? `${a}-${(u == null ? void 0 : u.toLowerCase()) ?? ""}` : c),
|
|
955
|
+
ticker: a
|
|
965
956
|
};
|
|
966
957
|
}, Zt = {
|
|
967
958
|
/**
|
|
@@ -1048,9 +1039,9 @@ export {
|
|
|
1048
1039
|
x as formatBigIntToSafeValue,
|
|
1049
1040
|
re as gasFeeMultiplier,
|
|
1050
1041
|
It as getAssetType,
|
|
1051
|
-
|
|
1042
|
+
Bt as getAsymmetricAssetShare,
|
|
1052
1043
|
oe as getAsymmetricAssetWithdrawAmount,
|
|
1053
|
-
|
|
1044
|
+
Ot as getAsymmetricRuneShare,
|
|
1054
1045
|
ie as getAsymmetricRuneWithdrawAmount,
|
|
1055
1046
|
Ct as getCommonAssetInfo,
|
|
1056
1047
|
Rt as getDecimal,
|
|
@@ -1058,9 +1049,9 @@ export {
|
|
|
1058
1049
|
ue as getLiquiditySlippage,
|
|
1059
1050
|
le as getMemoFor,
|
|
1060
1051
|
pe as getMinAmountByChain,
|
|
1061
|
-
|
|
1052
|
+
Mt as getSymmetricPoolShare,
|
|
1062
1053
|
ae as getSymmetricWithdraw,
|
|
1063
1054
|
he as getTHORNameCost,
|
|
1064
|
-
|
|
1055
|
+
St as isGasAsset,
|
|
1065
1056
|
de as validateTHORName
|
|
1066
1057
|
};
|
package/package.json
CHANGED
|
@@ -42,7 +42,7 @@
|
|
|
42
42
|
"repository": "https://github.com/thorswap/SwapKit.git",
|
|
43
43
|
"type": "module",
|
|
44
44
|
"types": "./dist/index.d.ts",
|
|
45
|
-
"version": "1.0.0-rc.
|
|
45
|
+
"version": "1.0.0-rc.22",
|
|
46
46
|
"scripts": {
|
|
47
47
|
"build": "vite build",
|
|
48
48
|
"clean": "rm -rf dist vite.config.ts.* .turbo node_modules",
|
|
@@ -200,6 +200,39 @@ describe('SwapKitNumber', () => {
|
|
|
200
200
|
});
|
|
201
201
|
});
|
|
202
202
|
|
|
203
|
+
describe('toCurrency', () => {
|
|
204
|
+
test('returns abbreviation with up to 3 integer digits', () => {
|
|
205
|
+
const skNumber = new SwapKitNumber(1234.5678);
|
|
206
|
+
expect(skNumber.toCurrency()).toBe('$1,234.56');
|
|
207
|
+
expect(
|
|
208
|
+
skNumber.toCurrency('€', {
|
|
209
|
+
decimalSeparator: ',',
|
|
210
|
+
thousandSeparator: ' ',
|
|
211
|
+
currencyPosition: 'end',
|
|
212
|
+
}),
|
|
213
|
+
).toBe('1 234,56€');
|
|
214
|
+
|
|
215
|
+
const skNumber2 = new SwapKitNumber(0.5678);
|
|
216
|
+
expect(skNumber2.toCurrency()).toBe('$0.5678');
|
|
217
|
+
expect(
|
|
218
|
+
skNumber2.toCurrency('€', {
|
|
219
|
+
decimalSeparator: ',',
|
|
220
|
+
currencyPosition: 'end',
|
|
221
|
+
}),
|
|
222
|
+
).toBe('0,5678€');
|
|
223
|
+
|
|
224
|
+
const skNumber3 = new SwapKitNumber(0.00005678);
|
|
225
|
+
expect(skNumber3.toCurrency()).toBe('$0.000057');
|
|
226
|
+
expect(
|
|
227
|
+
skNumber3.toCurrency('€', {
|
|
228
|
+
decimalSeparator: ',',
|
|
229
|
+
thousandSeparator: ' ',
|
|
230
|
+
currencyPosition: 'end',
|
|
231
|
+
}),
|
|
232
|
+
).toBe('0,000057€');
|
|
233
|
+
});
|
|
234
|
+
});
|
|
235
|
+
|
|
203
236
|
describe('add', () => {
|
|
204
237
|
test('adds same type numbers correctly', () => {
|
|
205
238
|
const skNumber1 = new SwapKitNumber(10);
|
|
@@ -92,25 +92,6 @@ export class BigIntArithmetics {
|
|
|
92
92
|
this.#setValue(value);
|
|
93
93
|
}
|
|
94
94
|
|
|
95
|
-
/**
|
|
96
|
-
* @deprecated Use `getBaseValue('string')` instead
|
|
97
|
-
*/
|
|
98
|
-
get baseValue() {
|
|
99
|
-
return this.getBaseValue('string') as string;
|
|
100
|
-
}
|
|
101
|
-
/**
|
|
102
|
-
* @deprecated Use `getBaseValue('number')` instead
|
|
103
|
-
*/
|
|
104
|
-
get baseValueNumber() {
|
|
105
|
-
return this.getBaseValue('number') as number;
|
|
106
|
-
}
|
|
107
|
-
/**
|
|
108
|
-
* @deprecated Use `getBaseValue('bigint')` instead
|
|
109
|
-
*/
|
|
110
|
-
get baseValueBigInt() {
|
|
111
|
-
return this.getBaseValue('bigint') as bigint;
|
|
112
|
-
}
|
|
113
|
-
|
|
114
95
|
set(value: SKBigIntParams): this {
|
|
115
96
|
// @ts-expect-error False positive
|
|
116
97
|
return new this.constructor({ decimal: this.decimal, value, identifier: this.toString() });
|
|
@@ -284,6 +265,31 @@ export class BigIntArithmetics {
|
|
|
284
265
|
return `${scaled.toFixed(digits)}${suffix}`;
|
|
285
266
|
}
|
|
286
267
|
|
|
268
|
+
toCurrency(
|
|
269
|
+
currency = '$',
|
|
270
|
+
{
|
|
271
|
+
currencyPosition = 'start',
|
|
272
|
+
decimal = 2,
|
|
273
|
+
decimalSeparator = '.',
|
|
274
|
+
thousandSeparator = ',',
|
|
275
|
+
} = {},
|
|
276
|
+
) {
|
|
277
|
+
const value = this.getValue('number');
|
|
278
|
+
const [int, dec = ''] = value.toFixed(6).split('.');
|
|
279
|
+
const integer = int.replace(/\B(?=(\d{3})+(?!\d))/g, thousandSeparator);
|
|
280
|
+
|
|
281
|
+
const parsedValue =
|
|
282
|
+
!int && !dec
|
|
283
|
+
? '0.00'
|
|
284
|
+
: int === '0'
|
|
285
|
+
? `${parseFloat(`0.${dec}`)}`.replace('.', decimalSeparator)
|
|
286
|
+
: `${integer}${dec ? `${decimalSeparator}${dec.slice(0, decimal)}` : ''}`;
|
|
287
|
+
|
|
288
|
+
return `${currencyPosition === 'start' ? currency : ''}${parsedValue}${
|
|
289
|
+
currencyPosition === 'end' ? currency : ''
|
|
290
|
+
}`;
|
|
291
|
+
}
|
|
292
|
+
|
|
287
293
|
#arithmetics(method: 'add' | 'sub' | 'mul' | 'div', ...args: InitialisationValueType[]): this {
|
|
288
294
|
const precisionDecimal = this.#retrievePrecisionDecimal(this, ...args);
|
|
289
295
|
const precisionDecimalMultiplier = toMultiplier(precisionDecimal);
|