@swapkit/helpers 1.0.0-rc.16 → 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 +177 -187
- package/package.json +1 -1
- package/src/helpers/liquidity.ts +12 -10
- package/src/modules/__tests__/swapKitNumber.test.ts +17 -4
- package/src/modules/assetValue.ts +0 -18
- package/src/modules/bigIntArithmetics.ts +4 -4
package/dist/index.cjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";var Tt=Object.create;var j=Object.defineProperty;var St=Object.getOwnPropertyDescriptor;var vt=Object.getOwnPropertyNames;var Rt=Object.getPrototypeOf,$t=Object.prototype.hasOwnProperty;var It=(r,t,e)=>t in r?j(r,t,{enumerable:!0,configurable:!0,writable:!0,value:e}):r[t]=e;var Bt=(r,t,e,s)=>{if(t&&typeof t=="object"||typeof t=="function")for(let n of vt(t))!$t.call(r,n)&&n!==e&&j(r,n,{get:()=>t[n],enumerable:!(s=St(t,n))||s.enumerable});return r};var Et=(r,t,e)=>(e=r!=null?Tt(Rt(r)):{},Bt(t||!r||!r.__esModule?j(e,"default",{value:r,enumerable:!0}):e,r));var p=(r,t,e)=>(It(r,typeof t!="symbol"?t+"":t,e),e),Ot=(r,t,e)=>{if(!t.has(r))throw TypeError("Cannot "+e)};var _=(r,t,e)=>{if(t.has(r))throw TypeError("Cannot add the same private member more than once");t instanceof WeakSet?t.add(r):t.set(r,e)};var m=(r,t,e)=>(Ot(r,t,"access private method"),e);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const i=require("@swapkit/types"),Mt="0x313ce567",nt=async({chain:r,to:t})=>{try{const{result:e}=await gt.post(i.ChainToRPC[r],{headers:{accept:"*/*","content-type":"application/json","cache-control":"no-cache"},body:JSON.stringify({id:44,jsonrpc:"2.0",method:"eth_call",params:[{to:t.toLowerCase(),data:Mt},"latest"]})});return parseInt(BigInt(e).toString())}catch(e){return console.error(e),i.BaseDecimal[r]}},Vt=async r=>{if(r===i.Chain.Ethereum)return i.BaseDecimal.ETH;const[,t]=r.split("-");return t!=null&&t.startsWith("0x")?nt({chain:i.Chain.Ethereum,to:t}):i.BaseDecimal.ETH},qt=async r=>{const[,t]=r.split("-");return t!=null&&t.startsWith("0x")?nt({chain:i.Chain.Avalanche,to:t.toLowerCase()}):i.BaseDecimal.AVAX},kt=async r=>(r===i.Chain.BinanceSmartChain,i.BaseDecimal.BSC),z=async({chain:r,symbol:t})=>{switch(r){case i.Chain.Ethereum:return Vt(t);case i.Chain.Avalanche:return qt(t);case i.Chain.BinanceSmartChain:return kt(t);default:return i.BaseDecimal[r]}},Pt={[i.FeeOption.Average]:1.2,[i.FeeOption.Fast]:1.5,[i.FeeOption.Fastest]:2},it=({chain:r,symbol:t})=>{switch(r){case i.Chain.Bitcoin:case i.Chain.BitcoinCash:case i.Chain.Litecoin:case i.Chain.Dogecoin:case i.Chain.Binance:case i.Chain.Ethereum:case i.Chain.Avalanche:return t===r;case i.Chain.Arbitrum:case i.Chain.Optimism:return t==="ETH";case i.Chain.Maya:return t==="CACAO";case i.Chain.Kujira:return t==="KUJI";case i.Chain.Cosmos:return t==="ATOM";case i.Chain.Polygon:return t==="MATIC";case i.Chain.BinanceSmartChain:return t==="BNB";case i.Chain.THORChain:return t==="RUNE"}},at=r=>{switch(r){case"ETH.THOR":return{identifier:"ETH.THOR-0xa5f2211b9b8170f694421f2046281775e8468044",decimal:18};case"ETH.vTHOR":return{identifier:"ETH.vTHOR-0x815c23eca83261b6ec689b60cc4a58b54bc24d8d",decimal:18};case i.Chain.Cosmos:return{identifier:"GAIA.ATOM",decimal:i.BaseDecimal[r]};case i.Chain.THORChain:return{identifier:"THOR.RUNE",decimal:i.BaseDecimal[r]};case i.Chain.BinanceSmartChain:return{identifier:"BSC.BNB",decimal:i.BaseDecimal[r]};case i.Chain.Maya:return{identifier:"MAYA.CACAO",decimal:i.BaseDecimal.MAYA};case"MAYA.MAYA":return{identifier:"MAYA.MAYA",decimal:4};case i.Chain.Kujira:case i.Chain.Arbitrum:case i.Chain.Optimism:case i.Chain.BitcoinCash:case i.Chain.Litecoin:case i.Chain.Dogecoin:case i.Chain.Binance:case i.Chain.Avalanche:case i.Chain.Polygon:case i.Chain.Bitcoin:case i.Chain.Ethereum:return{identifier:`${r}.${r}`,decimal:i.BaseDecimal[r]}}},ot=({chain:r,symbol:t})=>{if(t.includes("/"))return"Synth";switch(r){case i.Chain.Bitcoin:case i.Chain.BitcoinCash:case i.Chain.Dogecoin:case i.Chain.Litecoin:case i.Chain.Maya:case i.Chain.THORChain:return"Native";case i.Chain.Cosmos:return t==="ATOM"?"Native":i.Chain.Cosmos;case i.Chain.Kujira:return t===i.Chain.Kujira?"Native":i.Chain.Kujira;case i.Chain.Binance:return t===i.Chain.Binance?"Native":"BEP2";case i.Chain.BinanceSmartChain:return t===i.Chain.Binance?"Native":"BEP20";case i.Chain.Ethereum:return t===i.Chain.Ethereum?"Native":"ERC20";case i.Chain.Avalanche:return t===i.Chain.Avalanche?"Native":i.Chain.Avalanche;case i.Chain.Polygon:return t===i.Chain.Polygon?"Native":"POLYGON";case i.Chain.Arbitrum:return[i.Chain.Ethereum,i.Chain.Arbitrum].includes(t)?"Native":"ARBITRUM";case i.Chain.Optimism:return[i.Chain.Ethereum,i.Chain.Optimism].includes(t)?"Native":"OPTIMISM"}},xt=r=>{var o;const[t,...e]=r.split("."),s=r.includes("/"),n=e.join("."),a=(o=n==null?void 0:n.split("-"))==null?void 0:o[0];return{chain:t,symbol:n,ticker:a,synth:s}},Dt=new RegExp(/(.)\1{6}|\.ORG|\.NET|\.FINANCE|\.COM|WWW|HTTP|\\\\|\/\/|[\s$%:[\]]/,"gmi"),Nt=r=>r.filter(t=>!Dt.test(t.toString())&&!t.toString().includes("undefined")),ct=({liquidityUnits:r,poolUnits:t,runeDepth:e})=>{const s=d(r),n=d(t),a=d(e),o=s.mul(a),c=n.mul(n).mul(2),u=n.mul(s).mul(2),l=s.mul(s),h=n.mul(n).mul(n);return o.mul(c.sub(u).add(l)).div(h)},ut=({liquidityUnits:r,poolUnits:t,assetDepth:e})=>{const s=d(r),n=d(t),a=d(e),o=s.mul(a),c=n.mul(n).mul(2),u=n.mul(s).mul(2),l=s.mul(s),h=o.mul(c.sub(u).add(l)),g=n.mul(n).mul(n);return h.div(g)},Ht=({percent:r,runeDepth:t,liquidityUnits:e,poolUnits:s})=>ct({runeDepth:t,liquidityUnits:e,poolUnits:s}).mul(r),jt=({percent:r,assetDepth:t,liquidityUnits:e,poolUnits:s})=>ut({assetDepth:t,liquidityUnits:e,poolUnits:s}).mul(r),d=r=>new D({value:r,decimal:i.BaseDecimal.THOR}),lt=({liquidityUnits:r,poolUnits:t,runeDepth:e,assetDepth:s})=>({assetAmount:d(s).mul(r).div(t),runeAmount:d(e).mul(r).div(t)}),Lt=({liquidityUnits:r,poolUnits:t,runeDepth:e,assetDepth:s,percent:n})=>Object.fromEntries(Object.entries(lt({liquidityUnits:r,poolUnits:t,runeDepth:e,assetDepth:s})).map(([a,o])=>[a,o.mul(n)])),Ft=({runeDepth:r,poolUnits:t,assetDepth:e,liquidityUnits:s,runeAmount:n,assetAmount:a})=>{const o=d(r),c=d(e),u=d(t),l=d(n),h=d(a),g=l.mul(c),C=h.mul(o),N=l.mul(h),yt=o.mul(c),Ct=u.mul(g.add(C.add(N.mul(2)))),wt=g.add(C.add(yt.mul(2))),X=Ct.div(wt),H=d(s).add(X);if(X.baseValueNumber===0)return H.div(u).baseValueNumber;const At=u.add(H);return H.div(At).baseValueNumber},Ut=({runeAmount:r,assetAmount:t,runeDepth:e,assetDepth:s})=>{const n=d(e),a=d(s),o=d(t),c=d(r),u=o.mul(n).sub(a.mul(c)),l=a.mul(c).add(n.mul(a));return Math.abs(u.div(l).baseValueNumber)},Wt=({symbol:r,ticker:t,chain:e})=>e==="ETH"&&t!=="ETH"?`${t}-${r.slice(-3)}`:r,Gt=(r,t)=>{switch(r){case i.MemoType.LEAVE:case i.MemoType.BOND:{const{address:e}=t;return`${r}:${e}`}case i.MemoType.UNBOND:{const{address:e,unbondAmount:s}=t;return`${r}:${e}:${s*10**8}`}case i.MemoType.THORNAME_REGISTER:{const{name:e,chain:s,address:n,owner:a}=t;return`${r}:${e}:${s}:${n}${a?`:${a}`:""}`}case i.MemoType.DEPOSIT:{const{chain:e,symbol:s,address:n,singleSide:a}=t;return a?`${r}:${e}/${s}::t:0`:`${r}:${e}.${s}:${n||""}:t:0`}case i.MemoType.WITHDRAW:{const{chain:e,ticker:s,symbol:n,basisPoints:a,targetAssetString:o,singleSide:c}=t,u=!c&&o?`:${o}`:"",l=Wt({chain:e,symbol:n,ticker:s});return`${r}:${e}${c?"/":"."}${l}:${a}${u}`}case i.MemoType.OPEN_LOAN:case i.MemoType.CLOSE_LOAN:{const{asset:e,address:s}=t;return`${r}:${e}:${s}`}default:return""}},Kt=r=>{if(r<0)throw new Error("Invalid number of year");return 10+r},Yt=r=>{if(r.length>30)return!1;const t=/^[a-zA-Z0-9+_-]+$/g;return!!r.match(t)},zt=([r,t,e,s,n])=>`${r}'/${t}'/${e}'/${s}${typeof n!="number"?"":`/${n}`}`;class Z extends Error{constructor(t,e,s){const n=t.status||t.status===0?t.status:"",a=t.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=t,this.request=e,this.options=s}}class ht extends Error{constructor(t){super("Request timed out"),Object.defineProperty(this,"request",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.name="TimeoutError",this.request=t}}const O=r=>r!==null&&typeof r=="object",E=(...r)=>{for(const t of r)if((!O(t)||Array.isArray(t))&&t!==void 0)throw new TypeError("The `options` argument must be an object");return J({},...r)},dt=(r={},t={})=>{const e=new globalThis.Headers(r),s=t instanceof globalThis.Headers,n=new globalThis.Headers(t);for(const[a,o]of n.entries())s&&o==="undefined"||o===void 0?e.delete(a):e.set(a,o);return e},J=(...r)=>{let t={},e={};for(const s of r)if(Array.isArray(s))Array.isArray(t)||(t=[]),t=[...t,...s];else if(O(s)){for(let[n,a]of Object.entries(s))O(a)&&n in t&&(a=J(t[n],a)),t={...t,[n]:a};O(s.headers)&&(e=dt(e,s.headers),t.headers=e)}return t},Jt=(()=>{let r=!1,t=!1;const e=typeof globalThis.ReadableStream=="function",s=typeof globalThis.Request=="function";return e&&s&&(t=new globalThis.Request("https://empty.invalid",{body:new globalThis.ReadableStream,method:"POST",get duplex(){return r=!0,"half"}}).headers.has("Content-Type")),r&&!t})(),Qt=typeof globalThis.AbortController=="function",Xt=typeof globalThis.ReadableStream=="function",Zt=typeof globalThis.FormData=="function",mt=["get","post","put","patch","head","delete"],te={json:"application/json",text:"text/*",formData:"multipart/form-data",arrayBuffer:"*/*",blob:"*/*"},L=2147483647,pt=Symbol("stop"),ee={json:!0,parseJson:!0,searchParams:!0,prefixUrl:!0,retry:!0,timeout:!0,hooks:!0,throwHttpErrors:!0,onDownloadProgress:!0,fetch:!0},se={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},re=r=>mt.includes(r)?r.toUpperCase():r,ne=["get","put","head","delete","options","trace"],ie=[408,413,429,500,502,503,504],ft=[413,429,503],tt={limit:2,methods:ne,statusCodes:ie,afterStatusCodes:ft,maxRetryAfter:Number.POSITIVE_INFINITY,backoffLimit:Number.POSITIVE_INFINITY,delay:r=>.3*2**(r-1)*1e3},ae=(r={})=>{if(typeof r=="number")return{...tt,limit:r};if(r.methods&&!Array.isArray(r.methods))throw new Error("retry.methods must be an array");if(r.statusCodes&&!Array.isArray(r.statusCodes))throw new Error("retry.statusCodes must be an array");return{...tt,...r,afterStatusCodes:ft}};async function oe(r,t,e,s){return new Promise((n,a)=>{const o=setTimeout(()=>{e&&e.abort(),a(new ht(r))},s.timeout);s.fetch(r,t).then(n).catch(a).then(()=>{clearTimeout(o)})})}async function ce(r,{signal:t}){return new Promise((e,s)=>{t&&(t.throwIfAborted(),t.addEventListener("abort",n,{once:!0}));function n(){clearTimeout(a),s(t.reason)}const a=setTimeout(()=>{t==null||t.removeEventListener("abort",n),e()},r)})}const ue=(r,t)=>{const e={};for(const s in t)!(s in se)&&!(s in ee)&&!(s in r)&&(e[s]=t[s]);return e};class q{static create(t,e){const s=new q(t,e),n=async()=>{if(typeof s._options.timeout=="number"&&s._options.timeout>L)throw new RangeError(`The \`timeout\` option cannot be greater than ${L}`);await Promise.resolve();let c=await s._fetch();for(const u of s._options.hooks.afterResponse){const l=await u(s.request,s._options,s._decorateResponse(c.clone()));l instanceof globalThis.Response&&(c=l)}if(s._decorateResponse(c),!c.ok&&s._options.throwHttpErrors){let u=new Z(c,s.request,s._options);for(const l of s._options.hooks.beforeError)u=await l(u);throw u}if(s._options.onDownloadProgress){if(typeof s._options.onDownloadProgress!="function")throw new TypeError("The `onDownloadProgress` option must be a function");if(!Xt)throw new Error("Streams are not supported in your environment. `ReadableStream` is missing.");return s._stream(c.clone(),s._options.onDownloadProgress)}return c},o=s._options.retry.methods.includes(s.request.method.toLowerCase())?s._retry(n):n();for(const[c,u]of Object.entries(te))o[c]=async()=>{s.request.headers.set("accept",s.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(e.parseJson)return e.parseJson(await h.text())}return h[c]()};return o}constructor(t,e={}){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=t,this._options={credentials:this._input.credentials||"same-origin",...e,headers:dt(this._input.headers,e.headers),hooks:J({beforeRequest:[],beforeRetry:[],beforeError:[],afterResponse:[]},e.hooks),method:re(e.method??this._input.method),prefixUrl:String(e.prefixUrl||""),retry:ae(e.retry),throwHttpErrors:e.throwHttpErrors!==!1,timeout:e.timeout??1e4,fetch:e.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(Qt){if(this.abortController=new globalThis.AbortController,this._options.signal){const s=this._options.signal;this._options.signal.addEventListener("abort",()=>{this.abortController.abort(s.reason)})}this._options.signal=this.abortController.signal}if(Jt&&(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);(Zt&&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(t){if(this._retryCount++,this._retryCount<this._options.retry.limit&&!(t instanceof ht)){if(t instanceof Z){if(!this._options.retry.statusCodes.includes(t.response.status))return 0;const s=t.response.headers.get("Retry-After");if(s&&this._options.retry.afterStatusCodes.includes(t.response.status)){let n=Number(s);return Number.isNaN(n)?n=Date.parse(s)-Date.now():n*=1e3,this._options.retry.maxRetryAfter!==void 0&&n>this._options.retry.maxRetryAfter?0:n}if(t.response.status===413)return 0}const e=this._options.retry.delay(this._retryCount);return Math.min(this._options.retry.backoffLimit,e)}return 0}_decorateResponse(t){return this._options.parseJson&&(t.json=async()=>this._options.parseJson(await t.text())),t}async _retry(t){try{return await t()}catch(e){const s=Math.min(this._calculateRetryDelay(e),L);if(s!==0&&this._retryCount>0){await ce(s,{signal:this._options.signal});for(const n of this._options.hooks.beforeRetry)if(await n({request:this.request,options:this._options,error:e,retryCount:this._retryCount})===pt)return;return this._retry(t)}throw e}}async _fetch(){for(const e of this._options.hooks.beforeRequest){const s=await e(this.request,this._options);if(s instanceof Request){this.request=s;break}if(s instanceof Response)return s}const t=ue(this.request,this._options);return this._options.timeout===!1?this._options.fetch(this.request.clone(),t):oe(this.request.clone(),t,this.abortController,this._options)}_stream(t,e){const s=Number(t.headers.get("content-length"))||0;let n=0;return t.status===204?(e&&e({percent:1,totalBytes:s,transferredBytes:n},new Uint8Array),new globalThis.Response(null,{status:t.status,statusText:t.statusText,headers:t.headers})):new globalThis.Response(new globalThis.ReadableStream({async start(a){const o=t.body.getReader();e&&e({percent:0,transferredBytes:0,totalBytes:s},new Uint8Array);async function c(){const{done:u,value:l}=await o.read();if(u){a.close();return}if(e){n+=l.byteLength;const h=s===0?0:n/s;e({percent:h,transferredBytes:n,totalBytes:s},l)}a.enqueue(l),await c()}await c()}}),{status:t.status,statusText:t.statusText,headers:t.headers})}}/*! MIT License © Sindre Sorhus */const W=r=>{const t=(e,s)=>q.create(e,E(r,s));for(const e of mt)t[e]=(s,n)=>q.create(s,E(r,n,{method:e}));return t.create=e=>W(E(e)),t.extend=e=>W(E(r,e)),t.stop=pt,t},le=W(),he=le,de=typeof window<"u"?{}:{referrer:"https://sk.thorswap.net",referer:"https://sk.thorswap.net"},et=he.create({headers:de}),gt={get:(r,t)=>et.get(r,t).json(),post:(r,t)=>et.post(r,t).json()},st=Object.values(i.Chain),me=(r="")=>{const t=r.toUpperCase(),[e]=t.split(".");if(st.includes(e))return!0;const[s]=t.split("/");if(st.includes(s))return!0;throw new Error(`Invalid identifier: ${r}. Expected format: <Chain>.<Ticker> or <Chain>.<Ticker>-<ContractAddress>`)},R=8,w=r=>10n**BigInt(r),T=r=>Math.log10(parseFloat(r.toString()));function $({value:r,bigIntDecimal:t=R,decimal:e=R}){const s=r<0n;let n=r.toString().substring(s?1:0);const a=e-(n.length-1);a>0&&(n="0".repeat(a)+n);const o=n.length-e;let c=n.slice(-e);return parseInt(c[t])>=5?c=`${c.substring(0,t-1)}${(parseInt(c[t-1])+1).toString()}`:c=c.substring(0,t),`${s?"-":""}${n.slice(0,o)}.${c}`.replace(/\.?0*$/,"")}var b,S,k,_t,P,bt,I,G,y,v,B,K;const x=class x{constructor(t){_(this,b);_(this,k);_(this,P);_(this,I);_(this,y);_(this,B);p(this,"decimalMultiplier",10n**8n);p(this,"bigIntValue",0n);p(this,"decimal");const e=F(t);this.decimal=typeof t=="object"?t.decimal:void 0,this.decimalMultiplier=w(Math.max(m(this,B,K).call(this,m(this,y,v).call(this,e)),this.decimal||0)),m(this,k,_t).call(this,e)}static fromBigInt(t,e){return new x({decimal:e,value:$({value:t,bigIntDecimal:e,decimal:e})})}static shiftDecimals({value:t,from:e,to:s}){return this.fromBigInt(new x(t).bigIntValue*w(s)/w(e),s)}get baseValue(){return this.getBaseValue("string")}get baseValueNumber(){return this.getBaseValue("number")}get baseValueBigInt(){return this.getBaseValue("bigint")}set(t){return new this.constructor({decimal:this.decimal,value:t,identifier:this.toString()})}add(...t){return m(this,b,S).call(this,"add",...t)}sub(...t){return m(this,b,S).call(this,"sub",...t)}mul(...t){return m(this,b,S).call(this,"mul",...t)}div(...t){return m(this,b,S).call(this,"div",...t)}gt(t){return this.bigIntValue>this.getBigIntValue(t)}gte(t){return this.bigIntValue>=this.getBigIntValue(t)}lt(t){return this.bigIntValue<this.getBigIntValue(t)}lte(t){return this.bigIntValue<=this.getBigIntValue(t)}eqValue(t){return this.bigIntValue===this.getBigIntValue(t)}getValue(t){const e=this.formatBigIntToSafeValue(this.bigIntValue,this.decimal||T(this.decimalMultiplier));switch(t){case"number":return Number(e);case"string":return e;default:return this.bigIntValue*BigInt(this.decimal||8n)/this.decimalMultiplier}}getBaseValue(t){const e=this.decimalMultiplier/w(this.decimal||i.BaseDecimal.THOR),s=this.bigIntValue/e;switch(t){case"number":return Number(s);case"string":return s.toString();default:return s}}getBigIntValue(t,e){if(!e&&typeof t=="object")return t.bigIntValue;const s=F(t),n=m(this,y,v).call(this,s);return n==="0"||n==="undefined"?0n:m(this,I,G).call(this,n,e)}formatBigIntToSafeValue(t,e){const s=e||this.decimal||R,n=Math.max(s,T(this.decimalMultiplier)),a=t<0n,o=t.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[s])>=5?h=`${h.substring(0,s-1)}${(parseInt(h[s-1])+1).toString()}`:h=h.substring(0,s),`${a?"-":""}${u.slice(0,l)}.${h}`.replace(/\.?0*$/,"")}toSignificant(t=6){const[e,s]=this.getValue("string").split("."),n=e||"",a=s||"",o=parseInt(n)?n.length+a.length:a.length;if(o<=t)return this.getValue("string");if(n.length>=t)return n.slice(0,t).padEnd(n.length,"0");if(parseInt(n))return`${n}.${a.slice(0,t-n.length)}`.padEnd(o-t,"0");const c=parseInt(a),u=`${c}`.slice(0,t);return`0.${u.padStart(a.length-`${c}`.length+u.length,"0")}`}toFixed(t=6){const[e,s]=this.getValue("string").split("."),n=e||"",a=s||"";if(parseInt(n))return`${n}.${a.slice(0,t)}`.padEnd(t,"0");const o=parseInt(a),c=`${o}`.slice(0,t);return`0.${c.padStart(a.length-`${o}`.length+c.length,"0")}`}toAbbreviation(t=2){const e=this.getValue("number"),s=["","K","M","B","T","Q","Qi","S"],n=Math.floor(Math.log10(Math.abs(e))/3),a=s[n];if(!a)return this.getValue("string");const o=10**(n*3);return`${(e/o).toFixed(t)}${a}`}};b=new WeakSet,S=function(t,...e){const s=m(this,P,bt).call(this,this,...e),n=w(s),a=e.reduce((c,u)=>{const l=this.getBigIntValue(u,s);switch(t){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=$({bigIntDecimal:s,decimal:Math.max(s,T(this.decimalMultiplier)),value:a});return new this.constructor({decimal:this.decimal,value:o,identifier:this.toString()})},k=new WeakSet,_t=function(t){const e=m(this,y,v).call(this,t)||"0";this.bigIntValue=m(this,I,G).call(this,e)},P=new WeakSet,bt=function(...t){const e=t.map(s=>typeof s=="object"?s.decimal||T(s.decimalMultiplier):m(this,B,K).call(this,m(this,y,v).call(this,s))).filter(Boolean);return Math.max(...e,R)},I=new WeakSet,G=function(t,e){const s=e?w(e):this.decimalMultiplier,n=T(s),[a="",o=""]=t.split(".");return BigInt(`${a}${o.padEnd(n,"0")}`)},y=new WeakSet,v=function(t){const s=`${typeof t=="number"?Number(t).toLocaleString("fullwide",{useGrouping:!1,maximumFractionDigits:20}):F(t)}`.replaceAll(",",".").split(".");return s.length>1?`${s.slice(0,-1).join("")}.${s.at(-1)}`:s[0]},B=new WeakSet,K=function(t){var s;const e=((s=t.split(".")[1])==null?void 0:s.length)||0;return Math.max(e,R)};let A=x;function F(r){return typeof r=="object"?"getValue"in r?r.getValue("string"):r.value:r}const M=(r,t)=>typeof r=="bigint"?$({value:r,bigIntDecimal:t,decimal:t}):r;let Y;const U=r=>{if(!Y)throw new Error("Static assets not loaded, call await AssetValue.loadStaticAssets() first");return Y.get(r.toUpperCase())||{decimal:i.BaseDecimal.THOR,identifier:""}},rt=async(r,t=0)=>{me(r);const e=await z(V(r)),s=M(t,e);return new f({decimal:e,value:s,identifier:r})};class f extends A{constructor(e){super(e.value instanceof A?e.value:{decimal:e.decimal,value:e.value});p(this,"address");p(this,"chain");p(this,"isSynthetic",!1);p(this,"isGasAsset",!1);p(this,"symbol");p(this,"ticker");p(this,"type");const s="identifier"in e?e.identifier:`${e.chain}.${e.symbol}`,n=V(s);this.type=ot(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(e=!1){const s=this.isSynthetic?this.symbol.split("-")[0]:`${this.chain}.${this.ticker}`;return e?s:`${this.chain}.${this.symbol}`}eq({chain:e,symbol:s}){return this.chain===e&&this.symbol===s}static async fromString(e,s=0){return rt(e,s)}static fromStringSync(e,s=0){const{isSynthetic:n}=V(e),{decimal:a,identifier:o}=U(e),c=M(s,a);return o?new f({decimal:a,identifier:o,value:c}):n?new f({decimal:8,identifier:e,value:c}):void 0}static async fromIdentifier(e,s=0){return rt(e,s)}static fromIdentifierSync(e,s=0){const{decimal:n,identifier:a}=U(e),o=M(s,n);return new f({decimal:n,identifier:a,value:o})}static fromChainOrSignature(e,s=0){const{decimal:n,identifier:a}=at(e),o=M(s,n);return new f({value:o,decimal:n,identifier:a})}static async fromTCQuote(e,s=0){const n=await z(V(e)),a=this.shiftDecimals({value:s,from:i.BaseDecimal.THOR,to:n});return new f({value:a,identifier:e,decimal:n})}static fromTCQuoteStatic(e,s=0){const n=U(e),a=this.shiftDecimals({value:s,from:i.BaseDecimal.THOR,to:n.decimal});return new f({...n,value:a})}static async loadStaticAssets(){return new Promise(async(e,s)=>{try{const{ThorchainList:n,NativeList:a,...o}=await import("@swapkit/tokens");Y=[a,...Object.values(o)].reduce((u,{tokens:l})=>(l.forEach(({identifier:h,chain:g,...C})=>{const N="decimals"in C?C.decimals:i.BaseDecimal[g];u.set(h,{identifier:h,decimal:N})}),u),new Map),e({ok:!0})}catch(n){console.error(n),s({ok:!1,error:n,message:"Couldn't load static assets. Ensure you have installed @swapkit/tokens package"})}})}}const pe=r=>{const t=f.fromChainOrSignature(r);switch(r){case i.Chain.Bitcoin:case i.Chain.Litecoin:case i.Chain.BitcoinCash:return t.add(10001);case i.Chain.Dogecoin:return t.add(100000001);case i.Chain.Avalanche:case i.Chain.Ethereum:return t.add(10*10**9);case i.Chain.THORChain:case i.Chain.Maya:return t.add(0);default:return t.add(1)}},V=r=>{const t=r.slice(0,14).includes("/"),[e,s]=r.split(".").pop().split("/"),n=r.includes(".")&&!t?r:`${i.Chain.THORChain}.${s}`,[a,o]=n.split("."),[c,u]=(t?s:o).split("-");return{address:u==null?void 0:u.toLowerCase(),chain:a,isGasAsset:it({chain:a,symbol:o}),isSynthetic:t,symbol:(t?`${e}/`:"")+(u?`${c}-${(u==null?void 0:u.toLowerCase())??""}`:o),ticker:c}},fe={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(t,e){console.error(e),super(t,{cause:{code:fe[t],message:t}}),Object.setPrototypeOf(this,Q.prototype)}}class D extends A{eq(t){return this.eqValue(t)}static fromBigInt(t,e){return new D({decimal:e,value:$({value:t,bigIntDecimal:e,decimal:e})})}}exports.AssetValue=f;exports.BigIntArithmetics=A;exports.RequestClient=gt;exports.SwapKitError=Q;exports.SwapKitNumber=D;exports.assetFromString=xt;exports.derivationPathToString=zt;exports.filterAssets=Nt;exports.formatBigIntToSafeValue=$;exports.gasFeeMultiplier=Pt;exports.getAssetType=ot;exports.getAsymmetricAssetShare=ut;exports.getAsymmetricAssetWithdrawAmount=jt;exports.getAsymmetricRuneShare=ct;exports.getAsymmetricRuneWithdrawAmount=Ht;exports.getCommonAssetInfo=at;exports.getDecimal=z;exports.getEstimatedPoolShare=Ft;exports.getLiquiditySlippage=Ut;exports.getMemoFor=Gt;exports.getMinAmountByChain=pe;exports.getSymmetricPoolShare=lt;exports.getSymmetricWithdraw=Lt;exports.getTHORNameCost=Kt;exports.isGasAsset=it;exports.validateTHORName=Yt;
|
|
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,6 +1,6 @@
|
|
|
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
|
};
|
|
@@ -9,11 +9,11 @@ var y = (s, t, e) => {
|
|
|
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
|
|
13
|
-
import { FeeOption as L, BaseDecimal 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,31 +23,31 @@ 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
|
-
return console.error(e),
|
|
31
|
+
return console.error(e), d[s];
|
|
32
32
|
}
|
|
33
|
-
},
|
|
33
|
+
}, Tt = async (s) => {
|
|
34
34
|
if (s === o.Ethereum)
|
|
35
|
-
return
|
|
35
|
+
return d.ETH;
|
|
36
36
|
const [, t] = s.split("-");
|
|
37
|
-
return t != null && t.startsWith("0x") ? nt({ chain: o.Ethereum, to: t }) :
|
|
38
|
-
},
|
|
37
|
+
return t != null && t.startsWith("0x") ? nt({ chain: o.Ethereum, to: t }) : d.ETH;
|
|
38
|
+
}, vt = async (s) => {
|
|
39
39
|
const [, t] = s.split("-");
|
|
40
|
-
return t != null && t.startsWith("0x") ? nt({ chain: o.Avalanche, to: t.toLowerCase() }) :
|
|
41
|
-
}, St = async (s) => s === o.BinanceSmartChain ?
|
|
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, 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
|
-
return
|
|
50
|
+
return d[s];
|
|
51
51
|
}
|
|
52
52
|
}, re = {
|
|
53
53
|
[L.Average]: 1.2,
|
|
@@ -86,13 +86,13 @@ const Tt = "0x313ce567", nt = async ({ chain: s, to: t }) => {
|
|
|
86
86
|
case "ETH.vTHOR":
|
|
87
87
|
return { identifier: "ETH.vTHOR-0x815c23eca83261b6ec689b60cc4a58b54bc24d8d", decimal: 18 };
|
|
88
88
|
case o.Cosmos:
|
|
89
|
-
return { identifier: "GAIA.ATOM", decimal:
|
|
89
|
+
return { identifier: "GAIA.ATOM", decimal: d[s] };
|
|
90
90
|
case o.THORChain:
|
|
91
|
-
return { identifier: "THOR.RUNE", decimal:
|
|
91
|
+
return { identifier: "THOR.RUNE", decimal: d[s] };
|
|
92
92
|
case o.BinanceSmartChain:
|
|
93
|
-
return { identifier: "BSC.BNB", decimal:
|
|
93
|
+
return { identifier: "BSC.BNB", decimal: d[s] };
|
|
94
94
|
case o.Maya:
|
|
95
|
-
return { identifier: "MAYA.CACAO", decimal:
|
|
95
|
+
return { identifier: "MAYA.CACAO", decimal: d.MAYA };
|
|
96
96
|
case "MAYA.MAYA":
|
|
97
97
|
return { identifier: "MAYA.MAYA", decimal: 4 };
|
|
98
98
|
case o.Kujira:
|
|
@@ -106,7 +106,7 @@ const Tt = "0x313ce567", nt = async ({ chain: s, to: t }) => {
|
|
|
106
106
|
case o.Polygon:
|
|
107
107
|
case o.Bitcoin:
|
|
108
108
|
case o.Ethereum:
|
|
109
|
-
return { identifier: `${s}.${s}`, decimal:
|
|
109
|
+
return { identifier: `${s}.${s}`, decimal: d[s] };
|
|
110
110
|
}
|
|
111
111
|
}, It = ({ chain: s, symbol: t }) => {
|
|
112
112
|
if (t.includes("/"))
|
|
@@ -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,
|
|
@@ -186,7 +186,7 @@ const Tt = "0x313ce567", nt = async ({ chain: s, to: t }) => {
|
|
|
186
186
|
assetDepth: r,
|
|
187
187
|
percent: n
|
|
188
188
|
}) => Object.fromEntries(
|
|
189
|
-
Object.entries(
|
|
189
|
+
Object.entries(Vt({ liquidityUnits: s, poolUnits: t, runeDepth: e, assetDepth: r })).map(
|
|
190
190
|
([i, a]) => [i, a.mul(n)]
|
|
191
191
|
)
|
|
192
192
|
), ce = ({
|
|
@@ -197,48 +197,50 @@ const Tt = "0x313ce567", nt = async ({ chain: s, to: t }) => {
|
|
|
197
197
|
runeAmount: n,
|
|
198
198
|
assetAmount: i
|
|
199
199
|
}) => {
|
|
200
|
-
const a =
|
|
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,
|
|
208
208
|
runeDepth: e,
|
|
209
209
|
assetDepth: r
|
|
210
210
|
}) => {
|
|
211
|
-
|
|
212
|
-
|
|
211
|
+
if (s === "0" || t === "0" || e === "0" || r === "0")
|
|
212
|
+
return 0;
|
|
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
|
+
return Math.abs(u.div(l).getBaseValue("number"));
|
|
213
215
|
}, Mt = ({
|
|
214
216
|
symbol: s,
|
|
215
217
|
ticker: t,
|
|
216
218
|
chain: e
|
|
217
219
|
}) => e === "ETH" && t !== "ETH" ? `${t}-${s.slice(-3)}` : s, le = (s, t) => {
|
|
218
220
|
switch (s) {
|
|
219
|
-
case
|
|
220
|
-
case
|
|
221
|
+
case g.LEAVE:
|
|
222
|
+
case g.BOND: {
|
|
221
223
|
const { address: e } = t;
|
|
222
224
|
return `${s}:${e}`;
|
|
223
225
|
}
|
|
224
|
-
case
|
|
226
|
+
case g.UNBOND: {
|
|
225
227
|
const { address: e, unbondAmount: r } = t;
|
|
226
228
|
return `${s}:${e}:${r * 10 ** 8}`;
|
|
227
229
|
}
|
|
228
|
-
case
|
|
230
|
+
case g.THORNAME_REGISTER: {
|
|
229
231
|
const { name: e, chain: r, address: n, owner: i } = t;
|
|
230
232
|
return `${s}:${e}:${r}:${n}${i ? `:${i}` : ""}`;
|
|
231
233
|
}
|
|
232
|
-
case
|
|
234
|
+
case g.DEPOSIT: {
|
|
233
235
|
const { chain: e, symbol: r, address: n, singleSide: i } = t;
|
|
234
236
|
return i ? `${s}:${e}/${r}::t:0` : `${s}:${e}.${r}:${n || ""}:t:0`;
|
|
235
237
|
}
|
|
236
|
-
case
|
|
238
|
+
case g.WITHDRAW: {
|
|
237
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 });
|
|
238
240
|
return `${s}:${e}${c ? "/" : "."}${l}:${i}${u}`;
|
|
239
241
|
}
|
|
240
|
-
case
|
|
241
|
-
case
|
|
242
|
+
case g.OPEN_LOAN:
|
|
243
|
+
case g.CLOSE_LOAN: {
|
|
242
244
|
const { asset: e, address: r } = t;
|
|
243
245
|
return `${s}:${e}:${r}`;
|
|
244
246
|
}
|
|
@@ -255,7 +257,7 @@ const Tt = "0x313ce567", nt = async ({ chain: s, to: t }) => {
|
|
|
255
257
|
const t = /^[a-zA-Z0-9+_-]+$/g;
|
|
256
258
|
return !!s.match(t);
|
|
257
259
|
}, me = ([s, t, e, r, n]) => `${s}'/${t}'/${e}'/${r}${typeof n != "number" ? "" : `/${n}`}`;
|
|
258
|
-
class
|
|
260
|
+
class X extends Error {
|
|
259
261
|
constructor(t, e, r) {
|
|
260
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";
|
|
261
263
|
super(`Request failed with ${c}`), Object.defineProperty(this, "response", {
|
|
@@ -276,7 +278,7 @@ class Z extends Error {
|
|
|
276
278
|
}), this.name = "HTTPError", this.response = t, this.request = e, this.options = r;
|
|
277
279
|
}
|
|
278
280
|
}
|
|
279
|
-
class
|
|
281
|
+
class it extends Error {
|
|
280
282
|
constructor(t) {
|
|
281
283
|
super("Request timed out"), Object.defineProperty(this, "request", {
|
|
282
284
|
enumerable: !0,
|
|
@@ -286,25 +288,25 @@ class ot extends Error {
|
|
|
286
288
|
}), this.name = "TimeoutError", this.request = t;
|
|
287
289
|
}
|
|
288
290
|
}
|
|
289
|
-
const
|
|
291
|
+
const M = (s) => s !== null && typeof s == "object", V = (...s) => {
|
|
290
292
|
for (const t of s)
|
|
291
|
-
if ((!
|
|
293
|
+
if ((!M(t) || Array.isArray(t)) && t !== void 0)
|
|
292
294
|
throw new TypeError("The `options` argument must be an object");
|
|
293
|
-
return
|
|
294
|
-
},
|
|
295
|
+
return J({}, ...s);
|
|
296
|
+
}, ot = (s = {}, t = {}) => {
|
|
295
297
|
const e = new globalThis.Headers(s), r = t instanceof globalThis.Headers, n = new globalThis.Headers(t);
|
|
296
298
|
for (const [i, a] of n.entries())
|
|
297
299
|
r && a === "undefined" || a === void 0 ? e.delete(i) : e.set(i, a);
|
|
298
300
|
return e;
|
|
299
|
-
},
|
|
301
|
+
}, J = (...s) => {
|
|
300
302
|
let t = {}, e = {};
|
|
301
303
|
for (const r of s)
|
|
302
304
|
if (Array.isArray(r))
|
|
303
305
|
Array.isArray(t) || (t = []), t = [...t, ...r];
|
|
304
|
-
else if (
|
|
306
|
+
else if (M(r)) {
|
|
305
307
|
for (let [n, i] of Object.entries(r))
|
|
306
|
-
|
|
307
|
-
|
|
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);
|
|
308
310
|
}
|
|
309
311
|
return t;
|
|
310
312
|
}, kt = (() => {
|
|
@@ -318,13 +320,13 @@ const B = (s) => s !== null && typeof s == "object", V = (...s) => {
|
|
|
318
320
|
return s = !0, "half";
|
|
319
321
|
}
|
|
320
322
|
}).headers.has("Content-Type")), s && !t;
|
|
321
|
-
})(), 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 = {
|
|
322
324
|
json: "application/json",
|
|
323
325
|
text: "text/*",
|
|
324
326
|
formData: "multipart/form-data",
|
|
325
327
|
arrayBuffer: "*/*",
|
|
326
328
|
blob: "*/*"
|
|
327
|
-
},
|
|
329
|
+
}, D = 2147483647, ct = Symbol("stop"), jt = {
|
|
328
330
|
json: !0,
|
|
329
331
|
parseJson: !0,
|
|
330
332
|
searchParams: !0,
|
|
@@ -335,7 +337,7 @@ const B = (s) => s !== null && typeof s == "object", V = (...s) => {
|
|
|
335
337
|
throwHttpErrors: !0,
|
|
336
338
|
onDownloadProgress: !0,
|
|
337
339
|
fetch: !0
|
|
338
|
-
},
|
|
340
|
+
}, Ht = {
|
|
339
341
|
method: !0,
|
|
340
342
|
headers: !0,
|
|
341
343
|
body: !0,
|
|
@@ -351,18 +353,18 @@ const B = (s) => s !== null && typeof s == "object", V = (...s) => {
|
|
|
351
353
|
window: !0,
|
|
352
354
|
dispatcher: !0,
|
|
353
355
|
duplex: !0
|
|
354
|
-
},
|
|
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 = {
|
|
355
357
|
limit: 2,
|
|
356
|
-
methods:
|
|
358
|
+
methods: Dt,
|
|
357
359
|
statusCodes: Ut,
|
|
358
|
-
afterStatusCodes:
|
|
360
|
+
afterStatusCodes: ut,
|
|
359
361
|
maxRetryAfter: Number.POSITIVE_INFINITY,
|
|
360
362
|
backoffLimit: Number.POSITIVE_INFINITY,
|
|
361
363
|
delay: (s) => 0.3 * 2 ** (s - 1) * 1e3
|
|
362
364
|
}, Ft = (s = {}) => {
|
|
363
365
|
if (typeof s == "number")
|
|
364
366
|
return {
|
|
365
|
-
...
|
|
367
|
+
...Z,
|
|
366
368
|
limit: s
|
|
367
369
|
};
|
|
368
370
|
if (s.methods && !Array.isArray(s.methods))
|
|
@@ -370,15 +372,15 @@ const B = (s) => s !== null && typeof s == "object", V = (...s) => {
|
|
|
370
372
|
if (s.statusCodes && !Array.isArray(s.statusCodes))
|
|
371
373
|
throw new Error("retry.statusCodes must be an array");
|
|
372
374
|
return {
|
|
373
|
-
...
|
|
375
|
+
...Z,
|
|
374
376
|
...s,
|
|
375
|
-
afterStatusCodes:
|
|
377
|
+
afterStatusCodes: ut
|
|
376
378
|
};
|
|
377
379
|
};
|
|
378
380
|
async function Wt(s, t, e, r) {
|
|
379
381
|
return new Promise((n, i) => {
|
|
380
382
|
const a = setTimeout(() => {
|
|
381
|
-
e && e.abort(), i(new
|
|
383
|
+
e && e.abort(), i(new it(s));
|
|
382
384
|
}, r.timeout);
|
|
383
385
|
r.fetch(s, t).then(n).catch(i).then(() => {
|
|
384
386
|
clearTimeout(a);
|
|
@@ -399,14 +401,14 @@ async function Gt(s, { signal: t }) {
|
|
|
399
401
|
const Yt = (s, t) => {
|
|
400
402
|
const e = {};
|
|
401
403
|
for (const r in t)
|
|
402
|
-
!(r in
|
|
404
|
+
!(r in Ht) && !(r in jt) && !(r in s) && (e[r] = t[r]);
|
|
403
405
|
return e;
|
|
404
406
|
};
|
|
405
407
|
class q {
|
|
406
408
|
static create(t, e) {
|
|
407
409
|
const r = new q(t, e), n = async () => {
|
|
408
|
-
if (typeof r._options.timeout == "number" && r._options.timeout >
|
|
409
|
-
throw new RangeError(`The \`timeout\` option cannot be greater than ${
|
|
410
|
+
if (typeof r._options.timeout == "number" && r._options.timeout > D)
|
|
411
|
+
throw new RangeError(`The \`timeout\` option cannot be greater than ${D}`);
|
|
410
412
|
await Promise.resolve();
|
|
411
413
|
let c = await r._fetch();
|
|
412
414
|
for (const u of r._options.hooks.afterResponse) {
|
|
@@ -414,7 +416,7 @@ class q {
|
|
|
414
416
|
l instanceof globalThis.Response && (c = l);
|
|
415
417
|
}
|
|
416
418
|
if (r._decorateResponse(c), !c.ok && r._options.throwHttpErrors) {
|
|
417
|
-
let u = new
|
|
419
|
+
let u = new X(c, r.request, r._options);
|
|
418
420
|
for (const l of r._options.hooks.beforeError)
|
|
419
421
|
u = await l(u);
|
|
420
422
|
throw u;
|
|
@@ -473,14 +475,14 @@ class q {
|
|
|
473
475
|
// TODO: credentials can be removed when the spec change is implemented in all browsers. Context: https://www.chromestatus.com/feature/4539473312350208
|
|
474
476
|
credentials: this._input.credentials || "same-origin",
|
|
475
477
|
...e,
|
|
476
|
-
headers:
|
|
477
|
-
hooks:
|
|
478
|
+
headers: ot(this._input.headers, e.headers),
|
|
479
|
+
hooks: J({
|
|
478
480
|
beforeRequest: [],
|
|
479
481
|
beforeRetry: [],
|
|
480
482
|
beforeError: [],
|
|
481
483
|
afterResponse: []
|
|
482
484
|
}, e.hooks),
|
|
483
|
-
method:
|
|
485
|
+
method: Lt(e.method ?? this._input.method),
|
|
484
486
|
// eslint-disable-next-line @typescript-eslint/prefer-nullish-coalescing
|
|
485
487
|
prefixUrl: String(e.prefixUrl || ""),
|
|
486
488
|
retry: Ft(e.retry),
|
|
@@ -510,8 +512,8 @@ class q {
|
|
|
510
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 }));
|
|
511
513
|
}
|
|
512
514
|
_calculateRetryDelay(t) {
|
|
513
|
-
if (this._retryCount++, this._retryCount < this._options.retry.limit && !(t instanceof
|
|
514
|
-
if (t instanceof
|
|
515
|
+
if (this._retryCount++, this._retryCount < this._options.retry.limit && !(t instanceof it)) {
|
|
516
|
+
if (t instanceof X) {
|
|
515
517
|
if (!this._options.retry.statusCodes.includes(t.response.status))
|
|
516
518
|
return 0;
|
|
517
519
|
const r = t.response.headers.get("Retry-After");
|
|
@@ -534,7 +536,7 @@ class q {
|
|
|
534
536
|
try {
|
|
535
537
|
return await t();
|
|
536
538
|
} catch (e) {
|
|
537
|
-
const r = Math.min(this._calculateRetryDelay(e),
|
|
539
|
+
const r = Math.min(this._calculateRetryDelay(e), D);
|
|
538
540
|
if (r !== 0 && this._retryCount > 0) {
|
|
539
541
|
await Gt(r, { signal: this._options.signal });
|
|
540
542
|
for (const n of this._options.hooks.beforeRetry)
|
|
@@ -543,7 +545,7 @@ class q {
|
|
|
543
545
|
options: this._options,
|
|
544
546
|
error: e,
|
|
545
547
|
retryCount: this._retryCount
|
|
546
|
-
}) ===
|
|
548
|
+
}) === ct)
|
|
547
549
|
return;
|
|
548
550
|
return this._retry(t);
|
|
549
551
|
}
|
|
@@ -598,29 +600,29 @@ class q {
|
|
|
598
600
|
}
|
|
599
601
|
}
|
|
600
602
|
/*! MIT License © Sindre Sorhus */
|
|
601
|
-
const
|
|
603
|
+
const F = (s) => {
|
|
602
604
|
const t = (e, r) => q.create(e, V(s, r));
|
|
603
|
-
for (const e of
|
|
605
|
+
for (const e of at)
|
|
604
606
|
t[e] = (r, n) => q.create(r, V(s, n, { method: e }));
|
|
605
|
-
return t.create = (e) =>
|
|
606
|
-
}, zt =
|
|
607
|
-
get: (s, t) =>
|
|
608
|
-
post: (s, t) =>
|
|
609
|
-
},
|
|
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 = "") => {
|
|
610
612
|
const t = s.toUpperCase(), [e] = t.split(".");
|
|
611
|
-
if (
|
|
613
|
+
if (et.includes(e))
|
|
612
614
|
return !0;
|
|
613
615
|
const [r] = t.split("/");
|
|
614
|
-
if (
|
|
616
|
+
if (et.includes(r))
|
|
615
617
|
return !0;
|
|
616
618
|
throw new Error(
|
|
617
619
|
`Invalid identifier: ${s}. Expected format: <Chain>.<Ticker> or <Chain>.<Ticker>-<ContractAddress>`
|
|
618
620
|
);
|
|
619
|
-
},
|
|
621
|
+
}, I = 8, S = (s) => 10n ** BigInt(s), R = (s) => Math.log10(parseFloat(s.toString()));
|
|
620
622
|
function x({
|
|
621
623
|
value: s,
|
|
622
|
-
bigIntDecimal: t =
|
|
623
|
-
decimal: e =
|
|
624
|
+
bigIntDecimal: t = I,
|
|
625
|
+
decimal: e = I
|
|
624
626
|
}) {
|
|
625
627
|
const r = s < 0n;
|
|
626
628
|
let n = s.toString().substring(r ? 1 : 0);
|
|
@@ -633,25 +635,25 @@ function x({
|
|
|
633
635
|
""
|
|
634
636
|
);
|
|
635
637
|
}
|
|
636
|
-
var
|
|
637
|
-
const
|
|
638
|
+
var A, $, P, lt, N, ht, B, W, T, C, O, G;
|
|
639
|
+
const K = class K {
|
|
638
640
|
constructor(t) {
|
|
639
|
-
y(this,
|
|
641
|
+
y(this, A);
|
|
640
642
|
y(this, P);
|
|
641
643
|
y(this, N);
|
|
642
|
-
y(this,
|
|
643
|
-
y(this,
|
|
644
|
+
y(this, B);
|
|
645
|
+
y(this, T);
|
|
644
646
|
y(this, O);
|
|
645
|
-
|
|
646
|
-
|
|
647
|
-
|
|
648
|
-
const e =
|
|
649
|
-
this.decimal = typeof t == "object" ? t.decimal : void 0, this.decimalMultiplier =
|
|
650
|
-
Math.max(
|
|
651
|
-
),
|
|
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);
|
|
652
654
|
}
|
|
653
655
|
static fromBigInt(t, e) {
|
|
654
|
-
return new
|
|
656
|
+
return new K({
|
|
655
657
|
decimal: e,
|
|
656
658
|
value: x({ value: t, bigIntDecimal: e, decimal: e })
|
|
657
659
|
});
|
|
@@ -662,7 +664,7 @@ const H = class H {
|
|
|
662
664
|
to: r
|
|
663
665
|
}) {
|
|
664
666
|
return this.fromBigInt(
|
|
665
|
-
|
|
667
|
+
t.getBaseValue("bigint") * S(r) / S(e),
|
|
666
668
|
r
|
|
667
669
|
);
|
|
668
670
|
}
|
|
@@ -688,16 +690,16 @@ const H = class H {
|
|
|
688
690
|
return new this.constructor({ decimal: this.decimal, value: t, identifier: this.toString() });
|
|
689
691
|
}
|
|
690
692
|
add(...t) {
|
|
691
|
-
return
|
|
693
|
+
return m(this, A, $).call(this, "add", ...t);
|
|
692
694
|
}
|
|
693
695
|
sub(...t) {
|
|
694
|
-
return
|
|
696
|
+
return m(this, A, $).call(this, "sub", ...t);
|
|
695
697
|
}
|
|
696
698
|
mul(...t) {
|
|
697
|
-
return
|
|
699
|
+
return m(this, A, $).call(this, "mul", ...t);
|
|
698
700
|
}
|
|
699
701
|
div(...t) {
|
|
700
|
-
return
|
|
702
|
+
return m(this, A, $).call(this, "div", ...t);
|
|
701
703
|
}
|
|
702
704
|
gt(t) {
|
|
703
705
|
return this.bigIntValue > this.getBigIntValue(t);
|
|
@@ -729,7 +731,7 @@ const H = class H {
|
|
|
729
731
|
}
|
|
730
732
|
}
|
|
731
733
|
getBaseValue(t) {
|
|
732
|
-
const e = this.decimalMultiplier /
|
|
734
|
+
const e = this.decimalMultiplier / S(this.decimal || d.THOR), r = this.bigIntValue / e;
|
|
733
735
|
switch (t) {
|
|
734
736
|
case "number":
|
|
735
737
|
return Number(r);
|
|
@@ -742,11 +744,11 @@ const H = class H {
|
|
|
742
744
|
getBigIntValue(t, e) {
|
|
743
745
|
if (!e && typeof t == "object")
|
|
744
746
|
return t.bigIntValue;
|
|
745
|
-
const r =
|
|
746
|
-
return n === "0" || n === "undefined" ? 0n :
|
|
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);
|
|
747
749
|
}
|
|
748
750
|
formatBigIntToSafeValue(t, e) {
|
|
749
|
-
const r = e || this.decimal ||
|
|
751
|
+
const r = e || this.decimal || I, n = Math.max(
|
|
750
752
|
r,
|
|
751
753
|
R(this.decimalMultiplier)
|
|
752
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;
|
|
@@ -757,14 +759,14 @@ const H = class H {
|
|
|
757
759
|
)}.${h}`.replace(/\.?0*$/, "");
|
|
758
760
|
}
|
|
759
761
|
toSignificant(t = 6) {
|
|
760
|
-
const [e, r] = this.getValue("string").split("."), n = e || "", i = r || ""
|
|
761
|
-
if (
|
|
762
|
+
const [e, r] = this.getValue("string").split("."), n = e || "", i = r || "";
|
|
763
|
+
if ((parseInt(n) ? n.length + i.length : i.length) <= t)
|
|
762
764
|
return this.getValue("string");
|
|
763
765
|
if (n.length >= t)
|
|
764
766
|
return n.slice(0, t).padEnd(n.length, "0");
|
|
765
767
|
if (parseInt(n))
|
|
766
768
|
return `${n}.${i.slice(0, t - n.length)}`.padEnd(
|
|
767
|
-
|
|
769
|
+
t - n.length,
|
|
768
770
|
"0"
|
|
769
771
|
);
|
|
770
772
|
const c = parseInt(i), u = `${c}`.slice(0, t);
|
|
@@ -791,8 +793,8 @@ const H = class H {
|
|
|
791
793
|
return `${(e / a).toFixed(t)}${i}`;
|
|
792
794
|
}
|
|
793
795
|
};
|
|
794
|
-
|
|
795
|
-
const r =
|
|
796
|
+
A = new WeakSet(), $ = function(t, ...e) {
|
|
797
|
+
const r = m(this, N, ht).call(this, this, ...e), n = S(r), i = e.reduce(
|
|
796
798
|
(c, u) => {
|
|
797
799
|
const l = this.getBigIntValue(u, r);
|
|
798
800
|
switch (t) {
|
|
@@ -819,56 +821,56 @@ w = new WeakSet(), S = function(t, ...e) {
|
|
|
819
821
|
value: i
|
|
820
822
|
});
|
|
821
823
|
return new this.constructor({ decimal: this.decimal, value: a, identifier: this.toString() });
|
|
822
|
-
}, P = new WeakSet(),
|
|
823
|
-
const e =
|
|
824
|
-
this.bigIntValue =
|
|
825
|
-
}, N = new WeakSet(),
|
|
824
|
+
}, P = new WeakSet(), lt = function(t) {
|
|
825
|
+
const e = m(this, T, C).call(this, t) || "0";
|
|
826
|
+
this.bigIntValue = m(this, B, W).call(this, e);
|
|
827
|
+
}, N = new WeakSet(), ht = function(...t) {
|
|
826
828
|
const e = t.map(
|
|
827
|
-
(r) => typeof r == "object" ? r.decimal || R(r.decimalMultiplier) :
|
|
829
|
+
(r) => typeof r == "object" ? r.decimal || R(r.decimalMultiplier) : m(this, O, G).call(this, m(this, T, C).call(this, r))
|
|
828
830
|
).filter(Boolean);
|
|
829
|
-
return Math.max(...e,
|
|
830
|
-
},
|
|
831
|
-
const r = e ?
|
|
831
|
+
return Math.max(...e, I);
|
|
832
|
+
}, B = new WeakSet(), W = function(t, e) {
|
|
833
|
+
const r = e ? S(e) : this.decimalMultiplier, n = R(r), [i = "", a = ""] = t.split(".");
|
|
832
834
|
return BigInt(`${i}${a.padEnd(n, "0")}`);
|
|
833
|
-
},
|
|
835
|
+
}, T = new WeakSet(), C = function(t) {
|
|
834
836
|
const r = `${typeof t == "number" ? Number(t).toLocaleString("fullwide", {
|
|
835
837
|
useGrouping: !1,
|
|
836
838
|
maximumFractionDigits: 20
|
|
837
|
-
}) :
|
|
839
|
+
}) : U(t)}`.replaceAll(",", ".").split(".");
|
|
838
840
|
return r.length > 1 ? `${r.slice(0, -1).join("")}.${r.at(-1)}` : r[0];
|
|
839
|
-
}, O = new WeakSet(),
|
|
841
|
+
}, O = new WeakSet(), G = function(t) {
|
|
840
842
|
var r;
|
|
841
843
|
const e = ((r = t.split(".")[1]) == null ? void 0 : r.length) || 0;
|
|
842
|
-
return Math.max(e,
|
|
844
|
+
return Math.max(e, I);
|
|
843
845
|
};
|
|
844
|
-
let
|
|
845
|
-
function
|
|
846
|
+
let E = K;
|
|
847
|
+
function U(s) {
|
|
846
848
|
return typeof s == "object" ? "getValue" in s ? s.getValue("string") : s.value : s;
|
|
847
849
|
}
|
|
848
|
-
const
|
|
849
|
-
let
|
|
850
|
-
const
|
|
851
|
-
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)
|
|
852
854
|
throw new Error("Static assets not loaded, call await AssetValue.loadStaticAssets() first");
|
|
853
|
-
return
|
|
855
|
+
return Y.get(s.toUpperCase()) || { decimal: d.THOR, identifier: "" };
|
|
854
856
|
}, st = async (s, t = 0) => {
|
|
855
857
|
Xt(s);
|
|
856
|
-
const e = await
|
|
857
|
-
return new
|
|
858
|
+
const e = await Rt(z(s)), r = k(t, e);
|
|
859
|
+
return new w({ decimal: e, value: r, identifier: s });
|
|
858
860
|
};
|
|
859
|
-
class
|
|
861
|
+
class w extends E {
|
|
860
862
|
constructor(e) {
|
|
861
863
|
super(
|
|
862
|
-
e.value instanceof
|
|
864
|
+
e.value instanceof E ? e.value : { decimal: e.decimal, value: e.value }
|
|
863
865
|
);
|
|
864
|
-
|
|
865
|
-
|
|
866
|
-
|
|
867
|
-
|
|
868
|
-
|
|
869
|
-
|
|
870
|
-
|
|
871
|
-
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);
|
|
872
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;
|
|
873
875
|
}
|
|
874
876
|
get assetValue() {
|
|
@@ -888,33 +890,21 @@ class _ extends I {
|
|
|
888
890
|
return st(e, r);
|
|
889
891
|
}
|
|
890
892
|
static fromStringSync(e, r = 0) {
|
|
891
|
-
const { isSynthetic: n } =
|
|
893
|
+
const { isSynthetic: n } = z(e), { decimal: i, identifier: a } = rt(
|
|
892
894
|
e
|
|
893
|
-
), c =
|
|
894
|
-
return a ? new
|
|
895
|
+
), c = k(r, i);
|
|
896
|
+
return a ? new w({ decimal: i, identifier: a, value: c }) : n ? new w({ decimal: 8, identifier: e, value: c }) : void 0;
|
|
895
897
|
}
|
|
896
898
|
static async fromIdentifier(e, r = 0) {
|
|
897
899
|
return st(e, r);
|
|
898
900
|
}
|
|
899
901
|
static fromIdentifierSync(e, r = 0) {
|
|
900
|
-
const { decimal: n, identifier: i } =
|
|
901
|
-
return new
|
|
902
|
+
const { decimal: n, identifier: i } = rt(e), a = k(r, n);
|
|
903
|
+
return new w({ decimal: n, identifier: i, value: a });
|
|
902
904
|
}
|
|
903
905
|
static fromChainOrSignature(e, r = 0) {
|
|
904
|
-
const { decimal: n, identifier: i } = Ct(e), a =
|
|
905
|
-
return new
|
|
906
|
-
}
|
|
907
|
-
static async fromTCQuote(e, r = 0) {
|
|
908
|
-
const n = await it(k(e)), i = this.shiftDecimals({ value: r, from: m.THOR, to: n });
|
|
909
|
-
return new _({ value: i, identifier: e, decimal: n });
|
|
910
|
-
}
|
|
911
|
-
static fromTCQuoteStatic(e, r = 0) {
|
|
912
|
-
const n = W(e), i = this.shiftDecimals({
|
|
913
|
-
value: r,
|
|
914
|
-
from: m.THOR,
|
|
915
|
-
to: n.decimal
|
|
916
|
-
});
|
|
917
|
-
return new _({ ...n, value: i });
|
|
906
|
+
const { decimal: n, identifier: i } = Ct(e), a = k(r, n);
|
|
907
|
+
return new w({ value: a, decimal: n, identifier: i });
|
|
918
908
|
}
|
|
919
909
|
static async loadStaticAssets() {
|
|
920
910
|
return new Promise(
|
|
@@ -927,9 +917,9 @@ class _ extends I {
|
|
|
927
917
|
NativeList: i,
|
|
928
918
|
...a
|
|
929
919
|
} = await import("@swapkit/tokens");
|
|
930
|
-
|
|
931
|
-
(u, { tokens: l }) => (l.forEach(({ identifier: h, chain:
|
|
932
|
-
const j = "decimals" in
|
|
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[_];
|
|
933
923
|
u.set(h, { identifier: h, decimal: j });
|
|
934
924
|
}), u),
|
|
935
925
|
/* @__PURE__ */ new Map()
|
|
@@ -945,8 +935,8 @@ class _ extends I {
|
|
|
945
935
|
);
|
|
946
936
|
}
|
|
947
937
|
}
|
|
948
|
-
const
|
|
949
|
-
const t =
|
|
938
|
+
const pe = (s) => {
|
|
939
|
+
const t = w.fromChainOrSignature(s);
|
|
950
940
|
switch (s) {
|
|
951
941
|
case o.Bitcoin:
|
|
952
942
|
case o.Litecoin:
|
|
@@ -963,7 +953,7 @@ const fe = (s) => {
|
|
|
963
953
|
default:
|
|
964
954
|
return t.add(1);
|
|
965
955
|
}
|
|
966
|
-
},
|
|
956
|
+
}, z = (s) => {
|
|
967
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("-");
|
|
968
958
|
return {
|
|
969
959
|
address: u == null ? void 0 : u.toLowerCase(),
|
|
@@ -1030,45 +1020,45 @@ const fe = (s) => {
|
|
|
1030
1020
|
*/
|
|
1031
1021
|
helpers_number_different_decimals: 99101
|
|
1032
1022
|
};
|
|
1033
|
-
class
|
|
1023
|
+
class dt extends Error {
|
|
1034
1024
|
constructor(t, e) {
|
|
1035
|
-
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);
|
|
1036
1026
|
}
|
|
1037
1027
|
}
|
|
1038
|
-
class
|
|
1028
|
+
class b extends E {
|
|
1039
1029
|
eq(t) {
|
|
1040
1030
|
return this.eqValue(t);
|
|
1041
1031
|
}
|
|
1042
1032
|
static fromBigInt(t, e) {
|
|
1043
|
-
return new
|
|
1033
|
+
return new b({
|
|
1044
1034
|
decimal: e,
|
|
1045
1035
|
value: x({ value: t, bigIntDecimal: e, decimal: e })
|
|
1046
1036
|
});
|
|
1047
1037
|
}
|
|
1048
1038
|
}
|
|
1049
1039
|
export {
|
|
1050
|
-
|
|
1051
|
-
|
|
1040
|
+
w as AssetValue,
|
|
1041
|
+
E as BigIntArithmetics,
|
|
1052
1042
|
Qt as RequestClient,
|
|
1053
|
-
|
|
1054
|
-
|
|
1043
|
+
dt as SwapKitError,
|
|
1044
|
+
b as SwapKitNumber,
|
|
1055
1045
|
se as assetFromString,
|
|
1056
1046
|
me as derivationPathToString,
|
|
1057
1047
|
ne as filterAssets,
|
|
1058
1048
|
x as formatBigIntToSafeValue,
|
|
1059
1049
|
re as gasFeeMultiplier,
|
|
1060
1050
|
It as getAssetType,
|
|
1061
|
-
|
|
1051
|
+
Ot as getAsymmetricAssetShare,
|
|
1062
1052
|
oe as getAsymmetricAssetWithdrawAmount,
|
|
1063
|
-
|
|
1053
|
+
Bt as getAsymmetricRuneShare,
|
|
1064
1054
|
ie as getAsymmetricRuneWithdrawAmount,
|
|
1065
1055
|
Ct as getCommonAssetInfo,
|
|
1066
|
-
|
|
1056
|
+
Rt as getDecimal,
|
|
1067
1057
|
ce as getEstimatedPoolShare,
|
|
1068
1058
|
ue as getLiquiditySlippage,
|
|
1069
1059
|
le as getMemoFor,
|
|
1070
|
-
|
|
1071
|
-
|
|
1060
|
+
pe as getMinAmountByChain,
|
|
1061
|
+
Vt as getSymmetricPoolShare,
|
|
1072
1062
|
ae as getSymmetricWithdraw,
|
|
1073
1063
|
he as getTHORNameCost,
|
|
1074
1064
|
$t as isGasAsset,
|
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",
|
package/src/helpers/liquidity.ts
CHANGED
|
@@ -81,7 +81,7 @@ export const getAsymmetricAssetWithdrawAmount = ({
|
|
|
81
81
|
getAsymmetricAssetShare({ assetDepth, liquidityUnits, poolUnits }).mul(percent);
|
|
82
82
|
|
|
83
83
|
const toTCSwapKitNumber = (value: string) =>
|
|
84
|
-
|
|
84
|
+
SwapKitNumber.fromBigInt(BigInt(value), BaseDecimal.THOR);
|
|
85
85
|
|
|
86
86
|
export const getSymmetricPoolShare = ({
|
|
87
87
|
liquidityUnits,
|
|
@@ -126,11 +126,11 @@ export const getEstimatedPoolShare = ({
|
|
|
126
126
|
runeDepth: string;
|
|
127
127
|
assetDepth: string;
|
|
128
128
|
}>) => {
|
|
129
|
-
const R =
|
|
130
|
-
const A =
|
|
131
|
-
const P =
|
|
132
|
-
const runeAddAmount =
|
|
133
|
-
const assetAddAmount =
|
|
129
|
+
const R = new SwapKitNumber({ value: runeDepth, decimal: 8 });
|
|
130
|
+
const A = new SwapKitNumber({ value: assetDepth, decimal: 8 });
|
|
131
|
+
const P = new SwapKitNumber({ value: poolUnits, decimal: 8 });
|
|
132
|
+
const runeAddAmount = new SwapKitNumber({ value: runeAmount, decimal: 8 });
|
|
133
|
+
const assetAddAmount = new SwapKitNumber({ value: assetAmount, decimal: 8 });
|
|
134
134
|
|
|
135
135
|
// liquidityUnits = P * (r*A + a*R + 2*r*a) / (r*A + a*R + 2*R*A)
|
|
136
136
|
const rA = runeAddAmount.mul(A);
|
|
@@ -142,14 +142,14 @@ export const getEstimatedPoolShare = ({
|
|
|
142
142
|
const liquidityUnitsAfterAdd = numerator.div(denominator);
|
|
143
143
|
const estimatedLiquidityUnits = toTCSwapKitNumber(liquidityUnits).add(liquidityUnitsAfterAdd);
|
|
144
144
|
|
|
145
|
-
if (liquidityUnitsAfterAdd.
|
|
146
|
-
return estimatedLiquidityUnits.div(P).
|
|
145
|
+
if (liquidityUnitsAfterAdd.getBaseValue('number') === 0) {
|
|
146
|
+
return estimatedLiquidityUnits.div(P).getBaseValue('number');
|
|
147
147
|
}
|
|
148
148
|
|
|
149
149
|
// get pool units after add
|
|
150
150
|
const newPoolUnits = P.add(estimatedLiquidityUnits);
|
|
151
151
|
|
|
152
|
-
return estimatedLiquidityUnits.div(newPoolUnits).
|
|
152
|
+
return estimatedLiquidityUnits.div(newPoolUnits).getBaseValue('number');
|
|
153
153
|
};
|
|
154
154
|
|
|
155
155
|
export const getLiquiditySlippage = ({
|
|
@@ -158,6 +158,8 @@ export const getLiquiditySlippage = ({
|
|
|
158
158
|
runeDepth,
|
|
159
159
|
assetDepth,
|
|
160
160
|
}: PoolParams) => {
|
|
161
|
+
if (runeAmount === '0' || assetAmount === '0' || runeDepth === '0' || assetDepth === '0')
|
|
162
|
+
return 0;
|
|
161
163
|
// formula: (t * R - T * r)/ (T*r + R*T)
|
|
162
164
|
const R = toTCSwapKitNumber(runeDepth);
|
|
163
165
|
const T = toTCSwapKitNumber(assetDepth);
|
|
@@ -168,5 +170,5 @@ export const getLiquiditySlippage = ({
|
|
|
168
170
|
const denominator = T.mul(runeAddAmount).add(R.mul(T));
|
|
169
171
|
|
|
170
172
|
// set absolute value of percent, no negative allowed
|
|
171
|
-
return Math.abs(numerator.div(denominator).
|
|
173
|
+
return Math.abs(numerator.div(denominator).getBaseValue('number'));
|
|
172
174
|
};
|
|
@@ -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
|
}
|
|
@@ -238,7 +238,7 @@ export class BigIntArithmetics {
|
|
|
238
238
|
|
|
239
239
|
if (parseInt(integer)) {
|
|
240
240
|
return `${integer}.${decimal.slice(0, significantDigits - integer.length)}`.padEnd(
|
|
241
|
-
|
|
241
|
+
significantDigits - integer.length,
|
|
242
242
|
'0',
|
|
243
243
|
);
|
|
244
244
|
}
|