@swapkit/helpers 1.0.0-rc.17 → 1.0.0-rc.18
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 +2 -4
- package/dist/index.es.js +158 -170
- package/package.json +1 -1
- package/src/modules/__tests__/swapKitNumber.test.ts +17 -4
- package/src/modules/assetValue.ts +0 -18
- package/src/modules/bigIntArithmetics.ts +3 -3
package/dist/index.cjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";var Te=Object.create;var j=Object.defineProperty;var Se=Object.getOwnPropertyDescriptor;var ve=Object.getOwnPropertyNames;var Re=Object.getPrototypeOf,Ie=Object.prototype.hasOwnProperty;var Be=(s,e,t)=>e in s?j(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t;var $e=(s,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of ve(e))!Ie.call(s,n)&&n!==t&&j(s,n,{get:()=>e[n],enumerable:!(r=Se(e,n))||r.enumerable});return s};var Ee=(s,e,t)=>(t=s!=null?Te(Re(s)):{},$e(e||!s||!s.__esModule?j(t,"default",{value:s,enumerable:!0}):t,s));var p=(s,e,t)=>(Be(s,typeof e!="symbol"?e+"":e,t),t),Oe=(s,e,t)=>{if(!e.has(s))throw TypeError("Cannot "+t)};var y=(s,e,t)=>{if(e.has(s))throw TypeError("Cannot add the same private member more than once");e instanceof WeakSet?e.add(s):e.set(s,t)};var d=(s,e,t)=>(Oe(s,e,"access private method"),t);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const i=require("@swapkit/types"),Me="0x313ce567",ne=async({chain:s,to:e})=>{try{const{result:t}=await ge.post(i.ChainToRPC[s],{headers:{accept:"*/*","content-type":"application/json","cache-control":"no-cache"},body:JSON.stringify({id:44,jsonrpc:"2.0",method:"eth_call",params:[{to:e.toLowerCase(),data:Me},"latest"]})});return parseInt(BigInt(t).toString())}catch(t){return console.error(t),i.BaseDecimal[s]}},Ve=async s=>{if(s===i.Chain.Ethereum)return i.BaseDecimal.ETH;const[,e]=s.split("-");return e!=null&&e.startsWith("0x")?ne({chain:i.Chain.Ethereum,to:e}):i.BaseDecimal.ETH},qe=async s=>{const[,e]=s.split("-");return e!=null&&e.startsWith("0x")?ne({chain:i.Chain.Avalanche,to:e.toLowerCase()}):i.BaseDecimal.AVAX},ke=async s=>(s===i.Chain.BinanceSmartChain,i.BaseDecimal.BSC),z=async({chain:s,symbol:e})=>{switch(s){case i.Chain.Ethereum:return Ve(e);case i.Chain.Avalanche:return qe(e);case i.Chain.BinanceSmartChain:return ke(e);default:return i.BaseDecimal[s]}},Pe={[i.FeeOption.Average]:1.2,[i.FeeOption.Fast]:1.5,[i.FeeOption.Fastest]:2},ie=({chain:s,symbol:e})=>{switch(s){case i.Chain.Bitcoin:case i.Chain.BitcoinCash:case i.Chain.Litecoin:case i.Chain.Dogecoin:case i.Chain.Binance:case i.Chain.Ethereum:case i.Chain.Avalanche:return e===s;case i.Chain.Arbitrum:case i.Chain.Optimism:return e==="ETH";case i.Chain.Maya:return e==="CACAO";case i.Chain.Kujira:return e==="KUJI";case i.Chain.Cosmos:return e==="ATOM";case i.Chain.Polygon:return e==="MATIC";case i.Chain.BinanceSmartChain:return e==="BNB";case i.Chain.THORChain:return e==="RUNE"}},ae=s=>{switch(s){case"ETH.THOR":return{identifier:"ETH.THOR-0xa5f2211b9b8170f694421f2046281775e8468044",decimal:18};case"ETH.vTHOR":return{identifier:"ETH.vTHOR-0x815c23eca83261b6ec689b60cc4a58b54bc24d8d",decimal:18};case i.Chain.Cosmos:return{identifier:"GAIA.ATOM",decimal:i.BaseDecimal[s]};case i.Chain.THORChain:return{identifier:"THOR.RUNE",decimal:i.BaseDecimal[s]};case i.Chain.BinanceSmartChain:return{identifier:"BSC.BNB",decimal:i.BaseDecimal[s]};case i.Chain.Maya:return{identifier:"MAYA.CACAO",decimal:i.BaseDecimal.MAYA};case"MAYA.MAYA":return{identifier:"MAYA.MAYA",decimal:4};case i.Chain.Kujira:case i.Chain.Arbitrum:case i.Chain.Optimism:case i.Chain.BitcoinCash:case i.Chain.Litecoin:case i.Chain.Dogecoin:case i.Chain.Binance:case i.Chain.Avalanche:case i.Chain.Polygon:case i.Chain.Bitcoin:case i.Chain.Ethereum:return{identifier:`${s}.${s}`,decimal:i.BaseDecimal[s]}}},oe=({chain:s,symbol:e})=>{if(e.includes("/"))return"Synth";switch(s){case i.Chain.Bitcoin:case i.Chain.BitcoinCash:case i.Chain.Dogecoin:case i.Chain.Litecoin:case i.Chain.Maya:case i.Chain.THORChain:return"Native";case i.Chain.Cosmos:return e==="ATOM"?"Native":i.Chain.Cosmos;case i.Chain.Kujira:return e===i.Chain.Kujira?"Native":i.Chain.Kujira;case i.Chain.Binance:return e===i.Chain.Binance?"Native":"BEP2";case i.Chain.BinanceSmartChain:return e===i.Chain.Binance?"Native":"BEP20";case i.Chain.Ethereum:return e===i.Chain.Ethereum?"Native":"ERC20";case i.Chain.Avalanche:return e===i.Chain.Avalanche?"Native":i.Chain.Avalanche;case i.Chain.Polygon:return e===i.Chain.Polygon?"Native":"POLYGON";case i.Chain.Arbitrum:return[i.Chain.Ethereum,i.Chain.Arbitrum].includes(e)?"Native":"ARBITRUM";case i.Chain.Optimism:return[i.Chain.Ethereum,i.Chain.Optimism].includes(e)?"Native":"OPTIMISM"}},xe=s=>{var o;const[e,...t]=s.split("."),r=s.includes("/"),n=t.join("."),a=(o=n==null?void 0:n.split("-"))==null?void 0:o[0];return{chain:e,symbol:n,ticker:a,synth:r}},De=new RegExp(/(.)\1{6}|\.ORG|\.NET|\.FINANCE|\.COM|WWW|HTTP|\\\\|\/\/|[\s$%:[\]]/,"gmi"),Ne=s=>s.filter(e=>!De.test(e.toString())&&!e.toString().includes("undefined")),ce=({liquidityUnits:s,poolUnits:e,runeDepth:t})=>{const r=m(s),n=m(e),a=m(t),o=r.mul(a),c=n.mul(n).mul(2),u=n.mul(r).mul(2),l=r.mul(r),h=n.mul(n).mul(n);return o.mul(c.sub(u).add(l)).div(h)},ue=({liquidityUnits:s,poolUnits:e,assetDepth:t})=>{const r=m(s),n=m(e),a=m(t),o=r.mul(a),c=n.mul(n).mul(2),u=n.mul(r).mul(2),l=r.mul(r),h=o.mul(c.sub(u).add(l)),_=n.mul(n).mul(n);return h.div(_)},He=({percent:s,runeDepth:e,liquidityUnits:t,poolUnits:r})=>ce({runeDepth:e,liquidityUnits:t,poolUnits:r}).mul(s),je=({percent:s,assetDepth:e,liquidityUnits:t,poolUnits:r})=>ue({assetDepth:e,liquidityUnits:t,poolUnits:r}).mul(s),m=s=>g.fromBigInt(BigInt(s),i.BaseDecimal.THOR),le=({liquidityUnits:s,poolUnits:e,runeDepth:t,assetDepth:r})=>({assetAmount:m(r).mul(s).div(e),runeAmount:m(t).mul(s).div(e)}),Le=({liquidityUnits:s,poolUnits:e,runeDepth:t,assetDepth:r,percent:n})=>Object.fromEntries(Object.entries(le({liquidityUnits:s,poolUnits:e,runeDepth:t,assetDepth:r})).map(([a,o])=>[a,o.mul(n)])),Fe=({runeDepth:s,poolUnits:e,assetDepth:t,liquidityUnits:r,runeAmount:n,assetAmount:a})=>{const o=new g({value:s,decimal:8}),c=new g({value:t,decimal:8}),u=new g({value:e,decimal:8}),l=new g({value:n,decimal:8}),h=new g({value:a,decimal:8}),_=l.mul(c),w=h.mul(o),N=l.mul(h),be=o.mul(c),Ce=u.mul(_.add(w.add(N.mul(2)))),we=_.add(w.add(be.mul(2))),X=Ce.div(we),H=m(r).add(X);if(X.getBaseValue("number")===0)return H.div(u).getBaseValue("number");const Ae=u.add(H);return H.div(Ae).getBaseValue("number")},Ue=({runeAmount:s,assetAmount:e,runeDepth:t,assetDepth:r})=>{if(s==="0"||e==="0"||t==="0"||r==="0")return 0;const n=m(t),a=m(r),o=m(e),c=m(s),u=o.mul(n).sub(a.mul(c)),l=a.mul(c).add(n.mul(a));return Math.abs(u.div(l).getBaseValue("number"))},We=({symbol:s,ticker:e,chain:t})=>t==="ETH"&&e!=="ETH"?`${e}-${s.slice(-3)}`:s,Ge=(s,e)=>{switch(s){case i.MemoType.LEAVE:case i.MemoType.BOND:{const{address:t}=e;return`${s}:${t}`}case i.MemoType.UNBOND:{const{address:t,unbondAmount:r}=e;return`${s}:${t}:${r*10**8}`}case i.MemoType.THORNAME_REGISTER:{const{name:t,chain:r,address:n,owner:a}=e;return`${s}:${t}:${r}:${n}${a?`:${a}`:""}`}case i.MemoType.DEPOSIT:{const{chain:t,symbol:r,address:n,singleSide:a}=e;return a?`${s}:${t}/${r}::t:0`:`${s}:${t}.${r}:${n||""}:t:0`}case i.MemoType.WITHDRAW:{const{chain:t,ticker:r,symbol:n,basisPoints:a,targetAssetString:o,singleSide:c}=e,u=!c&&o?`:${o}`:"",l=We({chain:t,symbol:n,ticker:r});return`${s}:${t}${c?"/":"."}${l}:${a}${u}`}case i.MemoType.OPEN_LOAN:case i.MemoType.CLOSE_LOAN:{const{asset:t,address:r}=e;return`${s}:${t}:${r}`}default:return""}},Ke=s=>{if(s<0)throw new Error("Invalid number of year");return 10+s},Ye=s=>{if(s.length>30)return!1;const e=/^[a-zA-Z0-9+_-]+$/g;return!!s.match(e)},ze=([s,e,t,r,n])=>`${s}'/${e}'/${t}'/${r}${typeof n!="number"?"":`/${n}`}`;class Z extends Error{constructor(e,t,r){const n=e.status||e.status===0?e.status:"",a=e.statusText||"",o=`${n} ${a}`.trim(),c=o?`status code ${o}`:"an unknown error";super(`Request failed with ${c}`),Object.defineProperty(this,"response",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"request",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"options",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.name="HTTPError",this.response=e,this.request=t,this.options=r}}class he extends Error{constructor(e){super("Request timed out"),Object.defineProperty(this,"request",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.name="TimeoutError",this.request=e}}const M=s=>s!==null&&typeof s=="object",O=(...s)=>{for(const e of s)if((!M(e)||Array.isArray(e))&&e!==void 0)throw new TypeError("The `options` argument must be an object");return J({},...s)},de=(s={},e={})=>{const t=new globalThis.Headers(s),r=e instanceof globalThis.Headers,n=new globalThis.Headers(e);for(const[a,o]of n.entries())r&&o==="undefined"||o===void 0?t.delete(a):t.set(a,o);return t},J=(...s)=>{let e={},t={};for(const r of s)if(Array.isArray(r))Array.isArray(e)||(e=[]),e=[...e,...r];else if(M(r)){for(let[n,a]of Object.entries(r))M(a)&&n in e&&(a=J(e[n],a)),e={...e,[n]:a};M(r.headers)&&(t=de(t,r.headers),e.headers=t)}return e},Je=(()=>{let s=!1,e=!1;const t=typeof globalThis.ReadableStream=="function",r=typeof globalThis.Request=="function";return t&&r&&(e=new globalThis.Request("https://empty.invalid",{body:new globalThis.ReadableStream,method:"POST",get duplex(){return s=!0,"half"}}).headers.has("Content-Type")),s&&!e})(),Qe=typeof globalThis.AbortController=="function",Xe=typeof globalThis.ReadableStream=="function",Ze=typeof globalThis.FormData=="function",me=["get","post","put","patch","head","delete"],et={json:"application/json",text:"text/*",formData:"multipart/form-data",arrayBuffer:"*/*",blob:"*/*"},L=2147483647,pe=Symbol("stop"),tt={json:!0,parseJson:!0,searchParams:!0,prefixUrl:!0,retry:!0,timeout:!0,hooks:!0,throwHttpErrors:!0,onDownloadProgress:!0,fetch:!0},rt={method:!0,headers:!0,body:!0,mode:!0,credentials:!0,cache:!0,redirect:!0,referrer:!0,referrerPolicy:!0,integrity:!0,keepalive:!0,signal:!0,window:!0,dispatcher:!0,duplex:!0},st=s=>me.includes(s)?s.toUpperCase():s,nt=["get","put","head","delete","options","trace"],it=[408,413,429,500,502,503,504],fe=[413,429,503],ee={limit:2,methods:nt,statusCodes:it,afterStatusCodes:fe,maxRetryAfter:Number.POSITIVE_INFINITY,backoffLimit:Number.POSITIVE_INFINITY,delay:s=>.3*2**(s-1)*1e3},at=(s={})=>{if(typeof s=="number")return{...ee,limit:s};if(s.methods&&!Array.isArray(s.methods))throw new Error("retry.methods must be an array");if(s.statusCodes&&!Array.isArray(s.statusCodes))throw new Error("retry.statusCodes must be an array");return{...ee,...s,afterStatusCodes:fe}};async function ot(s,e,t,r){return new Promise((n,a)=>{const o=setTimeout(()=>{t&&t.abort(),a(new he(s))},r.timeout);r.fetch(s,e).then(n).catch(a).then(()=>{clearTimeout(o)})})}async function ct(s,{signal:e}){return new Promise((t,r)=>{e&&(e.throwIfAborted(),e.addEventListener("abort",n,{once:!0}));function n(){clearTimeout(a),r(e.reason)}const a=setTimeout(()=>{e==null||e.removeEventListener("abort",n),t()},s)})}const ut=(s,e)=>{const t={};for(const r in e)!(r in rt)&&!(r in tt)&&!(r in s)&&(t[r]=e[r]);return t};class k{static create(e,t){const r=new k(e,t),n=async()=>{if(typeof r._options.timeout=="number"&&r._options.timeout>L)throw new RangeError(`The \`timeout\` option cannot be greater than ${L}`);await Promise.resolve();let c=await r._fetch();for(const u of r._options.hooks.afterResponse){const l=await u(r.request,r._options,r._decorateResponse(c.clone()));l instanceof globalThis.Response&&(c=l)}if(r._decorateResponse(c),!c.ok&&r._options.throwHttpErrors){let u=new Z(c,r.request,r._options);for(const l of r._options.hooks.beforeError)u=await l(u);throw u}if(r._options.onDownloadProgress){if(typeof r._options.onDownloadProgress!="function")throw new TypeError("The `onDownloadProgress` option must be a function");if(!Xe)throw new Error("Streams are not supported in your environment. `ReadableStream` is missing.");return r._stream(c.clone(),r._options.onDownloadProgress)}return c},o=r._options.retry.methods.includes(r.request.method.toLowerCase())?r._retry(n):n();for(const[c,u]of Object.entries(et))o[c]=async()=>{r.request.headers.set("accept",r.request.headers.get("accept")||u);const h=(await o).clone();if(c==="json"){if(h.status===204||(await h.clone().arrayBuffer()).byteLength===0)return"";if(t.parseJson)return t.parseJson(await h.text())}return h[c]()};return o}constructor(e,t={}){if(Object.defineProperty(this,"request",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"abortController",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_retryCount",{enumerable:!0,configurable:!0,writable:!0,value:0}),Object.defineProperty(this,"_input",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_options",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this._input=e,this._options={credentials:this._input.credentials||"same-origin",...t,headers:de(this._input.headers,t.headers),hooks:J({beforeRequest:[],beforeRetry:[],beforeError:[],afterResponse:[]},t.hooks),method:st(t.method??this._input.method),prefixUrl:String(t.prefixUrl||""),retry:at(t.retry),throwHttpErrors:t.throwHttpErrors!==!1,timeout:t.timeout??1e4,fetch:t.fetch??globalThis.fetch.bind(globalThis)},typeof this._input!="string"&&!(this._input instanceof URL||this._input instanceof globalThis.Request))throw new TypeError("`input` must be a string, URL, or Request");if(this._options.prefixUrl&&typeof this._input=="string"){if(this._input.startsWith("/"))throw new Error("`input` must not begin with a slash when using `prefixUrl`");this._options.prefixUrl.endsWith("/")||(this._options.prefixUrl+="/"),this._input=this._options.prefixUrl+this._input}if(Qe){if(this.abortController=new globalThis.AbortController,this._options.signal){const r=this._options.signal;this._options.signal.addEventListener("abort",()=>{this.abortController.abort(r.reason)})}this._options.signal=this.abortController.signal}if(Je&&(this._options.duplex="half"),this.request=new globalThis.Request(this._input,this._options),this._options.searchParams){const n="?"+(typeof this._options.searchParams=="string"?this._options.searchParams.replace(/^\?/,""):new URLSearchParams(this._options.searchParams).toString()),a=this.request.url.replace(/(?:\?.*?)?(?=#|$)/,n);(Ze&&this._options.body instanceof globalThis.FormData||this._options.body instanceof URLSearchParams)&&!(this._options.headers&&this._options.headers["content-type"])&&this.request.headers.delete("content-type"),this.request=new globalThis.Request(new globalThis.Request(a,{...this.request}),this._options)}this._options.json!==void 0&&(this._options.body=JSON.stringify(this._options.json),this.request.headers.set("content-type",this._options.headers.get("content-type")??"application/json"),this.request=new globalThis.Request(this.request,{body:this._options.body}))}_calculateRetryDelay(e){if(this._retryCount++,this._retryCount<this._options.retry.limit&&!(e instanceof he)){if(e instanceof Z){if(!this._options.retry.statusCodes.includes(e.response.status))return 0;const r=e.response.headers.get("Retry-After");if(r&&this._options.retry.afterStatusCodes.includes(e.response.status)){let n=Number(r);return Number.isNaN(n)?n=Date.parse(r)-Date.now():n*=1e3,this._options.retry.maxRetryAfter!==void 0&&n>this._options.retry.maxRetryAfter?0:n}if(e.response.status===413)return 0}const t=this._options.retry.delay(this._retryCount);return Math.min(this._options.retry.backoffLimit,t)}return 0}_decorateResponse(e){return this._options.parseJson&&(e.json=async()=>this._options.parseJson(await e.text())),e}async _retry(e){try{return await e()}catch(t){const r=Math.min(this._calculateRetryDelay(t),L);if(r!==0&&this._retryCount>0){await ct(r,{signal:this._options.signal});for(const n of this._options.hooks.beforeRetry)if(await n({request:this.request,options:this._options,error:t,retryCount:this._retryCount})===pe)return;return this._retry(e)}throw t}}async _fetch(){for(const t of this._options.hooks.beforeRequest){const r=await t(this.request,this._options);if(r instanceof Request){this.request=r;break}if(r instanceof Response)return r}const e=ut(this.request,this._options);return this._options.timeout===!1?this._options.fetch(this.request.clone(),e):ot(this.request.clone(),e,this.abortController,this._options)}_stream(e,t){const r=Number(e.headers.get("content-length"))||0;let n=0;return e.status===204?(t&&t({percent:1,totalBytes:r,transferredBytes:n},new Uint8Array),new globalThis.Response(null,{status:e.status,statusText:e.statusText,headers:e.headers})):new globalThis.Response(new globalThis.ReadableStream({async start(a){const o=e.body.getReader();t&&t({percent:0,transferredBytes:0,totalBytes:r},new Uint8Array);async function c(){const{done:u,value:l}=await o.read();if(u){a.close();return}if(t){n+=l.byteLength;const h=r===0?0:n/r;t({percent:h,transferredBytes:n,totalBytes:r},l)}a.enqueue(l),await c()}await c()}}),{status:e.status,statusText:e.statusText,headers:e.headers})}}/*! MIT License © Sindre Sorhus */const W=s=>{const e=(t,r)=>k.create(t,O(s,r));for(const t of me)e[t]=(r,n)=>k.create(r,O(s,n,{method:t}));return e.create=t=>W(O(t)),e.extend=t=>W(O(s,t)),e.stop=pe,e},lt=W(),ht=lt,dt=typeof window<"u"?{}:{referrer:"https://sk.thorswap.net",referer:"https://sk.thorswap.net"},te=ht.create({headers:dt}),ge={get:(s,e)=>te.get(s,e).json(),post:(s,e)=>te.post(s,e).json()},re=Object.values(i.Chain),mt=(s="")=>{const e=s.toUpperCase(),[t]=e.split(".");if(re.includes(t))return!0;const[r]=e.split("/");if(re.includes(r))return!0;throw new Error(`Invalid identifier: ${s}. Expected format: <Chain>.<Ticker> or <Chain>.<Ticker>-<ContractAddress>`)},I=8,A=s=>10n**BigInt(s),S=s=>Math.log10(parseFloat(s.toString()));function B({value:s,bigIntDecimal:e=I,decimal:t=I}){const r=s<0n;let n=s.toString().substring(r?1:0);const a=t-(n.length-1);a>0&&(n="0".repeat(a)+n);const o=n.length-t;let c=n.slice(-t);return parseInt(c[e])>=5?c=`${c.substring(0,e-1)}${(parseInt(c[e-1])+1).toString()}`:c=c.substring(0,e),`${r?"-":""}${n.slice(0,o)}.${c}`.replace(/\.?0*$/,"")}var b,v,P,_e,x,ye,$,G,C,R,E,K;const D=class D{constructor(e){y(this,b);y(this,P);y(this,x);y(this,$);y(this,C);y(this,E);p(this,"decimalMultiplier",10n**8n);p(this,"bigIntValue",0n);p(this,"decimal");const t=F(e);this.decimal=typeof e=="object"?e.decimal:void 0,this.decimalMultiplier=A(Math.max(d(this,E,K).call(this,d(this,C,R).call(this,t)),this.decimal||0)),d(this,P,_e).call(this,t)}static fromBigInt(e,t){return new D({decimal:t,value:B({value:e,bigIntDecimal:t,decimal:t})})}static shiftDecimals({value:e,from:t,to:r}){return this.fromBigInt(new D(e).bigIntValue*A(r)/A(t),r)}get baseValue(){return this.getBaseValue("string")}get baseValueNumber(){return this.getBaseValue("number")}get baseValueBigInt(){return this.getBaseValue("bigint")}set(e){return new this.constructor({decimal:this.decimal,value:e,identifier:this.toString()})}add(...e){return d(this,b,v).call(this,"add",...e)}sub(...e){return d(this,b,v).call(this,"sub",...e)}mul(...e){return d(this,b,v).call(this,"mul",...e)}div(...e){return d(this,b,v).call(this,"div",...e)}gt(e){return this.bigIntValue>this.getBigIntValue(e)}gte(e){return this.bigIntValue>=this.getBigIntValue(e)}lt(e){return this.bigIntValue<this.getBigIntValue(e)}lte(e){return this.bigIntValue<=this.getBigIntValue(e)}eqValue(e){return this.bigIntValue===this.getBigIntValue(e)}getValue(e){const t=this.formatBigIntToSafeValue(this.bigIntValue,this.decimal||S(this.decimalMultiplier));switch(e){case"number":return Number(t);case"string":return t;default:return this.bigIntValue*BigInt(this.decimal||8n)/this.decimalMultiplier}}getBaseValue(e){const t=this.decimalMultiplier/A(this.decimal||i.BaseDecimal.THOR),r=this.bigIntValue/t;switch(e){case"number":return Number(r);case"string":return r.toString();default:return r}}getBigIntValue(e,t){if(!t&&typeof e=="object")return e.bigIntValue;const r=F(e),n=d(this,C,R).call(this,r);return n==="0"||n==="undefined"?0n:d(this,$,G).call(this,n,t)}formatBigIntToSafeValue(e,t){const r=t||this.decimal||I,n=Math.max(r,S(this.decimalMultiplier)),a=e<0n,o=e.toString().substring(a?1:0),c=n-(o.length-1),u=c>0?"0".repeat(c)+o:o,l=u.length-n;let h=u.slice(-n);return parseInt(h[r])>=5?h=`${h.substring(0,r-1)}${(parseInt(h[r-1])+1).toString()}`:h=h.substring(0,r),`${a?"-":""}${u.slice(0,l)}.${h}`.replace(/\.?0*$/,"")}toSignificant(e=6){const[t,r]=this.getValue("string").split("."),n=t||"",a=r||"";if((parseInt(n)?n.length+a.length:a.length)<=e)return this.getValue("string");if(n.length>=e)return n.slice(0,e).padEnd(n.length,"0");if(parseInt(n))return`${n}.${a.slice(0,e-n.length)}`.padEnd(e-n.length,"0");const c=parseInt(a),u=`${c}`.slice(0,e);return`0.${u.padStart(a.length-`${c}`.length+u.length,"0")}`}toFixed(e=6){const[t,r]=this.getValue("string").split("."),n=t||"",a=r||"";if(parseInt(n))return`${n}.${a.slice(0,e)}`.padEnd(e,"0");const o=parseInt(a),c=`${o}`.slice(0,e);return`0.${c.padStart(a.length-`${o}`.length+c.length,"0")}`}toAbbreviation(e=2){const t=this.getValue("number"),r=["","K","M","B","T","Q","Qi","S"],n=Math.floor(Math.log10(Math.abs(t))/3),a=r[n];if(!a)return this.getValue("string");const o=10**(n*3);return`${(t/o).toFixed(e)}${a}`}};b=new WeakSet,v=function(e,...t){const r=d(this,x,ye).call(this,this,...t),n=A(r),a=t.reduce((c,u)=>{const l=this.getBigIntValue(u,r);switch(e){case"add":return c+l;case"sub":return c-l;case"mul":return c*l/n;case"div":{if(l===0n)throw new RangeError("Division by zero");return c*n/l}default:return c}},this.bigIntValue*n/this.decimalMultiplier),o=B({bigIntDecimal:r,decimal:Math.max(r,S(this.decimalMultiplier)),value:a});return new this.constructor({decimal:this.decimal,value:o,identifier:this.toString()})},P=new WeakSet,_e=function(e){const t=d(this,C,R).call(this,e)||"0";this.bigIntValue=d(this,$,G).call(this,t)},x=new WeakSet,ye=function(...e){const t=e.map(r=>typeof r=="object"?r.decimal||S(r.decimalMultiplier):d(this,E,K).call(this,d(this,C,R).call(this,r))).filter(Boolean);return Math.max(...t,I)},$=new WeakSet,G=function(e,t){const r=t?A(t):this.decimalMultiplier,n=S(r),[a="",o=""]=e.split(".");return BigInt(`${a}${o.padEnd(n,"0")}`)},C=new WeakSet,R=function(e){const r=`${typeof e=="number"?Number(e).toLocaleString("fullwide",{useGrouping:!1,maximumFractionDigits:20}):F(e)}`.replaceAll(",",".").split(".");return r.length>1?`${r.slice(0,-1).join("")}.${r.at(-1)}`:r[0]},E=new WeakSet,K=function(e){var r;const t=((r=e.split(".")[1])==null?void 0:r.length)||0;return Math.max(t,I)};let T=D;function F(s){return typeof s=="object"?"getValue"in s?s.getValue("string"):s.value:s}const V=(s,e)=>typeof s=="bigint"?B({value:s,bigIntDecimal:e,decimal:e}):s;let Y;const U=s=>{if(!Y)throw new Error("Static assets not loaded, call await AssetValue.loadStaticAssets() first");return Y.get(s.toUpperCase())||{decimal:i.BaseDecimal.THOR,identifier:""}},se=async(s,e=0)=>{mt(s);const t=await z(q(s)),r=V(e,t);return new f({decimal:t,value:r,identifier:s})};class f extends T{constructor(t){super(t.value instanceof T?t.value:{decimal:t.decimal,value:t.value});p(this,"address");p(this,"chain");p(this,"isSynthetic",!1);p(this,"isGasAsset",!1);p(this,"symbol");p(this,"ticker");p(this,"type");const r="identifier"in t?t.identifier:`${t.chain}.${t.symbol}`,n=q(r);this.type=oe(n),this.chain=n.chain,this.ticker=n.ticker,this.symbol=n.symbol,this.address=n.address,this.isSynthetic=n.isSynthetic,this.isGasAsset=n.isGasAsset}get assetValue(){return`${this.getValue("string")} ${this.ticker}`}toString(t=!1){const r=this.isSynthetic?this.symbol.split("-")[0]:`${this.chain}.${this.ticker}`;return t?r:`${this.chain}.${this.symbol}`}eq({chain:t,symbol:r}){return this.chain===t&&this.symbol===r}static async fromString(t,r=0){return se(t,r)}static fromStringSync(t,r=0){const{isSynthetic:n}=q(t),{decimal:a,identifier:o}=U(t),c=V(r,a);return o?new f({decimal:a,identifier:o,value:c}):n?new f({decimal:8,identifier:t,value:c}):void 0}static async fromIdentifier(t,r=0){return se(t,r)}static fromIdentifierSync(t,r=0){const{decimal:n,identifier:a}=U(t),o=V(r,n);return new f({decimal:n,identifier:a,value:o})}static fromChainOrSignature(t,r=0){const{decimal:n,identifier:a}=ae(t),o=V(r,n);return new f({value:o,decimal:n,identifier:a})}static async fromTCQuote(t,r=0){const n=await z(q(t)),a=this.shiftDecimals({value:r,from:i.BaseDecimal.THOR,to:n});return new f({value:a,identifier:t,decimal:n})}static fromTCQuoteStatic(t,r=0){const n=U(t),a=this.shiftDecimals({value:r,from:i.BaseDecimal.THOR,to:n.decimal});return new f({...n,value:a})}static async loadStaticAssets(){return new Promise(async(t,r)=>{try{const{ThorchainList:n,NativeList:a,...o}=await import("@swapkit/tokens");Y=[a,...Object.values(o)].reduce((u,{tokens:l})=>(l.forEach(({identifier:h,chain:_,...w})=>{const N="decimals"in w?w.decimals:i.BaseDecimal[_];u.set(h,{identifier:h,decimal:N})}),u),new Map),t({ok:!0})}catch(n){console.error(n),r({ok:!1,error:n,message:"Couldn't load static assets. Ensure you have installed @swapkit/tokens package"})}})}}const pt=s=>{const e=f.fromChainOrSignature(s);switch(s){case i.Chain.Bitcoin:case i.Chain.Litecoin:case i.Chain.BitcoinCash:return e.add(10001);case i.Chain.Dogecoin:return e.add(100000001);case i.Chain.Avalanche:case i.Chain.Ethereum:return e.add(10*10**9);case i.Chain.THORChain:case i.Chain.Maya:return e.add(0);default:return e.add(1)}},q=s=>{const e=s.slice(0,14).includes("/"),[t,r]=s.split(".").pop().split("/"),n=s.includes(".")&&!e?s:`${i.Chain.THORChain}.${r}`,[a,o]=n.split("."),[c,u]=(e?r:o).split("-");return{address:u==null?void 0:u.toLowerCase(),chain:a,isGasAsset:ie({chain:a,symbol:o}),isSynthetic:e,symbol:(e?`${t}/`:"")+(u?`${c}-${(u==null?void 0:u.toLowerCase())??""}`:o),ticker:c}},ft={core_wallet_connection_not_found:10001,core_estimated_max_spendable_chain_not_supported:10002,core_extend_error:10003,core_inbound_data_not_found:10004,core_approve_asset_address_or_from_not_found:10005,core_chain_halted:10099,core_wallet_xdefi_not_installed:10101,core_wallet_evmwallet_not_installed:10102,core_wallet_walletconnect_not_installed:10103,core_wallet_keystore_not_installed:10104,core_wallet_ledger_not_installed:10105,core_wallet_trezor_not_installed:10106,core_wallet_keplr_not_installed:10107,core_wallet_okx_not_installed:10108,core_swap_invalid_params:10200,core_swap_route_not_complete:10201,core_swap_asset_not_recognized:10202,core_swap_contract_not_found:10203,core_swap_route_transaction_not_found:10204,core_swap_contract_not_supported:10205,core_swap_transaction_error:10206,core_swap_quote_mode_not_supported:10207,core_transaction_deposit_error:10301,core_transaction_create_liquidity_rune_error:10302,core_transaction_create_liquidity_asset_error:10303,core_transaction_create_liquidity_invalid_params:10304,core_transaction_add_liquidity_invalid_params:10305,core_transaction_add_liquidity_no_rune_address:10306,core_transaction_add_liquidity_rune_error:10307,core_transaction_add_liquidity_asset_error:10308,core_transaction_withdraw_error:10309,core_transaction_deposit_to_pool_error:10310,core_transaction_deposit_insufficient_funds_error:10311,core_transaction_deposit_gas_error:10312,core_transaction_deposit_server_error:10313,wallet_ledger_connection_error:20001,helpers_number_different_decimals:99101};class Q extends Error{constructor(e,t){console.error(t),super(e,{cause:{code:ft[e],message:e}}),Object.setPrototypeOf(this,Q.prototype)}}class g extends T{eq(e){return this.eqValue(e)}static fromBigInt(e,t){return new g({decimal:t,value:B({value:e,bigIntDecimal:t,decimal:t})})}}exports.AssetValue=f;exports.BigIntArithmetics=T;exports.RequestClient=ge;exports.SwapKitError=Q;exports.SwapKitNumber=g;exports.assetFromString=xe;exports.derivationPathToString=ze;exports.filterAssets=Ne;exports.formatBigIntToSafeValue=B;exports.gasFeeMultiplier=Pe;exports.getAssetType=oe;exports.getAsymmetricAssetShare=ue;exports.getAsymmetricAssetWithdrawAmount=je;exports.getAsymmetricRuneShare=ce;exports.getAsymmetricRuneWithdrawAmount=He;exports.getCommonAssetInfo=ae;exports.getDecimal=z;exports.getEstimatedPoolShare=Fe;exports.getLiquiditySlippage=Ue;exports.getMemoFor=Ge;exports.getMinAmountByChain=pt;exports.getSymmetricPoolShare=le;exports.getSymmetricWithdraw=Le;exports.getTHORNameCost=Ke;exports.isGasAsset=ie;exports.validateTHORName=Ye;
|
|
1
|
+
"use strict";var Te=Object.create;var D=Object.defineProperty;var Se=Object.getOwnPropertyDescriptor;var ve=Object.getOwnPropertyNames;var Re=Object.getPrototypeOf,$e=Object.prototype.hasOwnProperty;var Be=(s,e,t)=>e in s?D(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t;var Ie=(s,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of ve(e))!$e.call(s,n)&&n!==t&&D(s,n,{get:()=>e[n],enumerable:!(r=Se(e,n))||r.enumerable});return s};var Ee=(s,e,t)=>(t=s!=null?Te(Re(s)):{},Ie(e||!s||!s.__esModule?D(t,"default",{value:s,enumerable:!0}):t,s));var p=(s,e,t)=>(Be(s,typeof e!="symbol"?e+"":e,t),t),Oe=(s,e,t)=>{if(!e.has(s))throw TypeError("Cannot "+t)};var y=(s,e,t)=>{if(e.has(s))throw TypeError("Cannot add the same private member more than once");e instanceof WeakSet?e.add(s):e.set(s,t)};var d=(s,e,t)=>(Oe(s,e,"access private method"),t);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const i=require("@swapkit/types"),Me="0x313ce567",se=async({chain:s,to:e})=>{try{const{result:t}=await ge.post(i.ChainToRPC[s],{headers:{accept:"*/*","content-type":"application/json","cache-control":"no-cache"},body:JSON.stringify({id:44,jsonrpc:"2.0",method:"eth_call",params:[{to:e.toLowerCase(),data:Me},"latest"]})});return parseInt(BigInt(t).toString())}catch(t){return console.error(t),i.BaseDecimal[s]}},Ve=async s=>{if(s===i.Chain.Ethereum)return i.BaseDecimal.ETH;const[,e]=s.split("-");return e!=null&&e.startsWith("0x")?se({chain:i.Chain.Ethereum,to:e}):i.BaseDecimal.ETH},qe=async s=>{const[,e]=s.split("-");return e!=null&&e.startsWith("0x")?se({chain:i.Chain.Avalanche,to:e.toLowerCase()}):i.BaseDecimal.AVAX},ke=async s=>(s===i.Chain.BinanceSmartChain,i.BaseDecimal.BSC),ne=async({chain:s,symbol:e})=>{switch(s){case i.Chain.Ethereum:return Ve(e);case i.Chain.Avalanche:return qe(e);case i.Chain.BinanceSmartChain:return ke(e);default:return i.BaseDecimal[s]}},Pe={[i.FeeOption.Average]:1.2,[i.FeeOption.Fast]:1.5,[i.FeeOption.Fastest]:2},ie=({chain:s,symbol:e})=>{switch(s){case i.Chain.Bitcoin:case i.Chain.BitcoinCash:case i.Chain.Litecoin:case i.Chain.Dogecoin:case i.Chain.Binance:case i.Chain.Ethereum:case i.Chain.Avalanche:return e===s;case i.Chain.Arbitrum:case i.Chain.Optimism:return e==="ETH";case i.Chain.Maya:return e==="CACAO";case i.Chain.Kujira:return e==="KUJI";case i.Chain.Cosmos:return e==="ATOM";case i.Chain.Polygon:return e==="MATIC";case i.Chain.BinanceSmartChain:return e==="BNB";case i.Chain.THORChain:return e==="RUNE"}},ae=s=>{switch(s){case"ETH.THOR":return{identifier:"ETH.THOR-0xa5f2211b9b8170f694421f2046281775e8468044",decimal:18};case"ETH.vTHOR":return{identifier:"ETH.vTHOR-0x815c23eca83261b6ec689b60cc4a58b54bc24d8d",decimal:18};case i.Chain.Cosmos:return{identifier:"GAIA.ATOM",decimal:i.BaseDecimal[s]};case i.Chain.THORChain:return{identifier:"THOR.RUNE",decimal:i.BaseDecimal[s]};case i.Chain.BinanceSmartChain:return{identifier:"BSC.BNB",decimal:i.BaseDecimal[s]};case i.Chain.Maya:return{identifier:"MAYA.CACAO",decimal:i.BaseDecimal.MAYA};case"MAYA.MAYA":return{identifier:"MAYA.MAYA",decimal:4};case i.Chain.Kujira:case i.Chain.Arbitrum:case i.Chain.Optimism:case i.Chain.BitcoinCash:case i.Chain.Litecoin:case i.Chain.Dogecoin:case i.Chain.Binance:case i.Chain.Avalanche:case i.Chain.Polygon:case i.Chain.Bitcoin:case i.Chain.Ethereum:return{identifier:`${s}.${s}`,decimal:i.BaseDecimal[s]}}},oe=({chain:s,symbol:e})=>{if(e.includes("/"))return"Synth";switch(s){case i.Chain.Bitcoin:case i.Chain.BitcoinCash:case i.Chain.Dogecoin:case i.Chain.Litecoin:case i.Chain.Maya:case i.Chain.THORChain:return"Native";case i.Chain.Cosmos:return e==="ATOM"?"Native":i.Chain.Cosmos;case i.Chain.Kujira:return e===i.Chain.Kujira?"Native":i.Chain.Kujira;case i.Chain.Binance:return e===i.Chain.Binance?"Native":"BEP2";case i.Chain.BinanceSmartChain:return e===i.Chain.Binance?"Native":"BEP20";case i.Chain.Ethereum:return e===i.Chain.Ethereum?"Native":"ERC20";case i.Chain.Avalanche:return e===i.Chain.Avalanche?"Native":i.Chain.Avalanche;case i.Chain.Polygon:return e===i.Chain.Polygon?"Native":"POLYGON";case i.Chain.Arbitrum:return[i.Chain.Ethereum,i.Chain.Arbitrum].includes(e)?"Native":"ARBITRUM";case i.Chain.Optimism:return[i.Chain.Ethereum,i.Chain.Optimism].includes(e)?"Native":"OPTIMISM"}},xe=s=>{var o;const[e,...t]=s.split("."),r=s.includes("/"),n=t.join("."),a=(o=n==null?void 0:n.split("-"))==null?void 0:o[0];return{chain:e,symbol:n,ticker:a,synth:r}},Ne=new RegExp(/(.)\1{6}|\.ORG|\.NET|\.FINANCE|\.COM|WWW|HTTP|\\\\|\/\/|[\s$%:[\]]/,"gmi"),De=s=>s.filter(e=>!Ne.test(e.toString())&&!e.toString().includes("undefined")),ce=({liquidityUnits:s,poolUnits:e,runeDepth:t})=>{const r=m(s),n=m(e),a=m(t),o=r.mul(a),c=n.mul(n).mul(2),u=n.mul(r).mul(2),l=r.mul(r),h=n.mul(n).mul(n);return o.mul(c.sub(u).add(l)).div(h)},ue=({liquidityUnits:s,poolUnits:e,assetDepth:t})=>{const r=m(s),n=m(e),a=m(t),o=r.mul(a),c=n.mul(n).mul(2),u=n.mul(r).mul(2),l=r.mul(r),h=o.mul(c.sub(u).add(l)),g=n.mul(n).mul(n);return h.div(g)},je=({percent:s,runeDepth:e,liquidityUnits:t,poolUnits:r})=>ce({runeDepth:e,liquidityUnits:t,poolUnits:r}).mul(s),He=({percent:s,assetDepth:e,liquidityUnits:t,poolUnits:r})=>ue({assetDepth:e,liquidityUnits:t,poolUnits:r}).mul(s),m=s=>f.fromBigInt(BigInt(s),i.BaseDecimal.THOR),le=({liquidityUnits:s,poolUnits:e,runeDepth:t,assetDepth:r})=>({assetAmount:m(r).mul(s).div(e),runeAmount:m(t).mul(s).div(e)}),Le=({liquidityUnits:s,poolUnits:e,runeDepth:t,assetDepth:r,percent:n})=>Object.fromEntries(Object.entries(le({liquidityUnits:s,poolUnits:e,runeDepth:t,assetDepth:r})).map(([a,o])=>[a,o.mul(n)])),Fe=({runeDepth:s,poolUnits:e,assetDepth:t,liquidityUnits:r,runeAmount:n,assetAmount:a})=>{const o=new f({value:s,decimal:8}),c=new f({value:t,decimal:8}),u=new f({value:e,decimal:8}),l=new f({value:n,decimal:8}),h=new f({value:a,decimal:8}),g=l.mul(c),w=h.mul(o),x=l.mul(h),be=o.mul(c),Ce=u.mul(g.add(w.add(x.mul(2)))),we=g.add(w.add(be.mul(2))),J=Ce.div(we),N=m(r).add(J);if(J.getBaseValue("number")===0)return N.div(u).getBaseValue("number");const Ae=u.add(N);return N.div(Ae).getBaseValue("number")},Ue=({runeAmount:s,assetAmount:e,runeDepth:t,assetDepth:r})=>{if(s==="0"||e==="0"||t==="0"||r==="0")return 0;const n=m(t),a=m(r),o=m(e),c=m(s),u=o.mul(n).sub(a.mul(c)),l=a.mul(c).add(n.mul(a));return Math.abs(u.div(l).getBaseValue("number"))},We=({symbol:s,ticker:e,chain:t})=>t==="ETH"&&e!=="ETH"?`${e}-${s.slice(-3)}`:s,Ge=(s,e)=>{switch(s){case i.MemoType.LEAVE:case i.MemoType.BOND:{const{address:t}=e;return`${s}:${t}`}case i.MemoType.UNBOND:{const{address:t,unbondAmount:r}=e;return`${s}:${t}:${r*10**8}`}case i.MemoType.THORNAME_REGISTER:{const{name:t,chain:r,address:n,owner:a}=e;return`${s}:${t}:${r}:${n}${a?`:${a}`:""}`}case i.MemoType.DEPOSIT:{const{chain:t,symbol:r,address:n,singleSide:a}=e;return a?`${s}:${t}/${r}::t:0`:`${s}:${t}.${r}:${n||""}:t:0`}case i.MemoType.WITHDRAW:{const{chain:t,ticker:r,symbol:n,basisPoints:a,targetAssetString:o,singleSide:c}=e,u=!c&&o?`:${o}`:"",l=We({chain:t,symbol:n,ticker:r});return`${s}:${t}${c?"/":"."}${l}:${a}${u}`}case i.MemoType.OPEN_LOAN:case i.MemoType.CLOSE_LOAN:{const{asset:t,address:r}=e;return`${s}:${t}:${r}`}default:return""}},Ke=s=>{if(s<0)throw new Error("Invalid number of year");return 10+s},Ye=s=>{if(s.length>30)return!1;const e=/^[a-zA-Z0-9+_-]+$/g;return!!s.match(e)},ze=([s,e,t,r,n])=>`${s}'/${e}'/${t}'/${r}${typeof n!="number"?"":`/${n}`}`;class Q extends Error{constructor(e,t,r){const n=e.status||e.status===0?e.status:"",a=e.statusText||"",o=`${n} ${a}`.trim(),c=o?`status code ${o}`:"an unknown error";super(`Request failed with ${c}`),Object.defineProperty(this,"response",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"request",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"options",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.name="HTTPError",this.response=e,this.request=t,this.options=r}}class he extends Error{constructor(e){super("Request timed out"),Object.defineProperty(this,"request",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.name="TimeoutError",this.request=e}}const M=s=>s!==null&&typeof s=="object",O=(...s)=>{for(const e of s)if((!M(e)||Array.isArray(e))&&e!==void 0)throw new TypeError("The `options` argument must be an object");return K({},...s)},de=(s={},e={})=>{const t=new globalThis.Headers(s),r=e instanceof globalThis.Headers,n=new globalThis.Headers(e);for(const[a,o]of n.entries())r&&o==="undefined"||o===void 0?t.delete(a):t.set(a,o);return t},K=(...s)=>{let e={},t={};for(const r of s)if(Array.isArray(r))Array.isArray(e)||(e=[]),e=[...e,...r];else if(M(r)){for(let[n,a]of Object.entries(r))M(a)&&n in e&&(a=K(e[n],a)),e={...e,[n]:a};M(r.headers)&&(t=de(t,r.headers),e.headers=t)}return e},Je=(()=>{let s=!1,e=!1;const t=typeof globalThis.ReadableStream=="function",r=typeof globalThis.Request=="function";return t&&r&&(e=new globalThis.Request("https://empty.invalid",{body:new globalThis.ReadableStream,method:"POST",get duplex(){return s=!0,"half"}}).headers.has("Content-Type")),s&&!e})(),Qe=typeof globalThis.AbortController=="function",Xe=typeof globalThis.ReadableStream=="function",Ze=typeof globalThis.FormData=="function",me=["get","post","put","patch","head","delete"],et={json:"application/json",text:"text/*",formData:"multipart/form-data",arrayBuffer:"*/*",blob:"*/*"},j=2147483647,pe=Symbol("stop"),tt={json:!0,parseJson:!0,searchParams:!0,prefixUrl:!0,retry:!0,timeout:!0,hooks:!0,throwHttpErrors:!0,onDownloadProgress:!0,fetch:!0},rt={method:!0,headers:!0,body:!0,mode:!0,credentials:!0,cache:!0,redirect:!0,referrer:!0,referrerPolicy:!0,integrity:!0,keepalive:!0,signal:!0,window:!0,dispatcher:!0,duplex:!0},st=s=>me.includes(s)?s.toUpperCase():s,nt=["get","put","head","delete","options","trace"],it=[408,413,429,500,502,503,504],fe=[413,429,503],X={limit:2,methods:nt,statusCodes:it,afterStatusCodes:fe,maxRetryAfter:Number.POSITIVE_INFINITY,backoffLimit:Number.POSITIVE_INFINITY,delay:s=>.3*2**(s-1)*1e3},at=(s={})=>{if(typeof s=="number")return{...X,limit:s};if(s.methods&&!Array.isArray(s.methods))throw new Error("retry.methods must be an array");if(s.statusCodes&&!Array.isArray(s.statusCodes))throw new Error("retry.statusCodes must be an array");return{...X,...s,afterStatusCodes:fe}};async function ot(s,e,t,r){return new Promise((n,a)=>{const o=setTimeout(()=>{t&&t.abort(),a(new he(s))},r.timeout);r.fetch(s,e).then(n).catch(a).then(()=>{clearTimeout(o)})})}async function ct(s,{signal:e}){return new Promise((t,r)=>{e&&(e.throwIfAborted(),e.addEventListener("abort",n,{once:!0}));function n(){clearTimeout(a),r(e.reason)}const a=setTimeout(()=>{e==null||e.removeEventListener("abort",n),t()},s)})}const ut=(s,e)=>{const t={};for(const r in e)!(r in rt)&&!(r in tt)&&!(r in s)&&(t[r]=e[r]);return t};class q{static create(e,t){const r=new q(e,t),n=async()=>{if(typeof r._options.timeout=="number"&&r._options.timeout>j)throw new RangeError(`The \`timeout\` option cannot be greater than ${j}`);await Promise.resolve();let c=await r._fetch();for(const u of r._options.hooks.afterResponse){const l=await u(r.request,r._options,r._decorateResponse(c.clone()));l instanceof globalThis.Response&&(c=l)}if(r._decorateResponse(c),!c.ok&&r._options.throwHttpErrors){let u=new Q(c,r.request,r._options);for(const l of r._options.hooks.beforeError)u=await l(u);throw u}if(r._options.onDownloadProgress){if(typeof r._options.onDownloadProgress!="function")throw new TypeError("The `onDownloadProgress` option must be a function");if(!Xe)throw new Error("Streams are not supported in your environment. `ReadableStream` is missing.");return r._stream(c.clone(),r._options.onDownloadProgress)}return c},o=r._options.retry.methods.includes(r.request.method.toLowerCase())?r._retry(n):n();for(const[c,u]of Object.entries(et))o[c]=async()=>{r.request.headers.set("accept",r.request.headers.get("accept")||u);const h=(await o).clone();if(c==="json"){if(h.status===204||(await h.clone().arrayBuffer()).byteLength===0)return"";if(t.parseJson)return t.parseJson(await h.text())}return h[c]()};return o}constructor(e,t={}){if(Object.defineProperty(this,"request",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"abortController",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_retryCount",{enumerable:!0,configurable:!0,writable:!0,value:0}),Object.defineProperty(this,"_input",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_options",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this._input=e,this._options={credentials:this._input.credentials||"same-origin",...t,headers:de(this._input.headers,t.headers),hooks:K({beforeRequest:[],beforeRetry:[],beforeError:[],afterResponse:[]},t.hooks),method:st(t.method??this._input.method),prefixUrl:String(t.prefixUrl||""),retry:at(t.retry),throwHttpErrors:t.throwHttpErrors!==!1,timeout:t.timeout??1e4,fetch:t.fetch??globalThis.fetch.bind(globalThis)},typeof this._input!="string"&&!(this._input instanceof URL||this._input instanceof globalThis.Request))throw new TypeError("`input` must be a string, URL, or Request");if(this._options.prefixUrl&&typeof this._input=="string"){if(this._input.startsWith("/"))throw new Error("`input` must not begin with a slash when using `prefixUrl`");this._options.prefixUrl.endsWith("/")||(this._options.prefixUrl+="/"),this._input=this._options.prefixUrl+this._input}if(Qe){if(this.abortController=new globalThis.AbortController,this._options.signal){const r=this._options.signal;this._options.signal.addEventListener("abort",()=>{this.abortController.abort(r.reason)})}this._options.signal=this.abortController.signal}if(Je&&(this._options.duplex="half"),this.request=new globalThis.Request(this._input,this._options),this._options.searchParams){const n="?"+(typeof this._options.searchParams=="string"?this._options.searchParams.replace(/^\?/,""):new URLSearchParams(this._options.searchParams).toString()),a=this.request.url.replace(/(?:\?.*?)?(?=#|$)/,n);(Ze&&this._options.body instanceof globalThis.FormData||this._options.body instanceof URLSearchParams)&&!(this._options.headers&&this._options.headers["content-type"])&&this.request.headers.delete("content-type"),this.request=new globalThis.Request(new globalThis.Request(a,{...this.request}),this._options)}this._options.json!==void 0&&(this._options.body=JSON.stringify(this._options.json),this.request.headers.set("content-type",this._options.headers.get("content-type")??"application/json"),this.request=new globalThis.Request(this.request,{body:this._options.body}))}_calculateRetryDelay(e){if(this._retryCount++,this._retryCount<this._options.retry.limit&&!(e instanceof he)){if(e instanceof Q){if(!this._options.retry.statusCodes.includes(e.response.status))return 0;const r=e.response.headers.get("Retry-After");if(r&&this._options.retry.afterStatusCodes.includes(e.response.status)){let n=Number(r);return Number.isNaN(n)?n=Date.parse(r)-Date.now():n*=1e3,this._options.retry.maxRetryAfter!==void 0&&n>this._options.retry.maxRetryAfter?0:n}if(e.response.status===413)return 0}const t=this._options.retry.delay(this._retryCount);return Math.min(this._options.retry.backoffLimit,t)}return 0}_decorateResponse(e){return this._options.parseJson&&(e.json=async()=>this._options.parseJson(await e.text())),e}async _retry(e){try{return await e()}catch(t){const r=Math.min(this._calculateRetryDelay(t),j);if(r!==0&&this._retryCount>0){await ct(r,{signal:this._options.signal});for(const n of this._options.hooks.beforeRetry)if(await n({request:this.request,options:this._options,error:t,retryCount:this._retryCount})===pe)return;return this._retry(e)}throw t}}async _fetch(){for(const t of this._options.hooks.beforeRequest){const r=await t(this.request,this._options);if(r instanceof Request){this.request=r;break}if(r instanceof Response)return r}const e=ut(this.request,this._options);return this._options.timeout===!1?this._options.fetch(this.request.clone(),e):ot(this.request.clone(),e,this.abortController,this._options)}_stream(e,t){const r=Number(e.headers.get("content-length"))||0;let n=0;return e.status===204?(t&&t({percent:1,totalBytes:r,transferredBytes:n},new Uint8Array),new globalThis.Response(null,{status:e.status,statusText:e.statusText,headers:e.headers})):new globalThis.Response(new globalThis.ReadableStream({async start(a){const o=e.body.getReader();t&&t({percent:0,transferredBytes:0,totalBytes:r},new Uint8Array);async function c(){const{done:u,value:l}=await o.read();if(u){a.close();return}if(t){n+=l.byteLength;const h=r===0?0:n/r;t({percent:h,transferredBytes:n,totalBytes:r},l)}a.enqueue(l),await c()}await c()}}),{status:e.status,statusText:e.statusText,headers:e.headers})}}/*! MIT License © Sindre Sorhus */const L=s=>{const e=(t,r)=>q.create(t,O(s,r));for(const t of me)e[t]=(r,n)=>q.create(r,O(s,n,{method:t}));return e.create=t=>L(O(t)),e.extend=t=>L(O(s,t)),e.stop=pe,e},lt=L(),ht=lt,dt=typeof window<"u"?{}:{referrer:"https://sk.thorswap.net",referer:"https://sk.thorswap.net"},Z=ht.create({headers:dt}),ge={get:(s,e)=>Z.get(s,e).json(),post:(s,e)=>Z.post(s,e).json()},ee=Object.values(i.Chain),mt=(s="")=>{const e=s.toUpperCase(),[t]=e.split(".");if(ee.includes(t))return!0;const[r]=e.split("/");if(ee.includes(r))return!0;throw new Error(`Invalid identifier: ${s}. Expected format: <Chain>.<Ticker> or <Chain>.<Ticker>-<ContractAddress>`)},$=8,A=s=>10n**BigInt(s),S=s=>Math.log10(parseFloat(s.toString()));function B({value:s,bigIntDecimal:e=$,decimal:t=$}){const r=s<0n;let n=s.toString().substring(r?1:0);const a=t-(n.length-1);a>0&&(n="0".repeat(a)+n);const o=n.length-t;let c=n.slice(-t);return parseInt(c[e])>=5?c=`${c.substring(0,e-1)}${(parseInt(c[e-1])+1).toString()}`:c=c.substring(0,e),`${r?"-":""}${n.slice(0,o)}.${c}`.replace(/\.?0*$/,"")}var b,v,k,_e,P,ye,I,F,C,R,E,U;const z=class z{constructor(e){y(this,b);y(this,k);y(this,P);y(this,I);y(this,C);y(this,E);p(this,"decimalMultiplier",10n**8n);p(this,"bigIntValue",0n);p(this,"decimal");const t=H(e);this.decimal=typeof e=="object"?e.decimal:void 0,this.decimalMultiplier=A(Math.max(d(this,E,U).call(this,d(this,C,R).call(this,t)),this.decimal||0)),d(this,k,_e).call(this,t)}static fromBigInt(e,t){return new z({decimal:t,value:B({value:e,bigIntDecimal:t,decimal:t})})}static shiftDecimals({value:e,from:t,to:r}){return this.fromBigInt(e.getBaseValue("bigint")*A(r)/A(t),r)}get baseValue(){return this.getBaseValue("string")}get baseValueNumber(){return this.getBaseValue("number")}get baseValueBigInt(){return this.getBaseValue("bigint")}set(e){return new this.constructor({decimal:this.decimal,value:e,identifier:this.toString()})}add(...e){return d(this,b,v).call(this,"add",...e)}sub(...e){return d(this,b,v).call(this,"sub",...e)}mul(...e){return d(this,b,v).call(this,"mul",...e)}div(...e){return d(this,b,v).call(this,"div",...e)}gt(e){return this.bigIntValue>this.getBigIntValue(e)}gte(e){return this.bigIntValue>=this.getBigIntValue(e)}lt(e){return this.bigIntValue<this.getBigIntValue(e)}lte(e){return this.bigIntValue<=this.getBigIntValue(e)}eqValue(e){return this.bigIntValue===this.getBigIntValue(e)}getValue(e){const t=this.formatBigIntToSafeValue(this.bigIntValue,this.decimal||S(this.decimalMultiplier));switch(e){case"number":return Number(t);case"string":return t;default:return this.bigIntValue*BigInt(this.decimal||8n)/this.decimalMultiplier}}getBaseValue(e){const t=this.decimalMultiplier/A(this.decimal||i.BaseDecimal.THOR),r=this.bigIntValue/t;switch(e){case"number":return Number(r);case"string":return r.toString();default:return r}}getBigIntValue(e,t){if(!t&&typeof e=="object")return e.bigIntValue;const r=H(e),n=d(this,C,R).call(this,r);return n==="0"||n==="undefined"?0n:d(this,I,F).call(this,n,t)}formatBigIntToSafeValue(e,t){const r=t||this.decimal||$,n=Math.max(r,S(this.decimalMultiplier)),a=e<0n,o=e.toString().substring(a?1:0),c=n-(o.length-1),u=c>0?"0".repeat(c)+o:o,l=u.length-n;let h=u.slice(-n);return parseInt(h[r])>=5?h=`${h.substring(0,r-1)}${(parseInt(h[r-1])+1).toString()}`:h=h.substring(0,r),`${a?"-":""}${u.slice(0,l)}.${h}`.replace(/\.?0*$/,"")}toSignificant(e=6){const[t,r]=this.getValue("string").split("."),n=t||"",a=r||"";if((parseInt(n)?n.length+a.length:a.length)<=e)return this.getValue("string");if(n.length>=e)return n.slice(0,e).padEnd(n.length,"0");if(parseInt(n))return`${n}.${a.slice(0,e-n.length)}`.padEnd(e-n.length,"0");const c=parseInt(a),u=`${c}`.slice(0,e);return`0.${u.padStart(a.length-`${c}`.length+u.length,"0")}`}toFixed(e=6){const[t,r]=this.getValue("string").split("."),n=t||"",a=r||"";if(parseInt(n))return`${n}.${a.slice(0,e)}`.padEnd(e,"0");const o=parseInt(a),c=`${o}`.slice(0,e);return`0.${c.padStart(a.length-`${o}`.length+c.length,"0")}`}toAbbreviation(e=2){const t=this.getValue("number"),r=["","K","M","B","T","Q","Qi","S"],n=Math.floor(Math.log10(Math.abs(t))/3),a=r[n];if(!a)return this.getValue("string");const o=10**(n*3);return`${(t/o).toFixed(e)}${a}`}};b=new WeakSet,v=function(e,...t){const r=d(this,P,ye).call(this,this,...t),n=A(r),a=t.reduce((c,u)=>{const l=this.getBigIntValue(u,r);switch(e){case"add":return c+l;case"sub":return c-l;case"mul":return c*l/n;case"div":{if(l===0n)throw new RangeError("Division by zero");return c*n/l}default:return c}},this.bigIntValue*n/this.decimalMultiplier),o=B({bigIntDecimal:r,decimal:Math.max(r,S(this.decimalMultiplier)),value:a});return new this.constructor({decimal:this.decimal,value:o,identifier:this.toString()})},k=new WeakSet,_e=function(e){const t=d(this,C,R).call(this,e)||"0";this.bigIntValue=d(this,I,F).call(this,t)},P=new WeakSet,ye=function(...e){const t=e.map(r=>typeof r=="object"?r.decimal||S(r.decimalMultiplier):d(this,E,U).call(this,d(this,C,R).call(this,r))).filter(Boolean);return Math.max(...t,$)},I=new WeakSet,F=function(e,t){const r=t?A(t):this.decimalMultiplier,n=S(r),[a="",o=""]=e.split(".");return BigInt(`${a}${o.padEnd(n,"0")}`)},C=new WeakSet,R=function(e){const r=`${typeof e=="number"?Number(e).toLocaleString("fullwide",{useGrouping:!1,maximumFractionDigits:20}):H(e)}`.replaceAll(",",".").split(".");return r.length>1?`${r.slice(0,-1).join("")}.${r.at(-1)}`:r[0]},E=new WeakSet,U=function(e){var r;const t=((r=e.split(".")[1])==null?void 0:r.length)||0;return Math.max(t,$)};let T=z;function H(s){return typeof s=="object"?"getValue"in s?s.getValue("string"):s.value:s}const V=(s,e)=>typeof s=="bigint"?B({value:s,bigIntDecimal:e,decimal:e}):s;let W;const te=s=>{if(!W)throw new Error("Static assets not loaded, call await AssetValue.loadStaticAssets() first");return W.get(s.toUpperCase())||{decimal:i.BaseDecimal.THOR,identifier:""}},re=async(s,e=0)=>{mt(s);const t=await ne(G(s)),r=V(e,t);return new _({decimal:t,value:r,identifier:s})};class _ extends T{constructor(t){super(t.value instanceof T?t.value:{decimal:t.decimal,value:t.value});p(this,"address");p(this,"chain");p(this,"isSynthetic",!1);p(this,"isGasAsset",!1);p(this,"symbol");p(this,"ticker");p(this,"type");const r="identifier"in t?t.identifier:`${t.chain}.${t.symbol}`,n=G(r);this.type=oe(n),this.chain=n.chain,this.ticker=n.ticker,this.symbol=n.symbol,this.address=n.address,this.isSynthetic=n.isSynthetic,this.isGasAsset=n.isGasAsset}get assetValue(){return`${this.getValue("string")} ${this.ticker}`}toString(t=!1){const r=this.isSynthetic?this.symbol.split("-")[0]:`${this.chain}.${this.ticker}`;return t?r:`${this.chain}.${this.symbol}`}eq({chain:t,symbol:r}){return this.chain===t&&this.symbol===r}static async fromString(t,r=0){return re(t,r)}static fromStringSync(t,r=0){const{isSynthetic:n}=G(t),{decimal:a,identifier:o}=te(t),c=V(r,a);return o?new _({decimal:a,identifier:o,value:c}):n?new _({decimal:8,identifier:t,value:c}):void 0}static async fromIdentifier(t,r=0){return re(t,r)}static fromIdentifierSync(t,r=0){const{decimal:n,identifier:a}=te(t),o=V(r,n);return new _({decimal:n,identifier:a,value:o})}static fromChainOrSignature(t,r=0){const{decimal:n,identifier:a}=ae(t),o=V(r,n);return new _({value:o,decimal:n,identifier:a})}static async loadStaticAssets(){return new Promise(async(t,r)=>{try{const{ThorchainList:n,NativeList:a,...o}=await import("@swapkit/tokens");W=[a,...Object.values(o)].reduce((u,{tokens:l})=>(l.forEach(({identifier:h,chain:g,...w})=>{const x="decimals"in w?w.decimals:i.BaseDecimal[g];u.set(h,{identifier:h,decimal:x})}),u),new Map),t({ok:!0})}catch(n){console.error(n),r({ok:!1,error:n,message:"Couldn't load static assets. Ensure you have installed @swapkit/tokens package"})}})}}const pt=s=>{const e=_.fromChainOrSignature(s);switch(s){case i.Chain.Bitcoin:case i.Chain.Litecoin:case i.Chain.BitcoinCash:return e.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)}},G=s=>{const e=s.slice(0,14).includes("/"),[t,r]=s.split(".").pop().split("/"),n=s.includes(".")&&!e?s:`${i.Chain.THORChain}.${r}`,[a,o]=n.split("."),[c,u]=(e?r:o).split("-");return{address:u==null?void 0:u.toLowerCase(),chain:a,isGasAsset:ie({chain:a,symbol:o}),isSynthetic:e,symbol:(e?`${t}/`:"")+(u?`${c}-${(u==null?void 0:u.toLowerCase())??""}`:o),ticker:c}},ft={core_wallet_connection_not_found:10001,core_estimated_max_spendable_chain_not_supported:10002,core_extend_error:10003,core_inbound_data_not_found:10004,core_approve_asset_address_or_from_not_found:10005,core_chain_halted:10099,core_wallet_xdefi_not_installed:10101,core_wallet_evmwallet_not_installed:10102,core_wallet_walletconnect_not_installed:10103,core_wallet_keystore_not_installed:10104,core_wallet_ledger_not_installed:10105,core_wallet_trezor_not_installed:10106,core_wallet_keplr_not_installed:10107,core_wallet_okx_not_installed:10108,core_swap_invalid_params:10200,core_swap_route_not_complete:10201,core_swap_asset_not_recognized:10202,core_swap_contract_not_found:10203,core_swap_route_transaction_not_found:10204,core_swap_contract_not_supported:10205,core_swap_transaction_error:10206,core_swap_quote_mode_not_supported:10207,core_transaction_deposit_error:10301,core_transaction_create_liquidity_rune_error:10302,core_transaction_create_liquidity_asset_error:10303,core_transaction_create_liquidity_invalid_params:10304,core_transaction_add_liquidity_invalid_params:10305,core_transaction_add_liquidity_no_rune_address:10306,core_transaction_add_liquidity_rune_error:10307,core_transaction_add_liquidity_asset_error:10308,core_transaction_withdraw_error:10309,core_transaction_deposit_to_pool_error:10310,core_transaction_deposit_insufficient_funds_error:10311,core_transaction_deposit_gas_error:10312,core_transaction_deposit_server_error:10313,wallet_ledger_connection_error:20001,helpers_number_different_decimals:99101};class Y extends Error{constructor(e,t){console.error(t),super(e,{cause:{code:ft[e],message:e}}),Object.setPrototypeOf(this,Y.prototype)}}class f extends T{eq(e){return this.eqValue(e)}static fromBigInt(e,t){return new f({decimal:t,value:B({value:e,bigIntDecimal:t,decimal:t})})}}exports.AssetValue=_;exports.BigIntArithmetics=T;exports.RequestClient=ge;exports.SwapKitError=Y;exports.SwapKitNumber=f;exports.assetFromString=xe;exports.derivationPathToString=ze;exports.filterAssets=De;exports.formatBigIntToSafeValue=B;exports.gasFeeMultiplier=Pe;exports.getAssetType=oe;exports.getAsymmetricAssetShare=ue;exports.getAsymmetricAssetWithdrawAmount=He;exports.getAsymmetricRuneShare=ce;exports.getAsymmetricRuneWithdrawAmount=je;exports.getCommonAssetInfo=ae;exports.getDecimal=ne;exports.getEstimatedPoolShare=Fe;exports.getLiquiditySlippage=Ue;exports.getMemoFor=Ge;exports.getMinAmountByChain=pt;exports.getSymmetricPoolShare=le;exports.getSymmetricWithdraw=Le;exports.getTHORNameCost=Ke;exports.isGasAsset=ie;exports.validateTHORName=Ye;
|
package/dist/index.d.ts
CHANGED
|
@@ -41,8 +41,6 @@ export declare class AssetValue extends BigIntArithmetics {
|
|
|
41
41
|
static fromIdentifier(assetString: `${Chain}.${string}` | `${Chain}/${string}` | `${Chain}.${string}-${string}`, value?: NumberPrimitives): Promise<AssetValue>;
|
|
42
42
|
static fromIdentifierSync(identifier: TokenNames, value?: NumberPrimitives): AssetValue;
|
|
43
43
|
static fromChainOrSignature(assetString: CommonAssetString, value?: NumberPrimitives): AssetValue;
|
|
44
|
-
static fromTCQuote(identifier: TCTokenNames, value?: NumberPrimitives): Promise<AssetValue>;
|
|
45
|
-
static fromTCQuoteStatic(identifier: TCTokenNames, value?: NumberPrimitives): AssetValue;
|
|
46
44
|
static loadStaticAssets(): Promise<{
|
|
47
45
|
ok: true;
|
|
48
46
|
} | {
|
|
@@ -69,7 +67,7 @@ export declare class BigIntArithmetics {
|
|
|
69
67
|
decimal?: number;
|
|
70
68
|
static fromBigInt(value: bigint, decimal?: number): BigIntArithmetics;
|
|
71
69
|
static shiftDecimals({ value, from, to, }: {
|
|
72
|
-
value:
|
|
70
|
+
value: InstanceType<typeof SwapKitNumber>;
|
|
73
71
|
from: number;
|
|
74
72
|
to: number;
|
|
75
73
|
}): BigIntArithmetics;
|
|
@@ -86,7 +84,7 @@ export declare class BigIntArithmetics {
|
|
|
86
84
|
* @deprecated Use `getBaseValue('bigint')` instead
|
|
87
85
|
*/
|
|
88
86
|
get baseValueBigInt(): bigint;
|
|
89
|
-
set(value: SKBigIntParams):
|
|
87
|
+
set(value: SKBigIntParams): this;
|
|
90
88
|
add(...args: InitialisationValueType[]): this;
|
|
91
89
|
sub(...args: InitialisationValueType[]): this;
|
|
92
90
|
mul(...args: InitialisationValueType[]): this;
|
package/dist/index.es.js
CHANGED
|
@@ -1,19 +1,19 @@
|
|
|
1
|
-
var
|
|
2
|
-
var
|
|
3
|
-
var
|
|
1
|
+
var gt = Object.defineProperty;
|
|
2
|
+
var bt = (s, t, e) => t in s ? gt(s, t, { enumerable: !0, configurable: !0, writable: !0, value: e }) : s[t] = e;
|
|
3
|
+
var f = (s, t, e) => (bt(s, typeof t != "symbol" ? t + "" : t, e), e), yt = (s, t, e) => {
|
|
4
4
|
if (!t.has(s))
|
|
5
5
|
throw TypeError("Cannot " + e);
|
|
6
6
|
};
|
|
7
|
-
var
|
|
7
|
+
var y = (s, t, e) => {
|
|
8
8
|
if (t.has(s))
|
|
9
9
|
throw TypeError("Cannot add the same private member more than once");
|
|
10
10
|
t instanceof WeakSet ? t.add(s) : t.set(s, e);
|
|
11
11
|
};
|
|
12
|
-
var m = (s, t, e) => (
|
|
13
|
-
import { FeeOption as
|
|
14
|
-
const
|
|
12
|
+
var m = (s, t, e) => (yt(s, t, "access private method"), e);
|
|
13
|
+
import { FeeOption as L, BaseDecimal as d, Chain as o, ChainToRPC as wt, MemoType as g } from "@swapkit/types";
|
|
14
|
+
const At = "0x313ce567", nt = async ({ chain: s, to: t }) => {
|
|
15
15
|
try {
|
|
16
|
-
const { result: e } = await Qt.post(
|
|
16
|
+
const { result: e } = await Qt.post(wt[s], {
|
|
17
17
|
headers: {
|
|
18
18
|
accept: "*/*",
|
|
19
19
|
"content-type": "application/json",
|
|
@@ -23,36 +23,36 @@ const Tt = "0x313ce567", nt = async ({ chain: s, to: t }) => {
|
|
|
23
23
|
id: 44,
|
|
24
24
|
jsonrpc: "2.0",
|
|
25
25
|
method: "eth_call",
|
|
26
|
-
params: [{ to: t.toLowerCase(), data:
|
|
26
|
+
params: [{ to: t.toLowerCase(), data: At }, "latest"]
|
|
27
27
|
})
|
|
28
28
|
});
|
|
29
29
|
return parseInt(BigInt(e).toString());
|
|
30
30
|
} catch (e) {
|
|
31
31
|
return console.error(e), d[s];
|
|
32
32
|
}
|
|
33
|
-
},
|
|
33
|
+
}, Tt = async (s) => {
|
|
34
34
|
if (s === o.Ethereum)
|
|
35
35
|
return d.ETH;
|
|
36
36
|
const [, t] = s.split("-");
|
|
37
37
|
return t != null && t.startsWith("0x") ? nt({ chain: o.Ethereum, to: t }) : d.ETH;
|
|
38
|
-
},
|
|
38
|
+
}, vt = async (s) => {
|
|
39
39
|
const [, t] = s.split("-");
|
|
40
40
|
return t != null && t.startsWith("0x") ? nt({ chain: o.Avalanche, to: t.toLowerCase() }) : d.AVAX;
|
|
41
|
-
}, St = async (s) => s === o.BinanceSmartChain ? d.BSC : d.BSC,
|
|
41
|
+
}, St = async (s) => s === o.BinanceSmartChain ? d.BSC : d.BSC, Rt = async ({ chain: s, symbol: t }) => {
|
|
42
42
|
switch (s) {
|
|
43
43
|
case o.Ethereum:
|
|
44
|
-
return
|
|
44
|
+
return Tt(t);
|
|
45
45
|
case o.Avalanche:
|
|
46
|
-
return
|
|
46
|
+
return vt(t);
|
|
47
47
|
case o.BinanceSmartChain:
|
|
48
48
|
return St(t);
|
|
49
49
|
default:
|
|
50
50
|
return d[s];
|
|
51
51
|
}
|
|
52
52
|
}, re = {
|
|
53
|
-
[
|
|
54
|
-
[
|
|
55
|
-
[
|
|
53
|
+
[L.Average]: 1.2,
|
|
54
|
+
[L.Fast]: 1.5,
|
|
55
|
+
[L.Fastest]: 2
|
|
56
56
|
}, $t = ({ chain: s, symbol: t }) => {
|
|
57
57
|
switch (s) {
|
|
58
58
|
case o.Bitcoin:
|
|
@@ -147,38 +147,38 @@ const Tt = "0x313ce567", nt = async ({ chain: s, to: t }) => {
|
|
|
147
147
|
"gmi"
|
|
148
148
|
), ne = (s) => s.filter(
|
|
149
149
|
(t) => !Et.test(t.toString()) && !t.toString().includes("undefined")
|
|
150
|
-
),
|
|
150
|
+
), Bt = ({
|
|
151
151
|
liquidityUnits: s,
|
|
152
152
|
poolUnits: t,
|
|
153
153
|
runeDepth: e
|
|
154
154
|
}) => {
|
|
155
|
-
const r =
|
|
155
|
+
const r = p(s), n = p(t), i = p(e), a = r.mul(i), c = n.mul(n).mul(2), u = n.mul(r).mul(2), l = r.mul(r), h = n.mul(n).mul(n);
|
|
156
156
|
return a.mul(c.sub(u).add(l)).div(h);
|
|
157
|
-
},
|
|
157
|
+
}, Ot = ({
|
|
158
158
|
liquidityUnits: s,
|
|
159
159
|
poolUnits: t,
|
|
160
160
|
assetDepth: e
|
|
161
161
|
}) => {
|
|
162
|
-
const r =
|
|
163
|
-
return h.div(
|
|
162
|
+
const r = p(s), n = p(t), i = p(e), a = r.mul(i), c = n.mul(n).mul(2), u = n.mul(r).mul(2), l = r.mul(r), h = a.mul(c.sub(u).add(l)), _ = n.mul(n).mul(n);
|
|
163
|
+
return h.div(_);
|
|
164
164
|
}, ie = ({
|
|
165
165
|
percent: s,
|
|
166
166
|
runeDepth: t,
|
|
167
167
|
liquidityUnits: e,
|
|
168
168
|
poolUnits: r
|
|
169
|
-
}) =>
|
|
169
|
+
}) => Bt({ runeDepth: t, liquidityUnits: e, poolUnits: r }).mul(s), oe = ({
|
|
170
170
|
percent: s,
|
|
171
171
|
assetDepth: t,
|
|
172
172
|
liquidityUnits: e,
|
|
173
173
|
poolUnits: r
|
|
174
|
-
}) =>
|
|
174
|
+
}) => Ot({ assetDepth: t, liquidityUnits: e, poolUnits: r }).mul(s), p = (s) => b.fromBigInt(BigInt(s), d.THOR), Vt = ({
|
|
175
175
|
liquidityUnits: s,
|
|
176
176
|
poolUnits: t,
|
|
177
177
|
runeDepth: e,
|
|
178
178
|
assetDepth: r
|
|
179
179
|
}) => ({
|
|
180
|
-
assetAmount:
|
|
181
|
-
runeAmount:
|
|
180
|
+
assetAmount: p(r).mul(s).div(t),
|
|
181
|
+
runeAmount: p(e).mul(s).div(t)
|
|
182
182
|
}), ae = ({
|
|
183
183
|
liquidityUnits: s,
|
|
184
184
|
poolUnits: t,
|
|
@@ -197,11 +197,11 @@ const Tt = "0x313ce567", nt = async ({ chain: s, to: t }) => {
|
|
|
197
197
|
runeAmount: n,
|
|
198
198
|
assetAmount: i
|
|
199
199
|
}) => {
|
|
200
|
-
const a = new
|
|
201
|
-
if (
|
|
202
|
-
return
|
|
203
|
-
const
|
|
204
|
-
return
|
|
200
|
+
const a = new b({ value: s, decimal: 8 }), c = new b({ value: e, decimal: 8 }), u = new b({ value: t, decimal: 8 }), l = new b({ value: n, decimal: 8 }), h = new b({ value: i, decimal: 8 }), _ = l.mul(c), v = h.mul(a), j = l.mul(h), mt = a.mul(c), pt = u.mul(_.add(v.add(j.mul(2)))), ft = _.add(v.add(mt.mul(2))), Q = pt.div(ft), H = p(r).add(Q);
|
|
201
|
+
if (Q.getBaseValue("number") === 0)
|
|
202
|
+
return H.div(u).getBaseValue("number");
|
|
203
|
+
const _t = u.add(H);
|
|
204
|
+
return H.div(_t).getBaseValue("number");
|
|
205
205
|
}, ue = ({
|
|
206
206
|
runeAmount: s,
|
|
207
207
|
assetAmount: t,
|
|
@@ -210,7 +210,7 @@ const Tt = "0x313ce567", nt = async ({ chain: s, to: t }) => {
|
|
|
210
210
|
}) => {
|
|
211
211
|
if (s === "0" || t === "0" || e === "0" || r === "0")
|
|
212
212
|
return 0;
|
|
213
|
-
const n =
|
|
213
|
+
const n = p(e), i = p(r), a = p(t), c = p(s), u = a.mul(n).sub(i.mul(c)), l = i.mul(c).add(n.mul(i));
|
|
214
214
|
return Math.abs(u.div(l).getBaseValue("number"));
|
|
215
215
|
}, Mt = ({
|
|
216
216
|
symbol: s,
|
|
@@ -218,29 +218,29 @@ const Tt = "0x313ce567", nt = async ({ chain: s, to: t }) => {
|
|
|
218
218
|
chain: e
|
|
219
219
|
}) => e === "ETH" && t !== "ETH" ? `${t}-${s.slice(-3)}` : s, le = (s, t) => {
|
|
220
220
|
switch (s) {
|
|
221
|
-
case
|
|
222
|
-
case
|
|
221
|
+
case g.LEAVE:
|
|
222
|
+
case g.BOND: {
|
|
223
223
|
const { address: e } = t;
|
|
224
224
|
return `${s}:${e}`;
|
|
225
225
|
}
|
|
226
|
-
case
|
|
226
|
+
case g.UNBOND: {
|
|
227
227
|
const { address: e, unbondAmount: r } = t;
|
|
228
228
|
return `${s}:${e}:${r * 10 ** 8}`;
|
|
229
229
|
}
|
|
230
|
-
case
|
|
230
|
+
case g.THORNAME_REGISTER: {
|
|
231
231
|
const { name: e, chain: r, address: n, owner: i } = t;
|
|
232
232
|
return `${s}:${e}:${r}:${n}${i ? `:${i}` : ""}`;
|
|
233
233
|
}
|
|
234
|
-
case
|
|
234
|
+
case g.DEPOSIT: {
|
|
235
235
|
const { chain: e, symbol: r, address: n, singleSide: i } = t;
|
|
236
236
|
return i ? `${s}:${e}/${r}::t:0` : `${s}:${e}.${r}:${n || ""}:t:0`;
|
|
237
237
|
}
|
|
238
|
-
case
|
|
238
|
+
case g.WITHDRAW: {
|
|
239
239
|
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 });
|
|
240
240
|
return `${s}:${e}${c ? "/" : "."}${l}:${i}${u}`;
|
|
241
241
|
}
|
|
242
|
-
case
|
|
243
|
-
case
|
|
242
|
+
case g.OPEN_LOAN:
|
|
243
|
+
case g.CLOSE_LOAN: {
|
|
244
244
|
const { asset: e, address: r } = t;
|
|
245
245
|
return `${s}:${e}:${r}`;
|
|
246
246
|
}
|
|
@@ -257,7 +257,7 @@ const Tt = "0x313ce567", nt = async ({ chain: s, to: t }) => {
|
|
|
257
257
|
const t = /^[a-zA-Z0-9+_-]+$/g;
|
|
258
258
|
return !!s.match(t);
|
|
259
259
|
}, me = ([s, t, e, r, n]) => `${s}'/${t}'/${e}'/${r}${typeof n != "number" ? "" : `/${n}`}`;
|
|
260
|
-
class
|
|
260
|
+
class X extends Error {
|
|
261
261
|
constructor(t, e, r) {
|
|
262
262
|
const n = t.status || t.status === 0 ? t.status : "", i = t.statusText || "", a = `${n} ${i}`.trim(), c = a ? `status code ${a}` : "an unknown error";
|
|
263
263
|
super(`Request failed with ${c}`), Object.defineProperty(this, "response", {
|
|
@@ -278,7 +278,7 @@ class Z extends Error {
|
|
|
278
278
|
}), this.name = "HTTPError", this.response = t, this.request = e, this.options = r;
|
|
279
279
|
}
|
|
280
280
|
}
|
|
281
|
-
class
|
|
281
|
+
class it extends Error {
|
|
282
282
|
constructor(t) {
|
|
283
283
|
super("Request timed out"), Object.defineProperty(this, "request", {
|
|
284
284
|
enumerable: !0,
|
|
@@ -292,21 +292,21 @@ const M = (s) => s !== null && typeof s == "object", V = (...s) => {
|
|
|
292
292
|
for (const t of s)
|
|
293
293
|
if ((!M(t) || Array.isArray(t)) && t !== void 0)
|
|
294
294
|
throw new TypeError("The `options` argument must be an object");
|
|
295
|
-
return
|
|
296
|
-
},
|
|
295
|
+
return J({}, ...s);
|
|
296
|
+
}, ot = (s = {}, t = {}) => {
|
|
297
297
|
const e = new globalThis.Headers(s), r = t instanceof globalThis.Headers, n = new globalThis.Headers(t);
|
|
298
298
|
for (const [i, a] of n.entries())
|
|
299
299
|
r && a === "undefined" || a === void 0 ? e.delete(i) : e.set(i, a);
|
|
300
300
|
return e;
|
|
301
|
-
},
|
|
301
|
+
}, J = (...s) => {
|
|
302
302
|
let t = {}, e = {};
|
|
303
303
|
for (const r of s)
|
|
304
304
|
if (Array.isArray(r))
|
|
305
305
|
Array.isArray(t) || (t = []), t = [...t, ...r];
|
|
306
306
|
else if (M(r)) {
|
|
307
307
|
for (let [n, i] of Object.entries(r))
|
|
308
|
-
M(i) && n in t && (i =
|
|
309
|
-
M(r.headers) && (e =
|
|
308
|
+
M(i) && n in t && (i = J(t[n], i)), t = { ...t, [n]: i };
|
|
309
|
+
M(r.headers) && (e = ot(e, r.headers), t.headers = e);
|
|
310
310
|
}
|
|
311
311
|
return t;
|
|
312
312
|
}, kt = (() => {
|
|
@@ -320,13 +320,13 @@ const M = (s) => s !== null && typeof s == "object", V = (...s) => {
|
|
|
320
320
|
return s = !0, "half";
|
|
321
321
|
}
|
|
322
322
|
}).headers.has("Content-Type")), s && !t;
|
|
323
|
-
})(), qt = typeof globalThis.AbortController == "function", xt = typeof globalThis.ReadableStream == "function", Pt = typeof globalThis.FormData == "function",
|
|
323
|
+
})(), qt = typeof globalThis.AbortController == "function", xt = typeof globalThis.ReadableStream == "function", Pt = typeof globalThis.FormData == "function", at = ["get", "post", "put", "patch", "head", "delete"], Nt = {
|
|
324
324
|
json: "application/json",
|
|
325
325
|
text: "text/*",
|
|
326
326
|
formData: "multipart/form-data",
|
|
327
327
|
arrayBuffer: "*/*",
|
|
328
328
|
blob: "*/*"
|
|
329
|
-
},
|
|
329
|
+
}, D = 2147483647, ct = Symbol("stop"), jt = {
|
|
330
330
|
json: !0,
|
|
331
331
|
parseJson: !0,
|
|
332
332
|
searchParams: !0,
|
|
@@ -337,7 +337,7 @@ const M = (s) => s !== null && typeof s == "object", V = (...s) => {
|
|
|
337
337
|
throwHttpErrors: !0,
|
|
338
338
|
onDownloadProgress: !0,
|
|
339
339
|
fetch: !0
|
|
340
|
-
},
|
|
340
|
+
}, Ht = {
|
|
341
341
|
method: !0,
|
|
342
342
|
headers: !0,
|
|
343
343
|
body: !0,
|
|
@@ -353,18 +353,18 @@ const M = (s) => s !== null && typeof s == "object", V = (...s) => {
|
|
|
353
353
|
window: !0,
|
|
354
354
|
dispatcher: !0,
|
|
355
355
|
duplex: !0
|
|
356
|
-
}, Lt = (s) =>
|
|
356
|
+
}, Lt = (s) => at.includes(s) ? s.toUpperCase() : s, Dt = ["get", "put", "head", "delete", "options", "trace"], Ut = [408, 413, 429, 500, 502, 503, 504], ut = [413, 429, 503], Z = {
|
|
357
357
|
limit: 2,
|
|
358
358
|
methods: Dt,
|
|
359
359
|
statusCodes: Ut,
|
|
360
|
-
afterStatusCodes:
|
|
360
|
+
afterStatusCodes: ut,
|
|
361
361
|
maxRetryAfter: Number.POSITIVE_INFINITY,
|
|
362
362
|
backoffLimit: Number.POSITIVE_INFINITY,
|
|
363
363
|
delay: (s) => 0.3 * 2 ** (s - 1) * 1e3
|
|
364
364
|
}, Ft = (s = {}) => {
|
|
365
365
|
if (typeof s == "number")
|
|
366
366
|
return {
|
|
367
|
-
...
|
|
367
|
+
...Z,
|
|
368
368
|
limit: s
|
|
369
369
|
};
|
|
370
370
|
if (s.methods && !Array.isArray(s.methods))
|
|
@@ -372,15 +372,15 @@ const M = (s) => s !== null && typeof s == "object", V = (...s) => {
|
|
|
372
372
|
if (s.statusCodes && !Array.isArray(s.statusCodes))
|
|
373
373
|
throw new Error("retry.statusCodes must be an array");
|
|
374
374
|
return {
|
|
375
|
-
...
|
|
375
|
+
...Z,
|
|
376
376
|
...s,
|
|
377
|
-
afterStatusCodes:
|
|
377
|
+
afterStatusCodes: ut
|
|
378
378
|
};
|
|
379
379
|
};
|
|
380
380
|
async function Wt(s, t, e, r) {
|
|
381
381
|
return new Promise((n, i) => {
|
|
382
382
|
const a = setTimeout(() => {
|
|
383
|
-
e && e.abort(), i(new
|
|
383
|
+
e && e.abort(), i(new it(s));
|
|
384
384
|
}, r.timeout);
|
|
385
385
|
r.fetch(s, t).then(n).catch(i).then(() => {
|
|
386
386
|
clearTimeout(a);
|
|
@@ -401,14 +401,14 @@ async function Gt(s, { signal: t }) {
|
|
|
401
401
|
const Yt = (s, t) => {
|
|
402
402
|
const e = {};
|
|
403
403
|
for (const r in t)
|
|
404
|
-
!(r in
|
|
404
|
+
!(r in Ht) && !(r in jt) && !(r in s) && (e[r] = t[r]);
|
|
405
405
|
return e;
|
|
406
406
|
};
|
|
407
|
-
class
|
|
407
|
+
class q {
|
|
408
408
|
static create(t, e) {
|
|
409
|
-
const r = new
|
|
410
|
-
if (typeof r._options.timeout == "number" && r._options.timeout >
|
|
411
|
-
throw new RangeError(`The \`timeout\` option cannot be greater than ${
|
|
409
|
+
const r = new q(t, e), n = async () => {
|
|
410
|
+
if (typeof r._options.timeout == "number" && r._options.timeout > D)
|
|
411
|
+
throw new RangeError(`The \`timeout\` option cannot be greater than ${D}`);
|
|
412
412
|
await Promise.resolve();
|
|
413
413
|
let c = await r._fetch();
|
|
414
414
|
for (const u of r._options.hooks.afterResponse) {
|
|
@@ -416,7 +416,7 @@ class x {
|
|
|
416
416
|
l instanceof globalThis.Response && (c = l);
|
|
417
417
|
}
|
|
418
418
|
if (r._decorateResponse(c), !c.ok && r._options.throwHttpErrors) {
|
|
419
|
-
let u = new
|
|
419
|
+
let u = new X(c, r.request, r._options);
|
|
420
420
|
for (const l of r._options.hooks.beforeError)
|
|
421
421
|
u = await l(u);
|
|
422
422
|
throw u;
|
|
@@ -475,8 +475,8 @@ class x {
|
|
|
475
475
|
// TODO: credentials can be removed when the spec change is implemented in all browsers. Context: https://www.chromestatus.com/feature/4539473312350208
|
|
476
476
|
credentials: this._input.credentials || "same-origin",
|
|
477
477
|
...e,
|
|
478
|
-
headers:
|
|
479
|
-
hooks:
|
|
478
|
+
headers: ot(this._input.headers, e.headers),
|
|
479
|
+
hooks: J({
|
|
480
480
|
beforeRequest: [],
|
|
481
481
|
beforeRetry: [],
|
|
482
482
|
beforeError: [],
|
|
@@ -512,8 +512,8 @@ class x {
|
|
|
512
512
|
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 }));
|
|
513
513
|
}
|
|
514
514
|
_calculateRetryDelay(t) {
|
|
515
|
-
if (this._retryCount++, this._retryCount < this._options.retry.limit && !(t instanceof
|
|
516
|
-
if (t instanceof
|
|
515
|
+
if (this._retryCount++, this._retryCount < this._options.retry.limit && !(t instanceof it)) {
|
|
516
|
+
if (t instanceof X) {
|
|
517
517
|
if (!this._options.retry.statusCodes.includes(t.response.status))
|
|
518
518
|
return 0;
|
|
519
519
|
const r = t.response.headers.get("Retry-After");
|
|
@@ -536,7 +536,7 @@ class x {
|
|
|
536
536
|
try {
|
|
537
537
|
return await t();
|
|
538
538
|
} catch (e) {
|
|
539
|
-
const r = Math.min(this._calculateRetryDelay(e),
|
|
539
|
+
const r = Math.min(this._calculateRetryDelay(e), D);
|
|
540
540
|
if (r !== 0 && this._retryCount > 0) {
|
|
541
541
|
await Gt(r, { signal: this._options.signal });
|
|
542
542
|
for (const n of this._options.hooks.beforeRetry)
|
|
@@ -545,7 +545,7 @@ class x {
|
|
|
545
545
|
options: this._options,
|
|
546
546
|
error: e,
|
|
547
547
|
retryCount: this._retryCount
|
|
548
|
-
}) ===
|
|
548
|
+
}) === ct)
|
|
549
549
|
return;
|
|
550
550
|
return this._retry(t);
|
|
551
551
|
}
|
|
@@ -600,26 +600,26 @@ class x {
|
|
|
600
600
|
}
|
|
601
601
|
}
|
|
602
602
|
/*! MIT License © Sindre Sorhus */
|
|
603
|
-
const
|
|
604
|
-
const t = (e, r) =>
|
|
605
|
-
for (const e of
|
|
606
|
-
t[e] = (r, n) =>
|
|
607
|
-
return t.create = (e) =>
|
|
608
|
-
}, zt =
|
|
609
|
-
get: (s, t) =>
|
|
610
|
-
post: (s, t) =>
|
|
611
|
-
},
|
|
603
|
+
const F = (s) => {
|
|
604
|
+
const t = (e, r) => q.create(e, V(s, r));
|
|
605
|
+
for (const e of at)
|
|
606
|
+
t[e] = (r, n) => q.create(r, V(s, n, { method: e }));
|
|
607
|
+
return t.create = (e) => F(V(e)), t.extend = (e) => F(V(s, e)), t.stop = ct, t;
|
|
608
|
+
}, zt = F(), Jt = zt, Kt = typeof window < "u" ? {} : { referrer: "https://sk.thorswap.net", referer: "https://sk.thorswap.net" }, tt = Jt.create({ headers: Kt }), Qt = {
|
|
609
|
+
get: (s, t) => tt.get(s, t).json(),
|
|
610
|
+
post: (s, t) => tt.post(s, t).json()
|
|
611
|
+
}, et = Object.values(o), Xt = (s = "") => {
|
|
612
612
|
const t = s.toUpperCase(), [e] = t.split(".");
|
|
613
|
-
if (
|
|
613
|
+
if (et.includes(e))
|
|
614
614
|
return !0;
|
|
615
615
|
const [r] = t.split("/");
|
|
616
|
-
if (
|
|
616
|
+
if (et.includes(r))
|
|
617
617
|
return !0;
|
|
618
618
|
throw new Error(
|
|
619
619
|
`Invalid identifier: ${s}. Expected format: <Chain>.<Ticker> or <Chain>.<Ticker>-<ContractAddress>`
|
|
620
620
|
);
|
|
621
|
-
}, I = 8,
|
|
622
|
-
function
|
|
621
|
+
}, I = 8, S = (s) => 10n ** BigInt(s), R = (s) => Math.log10(parseFloat(s.toString()));
|
|
622
|
+
function x({
|
|
623
623
|
value: s,
|
|
624
624
|
bigIntDecimal: t = I,
|
|
625
625
|
decimal: e = I
|
|
@@ -635,27 +635,27 @@ function P({
|
|
|
635
635
|
""
|
|
636
636
|
);
|
|
637
637
|
}
|
|
638
|
-
var A, $,
|
|
639
|
-
const
|
|
638
|
+
var A, $, P, lt, N, ht, B, W, T, C, O, G;
|
|
639
|
+
const K = class K {
|
|
640
640
|
constructor(t) {
|
|
641
|
-
|
|
642
|
-
|
|
643
|
-
|
|
644
|
-
|
|
645
|
-
|
|
646
|
-
|
|
647
|
-
|
|
648
|
-
|
|
649
|
-
|
|
650
|
-
const e =
|
|
651
|
-
this.decimal = typeof t == "object" ? t.decimal : void 0, this.decimalMultiplier =
|
|
652
|
-
Math.max(m(this,
|
|
653
|
-
), m(this,
|
|
641
|
+
y(this, A);
|
|
642
|
+
y(this, P);
|
|
643
|
+
y(this, N);
|
|
644
|
+
y(this, B);
|
|
645
|
+
y(this, T);
|
|
646
|
+
y(this, O);
|
|
647
|
+
f(this, "decimalMultiplier", 10n ** 8n);
|
|
648
|
+
f(this, "bigIntValue", 0n);
|
|
649
|
+
f(this, "decimal");
|
|
650
|
+
const e = U(t);
|
|
651
|
+
this.decimal = typeof t == "object" ? t.decimal : void 0, this.decimalMultiplier = S(
|
|
652
|
+
Math.max(m(this, O, G).call(this, m(this, T, C).call(this, e)), this.decimal || 0)
|
|
653
|
+
), m(this, P, lt).call(this, e);
|
|
654
654
|
}
|
|
655
655
|
static fromBigInt(t, e) {
|
|
656
|
-
return new
|
|
656
|
+
return new K({
|
|
657
657
|
decimal: e,
|
|
658
|
-
value:
|
|
658
|
+
value: x({ value: t, bigIntDecimal: e, decimal: e })
|
|
659
659
|
});
|
|
660
660
|
}
|
|
661
661
|
static shiftDecimals({
|
|
@@ -664,7 +664,7 @@ const j = class j {
|
|
|
664
664
|
to: r
|
|
665
665
|
}) {
|
|
666
666
|
return this.fromBigInt(
|
|
667
|
-
|
|
667
|
+
t.getBaseValue("bigint") * S(r) / S(e),
|
|
668
668
|
r
|
|
669
669
|
);
|
|
670
670
|
}
|
|
@@ -719,7 +719,7 @@ const j = class j {
|
|
|
719
719
|
getValue(t) {
|
|
720
720
|
const e = this.formatBigIntToSafeValue(
|
|
721
721
|
this.bigIntValue,
|
|
722
|
-
this.decimal ||
|
|
722
|
+
this.decimal || R(this.decimalMultiplier)
|
|
723
723
|
);
|
|
724
724
|
switch (t) {
|
|
725
725
|
case "number":
|
|
@@ -731,7 +731,7 @@ const j = class j {
|
|
|
731
731
|
}
|
|
732
732
|
}
|
|
733
733
|
getBaseValue(t) {
|
|
734
|
-
const e = this.decimalMultiplier /
|
|
734
|
+
const e = this.decimalMultiplier / S(this.decimal || d.THOR), r = this.bigIntValue / e;
|
|
735
735
|
switch (t) {
|
|
736
736
|
case "number":
|
|
737
737
|
return Number(r);
|
|
@@ -744,13 +744,13 @@ const j = class j {
|
|
|
744
744
|
getBigIntValue(t, e) {
|
|
745
745
|
if (!e && typeof t == "object")
|
|
746
746
|
return t.bigIntValue;
|
|
747
|
-
const r =
|
|
748
|
-
return n === "0" || n === "undefined" ? 0n : m(this,
|
|
747
|
+
const r = U(t), n = m(this, T, C).call(this, r);
|
|
748
|
+
return n === "0" || n === "undefined" ? 0n : m(this, B, W).call(this, n, e);
|
|
749
749
|
}
|
|
750
750
|
formatBigIntToSafeValue(t, e) {
|
|
751
751
|
const r = e || this.decimal || I, 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;
|
|
755
755
|
let h = u.slice(-n);
|
|
756
756
|
return parseInt(h[r]) >= 5 ? h = `${h.substring(0, r - 1)}${(parseInt(h[r - 1]) + 1).toString()}` : h = h.substring(0, r), `${i ? "-" : ""}${u.slice(
|
|
@@ -794,7 +794,7 @@ const j = class j {
|
|
|
794
794
|
}
|
|
795
795
|
};
|
|
796
796
|
A = new WeakSet(), $ = function(t, ...e) {
|
|
797
|
-
const r = m(this,
|
|
797
|
+
const r = m(this, N, ht).call(this, this, ...e), n = S(r), i = e.reduce(
|
|
798
798
|
(c, u) => {
|
|
799
799
|
const l = this.getBigIntValue(u, r);
|
|
800
800
|
switch (t) {
|
|
@@ -815,62 +815,62 @@ A = new WeakSet(), $ = function(t, ...e) {
|
|
|
815
815
|
},
|
|
816
816
|
//normalize is to precision multiplier base
|
|
817
817
|
this.bigIntValue * n / this.decimalMultiplier
|
|
818
|
-
), a =
|
|
818
|
+
), a = x({
|
|
819
819
|
bigIntDecimal: r,
|
|
820
|
-
decimal: Math.max(r,
|
|
820
|
+
decimal: Math.max(r, R(this.decimalMultiplier)),
|
|
821
821
|
value: i
|
|
822
822
|
});
|
|
823
823
|
return new this.constructor({ decimal: this.decimal, value: a, identifier: this.toString() });
|
|
824
|
-
},
|
|
824
|
+
}, P = new WeakSet(), lt = function(t) {
|
|
825
825
|
const e = m(this, T, C).call(this, t) || "0";
|
|
826
|
-
this.bigIntValue = m(this,
|
|
827
|
-
},
|
|
826
|
+
this.bigIntValue = m(this, B, W).call(this, e);
|
|
827
|
+
}, N = new WeakSet(), ht = function(...t) {
|
|
828
828
|
const e = t.map(
|
|
829
|
-
(r) => typeof r == "object" ? r.decimal ||
|
|
829
|
+
(r) => typeof r == "object" ? r.decimal || R(r.decimalMultiplier) : m(this, O, G).call(this, m(this, T, C).call(this, r))
|
|
830
830
|
).filter(Boolean);
|
|
831
831
|
return Math.max(...e, I);
|
|
832
|
-
},
|
|
833
|
-
const r = e ?
|
|
832
|
+
}, B = new WeakSet(), W = function(t, e) {
|
|
833
|
+
const r = e ? S(e) : this.decimalMultiplier, n = R(r), [i = "", a = ""] = t.split(".");
|
|
834
834
|
return BigInt(`${i}${a.padEnd(n, "0")}`);
|
|
835
835
|
}, T = new WeakSet(), C = function(t) {
|
|
836
836
|
const r = `${typeof t == "number" ? Number(t).toLocaleString("fullwide", {
|
|
837
837
|
useGrouping: !1,
|
|
838
838
|
maximumFractionDigits: 20
|
|
839
|
-
}) :
|
|
839
|
+
}) : U(t)}`.replaceAll(",", ".").split(".");
|
|
840
840
|
return r.length > 1 ? `${r.slice(0, -1).join("")}.${r.at(-1)}` : r[0];
|
|
841
|
-
},
|
|
841
|
+
}, O = new WeakSet(), G = function(t) {
|
|
842
842
|
var r;
|
|
843
843
|
const e = ((r = t.split(".")[1]) == null ? void 0 : r.length) || 0;
|
|
844
844
|
return Math.max(e, I);
|
|
845
845
|
};
|
|
846
|
-
let E =
|
|
847
|
-
function
|
|
846
|
+
let E = K;
|
|
847
|
+
function U(s) {
|
|
848
848
|
return typeof s == "object" ? "getValue" in s ? s.getValue("string") : s.value : s;
|
|
849
849
|
}
|
|
850
|
-
const k = (s, t) => typeof s == "bigint" ?
|
|
851
|
-
let
|
|
852
|
-
const
|
|
853
|
-
if (!
|
|
850
|
+
const k = (s, t) => typeof s == "bigint" ? x({ value: s, bigIntDecimal: t, decimal: t }) : s;
|
|
851
|
+
let Y;
|
|
852
|
+
const rt = (s) => {
|
|
853
|
+
if (!Y)
|
|
854
854
|
throw new Error("Static assets not loaded, call await AssetValue.loadStaticAssets() first");
|
|
855
|
-
return
|
|
855
|
+
return Y.get(s.toUpperCase()) || { decimal: d.THOR, identifier: "" };
|
|
856
856
|
}, st = async (s, t = 0) => {
|
|
857
857
|
Xt(s);
|
|
858
|
-
const e = await
|
|
859
|
-
return new
|
|
858
|
+
const e = await Rt(z(s)), r = k(t, e);
|
|
859
|
+
return new w({ decimal: e, value: r, identifier: s });
|
|
860
860
|
};
|
|
861
|
-
class
|
|
861
|
+
class w extends E {
|
|
862
862
|
constructor(e) {
|
|
863
863
|
super(
|
|
864
864
|
e.value instanceof E ? e.value : { decimal: e.decimal, value: e.value }
|
|
865
865
|
);
|
|
866
|
-
|
|
867
|
-
|
|
868
|
-
|
|
869
|
-
|
|
870
|
-
|
|
871
|
-
|
|
872
|
-
|
|
873
|
-
const r = "identifier" in e ? e.identifier : `${e.chain}.${e.symbol}`, n =
|
|
866
|
+
f(this, "address");
|
|
867
|
+
f(this, "chain");
|
|
868
|
+
f(this, "isSynthetic", !1);
|
|
869
|
+
f(this, "isGasAsset", !1);
|
|
870
|
+
f(this, "symbol");
|
|
871
|
+
f(this, "ticker");
|
|
872
|
+
f(this, "type");
|
|
873
|
+
const r = "identifier" in e ? e.identifier : `${e.chain}.${e.symbol}`, n = z(r);
|
|
874
874
|
this.type = It(n), this.chain = n.chain, this.ticker = n.ticker, this.symbol = n.symbol, this.address = n.address, this.isSynthetic = n.isSynthetic, this.isGasAsset = n.isGasAsset;
|
|
875
875
|
}
|
|
876
876
|
get assetValue() {
|
|
@@ -890,33 +890,21 @@ class _ extends E {
|
|
|
890
890
|
return st(e, r);
|
|
891
891
|
}
|
|
892
892
|
static fromStringSync(e, r = 0) {
|
|
893
|
-
const { isSynthetic: n } =
|
|
893
|
+
const { isSynthetic: n } = z(e), { decimal: i, identifier: a } = rt(
|
|
894
894
|
e
|
|
895
895
|
), c = k(r, i);
|
|
896
|
-
return a ? new
|
|
896
|
+
return a ? new w({ decimal: i, identifier: a, value: c }) : n ? new w({ decimal: 8, identifier: e, value: c }) : void 0;
|
|
897
897
|
}
|
|
898
898
|
static async fromIdentifier(e, r = 0) {
|
|
899
899
|
return st(e, r);
|
|
900
900
|
}
|
|
901
901
|
static fromIdentifierSync(e, r = 0) {
|
|
902
|
-
const { decimal: n, identifier: i } =
|
|
903
|
-
return new
|
|
902
|
+
const { decimal: n, identifier: i } = rt(e), a = k(r, n);
|
|
903
|
+
return new w({ decimal: n, identifier: i, value: a });
|
|
904
904
|
}
|
|
905
905
|
static fromChainOrSignature(e, r = 0) {
|
|
906
906
|
const { decimal: n, identifier: i } = Ct(e), a = k(r, n);
|
|
907
|
-
return new
|
|
908
|
-
}
|
|
909
|
-
static async fromTCQuote(e, r = 0) {
|
|
910
|
-
const n = await it(q(e)), i = this.shiftDecimals({ value: r, from: d.THOR, to: n });
|
|
911
|
-
return new _({ value: i, identifier: e, decimal: n });
|
|
912
|
-
}
|
|
913
|
-
static fromTCQuoteStatic(e, r = 0) {
|
|
914
|
-
const n = G(e), i = this.shiftDecimals({
|
|
915
|
-
value: r,
|
|
916
|
-
from: d.THOR,
|
|
917
|
-
to: n.decimal
|
|
918
|
-
});
|
|
919
|
-
return new _({ ...n, value: i });
|
|
907
|
+
return new w({ value: a, decimal: n, identifier: i });
|
|
920
908
|
}
|
|
921
909
|
static async loadStaticAssets() {
|
|
922
910
|
return new Promise(
|
|
@@ -929,10 +917,10 @@ class _ extends E {
|
|
|
929
917
|
NativeList: i,
|
|
930
918
|
...a
|
|
931
919
|
} = await import("@swapkit/tokens");
|
|
932
|
-
|
|
933
|
-
(u, { tokens: l }) => (l.forEach(({ identifier: h, chain:
|
|
934
|
-
const
|
|
935
|
-
u.set(h, { identifier: h, decimal:
|
|
920
|
+
Y = [i, ...Object.values(a)].reduce(
|
|
921
|
+
(u, { tokens: l }) => (l.forEach(({ identifier: h, chain: _, ...v }) => {
|
|
922
|
+
const j = "decimals" in v ? v.decimals : d[_];
|
|
923
|
+
u.set(h, { identifier: h, decimal: j });
|
|
936
924
|
}), u),
|
|
937
925
|
/* @__PURE__ */ new Map()
|
|
938
926
|
), e({ ok: !0 });
|
|
@@ -947,8 +935,8 @@ class _ extends E {
|
|
|
947
935
|
);
|
|
948
936
|
}
|
|
949
937
|
}
|
|
950
|
-
const
|
|
951
|
-
const t =
|
|
938
|
+
const pe = (s) => {
|
|
939
|
+
const t = w.fromChainOrSignature(s);
|
|
952
940
|
switch (s) {
|
|
953
941
|
case o.Bitcoin:
|
|
954
942
|
case o.Litecoin:
|
|
@@ -965,7 +953,7 @@ const fe = (s) => {
|
|
|
965
953
|
default:
|
|
966
954
|
return t.add(1);
|
|
967
955
|
}
|
|
968
|
-
},
|
|
956
|
+
}, z = (s) => {
|
|
969
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("-");
|
|
970
958
|
return {
|
|
971
959
|
address: u == null ? void 0 : u.toLowerCase(),
|
|
@@ -1032,44 +1020,44 @@ const fe = (s) => {
|
|
|
1032
1020
|
*/
|
|
1033
1021
|
helpers_number_different_decimals: 99101
|
|
1034
1022
|
};
|
|
1035
|
-
class
|
|
1023
|
+
class dt extends Error {
|
|
1036
1024
|
constructor(t, e) {
|
|
1037
|
-
console.error(e), super(t, { cause: { code: Zt[t], message: t } }), Object.setPrototypeOf(this,
|
|
1025
|
+
console.error(e), super(t, { cause: { code: Zt[t], message: t } }), Object.setPrototypeOf(this, dt.prototype);
|
|
1038
1026
|
}
|
|
1039
1027
|
}
|
|
1040
|
-
class
|
|
1028
|
+
class b extends E {
|
|
1041
1029
|
eq(t) {
|
|
1042
1030
|
return this.eqValue(t);
|
|
1043
1031
|
}
|
|
1044
1032
|
static fromBigInt(t, e) {
|
|
1045
|
-
return new
|
|
1033
|
+
return new b({
|
|
1046
1034
|
decimal: e,
|
|
1047
|
-
value:
|
|
1035
|
+
value: x({ value: t, bigIntDecimal: e, decimal: e })
|
|
1048
1036
|
});
|
|
1049
1037
|
}
|
|
1050
1038
|
}
|
|
1051
1039
|
export {
|
|
1052
|
-
|
|
1040
|
+
w as AssetValue,
|
|
1053
1041
|
E as BigIntArithmetics,
|
|
1054
1042
|
Qt as RequestClient,
|
|
1055
|
-
|
|
1056
|
-
|
|
1043
|
+
dt as SwapKitError,
|
|
1044
|
+
b as SwapKitNumber,
|
|
1057
1045
|
se as assetFromString,
|
|
1058
1046
|
me as derivationPathToString,
|
|
1059
1047
|
ne as filterAssets,
|
|
1060
|
-
|
|
1048
|
+
x as formatBigIntToSafeValue,
|
|
1061
1049
|
re as gasFeeMultiplier,
|
|
1062
1050
|
It as getAssetType,
|
|
1063
|
-
|
|
1051
|
+
Ot as getAsymmetricAssetShare,
|
|
1064
1052
|
oe as getAsymmetricAssetWithdrawAmount,
|
|
1065
|
-
|
|
1053
|
+
Bt as getAsymmetricRuneShare,
|
|
1066
1054
|
ie as getAsymmetricRuneWithdrawAmount,
|
|
1067
1055
|
Ct as getCommonAssetInfo,
|
|
1068
|
-
|
|
1056
|
+
Rt as getDecimal,
|
|
1069
1057
|
ce as getEstimatedPoolShare,
|
|
1070
1058
|
ue as getLiquiditySlippage,
|
|
1071
1059
|
le as getMemoFor,
|
|
1072
|
-
|
|
1060
|
+
pe as getMinAmountByChain,
|
|
1073
1061
|
Vt as getSymmetricPoolShare,
|
|
1074
1062
|
ae as getSymmetricWithdraw,
|
|
1075
1063
|
he as getTHORNameCost,
|
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.18",
|
|
46
46
|
"scripts": {
|
|
47
47
|
"build": "vite build",
|
|
48
48
|
"clean": "rm -rf dist vite.config.ts.* .turbo node_modules",
|
|
@@ -53,12 +53,12 @@ describe('SwapKitNumber', () => {
|
|
|
53
53
|
|
|
54
54
|
const shiftedSkNumber = SwapKitNumber.shiftDecimals({
|
|
55
55
|
value: skNumber,
|
|
56
|
-
from:
|
|
57
|
-
to:
|
|
56
|
+
from: 8,
|
|
57
|
+
to: 6,
|
|
58
58
|
});
|
|
59
59
|
|
|
60
|
-
expect(shiftedSkNumber.getValue('string')).toBe('
|
|
61
|
-
expect(shiftedSkNumber.getBaseValue('bigint')).toBe(
|
|
60
|
+
expect(shiftedSkNumber.getValue('string')).toBe('1');
|
|
61
|
+
expect(shiftedSkNumber.getBaseValue('bigint')).toBe(1000000n);
|
|
62
62
|
});
|
|
63
63
|
|
|
64
64
|
test('shifts down and rounds down number', () => {
|
|
@@ -75,6 +75,19 @@ describe('SwapKitNumber', () => {
|
|
|
75
75
|
expect(shiftedSkNumber.getValue('string')).toBe('2.123456');
|
|
76
76
|
expect(shiftedSkNumber.getBaseValue('bigint')).toBe(2123456n);
|
|
77
77
|
});
|
|
78
|
+
|
|
79
|
+
test('shift eth from 18 to 8', () => {
|
|
80
|
+
const skNumber = new SwapKitNumber({ value: '0.2', decimal: 18 });
|
|
81
|
+
|
|
82
|
+
const shiftedSkNumber = SwapKitNumber.shiftDecimals({
|
|
83
|
+
value: skNumber,
|
|
84
|
+
from: 18,
|
|
85
|
+
to: 8,
|
|
86
|
+
});
|
|
87
|
+
|
|
88
|
+
expect(shiftedSkNumber.getValue('string')).toBe('0.2');
|
|
89
|
+
expect(shiftedSkNumber.getBaseValue('bigint')).toBe(20000000n);
|
|
90
|
+
});
|
|
78
91
|
});
|
|
79
92
|
|
|
80
93
|
describe('getValue', () => {
|
|
@@ -155,24 +155,6 @@ export class AssetValue extends BigIntArithmetics {
|
|
|
155
155
|
return new AssetValue({ value: parsedValue, decimal, identifier });
|
|
156
156
|
}
|
|
157
157
|
|
|
158
|
-
static async fromTCQuote(identifier: TCTokenNames, value: NumberPrimitives = 0) {
|
|
159
|
-
const decimal = await getDecimal(getAssetInfo(identifier));
|
|
160
|
-
const shiftedValue = this.shiftDecimals({ value, from: BaseDecimal.THOR, to: decimal });
|
|
161
|
-
|
|
162
|
-
return new AssetValue({ value: shiftedValue, identifier, decimal });
|
|
163
|
-
}
|
|
164
|
-
|
|
165
|
-
static fromTCQuoteStatic(identifier: TCTokenNames, value: NumberPrimitives = 0) {
|
|
166
|
-
const tokenInfo = getStaticToken(identifier);
|
|
167
|
-
const shiftedValue = this.shiftDecimals({
|
|
168
|
-
value,
|
|
169
|
-
from: BaseDecimal.THOR,
|
|
170
|
-
to: tokenInfo.decimal,
|
|
171
|
-
});
|
|
172
|
-
|
|
173
|
-
return new AssetValue({ ...tokenInfo, value: shiftedValue });
|
|
174
|
-
}
|
|
175
|
-
|
|
176
158
|
static async loadStaticAssets() {
|
|
177
159
|
return new Promise<{ ok: true } | { ok: false; message: string; error: any }>(
|
|
178
160
|
async (resolve, reject) => {
|
|
@@ -71,12 +71,12 @@ export class BigIntArithmetics {
|
|
|
71
71
|
from,
|
|
72
72
|
to,
|
|
73
73
|
}: {
|
|
74
|
-
value:
|
|
74
|
+
value: InstanceType<typeof SwapKitNumber>;
|
|
75
75
|
from: number;
|
|
76
76
|
to: number;
|
|
77
77
|
}) {
|
|
78
78
|
return this.fromBigInt(
|
|
79
|
-
(
|
|
79
|
+
(value.getBaseValue('bigint') * toMultiplier(to)) / toMultiplier(from),
|
|
80
80
|
to,
|
|
81
81
|
);
|
|
82
82
|
}
|
|
@@ -111,7 +111,7 @@ export class BigIntArithmetics {
|
|
|
111
111
|
return this.getBaseValue('bigint') as bigint;
|
|
112
112
|
}
|
|
113
113
|
|
|
114
|
-
set(value: SKBigIntParams) {
|
|
114
|
+
set(value: SKBigIntParams): this {
|
|
115
115
|
// @ts-expect-error False positive
|
|
116
116
|
return new this.constructor({ decimal: this.decimal, value, identifier: this.toString() });
|
|
117
117
|
}
|