@swapkit/helpers 1.0.0-rc.25 → 1.0.0-rc.27
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.es.js +243 -242
- package/package.json +5 -5
- package/src/modules/bigIntArithmetics.ts +28 -29
package/dist/index.cjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";var ve=Object.create;var H=Object.defineProperty;var Se=Object.getOwnPropertyDescriptor;var Re=Object.getOwnPropertyNames;var $e=Object.getPrototypeOf,Ie=Object.prototype.hasOwnProperty;var Be=(r,e,t)=>e in r?H(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t;var Ee=(r,e,t,s)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of Re(e))!Ie.call(r,n)&&n!==t&&H(r,n,{get:()=>e[n],enumerable:!(s=Se(e,n))||s.enumerable});return r};var Me=(r,e,t)=>(t=r!=null?ve($e(r)):{},Ee(e||!r||!r.__esModule?H(t,"default",{value:r,enumerable:!0}):t,r));var p=(r,e,t)=>(Be(r,typeof e!="symbol"?e+"":e,t),t),Oe=(r,e,t)=>{if(!e.has(r))throw TypeError("Cannot "+t)};var y=(r,e,t)=>{if(e.has(r))throw TypeError("Cannot add the same private member more than once");e instanceof WeakSet?e.add(r):e.set(r,t)};var d=(r,e,t)=>(Oe(r,e,"access private method"),t);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const i=require("@swapkit/types"),Ve="0x313ce567",ae=async({chain:r,to:e})=>{try{const{result:t}=await ye.post(i.ChainToRPC[r],{headers:{accept:"*/*","content-type":"application/json","cache-control":"no-cache"},body:JSON.stringify({id:44,jsonrpc:"2.0",method:"eth_call",params:[{to:e.toLowerCase(),data:Ve},"latest"]})});return parseInt(BigInt(t).toString())}catch(t){return console.error(t),i.BaseDecimal[r]}},qe=async r=>{if(r===i.Chain.Ethereum)return i.BaseDecimal.ETH;const[,e]=r.split("-");return e!=null&&e.startsWith("0x")?ae({chain:i.Chain.Ethereum,to:e}):i.BaseDecimal.ETH},Pe=async r=>{const[,e]=r.split("-");return e!=null&&e.startsWith("0x")?ae({chain:i.Chain.Avalanche,to:e.toLowerCase()}):i.BaseDecimal.AVAX},ke=async r=>(r===i.Chain.BinanceSmartChain,i.BaseDecimal.BSC),oe=async({chain:r,symbol:e})=>{switch(r){case i.Chain.Ethereum:return qe(e);case i.Chain.Avalanche:return Pe(e);case i.Chain.BinanceSmartChain:return ke(e);default:return i.BaseDecimal[r]}},xe={[i.FeeOption.Average]:1.2,[i.FeeOption.Fast]:1.5,[i.FeeOption.Fastest]:2},Y=({chain:r,symbol:e})=>{switch(r){case i.Chain.Bitcoin:case i.Chain.BitcoinCash:case i.Chain.Litecoin:case i.Chain.Dogecoin:case i.Chain.Binance:case i.Chain.Ethereum:case i.Chain.Avalanche:return e===r;case i.Chain.Arbitrum:case i.Chain.Optimism:return e==="ETH";case i.Chain.Maya:return e==="CACAO";case i.Chain.Kujira:return e==="KUJI";case i.Chain.Cosmos:return e==="ATOM";case i.Chain.Polygon:return e==="MATIC";case i.Chain.BinanceSmartChain:return e==="BNB";case i.Chain.THORChain:return e==="RUNE"}},ce=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]}}},ue=({chain:r,symbol:e})=>{if(e.includes("/"))return"Synth";switch(r){case i.Chain.Bitcoin:case i.Chain.BitcoinCash:case i.Chain.Dogecoin:case i.Chain.Litecoin:case i.Chain.Maya:case i.Chain.THORChain:return"Native";case i.Chain.Cosmos:return e==="ATOM"?"Native":i.Chain.Cosmos;case i.Chain.Kujira:return e===i.Chain.Kujira?"Native":i.Chain.Kujira;case i.Chain.Binance:return e===i.Chain.Binance?"Native":"BEP2";case i.Chain.BinanceSmartChain:return e===i.Chain.Binance?"Native":"BEP20";case i.Chain.Ethereum:return e===i.Chain.Ethereum?"Native":"ERC20";case i.Chain.Avalanche:return e===i.Chain.Avalanche?"Native":i.Chain.Avalanche;case i.Chain.Polygon:return e===i.Chain.Polygon?"Native":"POLYGON";case i.Chain.Arbitrum:return[i.Chain.Ethereum,i.Chain.Arbitrum].includes(e)?"Native":"ARBITRUM";case i.Chain.Optimism:return[i.Chain.Ethereum,i.Chain.Optimism].includes(e)?"Native":"OPTIMISM"}},Ne=r=>{var c;const[e,...t]=r.split("."),s=r.includes("/"),n=t.join("."),a=(c=n==null?void 0:n.split("-"))==null?void 0:c[0];return{chain:e,symbol:n,ticker:a,synth:s}},De=new RegExp(/(.)\1{6}|\.ORG|\.NET|\.FINANCE|\.COM|WWW|HTTP|\\\\|\/\/|[\s$%:[\]]/,"gmi"),He=r=>{const[e,t]=r.split(".");if(!i.EVMChainList.includes(e))return!0;const[,s]=t.split("-");return Y({chain:e,symbol:t})||!!s},je=r=>r.filter(e=>{const t=`${e.chain}.${e.symbol}`;return!De.test(t)&&He(t)&&e.value!=="0"}),le=({liquidityUnits:r,poolUnits:e,runeDepth:t})=>{const s=m(r),n=m(e),a=m(t),c=s.mul(a),o=n.mul(n).mul(2),u=n.mul(s).mul(2),l=s.mul(s),h=n.mul(n).mul(n);return c.mul(o.sub(u).add(l)).div(h)},he=({liquidityUnits:r,poolUnits:e,assetDepth:t})=>{const s=m(r),n=m(e),a=m(t),c=s.mul(a),o=n.mul(n).mul(2),u=n.mul(s).mul(2),l=s.mul(s),h=c.mul(o.sub(u).add(l)),g=n.mul(n).mul(n);return h.div(g)},Le=({percent:r,runeDepth:e,liquidityUnits:t,poolUnits:s})=>le({runeDepth:e,liquidityUnits:t,poolUnits:s}).mul(r),Fe=({percent:r,assetDepth:e,liquidityUnits:t,poolUnits:s})=>he({assetDepth:e,liquidityUnits:t,poolUnits:s}).mul(r),m=r=>f.fromBigInt(BigInt(r),i.BaseDecimal.THOR),de=({liquidityUnits:r,poolUnits:e,runeDepth:t,assetDepth:s})=>({assetAmount:m(s).mul(r).div(e),runeAmount:m(t).mul(r).div(e)}),Ue=({liquidityUnits:r,poolUnits:e,runeDepth:t,assetDepth:s,percent:n})=>Object.fromEntries(Object.entries(de({liquidityUnits:r,poolUnits:e,runeDepth:t,assetDepth:s})).map(([a,c])=>[a,c.mul(n)])),We=({runeDepth:r,poolUnits:e,assetDepth:t,liquidityUnits:s,runeAmount:n,assetAmount:a})=>{const c=new f({value:r,decimal:8}),o=new f({value:t,decimal:8}),u=new f({value:e,decimal:8}),l=new f({value:n,decimal:8}),h=new f({value:a,decimal:8}),g=l.mul(o),w=h.mul(c),N=l.mul(h),Ce=c.mul(o),we=u.mul(g.add(w.add(N.mul(2)))),Ae=g.add(w.add(Ce.mul(2))),X=we.div(Ae),D=m(s).add(X);if(X.getBaseValue("number")===0)return D.div(u).getBaseValue("number");const Te=u.add(D);return D.div(Te).getBaseValue("number")},Ge=({runeAmount:r,assetAmount:e,runeDepth:t,assetDepth:s})=>{if(r==="0"||e==="0"||t==="0"||s==="0")return 0;const n=m(t),a=m(s),c=m(e),o=m(r),u=c.mul(n).sub(a.mul(o)),l=a.mul(o).add(n.mul(a));return Math.abs(u.div(l).getBaseValue("number"))},Ke=({symbol:r,ticker:e,chain:t})=>t==="ETH"&&e!=="ETH"?`${e}-${r.slice(-3)}`:r,Ye=(r,e)=>{switch(r){case i.MemoType.LEAVE:case i.MemoType.BOND:{const{address:t}=e;return`${r}:${t}`}case i.MemoType.UNBOND:{const{address:t,unbondAmount:s}=e;return`${r}:${t}:${s*10**8}`}case i.MemoType.THORNAME_REGISTER:{const{name:t,chain:s,address:n,owner:a}=e;return`${r}:${t}:${s}:${n}${a?`:${a}`:""}`}case i.MemoType.DEPOSIT:{const{chain:t,symbol:s,address:n,singleSide:a}=e;return a?`${r}:${t}/${s}::t:0`:`${r}:${t}.${s}:${n||""}:t:0`}case i.MemoType.WITHDRAW:{const{chain:t,ticker:s,symbol:n,basisPoints:a,targetAssetString:c,singleSide:o}=e,u=!o&&c?`:${c}`:"",l=Ke({chain:t,symbol:n,ticker:s});return`${r}:${t}${o?"/":"."}${l}:${a}${u}`}case i.MemoType.OPEN_LOAN:case i.MemoType.CLOSE_LOAN:{const{asset:t,address:s}=e;return`${r}:${t}:${s}`}default:return""}},ze=r=>{if(r<0)throw new Error("Invalid number of year");return 10+r},Je=r=>{if(r.length>30)return!1;const e=/^[a-zA-Z0-9+_-]+$/g;return!!r.match(e)},Qe=([r,e,t,s,n])=>`${r}'/${e}'/${t}'/${s}${typeof n!="number"?"":`/${n}`}`;class Z extends Error{constructor(e,t,s){const n=e.status||e.status===0?e.status:"",a=e.statusText||"",c=`${n} ${a}`.trim(),o=c?`status code ${c}`:"an unknown error";super(`Request failed with ${o}`),Object.defineProperty(this,"response",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"request",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"options",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.name="HTTPError",this.response=e,this.request=t,this.options=s}}class me 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 q=r=>r!==null&&typeof r=="object",O=(...r)=>{for(const e of r)if((!q(e)||Array.isArray(e))&&e!==void 0)throw new TypeError("The `options` argument must be an object");return z({},...r)},pe=(r={},e={})=>{const t=new globalThis.Headers(r),s=e instanceof globalThis.Headers,n=new globalThis.Headers(e);for(const[a,c]of n.entries())s&&c==="undefined"||c===void 0?t.delete(a):t.set(a,c);return t},z=(...r)=>{let e={},t={};for(const s of r)if(Array.isArray(s))Array.isArray(e)||(e=[]),e=[...e,...s];else if(q(s)){for(let[n,a]of Object.entries(s))q(a)&&n in e&&(a=z(e[n],a)),e={...e,[n]:a};q(s.headers)&&(t=pe(t,s.headers),e.headers=t)}return e},Xe=(()=>{let r=!1,e=!1;const t=typeof globalThis.ReadableStream=="function",s=typeof globalThis.Request=="function";return t&&s&&(e=new globalThis.Request("https://empty.invalid",{body:new globalThis.ReadableStream,method:"POST",get duplex(){return r=!0,"half"}}).headers.has("Content-Type")),r&&!e})(),Ze=typeof globalThis.AbortController=="function",et=typeof globalThis.ReadableStream=="function",tt=typeof globalThis.FormData=="function",fe=["get","post","put","patch","head","delete"],st={json:"application/json",text:"text/*",formData:"multipart/form-data",arrayBuffer:"*/*",blob:"*/*"},j=2147483647,ge=Symbol("stop"),rt={json:!0,parseJson:!0,searchParams:!0,prefixUrl:!0,retry:!0,timeout:!0,hooks:!0,throwHttpErrors:!0,onDownloadProgress:!0,fetch:!0},nt={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},it=r=>fe.includes(r)?r.toUpperCase():r,at=["get","put","head","delete","options","trace"],ot=[408,413,429,500,502,503,504],_e=[413,429,503],ee={limit:2,methods:at,statusCodes:ot,afterStatusCodes:_e,maxRetryAfter:Number.POSITIVE_INFINITY,backoffLimit:Number.POSITIVE_INFINITY,delay:r=>.3*2**(r-1)*1e3},ct=(r={})=>{if(typeof r=="number")return{...ee,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{...ee,...r,afterStatusCodes:_e}};async function ut(r,e,t,s){return new Promise((n,a)=>{const c=setTimeout(()=>{t&&t.abort(),a(new me(r))},s.timeout);s.fetch(r,e).then(n).catch(a).then(()=>{clearTimeout(c)})})}async function lt(r,{signal:e}){return new Promise((t,s)=>{e&&(e.throwIfAborted(),e.addEventListener("abort",n,{once:!0}));function n(){clearTimeout(a),s(e.reason)}const a=setTimeout(()=>{e==null||e.removeEventListener("abort",n),t()},r)})}const ht=(r,e)=>{const t={};for(const s in e)!(s in nt)&&!(s in rt)&&!(s in r)&&(t[s]=e[s]);return t};class k{static create(e,t){const s=new k(e,t),n=async()=>{if(typeof s._options.timeout=="number"&&s._options.timeout>j)throw new RangeError(`The \`timeout\` option cannot be greater than ${j}`);await Promise.resolve();let o=await s._fetch();for(const u of s._options.hooks.afterResponse){const l=await u(s.request,s._options,s._decorateResponse(o.clone()));l instanceof globalThis.Response&&(o=l)}if(s._decorateResponse(o),!o.ok&&s._options.throwHttpErrors){let u=new Z(o,s.request,s._options);for(const l of s._options.hooks.beforeError)u=await l(u);throw u}if(s._options.onDownloadProgress){if(typeof s._options.onDownloadProgress!="function")throw new TypeError("The `onDownloadProgress` option must be a function");if(!et)throw new Error("Streams are not supported in your environment. `ReadableStream` is missing.");return s._stream(o.clone(),s._options.onDownloadProgress)}return o},c=s._options.retry.methods.includes(s.request.method.toLowerCase())?s._retry(n):n();for(const[o,u]of Object.entries(st))c[o]=async()=>{s.request.headers.set("accept",s.request.headers.get("accept")||u);const h=(await c).clone();if(o==="json"){if(h.status===204||(await h.clone().arrayBuffer()).byteLength===0)return"";if(t.parseJson)return t.parseJson(await h.text())}return h[o]()};return c}constructor(e,t={}){if(Object.defineProperty(this,"request",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"abortController",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_retryCount",{enumerable:!0,configurable:!0,writable:!0,value:0}),Object.defineProperty(this,"_input",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_options",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this._input=e,this._options={credentials:this._input.credentials||"same-origin",...t,headers:pe(this._input.headers,t.headers),hooks:z({beforeRequest:[],beforeRetry:[],beforeError:[],afterResponse:[]},t.hooks),method:it(t.method??this._input.method),prefixUrl:String(t.prefixUrl||""),retry:ct(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(Ze){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(Xe&&(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);(tt&&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 me)){if(e instanceof Z){if(!this._options.retry.statusCodes.includes(e.response.status))return 0;const s=e.response.headers.get("Retry-After");if(s&&this._options.retry.afterStatusCodes.includes(e.response.status)){let n=Number(s);return Number.isNaN(n)?n=Date.parse(s)-Date.now():n*=1e3,this._options.retry.maxRetryAfter!==void 0&&n>this._options.retry.maxRetryAfter?0:n}if(e.response.status===413)return 0}const t=this._options.retry.delay(this._retryCount);return Math.min(this._options.retry.backoffLimit,t)}return 0}_decorateResponse(e){return this._options.parseJson&&(e.json=async()=>this._options.parseJson(await e.text())),e}async _retry(e){try{return await e()}catch(t){const s=Math.min(this._calculateRetryDelay(t),j);if(s!==0&&this._retryCount>0){await lt(s,{signal:this._options.signal});for(const n of this._options.hooks.beforeRetry)if(await n({request:this.request,options:this._options,error:t,retryCount:this._retryCount})===ge)return;return this._retry(e)}throw t}}async _fetch(){for(const t of this._options.hooks.beforeRequest){const s=await t(this.request,this._options);if(s instanceof Request){this.request=s;break}if(s instanceof Response)return s}const e=ht(this.request,this._options);return this._options.timeout===!1?this._options.fetch(this.request.clone(),e):ut(this.request.clone(),e,this.abortController,this._options)}_stream(e,t){const s=Number(e.headers.get("content-length"))||0;let n=0;return e.status===204?(t&&t({percent:1,totalBytes:s,transferredBytes:n},new Uint8Array),new globalThis.Response(null,{status:e.status,statusText:e.statusText,headers:e.headers})):new globalThis.Response(new globalThis.ReadableStream({async start(a){const c=e.body.getReader();t&&t({percent:0,transferredBytes:0,totalBytes:s},new Uint8Array);async function o(){const{done:u,value:l}=await c.read();if(u){a.close();return}if(t){n+=l.byteLength;const h=s===0?0:n/s;t({percent:h,transferredBytes:n,totalBytes:s},l)}a.enqueue(l),await o()}await o()}}),{status:e.status,statusText:e.statusText,headers:e.headers})}}/*! MIT License © Sindre Sorhus */const L=r=>{const e=(t,s)=>k.create(t,O(r,s));for(const t of fe)e[t]=(s,n)=>k.create(s,O(r,n,{method:t}));return e.create=t=>L(O(t)),e.extend=t=>L(O(r,t)),e.stop=ge,e},dt=L(),mt=dt,pt=typeof window<"u"?{}:{referrer:"https://sk.thorswap.net",referer:"https://sk.thorswap.net"},te=mt.create({headers:pt}),ye={get:(r,e)=>te.get(r,e).json(),post:(r,e)=>te.post(r,e).json()},se=Object.values(i.Chain),ft=(r="")=>{const e=r.toUpperCase(),[t]=e.split(".");if(se.includes(t))return!0;const[s]=e.split("/");if(se.includes(s))return!0;throw new Error(`Invalid identifier: ${r}. Expected format: <Chain>.<Ticker> or <Chain>.<Ticker>-<ContractAddress>`)},$=8,A=r=>10n**BigInt(r),v=r=>Math.log10(parseFloat(r.toString()));function I({value:r,bigIntDecimal:e=$,decimal:t=$}){const s=r<0n;let n=r.toString().substring(s?1:0);const a=t-(n.length-1);a>0&&(n="0".repeat(a)+n);const c=n.length-t;let o=n.slice(-t);return parseInt(o[e])>=5?o=`${o.substring(0,e-1)}${(parseInt(o[e-1])+1).toString()}`:o=o.substring(0,e),`${s?"-":""}${n.slice(0,c)}.${o}`.replace(/\.?0*$/,"")}var b,S,B,F,x,be,E,U,C,R,M,W;const Q=class Q{constructor(e){y(this,b);y(this,B);y(this,x);y(this,E);y(this,C);y(this,M);p(this,"decimalMultiplier",10n**8n);p(this,"bigIntValue",0n);p(this,"decimal");const t=V(e);this.decimal=typeof e=="object"?e.decimal:void 0,this.decimalMultiplier=A(Math.max(d(this,M,W).call(this,d(this,C,R).call(this,t)),this.decimal||0)),d(this,B,F).call(this,t)}static fromBigInt(e,t){return new Q({decimal:t,value:I({value:e,bigIntDecimal:t,decimal:t})})}static shiftDecimals({value:e,from:t,to:s}){return this.fromBigInt(e.getBaseValue("bigint")*A(s)/A(t),s)}set(e){return d(this,B,F).call(this,V(e)),this}add(...e){return d(this,b,S).call(this,"add",...e)}sub(...e){return d(this,b,S).call(this,"sub",...e)}mul(...e){return d(this,b,S).call(this,"mul",...e)}div(...e){return d(this,b,S).call(this,"div",...e)}gt(e){return this.bigIntValue>this.getBigIntValue(e)}gte(e){return this.bigIntValue>=this.getBigIntValue(e)}lt(e){return this.bigIntValue<this.getBigIntValue(e)}lte(e){return this.bigIntValue<=this.getBigIntValue(e)}eqValue(e){return this.bigIntValue===this.getBigIntValue(e)}getValue(e){const t=this.formatBigIntToSafeValue(this.bigIntValue,this.decimal||v(this.decimalMultiplier));switch(e){case"number":return Number(t);case"string":return t;default:return this.bigIntValue*BigInt(this.decimal||8n)/this.decimalMultiplier}}getBaseValue(e){const t=this.decimalMultiplier/A(this.decimal||i.BaseDecimal.THOR),s=this.bigIntValue/t;switch(e){case"number":return Number(s);case"string":return s.toString();default:return s}}getBigIntValue(e,t){if(!t&&typeof e=="object")return e.bigIntValue;const s=V(e),n=d(this,C,R).call(this,s);return n==="0"||n==="undefined"?0n:d(this,E,U).call(this,n,t)}formatBigIntToSafeValue(e,t){const s=t||this.decimal||$,n=Math.max(s,v(this.decimalMultiplier)),a=e<0n,c=e.toString().substring(a?1:0),o=n-(c.length-1),u=o>0?"0".repeat(o)+c:c,l=u.length-n;let h=u.slice(-n);return parseInt(h[s])>=5?h=`${h.substring(0,s-1)}${(parseInt(h[s-1])+1).toString()}`:h=h.substring(0,s),`${a?"-":""}${u.slice(0,l)}.${h}`.replace(/\.?0*$/,"")}toSignificant(e=6){const[t,s]=this.getValue("string").split("."),n=t||"",a=s||"";if((parseInt(n)?n.length+a.length:a.length)<=e)return this.getValue("string");if(n.length>=e)return n.slice(0,e).padEnd(n.length,"0");if(parseInt(n))return`${n}.${a.slice(0,e-n.length)}`.padEnd(e-n.length,"0");const o=parseInt(a),u=`${o}`.slice(0,e);return`0.${u.padStart(a.length-`${o}`.length+u.length,"0")}`}toFixed(e=6){const[t,s]=this.getValue("string").split("."),n=t||"",a=s||"";if(parseInt(n))return`${n}.${a.slice(0,e)}`.padEnd(e,"0");const c=parseInt(a),o=`${c}`.slice(0,e);return`0.${o.padStart(a.length-`${c}`.length+o.length,"0")}`}toAbbreviation(e=2){const t=this.getValue("number"),s=["","K","M","B","T","Q","Qi","S"],n=Math.floor(Math.log10(Math.abs(t))/3),a=s[n];if(!a)return this.getValue("string");const c=10**(n*3);return`${(t/c).toFixed(e)}${a}`}toCurrency(e="$",{currencyPosition:t="start",decimal:s=2,decimalSeparator:n=".",thousandSeparator:a=","}={}){const c=this.getValue("number"),[o,u=""]=c.toFixed(6).split("."),l=o.replace(/\B(?=(\d{3})+(?!\d))/g,a),h=!o&&!u?"0.00":o==="0"?`${parseFloat(`0.${u}`)}`.replace(".",n):`${l}${u?`${n}${u.slice(0,s)}`:""}`;return`${t==="start"?e:""}${h}${t==="end"?e:""}`}};b=new WeakSet,S=function(e,...t){const s=d(this,x,be).call(this,this,...t),n=A(s),a=t.reduce((o,u)=>{const l=this.getBigIntValue(u,s);switch(e){case"add":return o+l;case"sub":return o-l;case"mul":return o*l/n;case"div":{if(l===0n)throw new RangeError("Division by zero");return o*n/l}default:return o}},this.bigIntValue*n/this.decimalMultiplier),c=I({bigIntDecimal:s,decimal:Math.max(s,v(this.decimalMultiplier)),value:a});return new this.constructor({decimal:this.decimal,value:c,identifier:this.toString()})},B=new WeakSet,F=function(e){const t=d(this,C,R).call(this,e)||"0";this.bigIntValue=d(this,E,U).call(this,t)},x=new WeakSet,be=function(...e){const t=e.map(s=>typeof s=="object"?s.decimal||v(s.decimalMultiplier):d(this,M,W).call(this,d(this,C,R).call(this,s))).filter(Boolean);return Math.max(...t,$)},E=new WeakSet,U=function(e,t){const s=t?A(t):this.decimalMultiplier,n=v(s),[a="",c=""]=e.split(".");return BigInt(`${a}${c.padEnd(n,"0")}`)},C=new WeakSet,R=function(e){const s=`${typeof e=="number"?Number(e).toLocaleString("fullwide",{useGrouping:!1,maximumFractionDigits:20}):V(e)}`.replaceAll(",",".").split(".");return s.length>1?`${s.slice(0,-1).join("")}.${s.at(-1)}`:s[0]},M=new WeakSet,W=function(e){var s;const t=((s=e.split(".")[1])==null?void 0:s.length)||0;return Math.max(t,$)};let T=Q;function V(r){return typeof r=="object"?"getValue"in r?r.getValue("string"):r.value:r}const P=(r,e)=>typeof r=="bigint"?I({value:r,bigIntDecimal:e,decimal:e}):r;let G;const re=r=>{if(!G)throw new Error("Static assets not loaded, call await AssetValue.loadStaticAssets() first");return G.get(r.toUpperCase())||{decimal:i.BaseDecimal.THOR,identifier:""}},ne=async(r,e=0)=>{ft(r);const t=await oe(K(r)),s=P(e,t);return new _({decimal:t,value:s,identifier:r})},ie=new Map;class _ extends T{constructor(t){const s="identifier"in t?t.identifier:`${t.chain}.${t.symbol}`,n=ie.get(s);if(n)return n.set(t.value);super(t.value instanceof T?t.value:{decimal:t.decimal,value:t.value});p(this,"address");p(this,"isSynthetic",!1);p(this,"isGasAsset",!1);p(this,"chain");p(this,"symbol");p(this,"ticker");p(this,"type");const a=K(s);this.type=ue(a),this.chain=a.chain,this.ticker=a.ticker,this.symbol=a.symbol,this.address=a.address,this.isSynthetic=a.isSynthetic,this.isGasAsset=a.isGasAsset,ie.set(s,this)}toString(t=!1){const s=this.isSynthetic?this.symbol.split("-")[0]:this.ticker;return t?s:`${this.chain}.${this.symbol}`}eq({chain:t,symbol:s}){return this.chain===t&&this.symbol===s}static async fromString(t,s=0){return ne(t,s)}static fromStringSync(t,s=0){const{isSynthetic:n}=K(t),{decimal:a,identifier:c}=re(t),o=P(s,a);return c?new _({decimal:a,identifier:c,value:o}):n?new _({decimal:8,identifier:t,value:o}):void 0}static async fromIdentifier(t,s=0){return ne(t,s)}static fromIdentifierSync(t,s=0){const{decimal:n,identifier:a}=re(t),c=P(s,n);return new _({decimal:n,identifier:a,value:c})}static fromChainOrSignature(t,s=0){const{decimal:n,identifier:a}=ce(t),c=P(s,n);return new _({value:c,decimal:n,identifier:a})}static async loadStaticAssets(){return new Promise(async(t,s)=>{try{const{ThorchainList:n,NativeList:a,...c}=await import("@swapkit/tokens");G=[a,...Object.values(c)].reduce((u,{tokens:l})=>(l.forEach(({identifier:h,chain:g,...w})=>{const N="decimals"in w?w.decimals:i.BaseDecimal[g];u.set(h,{identifier:h,decimal:N})}),u),new Map),t({ok:!0})}catch(n){console.error(n),s({ok:!1,error:n,message:"Couldn't load static assets. Ensure you have installed @swapkit/tokens package"})}})}}const gt=r=>{const e=_.fromChainOrSignature(r);switch(r){case i.Chain.Bitcoin:case i.Chain.Litecoin:case i.Chain.BitcoinCash:return e.set(10001e-8);case i.Chain.Dogecoin:return e.set(1.00000001);case i.Chain.Avalanche:case i.Chain.Ethereum:return e.set(1e-8);case i.Chain.THORChain:case i.Chain.Maya:return e.set(0);default:return e.set(1e-8)}},K=r=>{const e=r.slice(0,14).includes("/"),[t,s]=r.split(".").pop().split("/"),n=r.includes(".")&&!e?r:`${i.Chain.THORChain}.${s}`,[a,c]=n.split("."),[o,u]=(e?s:c).split("-");return{address:u==null?void 0:u.toLowerCase(),chain:a,isGasAsset:Y({chain:a,symbol:c}),isSynthetic:e,symbol:(e?`${t}/`:"")+(u?`${o}-${(u==null?void 0:u.toLowerCase())??""}`:c),ticker:o}},_t={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 J extends Error{constructor(e,t){console.error(t),super(e,{cause:{code:_t[e],message:e}}),Object.setPrototypeOf(this,J.prototype)}}class f extends T{eq(e){return this.eqValue(e)}static fromBigInt(e,t){return new f({decimal:t,value:I({value:e,bigIntDecimal:t,decimal:t})})}}exports.AssetValue=_;exports.BigIntArithmetics=T;exports.RequestClient=ye;exports.SwapKitError=J;exports.SwapKitNumber=f;exports.assetFromString=Ne;exports.derivationPathToString=Qe;exports.filterAssets=je;exports.formatBigIntToSafeValue=I;exports.gasFeeMultiplier=xe;exports.getAssetType=ue;exports.getAsymmetricAssetShare=he;exports.getAsymmetricAssetWithdrawAmount=Fe;exports.getAsymmetricRuneShare=le;exports.getAsymmetricRuneWithdrawAmount=Le;exports.getCommonAssetInfo=ce;exports.getDecimal=oe;exports.getEstimatedPoolShare=We;exports.getLiquiditySlippage=Ge;exports.getMemoFor=Ye;exports.getMinAmountByChain=gt;exports.getSymmetricPoolShare=de;exports.getSymmetricWithdraw=Ue;exports.getTHORNameCost=ze;exports.isGasAsset=Y;exports.validateTHORName=Je;
|
|
1
|
+
"use strict";var Ae=Object.create;var N=Object.defineProperty;var Te=Object.getOwnPropertyDescriptor;var ve=Object.getOwnPropertyNames;var Se=Object.getPrototypeOf,Re=Object.prototype.hasOwnProperty;var $e=(s,e,t)=>e in s?N(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))!Re.call(s,n)&&n!==t&&N(s,n,{get:()=>e[n],enumerable:!(r=Te(e,n))||r.enumerable});return s};var Be=(s,e,t)=>(t=s!=null?Ae(Se(s)):{},Ie(e||!s||!s.__esModule?N(t,"default",{value:s,enumerable:!0}):t,s));var m=(s,e,t)=>($e(s,typeof e!="symbol"?e+"":e,t),t),Ee=(s,e,t)=>{if(!e.has(s))throw TypeError("Cannot "+t)};var A=(s,e,t)=>{if(e.has(s))throw TypeError("Cannot add the same private member more than once");e instanceof WeakSet?e.add(s):e.set(s,t)};var p=(s,e,t)=>(Ee(s,e,"access private method"),t);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const i=require("@swapkit/types"),Me="0x313ce567",ne=async({chain:s,to:e})=>{try{const{result:t}=await ge.post(i.ChainToRPC[s],{headers:{accept:"*/*","content-type":"application/json","cache-control":"no-cache"},body:JSON.stringify({id:44,jsonrpc:"2.0",method:"eth_call",params:[{to:e.toLowerCase(),data:Me},"latest"]})});return parseInt(BigInt(t).toString())}catch(t){return console.error(t),i.BaseDecimal[s]}},Oe=async s=>{if(s===i.Chain.Ethereum)return i.BaseDecimal.ETH;const[,e]=s.split("-");return e!=null&&e.startsWith("0x")?ne({chain:i.Chain.Ethereum,to:e}):i.BaseDecimal.ETH},Ve=async s=>{const[,e]=s.split("-");return e!=null&&e.startsWith("0x")?ne({chain:i.Chain.Avalanche,to:e.toLowerCase()}):i.BaseDecimal.AVAX},qe=async s=>(s===i.Chain.BinanceSmartChain,i.BaseDecimal.BSC),ie=async({chain:s,symbol:e})=>{switch(s){case i.Chain.Ethereum:return Oe(e);case i.Chain.Avalanche:return Ve(e);case i.Chain.BinanceSmartChain:return qe(e);default:return i.BaseDecimal[s]}},Pe={[i.FeeOption.Average]:1.2,[i.FeeOption.Fast]:1.5,[i.FeeOption.Fastest]:2},W=({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"}},ke=s=>{var c;const[e,...t]=s.split("."),r=s.includes("/"),n=t.join("."),a=(c=n==null?void 0:n.split("-"))==null?void 0:c[0];return{chain:e,symbol:n,ticker:a,synth:r}},xe=new RegExp(/(.)\1{6}|\.ORG|\.NET|\.FINANCE|\.COM|WWW|HTTP|\\\\|\/\/|[\s$%:[\]]/,"gmi"),Ne=s=>{const[e,t]=s.split(".");if(!i.EVMChainList.includes(e))return!0;const[,r]=t.split("-");return W({chain:e,symbol:t})||!!r},De=s=>s.filter(e=>{const t=`${e.chain}.${e.symbol}`;return!xe.test(t)&&Ne(t)&&e.value!=="0"}),ce=({liquidityUnits:s,poolUnits:e,runeDepth:t})=>{const r=d(s),n=d(e),a=d(t),c=r.mul(a),o=n.mul(n).mul(2),u=n.mul(r).mul(2),l=r.mul(r),h=n.mul(n).mul(n);return c.mul(o.sub(u).add(l)).div(h)},ue=({liquidityUnits:s,poolUnits:e,assetDepth:t})=>{const r=d(s),n=d(e),a=d(t),c=r.mul(a),o=n.mul(n).mul(2),u=n.mul(r).mul(2),l=r.mul(r),h=c.mul(o.sub(u).add(l)),g=n.mul(n).mul(n);return h.div(g)},He=({percent:s,runeDepth:e,liquidityUnits:t,poolUnits:r})=>ce({runeDepth:e,liquidityUnits:t,poolUnits:r}).mul(s),je=({percent:s,assetDepth:e,liquidityUnits:t,poolUnits:r})=>ue({assetDepth:e,liquidityUnits:t,poolUnits:r}).mul(s),d=s=>f.fromBigInt(BigInt(s),i.BaseDecimal.THOR),le=({liquidityUnits:s,poolUnits:e,runeDepth:t,assetDepth:r})=>({assetAmount:d(r).mul(s).div(e),runeAmount:d(t).mul(s).div(e)}),Le=({liquidityUnits:s,poolUnits:e,runeDepth:t,assetDepth:r,percent:n})=>Object.fromEntries(Object.entries(le({liquidityUnits:s,poolUnits:e,runeDepth:t,assetDepth:r})).map(([a,c])=>[a,c.mul(n)])),Fe=({runeDepth:s,poolUnits:e,assetDepth:t,liquidityUnits:r,runeAmount:n,assetAmount:a})=>{const c=new f({value:s,decimal:8}),o=new f({value:t,decimal:8}),u=new f({value:e,decimal:8}),l=new f({value:n,decimal:8}),h=new f({value:a,decimal:8}),g=l.mul(o),b=h.mul(c),k=l.mul(h),ye=c.mul(o),be=u.mul(g.add(b.add(k.mul(2)))),Ce=g.add(b.add(ye.mul(2))),z=be.div(Ce),x=d(r).add(z);if(z.getBaseValue("number")===0)return x.div(u).getBaseValue("number");const we=u.add(x);return x.div(we).getBaseValue("number")},Ue=({runeAmount:s,assetAmount:e,runeDepth:t,assetDepth:r})=>{if(s==="0"||e==="0"||t==="0"||r==="0")return 0;const n=d(t),a=d(r),c=d(e),o=d(s),u=c.mul(n).sub(a.mul(o)),l=a.mul(o).add(n.mul(a));return Math.abs(u.div(l).getBaseValue("number"))},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:c,singleSide:o}=e,u=!o&&c?`:${c}`:"",l=We({chain:t,symbol:n,ticker:r});return`${s}:${t}${o?"/":"."}${l}:${a}${u}`}case i.MemoType.OPEN_LOAN:case i.MemoType.CLOSE_LOAN:{const{asset:t,address:r}=e;return`${s}:${t}:${r}`}default:return""}},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 J extends Error{constructor(e,t,r){const n=e.status||e.status===0?e.status:"",a=e.statusText||"",c=`${n} ${a}`.trim(),o=c?`status code ${c}`:"an unknown error";super(`Request failed with ${o}`),Object.defineProperty(this,"response",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"request",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"options",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.name="HTTPError",this.response=e,this.request=t,this.options=r}}class 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",B=(...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 G({},...s)},de=(s={},e={})=>{const t=new globalThis.Headers(s),r=e instanceof globalThis.Headers,n=new globalThis.Headers(e);for(const[a,c]of n.entries())r&&c==="undefined"||c===void 0?t.delete(a):t.set(a,c);return t},G=(...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=G(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:"*/*"},D=2147483647,pe=Symbol("stop"),tt={json:!0,parseJson:!0,searchParams:!0,prefixUrl:!0,retry:!0,timeout:!0,hooks:!0,throwHttpErrors:!0,onDownloadProgress:!0,fetch:!0},st={method:!0,headers:!0,body:!0,mode:!0,credentials:!0,cache:!0,redirect:!0,referrer:!0,referrerPolicy:!0,integrity:!0,keepalive:!0,signal:!0,window:!0,dispatcher:!0,duplex:!0},rt=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],Q={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{...Q,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{...Q,...s,afterStatusCodes:fe}};async function ot(s,e,t,r){return new Promise((n,a)=>{const c=setTimeout(()=>{t&&t.abort(),a(new he(s))},r.timeout);r.fetch(s,e).then(n).catch(a).then(()=>{clearTimeout(c)})})}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 st)&&!(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>D)throw new RangeError(`The \`timeout\` option cannot be greater than ${D}`);await Promise.resolve();let o=await r._fetch();for(const u of r._options.hooks.afterResponse){const l=await u(r.request,r._options,r._decorateResponse(o.clone()));l instanceof globalThis.Response&&(o=l)}if(r._decorateResponse(o),!o.ok&&r._options.throwHttpErrors){let u=new J(o,r.request,r._options);for(const l of r._options.hooks.beforeError)u=await l(u);throw u}if(r._options.onDownloadProgress){if(typeof r._options.onDownloadProgress!="function")throw new TypeError("The `onDownloadProgress` option must be a function");if(!Xe)throw new Error("Streams are not supported in your environment. `ReadableStream` is missing.");return r._stream(o.clone(),r._options.onDownloadProgress)}return o},c=r._options.retry.methods.includes(r.request.method.toLowerCase())?r._retry(n):n();for(const[o,u]of Object.entries(et))c[o]=async()=>{r.request.headers.set("accept",r.request.headers.get("accept")||u);const h=(await c).clone();if(o==="json"){if(h.status===204||(await h.clone().arrayBuffer()).byteLength===0)return"";if(t.parseJson)return t.parseJson(await h.text())}return h[o]()};return c}constructor(e,t={}){if(Object.defineProperty(this,"request",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"abortController",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_retryCount",{enumerable:!0,configurable:!0,writable:!0,value:0}),Object.defineProperty(this,"_input",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_options",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this._input=e,this._options={credentials:this._input.credentials||"same-origin",...t,headers:de(this._input.headers,t.headers),hooks:G({beforeRequest:[],beforeRetry:[],beforeError:[],afterResponse:[]},t.hooks),method:rt(t.method??this._input.method),prefixUrl:String(t.prefixUrl||""),retry:at(t.retry),throwHttpErrors:t.throwHttpErrors!==!1,timeout:t.timeout??1e4,fetch:t.fetch??globalThis.fetch.bind(globalThis)},typeof this._input!="string"&&!(this._input instanceof URL||this._input instanceof globalThis.Request))throw new TypeError("`input` must be a string, URL, or Request");if(this._options.prefixUrl&&typeof this._input=="string"){if(this._input.startsWith("/"))throw new Error("`input` must not begin with a slash when using `prefixUrl`");this._options.prefixUrl.endsWith("/")||(this._options.prefixUrl+="/"),this._input=this._options.prefixUrl+this._input}if(Qe){if(this.abortController=new globalThis.AbortController,this._options.signal){const 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 J){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),D);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 c=e.body.getReader();t&&t({percent:0,transferredBytes:0,totalBytes:r},new Uint8Array);async function o(){const{done:u,value:l}=await c.read();if(u){a.close();return}if(t){n+=l.byteLength;const h=r===0?0:n/r;t({percent:h,transferredBytes:n,totalBytes:r},l)}a.enqueue(l),await o()}await o()}}),{status:e.status,statusText:e.statusText,headers:e.headers})}}/*! MIT License © Sindre Sorhus */const H=s=>{const e=(t,r)=>q.create(t,B(s,r));for(const t of me)e[t]=(r,n)=>q.create(r,B(s,n,{method:t}));return e.create=t=>H(B(t)),e.extend=t=>H(B(s,t)),e.stop=pe,e},lt=H(),ht=lt,dt=typeof window<"u"?{}:{referrer:"https://sk.thorswap.net",referer:"https://sk.thorswap.net"},X=ht.create({headers:dt}),ge={get:(s,e)=>X.get(s,e).json(),post:(s,e)=>X.post(s,e).json()},Z=Object.values(i.Chain),mt=(s="")=>{const e=s.toUpperCase(),[t]=e.split(".");if(Z.includes(t))return!0;const[r]=e.split("/");if(Z.includes(r))return!0;throw new Error(`Invalid identifier: ${s}. Expected format: <Chain>.<Ticker> or <Chain>.<Ticker>-<ContractAddress>`)},S=8,C=s=>10n**BigInt(s),T=s=>Math.log10(parseFloat(s.toString()));function R({value:s,bigIntDecimal:e=S,decimal:t=S}){const r=s<0n;let n=s.toString().substring(r?1:0);const a=t-(n.length-1);a>0&&(n="0".repeat(a)+n);const c=n.length-t;let o=n.slice(-t);return parseInt(o[e])>=5?o=`${o.substring(0,e-1)}${(parseInt(o[e-1])+1).toString()}`:o=o.substring(0,e),`${r?"-":""}${n.slice(0,c)}.${o}`.replace(/\.?0*$/,"")}var y,v,$,j,P,_e,I,L;const Y=class Y{constructor(e){A(this,y);A(this,$);A(this,P);A(this,I);m(this,"decimalMultiplier",10n**8n);m(this,"bigIntValue",0n);m(this,"decimal");const t=O(e);this.decimal=typeof e=="object"?e.decimal:void 0,this.decimalMultiplier=C(Math.max(ee(E(t)),this.decimal||0)),p(this,$,j).call(this,t)}static fromBigInt(e,t){return new Y({decimal:t,value:R({value:e,bigIntDecimal:t,decimal:t})})}static shiftDecimals({value:e,from:t,to:r}){return this.fromBigInt(e.getBaseValue("bigint")*C(r)/C(t),r)}set(e){return p(this,$,j).call(this,O(e)),this}add(...e){return p(this,y,v).call(this,"add",...e)}sub(...e){return p(this,y,v).call(this,"sub",...e)}mul(...e){return p(this,y,v).call(this,"mul",...e)}div(...e){return p(this,y,v).call(this,"div",...e)}gt(e){return this.bigIntValue>this.getBigIntValue(e)}gte(e){return this.bigIntValue>=this.getBigIntValue(e)}lt(e){return this.bigIntValue<this.getBigIntValue(e)}lte(e){return this.bigIntValue<=this.getBigIntValue(e)}eqValue(e){return this.bigIntValue===this.getBigIntValue(e)}getValue(e){const t=this.formatBigIntToSafeValue(this.bigIntValue,this.decimal||T(this.decimalMultiplier));switch(e){case"number":return Number(t);case"string":return t;default:return this.bigIntValue*BigInt(this.decimal||8n)/this.decimalMultiplier}}getBaseValue(e){const t=this.decimalMultiplier/C(this.decimal||i.BaseDecimal.THOR),r=this.bigIntValue/t;switch(e){case"number":return Number(r);case"string":return r.toString();default:return r}}getBigIntValue(e,t){if(!t&&typeof e=="object")return e.bigIntValue;const r=O(e),n=E(r);return n==="0"||n==="undefined"?0n:p(this,I,L).call(this,n,t)}formatBigIntToSafeValue(e,t){const r=t||this.decimal||S,n=Math.max(r,T(this.decimalMultiplier)),a=e<0n,c=e.toString().substring(a?1:0),o=n-(c.length-1),u=o>0?"0".repeat(o)+c:c,l=u.length-n;let h=u.slice(-n);return parseInt(h[r])>=5?h=`${h.substring(0,r-1)}${(parseInt(h[r-1])+1).toString()}`:h=h.substring(0,r),`${a?"-":""}${u.slice(0,l)}.${h}`.replace(/\.?0*$/,"")}toSignificant(e=6){const[t,r]=this.getValue("string").split("."),n=t||"",a=r||"";if((parseInt(n)?n.length+a.length:a.length)<=e)return this.getValue("string");if(n.length>=e)return n.slice(0,e).padEnd(n.length,"0");if(parseInt(n))return`${n}.${a.slice(0,e-n.length)}`.padEnd(e-n.length,"0");const o=parseInt(a),u=`${o}`.slice(0,e);return`0.${u.padStart(a.length-`${o}`.length+u.length,"0")}`}toFixed(e=6){const[t,r]=this.getValue("string").split("."),n=t||"",a=r||"";if(parseInt(n))return`${n}.${a.slice(0,e)}`.padEnd(e,"0");const c=parseInt(a),o=`${c}`.slice(0,e);return`0.${o.padStart(a.length-`${c}`.length+o.length,"0")}`}toAbbreviation(e=2){const t=this.getValue("number"),r=["","K","M","B","T","Q","Qi","S"],n=Math.floor(Math.log10(Math.abs(t))/3),a=r[n];if(!a)return this.getValue("string");const c=10**(n*3);return`${(t/c).toFixed(e)}${a}`}toCurrency(e="$",{currencyPosition:t="start",decimal:r=2,decimalSeparator:n=".",thousandSeparator:a=","}={}){const c=this.getValue("number"),[o,u=""]=c.toFixed(6).split("."),l=o.replace(/\B(?=(\d{3})+(?!\d))/g,a),h=!o&&!u?"0.00":o==="0"?`${parseFloat(`0.${u}`)}`.replace(".",n):`${l}${u?`${n}${u.slice(0,r)}`:""}`;return`${t==="start"?e:""}${h}${t==="end"?e:""}`}};y=new WeakSet,v=function(e,...t){const r=p(this,P,_e).call(this,this,...t),n=C(r),a=t.reduce((o,u)=>{const l=this.getBigIntValue(u,r);switch(e){case"add":return o+l;case"sub":return o-l;case"mul":return o*l/n;case"div":{if(l===0n)throw new RangeError("Division by zero");return o*n/l}default:return o}},this.bigIntValue*n/this.decimalMultiplier),c=R({bigIntDecimal:r,decimal:Math.max(r,T(this.decimalMultiplier)),value:a});return new this.constructor({decimal:this.decimal,value:c,identifier:this.toString()})},$=new WeakSet,j=function(e){const t=E(e)||"0";this.bigIntValue=p(this,I,L).call(this,t)},P=new WeakSet,_e=function(...e){const t=e.map(r=>typeof r=="object"?r.decimal||T(r.decimalMultiplier):ee(E(r))).filter(Boolean);return Math.max(...t,S)},I=new WeakSet,L=function(e,t){const r=t?C(t):this.decimalMultiplier,n=T(r),[a="",c=""]=e.split(".");return BigInt(`${a}${c.padEnd(n,"0")}`)};let w=Y;const pt=Intl.NumberFormat("fullwide",{useGrouping:!1,maximumFractionDigits:20});function E(s){const t=`${typeof s=="number"?pt.format(s):O(s)}`.replaceAll(",",".").split(".");return t.length>1?`${t.slice(0,-1).join("")}.${t.at(-1)}`:t[0]}function ee(s){var t;const e=((t=s.split(".")[1])==null?void 0:t.length)||0;return Math.max(e,S)}function O(s){return typeof s=="object"?"getValue"in s?s.getValue("string"):s.value:s}const V=(s,e)=>typeof s=="bigint"?R({value:s,bigIntDecimal:e,decimal:e}):s;let F;const te=s=>{if(!F)throw new Error("Static assets not loaded, call await AssetValue.loadStaticAssets() first");return F.get(s.toUpperCase())||{decimal:i.BaseDecimal.THOR,identifier:""}},se=async(s,e=0)=>{mt(s);const t=await ie(U(s)),r=V(e,t);return new _({decimal:t,value:r,identifier:s})},re=new Map;class _ extends w{constructor(t){const r="identifier"in t?t.identifier:`${t.chain}.${t.symbol}`,n=re.get(r);if(n)return n.set(t.value);super(t.value instanceof w?t.value:{decimal:t.decimal,value:t.value});m(this,"address");m(this,"isSynthetic",!1);m(this,"isGasAsset",!1);m(this,"chain");m(this,"symbol");m(this,"ticker");m(this,"type");const a=U(r);this.type=oe(a),this.chain=a.chain,this.ticker=a.ticker,this.symbol=a.symbol,this.address=a.address,this.isSynthetic=a.isSynthetic,this.isGasAsset=a.isGasAsset,re.set(r,this)}toString(t=!1){const r=this.isSynthetic?this.symbol.split("-")[0]:this.ticker;return t?r:`${this.chain}.${this.symbol}`}eq({chain:t,symbol:r}){return this.chain===t&&this.symbol===r}static async fromString(t,r=0){return se(t,r)}static fromStringSync(t,r=0){const{isSynthetic:n}=U(t),{decimal:a,identifier:c}=te(t),o=V(r,a);return c?new _({decimal:a,identifier:c,value:o}):n?new _({decimal:8,identifier:t,value:o}):void 0}static async fromIdentifier(t,r=0){return se(t,r)}static fromIdentifierSync(t,r=0){const{decimal:n,identifier:a}=te(t),c=V(r,n);return new _({decimal:n,identifier:a,value:c})}static fromChainOrSignature(t,r=0){const{decimal:n,identifier:a}=ae(t),c=V(r,n);return new _({value:c,decimal:n,identifier:a})}static async loadStaticAssets(){return new Promise(async(t,r)=>{try{const{ThorchainList:n,NativeList:a,...c}=await import("@swapkit/tokens");F=[a,...Object.values(c)].reduce((u,{tokens:l})=>(l.forEach(({identifier:h,chain:g,...b})=>{const k="decimals"in b?b.decimals:i.BaseDecimal[g];u.set(h,{identifier:h,decimal:k})}),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 ft=s=>{const e=_.fromChainOrSignature(s);switch(s){case i.Chain.Bitcoin:case i.Chain.Litecoin:case i.Chain.BitcoinCash:return e.set(10001e-8);case i.Chain.Dogecoin:return e.set(1.00000001);case i.Chain.Avalanche:case i.Chain.Ethereum:return e.set(1e-8);case i.Chain.THORChain:case i.Chain.Maya:return e.set(0);default:return e.set(1e-8)}},U=s=>{const e=s.slice(0,14).includes("/"),[t,r]=s.split(".").pop().split("/"),n=s.includes(".")&&!e?s:`${i.Chain.THORChain}.${r}`,[a,c]=n.split("."),[o,u]=(e?r:c).split("-");return{address:u==null?void 0:u.toLowerCase(),chain:a,isGasAsset:W({chain:a,symbol:c}),isSynthetic:e,symbol:(e?`${t}/`:"")+(u?`${o}-${(u==null?void 0:u.toLowerCase())??""}`:c),ticker:o}},gt={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 K extends Error{constructor(e,t){console.error(t),super(e,{cause:{code:gt[e],message:e}}),Object.setPrototypeOf(this,K.prototype)}}class f extends w{eq(e){return this.eqValue(e)}static fromBigInt(e,t){return new f({decimal:t,value:R({value:e,bigIntDecimal:t,decimal:t})})}}exports.AssetValue=_;exports.BigIntArithmetics=w;exports.RequestClient=ge;exports.SwapKitError=K;exports.SwapKitNumber=f;exports.assetFromString=ke;exports.derivationPathToString=ze;exports.filterAssets=De;exports.formatBigIntToSafeValue=R;exports.gasFeeMultiplier=Pe;exports.getAssetType=oe;exports.getAsymmetricAssetShare=ue;exports.getAsymmetricAssetWithdrawAmount=je;exports.getAsymmetricRuneShare=ce;exports.getAsymmetricRuneWithdrawAmount=He;exports.getCommonAssetInfo=ae;exports.getDecimal=ie;exports.getEstimatedPoolShare=Fe;exports.getLiquiditySlippage=Ue;exports.getMemoFor=Ge;exports.getMinAmountByChain=ft;exports.getSymmetricPoolShare=le;exports.getSymmetricWithdraw=Le;exports.getTHORNameCost=Ke;exports.isGasAsset=W;exports.validateTHORName=Ye;
|
package/dist/index.es.js
CHANGED
|
@@ -1,19 +1,19 @@
|
|
|
1
|
-
var
|
|
2
|
-
var
|
|
3
|
-
var
|
|
1
|
+
var gt = Object.defineProperty;
|
|
2
|
+
var bt = (r, t, e) => t in r ? gt(r, t, { enumerable: !0, configurable: !0, writable: !0, value: e }) : r[t] = e;
|
|
3
|
+
var p = (r, t, e) => (bt(r, typeof t != "symbol" ? t + "" : t, e), e), yt = (r, t, e) => {
|
|
4
4
|
if (!t.has(r))
|
|
5
5
|
throw TypeError("Cannot " + e);
|
|
6
6
|
};
|
|
7
|
-
var
|
|
7
|
+
var T = (r, t, e) => {
|
|
8
8
|
if (t.has(r))
|
|
9
9
|
throw TypeError("Cannot add the same private member more than once");
|
|
10
10
|
t instanceof WeakSet ? t.add(r) : t.set(r, e);
|
|
11
11
|
};
|
|
12
|
-
var
|
|
13
|
-
import { FeeOption as
|
|
14
|
-
const
|
|
12
|
+
var f = (r, t, e) => (yt(r, t, "access private method"), e);
|
|
13
|
+
import { FeeOption as H, BaseDecimal as d, Chain as o, EVMChainList as wt, ChainToRPC as At, MemoType as g } from "@swapkit/types";
|
|
14
|
+
const vt = "0x313ce567", nt = async ({ chain: r, to: t }) => {
|
|
15
15
|
try {
|
|
16
|
-
const { result: e } = await
|
|
16
|
+
const { result: e } = await Xt.post(At[r], {
|
|
17
17
|
headers: {
|
|
18
18
|
accept: "*/*",
|
|
19
19
|
"content-type": "application/json",
|
|
@@ -23,37 +23,37 @@ const $t = "0x313ce567", ot = async ({ chain: r, 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: vt }, "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[r];
|
|
32
32
|
}
|
|
33
|
-
},
|
|
33
|
+
}, Tt = async (r) => {
|
|
34
34
|
if (r === o.Ethereum)
|
|
35
|
-
return
|
|
35
|
+
return d.ETH;
|
|
36
36
|
const [, t] = r.split("-");
|
|
37
|
-
return t != null && t.startsWith("0x") ?
|
|
38
|
-
},
|
|
37
|
+
return t != null && t.startsWith("0x") ? nt({ chain: o.Ethereum, to: t }) : d.ETH;
|
|
38
|
+
}, $t = async (r) => {
|
|
39
39
|
const [, t] = r.split("-");
|
|
40
|
-
return t != null && t.startsWith("0x") ?
|
|
41
|
-
},
|
|
40
|
+
return t != null && t.startsWith("0x") ? nt({ chain: o.Avalanche, to: t.toLowerCase() }) : d.AVAX;
|
|
41
|
+
}, Rt = async (r) => r === o.BinanceSmartChain ? d.BSC : d.BSC, St = async ({ chain: r, symbol: t }) => {
|
|
42
42
|
switch (r) {
|
|
43
43
|
case o.Ethereum:
|
|
44
|
-
return
|
|
44
|
+
return Tt(t);
|
|
45
45
|
case o.Avalanche:
|
|
46
|
-
return
|
|
46
|
+
return $t(t);
|
|
47
47
|
case o.BinanceSmartChain:
|
|
48
|
-
return
|
|
48
|
+
return Rt(t);
|
|
49
49
|
default:
|
|
50
|
-
return
|
|
50
|
+
return d[r];
|
|
51
51
|
}
|
|
52
|
-
},
|
|
53
|
-
[
|
|
54
|
-
[
|
|
55
|
-
[
|
|
56
|
-
},
|
|
52
|
+
}, ne = {
|
|
53
|
+
[H.Average]: 1.2,
|
|
54
|
+
[H.Fast]: 1.5,
|
|
55
|
+
[H.Fastest]: 2
|
|
56
|
+
}, it = ({ chain: r, symbol: t }) => {
|
|
57
57
|
switch (r) {
|
|
58
58
|
case o.Bitcoin:
|
|
59
59
|
case o.BitcoinCash:
|
|
@@ -79,20 +79,20 @@ const $t = "0x313ce567", ot = async ({ chain: r, to: t }) => {
|
|
|
79
79
|
case o.THORChain:
|
|
80
80
|
return t === "RUNE";
|
|
81
81
|
}
|
|
82
|
-
},
|
|
82
|
+
}, Ct = (r) => {
|
|
83
83
|
switch (r) {
|
|
84
84
|
case "ETH.THOR":
|
|
85
85
|
return { identifier: "ETH.THOR-0xa5f2211b9b8170f694421f2046281775e8468044", decimal: 18 };
|
|
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[r] };
|
|
90
90
|
case o.THORChain:
|
|
91
|
-
return { identifier: "THOR.RUNE", decimal:
|
|
91
|
+
return { identifier: "THOR.RUNE", decimal: d[r] };
|
|
92
92
|
case o.BinanceSmartChain:
|
|
93
|
-
return { identifier: "BSC.BNB", decimal:
|
|
93
|
+
return { identifier: "BSC.BNB", decimal: d[r] };
|
|
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,9 +106,9 @@ const $t = "0x313ce567", ot = async ({ chain: r, to: t }) => {
|
|
|
106
106
|
case o.Polygon:
|
|
107
107
|
case o.Bitcoin:
|
|
108
108
|
case o.Ethereum:
|
|
109
|
-
return { identifier: `${r}.${r}`, decimal:
|
|
109
|
+
return { identifier: `${r}.${r}`, decimal: d[r] };
|
|
110
110
|
}
|
|
111
|
-
},
|
|
111
|
+
}, It = ({ chain: r, symbol: t }) => {
|
|
112
112
|
if (t.includes("/"))
|
|
113
113
|
return "Synth";
|
|
114
114
|
switch (r) {
|
|
@@ -138,47 +138,47 @@ const $t = "0x313ce567", ot = async ({ chain: r, to: t }) => {
|
|
|
138
138
|
case o.Optimism:
|
|
139
139
|
return [o.Ethereum, o.Optimism].includes(t) ? "Native" : "OPTIMISM";
|
|
140
140
|
}
|
|
141
|
-
},
|
|
141
|
+
}, ie = (r) => {
|
|
142
142
|
var c;
|
|
143
143
|
const [t, ...e] = r.split("."), s = r.includes("/"), n = e.join("."), i = (c = n == null ? void 0 : n.split("-")) == null ? void 0 : c[0];
|
|
144
144
|
return { chain: t, symbol: n, ticker: i, synth: s };
|
|
145
|
-
},
|
|
145
|
+
}, Et = new RegExp(
|
|
146
146
|
/(.)\1{6}|\.ORG|\.NET|\.FINANCE|\.COM|WWW|HTTP|\\\\|\/\/|[\s$%:[\]]/,
|
|
147
147
|
"gmi"
|
|
148
|
-
),
|
|
148
|
+
), Ot = (r) => {
|
|
149
149
|
const [t, e] = r.split(".");
|
|
150
|
-
if (!
|
|
150
|
+
if (!wt.includes(t))
|
|
151
151
|
return !0;
|
|
152
152
|
const [, s] = e.split("-");
|
|
153
|
-
return
|
|
154
|
-
},
|
|
153
|
+
return it({ chain: t, symbol: e }) || !!s;
|
|
154
|
+
}, oe = (r) => r.filter((t) => {
|
|
155
155
|
const e = `${t.chain}.${t.symbol}`;
|
|
156
|
-
return !
|
|
157
|
-
}),
|
|
156
|
+
return !Et.test(e) && Ot(e) && t.value !== "0";
|
|
157
|
+
}), Bt = ({
|
|
158
158
|
liquidityUnits: r,
|
|
159
159
|
poolUnits: t,
|
|
160
160
|
runeDepth: e
|
|
161
161
|
}) => {
|
|
162
162
|
const s = m(r), n = m(t), i = m(e), c = s.mul(i), a = n.mul(n).mul(2), u = n.mul(s).mul(2), l = s.mul(s), h = n.mul(n).mul(n);
|
|
163
163
|
return c.mul(a.sub(u).add(l)).div(h);
|
|
164
|
-
},
|
|
164
|
+
}, Mt = ({
|
|
165
165
|
liquidityUnits: r,
|
|
166
166
|
poolUnits: t,
|
|
167
167
|
assetDepth: e
|
|
168
168
|
}) => {
|
|
169
169
|
const s = m(r), n = m(t), i = m(e), c = s.mul(i), a = n.mul(n).mul(2), u = n.mul(s).mul(2), l = s.mul(s), h = c.mul(a.sub(u).add(l)), _ = n.mul(n).mul(n);
|
|
170
170
|
return h.div(_);
|
|
171
|
-
},
|
|
171
|
+
}, ae = ({
|
|
172
172
|
percent: r,
|
|
173
173
|
runeDepth: t,
|
|
174
174
|
liquidityUnits: e,
|
|
175
175
|
poolUnits: s
|
|
176
|
-
}) =>
|
|
176
|
+
}) => Bt({ runeDepth: t, liquidityUnits: e, poolUnits: s }).mul(r), ce = ({
|
|
177
177
|
percent: r,
|
|
178
178
|
assetDepth: t,
|
|
179
179
|
liquidityUnits: e,
|
|
180
180
|
poolUnits: s
|
|
181
|
-
}) =>
|
|
181
|
+
}) => Mt({ assetDepth: t, liquidityUnits: e, poolUnits: s }).mul(r), m = (r) => b.fromBigInt(BigInt(r), d.THOR), Vt = ({
|
|
182
182
|
liquidityUnits: r,
|
|
183
183
|
poolUnits: t,
|
|
184
184
|
runeDepth: e,
|
|
@@ -186,17 +186,17 @@ const $t = "0x313ce567", ot = async ({ chain: r, to: t }) => {
|
|
|
186
186
|
}) => ({
|
|
187
187
|
assetAmount: m(s).mul(r).div(t),
|
|
188
188
|
runeAmount: m(e).mul(r).div(t)
|
|
189
|
-
}),
|
|
189
|
+
}), ue = ({
|
|
190
190
|
liquidityUnits: r,
|
|
191
191
|
poolUnits: t,
|
|
192
192
|
runeDepth: e,
|
|
193
193
|
assetDepth: s,
|
|
194
194
|
percent: n
|
|
195
195
|
}) => Object.fromEntries(
|
|
196
|
-
Object.entries(
|
|
196
|
+
Object.entries(Vt({ liquidityUnits: r, poolUnits: t, runeDepth: e, assetDepth: s })).map(
|
|
197
197
|
([i, c]) => [i, c.mul(n)]
|
|
198
198
|
)
|
|
199
|
-
),
|
|
199
|
+
), le = ({
|
|
200
200
|
runeDepth: r,
|
|
201
201
|
poolUnits: t,
|
|
202
202
|
assetDepth: e,
|
|
@@ -204,12 +204,12 @@ const $t = "0x313ce567", ot = async ({ chain: r, to: t }) => {
|
|
|
204
204
|
runeAmount: n,
|
|
205
205
|
assetAmount: i
|
|
206
206
|
}) => {
|
|
207
|
-
const c = new b({ value: r, decimal: 8 }), a = new b({ value: e, decimal: 8 }), u = new b({ value: t, decimal: 8 }), l = new b({ value: n, decimal: 8 }), h = new b({ value: i, decimal: 8 }), _ = l.mul(a),
|
|
208
|
-
if (
|
|
209
|
-
return
|
|
210
|
-
const
|
|
211
|
-
return
|
|
212
|
-
},
|
|
207
|
+
const c = new b({ value: r, decimal: 8 }), a = new b({ value: e, decimal: 8 }), u = new b({ value: t, decimal: 8 }), l = new b({ value: n, decimal: 8 }), h = new b({ value: i, decimal: 8 }), _ = l.mul(a), A = h.mul(c), N = l.mul(h), mt = c.mul(a), pt = u.mul(_.add(A.add(N.mul(2)))), ft = _.add(A.add(mt.mul(2))), J = pt.div(ft), j = m(s).add(J);
|
|
208
|
+
if (J.getBaseValue("number") === 0)
|
|
209
|
+
return j.div(u).getBaseValue("number");
|
|
210
|
+
const _t = u.add(j);
|
|
211
|
+
return j.div(_t).getBaseValue("number");
|
|
212
|
+
}, he = ({
|
|
213
213
|
runeAmount: r,
|
|
214
214
|
assetAmount: t,
|
|
215
215
|
runeDepth: e,
|
|
@@ -219,11 +219,11 @@ const $t = "0x313ce567", ot = async ({ chain: r, to: t }) => {
|
|
|
219
219
|
return 0;
|
|
220
220
|
const n = m(e), i = m(s), c = m(t), a = m(r), u = c.mul(n).sub(i.mul(a)), l = i.mul(a).add(n.mul(i));
|
|
221
221
|
return Math.abs(u.div(l).getBaseValue("number"));
|
|
222
|
-
},
|
|
222
|
+
}, qt = ({
|
|
223
223
|
symbol: r,
|
|
224
224
|
ticker: t,
|
|
225
225
|
chain: e
|
|
226
|
-
}) => e === "ETH" && t !== "ETH" ? `${t}-${r.slice(-3)}` : r,
|
|
226
|
+
}) => e === "ETH" && t !== "ETH" ? `${t}-${r.slice(-3)}` : r, de = (r, t) => {
|
|
227
227
|
switch (r) {
|
|
228
228
|
case g.LEAVE:
|
|
229
229
|
case g.BOND: {
|
|
@@ -243,7 +243,7 @@ const $t = "0x313ce567", ot = async ({ chain: r, to: t }) => {
|
|
|
243
243
|
return i ? `${r}:${e}/${s}::t:0` : `${r}:${e}.${s}:${n || ""}:t:0`;
|
|
244
244
|
}
|
|
245
245
|
case g.WITHDRAW: {
|
|
246
|
-
const { chain: e, ticker: s, symbol: n, basisPoints: i, targetAssetString: c, singleSide: a } = t, u = !a && c ? `:${c}` : "", l =
|
|
246
|
+
const { chain: e, ticker: s, symbol: n, basisPoints: i, targetAssetString: c, singleSide: a } = t, u = !a && c ? `:${c}` : "", l = qt({ chain: e, symbol: n, ticker: s });
|
|
247
247
|
return `${r}:${e}${a ? "/" : "."}${l}:${i}${u}`;
|
|
248
248
|
}
|
|
249
249
|
case g.OPEN_LOAN:
|
|
@@ -258,13 +258,13 @@ const $t = "0x313ce567", ot = async ({ chain: r, to: t }) => {
|
|
|
258
258
|
if (r < 0)
|
|
259
259
|
throw new Error("Invalid number of year");
|
|
260
260
|
return 10 + r;
|
|
261
|
-
},
|
|
261
|
+
}, pe = (r) => {
|
|
262
262
|
if (r.length > 30)
|
|
263
263
|
return !1;
|
|
264
264
|
const t = /^[a-zA-Z0-9+_-]+$/g;
|
|
265
265
|
return !!r.match(t);
|
|
266
|
-
},
|
|
267
|
-
class
|
|
266
|
+
}, fe = ([r, t, e, s, n]) => `${r}'/${t}'/${e}'/${s}${typeof n != "number" ? "" : `/${n}`}`;
|
|
267
|
+
class K extends Error {
|
|
268
268
|
constructor(t, e, s) {
|
|
269
269
|
const n = t.status || t.status === 0 ? t.status : "", i = t.statusText || "", c = `${n} ${i}`.trim(), a = c ? `status code ${c}` : "an unknown error";
|
|
270
270
|
super(`Request failed with ${a}`), Object.defineProperty(this, "response", {
|
|
@@ -285,7 +285,7 @@ class Z extends Error {
|
|
|
285
285
|
}), this.name = "HTTPError", this.response = t, this.request = e, this.options = s;
|
|
286
286
|
}
|
|
287
287
|
}
|
|
288
|
-
class
|
|
288
|
+
class ot extends Error {
|
|
289
289
|
constructor(t) {
|
|
290
290
|
super("Request timed out"), Object.defineProperty(this, "request", {
|
|
291
291
|
enumerable: !0,
|
|
@@ -295,28 +295,28 @@ class ct extends Error {
|
|
|
295
295
|
}), this.name = "TimeoutError", this.request = t;
|
|
296
296
|
}
|
|
297
297
|
}
|
|
298
|
-
const
|
|
298
|
+
const M = (r) => r !== null && typeof r == "object", O = (...r) => {
|
|
299
299
|
for (const t of r)
|
|
300
|
-
if ((!
|
|
300
|
+
if ((!M(t) || Array.isArray(t)) && t !== void 0)
|
|
301
301
|
throw new TypeError("The `options` argument must be an object");
|
|
302
|
-
return
|
|
303
|
-
},
|
|
302
|
+
return Y({}, ...r);
|
|
303
|
+
}, at = (r = {}, t = {}) => {
|
|
304
304
|
const e = new globalThis.Headers(r), s = t instanceof globalThis.Headers, n = new globalThis.Headers(t);
|
|
305
305
|
for (const [i, c] of n.entries())
|
|
306
306
|
s && c === "undefined" || c === void 0 ? e.delete(i) : e.set(i, c);
|
|
307
307
|
return e;
|
|
308
|
-
},
|
|
308
|
+
}, Y = (...r) => {
|
|
309
309
|
let t = {}, e = {};
|
|
310
310
|
for (const s of r)
|
|
311
311
|
if (Array.isArray(s))
|
|
312
312
|
Array.isArray(t) || (t = []), t = [...t, ...s];
|
|
313
|
-
else if (
|
|
313
|
+
else if (M(s)) {
|
|
314
314
|
for (let [n, i] of Object.entries(s))
|
|
315
|
-
|
|
316
|
-
|
|
315
|
+
M(i) && n in t && (i = Y(t[n], i)), t = { ...t, [n]: i };
|
|
316
|
+
M(s.headers) && (e = at(e, s.headers), t.headers = e);
|
|
317
317
|
}
|
|
318
318
|
return t;
|
|
319
|
-
},
|
|
319
|
+
}, xt = (() => {
|
|
320
320
|
let r = !1, t = !1;
|
|
321
321
|
const e = typeof globalThis.ReadableStream == "function", s = typeof globalThis.Request == "function";
|
|
322
322
|
return e && s && (t = new globalThis.Request("https://empty.invalid", {
|
|
@@ -327,13 +327,13 @@ const x = (r) => r !== null && typeof r == "object", V = (...r) => {
|
|
|
327
327
|
return r = !0, "half";
|
|
328
328
|
}
|
|
329
329
|
}).headers.has("Content-Type")), r && !t;
|
|
330
|
-
})(),
|
|
330
|
+
})(), kt = typeof globalThis.AbortController == "function", Pt = typeof globalThis.ReadableStream == "function", Nt = typeof globalThis.FormData == "function", ct = ["get", "post", "put", "patch", "head", "delete"], jt = {
|
|
331
331
|
json: "application/json",
|
|
332
332
|
text: "text/*",
|
|
333
333
|
formData: "multipart/form-data",
|
|
334
334
|
arrayBuffer: "*/*",
|
|
335
335
|
blob: "*/*"
|
|
336
|
-
},
|
|
336
|
+
}, L = 2147483647, ut = Symbol("stop"), Ht = {
|
|
337
337
|
json: !0,
|
|
338
338
|
parseJson: !0,
|
|
339
339
|
searchParams: !0,
|
|
@@ -344,7 +344,7 @@ const x = (r) => r !== null && typeof r == "object", V = (...r) => {
|
|
|
344
344
|
throwHttpErrors: !0,
|
|
345
345
|
onDownloadProgress: !0,
|
|
346
346
|
fetch: !0
|
|
347
|
-
},
|
|
347
|
+
}, Lt = {
|
|
348
348
|
method: !0,
|
|
349
349
|
headers: !0,
|
|
350
350
|
body: !0,
|
|
@@ -360,18 +360,18 @@ const x = (r) => r !== null && typeof r == "object", V = (...r) => {
|
|
|
360
360
|
window: !0,
|
|
361
361
|
dispatcher: !0,
|
|
362
362
|
duplex: !0
|
|
363
|
-
},
|
|
363
|
+
}, Dt = (r) => ct.includes(r) ? r.toUpperCase() : r, Ut = ["get", "put", "head", "delete", "options", "trace"], Ft = [408, 413, 429, 500, 502, 503, 504], lt = [413, 429, 503], Q = {
|
|
364
364
|
limit: 2,
|
|
365
|
-
methods:
|
|
366
|
-
statusCodes:
|
|
367
|
-
afterStatusCodes:
|
|
365
|
+
methods: Ut,
|
|
366
|
+
statusCodes: Ft,
|
|
367
|
+
afterStatusCodes: lt,
|
|
368
368
|
maxRetryAfter: Number.POSITIVE_INFINITY,
|
|
369
369
|
backoffLimit: Number.POSITIVE_INFINITY,
|
|
370
370
|
delay: (r) => 0.3 * 2 ** (r - 1) * 1e3
|
|
371
|
-
},
|
|
371
|
+
}, Wt = (r = {}) => {
|
|
372
372
|
if (typeof r == "number")
|
|
373
373
|
return {
|
|
374
|
-
...
|
|
374
|
+
...Q,
|
|
375
375
|
limit: r
|
|
376
376
|
};
|
|
377
377
|
if (r.methods && !Array.isArray(r.methods))
|
|
@@ -379,22 +379,22 @@ const x = (r) => r !== null && typeof r == "object", V = (...r) => {
|
|
|
379
379
|
if (r.statusCodes && !Array.isArray(r.statusCodes))
|
|
380
380
|
throw new Error("retry.statusCodes must be an array");
|
|
381
381
|
return {
|
|
382
|
-
...
|
|
382
|
+
...Q,
|
|
383
383
|
...r,
|
|
384
|
-
afterStatusCodes:
|
|
384
|
+
afterStatusCodes: lt
|
|
385
385
|
};
|
|
386
386
|
};
|
|
387
|
-
async function
|
|
387
|
+
async function Gt(r, t, e, s) {
|
|
388
388
|
return new Promise((n, i) => {
|
|
389
389
|
const c = setTimeout(() => {
|
|
390
|
-
e && e.abort(), i(new
|
|
390
|
+
e && e.abort(), i(new ot(r));
|
|
391
391
|
}, s.timeout);
|
|
392
392
|
s.fetch(r, t).then(n).catch(i).then(() => {
|
|
393
393
|
clearTimeout(c);
|
|
394
394
|
});
|
|
395
395
|
});
|
|
396
396
|
}
|
|
397
|
-
async function
|
|
397
|
+
async function Yt(r, { signal: t }) {
|
|
398
398
|
return new Promise((e, s) => {
|
|
399
399
|
t && (t.throwIfAborted(), t.addEventListener("abort", n, { once: !0 }));
|
|
400
400
|
function n() {
|
|
@@ -405,17 +405,17 @@ async function Jt(r, { signal: t }) {
|
|
|
405
405
|
}, r);
|
|
406
406
|
});
|
|
407
407
|
}
|
|
408
|
-
const
|
|
408
|
+
const zt = (r, t) => {
|
|
409
409
|
const e = {};
|
|
410
410
|
for (const s in t)
|
|
411
|
-
!(s in
|
|
411
|
+
!(s in Lt) && !(s in Ht) && !(s in r) && (e[s] = t[s]);
|
|
412
412
|
return e;
|
|
413
413
|
};
|
|
414
|
-
class
|
|
414
|
+
class x {
|
|
415
415
|
static create(t, e) {
|
|
416
|
-
const s = new
|
|
417
|
-
if (typeof s._options.timeout == "number" && s._options.timeout >
|
|
418
|
-
throw new RangeError(`The \`timeout\` option cannot be greater than ${
|
|
416
|
+
const s = new x(t, e), n = async () => {
|
|
417
|
+
if (typeof s._options.timeout == "number" && s._options.timeout > L)
|
|
418
|
+
throw new RangeError(`The \`timeout\` option cannot be greater than ${L}`);
|
|
419
419
|
await Promise.resolve();
|
|
420
420
|
let a = await s._fetch();
|
|
421
421
|
for (const u of s._options.hooks.afterResponse) {
|
|
@@ -423,7 +423,7 @@ class P {
|
|
|
423
423
|
l instanceof globalThis.Response && (a = l);
|
|
424
424
|
}
|
|
425
425
|
if (s._decorateResponse(a), !a.ok && s._options.throwHttpErrors) {
|
|
426
|
-
let u = new
|
|
426
|
+
let u = new K(a, s.request, s._options);
|
|
427
427
|
for (const l of s._options.hooks.beforeError)
|
|
428
428
|
u = await l(u);
|
|
429
429
|
throw u;
|
|
@@ -431,13 +431,13 @@ class P {
|
|
|
431
431
|
if (s._options.onDownloadProgress) {
|
|
432
432
|
if (typeof s._options.onDownloadProgress != "function")
|
|
433
433
|
throw new TypeError("The `onDownloadProgress` option must be a function");
|
|
434
|
-
if (!
|
|
434
|
+
if (!Pt)
|
|
435
435
|
throw new Error("Streams are not supported in your environment. `ReadableStream` is missing.");
|
|
436
436
|
return s._stream(a.clone(), s._options.onDownloadProgress);
|
|
437
437
|
}
|
|
438
438
|
return a;
|
|
439
439
|
}, c = s._options.retry.methods.includes(s.request.method.toLowerCase()) ? s._retry(n) : n();
|
|
440
|
-
for (const [a, u] of Object.entries(
|
|
440
|
+
for (const [a, u] of Object.entries(jt))
|
|
441
441
|
c[a] = async () => {
|
|
442
442
|
s.request.headers.set("accept", s.request.headers.get("accept") || u);
|
|
443
443
|
const h = (await c).clone();
|
|
@@ -482,17 +482,17 @@ class P {
|
|
|
482
482
|
// TODO: credentials can be removed when the spec change is implemented in all browsers. Context: https://www.chromestatus.com/feature/4539473312350208
|
|
483
483
|
credentials: this._input.credentials || "same-origin",
|
|
484
484
|
...e,
|
|
485
|
-
headers:
|
|
486
|
-
hooks:
|
|
485
|
+
headers: at(this._input.headers, e.headers),
|
|
486
|
+
hooks: Y({
|
|
487
487
|
beforeRequest: [],
|
|
488
488
|
beforeRetry: [],
|
|
489
489
|
beforeError: [],
|
|
490
490
|
afterResponse: []
|
|
491
491
|
}, e.hooks),
|
|
492
|
-
method:
|
|
492
|
+
method: Dt(e.method ?? this._input.method),
|
|
493
493
|
// eslint-disable-next-line @typescript-eslint/prefer-nullish-coalescing
|
|
494
494
|
prefixUrl: String(e.prefixUrl || ""),
|
|
495
|
-
retry:
|
|
495
|
+
retry: Wt(e.retry),
|
|
496
496
|
throwHttpErrors: e.throwHttpErrors !== !1,
|
|
497
497
|
timeout: e.timeout ?? 1e4,
|
|
498
498
|
fetch: e.fetch ?? globalThis.fetch.bind(globalThis)
|
|
@@ -503,7 +503,7 @@ class P {
|
|
|
503
503
|
throw new Error("`input` must not begin with a slash when using `prefixUrl`");
|
|
504
504
|
this._options.prefixUrl.endsWith("/") || (this._options.prefixUrl += "/"), this._input = this._options.prefixUrl + this._input;
|
|
505
505
|
}
|
|
506
|
-
if (
|
|
506
|
+
if (kt) {
|
|
507
507
|
if (this.abortController = new globalThis.AbortController(), this._options.signal) {
|
|
508
508
|
const s = this._options.signal;
|
|
509
509
|
this._options.signal.addEventListener("abort", () => {
|
|
@@ -512,15 +512,15 @@ class P {
|
|
|
512
512
|
}
|
|
513
513
|
this._options.signal = this.abortController.signal;
|
|
514
514
|
}
|
|
515
|
-
if (
|
|
515
|
+
if (xt && (this._options.duplex = "half"), this.request = new globalThis.Request(this._input, this._options), this._options.searchParams) {
|
|
516
516
|
const n = "?" + (typeof this._options.searchParams == "string" ? this._options.searchParams.replace(/^\?/, "") : new URLSearchParams(this._options.searchParams).toString()), i = this.request.url.replace(/(?:\?.*?)?(?=#|$)/, n);
|
|
517
|
-
(
|
|
517
|
+
(Nt && this._options.body instanceof globalThis.FormData || this._options.body instanceof URLSearchParams) && !(this._options.headers && this._options.headers["content-type"]) && this.request.headers.delete("content-type"), this.request = new globalThis.Request(new globalThis.Request(i, { ...this.request }), this._options);
|
|
518
518
|
}
|
|
519
519
|
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 }));
|
|
520
520
|
}
|
|
521
521
|
_calculateRetryDelay(t) {
|
|
522
|
-
if (this._retryCount++, this._retryCount < this._options.retry.limit && !(t instanceof
|
|
523
|
-
if (t instanceof
|
|
522
|
+
if (this._retryCount++, this._retryCount < this._options.retry.limit && !(t instanceof ot)) {
|
|
523
|
+
if (t instanceof K) {
|
|
524
524
|
if (!this._options.retry.statusCodes.includes(t.response.status))
|
|
525
525
|
return 0;
|
|
526
526
|
const s = t.response.headers.get("Retry-After");
|
|
@@ -543,16 +543,16 @@ class P {
|
|
|
543
543
|
try {
|
|
544
544
|
return await t();
|
|
545
545
|
} catch (e) {
|
|
546
|
-
const s = Math.min(this._calculateRetryDelay(e),
|
|
546
|
+
const s = Math.min(this._calculateRetryDelay(e), L);
|
|
547
547
|
if (s !== 0 && this._retryCount > 0) {
|
|
548
|
-
await
|
|
548
|
+
await Yt(s, { signal: this._options.signal });
|
|
549
549
|
for (const n of this._options.hooks.beforeRetry)
|
|
550
550
|
if (await n({
|
|
551
551
|
request: this.request,
|
|
552
552
|
options: this._options,
|
|
553
553
|
error: e,
|
|
554
554
|
retryCount: this._retryCount
|
|
555
|
-
}) ===
|
|
555
|
+
}) === ut)
|
|
556
556
|
return;
|
|
557
557
|
return this._retry(t);
|
|
558
558
|
}
|
|
@@ -569,8 +569,8 @@ class P {
|
|
|
569
569
|
if (s instanceof Response)
|
|
570
570
|
return s;
|
|
571
571
|
}
|
|
572
|
-
const t =
|
|
573
|
-
return this._options.timeout === !1 ? this._options.fetch(this.request.clone(), t) :
|
|
572
|
+
const t = zt(this.request, this._options);
|
|
573
|
+
return this._options.timeout === !1 ? this._options.fetch(this.request.clone(), t) : Gt(this.request.clone(), t, this.abortController, this._options);
|
|
574
574
|
}
|
|
575
575
|
/* istanbul ignore next */
|
|
576
576
|
_stream(t, e) {
|
|
@@ -607,29 +607,29 @@ class P {
|
|
|
607
607
|
}
|
|
608
608
|
}
|
|
609
609
|
/*! MIT License © Sindre Sorhus */
|
|
610
|
-
const
|
|
611
|
-
const t = (e, s) =>
|
|
612
|
-
for (const e of
|
|
613
|
-
t[e] = (s, n) =>
|
|
614
|
-
return t.create = (e) =>
|
|
615
|
-
},
|
|
616
|
-
get: (r, t) =>
|
|
617
|
-
post: (r, t) =>
|
|
618
|
-
},
|
|
610
|
+
const D = (r) => {
|
|
611
|
+
const t = (e, s) => x.create(e, O(r, s));
|
|
612
|
+
for (const e of ct)
|
|
613
|
+
t[e] = (s, n) => x.create(s, O(r, n, { method: e }));
|
|
614
|
+
return t.create = (e) => D(O(e)), t.extend = (e) => D(O(r, e)), t.stop = ut, t;
|
|
615
|
+
}, Jt = D(), Kt = Jt, Qt = typeof window < "u" ? {} : { referrer: "https://sk.thorswap.net", referer: "https://sk.thorswap.net" }, X = Kt.create({ headers: Qt }), Xt = {
|
|
616
|
+
get: (r, t) => X.get(r, t).json(),
|
|
617
|
+
post: (r, t) => X.post(r, t).json()
|
|
618
|
+
}, Z = Object.values(o), Zt = (r = "") => {
|
|
619
619
|
const t = r.toUpperCase(), [e] = t.split(".");
|
|
620
|
-
if (
|
|
620
|
+
if (Z.includes(e))
|
|
621
621
|
return !0;
|
|
622
622
|
const [s] = t.split("/");
|
|
623
|
-
if (
|
|
623
|
+
if (Z.includes(s))
|
|
624
624
|
return !0;
|
|
625
625
|
throw new Error(
|
|
626
626
|
`Invalid identifier: ${r}. Expected format: <Chain>.<Ticker> or <Chain>.<Ticker>-<ContractAddress>`
|
|
627
627
|
);
|
|
628
|
-
},
|
|
629
|
-
function
|
|
628
|
+
}, S = 8, v = (r) => 10n ** BigInt(r), $ = (r) => Math.log10(parseFloat(r.toString()));
|
|
629
|
+
function k({
|
|
630
630
|
value: r,
|
|
631
|
-
bigIntDecimal: t =
|
|
632
|
-
decimal: e =
|
|
631
|
+
bigIntDecimal: t = S,
|
|
632
|
+
decimal: e = S
|
|
633
633
|
}) {
|
|
634
634
|
const s = r < 0n;
|
|
635
635
|
let n = r.toString().substring(s ? 1 : 0);
|
|
@@ -642,27 +642,25 @@ function N({
|
|
|
642
642
|
""
|
|
643
643
|
);
|
|
644
644
|
}
|
|
645
|
-
var
|
|
646
|
-
const
|
|
645
|
+
var w, R, I, U, P, ht, E, F;
|
|
646
|
+
const z = class z {
|
|
647
647
|
constructor(t) {
|
|
648
|
-
|
|
649
|
-
|
|
650
|
-
|
|
651
|
-
|
|
652
|
-
|
|
653
|
-
|
|
654
|
-
|
|
655
|
-
|
|
656
|
-
|
|
657
|
-
|
|
658
|
-
this
|
|
659
|
-
Math.max(d(this, M, Y).call(this, d(this, v, C).call(this, e)), this.decimal || 0)
|
|
660
|
-
), d(this, O, W).call(this, e);
|
|
648
|
+
T(this, w);
|
|
649
|
+
T(this, I);
|
|
650
|
+
T(this, P);
|
|
651
|
+
T(this, E);
|
|
652
|
+
p(this, "decimalMultiplier", 10n ** 8n);
|
|
653
|
+
p(this, "bigIntValue", 0n);
|
|
654
|
+
p(this, "decimal");
|
|
655
|
+
const e = V(t);
|
|
656
|
+
this.decimal = typeof t == "object" ? t.decimal : void 0, this.decimalMultiplier = v(
|
|
657
|
+
Math.max(tt(B(e)), this.decimal || 0)
|
|
658
|
+
), f(this, I, U).call(this, e);
|
|
661
659
|
}
|
|
662
660
|
static fromBigInt(t, e) {
|
|
663
|
-
return new
|
|
661
|
+
return new z({
|
|
664
662
|
decimal: e,
|
|
665
|
-
value:
|
|
663
|
+
value: k({ value: t, bigIntDecimal: e, decimal: e })
|
|
666
664
|
});
|
|
667
665
|
}
|
|
668
666
|
static shiftDecimals({
|
|
@@ -671,24 +669,24 @@ const Q = class Q {
|
|
|
671
669
|
to: s
|
|
672
670
|
}) {
|
|
673
671
|
return this.fromBigInt(
|
|
674
|
-
t.getBaseValue("bigint") *
|
|
672
|
+
t.getBaseValue("bigint") * v(s) / v(e),
|
|
675
673
|
s
|
|
676
674
|
);
|
|
677
675
|
}
|
|
678
676
|
set(t) {
|
|
679
|
-
return
|
|
677
|
+
return f(this, I, U).call(this, V(t)), this;
|
|
680
678
|
}
|
|
681
679
|
add(...t) {
|
|
682
|
-
return
|
|
680
|
+
return f(this, w, R).call(this, "add", ...t);
|
|
683
681
|
}
|
|
684
682
|
sub(...t) {
|
|
685
|
-
return
|
|
683
|
+
return f(this, w, R).call(this, "sub", ...t);
|
|
686
684
|
}
|
|
687
685
|
mul(...t) {
|
|
688
|
-
return
|
|
686
|
+
return f(this, w, R).call(this, "mul", ...t);
|
|
689
687
|
}
|
|
690
688
|
div(...t) {
|
|
691
|
-
return
|
|
689
|
+
return f(this, w, R).call(this, "div", ...t);
|
|
692
690
|
}
|
|
693
691
|
gt(t) {
|
|
694
692
|
return this.bigIntValue > this.getBigIntValue(t);
|
|
@@ -708,7 +706,7 @@ const Q = class Q {
|
|
|
708
706
|
getValue(t) {
|
|
709
707
|
const e = this.formatBigIntToSafeValue(
|
|
710
708
|
this.bigIntValue,
|
|
711
|
-
this.decimal ||
|
|
709
|
+
this.decimal || $(this.decimalMultiplier)
|
|
712
710
|
);
|
|
713
711
|
switch (t) {
|
|
714
712
|
case "number":
|
|
@@ -720,7 +718,7 @@ const Q = class Q {
|
|
|
720
718
|
}
|
|
721
719
|
}
|
|
722
720
|
getBaseValue(t) {
|
|
723
|
-
const e = this.decimalMultiplier /
|
|
721
|
+
const e = this.decimalMultiplier / v(this.decimal || d.THOR), s = this.bigIntValue / e;
|
|
724
722
|
switch (t) {
|
|
725
723
|
case "number":
|
|
726
724
|
return Number(s);
|
|
@@ -733,13 +731,13 @@ const Q = class Q {
|
|
|
733
731
|
getBigIntValue(t, e) {
|
|
734
732
|
if (!e && typeof t == "object")
|
|
735
733
|
return t.bigIntValue;
|
|
736
|
-
const s =
|
|
737
|
-
return n === "0" || n === "undefined" ? 0n :
|
|
734
|
+
const s = V(t), n = B(s);
|
|
735
|
+
return n === "0" || n === "undefined" ? 0n : f(this, E, F).call(this, n, e);
|
|
738
736
|
}
|
|
739
737
|
formatBigIntToSafeValue(t, e) {
|
|
740
|
-
const s = e || this.decimal ||
|
|
738
|
+
const s = e || this.decimal || S, n = Math.max(
|
|
741
739
|
s,
|
|
742
|
-
|
|
740
|
+
$(this.decimalMultiplier)
|
|
743
741
|
), i = t < 0n, c = t.toString().substring(i ? 1 : 0), a = n - (c.length - 1), u = a > 0 ? "0".repeat(a) + c : c, l = u.length - n;
|
|
744
742
|
let h = u.slice(-n);
|
|
745
743
|
return parseInt(h[s]) >= 5 ? h = `${h.substring(0, s - 1)}${(parseInt(h[s - 1]) + 1).toString()}` : h = h.substring(0, s), `${i ? "-" : ""}${u.slice(
|
|
@@ -791,8 +789,8 @@ const Q = class Q {
|
|
|
791
789
|
return `${e === "start" ? t : ""}${h}${e === "end" ? t : ""}`;
|
|
792
790
|
}
|
|
793
791
|
};
|
|
794
|
-
|
|
795
|
-
const s =
|
|
792
|
+
w = new WeakSet(), R = function(t, ...e) {
|
|
793
|
+
const s = f(this, P, ht).call(this, this, ...e), n = v(s), i = e.reduce(
|
|
796
794
|
(a, u) => {
|
|
797
795
|
const l = this.getBigIntValue(u, s);
|
|
798
796
|
switch (t) {
|
|
@@ -813,70 +811,73 @@ A = new WeakSet(), S = function(t, ...e) {
|
|
|
813
811
|
},
|
|
814
812
|
//normalize is to precision multiplier base
|
|
815
813
|
this.bigIntValue * n / this.decimalMultiplier
|
|
816
|
-
), c =
|
|
814
|
+
), c = k({
|
|
817
815
|
bigIntDecimal: s,
|
|
818
|
-
decimal: Math.max(s,
|
|
816
|
+
decimal: Math.max(s, $(this.decimalMultiplier)),
|
|
819
817
|
value: i
|
|
820
818
|
});
|
|
821
819
|
return new this.constructor({ decimal: this.decimal, value: c, identifier: this.toString() });
|
|
822
|
-
},
|
|
823
|
-
const e =
|
|
824
|
-
this.bigIntValue =
|
|
825
|
-
},
|
|
820
|
+
}, I = new WeakSet(), U = function(t) {
|
|
821
|
+
const e = B(t) || "0";
|
|
822
|
+
this.bigIntValue = f(this, E, F).call(this, e);
|
|
823
|
+
}, P = new WeakSet(), ht = function(...t) {
|
|
826
824
|
const e = t.map(
|
|
827
|
-
(s) => typeof s == "object" ? s.decimal ||
|
|
825
|
+
(s) => typeof s == "object" ? s.decimal || $(s.decimalMultiplier) : tt(B(s))
|
|
828
826
|
).filter(Boolean);
|
|
829
|
-
return Math.max(...e,
|
|
830
|
-
},
|
|
831
|
-
const s = e ?
|
|
827
|
+
return Math.max(...e, S);
|
|
828
|
+
}, E = new WeakSet(), F = function(t, e) {
|
|
829
|
+
const s = e ? v(e) : this.decimalMultiplier, n = $(s), [i = "", c = ""] = t.split(".");
|
|
832
830
|
return BigInt(`${i}${c.padEnd(n, "0")}`);
|
|
833
|
-
}, v = new WeakSet(), C = function(t) {
|
|
834
|
-
const s = `${typeof t == "number" ? Number(t).toLocaleString("fullwide", {
|
|
835
|
-
useGrouping: !1,
|
|
836
|
-
maximumFractionDigits: 20
|
|
837
|
-
}) : q(t)}`.replaceAll(",", ".").split(".");
|
|
838
|
-
return s.length > 1 ? `${s.slice(0, -1).join("")}.${s.at(-1)}` : s[0];
|
|
839
|
-
}, M = new WeakSet(), Y = function(t) {
|
|
840
|
-
var s;
|
|
841
|
-
const e = ((s = t.split(".")[1]) == null ? void 0 : s.length) || 0;
|
|
842
|
-
return Math.max(e, I);
|
|
843
831
|
};
|
|
844
|
-
let
|
|
845
|
-
|
|
832
|
+
let C = z;
|
|
833
|
+
const te = Intl.NumberFormat("fullwide", {
|
|
834
|
+
useGrouping: !1,
|
|
835
|
+
maximumFractionDigits: 20
|
|
836
|
+
});
|
|
837
|
+
function B(r) {
|
|
838
|
+
const e = `${typeof r == "number" ? te.format(r) : V(r)}`.replaceAll(",", ".").split(".");
|
|
839
|
+
return e.length > 1 ? `${e.slice(0, -1).join("")}.${e.at(-1)}` : e[0];
|
|
840
|
+
}
|
|
841
|
+
function tt(r) {
|
|
842
|
+
var e;
|
|
843
|
+
const t = ((e = r.split(".")[1]) == null ? void 0 : e.length) || 0;
|
|
844
|
+
return Math.max(t, S);
|
|
845
|
+
}
|
|
846
|
+
function V(r) {
|
|
846
847
|
return typeof r == "object" ? "getValue" in r ? r.getValue("string") : r.value : r;
|
|
847
848
|
}
|
|
848
|
-
const
|
|
849
|
-
let
|
|
850
|
-
const
|
|
851
|
-
if (!
|
|
849
|
+
const q = (r, t) => typeof r == "bigint" ? k({ value: r, bigIntDecimal: t, decimal: t }) : r;
|
|
850
|
+
let W;
|
|
851
|
+
const et = (r) => {
|
|
852
|
+
if (!W)
|
|
852
853
|
throw new Error("Static assets not loaded, call await AssetValue.loadStaticAssets() first");
|
|
853
|
-
return
|
|
854
|
-
},
|
|
855
|
-
|
|
856
|
-
const e = await
|
|
857
|
-
return new
|
|
858
|
-
},
|
|
859
|
-
class
|
|
854
|
+
return W.get(r.toUpperCase()) || { decimal: d.THOR, identifier: "" };
|
|
855
|
+
}, st = async (r, t = 0) => {
|
|
856
|
+
Zt(r);
|
|
857
|
+
const e = await St(G(r)), s = q(t, e);
|
|
858
|
+
return new y({ decimal: e, value: s, identifier: r });
|
|
859
|
+
}, rt = /* @__PURE__ */ new Map();
|
|
860
|
+
class y extends C {
|
|
860
861
|
constructor(e) {
|
|
861
|
-
const s = "identifier" in e ? e.identifier : `${e.chain}.${e.symbol}`, n =
|
|
862
|
+
const s = "identifier" in e ? e.identifier : `${e.chain}.${e.symbol}`, n = rt.get(s);
|
|
862
863
|
if (n)
|
|
863
864
|
return n.set(e.value);
|
|
864
865
|
super(
|
|
865
|
-
e.value instanceof
|
|
866
|
+
e.value instanceof C ? e.value : { decimal: e.decimal, value: e.value }
|
|
866
867
|
);
|
|
867
|
-
|
|
868
|
-
|
|
869
|
-
|
|
868
|
+
p(this, "address");
|
|
869
|
+
p(this, "isSynthetic", !1);
|
|
870
|
+
p(this, "isGasAsset", !1);
|
|
870
871
|
// @ts-expect-error cache is false positive on that case
|
|
871
|
-
|
|
872
|
+
p(this, "chain");
|
|
872
873
|
// @ts-expect-error cache is false positive on that case
|
|
873
|
-
|
|
874
|
+
p(this, "symbol");
|
|
874
875
|
// @ts-expect-error cache is false positive on that case
|
|
875
|
-
|
|
876
|
+
p(this, "ticker");
|
|
876
877
|
// @ts-expect-error cache is false positive on that case
|
|
877
|
-
|
|
878
|
-
const i =
|
|
879
|
-
this.type =
|
|
878
|
+
p(this, "type");
|
|
879
|
+
const i = G(s);
|
|
880
|
+
this.type = It(i), this.chain = i.chain, this.ticker = i.ticker, this.symbol = i.symbol, this.address = i.address, this.isSynthetic = i.isSynthetic, this.isGasAsset = i.isGasAsset, rt.set(s, this);
|
|
880
881
|
}
|
|
881
882
|
toString(e = !1) {
|
|
882
883
|
const s = this.isSynthetic ? this.symbol.split("-")[0] : this.ticker;
|
|
@@ -889,24 +890,24 @@ class w extends E {
|
|
|
889
890
|
return this.chain === e && this.symbol === s;
|
|
890
891
|
}
|
|
891
892
|
static async fromString(e, s = 0) {
|
|
892
|
-
return
|
|
893
|
+
return st(e, s);
|
|
893
894
|
}
|
|
894
895
|
static fromStringSync(e, s = 0) {
|
|
895
|
-
const { isSynthetic: n } =
|
|
896
|
+
const { isSynthetic: n } = G(e), { decimal: i, identifier: c } = et(
|
|
896
897
|
e
|
|
897
|
-
), a =
|
|
898
|
-
return c ? new
|
|
898
|
+
), a = q(s, i);
|
|
899
|
+
return c ? new y({ decimal: i, identifier: c, value: a }) : n ? new y({ decimal: 8, identifier: e, value: a }) : void 0;
|
|
899
900
|
}
|
|
900
901
|
static async fromIdentifier(e, s = 0) {
|
|
901
|
-
return
|
|
902
|
+
return st(e, s);
|
|
902
903
|
}
|
|
903
904
|
static fromIdentifierSync(e, s = 0) {
|
|
904
|
-
const { decimal: n, identifier: i } =
|
|
905
|
-
return new
|
|
905
|
+
const { decimal: n, identifier: i } = et(e), c = q(s, n);
|
|
906
|
+
return new y({ decimal: n, identifier: i, value: c });
|
|
906
907
|
}
|
|
907
908
|
static fromChainOrSignature(e, s = 0) {
|
|
908
|
-
const { decimal: n, identifier: i } =
|
|
909
|
-
return new
|
|
909
|
+
const { decimal: n, identifier: i } = Ct(e), c = q(s, n);
|
|
910
|
+
return new y({ value: c, decimal: n, identifier: i });
|
|
910
911
|
}
|
|
911
912
|
static async loadStaticAssets() {
|
|
912
913
|
return new Promise(
|
|
@@ -919,10 +920,10 @@ class w extends E {
|
|
|
919
920
|
NativeList: i,
|
|
920
921
|
...c
|
|
921
922
|
} = await import("@swapkit/tokens");
|
|
922
|
-
|
|
923
|
-
(u, { tokens: l }) => (l.forEach(({ identifier: h, chain: _, ...
|
|
924
|
-
const
|
|
925
|
-
u.set(h, { identifier: h, decimal:
|
|
923
|
+
W = [i, ...Object.values(c)].reduce(
|
|
924
|
+
(u, { tokens: l }) => (l.forEach(({ identifier: h, chain: _, ...A }) => {
|
|
925
|
+
const N = "decimals" in A ? A.decimals : d[_];
|
|
926
|
+
u.set(h, { identifier: h, decimal: N });
|
|
926
927
|
}), u),
|
|
927
928
|
/* @__PURE__ */ new Map()
|
|
928
929
|
), e({ ok: !0 });
|
|
@@ -937,8 +938,8 @@ class w extends E {
|
|
|
937
938
|
);
|
|
938
939
|
}
|
|
939
940
|
}
|
|
940
|
-
const
|
|
941
|
-
const t =
|
|
941
|
+
const _e = (r) => {
|
|
942
|
+
const t = y.fromChainOrSignature(r);
|
|
942
943
|
switch (r) {
|
|
943
944
|
case o.Bitcoin:
|
|
944
945
|
case o.Litecoin:
|
|
@@ -955,17 +956,17 @@ const ge = (r) => {
|
|
|
955
956
|
default:
|
|
956
957
|
return t.set(1e-8);
|
|
957
958
|
}
|
|
958
|
-
},
|
|
959
|
+
}, G = (r) => {
|
|
959
960
|
const t = r.slice(0, 14).includes("/"), [e, s] = r.split(".").pop().split("/"), n = r.includes(".") && !t ? r : `${o.THORChain}.${s}`, [i, c] = n.split("."), [a, u] = (t ? s : c).split("-");
|
|
960
961
|
return {
|
|
961
962
|
address: u == null ? void 0 : u.toLowerCase(),
|
|
962
963
|
chain: i,
|
|
963
|
-
isGasAsset:
|
|
964
|
+
isGasAsset: it({ chain: i, symbol: c }),
|
|
964
965
|
isSynthetic: t,
|
|
965
966
|
symbol: (t ? `${e}/` : "") + (u ? `${a}-${(u == null ? void 0 : u.toLowerCase()) ?? ""}` : c),
|
|
966
967
|
ticker: a
|
|
967
968
|
};
|
|
968
|
-
},
|
|
969
|
+
}, ee = {
|
|
969
970
|
/**
|
|
970
971
|
* Core
|
|
971
972
|
*/
|
|
@@ -1022,47 +1023,47 @@ const ge = (r) => {
|
|
|
1022
1023
|
*/
|
|
1023
1024
|
helpers_number_different_decimals: 99101
|
|
1024
1025
|
};
|
|
1025
|
-
class
|
|
1026
|
+
class dt extends Error {
|
|
1026
1027
|
constructor(t, e) {
|
|
1027
|
-
console.error(e), super(t, { cause: { code:
|
|
1028
|
+
console.error(e), super(t, { cause: { code: ee[t], message: t } }), Object.setPrototypeOf(this, dt.prototype);
|
|
1028
1029
|
}
|
|
1029
1030
|
}
|
|
1030
|
-
class b extends
|
|
1031
|
+
class b extends C {
|
|
1031
1032
|
eq(t) {
|
|
1032
1033
|
return this.eqValue(t);
|
|
1033
1034
|
}
|
|
1034
1035
|
static fromBigInt(t, e) {
|
|
1035
1036
|
return new b({
|
|
1036
1037
|
decimal: e,
|
|
1037
|
-
value:
|
|
1038
|
+
value: k({ value: t, bigIntDecimal: e, decimal: e })
|
|
1038
1039
|
});
|
|
1039
1040
|
}
|
|
1040
1041
|
}
|
|
1041
1042
|
export {
|
|
1042
|
-
|
|
1043
|
-
|
|
1044
|
-
|
|
1045
|
-
|
|
1043
|
+
y as AssetValue,
|
|
1044
|
+
C as BigIntArithmetics,
|
|
1045
|
+
Xt as RequestClient,
|
|
1046
|
+
dt as SwapKitError,
|
|
1046
1047
|
b as SwapKitNumber,
|
|
1047
|
-
|
|
1048
|
-
|
|
1049
|
-
|
|
1050
|
-
|
|
1051
|
-
|
|
1052
|
-
|
|
1053
|
-
|
|
1054
|
-
|
|
1055
|
-
|
|
1056
|
-
|
|
1057
|
-
|
|
1058
|
-
|
|
1059
|
-
|
|
1060
|
-
|
|
1061
|
-
|
|
1062
|
-
|
|
1063
|
-
|
|
1064
|
-
|
|
1048
|
+
ie as assetFromString,
|
|
1049
|
+
fe as derivationPathToString,
|
|
1050
|
+
oe as filterAssets,
|
|
1051
|
+
k as formatBigIntToSafeValue,
|
|
1052
|
+
ne as gasFeeMultiplier,
|
|
1053
|
+
It as getAssetType,
|
|
1054
|
+
Mt as getAsymmetricAssetShare,
|
|
1055
|
+
ce as getAsymmetricAssetWithdrawAmount,
|
|
1056
|
+
Bt as getAsymmetricRuneShare,
|
|
1057
|
+
ae as getAsymmetricRuneWithdrawAmount,
|
|
1058
|
+
Ct as getCommonAssetInfo,
|
|
1059
|
+
St as getDecimal,
|
|
1060
|
+
le as getEstimatedPoolShare,
|
|
1061
|
+
he as getLiquiditySlippage,
|
|
1062
|
+
de as getMemoFor,
|
|
1063
|
+
_e as getMinAmountByChain,
|
|
1064
|
+
Vt as getSymmetricPoolShare,
|
|
1065
|
+
ue as getSymmetricWithdraw,
|
|
1065
1066
|
me as getTHORNameCost,
|
|
1066
|
-
|
|
1067
|
-
|
|
1067
|
+
it as isGasAsset,
|
|
1068
|
+
pe as validateTHORName
|
|
1068
1069
|
};
|
package/package.json
CHANGED
|
@@ -9,15 +9,15 @@
|
|
|
9
9
|
"vite": "4.4.9",
|
|
10
10
|
"vitest": "0.34.4",
|
|
11
11
|
"@internal/config": "0.0.0-rc.1",
|
|
12
|
-
"@swapkit/tokens": "1.0.0-rc.
|
|
13
|
-
"@swapkit/types": "1.0.0-rc.
|
|
12
|
+
"@swapkit/tokens": "1.0.0-rc.9",
|
|
13
|
+
"@swapkit/types": "1.0.0-rc.9"
|
|
14
14
|
},
|
|
15
15
|
"eslintConfig": {
|
|
16
16
|
"extends": "../../../internal/eslint-config"
|
|
17
17
|
},
|
|
18
18
|
"peerDependencies": {
|
|
19
|
-
"@swapkit/tokens": "1.0.0-rc.
|
|
20
|
-
"@swapkit/types": "1.0.0-rc.
|
|
19
|
+
"@swapkit/tokens": "1.0.0-rc.9",
|
|
20
|
+
"@swapkit/types": "1.0.0-rc.9"
|
|
21
21
|
},
|
|
22
22
|
"exports": {
|
|
23
23
|
".": {
|
|
@@ -42,7 +42,7 @@
|
|
|
42
42
|
"repository": "https://github.com/thorswap/SwapKit.git",
|
|
43
43
|
"type": "module",
|
|
44
44
|
"types": "./dist/index.d.ts",
|
|
45
|
-
"version": "1.0.0-rc.
|
|
45
|
+
"version": "1.0.0-rc.27",
|
|
46
46
|
"scripts": {
|
|
47
47
|
"build": "vite build",
|
|
48
48
|
"clean": "rm -rf dist vite.config.ts.* .turbo node_modules",
|
|
@@ -87,7 +87,7 @@ export class BigIntArithmetics {
|
|
|
87
87
|
|
|
88
88
|
// use the multiplier to keep track of decimal point - defaults to 8 if lower than 8
|
|
89
89
|
this.decimalMultiplier = toMultiplier(
|
|
90
|
-
Math.max(
|
|
90
|
+
Math.max(getFloatDecimals(toSafeValue(value)), this.decimal || 0),
|
|
91
91
|
);
|
|
92
92
|
this.#setValue(value);
|
|
93
93
|
}
|
|
@@ -164,7 +164,7 @@ export class BigIntArithmetics {
|
|
|
164
164
|
if (!decimal && typeof value === 'object') return value.bigIntValue;
|
|
165
165
|
|
|
166
166
|
const stringValue = getStringValue(value);
|
|
167
|
-
const safeValue =
|
|
167
|
+
const safeValue = toSafeValue(stringValue);
|
|
168
168
|
|
|
169
169
|
if (safeValue === '0' || safeValue === 'undefined') return 0n;
|
|
170
170
|
return this.#toBigInt(safeValue, decimal);
|
|
@@ -336,7 +336,7 @@ export class BigIntArithmetics {
|
|
|
336
336
|
}
|
|
337
337
|
|
|
338
338
|
#setValue(value: InitialisationValueType) {
|
|
339
|
-
const safeValue =
|
|
339
|
+
const safeValue = toSafeValue(value) || '0';
|
|
340
340
|
this.bigIntValue = this.#toBigInt(safeValue);
|
|
341
341
|
}
|
|
342
342
|
|
|
@@ -345,7 +345,7 @@ export class BigIntArithmetics {
|
|
|
345
345
|
.map((arg) =>
|
|
346
346
|
typeof arg === 'object'
|
|
347
347
|
? arg.decimal || decimalFromMultiplier(arg.decimalMultiplier)
|
|
348
|
-
:
|
|
348
|
+
: getFloatDecimals(toSafeValue(arg)),
|
|
349
349
|
)
|
|
350
350
|
.filter(Boolean) as number[];
|
|
351
351
|
return Math.max(...decimals, DEFAULT_DECIMAL);
|
|
@@ -358,33 +358,32 @@ export class BigIntArithmetics {
|
|
|
358
358
|
|
|
359
359
|
return BigInt(`${integerPart}${decimalPart.padEnd(padDecimal, '0')}`);
|
|
360
360
|
}
|
|
361
|
+
}
|
|
361
362
|
|
|
362
|
-
|
|
363
|
-
|
|
364
|
-
|
|
365
|
-
|
|
366
|
-
useGrouping: false,
|
|
367
|
-
maximumFractionDigits: 20,
|
|
368
|
-
})
|
|
369
|
-
: getStringValue(value);
|
|
370
|
-
|
|
371
|
-
const splitValue = `${parsedValue}`.replaceAll(',', '.').split('.');
|
|
372
|
-
|
|
373
|
-
return splitValue.length > 1
|
|
374
|
-
? `${splitValue.slice(0, -1).join('')}.${splitValue.at(-1)}`
|
|
375
|
-
: splitValue[0];
|
|
376
|
-
}
|
|
363
|
+
const numberFormatter = Intl.NumberFormat('fullwide', {
|
|
364
|
+
useGrouping: false,
|
|
365
|
+
maximumFractionDigits: 20,
|
|
366
|
+
});
|
|
377
367
|
|
|
378
|
-
|
|
379
|
-
|
|
380
|
-
|
|
381
|
-
}
|
|
368
|
+
function toSafeValue(value: InitialisationValueType) {
|
|
369
|
+
const parsedValue =
|
|
370
|
+
typeof value === 'number' ? numberFormatter.format(value) : getStringValue(value);
|
|
371
|
+
const splitValue = `${parsedValue}`.replaceAll(',', '.').split('.');
|
|
372
|
+
|
|
373
|
+
return splitValue.length > 1
|
|
374
|
+
? `${splitValue.slice(0, -1).join('')}.${splitValue.at(-1)}`
|
|
375
|
+
: splitValue[0];
|
|
376
|
+
}
|
|
377
|
+
|
|
378
|
+
function getFloatDecimals(value: string) {
|
|
379
|
+
const decimals = value.split('.')[1]?.length || 0;
|
|
380
|
+
return Math.max(decimals, DEFAULT_DECIMAL);
|
|
382
381
|
}
|
|
383
382
|
|
|
384
|
-
function getStringValue(
|
|
385
|
-
return typeof
|
|
386
|
-
? 'getValue' in
|
|
387
|
-
?
|
|
388
|
-
:
|
|
389
|
-
:
|
|
383
|
+
function getStringValue(param: SKBigIntParams) {
|
|
384
|
+
return typeof param === 'object'
|
|
385
|
+
? 'getValue' in param
|
|
386
|
+
? param.getValue('string')
|
|
387
|
+
: param.value
|
|
388
|
+
: param;
|
|
390
389
|
}
|