@swapkit/helpers 1.0.0-rc.34 → 1.0.0-rc.36
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 +5 -3
- package/dist/index.es.js +125 -122
- package/package.json +10 -10
- package/src/modules/__tests__/swapKitNumber.test.ts +20 -1
- package/src/modules/assetValue.ts +2 -2
- package/src/modules/bigIntArithmetics.ts +74 -64
package/dist/index.cjs
CHANGED
|
@@ -1 +1 @@
|
|
|
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;
|
|
1
|
+
"use strict";var we=Object.create;var k=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?k(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&&k(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?k(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"}},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}},Pe=new RegExp(/(.)\1{6}|\.ORG|\.NET|\.FINANCE|\.COM|WWW|HTTP|\\\\|\/\/|[\s$%:[\]]/,"gmi"),ke=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!Pe.test(t)&&ke(t)&&e.value!=="0"}),ae=({liquidityUnits:s,poolUnits:e,runeDepth:t})=>{const r=d(s),n=d(e),a=d(t),o=r.mul(a),c=n.mul(n).mul(2),u=n.mul(r).mul(2),h=r.mul(r),l=n.mul(n).mul(n);return o.mul(c.sub(u).add(h)).div(l)},oe=({liquidityUnits:s,poolUnits:e,assetDepth:t})=>{const r=d(s),n=d(e),a=d(t),o=r.mul(a),c=n.mul(n).mul(2),u=n.mul(r).mul(2),h=r.mul(r),l=o.mul(c.sub(u).add(h)),g=n.mul(n).mul(n);return l.div(g)},De=({percent:s,runeDepth:e,liquidityUnits:t,poolUnits:r})=>ae({runeDepth:e,liquidityUnits:t,poolUnits:r}).mul(s),je=({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)}),He=({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,o])=>[a,o.mul(n)])),Le=({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}),h=new f({value:n,decimal:8}),l=new f({value:a,decimal:8}),g=h.mul(c),C=l.mul(o),x=h.mul(l),_e=o.mul(c),ye=u.mul(g.add(C.add(x.mul(2)))),be=g.add(C.add(_e.mul(2))),Y=ye.div(be),P=d(r).add(Y);if(Y.getBaseValue("number")===0)return P.div(u).getBaseValue("number");const Ce=u.add(P);return P.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),o=d(e),c=d(s),u=o.mul(n).sub(a.mul(c)),h=a.mul(c).add(n.mul(a));return Math.abs(u.div(h).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:o,singleSide:c}=e,u=!c&&o?`:${o}`:"",h=Ue({chain:t,symbol:n,ticker:r});return`${s}:${t}${c?"/":"."}${h}:${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||"",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 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,o]of n.entries())r&&o==="undefined"||o===void 0?t.delete(a):t.set(a,o);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 o=setTimeout(()=>{t&&t.abort(),a(new ue(s))},r.timeout);r.fetch(s,e).then(n).catch(a).then(()=>{clearTimeout(o)})})}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 c=await r._fetch();for(const u of r._options.hooks.afterResponse){const h=await u(r.request,r._options,r._decorateResponse(c.clone()));h instanceof globalThis.Response&&(c=h)}if(r._decorateResponse(c),!c.ok&&r._options.throwHttpErrors){let u=new z(c,r.request,r._options);for(const h of r._options.hooks.beforeError)u=await h(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(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(Ze))o[c]=async()=>{r.request.headers.set("accept",r.request.headers.get("accept")||u);const l=(await o).clone();if(c==="json"){if(l.status===204||(await l.clone().arrayBuffer()).byteLength===0)return"";if(t.parseJson)return t.parseJson(await l.text())}return l[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: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 o=e.body.getReader();t&&t({percent:0,transferredBytes:0,totalBytes:r},new Uint8Array);async function c(){const{done:u,value:h}=await o.read();if(u){a.close();return}if(t){n+=h.byteLength;const l=r===0?0:n/r;t({percent:l,transferredBytes:n,totalBytes:r},h)}a.enqueue(h),await c()}await c()}}),{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,y=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 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,V,fe,q,ge,$,j;const K=class K{constructor(e){A(this,b);A(this,V);A(this,q);A(this,$);m(this,"decimalMultiplier",10n**8n);m(this,"bigIntValue",0n);m(this,"decimal");const t=H(e),r=typeof e=="object";this.decimal=r?e.decimal:void 0,this.decimalMultiplier=r&&"decimalMultiplier"in e?e.decimalMultiplier:y(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")*y(r)/y(t),r)}set(e){return new this.constructor({decimal:this.decimal,value:e,identifier:this.toString()})}add(...e){return p(this,b,v).call(this,"add",...e)}sub(...e){return p(this,b,v).call(this,"sub",...e)}mul(...e){return p(this,b,v).call(this,"mul",...e)}div(...e){return p(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||T(this.decimalMultiplier));switch(e){case"number":return Number(t);case"string":return t;case"bigint":return this.bigIntValue*10n**BigInt(this.decimal||8n)/this.decimalMultiplier}}getBaseValue(e){const t=this.decimalMultiplier/y(this.decimal||i.BaseDecimal.THOR),r=this.bigIntValue/t;switch(e){case"number":return Number(r);case"string":return r.toString();case"bigint":return r}}getBigIntValue(e,t){if(!t&&typeof e=="object")return e.bigIntValue;const r=H(e),n=B(r);return n==="0"||n==="undefined"?0n:p(this,$,j).call(this,n,t)}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}`}toCurrency(e="$",{currencyPosition:t="start",decimal:r=2,decimalSeparator:n=".",thousandSeparator:a=","}={}){const o=this.getValue("number"),[c,u=""]=o.toFixed(6).split("."),h=c.replace(/\B(?=(\d{3})+(?!\d))/g,a),l=!c&&!u?"0.00":c==="0"?`${parseFloat(`0.${u}`)}`.replace(".",n):`${h}${parseInt(u)?`${n}${u.slice(0,r)}`:""}`;return`${t==="start"?e:""}${l}${t==="end"?e:""}`}formatBigIntToSafeValue(e,t){const r=t||this.decimal||S,n=Math.max(r,T(this.decimalMultiplier)),a=e<0n,o=e.toString().substring(a?1:0),c=n-(o.length-1),u=c>0?"0".repeat(c)+o:o,h=u.length-n;let l=u.slice(-n);return parseInt(l[r])>=5?l=`${l.substring(0,r-1)}${(parseInt(l[r-1])+1).toString()}`:l=l.substring(0,r),`${a?"-":""}${u.slice(0,h)}.${l}`.replace(/\.?0*$/,"")}};b=new WeakSet,v=function(e,...t){const r=p(this,q,ge).call(this,this,...t),n=Math.max(r,T(this.decimalMultiplier)),a=y(n),o=t.reduce((u,h)=>{const l=this.getBigIntValue(h,n);switch(e){case"add":return u+l;case"sub":return u-l;case"mul":return u*l/a;case"div":{if(l===0n)throw new RangeError("Division by zero");return u*a/l}default:return u}},this.bigIntValue*a/this.decimalMultiplier),c=R({bigIntDecimal:n,decimal:n,value:o});return new this.constructor({decimalMultiplier:y(n),decimal:this.decimal,value:c,identifier:this.toString()})},V=new WeakSet,fe=function(e){const t=B(e)||"0";this.bigIntValue=p(this,$,j).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,j=function(e,t){const r=t?y(t):this.decimalMultiplier,n=T(r),[a="",o=""]=e.split(".");return BigInt(`${a}${o.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):H(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 H(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:o}=ee(t),c=M(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 te(t,r)}static fromIdentifierSync(t,r=0){const{decimal:n,identifier:a}=ee(t),o=M(r,n);return new _({decimal:n,identifier:a,value:o})}static fromChainOrSignature(t,r=0){const{decimal:n,identifier:a}=ne(t),o=M(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");L=[a,...Object.values(o)].reduce((u,{tokens:h})=>(h.forEach(({identifier:l,chain:g,...C})=>{const x="decimals"in C?C.decimals:i.BaseDecimal[g];u.set(l,{identifier:l,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)}},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,o]=n.split("."),[c,u]=(e?r:o).split("-");return{address:u==null?void 0:u.toLowerCase(),chain:a,isGasAsset:U({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 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=xe;exports.derivationPathToString=Ye;exports.filterAssets=Ne;exports.formatBigIntToSafeValue=R;exports.gasFeeMultiplier=qe;exports.getAssetType=ie;exports.getAsymmetricAssetShare=oe;exports.getAsymmetricAssetWithdrawAmount=je;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=He;exports.getTHORNameCost=Ge;exports.isGasAsset=U;exports.validateTHORName=Ke;
|
package/dist/index.d.ts
CHANGED
|
@@ -14,6 +14,8 @@ import type { TraderjoeList } from '@swapkit/tokens';
|
|
|
14
14
|
import type { UniswapList } from '@swapkit/tokens';
|
|
15
15
|
import type { WoofiList } from '@swapkit/tokens';
|
|
16
16
|
|
|
17
|
+
declare type AllowedNumberTypes = 'bigint' | 'number' | 'string';
|
|
18
|
+
|
|
17
19
|
export declare const assetFromString: (assetString: string) => {
|
|
18
20
|
chain: Chain;
|
|
19
21
|
symbol: string;
|
|
@@ -81,10 +83,9 @@ export declare class BigIntArithmetics {
|
|
|
81
83
|
lt(value: InitialisationValueType): boolean;
|
|
82
84
|
lte(value: InitialisationValueType): boolean;
|
|
83
85
|
eqValue(value: InitialisationValueType): boolean;
|
|
84
|
-
getValue<T extends
|
|
85
|
-
getBaseValue<T extends
|
|
86
|
+
getValue<T extends AllowedNumberTypes>(type: T): NumberPrimitivesType[T];
|
|
87
|
+
getBaseValue<T extends AllowedNumberTypes>(type: T): NumberPrimitivesType[T];
|
|
86
88
|
getBigIntValue(value: InitialisationValueType, decimal?: number): bigint;
|
|
87
|
-
formatBigIntToSafeValue(value: bigint, decimal?: number): string;
|
|
88
89
|
toSignificant(significantDigits?: number): string;
|
|
89
90
|
toFixed(fixedDigits?: number): string;
|
|
90
91
|
toAbbreviation(digits?: number): string;
|
|
@@ -94,6 +95,7 @@ export declare class BigIntArithmetics {
|
|
|
94
95
|
decimalSeparator?: string | undefined;
|
|
95
96
|
thousandSeparator?: string | undefined;
|
|
96
97
|
}): string;
|
|
98
|
+
formatBigIntToSafeValue(value: bigint, decimal?: number): string;
|
|
97
99
|
}
|
|
98
100
|
|
|
99
101
|
export declare type CommonAssetString = 'MAYA.MAYA' | 'ETH.THOR' | 'ETH.vTHOR' | Chain;
|
package/dist/index.es.js
CHANGED
|
@@ -139,8 +139,8 @@ const At = "0x313ce567", rt = async ({ chain: s, to: t }) => {
|
|
|
139
139
|
return [o.Ethereum, o.Optimism].includes(t) ? "Native" : "OPTIMISM";
|
|
140
140
|
}
|
|
141
141
|
}, ne = (s) => {
|
|
142
|
-
var
|
|
143
|
-
const [t, ...e] = s.split("."), r = s.includes("/"), n = e.join("."), i = (
|
|
142
|
+
var a;
|
|
143
|
+
const [t, ...e] = s.split("."), r = s.includes("/"), n = e.join("."), i = (a = n == null ? void 0 : n.split("-")) == null ? void 0 : a[0];
|
|
144
144
|
return { chain: t, symbol: n, ticker: i, synth: r };
|
|
145
145
|
}, It = new RegExp(
|
|
146
146
|
/(.)\1{6}|\.ORG|\.NET|\.FINANCE|\.COM|WWW|HTTP|\\\\|\/\/|[\s$%:[\]]/,
|
|
@@ -159,15 +159,15 @@ const At = "0x313ce567", rt = 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),
|
|
163
|
-
return
|
|
162
|
+
const r = m(s), n = m(t), i = m(e), a = r.mul(i), c = n.mul(n).mul(2), u = n.mul(r).mul(2), d = r.mul(r), l = n.mul(n).mul(n);
|
|
163
|
+
return a.mul(c.sub(u).add(d)).div(l);
|
|
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),
|
|
170
|
-
return
|
|
169
|
+
const r = m(s), n = m(t), i = m(e), a = r.mul(i), c = n.mul(n).mul(2), u = n.mul(r).mul(2), d = r.mul(r), l = a.mul(c.sub(u).add(d)), _ = n.mul(n).mul(n);
|
|
170
|
+
return l.div(_);
|
|
171
171
|
}, oe = ({
|
|
172
172
|
percent: s,
|
|
173
173
|
runeDepth: t,
|
|
@@ -194,7 +194,7 @@ const At = "0x313ce567", rt = async ({ chain: s, to: t }) => {
|
|
|
194
194
|
percent: n
|
|
195
195
|
}) => Object.fromEntries(
|
|
196
196
|
Object.entries(Mt({ liquidityUnits: s, poolUnits: t, runeDepth: e, assetDepth: r })).map(
|
|
197
|
-
([i,
|
|
197
|
+
([i, a]) => [i, a.mul(n)]
|
|
198
198
|
)
|
|
199
199
|
), ue = ({
|
|
200
200
|
runeDepth: s,
|
|
@@ -204,7 +204,7 @@ const At = "0x313ce567", rt = async ({ chain: s, to: t }) => {
|
|
|
204
204
|
runeAmount: n,
|
|
205
205
|
assetAmount: i
|
|
206
206
|
}) => {
|
|
207
|
-
const
|
|
207
|
+
const a = new b({ value: s, decimal: 8 }), c = new b({ value: e, decimal: 8 }), u = new b({ value: t, decimal: 8 }), d = new b({ value: n, decimal: 8 }), l = new b({ value: i, decimal: 8 }), _ = d.mul(c), v = l.mul(a), P = d.mul(l), ht = a.mul(c), mt = u.mul(_.add(v.add(P.mul(2)))), pt = _.add(v.add(ht.mul(2))), z = mt.div(pt), N = m(r).add(z);
|
|
208
208
|
if (z.getBaseValue("number") === 0)
|
|
209
209
|
return N.div(u).getBaseValue("number");
|
|
210
210
|
const ft = u.add(N);
|
|
@@ -217,8 +217,8 @@ const At = "0x313ce567", rt = async ({ chain: s, to: t }) => {
|
|
|
217
217
|
}) => {
|
|
218
218
|
if (s === "0" || t === "0" || e === "0" || r === "0")
|
|
219
219
|
return 0;
|
|
220
|
-
const n = m(e), i = m(r),
|
|
221
|
-
return Math.abs(u.div(
|
|
220
|
+
const n = m(e), i = m(r), a = m(t), c = m(s), u = a.mul(n).sub(i.mul(c)), d = i.mul(c).add(n.mul(i));
|
|
221
|
+
return Math.abs(u.div(d).getBaseValue("number"));
|
|
222
222
|
}, Vt = ({
|
|
223
223
|
symbol: s,
|
|
224
224
|
ticker: t,
|
|
@@ -243,8 +243,8 @@ const At = "0x313ce567", rt = async ({ chain: s, to: t }) => {
|
|
|
243
243
|
return i ? `${s}:${e}/${r}::t:0` : `${s}:${e}.${r}:${n || ""}:t:0`;
|
|
244
244
|
}
|
|
245
245
|
case g.WITHDRAW: {
|
|
246
|
-
const { chain: e, ticker: r, symbol: n, basisPoints: i, targetAssetString:
|
|
247
|
-
return `${s}:${e}${
|
|
246
|
+
const { chain: e, ticker: r, symbol: n, basisPoints: i, targetAssetString: a, singleSide: c } = t, u = !c && a ? `:${a}` : "", d = Vt({ chain: e, symbol: n, ticker: r });
|
|
247
|
+
return `${s}:${e}${c ? "/" : "."}${d}:${i}${u}`;
|
|
248
248
|
}
|
|
249
249
|
case g.OPEN_LOAN:
|
|
250
250
|
case g.CLOSE_LOAN: {
|
|
@@ -266,8 +266,8 @@ const At = "0x313ce567", rt = async ({ chain: s, to: t }) => {
|
|
|
266
266
|
}, pe = ([s, t, e, r, n]) => `${s}'/${t}'/${e}'/${r}${typeof n != "number" ? "" : `/${n}`}`;
|
|
267
267
|
class J extends Error {
|
|
268
268
|
constructor(t, e, r) {
|
|
269
|
-
const n = t.status || t.status === 0 ? t.status : "", i = t.statusText || "",
|
|
270
|
-
super(`Request failed with ${
|
|
269
|
+
const n = t.status || t.status === 0 ? t.status : "", i = t.statusText || "", a = `${n} ${i}`.trim(), c = a ? `status code ${a}` : "an unknown error";
|
|
270
|
+
super(`Request failed with ${c}`), Object.defineProperty(this, "response", {
|
|
271
271
|
enumerable: !0,
|
|
272
272
|
configurable: !0,
|
|
273
273
|
writable: !0,
|
|
@@ -302,8 +302,8 @@ const B = (s) => s !== null && typeof s == "object", E = (...s) => {
|
|
|
302
302
|
return G({}, ...s);
|
|
303
303
|
}, it = (s = {}, t = {}) => {
|
|
304
304
|
const e = new globalThis.Headers(s), r = t instanceof globalThis.Headers, n = new globalThis.Headers(t);
|
|
305
|
-
for (const [i,
|
|
306
|
-
r &&
|
|
305
|
+
for (const [i, a] of n.entries())
|
|
306
|
+
r && a === "undefined" || a === void 0 ? e.delete(i) : e.set(i, a);
|
|
307
307
|
return e;
|
|
308
308
|
}, G = (...s) => {
|
|
309
309
|
let t = {}, e = {};
|
|
@@ -386,11 +386,11 @@ const B = (s) => s !== null && typeof s == "object", E = (...s) => {
|
|
|
386
386
|
};
|
|
387
387
|
async function Wt(s, t, e, r) {
|
|
388
388
|
return new Promise((n, i) => {
|
|
389
|
-
const
|
|
389
|
+
const a = setTimeout(() => {
|
|
390
390
|
e && e.abort(), i(new nt(s));
|
|
391
391
|
}, r.timeout);
|
|
392
392
|
r.fetch(s, t).then(n).catch(i).then(() => {
|
|
393
|
-
clearTimeout(
|
|
393
|
+
clearTimeout(a);
|
|
394
394
|
});
|
|
395
395
|
});
|
|
396
396
|
}
|
|
@@ -417,15 +417,15 @@ class V {
|
|
|
417
417
|
if (typeof r._options.timeout == "number" && r._options.timeout > H)
|
|
418
418
|
throw new RangeError(`The \`timeout\` option cannot be greater than ${H}`);
|
|
419
419
|
await Promise.resolve();
|
|
420
|
-
let
|
|
420
|
+
let c = await r._fetch();
|
|
421
421
|
for (const u of r._options.hooks.afterResponse) {
|
|
422
|
-
const
|
|
423
|
-
|
|
422
|
+
const d = await u(r.request, r._options, r._decorateResponse(c.clone()));
|
|
423
|
+
d instanceof globalThis.Response && (c = d);
|
|
424
424
|
}
|
|
425
|
-
if (r._decorateResponse(
|
|
426
|
-
let u = new J(
|
|
427
|
-
for (const
|
|
428
|
-
u = await
|
|
425
|
+
if (r._decorateResponse(c), !c.ok && r._options.throwHttpErrors) {
|
|
426
|
+
let u = new J(c, r.request, r._options);
|
|
427
|
+
for (const d of r._options.hooks.beforeError)
|
|
428
|
+
u = await d(u);
|
|
429
429
|
throw u;
|
|
430
430
|
}
|
|
431
431
|
if (r._options.onDownloadProgress) {
|
|
@@ -433,23 +433,23 @@ class V {
|
|
|
433
433
|
throw new TypeError("The `onDownloadProgress` option must be a function");
|
|
434
434
|
if (!kt)
|
|
435
435
|
throw new Error("Streams are not supported in your environment. `ReadableStream` is missing.");
|
|
436
|
-
return r._stream(
|
|
436
|
+
return r._stream(c.clone(), r._options.onDownloadProgress);
|
|
437
437
|
}
|
|
438
|
-
return
|
|
439
|
-
},
|
|
440
|
-
for (const [
|
|
441
|
-
c
|
|
438
|
+
return c;
|
|
439
|
+
}, a = r._options.retry.methods.includes(r.request.method.toLowerCase()) ? r._retry(n) : n();
|
|
440
|
+
for (const [c, u] of Object.entries(Nt))
|
|
441
|
+
a[c] = async () => {
|
|
442
442
|
r.request.headers.set("accept", r.request.headers.get("accept") || u);
|
|
443
|
-
const
|
|
444
|
-
if (
|
|
445
|
-
if (
|
|
443
|
+
const l = (await a).clone();
|
|
444
|
+
if (c === "json") {
|
|
445
|
+
if (l.status === 204 || (await l.clone().arrayBuffer()).byteLength === 0)
|
|
446
446
|
return "";
|
|
447
447
|
if (e.parseJson)
|
|
448
|
-
return e.parseJson(await
|
|
448
|
+
return e.parseJson(await l.text());
|
|
449
449
|
}
|
|
450
|
-
return
|
|
450
|
+
return l[c]();
|
|
451
451
|
};
|
|
452
|
-
return
|
|
452
|
+
return a;
|
|
453
453
|
}
|
|
454
454
|
// eslint-disable-next-line complexity
|
|
455
455
|
constructor(t, e = {}) {
|
|
@@ -582,22 +582,22 @@ class V {
|
|
|
582
582
|
headers: t.headers
|
|
583
583
|
})) : new globalThis.Response(new globalThis.ReadableStream({
|
|
584
584
|
async start(i) {
|
|
585
|
-
const
|
|
585
|
+
const a = t.body.getReader();
|
|
586
586
|
e && e({ percent: 0, transferredBytes: 0, totalBytes: r }, new Uint8Array());
|
|
587
|
-
async function
|
|
588
|
-
const { done: u, value:
|
|
587
|
+
async function c() {
|
|
588
|
+
const { done: u, value: d } = await a.read();
|
|
589
589
|
if (u) {
|
|
590
590
|
i.close();
|
|
591
591
|
return;
|
|
592
592
|
}
|
|
593
593
|
if (e) {
|
|
594
|
-
n +=
|
|
595
|
-
const
|
|
596
|
-
e({ percent:
|
|
594
|
+
n += d.byteLength;
|
|
595
|
+
const l = r === 0 ? 0 : n / r;
|
|
596
|
+
e({ percent: l, transferredBytes: n, totalBytes: r }, d);
|
|
597
597
|
}
|
|
598
|
-
i.enqueue(
|
|
598
|
+
i.enqueue(d), await c();
|
|
599
599
|
}
|
|
600
|
-
await
|
|
600
|
+
await c();
|
|
601
601
|
}
|
|
602
602
|
}), {
|
|
603
603
|
status: t.status,
|
|
@@ -625,7 +625,7 @@ const L = (s) => {
|
|
|
625
625
|
throw new Error(
|
|
626
626
|
`Invalid identifier: ${s}. Expected format: <Chain>.<Ticker> or <Chain>.<Ticker>-<ContractAddress>`
|
|
627
627
|
);
|
|
628
|
-
}, S = 8,
|
|
628
|
+
}, S = 8, y = (s) => 10n ** BigInt(s), $ = (s) => Math.log10(parseFloat(s.toString()));
|
|
629
629
|
function q({
|
|
630
630
|
value: s,
|
|
631
631
|
bigIntDecimal: t = S,
|
|
@@ -635,27 +635,25 @@ function q({
|
|
|
635
635
|
let n = s.toString().substring(r ? 1 : 0);
|
|
636
636
|
const i = e - (n.length - 1);
|
|
637
637
|
i > 0 && (n = "0".repeat(i) + n);
|
|
638
|
-
const
|
|
639
|
-
let
|
|
640
|
-
return parseInt(
|
|
638
|
+
const a = n.length - e;
|
|
639
|
+
let c = n.slice(-e);
|
|
640
|
+
return parseInt(c[t]) >= 5 ? c = `${c.substring(0, t - 1)}${(parseInt(c[t - 1]) + 1).toString()}` : c = c.substring(0, t), `${r ? "-" : ""}${n.slice(0, a)}.${c}`.replace(
|
|
641
641
|
/\.?0*$/,
|
|
642
642
|
""
|
|
643
643
|
);
|
|
644
644
|
}
|
|
645
|
-
var
|
|
645
|
+
var A, R, x, ut, k, lt, I, D;
|
|
646
646
|
const Y = class Y {
|
|
647
647
|
constructor(t) {
|
|
648
|
-
T(this,
|
|
648
|
+
T(this, A);
|
|
649
649
|
T(this, x);
|
|
650
650
|
T(this, k);
|
|
651
651
|
T(this, I);
|
|
652
652
|
p(this, "decimalMultiplier", 10n ** 8n);
|
|
653
653
|
p(this, "bigIntValue", 0n);
|
|
654
654
|
p(this, "decimal");
|
|
655
|
-
const e = U(t);
|
|
656
|
-
this.decimal =
|
|
657
|
-
Math.max(Z(O(e)), this.decimal || 0)
|
|
658
|
-
), f(this, x, ut).call(this, e);
|
|
655
|
+
const e = U(t), r = typeof t == "object";
|
|
656
|
+
this.decimal = r ? t.decimal : void 0, this.decimalMultiplier = r && "decimalMultiplier" in t ? t.decimalMultiplier : y(Math.max(Z(O(e)), this.decimal || 0)), f(this, x, ut).call(this, e);
|
|
659
657
|
}
|
|
660
658
|
static fromBigInt(t, e) {
|
|
661
659
|
return new Y({
|
|
@@ -669,7 +667,7 @@ const Y = class Y {
|
|
|
669
667
|
to: r
|
|
670
668
|
}) {
|
|
671
669
|
return this.fromBigInt(
|
|
672
|
-
t.getBaseValue("bigint") *
|
|
670
|
+
t.getBaseValue("bigint") * y(r) / y(e),
|
|
673
671
|
r
|
|
674
672
|
);
|
|
675
673
|
}
|
|
@@ -677,16 +675,16 @@ const Y = class Y {
|
|
|
677
675
|
return new this.constructor({ decimal: this.decimal, value: t, identifier: this.toString() });
|
|
678
676
|
}
|
|
679
677
|
add(...t) {
|
|
680
|
-
return f(this,
|
|
678
|
+
return f(this, A, R).call(this, "add", ...t);
|
|
681
679
|
}
|
|
682
680
|
sub(...t) {
|
|
683
|
-
return f(this,
|
|
681
|
+
return f(this, A, R).call(this, "sub", ...t);
|
|
684
682
|
}
|
|
685
683
|
mul(...t) {
|
|
686
|
-
return f(this,
|
|
684
|
+
return f(this, A, R).call(this, "mul", ...t);
|
|
687
685
|
}
|
|
688
686
|
div(...t) {
|
|
689
|
-
return f(this,
|
|
687
|
+
return f(this, A, R).call(this, "div", ...t);
|
|
690
688
|
}
|
|
691
689
|
gt(t) {
|
|
692
690
|
return this.bigIntValue > this.getBigIntValue(t);
|
|
@@ -703,6 +701,7 @@ const Y = class Y {
|
|
|
703
701
|
eqValue(t) {
|
|
704
702
|
return this.bigIntValue === this.getBigIntValue(t);
|
|
705
703
|
}
|
|
704
|
+
// @ts-expect-error False positive
|
|
706
705
|
getValue(t) {
|
|
707
706
|
const e = this.formatBigIntToSafeValue(
|
|
708
707
|
this.bigIntValue,
|
|
@@ -713,18 +712,19 @@ const Y = class Y {
|
|
|
713
712
|
return Number(e);
|
|
714
713
|
case "string":
|
|
715
714
|
return e;
|
|
716
|
-
|
|
717
|
-
return this.bigIntValue * BigInt(this.decimal || 8n) / this.decimalMultiplier;
|
|
715
|
+
case "bigint":
|
|
716
|
+
return this.bigIntValue * 10n ** BigInt(this.decimal || 8n) / this.decimalMultiplier;
|
|
718
717
|
}
|
|
719
718
|
}
|
|
719
|
+
// @ts-expect-error
|
|
720
720
|
getBaseValue(t) {
|
|
721
|
-
const e = this.decimalMultiplier /
|
|
721
|
+
const e = this.decimalMultiplier / y(this.decimal || h.THOR), r = this.bigIntValue / e;
|
|
722
722
|
switch (t) {
|
|
723
723
|
case "number":
|
|
724
724
|
return Number(r);
|
|
725
725
|
case "string":
|
|
726
726
|
return r.toString();
|
|
727
|
-
|
|
727
|
+
case "bigint":
|
|
728
728
|
return r;
|
|
729
729
|
}
|
|
730
730
|
}
|
|
@@ -734,17 +734,6 @@ const Y = class Y {
|
|
|
734
734
|
const r = U(t), n = O(r);
|
|
735
735
|
return n === "0" || n === "undefined" ? 0n : f(this, I, D).call(this, n, e);
|
|
736
736
|
}
|
|
737
|
-
formatBigIntToSafeValue(t, e) {
|
|
738
|
-
const r = e || this.decimal || S, n = Math.max(
|
|
739
|
-
r,
|
|
740
|
-
$(this.decimalMultiplier)
|
|
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 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
|
-
0,
|
|
745
|
-
l
|
|
746
|
-
)}.${d}`.replace(/\.?0*$/, "");
|
|
747
|
-
}
|
|
748
737
|
toSignificant(t = 6) {
|
|
749
738
|
const [e, r] = this.getValue("string").split("."), n = e || "", i = r || "";
|
|
750
739
|
if ((parseInt(n) ? n.length + i.length : i.length) <= t)
|
|
@@ -756,9 +745,9 @@ const Y = class Y {
|
|
|
756
745
|
t - n.length,
|
|
757
746
|
"0"
|
|
758
747
|
);
|
|
759
|
-
const
|
|
748
|
+
const c = parseInt(i), u = `${c}`.slice(0, t);
|
|
760
749
|
return `0.${u.padStart(
|
|
761
|
-
i.length - `${
|
|
750
|
+
i.length - `${c}`.length + u.length,
|
|
762
751
|
"0"
|
|
763
752
|
)}`;
|
|
764
753
|
}
|
|
@@ -766,9 +755,9 @@ const Y = class Y {
|
|
|
766
755
|
const [e, r] = this.getValue("string").split("."), n = e || "", i = r || "";
|
|
767
756
|
if (parseInt(n))
|
|
768
757
|
return `${n}.${i.slice(0, t)}`.padEnd(t, "0");
|
|
769
|
-
const
|
|
770
|
-
return `0.${
|
|
771
|
-
i.length - `${
|
|
758
|
+
const a = parseInt(i), c = `${a}`.slice(0, t);
|
|
759
|
+
return `0.${c.padStart(
|
|
760
|
+
i.length - `${a}`.length + c.length,
|
|
772
761
|
"0"
|
|
773
762
|
)}`;
|
|
774
763
|
}
|
|
@@ -776,8 +765,8 @@ const Y = class Y {
|
|
|
776
765
|
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];
|
|
777
766
|
if (!i)
|
|
778
767
|
return this.getValue("string");
|
|
779
|
-
const
|
|
780
|
-
return `${(e /
|
|
768
|
+
const a = 10 ** (n * 3);
|
|
769
|
+
return `${(e / a).toFixed(t)}${i}`;
|
|
781
770
|
}
|
|
782
771
|
toCurrency(t = "$", {
|
|
783
772
|
currencyPosition: e = "start",
|
|
@@ -785,49 +774,63 @@ const Y = class Y {
|
|
|
785
774
|
decimalSeparator: n = ".",
|
|
786
775
|
thousandSeparator: i = ","
|
|
787
776
|
} = {}) {
|
|
788
|
-
const
|
|
789
|
-
return `${e === "start" ? t : ""}${
|
|
777
|
+
const a = this.getValue("number"), [c, u = ""] = a.toFixed(6).split("."), d = c.replace(/\B(?=(\d{3})+(?!\d))/g, i), l = !c && !u ? "0.00" : c === "0" ? `${parseFloat(`0.${u}`)}`.replace(".", n) : `${d}${parseInt(u) ? `${n}${u.slice(0, r)}` : ""}`;
|
|
778
|
+
return `${e === "start" ? t : ""}${l}${e === "end" ? t : ""}`;
|
|
779
|
+
}
|
|
780
|
+
formatBigIntToSafeValue(t, e) {
|
|
781
|
+
const r = e || this.decimal || S, n = Math.max(
|
|
782
|
+
r,
|
|
783
|
+
$(this.decimalMultiplier)
|
|
784
|
+
), i = t < 0n, a = t.toString().substring(i ? 1 : 0), c = n - (a.length - 1), u = c > 0 ? "0".repeat(c) + a : a, d = u.length - n;
|
|
785
|
+
let l = u.slice(-n);
|
|
786
|
+
return parseInt(l[r]) >= 5 ? l = `${l.substring(0, r - 1)}${(parseInt(l[r - 1]) + 1).toString()}` : l = l.substring(0, r), `${i ? "-" : ""}${u.slice(
|
|
787
|
+
0,
|
|
788
|
+
d
|
|
789
|
+
)}.${l}`.replace(/\.?0*$/, "");
|
|
790
790
|
}
|
|
791
791
|
};
|
|
792
|
-
|
|
793
|
-
const r = f(this, k, lt).call(this, this, ...e), n =
|
|
794
|
-
(
|
|
795
|
-
const l = this.getBigIntValue(
|
|
792
|
+
A = new WeakSet(), R = function(t, ...e) {
|
|
793
|
+
const r = f(this, k, lt).call(this, this, ...e), n = Math.max(r, $(this.decimalMultiplier)), i = y(n), a = e.reduce(
|
|
794
|
+
(u, d) => {
|
|
795
|
+
const l = this.getBigIntValue(d, n);
|
|
796
796
|
switch (t) {
|
|
797
797
|
case "add":
|
|
798
|
-
return
|
|
798
|
+
return u + l;
|
|
799
799
|
case "sub":
|
|
800
|
-
return
|
|
800
|
+
return u - l;
|
|
801
801
|
case "mul":
|
|
802
|
-
return
|
|
802
|
+
return u * l / i;
|
|
803
803
|
case "div": {
|
|
804
804
|
if (l === 0n)
|
|
805
805
|
throw new RangeError("Division by zero");
|
|
806
|
-
return
|
|
806
|
+
return u * i / l;
|
|
807
807
|
}
|
|
808
808
|
default:
|
|
809
|
-
return
|
|
809
|
+
return u;
|
|
810
810
|
}
|
|
811
811
|
},
|
|
812
812
|
//normalize is to precision multiplier base
|
|
813
|
-
this.bigIntValue *
|
|
813
|
+
this.bigIntValue * i / this.decimalMultiplier
|
|
814
814
|
), c = q({
|
|
815
|
-
bigIntDecimal:
|
|
816
|
-
decimal:
|
|
817
|
-
value:
|
|
815
|
+
bigIntDecimal: n,
|
|
816
|
+
decimal: n,
|
|
817
|
+
value: a
|
|
818
|
+
});
|
|
819
|
+
return new this.constructor({
|
|
820
|
+
decimalMultiplier: y(n),
|
|
821
|
+
decimal: this.decimal,
|
|
822
|
+
value: c,
|
|
823
|
+
identifier: this.toString()
|
|
818
824
|
});
|
|
819
|
-
return new this.constructor({ decimal: this.decimal, value: c, identifier: this.toString() });
|
|
820
825
|
}, x = new WeakSet(), ut = function(t) {
|
|
821
826
|
const e = O(t) || "0";
|
|
822
827
|
this.bigIntValue = f(this, I, D).call(this, e);
|
|
823
828
|
}, k = new WeakSet(), lt = function(...t) {
|
|
824
|
-
const e = t.map(
|
|
825
|
-
(r) => typeof r == "object" ? r.decimal || $(r.decimalMultiplier) : Z(O(r))
|
|
826
|
-
).filter(Boolean);
|
|
829
|
+
const e = t.map((r) => typeof r == "object" ? r.decimal || $(r.decimalMultiplier) : Z(O(r))).filter(Boolean);
|
|
827
830
|
return Math.max(...e, S);
|
|
828
831
|
}, I = new WeakSet(), D = function(t, e) {
|
|
829
|
-
const r = e ?
|
|
830
|
-
return BigInt(`${i}${
|
|
832
|
+
const r = e ? y(e) : this.decimalMultiplier, n = $(r), [i = "", a = ""] = t.split(".");
|
|
833
|
+
return BigInt(`${i}${a.padEnd(n, "0")}`);
|
|
831
834
|
};
|
|
832
835
|
let C = Y;
|
|
833
836
|
const Zt = Intl.NumberFormat("fullwide", {
|
|
@@ -855,9 +858,9 @@ const tt = (s) => {
|
|
|
855
858
|
}, et = async (s, t = 0) => {
|
|
856
859
|
Xt(s);
|
|
857
860
|
const e = await Rt(W(s)), r = M(t, e);
|
|
858
|
-
return new
|
|
861
|
+
return new w({ decimal: e, value: r, identifier: s });
|
|
859
862
|
};
|
|
860
|
-
class
|
|
863
|
+
class w extends C {
|
|
861
864
|
constructor(e) {
|
|
862
865
|
const r = "identifier" in e ? e.identifier : `${e.chain}.${e.symbol}`;
|
|
863
866
|
super(
|
|
@@ -887,21 +890,21 @@ class y extends C {
|
|
|
887
890
|
return et(e, r);
|
|
888
891
|
}
|
|
889
892
|
static fromStringSync(e, r = 0) {
|
|
890
|
-
const { isSynthetic: n } = W(e), { decimal: i, identifier:
|
|
893
|
+
const { isSynthetic: n } = W(e), { decimal: i, identifier: a } = tt(
|
|
891
894
|
e
|
|
892
|
-
),
|
|
893
|
-
return
|
|
895
|
+
), c = M(r, i);
|
|
896
|
+
return a ? new w({ decimal: i, identifier: a, value: c }) : n ? new w({ decimal: 8, identifier: e, value: c }) : void 0;
|
|
894
897
|
}
|
|
895
898
|
static async fromIdentifier(e, r = 0) {
|
|
896
899
|
return et(e, r);
|
|
897
900
|
}
|
|
898
901
|
static fromIdentifierSync(e, r = 0) {
|
|
899
|
-
const { decimal: n, identifier: i } = tt(e),
|
|
900
|
-
return new
|
|
902
|
+
const { decimal: n, identifier: i } = tt(e), a = M(r, n);
|
|
903
|
+
return new w({ decimal: n, identifier: i, value: a });
|
|
901
904
|
}
|
|
902
905
|
static fromChainOrSignature(e, r = 0) {
|
|
903
|
-
const { decimal: n, identifier: i } = St(e),
|
|
904
|
-
return new
|
|
906
|
+
const { decimal: n, identifier: i } = St(e), a = M(r, n);
|
|
907
|
+
return new w({ value: a, decimal: n, identifier: i });
|
|
905
908
|
}
|
|
906
909
|
static async loadStaticAssets() {
|
|
907
910
|
return new Promise(
|
|
@@ -912,12 +915,12 @@ class y extends C {
|
|
|
912
915
|
// eslint-disable-next-line @typescript-eslint/no-unused-vars
|
|
913
916
|
ThorchainList: n,
|
|
914
917
|
NativeList: i,
|
|
915
|
-
...
|
|
918
|
+
...a
|
|
916
919
|
} = await import("@swapkit/tokens");
|
|
917
|
-
F = [i, ...Object.values(
|
|
918
|
-
(u, { tokens:
|
|
919
|
-
const P = "decimals" in
|
|
920
|
-
u.set(
|
|
920
|
+
F = [i, ...Object.values(a)].reduce(
|
|
921
|
+
(u, { tokens: d }) => (d.forEach(({ identifier: l, chain: _, ...v }) => {
|
|
922
|
+
const P = "decimals" in v ? v.decimals : h[_];
|
|
923
|
+
u.set(l, { identifier: l, decimal: P });
|
|
921
924
|
}), u),
|
|
922
925
|
/* @__PURE__ */ new Map()
|
|
923
926
|
), e({ ok: !0 });
|
|
@@ -933,7 +936,7 @@ class y extends C {
|
|
|
933
936
|
}
|
|
934
937
|
}
|
|
935
938
|
const fe = (s) => {
|
|
936
|
-
const t =
|
|
939
|
+
const t = w.fromChainOrSignature(s);
|
|
937
940
|
switch (s) {
|
|
938
941
|
case o.Bitcoin:
|
|
939
942
|
case o.Litecoin:
|
|
@@ -951,14 +954,14 @@ const fe = (s) => {
|
|
|
951
954
|
return t.set(1e-8);
|
|
952
955
|
}
|
|
953
956
|
}, W = (s) => {
|
|
954
|
-
const t = s.slice(0, 14).includes("/"), [e, r] = s.split(".").pop().split("/"), n = s.includes(".") && !t ? s : `${o.THORChain}.${r}`, [i,
|
|
957
|
+
const t = s.slice(0, 14).includes("/"), [e, r] = s.split(".").pop().split("/"), n = s.includes(".") && !t ? s : `${o.THORChain}.${r}`, [i, a] = n.split("."), [c, u] = (t ? r : a).split("-");
|
|
955
958
|
return {
|
|
956
959
|
address: u == null ? void 0 : u.toLowerCase(),
|
|
957
960
|
chain: i,
|
|
958
|
-
isGasAsset: st({ chain: i, symbol:
|
|
961
|
+
isGasAsset: st({ chain: i, symbol: a }),
|
|
959
962
|
isSynthetic: t,
|
|
960
|
-
symbol: (t ? `${e}/` : "") + (u ? `${
|
|
961
|
-
ticker:
|
|
963
|
+
symbol: (t ? `${e}/` : "") + (u ? `${c}-${(u == null ? void 0 : u.toLowerCase()) ?? ""}` : a),
|
|
964
|
+
ticker: c
|
|
962
965
|
};
|
|
963
966
|
}, te = {
|
|
964
967
|
/**
|
|
@@ -1034,7 +1037,7 @@ class b extends C {
|
|
|
1034
1037
|
}
|
|
1035
1038
|
}
|
|
1036
1039
|
export {
|
|
1037
|
-
|
|
1040
|
+
w as AssetValue,
|
|
1038
1041
|
C as BigIntArithmetics,
|
|
1039
1042
|
Qt as RequestClient,
|
|
1040
1043
|
dt as SwapKitError,
|
package/package.json
CHANGED
|
@@ -2,22 +2,22 @@
|
|
|
2
2
|
"author": "swapkit-oss-team",
|
|
3
3
|
"description": "SwapKit Lib swapkit-helpers",
|
|
4
4
|
"dependencies": {
|
|
5
|
-
"ky": "1.1.
|
|
5
|
+
"ky": "1.1.3"
|
|
6
6
|
},
|
|
7
7
|
"devDependencies": {
|
|
8
|
-
"@vitest/coverage-istanbul": "0.34.
|
|
9
|
-
"vite": "4.
|
|
10
|
-
"vitest": "0.34.
|
|
11
|
-
"@internal/config": "0.0.0-rc.
|
|
12
|
-
"@swapkit/tokens": "1.0.0-rc.
|
|
13
|
-
"@swapkit/types": "1.0.0-rc.
|
|
8
|
+
"@vitest/coverage-istanbul": "0.34.6",
|
|
9
|
+
"vite": "4.5.0",
|
|
10
|
+
"vitest": "0.34.6",
|
|
11
|
+
"@internal/config": "0.0.0-rc.3",
|
|
12
|
+
"@swapkit/tokens": "1.0.0-rc.18",
|
|
13
|
+
"@swapkit/types": "1.0.0-rc.17"
|
|
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.18",
|
|
20
|
+
"@swapkit/types": "1.0.0-rc.17"
|
|
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.36",
|
|
46
46
|
"scripts": {
|
|
47
47
|
"build": "vite build",
|
|
48
48
|
"clean": "rm -rf dist vite.config.ts.* .turbo node_modules",
|
|
@@ -328,7 +328,6 @@ describe('SwapKitNumber', () => {
|
|
|
328
328
|
const result = skNumber1.mul(skNumber2);
|
|
329
329
|
|
|
330
330
|
// The exact result of 1.23 * 4.56 is 5.6088
|
|
331
|
-
// If we round it to 2 decimal places, we should get 5.61
|
|
332
331
|
expect(result.getValue('string')).toBe('5.609');
|
|
333
332
|
expect(result.getBaseValue('bigint')).toBe(5608n);
|
|
334
333
|
|
|
@@ -428,6 +427,26 @@ describe('SwapKitNumber', () => {
|
|
|
428
427
|
});
|
|
429
428
|
});
|
|
430
429
|
|
|
430
|
+
describe('extending multiplier without loosing precision', () => {
|
|
431
|
+
test('edge case 1', () => {
|
|
432
|
+
const asset1 = new SwapKitNumber({ value: 41.90963702, decimal: 8 });
|
|
433
|
+
const multiplier = 5.337952274462478;
|
|
434
|
+
const divider = 105.2562773915526;
|
|
435
|
+
const result = asset1.mul(multiplier).div(divider);
|
|
436
|
+
|
|
437
|
+
expect(result.getValue('string')).toBe('2.12539953');
|
|
438
|
+
});
|
|
439
|
+
|
|
440
|
+
test('edge case 2', () => {
|
|
441
|
+
const asset1 = new SwapKitNumber('41.90963702');
|
|
442
|
+
const multiplier = new SwapKitNumber('5.337952274462478');
|
|
443
|
+
const divider = new SwapKitNumber('105.2562773915526');
|
|
444
|
+
const result = asset1.mul(multiplier).div(divider);
|
|
445
|
+
|
|
446
|
+
expect(result.getValue('string')).toBe('2.125399527674726');
|
|
447
|
+
});
|
|
448
|
+
});
|
|
449
|
+
|
|
431
450
|
describe('gt', () => {
|
|
432
451
|
test('greater than', () => {
|
|
433
452
|
const skNumber1 = new SwapKitNumber(10);
|
|
@@ -124,8 +124,8 @@ export class AssetValue extends BigIntArithmetics {
|
|
|
124
124
|
const asset = tokenIdentifier
|
|
125
125
|
? new AssetValue({ decimal, identifier: tokenIdentifier, value: parsedValue })
|
|
126
126
|
: isSynthetic
|
|
127
|
-
|
|
128
|
-
|
|
127
|
+
? new AssetValue({ decimal: 8, identifier: assetString, value: parsedValue })
|
|
128
|
+
: undefined;
|
|
129
129
|
|
|
130
130
|
return asset;
|
|
131
131
|
}
|
|
@@ -11,6 +11,7 @@ export type NumberPrimitives = bigint | number | string;
|
|
|
11
11
|
type InitialisationValueType = NumberPrimitives | BigIntArithmetics | SwapKitNumber;
|
|
12
12
|
|
|
13
13
|
type SKBigIntParams = InitialisationValueType | { decimal?: number; value: number | string };
|
|
14
|
+
type AllowedNumberTypes = 'bigint' | 'number' | 'string';
|
|
14
15
|
|
|
15
16
|
const DEFAULT_DECIMAL = 8;
|
|
16
17
|
const toMultiplier = (decimal: number) => 10n ** BigInt(decimal);
|
|
@@ -83,12 +84,14 @@ export class BigIntArithmetics {
|
|
|
83
84
|
|
|
84
85
|
constructor(params: SKBigIntParams) {
|
|
85
86
|
const value = getStringValue(params);
|
|
86
|
-
|
|
87
|
+
const isComplex = typeof params === 'object';
|
|
88
|
+
this.decimal = isComplex ? params.decimal : undefined;
|
|
87
89
|
|
|
88
90
|
// use the multiplier to keep track of decimal point - defaults to 8 if lower than 8
|
|
89
|
-
this.decimalMultiplier =
|
|
90
|
-
|
|
91
|
-
|
|
91
|
+
this.decimalMultiplier =
|
|
92
|
+
isComplex && 'decimalMultiplier' in params
|
|
93
|
+
? params.decimalMultiplier
|
|
94
|
+
: toMultiplier(Math.max(getFloatDecimals(toSafeValue(value)), this.decimal || 0));
|
|
92
95
|
this.#setValue(value);
|
|
93
96
|
}
|
|
94
97
|
|
|
@@ -124,7 +127,8 @@ export class BigIntArithmetics {
|
|
|
124
127
|
return this.bigIntValue === this.getBigIntValue(value);
|
|
125
128
|
}
|
|
126
129
|
|
|
127
|
-
|
|
130
|
+
// @ts-expect-error False positive
|
|
131
|
+
getValue<T extends AllowedNumberTypes>(type: T): NumberPrimitivesType[T] {
|
|
128
132
|
const value = this.formatBigIntToSafeValue(
|
|
129
133
|
this.bigIntValue,
|
|
130
134
|
this.decimal || decimalFromMultiplier(this.decimalMultiplier),
|
|
@@ -132,31 +136,27 @@ export class BigIntArithmetics {
|
|
|
132
136
|
|
|
133
137
|
switch (type) {
|
|
134
138
|
case 'number':
|
|
135
|
-
|
|
136
|
-
return Number(value);
|
|
139
|
+
return Number(value) as NumberPrimitivesType[T];
|
|
137
140
|
case 'string':
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
return (this.bigIntValue * BigInt(this.decimal || 8n)) / this.decimalMultiplier;
|
|
141
|
+
return value as NumberPrimitivesType[T];
|
|
142
|
+
case 'bigint':
|
|
143
|
+
return ((this.bigIntValue * 10n ** BigInt(this.decimal || 8n)) /
|
|
144
|
+
this.decimalMultiplier) as NumberPrimitivesType[T];
|
|
143
145
|
}
|
|
144
146
|
}
|
|
145
147
|
|
|
146
|
-
|
|
148
|
+
// @ts-expect-error
|
|
149
|
+
getBaseValue<T extends AllowedNumberTypes>(type: T): NumberPrimitivesType[T] {
|
|
147
150
|
const divisor = this.decimalMultiplier / toMultiplier(this.decimal || BaseDecimal.THOR);
|
|
148
151
|
const baseValue = this.bigIntValue / divisor;
|
|
149
152
|
|
|
150
153
|
switch (type) {
|
|
151
154
|
case 'number':
|
|
152
|
-
|
|
153
|
-
return Number(baseValue);
|
|
155
|
+
return Number(baseValue) as NumberPrimitivesType[T];
|
|
154
156
|
case 'string':
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
// @ts-expect-error False positive
|
|
159
|
-
return baseValue;
|
|
157
|
+
return baseValue.toString() as NumberPrimitivesType[T];
|
|
158
|
+
case 'bigint':
|
|
159
|
+
return baseValue as NumberPrimitivesType[T];
|
|
160
160
|
}
|
|
161
161
|
}
|
|
162
162
|
|
|
@@ -170,39 +170,6 @@ export class BigIntArithmetics {
|
|
|
170
170
|
return this.#toBigInt(safeValue, decimal);
|
|
171
171
|
}
|
|
172
172
|
|
|
173
|
-
formatBigIntToSafeValue(value: bigint, decimal?: number) {
|
|
174
|
-
const bigIntDecimal = decimal || this.decimal || DEFAULT_DECIMAL;
|
|
175
|
-
const decimalToUseForConversion = Math.max(
|
|
176
|
-
bigIntDecimal,
|
|
177
|
-
decimalFromMultiplier(this.decimalMultiplier),
|
|
178
|
-
);
|
|
179
|
-
const isNegative = value < 0n;
|
|
180
|
-
|
|
181
|
-
const valueString = value.toString().substring(isNegative ? 1 : 0);
|
|
182
|
-
const padLength = decimalToUseForConversion - (valueString.length - 1);
|
|
183
|
-
|
|
184
|
-
const parsedValueString = padLength > 0 ? '0'.repeat(padLength) + valueString : valueString;
|
|
185
|
-
|
|
186
|
-
const decimalIndex = parsedValueString.length - decimalToUseForConversion;
|
|
187
|
-
let decimalString = parsedValueString.slice(-decimalToUseForConversion);
|
|
188
|
-
|
|
189
|
-
// Check if we need to round up
|
|
190
|
-
if (parseInt(decimalString[bigIntDecimal]) >= 5) {
|
|
191
|
-
// Increment the last decimal place and slice off the rest
|
|
192
|
-
decimalString = `${decimalString.substring(0, bigIntDecimal - 1)}${(
|
|
193
|
-
parseInt(decimalString[bigIntDecimal - 1]) + 1
|
|
194
|
-
).toString()}`;
|
|
195
|
-
} else {
|
|
196
|
-
// Just slice off the extra digits
|
|
197
|
-
decimalString = decimalString.substring(0, bigIntDecimal);
|
|
198
|
-
}
|
|
199
|
-
|
|
200
|
-
return `${isNegative ? '-' : ''}${parsedValueString.slice(
|
|
201
|
-
0,
|
|
202
|
-
decimalIndex,
|
|
203
|
-
)}.${decimalString}`.replace(/\.?0*$/, '');
|
|
204
|
-
}
|
|
205
|
-
|
|
206
173
|
toSignificant(significantDigits: number = 6) {
|
|
207
174
|
const [int, dec] = this.getValue('string').split('.');
|
|
208
175
|
const integer = int || '';
|
|
@@ -282,21 +249,55 @@ export class BigIntArithmetics {
|
|
|
282
249
|
!int && !dec
|
|
283
250
|
? '0.00'
|
|
284
251
|
: int === '0'
|
|
285
|
-
|
|
286
|
-
|
|
252
|
+
? `${parseFloat(`0.${dec}`)}`.replace('.', decimalSeparator)
|
|
253
|
+
: `${integer}${parseInt(dec) ? `${decimalSeparator}${dec.slice(0, decimal)}` : ''}`;
|
|
287
254
|
|
|
288
255
|
return `${currencyPosition === 'start' ? currency : ''}${parsedValue}${
|
|
289
256
|
currencyPosition === 'end' ? currency : ''
|
|
290
257
|
}`;
|
|
291
258
|
}
|
|
292
259
|
|
|
260
|
+
formatBigIntToSafeValue(value: bigint, decimal?: number) {
|
|
261
|
+
const bigIntDecimal = decimal || this.decimal || DEFAULT_DECIMAL;
|
|
262
|
+
const decimalToUseForConversion = Math.max(
|
|
263
|
+
bigIntDecimal,
|
|
264
|
+
decimalFromMultiplier(this.decimalMultiplier),
|
|
265
|
+
);
|
|
266
|
+
const isNegative = value < 0n;
|
|
267
|
+
|
|
268
|
+
const valueString = value.toString().substring(isNegative ? 1 : 0);
|
|
269
|
+
const padLength = decimalToUseForConversion - (valueString.length - 1);
|
|
270
|
+
|
|
271
|
+
const parsedValueString = padLength > 0 ? '0'.repeat(padLength) + valueString : valueString;
|
|
272
|
+
|
|
273
|
+
const decimalIndex = parsedValueString.length - decimalToUseForConversion;
|
|
274
|
+
let decimalString = parsedValueString.slice(-decimalToUseForConversion);
|
|
275
|
+
|
|
276
|
+
// Check if we need to round up
|
|
277
|
+
if (parseInt(decimalString[bigIntDecimal]) >= 5) {
|
|
278
|
+
// Increment the last decimal place and slice off the rest
|
|
279
|
+
decimalString = `${decimalString.substring(0, bigIntDecimal - 1)}${(
|
|
280
|
+
parseInt(decimalString[bigIntDecimal - 1]) + 1
|
|
281
|
+
).toString()}`;
|
|
282
|
+
} else {
|
|
283
|
+
// Just slice off the extra digits
|
|
284
|
+
decimalString = decimalString.substring(0, bigIntDecimal);
|
|
285
|
+
}
|
|
286
|
+
|
|
287
|
+
return `${isNegative ? '-' : ''}${parsedValueString.slice(
|
|
288
|
+
0,
|
|
289
|
+
decimalIndex,
|
|
290
|
+
)}.${decimalString}`.replace(/\.?0*$/, '');
|
|
291
|
+
}
|
|
292
|
+
|
|
293
293
|
#arithmetics(method: 'add' | 'sub' | 'mul' | 'div', ...args: InitialisationValueType[]): this {
|
|
294
294
|
const precisionDecimal = this.#retrievePrecisionDecimal(this, ...args);
|
|
295
|
-
const
|
|
295
|
+
const decimal = Math.max(precisionDecimal, decimalFromMultiplier(this.decimalMultiplier));
|
|
296
|
+
const precisionDecimalMultiplier = toMultiplier(decimal);
|
|
296
297
|
|
|
297
298
|
const result = args.reduce(
|
|
298
299
|
(acc: bigint, arg) => {
|
|
299
|
-
const value = this.getBigIntValue(arg,
|
|
300
|
+
const value = this.getBigIntValue(arg, decimal);
|
|
300
301
|
|
|
301
302
|
switch (method) {
|
|
302
303
|
case 'add':
|
|
@@ -326,13 +327,18 @@ export class BigIntArithmetics {
|
|
|
326
327
|
);
|
|
327
328
|
|
|
328
329
|
const value = formatBigIntToSafeValue({
|
|
329
|
-
bigIntDecimal:
|
|
330
|
-
decimal
|
|
330
|
+
bigIntDecimal: decimal,
|
|
331
|
+
decimal,
|
|
331
332
|
value: result,
|
|
332
333
|
});
|
|
333
334
|
|
|
334
335
|
// @ts-expect-error False positive
|
|
335
|
-
return new this.constructor({
|
|
336
|
+
return new this.constructor({
|
|
337
|
+
decimalMultiplier: toMultiplier(decimal),
|
|
338
|
+
decimal: this.decimal,
|
|
339
|
+
value,
|
|
340
|
+
identifier: this.toString(),
|
|
341
|
+
});
|
|
336
342
|
}
|
|
337
343
|
|
|
338
344
|
#setValue(value: InitialisationValueType) {
|
|
@@ -342,12 +348,16 @@ export class BigIntArithmetics {
|
|
|
342
348
|
|
|
343
349
|
#retrievePrecisionDecimal(...args: InitialisationValueType[]) {
|
|
344
350
|
const decimals = args
|
|
345
|
-
.map((arg) =>
|
|
346
|
-
typeof arg === 'object'
|
|
351
|
+
.map((arg) => {
|
|
352
|
+
const isObject = typeof arg === 'object';
|
|
353
|
+
const value = isObject
|
|
347
354
|
? arg.decimal || decimalFromMultiplier(arg.decimalMultiplier)
|
|
348
|
-
: getFloatDecimals(toSafeValue(arg))
|
|
349
|
-
|
|
355
|
+
: getFloatDecimals(toSafeValue(arg));
|
|
356
|
+
|
|
357
|
+
return value;
|
|
358
|
+
})
|
|
350
359
|
.filter(Boolean) as number[];
|
|
360
|
+
|
|
351
361
|
return Math.max(...decimals, DEFAULT_DECIMAL);
|
|
352
362
|
}
|
|
353
363
|
|