@swapkit/helpers 1.0.0-rc.11 → 1.0.0-rc.12
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 +1 -0
- package/dist/index.es.js +44 -37
- package/package.json +1 -1
- package/src/modules/__tests__/swapKitNumber.test.ts +31 -0
- package/src/modules/bigIntArithmetics.ts +14 -0
package/dist/index.cjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";var Te=Object.create;var H=Object.defineProperty;var Se=Object.getOwnPropertyDescriptor;var Re=Object.getOwnPropertyNames;var ve=Object.getPrototypeOf,Ie=Object.prototype.hasOwnProperty;var $e=(s,e,t)=>e in s?H(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t;var Be=(s,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of Re(e))!Ie.call(s,n)&&n!==t&&H(s,n,{get:()=>e[n],enumerable:!(r=Se(e,n))||r.enumerable});return s};var Ee=(s,e,t)=>(t=s!=null?Te(ve(s)):{},Be(e||!s||!s.__esModule?H(t,"default",{value:s,enumerable:!0}):t,s));var p=(s,e,t)=>($e(s,typeof e!="symbol"?e+"":e,t),t),Oe=(s,e,t)=>{if(!e.has(s))throw TypeError("Cannot "+t)};var _=(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 m=(s,e,t)=>(Oe(s,e,"access private method"),t);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const i=require("@swapkit/types"),Me="0x313ce567",ne=async({chain:s,to:e})=>{try{const{result:t}=await ge.post(i.ChainToRPC[s],{headers:{accept:"*/*","cache-control":"no-cache"},body:JSON.stringify({id:44,jsonrpc:"2.0",method:"eth_call",params:[{to:e.toLowerCase(),data:Me},"latest"]})});return parseInt(BigInt(t).toString())}catch(t){return console.error(t),i.BaseDecimal[s]}},Ve=async s=>{if(s===i.Chain.Ethereum)return i.BaseDecimal.ETH;const[,e]=s.split("-");return e!=null&&e.startsWith("0x")?ne({chain:i.Chain.Ethereum,to:e}):i.BaseDecimal.ETH},ke=async s=>{const[,e]=s.split("-");return e!=null&&e.startsWith("0x")?ne({chain:i.Chain.Avalanche,to:e.toLowerCase()}):i.BaseDecimal.AVAX},qe=async s=>(s===i.Chain.BinanceSmartChain,i.BaseDecimal.BSC),J=async({chain:s,symbol:e})=>{switch(s){case i.Chain.Ethereum:return Ve(e);case i.Chain.Avalanche:return ke(e);case i.Chain.BinanceSmartChain:return qe(e);default:return i.BaseDecimal[s]}},Pe={[i.FeeOption.Average]:1.2,[i.FeeOption.Fast]:1.5,[i.FeeOption.Fastest]:2},ie=({chain:s,symbol:e})=>{switch(s){case i.Chain.Bitcoin:case i.Chain.BitcoinCash:case i.Chain.Litecoin:case i.Chain.Dogecoin:case i.Chain.Binance:case i.Chain.Ethereum:case i.Chain.Avalanche:return e===s;case i.Chain.Arbitrum:case i.Chain.Optimism:return e==="ETH";case i.Chain.Maya:return e==="CACAO";case i.Chain.Kujira:return e==="KUJI";case i.Chain.Cosmos:return e==="ATOM";case i.Chain.Polygon:return e==="MATIC";case i.Chain.BinanceSmartChain:return e==="BNB";case i.Chain.THORChain:return e==="RUNE"}},ae=s=>{switch(s){case"ETH.THOR":return{identifier:"ETH.THOR-0xa5f2211b9b8170f694421f2046281775e8468044",decimal:18};case"ETH.vTHOR":return{identifier:"ETH.vTHOR-0x815c23eca83261b6ec689b60cc4a58b54bc24d8d",decimal:18};case i.Chain.Cosmos:return{identifier:"GAIA.ATOM",decimal:i.BaseDecimal[s]};case i.Chain.THORChain:return{identifier:"THOR.RUNE",decimal:i.BaseDecimal[s]};case i.Chain.BinanceSmartChain:return{identifier:"BSC.BNB",decimal:i.BaseDecimal[s]};case i.Chain.Maya:return{identifier:"MAYA.CACAO",decimal:i.BaseDecimal.MAYA};case"MAYA.MAYA":return{identifier:"MAYA.MAYA",decimal:4};case i.Chain.Kujira:case i.Chain.Arbitrum:case i.Chain.Optimism:case i.Chain.BitcoinCash:case i.Chain.Litecoin:case i.Chain.Dogecoin:case i.Chain.Binance:case i.Chain.Avalanche:case i.Chain.Polygon:case i.Chain.Bitcoin:case i.Chain.Ethereum:return{identifier:`${s}.${s}`,decimal:i.BaseDecimal[s]}}},oe=({chain:s,symbol:e})=>{if(e.includes("/"))return"Synth";switch(s){case i.Chain.Bitcoin:case i.Chain.BitcoinCash:case i.Chain.Dogecoin:case i.Chain.Litecoin:case i.Chain.Maya:case i.Chain.THORChain:return"Native";case i.Chain.Cosmos:return e==="ATOM"?"Native":i.Chain.Cosmos;case i.Chain.Kujira:return e===i.Chain.Kujira?"Native":i.Chain.Kujira;case i.Chain.Binance:return e===i.Chain.Binance?"Native":"BEP2";case i.Chain.BinanceSmartChain:return e===i.Chain.Binance?"Native":"BEP20";case i.Chain.Ethereum:return e===i.Chain.Ethereum?"Native":"ERC20";case i.Chain.Avalanche:return e===i.Chain.Avalanche?"Native":i.Chain.Avalanche;case i.Chain.Polygon:return e===i.Chain.Polygon?"Native":"POLYGON";case i.Chain.Arbitrum:return[i.Chain.Ethereum,i.Chain.Arbitrum].includes(e)?"Native":"ARBITRUM";case i.Chain.Optimism:return[i.Chain.Ethereum,i.Chain.Optimism].includes(e)?"Native":"OPTIMISM"}},De=s=>{var o;const[e,...t]=s.split("."),r=s.includes("/"),n=t.join("."),a=(o=n==null?void 0:n.split("-"))==null?void 0:o[0];return{chain:e,symbol:n,ticker:a,synth:r}},Ne=new RegExp(/(.)\1{6}|\.ORG|\.NET|\.FINANCE|\.COM|WWW|HTTP|\\\\|\/\/|[\s$%:[\]]/,"gmi"),xe=s=>s.filter(e=>!Ne.test(e.toString())&&!e.toString().includes("undefined")),ce=({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),l=r.mul(r),h=n.mul(n).mul(n);return o.mul(c.sub(u).add(l)).div(h)},ue=({liquidityUnits:s,poolUnits:e,assetDepth:t})=>{const r=d(s),n=d(e),a=d(t),o=r.mul(a),c=n.mul(n).mul(2),u=n.mul(r).mul(2),l=r.mul(r),h=o.mul(c.sub(u).add(l)),g=n.mul(n).mul(n);return h.div(g)},He=({percent:s,runeDepth:e,liquidityUnits:t,poolUnits:r})=>ce({runeDepth:e,liquidityUnits:t,poolUnits:r}).mul(s),je=({percent:s,assetDepth:e,liquidityUnits:t,poolUnits:r})=>ue({assetDepth:e,liquidityUnits:t,poolUnits:r}).mul(s),d=s=>new D({value:s,decimal:i.BaseDecimal.THOR}),le=({liquidityUnits:s,poolUnits:e,runeDepth:t,assetDepth:r})=>({assetAmount:d(r).mul(s).div(e),runeAmount:d(t).mul(s).div(e)}),Le=({liquidityUnits:s,poolUnits:e,runeDepth:t,assetDepth:r,percent:n})=>Object.fromEntries(Object.entries(le({liquidityUnits:s,poolUnits:e,runeDepth:t,assetDepth:r})).map(([a,o])=>[a,o.mul(n)])),Ue=({runeDepth:s,poolUnits:e,assetDepth:t,liquidityUnits:r,runeAmount:n,assetAmount:a})=>{const o=d(s),c=d(t),u=d(e),l=d(n),h=d(a),g=l.mul(c),C=h.mul(o),N=l.mul(h),be=o.mul(c),Ce=u.mul(g.add(C.add(N.mul(2)))),we=g.add(C.add(be.mul(2))),X=Ce.div(we),x=d(r).add(X);if(X.baseValueNumber===0)return x.div(u).baseValueNumber;const Ae=u.add(x);return x.div(Ae).baseValueNumber},Fe=({runeAmount:s,assetAmount:e,runeDepth:t,assetDepth:r})=>{const n=d(t),a=d(r),o=d(e),c=d(s),u=o.mul(n).sub(a.mul(c)),l=a.mul(c).add(n.mul(a));return Math.abs(u.div(l).baseValueNumber)},We=({symbol:s,ticker:e,chain:t})=>t==="ETH"&&e!=="ETH"?`${e}-${s.slice(-3)}`:s,Ge=(s,e)=>{switch(s){case i.MemoType.LEAVE:case i.MemoType.BOND:{const{address:t}=e;return`${s}:${t}`}case i.MemoType.UNBOND:{const{address:t,unbondAmount:r}=e;return`${s}:${t}:${r*10**8}`}case i.MemoType.THORNAME_REGISTER:{const{name:t,chain:r,address:n,owner:a}=e;return`${s}:${t}:${r}:${n}${a?`:${a}`:""}`}case i.MemoType.DEPOSIT:{const{chain:t,symbol:r,address:n,singleSide:a}=e;return a?`${s}:${t}/${r}::t:0`:`${s}:${t}.${r}:${n||""}:t:0`}case i.MemoType.WITHDRAW:{const{chain:t,ticker:r,symbol:n,basisPoints:a,targetAssetString:o,singleSide:c}=e,u=!c&&o?`:${o}`:"",l=We({chain:t,symbol:n,ticker:r});return`${s}:${t}${c?"/":"."}${l}:${a}${u}`}case i.MemoType.OPEN_LOAN:case i.MemoType.CLOSE_LOAN:{const{asset:t,address:r}=e;return`${s}:${t}:${r}`}default:return""}},Ye=s=>{if(s<0)throw new Error("Invalid number of year");return 10+s},ze=s=>{if(s.length>30)return!1;const e=/^[a-zA-Z0-9+_-]+$/g;return!!s.match(e)},Je=([s,e,t,r,n])=>`${s}'/${e}'/${t}'/${r}${typeof n!="number"?"":`/${n}`}`;class Z extends Error{constructor(e,t,r){const n=e.status||e.status===0?e.status:"",a=e.statusText||"",o=`${n} ${a}`.trim(),c=o?`status code ${o}`:"an unknown error";super(`Request failed with ${c}`),Object.defineProperty(this,"response",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"request",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"options",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.name="HTTPError",this.response=e,this.request=t,this.options=r}}class he extends Error{constructor(e){super("Request timed out"),Object.defineProperty(this,"request",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.name="TimeoutError",this.request=e}}const O=s=>s!==null&&typeof s=="object",E=(...s)=>{for(const e of s)if((!O(e)||Array.isArray(e))&&e!==void 0)throw new TypeError("The `options` argument must be an object");return K({},...s)},de=(s={},e={})=>{const t=new globalThis.Headers(s),r=e instanceof globalThis.Headers,n=new globalThis.Headers(e);for(const[a,o]of n.entries())r&&o==="undefined"||o===void 0?t.delete(a):t.set(a,o);return t},K=(...s)=>{let e={},t={};for(const r of s)if(Array.isArray(r))Array.isArray(e)||(e=[]),e=[...e,...r];else if(O(r)){for(let[n,a]of Object.entries(r))O(a)&&n in e&&(a=K(e[n],a)),e={...e,[n]:a};O(r.headers)&&(t=de(t,r.headers),e.headers=t)}return e},Ke=(()=>{let s=!1,e=!1;const t=typeof globalThis.ReadableStream=="function",r=typeof globalThis.Request=="function";return t&&r&&(e=new globalThis.Request("https://empty.invalid",{body:new globalThis.ReadableStream,method:"POST",get duplex(){return s=!0,"half"}}).headers.has("Content-Type")),s&&!e})(),Qe=typeof globalThis.AbortController=="function",Xe=typeof globalThis.ReadableStream=="function",Ze=typeof globalThis.FormData=="function",me=["get","post","put","patch","head","delete"],et={json:"application/json",text:"text/*",formData:"multipart/form-data",arrayBuffer:"*/*",blob:"*/*"},j=2147483647,pe=Symbol("stop"),tt={json:!0,parseJson:!0,searchParams:!0,prefixUrl:!0,retry:!0,timeout:!0,hooks:!0,throwHttpErrors:!0,onDownloadProgress:!0,fetch:!0},rt={method:!0,headers:!0,body:!0,mode:!0,credentials:!0,cache:!0,redirect:!0,referrer:!0,referrerPolicy:!0,integrity:!0,keepalive:!0,signal:!0,window:!0,dispatcher:!0,duplex:!0},st=s=>me.includes(s)?s.toUpperCase():s,nt=["get","put","head","delete","options","trace"],it=[408,413,429,500,502,503,504],fe=[413,429,503],ee={limit:2,methods:nt,statusCodes:it,afterStatusCodes:fe,maxRetryAfter:Number.POSITIVE_INFINITY,backoffLimit:Number.POSITIVE_INFINITY,delay:s=>.3*2**(s-1)*1e3},at=(s={})=>{if(typeof s=="number")return{...ee,limit:s};if(s.methods&&!Array.isArray(s.methods))throw new Error("retry.methods must be an array");if(s.statusCodes&&!Array.isArray(s.statusCodes))throw new Error("retry.statusCodes must be an array");return{...ee,...s,afterStatusCodes:fe}};async function ot(s,e,t,r){return new Promise((n,a)=>{const o=setTimeout(()=>{t&&t.abort(),a(new he(s))},r.timeout);r.fetch(s,e).then(n).catch(a).then(()=>{clearTimeout(o)})})}async function ct(s,{signal:e}){return new Promise((t,r)=>{e&&(e.throwIfAborted(),e.addEventListener("abort",n,{once:!0}));function n(){clearTimeout(a),r(e.reason)}const a=setTimeout(()=>{e==null||e.removeEventListener("abort",n),t()},s)})}const ut=(s,e)=>{const t={};for(const r in e)!(r in rt)&&!(r in tt)&&!(r in s)&&(t[r]=e[r]);return t};class V{static create(e,t){const r=new V(e,t),n=async()=>{if(typeof r._options.timeout=="number"&&r._options.timeout>j)throw new RangeError(`The \`timeout\` option cannot be greater than ${j}`);await Promise.resolve();let c=await r._fetch();for(const u of r._options.hooks.afterResponse){const l=await u(r.request,r._options,r._decorateResponse(c.clone()));l instanceof globalThis.Response&&(c=l)}if(r._decorateResponse(c),!c.ok&&r._options.throwHttpErrors){let u=new Z(c,r.request,r._options);for(const l of r._options.hooks.beforeError)u=await l(u);throw u}if(r._options.onDownloadProgress){if(typeof r._options.onDownloadProgress!="function")throw new TypeError("The `onDownloadProgress` option must be a function");if(!Xe)throw new Error("Streams are not supported in your environment. `ReadableStream` is missing.");return r._stream(c.clone(),r._options.onDownloadProgress)}return c},o=r._options.retry.methods.includes(r.request.method.toLowerCase())?r._retry(n):n();for(const[c,u]of Object.entries(et))o[c]=async()=>{r.request.headers.set("accept",r.request.headers.get("accept")||u);const h=(await o).clone();if(c==="json"){if(h.status===204||(await h.clone().arrayBuffer()).byteLength===0)return"";if(t.parseJson)return t.parseJson(await h.text())}return h[c]()};return o}constructor(e,t={}){if(Object.defineProperty(this,"request",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"abortController",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_retryCount",{enumerable:!0,configurable:!0,writable:!0,value:0}),Object.defineProperty(this,"_input",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_options",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this._input=e,this._options={credentials:this._input.credentials||"same-origin",...t,headers:de(this._input.headers,t.headers),hooks:K({beforeRequest:[],beforeRetry:[],beforeError:[],afterResponse:[]},t.hooks),method:st(t.method??this._input.method),prefixUrl:String(t.prefixUrl||""),retry:at(t.retry),throwHttpErrors:t.throwHttpErrors!==!1,timeout:t.timeout??1e4,fetch:t.fetch??globalThis.fetch.bind(globalThis)},typeof this._input!="string"&&!(this._input instanceof URL||this._input instanceof globalThis.Request))throw new TypeError("`input` must be a string, URL, or Request");if(this._options.prefixUrl&&typeof this._input=="string"){if(this._input.startsWith("/"))throw new Error("`input` must not begin with a slash when using `prefixUrl`");this._options.prefixUrl.endsWith("/")||(this._options.prefixUrl+="/"),this._input=this._options.prefixUrl+this._input}if(Qe){if(this.abortController=new globalThis.AbortController,this._options.signal){const r=this._options.signal;this._options.signal.addEventListener("abort",()=>{this.abortController.abort(r.reason)})}this._options.signal=this.abortController.signal}if(Ke&&(this._options.duplex="half"),this.request=new globalThis.Request(this._input,this._options),this._options.searchParams){const n="?"+(typeof this._options.searchParams=="string"?this._options.searchParams.replace(/^\?/,""):new URLSearchParams(this._options.searchParams).toString()),a=this.request.url.replace(/(?:\?.*?)?(?=#|$)/,n);(Ze&&this._options.body instanceof globalThis.FormData||this._options.body instanceof URLSearchParams)&&!(this._options.headers&&this._options.headers["content-type"])&&this.request.headers.delete("content-type"),this.request=new globalThis.Request(new globalThis.Request(a,{...this.request}),this._options)}this._options.json!==void 0&&(this._options.body=JSON.stringify(this._options.json),this.request.headers.set("content-type",this._options.headers.get("content-type")??"application/json"),this.request=new globalThis.Request(this.request,{body:this._options.body}))}_calculateRetryDelay(e){if(this._retryCount++,this._retryCount<this._options.retry.limit&&!(e instanceof he)){if(e instanceof Z){if(!this._options.retry.statusCodes.includes(e.response.status))return 0;const r=e.response.headers.get("Retry-After");if(r&&this._options.retry.afterStatusCodes.includes(e.response.status)){let n=Number(r);return Number.isNaN(n)?n=Date.parse(r)-Date.now():n*=1e3,this._options.retry.maxRetryAfter!==void 0&&n>this._options.retry.maxRetryAfter?0:n}if(e.response.status===413)return 0}const t=this._options.retry.delay(this._retryCount);return Math.min(this._options.retry.backoffLimit,t)}return 0}_decorateResponse(e){return this._options.parseJson&&(e.json=async()=>this._options.parseJson(await e.text())),e}async _retry(e){try{return await e()}catch(t){const r=Math.min(this._calculateRetryDelay(t),j);if(r!==0&&this._retryCount>0){await ct(r,{signal:this._options.signal});for(const n of this._options.hooks.beforeRetry)if(await n({request:this.request,options:this._options,error:t,retryCount:this._retryCount})===pe)return;return this._retry(e)}throw t}}async _fetch(){for(const t of this._options.hooks.beforeRequest){const r=await t(this.request,this._options);if(r instanceof Request){this.request=r;break}if(r instanceof Response)return r}const e=ut(this.request,this._options);return this._options.timeout===!1?this._options.fetch(this.request.clone(),e):ot(this.request.clone(),e,this.abortController,this._options)}_stream(e,t){const r=Number(e.headers.get("content-length"))||0;let n=0;return e.status===204?(t&&t({percent:1,totalBytes:r,transferredBytes:n},new Uint8Array),new globalThis.Response(null,{status:e.status,statusText:e.statusText,headers:e.headers})):new globalThis.Response(new globalThis.ReadableStream({async start(a){const o=e.body.getReader();t&&t({percent:0,transferredBytes:0,totalBytes:r},new Uint8Array);async function c(){const{done:u,value:l}=await o.read();if(u){a.close();return}if(t){n+=l.byteLength;const h=r===0?0:n/r;t({percent:h,transferredBytes:n,totalBytes:r},l)}a.enqueue(l),await c()}await c()}}),{status:e.status,statusText:e.statusText,headers:e.headers})}}/*! MIT License © Sindre Sorhus */const F=s=>{const e=(t,r)=>V.create(t,E(s,r));for(const t of me)e[t]=(r,n)=>V.create(r,E(s,n,{method:t}));return e.create=t=>F(E(t)),e.extend=t=>F(E(s,t)),e.stop=pe,e},lt=F(),ht=lt,te=ht.create({headers:{referrer:"https://sk.thorswap.net",referer:"https://sk.thorswap.net","Content-Type":"application/json"}}),ge={get:(s,e)=>te.get(s,e).json(),post:(s,e)=>te.post(s,e).json()},re=Object.values(i.Chain),dt=(s="")=>{const e=s.toUpperCase(),[t]=e.split(".");if(re.includes(t))return!0;const[r]=e.split("/");if(re.includes(r))return!0;throw new Error(`Invalid identifier: ${s}. Expected format: <Chain>.<Ticker> or <Chain>.<Ticker>-<ContractAddress>`)},v=8,w=s=>10n**BigInt(s),T=s=>Math.log10(parseFloat(s.toString()));function I({value:s,bigIntDecimal:e=v,decimal:t=v}){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 y,S,k,_e,q,ye,$,W,b,R,B,G;const P=class P{constructor(e){_(this,y);_(this,k);_(this,q);_(this,$);_(this,b);_(this,B);p(this,"decimalMultiplier",10n**8n);p(this,"bigIntValue",0n);p(this,"decimal");const t=L(e);this.decimal=typeof e=="object"?e.decimal:void 0,this.decimalMultiplier=w(Math.max(m(this,B,G).call(this,m(this,b,R).call(this,t)),this.decimal||0)),m(this,k,_e).call(this,t)}static fromBigInt(e,t){return new P({decimal:t,value:I({value:e,bigIntDecimal:t,decimal:t})})}static shiftDecimals({value:e,from:t,to:r}){return this.fromBigInt(new P(e).bigIntValue*w(r)/w(t),r)}get baseValue(){return this.getBaseValue("string")}get baseValueNumber(){return this.getBaseValue("number")}get baseValueBigInt(){return this.getBaseValue("bigint")}set(e){return new this.constructor({decimal:this.decimal,value:e,identifier:this.toString()})}add(...e){return m(this,y,S).call(this,"add",...e)}sub(...e){return m(this,y,S).call(this,"sub",...e)}mul(...e){return m(this,y,S).call(this,"mul",...e)}div(...e){return m(this,y,S).call(this,"div",...e)}gt(e){return this.bigIntValue>this.getBigIntValue(e)}gte(e){return this.bigIntValue>=this.getBigIntValue(e)}lt(e){return this.bigIntValue<this.getBigIntValue(e)}lte(e){return this.bigIntValue<=this.getBigIntValue(e)}eqValue(e){return this.bigIntValue===this.getBigIntValue(e)}getValue(e){const t=this.formatBigIntToSafeValue(this.bigIntValue,this.decimal||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/w(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=L(e),n=m(this,b,R).call(this,r);return n==="0"||n==="undefined"?0n:m(this,$,W).call(this,n,t)}formatBigIntToSafeValue(e,t){const r=t||this.decimal||v,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,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||"",o=parseInt(n)?n.length+a.length:a.length;if(o<=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(o-e,"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")}`}};y=new WeakSet,S=function(e,...t){const r=m(this,q,ye).call(this,this,...t),n=w(r),a=t.reduce((c,u)=>{const l=this.getBigIntValue(u,r);switch(e){case"add":return c+l;case"sub":return c-l;case"mul":return c*l/n;case"div":{if(l===0n)throw new RangeError("Division by zero");return c*n/l}default:return c}},this.bigIntValue*n/this.decimalMultiplier),o=I({bigIntDecimal:r,decimal:Math.max(r,T(this.decimalMultiplier)),value:a});return new this.constructor({decimal:this.decimal,value:o,identifier:this.toString()})},k=new WeakSet,_e=function(e){const t=m(this,b,R).call(this,e)||"0";this.bigIntValue=m(this,$,W).call(this,t)},q=new WeakSet,ye=function(...e){const t=e.map(r=>typeof r=="object"?r.decimal||T(r.decimalMultiplier):m(this,B,G).call(this,m(this,b,R).call(this,r))).filter(Boolean);return Math.max(...t,v)},$=new WeakSet,W=function(e,t){const r=t?w(t):this.decimalMultiplier,n=T(r),[a="",o=""]=e.split(".");return BigInt(`${a}${o.padEnd(n,"0")}`)},b=new WeakSet,R=function(e){const r=`${typeof e=="number"?Number(e).toLocaleString("fullwide",{useGrouping:!1,maximumFractionDigits:20}):L(e)}`.replaceAll(",",".").split(".");return r.length>1?`${r.slice(0,-1).join("")}.${r.at(-1)}`:r[0]},B=new WeakSet,G=function(e){var r;const t=((r=e.split(".")[1])==null?void 0:r.length)||0;return Math.max(t,v)};let A=P;function L(s){return typeof s=="object"?"getValue"in s?s.getValue("string"):s.value:s}const M=(s,e)=>typeof s=="bigint"?I({value:s,bigIntDecimal:e,decimal:e}):s;let Y;const U=s=>{if(!Y)throw new Error("Static assets not loaded, call await AssetValue.loadStaticAssets() first");return Y.get(s.toUpperCase())||{decimal:i.BaseDecimal.THOR,identifier:""}},se=async(s,e=0)=>{dt(s);const t=await J(z(s)),r=M(e,t);return new f({decimal:t,value:r,identifier:s})};class f extends A{constructor(t){super(t.value instanceof A?t.value:{decimal:t.decimal,value:t.value});p(this,"address");p(this,"chain");p(this,"isSynthetic",!1);p(this,"isGasAsset",!1);p(this,"symbol");p(this,"ticker");p(this,"type");const r="identifier"in t?t.identifier:`${t.chain}.${t.symbol}`,n=z(r);this.type=oe(n),this.chain=n.chain,this.ticker=n.ticker,this.symbol=n.symbol,this.address=n.address,this.isSynthetic=n.isSynthetic,this.isGasAsset=n.isGasAsset}get assetValue(){return`${this.getValue("string")} ${this.ticker}`}toString(t=!1){const r=this.isSynthetic?this.ticker:`${this.chain}.${this.ticker}`;return t?r:`${this.chain}.${this.symbol}`}eq({chain:t,symbol:r}){return this.chain===t&&this.symbol===r}static async fromString(t,r=0){return se(t,r)}static fromStringSync(t,r=0){const{decimal:n,identifier:a}=U(t),o=M(r,n);return a?new f({decimal:n,identifier:a,value:o}):void 0}static async fromIdentifier(t,r=0){return se(t,r)}static fromIdentifierSync(t,r=0){const{decimal:n,identifier:a}=U(t),o=M(r,n);return new f({decimal:n,identifier:a,value:o})}static fromChainOrSignature(t,r=0){const{decimal:n,identifier:a}=ae(t),o=M(r,n);return new f({value:o,decimal:n,identifier:a})}static async fromTCQuote(t,r=0){const n=await J(z(t)),a=this.shiftDecimals({value:r,from:i.BaseDecimal.THOR,to:n});return new f({value:a,identifier:t,decimal:n})}static fromTCQuoteStatic(t,r=0){const n=U(t),a=this.shiftDecimals({value:r,from:i.BaseDecimal.THOR,to:n.decimal});return new f({...n,value:a})}static async loadStaticAssets(){return new Promise(async(t,r)=>{try{const{ThorchainList:n,NativeList:a,...o}=await import("@swapkit/tokens");Y=[a,...Object.values(o)].reduce((u,{tokens:l})=>(l.forEach(({identifier:h,chain:g,...C})=>{const N="decimals"in C?C.decimals:i.BaseDecimal[g];u.set(h,{identifier:h,decimal:N})}),u),new Map),t({ok:!0})}catch(n){console.error(n),r({ok:!1,error:n,message:"Couldn't load static assets. Ensure you have installed @swapkit/tokens package"})}})}}const mt=s=>{const e=f.fromChainOrSignature(s);switch(s){case i.Chain.Bitcoin:case i.Chain.Litecoin:case i.Chain.BitcoinCash:return e.add(10001);case i.Chain.Dogecoin:return e.add(100000001);case i.Chain.Avalanche:case i.Chain.Ethereum:return e.add(10*10**9);case i.Chain.THORChain:case i.Chain.Maya:return e.add(0);default:return e.add(1)}},z=s=>{const e=s.slice(0,14).includes("/"),t=s.includes(".")?s:`${i.Chain.THORChain}.${s}`,[r,n]=t.split("."),[a,o]=n.split("-");return{address:o==null?void 0:o.toLowerCase(),chain:r,isGasAsset:ie({chain:r,symbol:n}),isSynthetic:e,symbol:o?`${a}-${(o==null?void 0:o.toLowerCase())??""}`:n,ticker:e?n:a}},pt={core_wallet_connection_not_found:10001,core_estimated_max_spendable_chain_not_supported:10002,core_extend_error:10003,core_inbound_data_not_found:10004,core_approve_asset_address_or_from_not_found:10005,core_chain_halted:10099,core_wallet_xdefi_not_installed:10101,core_wallet_evmwallet_not_installed:10102,core_wallet_walletconnect_not_installed:10103,core_wallet_keystore_not_installed:10104,core_wallet_ledger_not_installed:10105,core_wallet_trezor_not_installed:10106,core_wallet_keplr_not_installed:10107,core_wallet_okx_not_installed:10108,core_swap_invalid_params:10200,core_swap_route_not_complete:10201,core_swap_asset_not_recognized:10202,core_swap_contract_not_found:10203,core_swap_route_transaction_not_found:10204,core_swap_contract_not_supported:10205,core_swap_transaction_error:10206,core_swap_quote_mode_not_supported:10207,core_transaction_deposit_error:10301,core_transaction_create_liquidity_rune_error:10302,core_transaction_create_liquidity_asset_error:10303,core_transaction_create_liquidity_invalid_params:10304,core_transaction_add_liquidity_invalid_params:10305,core_transaction_add_liquidity_no_rune_address:10306,core_transaction_add_liquidity_rune_error:10307,core_transaction_add_liquidity_asset_error:10308,core_transaction_withdraw_error:10309,core_transaction_deposit_to_pool_error:10310,core_transaction_deposit_insufficient_funds_error:10311,core_transaction_deposit_gas_error:10312,core_transaction_deposit_server_error:10313,wallet_ledger_connection_error:20001,helpers_number_different_decimals:99101};class Q extends Error{constructor(e,t){console.error(t),super(e,{cause:{code:pt[e],message:e}}),Object.setPrototypeOf(this,Q.prototype)}}class D extends A{eq(e){return this.eqValue(e)}static fromBigInt(e,t){return new D({decimal:t,value:I({value:e,bigIntDecimal:t,decimal:t})})}}exports.AssetValue=f;exports.BigIntArithmetics=A;exports.RequestClient=ge;exports.SwapKitError=Q;exports.SwapKitNumber=D;exports.assetFromString=De;exports.derivationPathToString=Je;exports.filterAssets=xe;exports.formatBigIntToSafeValue=I;exports.gasFeeMultiplier=Pe;exports.getAssetType=oe;exports.getAsymmetricAssetShare=ue;exports.getAsymmetricAssetWithdrawAmount=je;exports.getAsymmetricRuneShare=ce;exports.getAsymmetricRuneWithdrawAmount=He;exports.getCommonAssetInfo=ae;exports.getDecimal=J;exports.getEstimatedPoolShare=Ue;exports.getLiquiditySlippage=Fe;exports.getMemoFor=Ge;exports.getMinAmountByChain=mt;exports.getSymmetricPoolShare=le;exports.getSymmetricWithdraw=Le;exports.getTHORNameCost=Ye;exports.isGasAsset=ie;exports.validateTHORName=ze;
|
|
1
|
+
"use strict";var Te=Object.create;var H=Object.defineProperty;var Se=Object.getOwnPropertyDescriptor;var ve=Object.getOwnPropertyNames;var Re=Object.getPrototypeOf,Ie=Object.prototype.hasOwnProperty;var $e=(s,e,t)=>e in s?H(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t;var Be=(s,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of ve(e))!Ie.call(s,n)&&n!==t&&H(s,n,{get:()=>e[n],enumerable:!(r=Se(e,n))||r.enumerable});return s};var Ee=(s,e,t)=>(t=s!=null?Te(Re(s)):{},Be(e||!s||!s.__esModule?H(t,"default",{value:s,enumerable:!0}):t,s));var p=(s,e,t)=>($e(s,typeof e!="symbol"?e+"":e,t),t),Oe=(s,e,t)=>{if(!e.has(s))throw TypeError("Cannot "+t)};var _=(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 m=(s,e,t)=>(Oe(s,e,"access private method"),t);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const i=require("@swapkit/types"),Me="0x313ce567",ne=async({chain:s,to:e})=>{try{const{result:t}=await ge.post(i.ChainToRPC[s],{headers:{accept:"*/*","cache-control":"no-cache"},body:JSON.stringify({id:44,jsonrpc:"2.0",method:"eth_call",params:[{to:e.toLowerCase(),data:Me},"latest"]})});return parseInt(BigInt(t).toString())}catch(t){return console.error(t),i.BaseDecimal[s]}},Ve=async s=>{if(s===i.Chain.Ethereum)return i.BaseDecimal.ETH;const[,e]=s.split("-");return e!=null&&e.startsWith("0x")?ne({chain:i.Chain.Ethereum,to:e}):i.BaseDecimal.ETH},ke=async s=>{const[,e]=s.split("-");return e!=null&&e.startsWith("0x")?ne({chain:i.Chain.Avalanche,to:e.toLowerCase()}):i.BaseDecimal.AVAX},qe=async s=>(s===i.Chain.BinanceSmartChain,i.BaseDecimal.BSC),z=async({chain:s,symbol:e})=>{switch(s){case i.Chain.Ethereum:return Ve(e);case i.Chain.Avalanche:return ke(e);case i.Chain.BinanceSmartChain:return qe(e);default:return i.BaseDecimal[s]}},Pe={[i.FeeOption.Average]:1.2,[i.FeeOption.Fast]:1.5,[i.FeeOption.Fastest]:2},ie=({chain:s,symbol:e})=>{switch(s){case i.Chain.Bitcoin:case i.Chain.BitcoinCash:case i.Chain.Litecoin:case i.Chain.Dogecoin:case i.Chain.Binance:case i.Chain.Ethereum:case i.Chain.Avalanche:return e===s;case i.Chain.Arbitrum:case i.Chain.Optimism:return e==="ETH";case i.Chain.Maya:return e==="CACAO";case i.Chain.Kujira:return e==="KUJI";case i.Chain.Cosmos:return e==="ATOM";case i.Chain.Polygon:return e==="MATIC";case i.Chain.BinanceSmartChain:return e==="BNB";case i.Chain.THORChain:return e==="RUNE"}},ae=s=>{switch(s){case"ETH.THOR":return{identifier:"ETH.THOR-0xa5f2211b9b8170f694421f2046281775e8468044",decimal:18};case"ETH.vTHOR":return{identifier:"ETH.vTHOR-0x815c23eca83261b6ec689b60cc4a58b54bc24d8d",decimal:18};case i.Chain.Cosmos:return{identifier:"GAIA.ATOM",decimal:i.BaseDecimal[s]};case i.Chain.THORChain:return{identifier:"THOR.RUNE",decimal:i.BaseDecimal[s]};case i.Chain.BinanceSmartChain:return{identifier:"BSC.BNB",decimal:i.BaseDecimal[s]};case i.Chain.Maya:return{identifier:"MAYA.CACAO",decimal:i.BaseDecimal.MAYA};case"MAYA.MAYA":return{identifier:"MAYA.MAYA",decimal:4};case i.Chain.Kujira:case i.Chain.Arbitrum:case i.Chain.Optimism:case i.Chain.BitcoinCash:case i.Chain.Litecoin:case i.Chain.Dogecoin:case i.Chain.Binance:case i.Chain.Avalanche:case i.Chain.Polygon:case i.Chain.Bitcoin:case i.Chain.Ethereum:return{identifier:`${s}.${s}`,decimal:i.BaseDecimal[s]}}},oe=({chain:s,symbol:e})=>{if(e.includes("/"))return"Synth";switch(s){case i.Chain.Bitcoin:case i.Chain.BitcoinCash:case i.Chain.Dogecoin:case i.Chain.Litecoin:case i.Chain.Maya:case i.Chain.THORChain:return"Native";case i.Chain.Cosmos:return e==="ATOM"?"Native":i.Chain.Cosmos;case i.Chain.Kujira:return e===i.Chain.Kujira?"Native":i.Chain.Kujira;case i.Chain.Binance:return e===i.Chain.Binance?"Native":"BEP2";case i.Chain.BinanceSmartChain:return e===i.Chain.Binance?"Native":"BEP20";case i.Chain.Ethereum:return e===i.Chain.Ethereum?"Native":"ERC20";case i.Chain.Avalanche:return e===i.Chain.Avalanche?"Native":i.Chain.Avalanche;case i.Chain.Polygon:return e===i.Chain.Polygon?"Native":"POLYGON";case i.Chain.Arbitrum:return[i.Chain.Ethereum,i.Chain.Arbitrum].includes(e)?"Native":"ARBITRUM";case i.Chain.Optimism:return[i.Chain.Ethereum,i.Chain.Optimism].includes(e)?"Native":"OPTIMISM"}},xe=s=>{var o;const[e,...t]=s.split("."),r=s.includes("/"),n=t.join("."),a=(o=n==null?void 0:n.split("-"))==null?void 0:o[0];return{chain:e,symbol:n,ticker:a,synth:r}},De=new RegExp(/(.)\1{6}|\.ORG|\.NET|\.FINANCE|\.COM|WWW|HTTP|\\\\|\/\/|[\s$%:[\]]/,"gmi"),Ne=s=>s.filter(e=>!De.test(e.toString())&&!e.toString().includes("undefined")),ce=({liquidityUnits:s,poolUnits:e,runeDepth:t})=>{const r=d(s),n=d(e),a=d(t),o=r.mul(a),c=n.mul(n).mul(2),u=n.mul(r).mul(2),l=r.mul(r),h=n.mul(n).mul(n);return o.mul(c.sub(u).add(l)).div(h)},ue=({liquidityUnits:s,poolUnits:e,assetDepth:t})=>{const r=d(s),n=d(e),a=d(t),o=r.mul(a),c=n.mul(n).mul(2),u=n.mul(r).mul(2),l=r.mul(r),h=o.mul(c.sub(u).add(l)),g=n.mul(n).mul(n);return h.div(g)},He=({percent:s,runeDepth:e,liquidityUnits:t,poolUnits:r})=>ce({runeDepth:e,liquidityUnits:t,poolUnits:r}).mul(s),je=({percent:s,assetDepth:e,liquidityUnits:t,poolUnits:r})=>ue({assetDepth:e,liquidityUnits:t,poolUnits:r}).mul(s),d=s=>new x({value:s,decimal:i.BaseDecimal.THOR}),le=({liquidityUnits:s,poolUnits:e,runeDepth:t,assetDepth:r})=>({assetAmount:d(r).mul(s).div(e),runeAmount:d(t).mul(s).div(e)}),Le=({liquidityUnits:s,poolUnits:e,runeDepth:t,assetDepth:r,percent:n})=>Object.fromEntries(Object.entries(le({liquidityUnits:s,poolUnits:e,runeDepth:t,assetDepth:r})).map(([a,o])=>[a,o.mul(n)])),Fe=({runeDepth:s,poolUnits:e,assetDepth:t,liquidityUnits:r,runeAmount:n,assetAmount:a})=>{const o=d(s),c=d(t),u=d(e),l=d(n),h=d(a),g=l.mul(c),C=h.mul(o),D=l.mul(h),ye=o.mul(c),Ce=u.mul(g.add(C.add(D.mul(2)))),we=g.add(C.add(ye.mul(2))),X=Ce.div(we),N=d(r).add(X);if(X.baseValueNumber===0)return N.div(u).baseValueNumber;const Ae=u.add(N);return N.div(Ae).baseValueNumber},Ue=({runeAmount:s,assetAmount:e,runeDepth:t,assetDepth:r})=>{const n=d(t),a=d(r),o=d(e),c=d(s),u=o.mul(n).sub(a.mul(c)),l=a.mul(c).add(n.mul(a));return Math.abs(u.div(l).baseValueNumber)},We=({symbol:s,ticker:e,chain:t})=>t==="ETH"&&e!=="ETH"?`${e}-${s.slice(-3)}`:s,Ge=(s,e)=>{switch(s){case i.MemoType.LEAVE:case i.MemoType.BOND:{const{address:t}=e;return`${s}:${t}`}case i.MemoType.UNBOND:{const{address:t,unbondAmount:r}=e;return`${s}:${t}:${r*10**8}`}case i.MemoType.THORNAME_REGISTER:{const{name:t,chain:r,address:n,owner:a}=e;return`${s}:${t}:${r}:${n}${a?`:${a}`:""}`}case i.MemoType.DEPOSIT:{const{chain:t,symbol:r,address:n,singleSide:a}=e;return a?`${s}:${t}/${r}::t:0`:`${s}:${t}.${r}:${n||""}:t:0`}case i.MemoType.WITHDRAW:{const{chain:t,ticker:r,symbol:n,basisPoints:a,targetAssetString:o,singleSide:c}=e,u=!c&&o?`:${o}`:"",l=We({chain:t,symbol:n,ticker:r});return`${s}:${t}${c?"/":"."}${l}:${a}${u}`}case i.MemoType.OPEN_LOAN:case i.MemoType.CLOSE_LOAN:{const{asset:t,address:r}=e;return`${s}:${t}:${r}`}default:return""}},Ke=s=>{if(s<0)throw new Error("Invalid number of year");return 10+s},Ye=s=>{if(s.length>30)return!1;const e=/^[a-zA-Z0-9+_-]+$/g;return!!s.match(e)},ze=([s,e,t,r,n])=>`${s}'/${e}'/${t}'/${r}${typeof n!="number"?"":`/${n}`}`;class Z extends Error{constructor(e,t,r){const n=e.status||e.status===0?e.status:"",a=e.statusText||"",o=`${n} ${a}`.trim(),c=o?`status code ${o}`:"an unknown error";super(`Request failed with ${c}`),Object.defineProperty(this,"response",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"request",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"options",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.name="HTTPError",this.response=e,this.request=t,this.options=r}}class he extends Error{constructor(e){super("Request timed out"),Object.defineProperty(this,"request",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.name="TimeoutError",this.request=e}}const O=s=>s!==null&&typeof s=="object",E=(...s)=>{for(const e of s)if((!O(e)||Array.isArray(e))&&e!==void 0)throw new TypeError("The `options` argument must be an object");return J({},...s)},de=(s={},e={})=>{const t=new globalThis.Headers(s),r=e instanceof globalThis.Headers,n=new globalThis.Headers(e);for(const[a,o]of n.entries())r&&o==="undefined"||o===void 0?t.delete(a):t.set(a,o);return t},J=(...s)=>{let e={},t={};for(const r of s)if(Array.isArray(r))Array.isArray(e)||(e=[]),e=[...e,...r];else if(O(r)){for(let[n,a]of Object.entries(r))O(a)&&n in e&&(a=J(e[n],a)),e={...e,[n]:a};O(r.headers)&&(t=de(t,r.headers),e.headers=t)}return e},Je=(()=>{let s=!1,e=!1;const t=typeof globalThis.ReadableStream=="function",r=typeof globalThis.Request=="function";return t&&r&&(e=new globalThis.Request("https://empty.invalid",{body:new globalThis.ReadableStream,method:"POST",get duplex(){return s=!0,"half"}}).headers.has("Content-Type")),s&&!e})(),Qe=typeof globalThis.AbortController=="function",Xe=typeof globalThis.ReadableStream=="function",Ze=typeof globalThis.FormData=="function",me=["get","post","put","patch","head","delete"],et={json:"application/json",text:"text/*",formData:"multipart/form-data",arrayBuffer:"*/*",blob:"*/*"},j=2147483647,pe=Symbol("stop"),tt={json:!0,parseJson:!0,searchParams:!0,prefixUrl:!0,retry:!0,timeout:!0,hooks:!0,throwHttpErrors:!0,onDownloadProgress:!0,fetch:!0},rt={method:!0,headers:!0,body:!0,mode:!0,credentials:!0,cache:!0,redirect:!0,referrer:!0,referrerPolicy:!0,integrity:!0,keepalive:!0,signal:!0,window:!0,dispatcher:!0,duplex:!0},st=s=>me.includes(s)?s.toUpperCase():s,nt=["get","put","head","delete","options","trace"],it=[408,413,429,500,502,503,504],fe=[413,429,503],ee={limit:2,methods:nt,statusCodes:it,afterStatusCodes:fe,maxRetryAfter:Number.POSITIVE_INFINITY,backoffLimit:Number.POSITIVE_INFINITY,delay:s=>.3*2**(s-1)*1e3},at=(s={})=>{if(typeof s=="number")return{...ee,limit:s};if(s.methods&&!Array.isArray(s.methods))throw new Error("retry.methods must be an array");if(s.statusCodes&&!Array.isArray(s.statusCodes))throw new Error("retry.statusCodes must be an array");return{...ee,...s,afterStatusCodes:fe}};async function ot(s,e,t,r){return new Promise((n,a)=>{const o=setTimeout(()=>{t&&t.abort(),a(new he(s))},r.timeout);r.fetch(s,e).then(n).catch(a).then(()=>{clearTimeout(o)})})}async function ct(s,{signal:e}){return new Promise((t,r)=>{e&&(e.throwIfAborted(),e.addEventListener("abort",n,{once:!0}));function n(){clearTimeout(a),r(e.reason)}const a=setTimeout(()=>{e==null||e.removeEventListener("abort",n),t()},s)})}const ut=(s,e)=>{const t={};for(const r in e)!(r in rt)&&!(r in tt)&&!(r in s)&&(t[r]=e[r]);return t};class V{static create(e,t){const r=new V(e,t),n=async()=>{if(typeof r._options.timeout=="number"&&r._options.timeout>j)throw new RangeError(`The \`timeout\` option cannot be greater than ${j}`);await Promise.resolve();let c=await r._fetch();for(const u of r._options.hooks.afterResponse){const l=await u(r.request,r._options,r._decorateResponse(c.clone()));l instanceof globalThis.Response&&(c=l)}if(r._decorateResponse(c),!c.ok&&r._options.throwHttpErrors){let u=new Z(c,r.request,r._options);for(const l of r._options.hooks.beforeError)u=await l(u);throw u}if(r._options.onDownloadProgress){if(typeof r._options.onDownloadProgress!="function")throw new TypeError("The `onDownloadProgress` option must be a function");if(!Xe)throw new Error("Streams are not supported in your environment. `ReadableStream` is missing.");return r._stream(c.clone(),r._options.onDownloadProgress)}return c},o=r._options.retry.methods.includes(r.request.method.toLowerCase())?r._retry(n):n();for(const[c,u]of Object.entries(et))o[c]=async()=>{r.request.headers.set("accept",r.request.headers.get("accept")||u);const h=(await o).clone();if(c==="json"){if(h.status===204||(await h.clone().arrayBuffer()).byteLength===0)return"";if(t.parseJson)return t.parseJson(await h.text())}return h[c]()};return o}constructor(e,t={}){if(Object.defineProperty(this,"request",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"abortController",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_retryCount",{enumerable:!0,configurable:!0,writable:!0,value:0}),Object.defineProperty(this,"_input",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_options",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this._input=e,this._options={credentials:this._input.credentials||"same-origin",...t,headers:de(this._input.headers,t.headers),hooks:J({beforeRequest:[],beforeRetry:[],beforeError:[],afterResponse:[]},t.hooks),method:st(t.method??this._input.method),prefixUrl:String(t.prefixUrl||""),retry:at(t.retry),throwHttpErrors:t.throwHttpErrors!==!1,timeout:t.timeout??1e4,fetch:t.fetch??globalThis.fetch.bind(globalThis)},typeof this._input!="string"&&!(this._input instanceof URL||this._input instanceof globalThis.Request))throw new TypeError("`input` must be a string, URL, or Request");if(this._options.prefixUrl&&typeof this._input=="string"){if(this._input.startsWith("/"))throw new Error("`input` must not begin with a slash when using `prefixUrl`");this._options.prefixUrl.endsWith("/")||(this._options.prefixUrl+="/"),this._input=this._options.prefixUrl+this._input}if(Qe){if(this.abortController=new globalThis.AbortController,this._options.signal){const r=this._options.signal;this._options.signal.addEventListener("abort",()=>{this.abortController.abort(r.reason)})}this._options.signal=this.abortController.signal}if(Je&&(this._options.duplex="half"),this.request=new globalThis.Request(this._input,this._options),this._options.searchParams){const n="?"+(typeof this._options.searchParams=="string"?this._options.searchParams.replace(/^\?/,""):new URLSearchParams(this._options.searchParams).toString()),a=this.request.url.replace(/(?:\?.*?)?(?=#|$)/,n);(Ze&&this._options.body instanceof globalThis.FormData||this._options.body instanceof URLSearchParams)&&!(this._options.headers&&this._options.headers["content-type"])&&this.request.headers.delete("content-type"),this.request=new globalThis.Request(new globalThis.Request(a,{...this.request}),this._options)}this._options.json!==void 0&&(this._options.body=JSON.stringify(this._options.json),this.request.headers.set("content-type",this._options.headers.get("content-type")??"application/json"),this.request=new globalThis.Request(this.request,{body:this._options.body}))}_calculateRetryDelay(e){if(this._retryCount++,this._retryCount<this._options.retry.limit&&!(e instanceof he)){if(e instanceof Z){if(!this._options.retry.statusCodes.includes(e.response.status))return 0;const r=e.response.headers.get("Retry-After");if(r&&this._options.retry.afterStatusCodes.includes(e.response.status)){let n=Number(r);return Number.isNaN(n)?n=Date.parse(r)-Date.now():n*=1e3,this._options.retry.maxRetryAfter!==void 0&&n>this._options.retry.maxRetryAfter?0:n}if(e.response.status===413)return 0}const t=this._options.retry.delay(this._retryCount);return Math.min(this._options.retry.backoffLimit,t)}return 0}_decorateResponse(e){return this._options.parseJson&&(e.json=async()=>this._options.parseJson(await e.text())),e}async _retry(e){try{return await e()}catch(t){const r=Math.min(this._calculateRetryDelay(t),j);if(r!==0&&this._retryCount>0){await ct(r,{signal:this._options.signal});for(const n of this._options.hooks.beforeRetry)if(await n({request:this.request,options:this._options,error:t,retryCount:this._retryCount})===pe)return;return this._retry(e)}throw t}}async _fetch(){for(const t of this._options.hooks.beforeRequest){const r=await t(this.request,this._options);if(r instanceof Request){this.request=r;break}if(r instanceof Response)return r}const e=ut(this.request,this._options);return this._options.timeout===!1?this._options.fetch(this.request.clone(),e):ot(this.request.clone(),e,this.abortController,this._options)}_stream(e,t){const r=Number(e.headers.get("content-length"))||0;let n=0;return e.status===204?(t&&t({percent:1,totalBytes:r,transferredBytes:n},new Uint8Array),new globalThis.Response(null,{status:e.status,statusText:e.statusText,headers:e.headers})):new globalThis.Response(new globalThis.ReadableStream({async start(a){const o=e.body.getReader();t&&t({percent:0,transferredBytes:0,totalBytes:r},new Uint8Array);async function c(){const{done:u,value:l}=await o.read();if(u){a.close();return}if(t){n+=l.byteLength;const h=r===0?0:n/r;t({percent:h,transferredBytes:n,totalBytes:r},l)}a.enqueue(l),await c()}await c()}}),{status:e.status,statusText:e.statusText,headers:e.headers})}}/*! MIT License © Sindre Sorhus */const U=s=>{const e=(t,r)=>V.create(t,E(s,r));for(const t of me)e[t]=(r,n)=>V.create(r,E(s,n,{method:t}));return e.create=t=>U(E(t)),e.extend=t=>U(E(s,t)),e.stop=pe,e},lt=U(),ht=lt,te=ht.create({headers:{referrer:"https://sk.thorswap.net",referer:"https://sk.thorswap.net","Content-Type":"application/json"}}),ge={get:(s,e)=>te.get(s,e).json(),post:(s,e)=>te.post(s,e).json()},re=Object.values(i.Chain),dt=(s="")=>{const e=s.toUpperCase(),[t]=e.split(".");if(re.includes(t))return!0;const[r]=e.split("/");if(re.includes(r))return!0;throw new Error(`Invalid identifier: ${s}. Expected format: <Chain>.<Ticker> or <Chain>.<Ticker>-<ContractAddress>`)},R=8,w=s=>10n**BigInt(s),T=s=>Math.log10(parseFloat(s.toString()));function I({value:s,bigIntDecimal:e=R,decimal:t=R}){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,S,k,_e,q,be,$,W,y,v,B,G;const P=class P{constructor(e){_(this,b);_(this,k);_(this,q);_(this,$);_(this,y);_(this,B);p(this,"decimalMultiplier",10n**8n);p(this,"bigIntValue",0n);p(this,"decimal");const t=L(e);this.decimal=typeof e=="object"?e.decimal:void 0,this.decimalMultiplier=w(Math.max(m(this,B,G).call(this,m(this,y,v).call(this,t)),this.decimal||0)),m(this,k,_e).call(this,t)}static fromBigInt(e,t){return new P({decimal:t,value:I({value:e,bigIntDecimal:t,decimal:t})})}static shiftDecimals({value:e,from:t,to:r}){return this.fromBigInt(new P(e).bigIntValue*w(r)/w(t),r)}get baseValue(){return this.getBaseValue("string")}get baseValueNumber(){return this.getBaseValue("number")}get baseValueBigInt(){return this.getBaseValue("bigint")}set(e){return new this.constructor({decimal:this.decimal,value:e,identifier:this.toString()})}add(...e){return m(this,b,S).call(this,"add",...e)}sub(...e){return m(this,b,S).call(this,"sub",...e)}mul(...e){return m(this,b,S).call(this,"mul",...e)}div(...e){return m(this,b,S).call(this,"div",...e)}gt(e){return this.bigIntValue>this.getBigIntValue(e)}gte(e){return this.bigIntValue>=this.getBigIntValue(e)}lt(e){return this.bigIntValue<this.getBigIntValue(e)}lte(e){return this.bigIntValue<=this.getBigIntValue(e)}eqValue(e){return this.bigIntValue===this.getBigIntValue(e)}getValue(e){const t=this.formatBigIntToSafeValue(this.bigIntValue,this.decimal||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/w(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=L(e),n=m(this,y,v).call(this,r);return n==="0"||n==="undefined"?0n:m(this,$,W).call(this,n,t)}formatBigIntToSafeValue(e,t){const r=t||this.decimal||R,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,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||"",o=parseInt(n)?n.length+a.length:a.length;if(o<=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(o-e,"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 t;const o=10**(n*3);return`${(t/o).toFixed(e)}${a}`}};b=new WeakSet,S=function(e,...t){const r=m(this,q,be).call(this,this,...t),n=w(r),a=t.reduce((c,u)=>{const l=this.getBigIntValue(u,r);switch(e){case"add":return c+l;case"sub":return c-l;case"mul":return c*l/n;case"div":{if(l===0n)throw new RangeError("Division by zero");return c*n/l}default:return c}},this.bigIntValue*n/this.decimalMultiplier),o=I({bigIntDecimal:r,decimal:Math.max(r,T(this.decimalMultiplier)),value:a});return new this.constructor({decimal:this.decimal,value:o,identifier:this.toString()})},k=new WeakSet,_e=function(e){const t=m(this,y,v).call(this,e)||"0";this.bigIntValue=m(this,$,W).call(this,t)},q=new WeakSet,be=function(...e){const t=e.map(r=>typeof r=="object"?r.decimal||T(r.decimalMultiplier):m(this,B,G).call(this,m(this,y,v).call(this,r))).filter(Boolean);return Math.max(...t,R)},$=new WeakSet,W=function(e,t){const r=t?w(t):this.decimalMultiplier,n=T(r),[a="",o=""]=e.split(".");return BigInt(`${a}${o.padEnd(n,"0")}`)},y=new WeakSet,v=function(e){const r=`${typeof e=="number"?Number(e).toLocaleString("fullwide",{useGrouping:!1,maximumFractionDigits:20}):L(e)}`.replaceAll(",",".").split(".");return r.length>1?`${r.slice(0,-1).join("")}.${r.at(-1)}`:r[0]},B=new WeakSet,G=function(e){var r;const t=((r=e.split(".")[1])==null?void 0:r.length)||0;return Math.max(t,R)};let A=P;function L(s){return typeof s=="object"?"getValue"in s?s.getValue("string"):s.value:s}const M=(s,e)=>typeof s=="bigint"?I({value:s,bigIntDecimal:e,decimal:e}):s;let K;const F=s=>{if(!K)throw new Error("Static assets not loaded, call await AssetValue.loadStaticAssets() first");return K.get(s.toUpperCase())||{decimal:i.BaseDecimal.THOR,identifier:""}},se=async(s,e=0)=>{dt(s);const t=await z(Y(s)),r=M(e,t);return new f({decimal:t,value:r,identifier:s})};class f extends A{constructor(t){super(t.value instanceof A?t.value:{decimal:t.decimal,value:t.value});p(this,"address");p(this,"chain");p(this,"isSynthetic",!1);p(this,"isGasAsset",!1);p(this,"symbol");p(this,"ticker");p(this,"type");const r="identifier"in t?t.identifier:`${t.chain}.${t.symbol}`,n=Y(r);this.type=oe(n),this.chain=n.chain,this.ticker=n.ticker,this.symbol=n.symbol,this.address=n.address,this.isSynthetic=n.isSynthetic,this.isGasAsset=n.isGasAsset}get assetValue(){return`${this.getValue("string")} ${this.ticker}`}toString(t=!1){const r=this.isSynthetic?this.ticker:`${this.chain}.${this.ticker}`;return t?r:`${this.chain}.${this.symbol}`}eq({chain:t,symbol:r}){return this.chain===t&&this.symbol===r}static async fromString(t,r=0){return se(t,r)}static fromStringSync(t,r=0){const{decimal:n,identifier:a}=F(t),o=M(r,n);return a?new f({decimal:n,identifier:a,value:o}):void 0}static async fromIdentifier(t,r=0){return se(t,r)}static fromIdentifierSync(t,r=0){const{decimal:n,identifier:a}=F(t),o=M(r,n);return new f({decimal:n,identifier:a,value:o})}static fromChainOrSignature(t,r=0){const{decimal:n,identifier:a}=ae(t),o=M(r,n);return new f({value:o,decimal:n,identifier:a})}static async fromTCQuote(t,r=0){const n=await z(Y(t)),a=this.shiftDecimals({value:r,from:i.BaseDecimal.THOR,to:n});return new f({value:a,identifier:t,decimal:n})}static fromTCQuoteStatic(t,r=0){const n=F(t),a=this.shiftDecimals({value:r,from:i.BaseDecimal.THOR,to:n.decimal});return new f({...n,value:a})}static async loadStaticAssets(){return new Promise(async(t,r)=>{try{const{ThorchainList:n,NativeList:a,...o}=await import("@swapkit/tokens");K=[a,...Object.values(o)].reduce((u,{tokens:l})=>(l.forEach(({identifier:h,chain:g,...C})=>{const D="decimals"in C?C.decimals:i.BaseDecimal[g];u.set(h,{identifier:h,decimal:D})}),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 mt=s=>{const e=f.fromChainOrSignature(s);switch(s){case i.Chain.Bitcoin:case i.Chain.Litecoin:case i.Chain.BitcoinCash:return e.add(10001);case i.Chain.Dogecoin:return e.add(100000001);case i.Chain.Avalanche:case i.Chain.Ethereum:return e.add(10*10**9);case i.Chain.THORChain:case i.Chain.Maya:return e.add(0);default:return e.add(1)}},Y=s=>{const e=s.slice(0,14).includes("/"),t=s.includes(".")?s:`${i.Chain.THORChain}.${s}`,[r,n]=t.split("."),[a,o]=n.split("-");return{address:o==null?void 0:o.toLowerCase(),chain:r,isGasAsset:ie({chain:r,symbol:n}),isSynthetic:e,symbol:o?`${a}-${(o==null?void 0:o.toLowerCase())??""}`:n,ticker:e?n:a}},pt={core_wallet_connection_not_found:10001,core_estimated_max_spendable_chain_not_supported:10002,core_extend_error:10003,core_inbound_data_not_found:10004,core_approve_asset_address_or_from_not_found:10005,core_chain_halted:10099,core_wallet_xdefi_not_installed:10101,core_wallet_evmwallet_not_installed:10102,core_wallet_walletconnect_not_installed:10103,core_wallet_keystore_not_installed:10104,core_wallet_ledger_not_installed:10105,core_wallet_trezor_not_installed:10106,core_wallet_keplr_not_installed:10107,core_wallet_okx_not_installed:10108,core_swap_invalid_params:10200,core_swap_route_not_complete:10201,core_swap_asset_not_recognized:10202,core_swap_contract_not_found:10203,core_swap_route_transaction_not_found:10204,core_swap_contract_not_supported:10205,core_swap_transaction_error:10206,core_swap_quote_mode_not_supported:10207,core_transaction_deposit_error:10301,core_transaction_create_liquidity_rune_error:10302,core_transaction_create_liquidity_asset_error:10303,core_transaction_create_liquidity_invalid_params:10304,core_transaction_add_liquidity_invalid_params:10305,core_transaction_add_liquidity_no_rune_address:10306,core_transaction_add_liquidity_rune_error:10307,core_transaction_add_liquidity_asset_error:10308,core_transaction_withdraw_error:10309,core_transaction_deposit_to_pool_error:10310,core_transaction_deposit_insufficient_funds_error:10311,core_transaction_deposit_gas_error:10312,core_transaction_deposit_server_error:10313,wallet_ledger_connection_error:20001,helpers_number_different_decimals:99101};class Q extends Error{constructor(e,t){console.error(t),super(e,{cause:{code:pt[e],message:e}}),Object.setPrototypeOf(this,Q.prototype)}}class x extends A{eq(e){return this.eqValue(e)}static fromBigInt(e,t){return new x({decimal:t,value:I({value:e,bigIntDecimal:t,decimal:t})})}}exports.AssetValue=f;exports.BigIntArithmetics=A;exports.RequestClient=ge;exports.SwapKitError=Q;exports.SwapKitNumber=x;exports.assetFromString=xe;exports.derivationPathToString=ze;exports.filterAssets=Ne;exports.formatBigIntToSafeValue=I;exports.gasFeeMultiplier=Pe;exports.getAssetType=oe;exports.getAsymmetricAssetShare=ue;exports.getAsymmetricAssetWithdrawAmount=je;exports.getAsymmetricRuneShare=ce;exports.getAsymmetricRuneWithdrawAmount=He;exports.getCommonAssetInfo=ae;exports.getDecimal=z;exports.getEstimatedPoolShare=Fe;exports.getLiquiditySlippage=Ue;exports.getMemoFor=Ge;exports.getMinAmountByChain=mt;exports.getSymmetricPoolShare=le;exports.getSymmetricWithdraw=Le;exports.getTHORNameCost=Ke;exports.isGasAsset=ie;exports.validateTHORName=Ye;
|
package/dist/index.d.ts
CHANGED
|
@@ -102,6 +102,7 @@ export declare class BigIntArithmetics {
|
|
|
102
102
|
formatBigIntToSafeValue(value: bigint, decimal?: number): string;
|
|
103
103
|
toSignificant(significantDigits?: number): string;
|
|
104
104
|
toFixed(fixedDigits?: number): string;
|
|
105
|
+
toAbbreviation(digits?: number): string | number;
|
|
105
106
|
}
|
|
106
107
|
|
|
107
108
|
export declare type CommonAssetString = 'MAYA.MAYA' | 'ETH.THOR' | 'ETH.vTHOR' | Chain;
|
package/dist/index.es.js
CHANGED
|
@@ -49,7 +49,7 @@ const Tt = "0x313ce567", nt = async ({ chain: s, to: t }) => {
|
|
|
49
49
|
[D.Average]: 1.2,
|
|
50
50
|
[D.Fast]: 1.5,
|
|
51
51
|
[D.Fastest]: 2
|
|
52
|
-
},
|
|
52
|
+
}, $t = ({ chain: s, symbol: t }) => {
|
|
53
53
|
switch (s) {
|
|
54
54
|
case o.Bitcoin:
|
|
55
55
|
case o.BitcoinCash:
|
|
@@ -75,7 +75,7 @@ const Tt = "0x313ce567", nt = async ({ chain: s, to: t }) => {
|
|
|
75
75
|
case o.THORChain:
|
|
76
76
|
return t === "RUNE";
|
|
77
77
|
}
|
|
78
|
-
},
|
|
78
|
+
}, Ct = (s) => {
|
|
79
79
|
switch (s) {
|
|
80
80
|
case "ETH.THOR":
|
|
81
81
|
return { identifier: "ETH.THOR-0xa5f2211b9b8170f694421f2046281775e8468044", decimal: 18 };
|
|
@@ -206,7 +206,7 @@ const Tt = "0x313ce567", nt = async ({ chain: s, to: t }) => {
|
|
|
206
206
|
}) => {
|
|
207
207
|
const n = d(e), i = d(r), a = d(t), c = d(s), u = a.mul(n).sub(i.mul(c)), l = i.mul(c).add(n.mul(i));
|
|
208
208
|
return Math.abs(u.div(l).baseValueNumber);
|
|
209
|
-
},
|
|
209
|
+
}, Mt = ({
|
|
210
210
|
symbol: s,
|
|
211
211
|
ticker: t,
|
|
212
212
|
chain: e
|
|
@@ -230,7 +230,7 @@ const Tt = "0x313ce567", nt = async ({ chain: s, to: t }) => {
|
|
|
230
230
|
return i ? `${s}:${e}/${r}::t:0` : `${s}:${e}.${r}:${n || ""}:t:0`;
|
|
231
231
|
}
|
|
232
232
|
case g.WITHDRAW: {
|
|
233
|
-
const { chain: e, ticker: r, symbol: n, basisPoints: i, targetAssetString: a, singleSide: c } = t, u = !c && a ? `:${a}` : "", l =
|
|
233
|
+
const { chain: e, ticker: r, symbol: n, basisPoints: i, targetAssetString: a, singleSide: c } = t, u = !c && a ? `:${a}` : "", l = Mt({ chain: e, symbol: n, ticker: r });
|
|
234
234
|
return `${s}:${e}${c ? "/" : "."}${l}:${i}${u}`;
|
|
235
235
|
}
|
|
236
236
|
case g.OPEN_LOAN:
|
|
@@ -303,7 +303,7 @@ const B = (s) => s !== null && typeof s == "object", V = (...s) => {
|
|
|
303
303
|
B(r.headers) && (e = at(e, r.headers), t.headers = e);
|
|
304
304
|
}
|
|
305
305
|
return t;
|
|
306
|
-
},
|
|
306
|
+
}, kt = (() => {
|
|
307
307
|
let s = !1, t = !1;
|
|
308
308
|
const e = typeof globalThis.ReadableStream == "function", r = typeof globalThis.Request == "function";
|
|
309
309
|
return e && r && (t = new globalThis.Request("https://empty.invalid", {
|
|
@@ -314,7 +314,7 @@ const B = (s) => s !== null && typeof s == "object", V = (...s) => {
|
|
|
314
314
|
return s = !0, "half";
|
|
315
315
|
}
|
|
316
316
|
}).headers.has("Content-Type")), s && !t;
|
|
317
|
-
})(),
|
|
317
|
+
})(), qt = typeof globalThis.AbortController == "function", xt = typeof globalThis.ReadableStream == "function", Pt = typeof globalThis.FormData == "function", ct = ["get", "post", "put", "patch", "head", "delete"], Nt = {
|
|
318
318
|
json: "application/json",
|
|
319
319
|
text: "text/*",
|
|
320
320
|
formData: "multipart/form-data",
|
|
@@ -398,9 +398,9 @@ const Yt = (s, t) => {
|
|
|
398
398
|
!(r in jt) && !(r in Ht) && !(r in s) && (e[r] = t[r]);
|
|
399
399
|
return e;
|
|
400
400
|
};
|
|
401
|
-
class
|
|
401
|
+
class k {
|
|
402
402
|
static create(t, e) {
|
|
403
|
-
const r = new
|
|
403
|
+
const r = new k(t, e), n = async () => {
|
|
404
404
|
if (typeof r._options.timeout == "number" && r._options.timeout > L)
|
|
405
405
|
throw new RangeError(`The \`timeout\` option cannot be greater than ${L}`);
|
|
406
406
|
await Promise.resolve();
|
|
@@ -490,7 +490,7 @@ class q {
|
|
|
490
490
|
throw new Error("`input` must not begin with a slash when using `prefixUrl`");
|
|
491
491
|
this._options.prefixUrl.endsWith("/") || (this._options.prefixUrl += "/"), this._input = this._options.prefixUrl + this._input;
|
|
492
492
|
}
|
|
493
|
-
if (
|
|
493
|
+
if (qt) {
|
|
494
494
|
if (this.abortController = new globalThis.AbortController(), this._options.signal) {
|
|
495
495
|
const r = this._options.signal;
|
|
496
496
|
this._options.signal.addEventListener("abort", () => {
|
|
@@ -499,7 +499,7 @@ class q {
|
|
|
499
499
|
}
|
|
500
500
|
this._options.signal = this.abortController.signal;
|
|
501
501
|
}
|
|
502
|
-
if (
|
|
502
|
+
if (kt && (this._options.duplex = "half"), this.request = new globalThis.Request(this._input, this._options), this._options.searchParams) {
|
|
503
503
|
const n = "?" + (typeof this._options.searchParams == "string" ? this._options.searchParams.replace(/^\?/, "") : new URLSearchParams(this._options.searchParams).toString()), i = this.request.url.replace(/(?:\?.*?)?(?=#|$)/, n);
|
|
504
504
|
(Pt && 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(i, { ...this.request }), this._options);
|
|
505
505
|
}
|
|
@@ -595,9 +595,9 @@ class q {
|
|
|
595
595
|
}
|
|
596
596
|
/*! MIT License © Sindre Sorhus */
|
|
597
597
|
const W = (s) => {
|
|
598
|
-
const t = (e, r) =>
|
|
598
|
+
const t = (e, r) => k.create(e, V(s, r));
|
|
599
599
|
for (const e of ct)
|
|
600
|
-
t[e] = (r, n) =>
|
|
600
|
+
t[e] = (r, n) => k.create(r, V(s, n, { method: e }));
|
|
601
601
|
return t.create = (e) => W(V(e)), t.extend = (e) => W(V(s, e)), t.stop = ut, t;
|
|
602
602
|
}, zt = W(), Jt = zt, et = Jt.create({
|
|
603
603
|
headers: {
|
|
@@ -618,11 +618,11 @@ const W = (s) => {
|
|
|
618
618
|
throw new Error(
|
|
619
619
|
`Invalid identifier: ${s}. Expected format: <Chain>.<Ticker> or <Chain>.<Ticker>-<ContractAddress>`
|
|
620
620
|
);
|
|
621
|
-
},
|
|
622
|
-
function
|
|
621
|
+
}, C = 8, v = (s) => 10n ** BigInt(s), R = (s) => Math.log10(parseFloat(s.toString()));
|
|
622
|
+
function q({
|
|
623
623
|
value: s,
|
|
624
|
-
bigIntDecimal: t =
|
|
625
|
-
decimal: e =
|
|
624
|
+
bigIntDecimal: t = C,
|
|
625
|
+
decimal: e = C
|
|
626
626
|
}) {
|
|
627
627
|
const r = s < 0n;
|
|
628
628
|
let n = s.toString().substring(r ? 1 : 0);
|
|
@@ -635,7 +635,7 @@ function M({
|
|
|
635
635
|
""
|
|
636
636
|
);
|
|
637
637
|
}
|
|
638
|
-
var w, S, x, ht, P, dt, E, G, A,
|
|
638
|
+
var w, S, x, ht, P, dt, E, G, A, $, O, Y;
|
|
639
639
|
const N = class N {
|
|
640
640
|
constructor(t) {
|
|
641
641
|
y(this, w);
|
|
@@ -649,13 +649,13 @@ const N = class N {
|
|
|
649
649
|
p(this, "decimal");
|
|
650
650
|
const e = U(t);
|
|
651
651
|
this.decimal = typeof t == "object" ? t.decimal : void 0, this.decimalMultiplier = v(
|
|
652
|
-
Math.max(f(this, O, Y).call(this, f(this, A,
|
|
652
|
+
Math.max(f(this, O, Y).call(this, f(this, A, $).call(this, e)), this.decimal || 0)
|
|
653
653
|
), f(this, x, ht).call(this, e);
|
|
654
654
|
}
|
|
655
655
|
static fromBigInt(t, e) {
|
|
656
656
|
return new N({
|
|
657
657
|
decimal: e,
|
|
658
|
-
value:
|
|
658
|
+
value: q({ value: t, bigIntDecimal: e, decimal: e })
|
|
659
659
|
});
|
|
660
660
|
}
|
|
661
661
|
static shiftDecimals({
|
|
@@ -744,11 +744,11 @@ const N = class N {
|
|
|
744
744
|
getBigIntValue(t, e) {
|
|
745
745
|
if (!e && typeof t == "object")
|
|
746
746
|
return t.bigIntValue;
|
|
747
|
-
const r = U(t), n = f(this, A,
|
|
747
|
+
const r = U(t), n = f(this, A, $).call(this, r);
|
|
748
748
|
return n === "0" || n === "undefined" ? 0n : f(this, E, G).call(this, n, e);
|
|
749
749
|
}
|
|
750
750
|
formatBigIntToSafeValue(t, e) {
|
|
751
|
-
const r = e || this.decimal ||
|
|
751
|
+
const r = e || this.decimal || C, n = Math.max(
|
|
752
752
|
r,
|
|
753
753
|
R(this.decimalMultiplier)
|
|
754
754
|
), i = t < 0n, a = t.toString().substring(i ? 1 : 0), c = n - (a.length - 1), u = c > 0 ? "0".repeat(c) + a : a, l = u.length - n;
|
|
@@ -785,6 +785,13 @@ const N = class N {
|
|
|
785
785
|
"0"
|
|
786
786
|
)}`;
|
|
787
787
|
}
|
|
788
|
+
toAbbreviation(t = 2) {
|
|
789
|
+
const e = this.getValue("number"), r = ["", "K", "M", "B", "T", "Q", "Qi", "S"], n = Math.floor(Math.log10(Math.abs(e)) / 3), i = r[n];
|
|
790
|
+
if (!i)
|
|
791
|
+
return e;
|
|
792
|
+
const a = 10 ** (n * 3);
|
|
793
|
+
return `${(e / a).toFixed(t)}${i}`;
|
|
794
|
+
}
|
|
788
795
|
};
|
|
789
796
|
w = new WeakSet(), S = function(t, ...e) {
|
|
790
797
|
const r = f(this, P, dt).call(this, this, ...e), n = v(r), i = e.reduce(
|
|
@@ -808,24 +815,24 @@ w = new WeakSet(), S = function(t, ...e) {
|
|
|
808
815
|
},
|
|
809
816
|
//normalize is to precision multiplier base
|
|
810
817
|
this.bigIntValue * n / this.decimalMultiplier
|
|
811
|
-
), a =
|
|
818
|
+
), a = q({
|
|
812
819
|
bigIntDecimal: r,
|
|
813
820
|
decimal: Math.max(r, R(this.decimalMultiplier)),
|
|
814
821
|
value: i
|
|
815
822
|
});
|
|
816
823
|
return new this.constructor({ decimal: this.decimal, value: a, identifier: this.toString() });
|
|
817
824
|
}, x = new WeakSet(), ht = function(t) {
|
|
818
|
-
const e = f(this, A,
|
|
825
|
+
const e = f(this, A, $).call(this, t) || "0";
|
|
819
826
|
this.bigIntValue = f(this, E, G).call(this, e);
|
|
820
827
|
}, P = new WeakSet(), dt = function(...t) {
|
|
821
828
|
const e = t.map(
|
|
822
|
-
(r) => typeof r == "object" ? r.decimal || R(r.decimalMultiplier) : f(this, O, Y).call(this, f(this, A,
|
|
829
|
+
(r) => typeof r == "object" ? r.decimal || R(r.decimalMultiplier) : f(this, O, Y).call(this, f(this, A, $).call(this, r))
|
|
823
830
|
).filter(Boolean);
|
|
824
|
-
return Math.max(...e,
|
|
831
|
+
return Math.max(...e, C);
|
|
825
832
|
}, E = new WeakSet(), G = function(t, e) {
|
|
826
833
|
const r = e ? v(e) : this.decimalMultiplier, n = R(r), [i = "", a = ""] = t.split(".");
|
|
827
834
|
return BigInt(`${i}${a.padEnd(n, "0")}`);
|
|
828
|
-
}, A = new WeakSet(),
|
|
835
|
+
}, A = new WeakSet(), $ = function(t) {
|
|
829
836
|
const r = `${typeof t == "number" ? Number(t).toLocaleString("fullwide", {
|
|
830
837
|
useGrouping: !1,
|
|
831
838
|
maximumFractionDigits: 20
|
|
@@ -834,13 +841,13 @@ w = new WeakSet(), S = function(t, ...e) {
|
|
|
834
841
|
}, O = new WeakSet(), Y = function(t) {
|
|
835
842
|
var r;
|
|
836
843
|
const e = ((r = t.split(".")[1]) == null ? void 0 : r.length) || 0;
|
|
837
|
-
return Math.max(e,
|
|
844
|
+
return Math.max(e, C);
|
|
838
845
|
};
|
|
839
846
|
let I = N;
|
|
840
847
|
function U(s) {
|
|
841
848
|
return typeof s == "object" ? "getValue" in s ? s.getValue("string") : s.value : s;
|
|
842
849
|
}
|
|
843
|
-
const
|
|
850
|
+
const M = (s, t) => typeof s == "bigint" ? q({ value: s, bigIntDecimal: t, decimal: t }) : s;
|
|
844
851
|
let z;
|
|
845
852
|
const F = (s) => {
|
|
846
853
|
if (!z)
|
|
@@ -848,7 +855,7 @@ const F = (s) => {
|
|
|
848
855
|
return z.get(s.toUpperCase()) || { decimal: m.THOR, identifier: "" };
|
|
849
856
|
}, st = async (s, t = 0) => {
|
|
850
857
|
Qt(s);
|
|
851
|
-
const e = await it(J(s)), r =
|
|
858
|
+
const e = await it(J(s)), r = M(t, e);
|
|
852
859
|
return new b({ decimal: e, value: r, identifier: s });
|
|
853
860
|
};
|
|
854
861
|
class b extends I {
|
|
@@ -885,18 +892,18 @@ class b extends I {
|
|
|
885
892
|
static fromStringSync(e, r = 0) {
|
|
886
893
|
const { decimal: n, identifier: i } = F(
|
|
887
894
|
e
|
|
888
|
-
), a =
|
|
895
|
+
), a = M(r, n);
|
|
889
896
|
return i ? new b({ decimal: n, identifier: i, value: a }) : void 0;
|
|
890
897
|
}
|
|
891
898
|
static async fromIdentifier(e, r = 0) {
|
|
892
899
|
return st(e, r);
|
|
893
900
|
}
|
|
894
901
|
static fromIdentifierSync(e, r = 0) {
|
|
895
|
-
const { decimal: n, identifier: i } = F(e), a =
|
|
902
|
+
const { decimal: n, identifier: i } = F(e), a = M(r, n);
|
|
896
903
|
return new b({ decimal: n, identifier: i, value: a });
|
|
897
904
|
}
|
|
898
905
|
static fromChainOrSignature(e, r = 0) {
|
|
899
|
-
const { decimal: n, identifier: i } =
|
|
906
|
+
const { decimal: n, identifier: i } = Ct(e), a = M(r, n);
|
|
900
907
|
return new b({ value: a, decimal: n, identifier: i });
|
|
901
908
|
}
|
|
902
909
|
static async fromTCQuote(e, r = 0) {
|
|
@@ -963,7 +970,7 @@ const me = (s) => {
|
|
|
963
970
|
return {
|
|
964
971
|
address: a == null ? void 0 : a.toLowerCase(),
|
|
965
972
|
chain: r,
|
|
966
|
-
isGasAsset:
|
|
973
|
+
isGasAsset: $t({ chain: r, symbol: n }),
|
|
967
974
|
isSynthetic: t,
|
|
968
975
|
symbol: a ? `${i}-${(a == null ? void 0 : a.toLowerCase()) ?? ""}` : n,
|
|
969
976
|
ticker: t ? n : i
|
|
@@ -1037,7 +1044,7 @@ class Q extends I {
|
|
|
1037
1044
|
static fromBigInt(t, e) {
|
|
1038
1045
|
return new Q({
|
|
1039
1046
|
decimal: e,
|
|
1040
|
-
value:
|
|
1047
|
+
value: q({ value: t, bigIntDecimal: e, decimal: e })
|
|
1041
1048
|
});
|
|
1042
1049
|
}
|
|
1043
1050
|
}
|
|
@@ -1050,14 +1057,14 @@ export {
|
|
|
1050
1057
|
re as assetFromString,
|
|
1051
1058
|
de as derivationPathToString,
|
|
1052
1059
|
se as filterAssets,
|
|
1053
|
-
|
|
1060
|
+
q as formatBigIntToSafeValue,
|
|
1054
1061
|
ee as gasFeeMultiplier,
|
|
1055
1062
|
It as getAssetType,
|
|
1056
1063
|
Vt as getAsymmetricAssetShare,
|
|
1057
1064
|
ie as getAsymmetricAssetWithdrawAmount,
|
|
1058
1065
|
Ot as getAsymmetricRuneShare,
|
|
1059
1066
|
ne as getAsymmetricRuneWithdrawAmount,
|
|
1060
|
-
|
|
1067
|
+
Ct as getCommonAssetInfo,
|
|
1061
1068
|
it as getDecimal,
|
|
1062
1069
|
ae as getEstimatedPoolShare,
|
|
1063
1070
|
ce as getLiquiditySlippage,
|
|
@@ -1066,6 +1073,6 @@ export {
|
|
|
1066
1073
|
Bt as getSymmetricPoolShare,
|
|
1067
1074
|
oe as getSymmetricWithdraw,
|
|
1068
1075
|
le as getTHORNameCost,
|
|
1069
|
-
|
|
1076
|
+
$t as isGasAsset,
|
|
1070
1077
|
he as validateTHORName
|
|
1071
1078
|
};
|
package/package.json
CHANGED
|
@@ -42,7 +42,7 @@
|
|
|
42
42
|
"repository": "https://github.com/thorswap/SwapKit.git",
|
|
43
43
|
"type": "module",
|
|
44
44
|
"types": "./dist/index.d.ts",
|
|
45
|
-
"version": "1.0.0-rc.
|
|
45
|
+
"version": "1.0.0-rc.12",
|
|
46
46
|
"scripts": {
|
|
47
47
|
"build": "vite build",
|
|
48
48
|
"clean": "rm -rf dist vite.config.ts.* .turbo node_modules",
|
|
@@ -153,6 +153,37 @@ describe('SwapKitNumber', () => {
|
|
|
153
153
|
});
|
|
154
154
|
});
|
|
155
155
|
|
|
156
|
+
describe('toAbbreviation', () => {
|
|
157
|
+
test('returns abbreviation with up to 3 integer digits', () => {
|
|
158
|
+
const skNumber = new SwapKitNumber(1234.5678);
|
|
159
|
+
expect(skNumber.toAbbreviation()).toBe('1.23K');
|
|
160
|
+
|
|
161
|
+
const skNumber2 = new SwapKitNumber(1234567.5678);
|
|
162
|
+
expect(skNumber2.toAbbreviation()).toBe('1.23M');
|
|
163
|
+
|
|
164
|
+
const skNumber3 = new SwapKitNumber(1234567890.5678);
|
|
165
|
+
expect(skNumber3.toAbbreviation()).toBe('1.23B');
|
|
166
|
+
|
|
167
|
+
const skNumber4 = new SwapKitNumber(1234567890123.5678);
|
|
168
|
+
expect(skNumber4.toAbbreviation()).toBe('1.23T');
|
|
169
|
+
|
|
170
|
+
const skNumber5 = new SwapKitNumber(1234567890123456.5678);
|
|
171
|
+
expect(skNumber5.toAbbreviation()).toBe('1.23Q');
|
|
172
|
+
|
|
173
|
+
const skNumber6 = new SwapKitNumber(1234567890123456789.5678);
|
|
174
|
+
expect(skNumber6.toAbbreviation()).toBe('1.23Qi');
|
|
175
|
+
|
|
176
|
+
const skNumber7 = new SwapKitNumber(1234567890123456789012.5678);
|
|
177
|
+
expect(skNumber7.toAbbreviation()).toBe('1.23S');
|
|
178
|
+
|
|
179
|
+
const skNumber8 = new SwapKitNumber(1234.5678);
|
|
180
|
+
expect(skNumber8.toAbbreviation(0)).toBe('1K');
|
|
181
|
+
|
|
182
|
+
const skNumber9 = new SwapKitNumber(1234.5678);
|
|
183
|
+
expect(skNumber9.toAbbreviation(1)).toBe('1.2K');
|
|
184
|
+
});
|
|
185
|
+
});
|
|
186
|
+
|
|
156
187
|
describe('add', () => {
|
|
157
188
|
test('adds same type numbers correctly', () => {
|
|
158
189
|
const skNumber1 = new SwapKitNumber(10);
|
|
@@ -270,6 +270,20 @@ export class BigIntArithmetics {
|
|
|
270
270
|
)}`;
|
|
271
271
|
}
|
|
272
272
|
|
|
273
|
+
toAbbreviation(digits = 2) {
|
|
274
|
+
const value = this.getValue('number');
|
|
275
|
+
const abbreviations = ['', 'K', 'M', 'B', 'T', 'Q', 'Qi', 'S'];
|
|
276
|
+
const tier = Math.floor(Math.log10(Math.abs(value)) / 3);
|
|
277
|
+
const suffix = abbreviations[tier];
|
|
278
|
+
|
|
279
|
+
if (!suffix) return value;
|
|
280
|
+
|
|
281
|
+
const scale = 10 ** (tier * 3);
|
|
282
|
+
const scaled = value / scale;
|
|
283
|
+
|
|
284
|
+
return `${scaled.toFixed(digits)}${suffix}`;
|
|
285
|
+
}
|
|
286
|
+
|
|
273
287
|
#arithmetics(method: 'add' | 'sub' | 'mul' | 'div', ...args: InitialisationValueType[]): this {
|
|
274
288
|
const precisionDecimal = this.#retrievePrecisionDecimal(this, ...args);
|
|
275
289
|
const precisionDecimalMultiplier = toMultiplier(precisionDecimal);
|