@swapkit/helpers 1.0.0-rc.23 → 1.0.0-rc.24
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.cjs +1 -1
- package/dist/index.d.ts +11 -1
- package/dist/index.es.js +263 -255
- package/package.json +1 -1
- package/src/helpers/asset.ts +19 -11
- package/src/modules/assetValue.ts +5 -4
package/dist/index.cjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";var Te=Object.create;var D=Object.defineProperty;var ve=Object.getOwnPropertyDescriptor;var Se=Object.getOwnPropertyNames;var $e=Object.getPrototypeOf,Re=Object.prototype.hasOwnProperty;var Ie=(r,e,t)=>e in r?D(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t;var Be=(r,e,t,s)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of Se(e))!Re.call(r,n)&&n!==t&&D(r,n,{get:()=>e[n],enumerable:!(s=ve(e,n))||s.enumerable});return r};var Ee=(r,e,t)=>(t=r!=null?Te($e(r)):{},Be(e||!r||!r.__esModule?D(t,"default",{value:r,enumerable:!0}):t,r));var p=(r,e,t)=>(Ie(r,typeof e!="symbol"?e+"":e,t),t),Me=(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)=>(Me(r,e,"access private method"),t);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const i=require("@swapkit/types"),Oe="0x313ce567",re=async({chain:r,to:e})=>{try{const{result:t}=await ge.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:Oe},"latest"]})});return parseInt(BigInt(t).toString())}catch(t){return console.error(t),i.BaseDecimal[r]}},Ve=async r=>{if(r===i.Chain.Ethereum)return i.BaseDecimal.ETH;const[,e]=r.split("-");return e!=null&&e.startsWith("0x")?re({chain:i.Chain.Ethereum,to:e}):i.BaseDecimal.ETH},qe=async r=>{const[,e]=r.split("-");return e!=null&&e.startsWith("0x")?re({chain:i.Chain.Avalanche,to:e.toLowerCase()}):i.BaseDecimal.AVAX},ke=async r=>(r===i.Chain.BinanceSmartChain,i.BaseDecimal.BSC),ne=async({chain:r,symbol:e})=>{switch(r){case i.Chain.Ethereum:return Ve(e);case i.Chain.Avalanche:return qe(e);case i.Chain.BinanceSmartChain:return ke(e);default:return i.BaseDecimal[r]}},Pe={[i.FeeOption.Average]:1.2,[i.FeeOption.Fast]:1.5,[i.FeeOption.Fastest]:2},ie=({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"}},ae=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]}}},oe=({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"}},xe=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}},Ne=new RegExp(/(.)\1{6}|\.ORG|\.NET|\.FINANCE|\.COM|WWW|HTTP|\\\\|\/\/|[\s$%:[\]]/,"gmi"),De=r=>i.EVMChainList.includes(r.chain)?!r.isGasAsset&&r.address&&!Number.isNaN(r.decimal):!0,He=r=>r.filter(e=>!e.toString().includes("undefined")&&!Ne.test(e.toString())&&De(e)),ce=({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)},ue=({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)},je=({percent:r,runeDepth:e,liquidityUnits:t,poolUnits:s})=>ce({runeDepth:e,liquidityUnits:t,poolUnits:s}).mul(r),Le=({percent:r,assetDepth:e,liquidityUnits:t,poolUnits:s})=>ue({assetDepth:e,liquidityUnits:t,poolUnits:s}).mul(r),m=r=>f.fromBigInt(BigInt(r),i.BaseDecimal.THOR),le=({liquidityUnits:r,poolUnits:e,runeDepth:t,assetDepth:s})=>({assetAmount:m(s).mul(r).div(e),runeAmount:m(t).mul(r).div(e)}),Fe=({liquidityUnits:r,poolUnits:e,runeDepth:t,assetDepth:s,percent:n})=>Object.fromEntries(Object.entries(le({liquidityUnits:r,poolUnits:e,runeDepth:t,assetDepth:s})).map(([a,c])=>[a,c.mul(n)])),Ue=({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),x=l.mul(h),be=c.mul(o),Ce=u.mul(g.add(w.add(x.mul(2)))),we=g.add(w.add(be.mul(2))),J=Ce.div(we),N=m(s).add(J);if(J.getBaseValue("number")===0)return N.div(u).getBaseValue("number");const Ae=u.add(N);return N.div(Ae).getBaseValue("number")},We=({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"))},Ge=({symbol:r,ticker:e,chain:t})=>t==="ETH"&&e!=="ETH"?`${e}-${r.slice(-3)}`:r,Ke=(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=Ge({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""}},Ye=r=>{if(r<0)throw new Error("Invalid number of year");return 10+r},ze=r=>{if(r.length>30)return!1;const e=/^[a-zA-Z0-9+_-]+$/g;return!!r.match(e)},Je=([r,e,t,s,n])=>`${r}'/${e}'/${t}'/${s}${typeof n!="number"?"":`/${n}`}`;class Q 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 he extends Error{constructor(e){super("Request timed out"),Object.defineProperty(this,"request",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.name="TimeoutError",this.request=e}}const O=r=>r!==null&&typeof r=="object",M=(...r)=>{for(const e of r)if((!O(e)||Array.isArray(e))&&e!==void 0)throw new TypeError("The `options` argument must be an object");return K({},...r)},de=(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},K=(...r)=>{let e={},t={};for(const s of r)if(Array.isArray(s))Array.isArray(e)||(e=[]),e=[...e,...s];else if(O(s)){for(let[n,a]of Object.entries(s))O(a)&&n in e&&(a=K(e[n],a)),e={...e,[n]:a};O(s.headers)&&(t=de(t,s.headers),e.headers=t)}return e},Qe=(()=>{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})(),Xe=typeof globalThis.AbortController=="function",Ze=typeof globalThis.ReadableStream=="function",et=typeof globalThis.FormData=="function",me=["get","post","put","patch","head","delete"],tt={json:"application/json",text:"text/*",formData:"multipart/form-data",arrayBuffer:"*/*",blob:"*/*"},H=2147483647,pe=Symbol("stop"),st={json:!0,parseJson:!0,searchParams:!0,prefixUrl:!0,retry:!0,timeout:!0,hooks:!0,throwHttpErrors:!0,onDownloadProgress:!0,fetch:!0},rt={method:!0,headers:!0,body:!0,mode:!0,credentials:!0,cache:!0,redirect:!0,referrer:!0,referrerPolicy:!0,integrity:!0,keepalive:!0,signal:!0,window:!0,dispatcher:!0,duplex:!0},nt=r=>me.includes(r)?r.toUpperCase():r,it=["get","put","head","delete","options","trace"],at=[408,413,429,500,502,503,504],fe=[413,429,503],X={limit:2,methods:it,statusCodes:at,afterStatusCodes:fe,maxRetryAfter:Number.POSITIVE_INFINITY,backoffLimit:Number.POSITIVE_INFINITY,delay:r=>.3*2**(r-1)*1e3},ot=(r={})=>{if(typeof r=="number")return{...X,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{...X,...r,afterStatusCodes:fe}};async function ct(r,e,t,s){return new Promise((n,a)=>{const c=setTimeout(()=>{t&&t.abort(),a(new he(r))},s.timeout);s.fetch(r,e).then(n).catch(a).then(()=>{clearTimeout(c)})})}async function ut(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 lt=(r,e)=>{const t={};for(const s in e)!(s in rt)&&!(s in st)&&!(s in r)&&(t[s]=e[s]);return t};class q{static create(e,t){const s=new q(e,t),n=async()=>{if(typeof s._options.timeout=="number"&&s._options.timeout>H)throw new RangeError(`The \`timeout\` option cannot be greater than ${H}`);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 Q(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(!Ze)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(tt))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:de(this._input.headers,t.headers),hooks:K({beforeRequest:[],beforeRetry:[],beforeError:[],afterResponse:[]},t.hooks),method:nt(t.method??this._input.method),prefixUrl:String(t.prefixUrl||""),retry:ot(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(Xe){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(Qe&&(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);(et&&this._options.body instanceof globalThis.FormData||this._options.body instanceof URLSearchParams)&&!(this._options.headers&&this._options.headers["content-type"])&&this.request.headers.delete("content-type"),this.request=new globalThis.Request(new globalThis.Request(a,{...this.request}),this._options)}this._options.json!==void 0&&(this._options.body=JSON.stringify(this._options.json),this.request.headers.set("content-type",this._options.headers.get("content-type")??"application/json"),this.request=new globalThis.Request(this.request,{body:this._options.body}))}_calculateRetryDelay(e){if(this._retryCount++,this._retryCount<this._options.retry.limit&&!(e instanceof he)){if(e instanceof Q){if(!this._options.retry.statusCodes.includes(e.response.status))return 0;const 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),H);if(s!==0&&this._retryCount>0){await ut(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})===pe)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=lt(this.request,this._options);return this._options.timeout===!1?this._options.fetch(this.request.clone(),e):ct(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)=>q.create(t,M(r,s));for(const t of me)e[t]=(s,n)=>q.create(s,M(r,n,{method:t}));return e.create=t=>L(M(t)),e.extend=t=>L(M(r,t)),e.stop=pe,e},ht=L(),dt=ht,mt=typeof window<"u"?{}:{referrer:"https://sk.thorswap.net",referer:"https://sk.thorswap.net"},Z=dt.create({headers:mt}),ge={get:(r,e)=>Z.get(r,e).json(),post:(r,e)=>Z.post(r,e).json()},ee=Object.values(i.Chain),pt=(r="")=>{const e=r.toUpperCase(),[t]=e.split(".");if(ee.includes(t))return!0;const[s]=e.split("/");if(ee.includes(s))return!0;throw new Error(`Invalid identifier: ${r}. Expected format: <Chain>.<Ticker> or <Chain>.<Ticker>-<ContractAddress>`)},R=8,A=r=>10n**BigInt(r),v=r=>Math.log10(parseFloat(r.toString()));function I({value:r,bigIntDecimal:e=R,decimal:t=R}){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,k,_e,P,ye,B,F,C,$,E,U;const z=class z{constructor(e){y(this,b);y(this,k);y(this,P);y(this,B);y(this,C);y(this,E);p(this,"decimalMultiplier",10n**8n);p(this,"bigIntValue",0n);p(this,"decimal");const t=j(e);this.decimal=typeof e=="object"?e.decimal:void 0,this.decimalMultiplier=A(Math.max(d(this,E,U).call(this,d(this,C,$).call(this,t)),this.decimal||0)),d(this,k,_e).call(this,t)}static fromBigInt(e,t){return new z({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 new this.constructor({decimal:this.decimal,value:e,identifier:this.toString()})}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=j(e),n=d(this,C,$).call(this,s);return n==="0"||n==="undefined"?0n:d(this,B,F).call(this,n,t)}formatBigIntToSafeValue(e,t){const s=t||this.decimal||R,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,P,ye).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()})},k=new WeakSet,_e=function(e){const t=d(this,C,$).call(this,e)||"0";this.bigIntValue=d(this,B,F).call(this,t)},P=new WeakSet,ye=function(...e){const t=e.map(s=>typeof s=="object"?s.decimal||v(s.decimalMultiplier):d(this,E,U).call(this,d(this,C,$).call(this,s))).filter(Boolean);return Math.max(...t,R)},B=new WeakSet,F=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,$=function(e){const s=`${typeof e=="number"?Number(e).toLocaleString("fullwide",{useGrouping:!1,maximumFractionDigits:20}):j(e)}`.replaceAll(",",".").split(".");return s.length>1?`${s.slice(0,-1).join("")}.${s.at(-1)}`:s[0]},E=new WeakSet,U=function(e){var s;const t=((s=e.split(".")[1])==null?void 0:s.length)||0;return Math.max(t,R)};let T=z;function j(r){return typeof r=="object"?"getValue"in r?r.getValue("string"):r.value:r}const V=(r,e)=>typeof r=="bigint"?I({value:r,bigIntDecimal:e,decimal:e}):r;let W;const te=r=>{if(!W)throw new Error("Static assets not loaded, call await AssetValue.loadStaticAssets() first");return W.get(r.toUpperCase())||{decimal:i.BaseDecimal.THOR,identifier:""}},se=async(r,e=0)=>{pt(r);const t=await ne(G(r)),s=V(e,t);return new _({decimal:t,value:s,identifier:r})};class _ extends T{constructor(t){super(t.value instanceof T?t.value:{decimal:t.decimal,value:t.value});p(this,"address");p(this,"chain");p(this,"isSynthetic",!1);p(this,"isGasAsset",!1);p(this,"symbol");p(this,"ticker");p(this,"type");const s="identifier"in t?t.identifier:`${t.chain}.${t.symbol}`,n=G(s);this.type=oe(n),this.chain=n.chain,this.ticker=n.ticker,this.symbol=n.symbol,this.address=n.address,this.isSynthetic=n.isSynthetic,this.isGasAsset=n.isGasAsset}get assetValue(){return`${this.getValue("string")} ${this.ticker}`}toString(t=!1){const s=this.isSynthetic?this.symbol.split("-")[0]:`${this.chain}.${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 se(t,s)}static fromStringSync(t,s=0){const{isSynthetic:n}=G(t),{decimal:a,identifier:c}=te(t),o=V(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 se(t,s)}static fromIdentifierSync(t,s=0){const{decimal:n,identifier:a}=te(t),c=V(s,n);return new _({decimal:n,identifier:a,value:c})}static fromChainOrSignature(t,s=0){const{decimal:n,identifier:a}=ae(t),c=V(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");W=[a,...Object.values(c)].reduce((u,{tokens:l})=>(l.forEach(({identifier:h,chain:g,...w})=>{const x="decimals"in w?w.decimals:i.BaseDecimal[g];u.set(h,{identifier:h,decimal:x})}),u),new Map),t({ok:!0})}catch(n){console.error(n),s({ok:!1,error:n,message:"Couldn't load static assets. Ensure you have installed @swapkit/tokens package"})}})}}const ft=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)}},G=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:ie({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 Y extends Error{constructor(e,t){console.error(t),super(e,{cause:{code:gt[e],message:e}}),Object.setPrototypeOf(this,Y.prototype)}}class f extends T{eq(e){return this.eqValue(e)}static fromBigInt(e,t){return new f({decimal:t,value:I({value:e,bigIntDecimal:t,decimal:t})})}}exports.AssetValue=_;exports.BigIntArithmetics=T;exports.RequestClient=ge;exports.SwapKitError=Y;exports.SwapKitNumber=f;exports.assetFromString=xe;exports.derivationPathToString=Je;exports.filterAssets=He;exports.formatBigIntToSafeValue=I;exports.gasFeeMultiplier=Pe;exports.getAssetType=oe;exports.getAsymmetricAssetShare=ue;exports.getAsymmetricAssetWithdrawAmount=Le;exports.getAsymmetricRuneShare=ce;exports.getAsymmetricRuneWithdrawAmount=je;exports.getCommonAssetInfo=ae;exports.getDecimal=ne;exports.getEstimatedPoolShare=Ue;exports.getLiquiditySlippage=We;exports.getMemoFor=Ke;exports.getMinAmountByChain=ft;exports.getSymmetricPoolShare=le;exports.getSymmetricWithdraw=Fe;exports.getTHORNameCost=Ye;exports.isGasAsset=ie;exports.validateTHORName=ze;
|
|
1
|
+
"use strict";var Te=Object.create;var D=Object.defineProperty;var ve=Object.getOwnPropertyDescriptor;var Se=Object.getOwnPropertyNames;var $e=Object.getPrototypeOf,Re=Object.prototype.hasOwnProperty;var Ie=(r,e,t)=>e in r?D(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t;var Be=(r,e,t,s)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of Se(e))!Re.call(r,n)&&n!==t&&D(r,n,{get:()=>e[n],enumerable:!(s=ve(e,n))||s.enumerable});return r};var Ee=(r,e,t)=>(t=r!=null?Te($e(r)):{},Be(e||!r||!r.__esModule?D(t,"default",{value:r,enumerable:!0}):t,r));var p=(r,e,t)=>(Ie(r,typeof e!="symbol"?e+"":e,t),t),Me=(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)=>(Me(r,e,"access private method"),t);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const i=require("@swapkit/types"),Oe="0x313ce567",ne=async({chain:r,to:e})=>{try{const{result:t}=await ge.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:Oe},"latest"]})});return parseInt(BigInt(t).toString())}catch(t){return console.error(t),i.BaseDecimal[r]}},Ve=async r=>{if(r===i.Chain.Ethereum)return i.BaseDecimal.ETH;const[,e]=r.split("-");return e!=null&&e.startsWith("0x")?ne({chain:i.Chain.Ethereum,to:e}):i.BaseDecimal.ETH},qe=async r=>{const[,e]=r.split("-");return e!=null&&e.startsWith("0x")?ne({chain:i.Chain.Avalanche,to:e.toLowerCase()}):i.BaseDecimal.AVAX},ke=async r=>(r===i.Chain.BinanceSmartChain,i.BaseDecimal.BSC),ie=async({chain:r,symbol:e})=>{switch(r){case i.Chain.Ethereum:return Ve(e);case i.Chain.Avalanche:return qe(e);case i.Chain.BinanceSmartChain:return ke(e);default:return i.BaseDecimal[r]}},Pe={[i.FeeOption.Average]:1.2,[i.FeeOption.Fast]:1.5,[i.FeeOption.Fastest]:2},K=({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"}},ae=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]}}},oe=({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"}},xe=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}},Ne=new RegExp(/(.)\1{6}|\.ORG|\.NET|\.FINANCE|\.COM|WWW|HTTP|\\\\|\/\/|[\s$%:[\]]/,"gmi"),De=r=>{const[e,t]=r.split(".");if(!i.EVMChainList.includes(e))return!0;const[,s]=t.split("-");return K({chain:e,symbol:t})||!!s},He=r=>r.filter(e=>{const t=`${e.chain}.${e.symbol}`;return!Ne.test(t)&&De(t)}),ce=({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)},ue=({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)},je=({percent:r,runeDepth:e,liquidityUnits:t,poolUnits:s})=>ce({runeDepth:e,liquidityUnits:t,poolUnits:s}).mul(r),Le=({percent:r,assetDepth:e,liquidityUnits:t,poolUnits:s})=>ue({assetDepth:e,liquidityUnits:t,poolUnits:s}).mul(r),m=r=>f.fromBigInt(BigInt(r),i.BaseDecimal.THOR),le=({liquidityUnits:r,poolUnits:e,runeDepth:t,assetDepth:s})=>({assetAmount:m(s).mul(r).div(e),runeAmount:m(t).mul(r).div(e)}),Fe=({liquidityUnits:r,poolUnits:e,runeDepth:t,assetDepth:s,percent:n})=>Object.fromEntries(Object.entries(le({liquidityUnits:r,poolUnits:e,runeDepth:t,assetDepth:s})).map(([a,c])=>[a,c.mul(n)])),Ue=({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),x=l.mul(h),be=c.mul(o),Ce=u.mul(g.add(w.add(x.mul(2)))),we=g.add(w.add(be.mul(2))),Q=Ce.div(we),N=m(s).add(Q);if(Q.getBaseValue("number")===0)return N.div(u).getBaseValue("number");const Ae=u.add(N);return N.div(Ae).getBaseValue("number")},We=({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"))},Ge=({symbol:r,ticker:e,chain:t})=>t==="ETH"&&e!=="ETH"?`${e}-${r.slice(-3)}`:r,Ke=(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=Ge({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""}},Ye=r=>{if(r<0)throw new Error("Invalid number of year");return 10+r},ze=r=>{if(r.length>30)return!1;const e=/^[a-zA-Z0-9+_-]+$/g;return!!r.match(e)},Je=([r,e,t,s,n])=>`${r}'/${e}'/${t}'/${s}${typeof n!="number"?"":`/${n}`}`;class X 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 he extends Error{constructor(e){super("Request timed out"),Object.defineProperty(this,"request",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.name="TimeoutError",this.request=e}}const O=r=>r!==null&&typeof r=="object",M=(...r)=>{for(const e of r)if((!O(e)||Array.isArray(e))&&e!==void 0)throw new TypeError("The `options` argument must be an object");return Y({},...r)},de=(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},Y=(...r)=>{let e={},t={};for(const s of r)if(Array.isArray(s))Array.isArray(e)||(e=[]),e=[...e,...s];else if(O(s)){for(let[n,a]of Object.entries(s))O(a)&&n in e&&(a=Y(e[n],a)),e={...e,[n]:a};O(s.headers)&&(t=de(t,s.headers),e.headers=t)}return e},Qe=(()=>{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})(),Xe=typeof globalThis.AbortController=="function",Ze=typeof globalThis.ReadableStream=="function",et=typeof globalThis.FormData=="function",me=["get","post","put","patch","head","delete"],tt={json:"application/json",text:"text/*",formData:"multipart/form-data",arrayBuffer:"*/*",blob:"*/*"},H=2147483647,pe=Symbol("stop"),st={json:!0,parseJson:!0,searchParams:!0,prefixUrl:!0,retry:!0,timeout:!0,hooks:!0,throwHttpErrors:!0,onDownloadProgress:!0,fetch:!0},rt={method:!0,headers:!0,body:!0,mode:!0,credentials:!0,cache:!0,redirect:!0,referrer:!0,referrerPolicy:!0,integrity:!0,keepalive:!0,signal:!0,window:!0,dispatcher:!0,duplex:!0},nt=r=>me.includes(r)?r.toUpperCase():r,it=["get","put","head","delete","options","trace"],at=[408,413,429,500,502,503,504],fe=[413,429,503],Z={limit:2,methods:it,statusCodes:at,afterStatusCodes:fe,maxRetryAfter:Number.POSITIVE_INFINITY,backoffLimit:Number.POSITIVE_INFINITY,delay:r=>.3*2**(r-1)*1e3},ot=(r={})=>{if(typeof r=="number")return{...Z,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{...Z,...r,afterStatusCodes:fe}};async function ct(r,e,t,s){return new Promise((n,a)=>{const c=setTimeout(()=>{t&&t.abort(),a(new he(r))},s.timeout);s.fetch(r,e).then(n).catch(a).then(()=>{clearTimeout(c)})})}async function ut(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 lt=(r,e)=>{const t={};for(const s in e)!(s in rt)&&!(s in st)&&!(s in r)&&(t[s]=e[s]);return t};class q{static create(e,t){const s=new q(e,t),n=async()=>{if(typeof s._options.timeout=="number"&&s._options.timeout>H)throw new RangeError(`The \`timeout\` option cannot be greater than ${H}`);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 X(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(!Ze)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(tt))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:de(this._input.headers,t.headers),hooks:Y({beforeRequest:[],beforeRetry:[],beforeError:[],afterResponse:[]},t.hooks),method:nt(t.method??this._input.method),prefixUrl:String(t.prefixUrl||""),retry:ot(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(Xe){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(Qe&&(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);(et&&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 X){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),H);if(s!==0&&this._retryCount>0){await ut(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})===pe)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=lt(this.request,this._options);return this._options.timeout===!1?this._options.fetch(this.request.clone(),e):ct(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)=>q.create(t,M(r,s));for(const t of me)e[t]=(s,n)=>q.create(s,M(r,n,{method:t}));return e.create=t=>L(M(t)),e.extend=t=>L(M(r,t)),e.stop=pe,e},ht=L(),dt=ht,mt=typeof window<"u"?{}:{referrer:"https://sk.thorswap.net",referer:"https://sk.thorswap.net"},ee=dt.create({headers:mt}),ge={get:(r,e)=>ee.get(r,e).json(),post:(r,e)=>ee.post(r,e).json()},te=Object.values(i.Chain),pt=(r="")=>{const e=r.toUpperCase(),[t]=e.split(".");if(te.includes(t))return!0;const[s]=e.split("/");if(te.includes(s))return!0;throw new Error(`Invalid identifier: ${r}. Expected format: <Chain>.<Ticker> or <Chain>.<Ticker>-<ContractAddress>`)},R=8,A=r=>10n**BigInt(r),v=r=>Math.log10(parseFloat(r.toString()));function I({value:r,bigIntDecimal:e=R,decimal:t=R}){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,k,_e,P,ye,B,F,C,$,E,U;const J=class J{constructor(e){y(this,b);y(this,k);y(this,P);y(this,B);y(this,C);y(this,E);p(this,"decimalMultiplier",10n**8n);p(this,"bigIntValue",0n);p(this,"decimal");const t=j(e);this.decimal=typeof e=="object"?e.decimal:void 0,this.decimalMultiplier=A(Math.max(d(this,E,U).call(this,d(this,C,$).call(this,t)),this.decimal||0)),d(this,k,_e).call(this,t)}static fromBigInt(e,t){return new J({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 new this.constructor({decimal:this.decimal,value:e,identifier:this.toString()})}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=j(e),n=d(this,C,$).call(this,s);return n==="0"||n==="undefined"?0n:d(this,B,F).call(this,n,t)}formatBigIntToSafeValue(e,t){const s=t||this.decimal||R,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,P,ye).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()})},k=new WeakSet,_e=function(e){const t=d(this,C,$).call(this,e)||"0";this.bigIntValue=d(this,B,F).call(this,t)},P=new WeakSet,ye=function(...e){const t=e.map(s=>typeof s=="object"?s.decimal||v(s.decimalMultiplier):d(this,E,U).call(this,d(this,C,$).call(this,s))).filter(Boolean);return Math.max(...t,R)},B=new WeakSet,F=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,$=function(e){const s=`${typeof e=="number"?Number(e).toLocaleString("fullwide",{useGrouping:!1,maximumFractionDigits:20}):j(e)}`.replaceAll(",",".").split(".");return s.length>1?`${s.slice(0,-1).join("")}.${s.at(-1)}`:s[0]},E=new WeakSet,U=function(e){var s;const t=((s=e.split(".")[1])==null?void 0:s.length)||0;return Math.max(t,R)};let T=J;function j(r){return typeof r=="object"?"getValue"in r?r.getValue("string"):r.value:r}const V=(r,e)=>typeof r=="bigint"?I({value:r,bigIntDecimal:e,decimal:e}):r;let W;const se=r=>{if(!W)throw new Error("Static assets not loaded, call await AssetValue.loadStaticAssets() first");return W.get(r.toUpperCase())||{decimal:i.BaseDecimal.THOR,identifier:""}},re=async(r,e=0)=>{pt(r);const t=await ie(G(r)),s=V(e,t);return new _({decimal:t,value:s,identifier:r})};class _ extends T{constructor(t){const s="identifier"in t?t.identifier:`${t.chain}.${t.symbol}`;super(t.value instanceof T?t.value:{decimal:t.decimal,value:t.value});p(this,"address");p(this,"chain");p(this,"isSynthetic",!1);p(this,"isGasAsset",!1);p(this,"symbol");p(this,"ticker");p(this,"type");const n=G(s);this.type=oe(n),this.chain=n.chain,this.ticker=n.ticker,this.symbol=n.symbol,this.address=n.address,this.isSynthetic=n.isSynthetic,this.isGasAsset=n.isGasAsset}get assetValue(){return`${this.getValue("string")} ${this.ticker}`}toString(t=!1){const s=this.isSynthetic?this.symbol.split("-")[0]:`${this.chain}.${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 re(t,s)}static fromStringSync(t,s=0){const{isSynthetic:n}=G(t),{decimal:a,identifier:c}=se(t),o=V(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 re(t,s)}static fromIdentifierSync(t,s=0){const{decimal:n,identifier:a}=se(t),c=V(s,n);return new _({decimal:n,identifier:a,value:c})}static fromChainOrSignature(t,s=0){const{decimal:n,identifier:a}=ae(t),c=V(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");W=[a,...Object.values(c)].reduce((u,{tokens:l})=>(l.forEach(({identifier:h,chain:g,...w})=>{const x="decimals"in w?w.decimals:i.BaseDecimal[g];u.set(h,{identifier:h,decimal:x})}),u),new Map),t({ok:!0})}catch(n){console.error(n),s({ok:!1,error:n,message:"Couldn't load static assets. Ensure you have installed @swapkit/tokens package"})}})}}const ft=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)}},G=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:K({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 z extends Error{constructor(e,t){console.error(t),super(e,{cause:{code:gt[e],message:e}}),Object.setPrototypeOf(this,z.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=ge;exports.SwapKitError=z;exports.SwapKitNumber=f;exports.assetFromString=xe;exports.derivationPathToString=Je;exports.filterAssets=He;exports.formatBigIntToSafeValue=I;exports.gasFeeMultiplier=Pe;exports.getAssetType=oe;exports.getAsymmetricAssetShare=ue;exports.getAsymmetricAssetWithdrawAmount=Le;exports.getAsymmetricRuneShare=ce;exports.getAsymmetricRuneWithdrawAmount=je;exports.getCommonAssetInfo=ae;exports.getDecimal=ie;exports.getEstimatedPoolShare=Ue;exports.getLiquiditySlippage=We;exports.getMemoFor=Ke;exports.getMinAmountByChain=ft;exports.getSymmetricPoolShare=le;exports.getSymmetricWithdraw=Fe;exports.getTHORNameCost=Ye;exports.isGasAsset=K;exports.validateTHORName=ze;
|
package/dist/index.d.ts
CHANGED
|
@@ -159,7 +159,17 @@ declare const errorMessages: {
|
|
|
159
159
|
readonly helpers_number_different_decimals: 99101;
|
|
160
160
|
};
|
|
161
161
|
|
|
162
|
-
export declare const filterAssets: (
|
|
162
|
+
export declare const filterAssets: (tokens: {
|
|
163
|
+
value: string;
|
|
164
|
+
decimal: number;
|
|
165
|
+
chain: Chain;
|
|
166
|
+
symbol: string;
|
|
167
|
+
}[]) => {
|
|
168
|
+
value: string;
|
|
169
|
+
decimal: number;
|
|
170
|
+
chain: Chain;
|
|
171
|
+
symbol: string;
|
|
172
|
+
}[];
|
|
163
173
|
|
|
164
174
|
export declare function formatBigIntToSafeValue({ value, bigIntDecimal, decimal, }: {
|
|
165
175
|
value: bigint;
|
package/dist/index.es.js
CHANGED
|
@@ -1,19 +1,19 @@
|
|
|
1
|
-
var
|
|
2
|
-
var
|
|
3
|
-
var f = (
|
|
4
|
-
if (!t.has(
|
|
1
|
+
var bt = Object.defineProperty;
|
|
2
|
+
var yt = (r, t, e) => t in r ? bt(r, t, { enumerable: !0, configurable: !0, writable: !0, value: e }) : r[t] = e;
|
|
3
|
+
var f = (r, t, e) => (yt(r, typeof t != "symbol" ? t + "" : t, e), e), wt = (r, t, e) => {
|
|
4
|
+
if (!t.has(r))
|
|
5
5
|
throw TypeError("Cannot " + e);
|
|
6
6
|
};
|
|
7
|
-
var y = (
|
|
8
|
-
if (t.has(
|
|
7
|
+
var y = (r, t, e) => {
|
|
8
|
+
if (t.has(r))
|
|
9
9
|
throw TypeError("Cannot add the same private member more than once");
|
|
10
|
-
t instanceof WeakSet ? t.add(
|
|
10
|
+
t instanceof WeakSet ? t.add(r) : t.set(r, e);
|
|
11
11
|
};
|
|
12
|
-
var m = (
|
|
13
|
-
import { FeeOption as L, BaseDecimal as d, Chain as o, EVMChainList as
|
|
14
|
-
const
|
|
12
|
+
var m = (r, t, e) => (wt(r, t, "access private method"), e);
|
|
13
|
+
import { FeeOption as L, BaseDecimal as d, Chain as o, EVMChainList as At, ChainToRPC as vt, MemoType as g } from "@swapkit/types";
|
|
14
|
+
const Tt = "0x313ce567", nt = async ({ chain: r, to: t }) => {
|
|
15
15
|
try {
|
|
16
|
-
const { result: e } = await Zt.post(
|
|
16
|
+
const { result: e } = await Zt.post(vt[r], {
|
|
17
17
|
headers: {
|
|
18
18
|
accept: "*/*",
|
|
19
19
|
"content-type": "application/json",
|
|
@@ -23,38 +23,38 @@ const vt = "0x313ce567", nt = async ({ chain: s, to: t }) => {
|
|
|
23
23
|
id: 44,
|
|
24
24
|
jsonrpc: "2.0",
|
|
25
25
|
method: "eth_call",
|
|
26
|
-
params: [{ to: t.toLowerCase(), data:
|
|
26
|
+
params: [{ to: t.toLowerCase(), data: Tt }, "latest"]
|
|
27
27
|
})
|
|
28
28
|
});
|
|
29
29
|
return parseInt(BigInt(e).toString());
|
|
30
30
|
} catch (e) {
|
|
31
|
-
return console.error(e), d[
|
|
31
|
+
return console.error(e), d[r];
|
|
32
32
|
}
|
|
33
|
-
},
|
|
34
|
-
if (
|
|
33
|
+
}, $t = async (r) => {
|
|
34
|
+
if (r === o.Ethereum)
|
|
35
35
|
return d.ETH;
|
|
36
|
-
const [, t] =
|
|
36
|
+
const [, t] = r.split("-");
|
|
37
37
|
return t != null && t.startsWith("0x") ? nt({ chain: o.Ethereum, to: t }) : d.ETH;
|
|
38
|
-
},
|
|
39
|
-
const [, t] =
|
|
38
|
+
}, Rt = async (r) => {
|
|
39
|
+
const [, t] = r.split("-");
|
|
40
40
|
return t != null && t.startsWith("0x") ? nt({ chain: o.Avalanche, to: t.toLowerCase() }) : d.AVAX;
|
|
41
|
-
},
|
|
42
|
-
switch (
|
|
41
|
+
}, St = async (r) => r === o.BinanceSmartChain ? d.BSC : d.BSC, Ct = async ({ chain: r, symbol: t }) => {
|
|
42
|
+
switch (r) {
|
|
43
43
|
case o.Ethereum:
|
|
44
|
-
return Tt(t);
|
|
45
|
-
case o.Avalanche:
|
|
46
44
|
return $t(t);
|
|
47
|
-
case o.
|
|
45
|
+
case o.Avalanche:
|
|
48
46
|
return Rt(t);
|
|
47
|
+
case o.BinanceSmartChain:
|
|
48
|
+
return St(t);
|
|
49
49
|
default:
|
|
50
|
-
return d[
|
|
50
|
+
return d[r];
|
|
51
51
|
}
|
|
52
52
|
}, ne = {
|
|
53
53
|
[L.Average]: 1.2,
|
|
54
54
|
[L.Fast]: 1.5,
|
|
55
55
|
[L.Fastest]: 2
|
|
56
|
-
},
|
|
57
|
-
switch (
|
|
56
|
+
}, it = ({ chain: r, symbol: t }) => {
|
|
57
|
+
switch (r) {
|
|
58
58
|
case o.Bitcoin:
|
|
59
59
|
case o.BitcoinCash:
|
|
60
60
|
case o.Litecoin:
|
|
@@ -62,7 +62,7 @@ const vt = "0x313ce567", nt = async ({ chain: s, to: t }) => {
|
|
|
62
62
|
case o.Binance:
|
|
63
63
|
case o.Ethereum:
|
|
64
64
|
case o.Avalanche:
|
|
65
|
-
return t ===
|
|
65
|
+
return t === r;
|
|
66
66
|
case o.Arbitrum:
|
|
67
67
|
case o.Optimism:
|
|
68
68
|
return t === "ETH";
|
|
@@ -79,18 +79,18 @@ const vt = "0x313ce567", nt = async ({ chain: s, to: t }) => {
|
|
|
79
79
|
case o.THORChain:
|
|
80
80
|
return t === "RUNE";
|
|
81
81
|
}
|
|
82
|
-
}, It = (
|
|
83
|
-
switch (
|
|
82
|
+
}, It = (r) => {
|
|
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: d[
|
|
89
|
+
return { identifier: "GAIA.ATOM", decimal: d[r] };
|
|
90
90
|
case o.THORChain:
|
|
91
|
-
return { identifier: "THOR.RUNE", decimal: d[
|
|
91
|
+
return { identifier: "THOR.RUNE", decimal: d[r] };
|
|
92
92
|
case o.BinanceSmartChain:
|
|
93
|
-
return { identifier: "BSC.BNB", decimal: d[
|
|
93
|
+
return { identifier: "BSC.BNB", decimal: d[r] };
|
|
94
94
|
case o.Maya:
|
|
95
95
|
return { identifier: "MAYA.CACAO", decimal: d.MAYA };
|
|
96
96
|
case "MAYA.MAYA":
|
|
@@ -106,12 +106,12 @@ const vt = "0x313ce567", nt = async ({ chain: s, to: t }) => {
|
|
|
106
106
|
case o.Polygon:
|
|
107
107
|
case o.Bitcoin:
|
|
108
108
|
case o.Ethereum:
|
|
109
|
-
return { identifier: `${
|
|
109
|
+
return { identifier: `${r}.${r}`, decimal: d[r] };
|
|
110
110
|
}
|
|
111
|
-
}, Et = ({ chain:
|
|
111
|
+
}, Et = ({ chain: r, symbol: t }) => {
|
|
112
112
|
if (t.includes("/"))
|
|
113
113
|
return "Synth";
|
|
114
|
-
switch (
|
|
114
|
+
switch (r) {
|
|
115
115
|
case o.Bitcoin:
|
|
116
116
|
case o.BitcoinCash:
|
|
117
117
|
case o.Dogecoin:
|
|
@@ -138,127 +138,134 @@ const vt = "0x313ce567", nt = async ({ chain: s, to: t }) => {
|
|
|
138
138
|
case o.Optimism:
|
|
139
139
|
return [o.Ethereum, o.Optimism].includes(t) ? "Native" : "OPTIMISM";
|
|
140
140
|
}
|
|
141
|
-
}, ie = (
|
|
141
|
+
}, ie = (r) => {
|
|
142
142
|
var c;
|
|
143
|
-
const [t, ...e] =
|
|
144
|
-
return { chain: t, symbol: n, ticker: i, synth:
|
|
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
|
+
return { chain: t, symbol: n, ticker: i, synth: s };
|
|
145
145
|
}, Ot = new RegExp(
|
|
146
146
|
/(.)\1{6}|\.ORG|\.NET|\.FINANCE|\.COM|WWW|HTTP|\\\\|\/\/|[\s$%:[\]]/,
|
|
147
147
|
"gmi"
|
|
148
|
-
), Bt = (
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
148
|
+
), Bt = (r) => {
|
|
149
|
+
const [t, e] = r.split(".");
|
|
150
|
+
if (!At.includes(t))
|
|
151
|
+
return !0;
|
|
152
|
+
const [, s] = e.split("-");
|
|
153
|
+
return it({ chain: t, symbol: e }) || !!s;
|
|
154
|
+
}, oe = (r) => r.filter((t) => {
|
|
155
|
+
const e = `${t.chain}.${t.symbol}`;
|
|
156
|
+
return !Ot.test(e) && Bt(e);
|
|
157
|
+
}), Mt = ({
|
|
158
|
+
liquidityUnits: r,
|
|
152
159
|
poolUnits: t,
|
|
153
160
|
runeDepth: e
|
|
154
161
|
}) => {
|
|
155
|
-
const
|
|
162
|
+
const s = p(r), n = p(t), i = p(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);
|
|
156
163
|
return c.mul(a.sub(u).add(l)).div(h);
|
|
157
164
|
}, Vt = ({
|
|
158
|
-
liquidityUnits:
|
|
165
|
+
liquidityUnits: r,
|
|
159
166
|
poolUnits: t,
|
|
160
167
|
assetDepth: e
|
|
161
168
|
}) => {
|
|
162
|
-
const
|
|
169
|
+
const s = p(r), n = p(t), i = p(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);
|
|
163
170
|
return h.div(_);
|
|
164
171
|
}, ae = ({
|
|
165
|
-
percent:
|
|
172
|
+
percent: r,
|
|
166
173
|
runeDepth: t,
|
|
167
174
|
liquidityUnits: e,
|
|
168
|
-
poolUnits:
|
|
169
|
-
}) => Mt({ runeDepth: t, liquidityUnits: e, poolUnits:
|
|
170
|
-
percent:
|
|
175
|
+
poolUnits: s
|
|
176
|
+
}) => Mt({ runeDepth: t, liquidityUnits: e, poolUnits: s }).mul(r), ce = ({
|
|
177
|
+
percent: r,
|
|
171
178
|
assetDepth: t,
|
|
172
179
|
liquidityUnits: e,
|
|
173
|
-
poolUnits:
|
|
174
|
-
}) => Vt({ assetDepth: t, liquidityUnits: e, poolUnits:
|
|
175
|
-
liquidityUnits:
|
|
180
|
+
poolUnits: s
|
|
181
|
+
}) => Vt({ assetDepth: t, liquidityUnits: e, poolUnits: s }).mul(r), p = (r) => b.fromBigInt(BigInt(r), d.THOR), qt = ({
|
|
182
|
+
liquidityUnits: r,
|
|
176
183
|
poolUnits: t,
|
|
177
184
|
runeDepth: e,
|
|
178
|
-
assetDepth:
|
|
185
|
+
assetDepth: s
|
|
179
186
|
}) => ({
|
|
180
|
-
assetAmount: p(
|
|
181
|
-
runeAmount: p(e).mul(
|
|
187
|
+
assetAmount: p(s).mul(r).div(t),
|
|
188
|
+
runeAmount: p(e).mul(r).div(t)
|
|
182
189
|
}), ue = ({
|
|
183
|
-
liquidityUnits:
|
|
190
|
+
liquidityUnits: r,
|
|
184
191
|
poolUnits: t,
|
|
185
192
|
runeDepth: e,
|
|
186
|
-
assetDepth:
|
|
193
|
+
assetDepth: s,
|
|
187
194
|
percent: n
|
|
188
195
|
}) => Object.fromEntries(
|
|
189
|
-
Object.entries(
|
|
196
|
+
Object.entries(qt({ liquidityUnits: r, poolUnits: t, runeDepth: e, assetDepth: s })).map(
|
|
190
197
|
([i, c]) => [i, c.mul(n)]
|
|
191
198
|
)
|
|
192
199
|
), le = ({
|
|
193
|
-
runeDepth:
|
|
200
|
+
runeDepth: r,
|
|
194
201
|
poolUnits: t,
|
|
195
202
|
assetDepth: e,
|
|
196
|
-
liquidityUnits:
|
|
203
|
+
liquidityUnits: s,
|
|
197
204
|
runeAmount: n,
|
|
198
205
|
assetAmount: i
|
|
199
206
|
}) => {
|
|
200
|
-
const c = new b({ value:
|
|
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), T = h.mul(c), j = l.mul(h), pt = c.mul(a), ft = u.mul(_.add(T.add(j.mul(2)))), _t = _.add(T.add(pt.mul(2))), Q = ft.div(_t), H = p(s).add(Q);
|
|
201
208
|
if (Q.getBaseValue("number") === 0)
|
|
202
209
|
return H.div(u).getBaseValue("number");
|
|
203
|
-
const
|
|
204
|
-
return H.div(
|
|
210
|
+
const gt = u.add(H);
|
|
211
|
+
return H.div(gt).getBaseValue("number");
|
|
205
212
|
}, he = ({
|
|
206
|
-
runeAmount:
|
|
213
|
+
runeAmount: r,
|
|
207
214
|
assetAmount: t,
|
|
208
215
|
runeDepth: e,
|
|
209
|
-
assetDepth:
|
|
216
|
+
assetDepth: s
|
|
210
217
|
}) => {
|
|
211
|
-
if (
|
|
218
|
+
if (r === "0" || t === "0" || e === "0" || s === "0")
|
|
212
219
|
return 0;
|
|
213
|
-
const n = p(e), i = p(
|
|
220
|
+
const n = p(e), i = p(s), c = p(t), a = p(r), u = c.mul(n).sub(i.mul(a)), l = i.mul(a).add(n.mul(i));
|
|
214
221
|
return Math.abs(u.div(l).getBaseValue("number"));
|
|
215
|
-
},
|
|
216
|
-
symbol:
|
|
222
|
+
}, kt = ({
|
|
223
|
+
symbol: r,
|
|
217
224
|
ticker: t,
|
|
218
225
|
chain: e
|
|
219
|
-
}) => e === "ETH" && t !== "ETH" ? `${t}-${
|
|
220
|
-
switch (
|
|
226
|
+
}) => e === "ETH" && t !== "ETH" ? `${t}-${r.slice(-3)}` : r, de = (r, t) => {
|
|
227
|
+
switch (r) {
|
|
221
228
|
case g.LEAVE:
|
|
222
229
|
case g.BOND: {
|
|
223
230
|
const { address: e } = t;
|
|
224
|
-
return `${
|
|
231
|
+
return `${r}:${e}`;
|
|
225
232
|
}
|
|
226
233
|
case g.UNBOND: {
|
|
227
|
-
const { address: e, unbondAmount:
|
|
228
|
-
return `${
|
|
234
|
+
const { address: e, unbondAmount: s } = t;
|
|
235
|
+
return `${r}:${e}:${s * 10 ** 8}`;
|
|
229
236
|
}
|
|
230
237
|
case g.THORNAME_REGISTER: {
|
|
231
|
-
const { name: e, chain:
|
|
232
|
-
return `${
|
|
238
|
+
const { name: e, chain: s, address: n, owner: i } = t;
|
|
239
|
+
return `${r}:${e}:${s}:${n}${i ? `:${i}` : ""}`;
|
|
233
240
|
}
|
|
234
241
|
case g.DEPOSIT: {
|
|
235
|
-
const { chain: e, symbol:
|
|
236
|
-
return i ? `${
|
|
242
|
+
const { chain: e, symbol: s, address: n, singleSide: i } = t;
|
|
243
|
+
return i ? `${r}:${e}/${s}::t:0` : `${r}:${e}.${s}:${n || ""}:t:0`;
|
|
237
244
|
}
|
|
238
245
|
case g.WITHDRAW: {
|
|
239
|
-
const { chain: e, ticker:
|
|
240
|
-
return `${
|
|
246
|
+
const { chain: e, ticker: s, symbol: n, basisPoints: i, targetAssetString: c, singleSide: a } = t, u = !a && c ? `:${c}` : "", l = kt({ chain: e, symbol: n, ticker: s });
|
|
247
|
+
return `${r}:${e}${a ? "/" : "."}${l}:${i}${u}`;
|
|
241
248
|
}
|
|
242
249
|
case g.OPEN_LOAN:
|
|
243
250
|
case g.CLOSE_LOAN: {
|
|
244
|
-
const { asset: e, address:
|
|
245
|
-
return `${
|
|
251
|
+
const { asset: e, address: s } = t;
|
|
252
|
+
return `${r}:${e}:${s}`;
|
|
246
253
|
}
|
|
247
254
|
default:
|
|
248
255
|
return "";
|
|
249
256
|
}
|
|
250
|
-
}, me = (
|
|
251
|
-
if (
|
|
257
|
+
}, me = (r) => {
|
|
258
|
+
if (r < 0)
|
|
252
259
|
throw new Error("Invalid number of year");
|
|
253
|
-
return 10 +
|
|
254
|
-
}, pe = (
|
|
255
|
-
if (
|
|
260
|
+
return 10 + r;
|
|
261
|
+
}, pe = (r) => {
|
|
262
|
+
if (r.length > 30)
|
|
256
263
|
return !1;
|
|
257
264
|
const t = /^[a-zA-Z0-9+_-]+$/g;
|
|
258
|
-
return !!
|
|
259
|
-
}, fe = ([
|
|
265
|
+
return !!r.match(t);
|
|
266
|
+
}, fe = ([r, t, e, s, n]) => `${r}'/${t}'/${e}'/${s}${typeof n != "number" ? "" : `/${n}`}`;
|
|
260
267
|
class X extends Error {
|
|
261
|
-
constructor(t, e,
|
|
268
|
+
constructor(t, e, s) {
|
|
262
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";
|
|
263
270
|
super(`Request failed with ${a}`), Object.defineProperty(this, "response", {
|
|
264
271
|
enumerable: !0,
|
|
@@ -275,10 +282,10 @@ class X extends Error {
|
|
|
275
282
|
configurable: !0,
|
|
276
283
|
writable: !0,
|
|
277
284
|
value: void 0
|
|
278
|
-
}), this.name = "HTTPError", this.response = t, this.request = e, this.options =
|
|
285
|
+
}), this.name = "HTTPError", this.response = t, this.request = e, this.options = s;
|
|
279
286
|
}
|
|
280
287
|
}
|
|
281
|
-
class
|
|
288
|
+
class ot extends Error {
|
|
282
289
|
constructor(t) {
|
|
283
290
|
super("Request timed out"), Object.defineProperty(this, "request", {
|
|
284
291
|
enumerable: !0,
|
|
@@ -288,45 +295,45 @@ class it extends Error {
|
|
|
288
295
|
}), this.name = "TimeoutError", this.request = t;
|
|
289
296
|
}
|
|
290
297
|
}
|
|
291
|
-
const V = (
|
|
292
|
-
for (const t of
|
|
298
|
+
const V = (r) => r !== null && typeof r == "object", M = (...r) => {
|
|
299
|
+
for (const t of r)
|
|
293
300
|
if ((!V(t) || Array.isArray(t)) && t !== void 0)
|
|
294
301
|
throw new TypeError("The `options` argument must be an object");
|
|
295
|
-
return J({}, ...
|
|
296
|
-
},
|
|
297
|
-
const e = new globalThis.Headers(
|
|
302
|
+
return J({}, ...r);
|
|
303
|
+
}, at = (r = {}, t = {}) => {
|
|
304
|
+
const e = new globalThis.Headers(r), s = t instanceof globalThis.Headers, n = new globalThis.Headers(t);
|
|
298
305
|
for (const [i, c] of n.entries())
|
|
299
|
-
|
|
306
|
+
s && c === "undefined" || c === void 0 ? e.delete(i) : e.set(i, c);
|
|
300
307
|
return e;
|
|
301
|
-
}, J = (...
|
|
308
|
+
}, J = (...r) => {
|
|
302
309
|
let t = {}, e = {};
|
|
303
|
-
for (const
|
|
304
|
-
if (Array.isArray(
|
|
305
|
-
Array.isArray(t) || (t = []), t = [...t, ...
|
|
306
|
-
else if (V(
|
|
307
|
-
for (let [n, i] of Object.entries(
|
|
310
|
+
for (const s of r)
|
|
311
|
+
if (Array.isArray(s))
|
|
312
|
+
Array.isArray(t) || (t = []), t = [...t, ...s];
|
|
313
|
+
else if (V(s)) {
|
|
314
|
+
for (let [n, i] of Object.entries(s))
|
|
308
315
|
V(i) && n in t && (i = J(t[n], i)), t = { ...t, [n]: i };
|
|
309
|
-
V(
|
|
316
|
+
V(s.headers) && (e = at(e, s.headers), t.headers = e);
|
|
310
317
|
}
|
|
311
318
|
return t;
|
|
312
319
|
}, xt = (() => {
|
|
313
|
-
let
|
|
314
|
-
const e = typeof globalThis.ReadableStream == "function",
|
|
315
|
-
return e &&
|
|
320
|
+
let r = !1, t = !1;
|
|
321
|
+
const e = typeof globalThis.ReadableStream == "function", s = typeof globalThis.Request == "function";
|
|
322
|
+
return e && s && (t = new globalThis.Request("https://empty.invalid", {
|
|
316
323
|
body: new globalThis.ReadableStream(),
|
|
317
324
|
method: "POST",
|
|
318
325
|
// @ts-expect-error - Types are outdated.
|
|
319
326
|
get duplex() {
|
|
320
|
-
return
|
|
327
|
+
return r = !0, "half";
|
|
321
328
|
}
|
|
322
|
-
}).headers.has("Content-Type")),
|
|
323
|
-
})(), Pt = typeof globalThis.AbortController == "function", Nt = typeof globalThis.ReadableStream == "function", jt = typeof globalThis.FormData == "function",
|
|
329
|
+
}).headers.has("Content-Type")), r && !t;
|
|
330
|
+
})(), Pt = typeof globalThis.AbortController == "function", Nt = typeof globalThis.ReadableStream == "function", jt = typeof globalThis.FormData == "function", ct = ["get", "post", "put", "patch", "head", "delete"], Ht = {
|
|
324
331
|
json: "application/json",
|
|
325
332
|
text: "text/*",
|
|
326
333
|
formData: "multipart/form-data",
|
|
327
334
|
arrayBuffer: "*/*",
|
|
328
335
|
blob: "*/*"
|
|
329
|
-
}, D = 2147483647,
|
|
336
|
+
}, D = 2147483647, ut = Symbol("stop"), Lt = {
|
|
330
337
|
json: !0,
|
|
331
338
|
parseJson: !0,
|
|
332
339
|
searchParams: !0,
|
|
@@ -353,86 +360,86 @@ const V = (s) => s !== null && typeof s == "object", M = (...s) => {
|
|
|
353
360
|
window: !0,
|
|
354
361
|
dispatcher: !0,
|
|
355
362
|
duplex: !0
|
|
356
|
-
}, Ut = (
|
|
363
|
+
}, Ut = (r) => ct.includes(r) ? r.toUpperCase() : r, Ft = ["get", "put", "head", "delete", "options", "trace"], Wt = [408, 413, 429, 500, 502, 503, 504], lt = [413, 429, 503], Z = {
|
|
357
364
|
limit: 2,
|
|
358
365
|
methods: Ft,
|
|
359
366
|
statusCodes: Wt,
|
|
360
|
-
afterStatusCodes:
|
|
367
|
+
afterStatusCodes: lt,
|
|
361
368
|
maxRetryAfter: Number.POSITIVE_INFINITY,
|
|
362
369
|
backoffLimit: Number.POSITIVE_INFINITY,
|
|
363
|
-
delay: (
|
|
364
|
-
}, Gt = (
|
|
365
|
-
if (typeof
|
|
370
|
+
delay: (r) => 0.3 * 2 ** (r - 1) * 1e3
|
|
371
|
+
}, Gt = (r = {}) => {
|
|
372
|
+
if (typeof r == "number")
|
|
366
373
|
return {
|
|
367
374
|
...Z,
|
|
368
|
-
limit:
|
|
375
|
+
limit: r
|
|
369
376
|
};
|
|
370
|
-
if (
|
|
377
|
+
if (r.methods && !Array.isArray(r.methods))
|
|
371
378
|
throw new Error("retry.methods must be an array");
|
|
372
|
-
if (
|
|
379
|
+
if (r.statusCodes && !Array.isArray(r.statusCodes))
|
|
373
380
|
throw new Error("retry.statusCodes must be an array");
|
|
374
381
|
return {
|
|
375
382
|
...Z,
|
|
376
|
-
...
|
|
377
|
-
afterStatusCodes:
|
|
383
|
+
...r,
|
|
384
|
+
afterStatusCodes: lt
|
|
378
385
|
};
|
|
379
386
|
};
|
|
380
|
-
async function Yt(
|
|
387
|
+
async function Yt(r, t, e, s) {
|
|
381
388
|
return new Promise((n, i) => {
|
|
382
389
|
const c = setTimeout(() => {
|
|
383
|
-
e && e.abort(), i(new
|
|
384
|
-
},
|
|
385
|
-
|
|
390
|
+
e && e.abort(), i(new ot(r));
|
|
391
|
+
}, s.timeout);
|
|
392
|
+
s.fetch(r, t).then(n).catch(i).then(() => {
|
|
386
393
|
clearTimeout(c);
|
|
387
394
|
});
|
|
388
395
|
});
|
|
389
396
|
}
|
|
390
|
-
async function zt(
|
|
391
|
-
return new Promise((e,
|
|
397
|
+
async function zt(r, { signal: t }) {
|
|
398
|
+
return new Promise((e, s) => {
|
|
392
399
|
t && (t.throwIfAborted(), t.addEventListener("abort", n, { once: !0 }));
|
|
393
400
|
function n() {
|
|
394
|
-
clearTimeout(i),
|
|
401
|
+
clearTimeout(i), s(t.reason);
|
|
395
402
|
}
|
|
396
403
|
const i = setTimeout(() => {
|
|
397
404
|
t == null || t.removeEventListener("abort", n), e();
|
|
398
|
-
},
|
|
405
|
+
}, r);
|
|
399
406
|
});
|
|
400
407
|
}
|
|
401
|
-
const Jt = (
|
|
408
|
+
const Jt = (r, t) => {
|
|
402
409
|
const e = {};
|
|
403
|
-
for (const
|
|
404
|
-
!(
|
|
410
|
+
for (const s in t)
|
|
411
|
+
!(s in Dt) && !(s in Lt) && !(s in r) && (e[s] = t[s]);
|
|
405
412
|
return e;
|
|
406
413
|
};
|
|
407
|
-
class
|
|
414
|
+
class k {
|
|
408
415
|
static create(t, e) {
|
|
409
|
-
const
|
|
410
|
-
if (typeof
|
|
416
|
+
const s = new k(t, e), n = async () => {
|
|
417
|
+
if (typeof s._options.timeout == "number" && s._options.timeout > D)
|
|
411
418
|
throw new RangeError(`The \`timeout\` option cannot be greater than ${D}`);
|
|
412
419
|
await Promise.resolve();
|
|
413
|
-
let a = await
|
|
414
|
-
for (const u of
|
|
415
|
-
const l = await u(
|
|
420
|
+
let a = await s._fetch();
|
|
421
|
+
for (const u of s._options.hooks.afterResponse) {
|
|
422
|
+
const l = await u(s.request, s._options, s._decorateResponse(a.clone()));
|
|
416
423
|
l instanceof globalThis.Response && (a = l);
|
|
417
424
|
}
|
|
418
|
-
if (
|
|
419
|
-
let u = new X(a,
|
|
420
|
-
for (const l of
|
|
425
|
+
if (s._decorateResponse(a), !a.ok && s._options.throwHttpErrors) {
|
|
426
|
+
let u = new X(a, s.request, s._options);
|
|
427
|
+
for (const l of s._options.hooks.beforeError)
|
|
421
428
|
u = await l(u);
|
|
422
429
|
throw u;
|
|
423
430
|
}
|
|
424
|
-
if (
|
|
425
|
-
if (typeof
|
|
431
|
+
if (s._options.onDownloadProgress) {
|
|
432
|
+
if (typeof s._options.onDownloadProgress != "function")
|
|
426
433
|
throw new TypeError("The `onDownloadProgress` option must be a function");
|
|
427
434
|
if (!Nt)
|
|
428
435
|
throw new Error("Streams are not supported in your environment. `ReadableStream` is missing.");
|
|
429
|
-
return
|
|
436
|
+
return s._stream(a.clone(), s._options.onDownloadProgress);
|
|
430
437
|
}
|
|
431
438
|
return a;
|
|
432
|
-
}, c =
|
|
439
|
+
}, c = s._options.retry.methods.includes(s.request.method.toLowerCase()) ? s._retry(n) : n();
|
|
433
440
|
for (const [a, u] of Object.entries(Ht))
|
|
434
441
|
c[a] = async () => {
|
|
435
|
-
|
|
442
|
+
s.request.headers.set("accept", s.request.headers.get("accept") || u);
|
|
436
443
|
const h = (await c).clone();
|
|
437
444
|
if (a === "json") {
|
|
438
445
|
if (h.status === 204 || (await h.clone().arrayBuffer()).byteLength === 0)
|
|
@@ -475,7 +482,7 @@ class q {
|
|
|
475
482
|
// TODO: credentials can be removed when the spec change is implemented in all browsers. Context: https://www.chromestatus.com/feature/4539473312350208
|
|
476
483
|
credentials: this._input.credentials || "same-origin",
|
|
477
484
|
...e,
|
|
478
|
-
headers:
|
|
485
|
+
headers: at(this._input.headers, e.headers),
|
|
479
486
|
hooks: J({
|
|
480
487
|
beforeRequest: [],
|
|
481
488
|
beforeRetry: [],
|
|
@@ -498,9 +505,9 @@ class q {
|
|
|
498
505
|
}
|
|
499
506
|
if (Pt) {
|
|
500
507
|
if (this.abortController = new globalThis.AbortController(), this._options.signal) {
|
|
501
|
-
const
|
|
508
|
+
const s = this._options.signal;
|
|
502
509
|
this._options.signal.addEventListener("abort", () => {
|
|
503
|
-
this.abortController.abort(
|
|
510
|
+
this.abortController.abort(s.reason);
|
|
504
511
|
});
|
|
505
512
|
}
|
|
506
513
|
this._options.signal = this.abortController.signal;
|
|
@@ -512,14 +519,14 @@ class q {
|
|
|
512
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 }));
|
|
513
520
|
}
|
|
514
521
|
_calculateRetryDelay(t) {
|
|
515
|
-
if (this._retryCount++, this._retryCount < this._options.retry.limit && !(t instanceof
|
|
522
|
+
if (this._retryCount++, this._retryCount < this._options.retry.limit && !(t instanceof ot)) {
|
|
516
523
|
if (t instanceof X) {
|
|
517
524
|
if (!this._options.retry.statusCodes.includes(t.response.status))
|
|
518
525
|
return 0;
|
|
519
|
-
const
|
|
520
|
-
if (
|
|
521
|
-
let n = Number(
|
|
522
|
-
return Number.isNaN(n) ? n = Date.parse(
|
|
526
|
+
const s = t.response.headers.get("Retry-After");
|
|
527
|
+
if (s && this._options.retry.afterStatusCodes.includes(t.response.status)) {
|
|
528
|
+
let n = Number(s);
|
|
529
|
+
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;
|
|
523
530
|
}
|
|
524
531
|
if (t.response.status === 413)
|
|
525
532
|
return 0;
|
|
@@ -536,16 +543,16 @@ class q {
|
|
|
536
543
|
try {
|
|
537
544
|
return await t();
|
|
538
545
|
} catch (e) {
|
|
539
|
-
const
|
|
540
|
-
if (
|
|
541
|
-
await zt(
|
|
546
|
+
const s = Math.min(this._calculateRetryDelay(e), D);
|
|
547
|
+
if (s !== 0 && this._retryCount > 0) {
|
|
548
|
+
await zt(s, { signal: this._options.signal });
|
|
542
549
|
for (const n of this._options.hooks.beforeRetry)
|
|
543
550
|
if (await n({
|
|
544
551
|
request: this.request,
|
|
545
552
|
options: this._options,
|
|
546
553
|
error: e,
|
|
547
554
|
retryCount: this._retryCount
|
|
548
|
-
}) ===
|
|
555
|
+
}) === ut)
|
|
549
556
|
return;
|
|
550
557
|
return this._retry(t);
|
|
551
558
|
}
|
|
@@ -554,29 +561,29 @@ class q {
|
|
|
554
561
|
}
|
|
555
562
|
async _fetch() {
|
|
556
563
|
for (const e of this._options.hooks.beforeRequest) {
|
|
557
|
-
const
|
|
558
|
-
if (
|
|
559
|
-
this.request =
|
|
564
|
+
const s = await e(this.request, this._options);
|
|
565
|
+
if (s instanceof Request) {
|
|
566
|
+
this.request = s;
|
|
560
567
|
break;
|
|
561
568
|
}
|
|
562
|
-
if (
|
|
563
|
-
return
|
|
569
|
+
if (s instanceof Response)
|
|
570
|
+
return s;
|
|
564
571
|
}
|
|
565
572
|
const t = Jt(this.request, this._options);
|
|
566
573
|
return this._options.timeout === !1 ? this._options.fetch(this.request.clone(), t) : Yt(this.request.clone(), t, this.abortController, this._options);
|
|
567
574
|
}
|
|
568
575
|
/* istanbul ignore next */
|
|
569
576
|
_stream(t, e) {
|
|
570
|
-
const
|
|
577
|
+
const s = Number(t.headers.get("content-length")) || 0;
|
|
571
578
|
let n = 0;
|
|
572
|
-
return t.status === 204 ? (e && e({ percent: 1, totalBytes:
|
|
579
|
+
return t.status === 204 ? (e && e({ percent: 1, totalBytes: s, transferredBytes: n }, new Uint8Array()), new globalThis.Response(null, {
|
|
573
580
|
status: t.status,
|
|
574
581
|
statusText: t.statusText,
|
|
575
582
|
headers: t.headers
|
|
576
583
|
})) : new globalThis.Response(new globalThis.ReadableStream({
|
|
577
584
|
async start(i) {
|
|
578
585
|
const c = t.body.getReader();
|
|
579
|
-
e && e({ percent: 0, transferredBytes: 0, totalBytes:
|
|
586
|
+
e && e({ percent: 0, transferredBytes: 0, totalBytes: s }, new Uint8Array());
|
|
580
587
|
async function a() {
|
|
581
588
|
const { done: u, value: l } = await c.read();
|
|
582
589
|
if (u) {
|
|
@@ -585,8 +592,8 @@ class q {
|
|
|
585
592
|
}
|
|
586
593
|
if (e) {
|
|
587
594
|
n += l.byteLength;
|
|
588
|
-
const h =
|
|
589
|
-
e({ percent: h, transferredBytes: n, totalBytes:
|
|
595
|
+
const h = s === 0 ? 0 : n / s;
|
|
596
|
+
e({ percent: h, transferredBytes: n, totalBytes: s }, l);
|
|
590
597
|
}
|
|
591
598
|
i.enqueue(l), await a();
|
|
592
599
|
}
|
|
@@ -600,42 +607,42 @@ class q {
|
|
|
600
607
|
}
|
|
601
608
|
}
|
|
602
609
|
/*! MIT License © Sindre Sorhus */
|
|
603
|
-
const F = (
|
|
604
|
-
const t = (e,
|
|
605
|
-
for (const e of
|
|
606
|
-
t[e] = (
|
|
607
|
-
return t.create = (e) => F(M(e)), t.extend = (e) => F(M(
|
|
610
|
+
const F = (r) => {
|
|
611
|
+
const t = (e, s) => k.create(e, M(r, s));
|
|
612
|
+
for (const e of ct)
|
|
613
|
+
t[e] = (s, n) => k.create(s, M(r, n, { method: e }));
|
|
614
|
+
return t.create = (e) => F(M(e)), t.extend = (e) => F(M(r, e)), t.stop = ut, t;
|
|
608
615
|
}, Kt = F(), Qt = Kt, Xt = typeof window < "u" ? {} : { referrer: "https://sk.thorswap.net", referer: "https://sk.thorswap.net" }, tt = Qt.create({ headers: Xt }), Zt = {
|
|
609
|
-
get: (
|
|
610
|
-
post: (
|
|
611
|
-
}, et = Object.values(o), te = (
|
|
612
|
-
const t =
|
|
616
|
+
get: (r, t) => tt.get(r, t).json(),
|
|
617
|
+
post: (r, t) => tt.post(r, t).json()
|
|
618
|
+
}, et = Object.values(o), te = (r = "") => {
|
|
619
|
+
const t = r.toUpperCase(), [e] = t.split(".");
|
|
613
620
|
if (et.includes(e))
|
|
614
621
|
return !0;
|
|
615
|
-
const [
|
|
616
|
-
if (et.includes(
|
|
622
|
+
const [s] = t.split("/");
|
|
623
|
+
if (et.includes(s))
|
|
617
624
|
return !0;
|
|
618
625
|
throw new Error(
|
|
619
|
-
`Invalid identifier: ${
|
|
626
|
+
`Invalid identifier: ${r}. Expected format: <Chain>.<Ticker> or <Chain>.<Ticker>-<ContractAddress>`
|
|
620
627
|
);
|
|
621
|
-
}, I = 8, $ = (
|
|
628
|
+
}, I = 8, $ = (r) => 10n ** BigInt(r), R = (r) => Math.log10(parseFloat(r.toString()));
|
|
622
629
|
function x({
|
|
623
|
-
value:
|
|
630
|
+
value: r,
|
|
624
631
|
bigIntDecimal: t = I,
|
|
625
632
|
decimal: e = I
|
|
626
633
|
}) {
|
|
627
|
-
const
|
|
628
|
-
let n =
|
|
634
|
+
const s = r < 0n;
|
|
635
|
+
let n = r.toString().substring(s ? 1 : 0);
|
|
629
636
|
const i = e - (n.length - 1);
|
|
630
637
|
i > 0 && (n = "0".repeat(i) + n);
|
|
631
638
|
const c = n.length - e;
|
|
632
639
|
let a = n.slice(-e);
|
|
633
|
-
return parseInt(a[t]) >= 5 ? a = `${a.substring(0, t - 1)}${(parseInt(a[t - 1]) + 1).toString()}` : a = a.substring(0, t), `${
|
|
640
|
+
return parseInt(a[t]) >= 5 ? a = `${a.substring(0, t - 1)}${(parseInt(a[t - 1]) + 1).toString()}` : a = a.substring(0, t), `${s ? "-" : ""}${n.slice(0, c)}.${a}`.replace(
|
|
634
641
|
/\.?0*$/,
|
|
635
642
|
""
|
|
636
643
|
);
|
|
637
644
|
}
|
|
638
|
-
var A, S, P,
|
|
645
|
+
var A, S, P, ht, N, dt, O, W, v, C, B, G;
|
|
639
646
|
const K = class K {
|
|
640
647
|
constructor(t) {
|
|
641
648
|
y(this, A);
|
|
@@ -650,7 +657,7 @@ const K = class K {
|
|
|
650
657
|
const e = U(t);
|
|
651
658
|
this.decimal = typeof t == "object" ? t.decimal : void 0, this.decimalMultiplier = $(
|
|
652
659
|
Math.max(m(this, B, G).call(this, m(this, v, C).call(this, e)), this.decimal || 0)
|
|
653
|
-
), m(this, P,
|
|
660
|
+
), m(this, P, ht).call(this, e);
|
|
654
661
|
}
|
|
655
662
|
static fromBigInt(t, e) {
|
|
656
663
|
return new K({
|
|
@@ -661,11 +668,11 @@ const K = class K {
|
|
|
661
668
|
static shiftDecimals({
|
|
662
669
|
value: t,
|
|
663
670
|
from: e,
|
|
664
|
-
to:
|
|
671
|
+
to: s
|
|
665
672
|
}) {
|
|
666
673
|
return this.fromBigInt(
|
|
667
|
-
t.getBaseValue("bigint") * $(
|
|
668
|
-
|
|
674
|
+
t.getBaseValue("bigint") * $(s) / $(e),
|
|
675
|
+
s
|
|
669
676
|
);
|
|
670
677
|
}
|
|
671
678
|
set(t) {
|
|
@@ -713,35 +720,35 @@ const K = class K {
|
|
|
713
720
|
}
|
|
714
721
|
}
|
|
715
722
|
getBaseValue(t) {
|
|
716
|
-
const e = this.decimalMultiplier / $(this.decimal || d.THOR),
|
|
723
|
+
const e = this.decimalMultiplier / $(this.decimal || d.THOR), s = this.bigIntValue / e;
|
|
717
724
|
switch (t) {
|
|
718
725
|
case "number":
|
|
719
|
-
return Number(
|
|
726
|
+
return Number(s);
|
|
720
727
|
case "string":
|
|
721
|
-
return
|
|
728
|
+
return s.toString();
|
|
722
729
|
default:
|
|
723
|
-
return
|
|
730
|
+
return s;
|
|
724
731
|
}
|
|
725
732
|
}
|
|
726
733
|
getBigIntValue(t, e) {
|
|
727
734
|
if (!e && typeof t == "object")
|
|
728
735
|
return t.bigIntValue;
|
|
729
|
-
const
|
|
736
|
+
const s = U(t), n = m(this, v, C).call(this, s);
|
|
730
737
|
return n === "0" || n === "undefined" ? 0n : m(this, O, W).call(this, n, e);
|
|
731
738
|
}
|
|
732
739
|
formatBigIntToSafeValue(t, e) {
|
|
733
|
-
const
|
|
734
|
-
|
|
740
|
+
const s = e || this.decimal || I, n = Math.max(
|
|
741
|
+
s,
|
|
735
742
|
R(this.decimalMultiplier)
|
|
736
743
|
), 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;
|
|
737
744
|
let h = u.slice(-n);
|
|
738
|
-
return parseInt(h[
|
|
745
|
+
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(
|
|
739
746
|
0,
|
|
740
747
|
l
|
|
741
748
|
)}.${h}`.replace(/\.?0*$/, "");
|
|
742
749
|
}
|
|
743
750
|
toSignificant(t = 6) {
|
|
744
|
-
const [e,
|
|
751
|
+
const [e, s] = this.getValue("string").split("."), n = e || "", i = s || "";
|
|
745
752
|
if ((parseInt(n) ? n.length + i.length : i.length) <= t)
|
|
746
753
|
return this.getValue("string");
|
|
747
754
|
if (n.length >= t)
|
|
@@ -758,7 +765,7 @@ const K = class K {
|
|
|
758
765
|
)}`;
|
|
759
766
|
}
|
|
760
767
|
toFixed(t = 6) {
|
|
761
|
-
const [e,
|
|
768
|
+
const [e, s] = this.getValue("string").split("."), n = e || "", i = s || "";
|
|
762
769
|
if (parseInt(n))
|
|
763
770
|
return `${n}.${i.slice(0, t)}`.padEnd(t, "0");
|
|
764
771
|
const c = parseInt(i), a = `${c}`.slice(0, t);
|
|
@@ -768,7 +775,7 @@ const K = class K {
|
|
|
768
775
|
)}`;
|
|
769
776
|
}
|
|
770
777
|
toAbbreviation(t = 2) {
|
|
771
|
-
const e = this.getValue("number"),
|
|
778
|
+
const e = this.getValue("number"), s = ["", "K", "M", "B", "T", "Q", "Qi", "S"], n = Math.floor(Math.log10(Math.abs(e)) / 3), i = s[n];
|
|
772
779
|
if (!i)
|
|
773
780
|
return this.getValue("string");
|
|
774
781
|
const c = 10 ** (n * 3);
|
|
@@ -776,18 +783,18 @@ const K = class K {
|
|
|
776
783
|
}
|
|
777
784
|
toCurrency(t = "$", {
|
|
778
785
|
currencyPosition: e = "start",
|
|
779
|
-
decimal:
|
|
786
|
+
decimal: s = 2,
|
|
780
787
|
decimalSeparator: n = ".",
|
|
781
788
|
thousandSeparator: i = ","
|
|
782
789
|
} = {}) {
|
|
783
|
-
const c = this.getValue("number"), [a, u = ""] = c.toFixed(6).split("."), l = a.replace(/\B(?=(\d{3})+(?!\d))/g, i), h = !a && !u ? "0.00" : a === "0" ? `${parseFloat(`0.${u}`)}`.replace(".", n) : `${l}${u ? `${n}${u.slice(0,
|
|
790
|
+
const c = this.getValue("number"), [a, u = ""] = c.toFixed(6).split("."), l = a.replace(/\B(?=(\d{3})+(?!\d))/g, i), h = !a && !u ? "0.00" : a === "0" ? `${parseFloat(`0.${u}`)}`.replace(".", n) : `${l}${u ? `${n}${u.slice(0, s)}` : ""}`;
|
|
784
791
|
return `${e === "start" ? t : ""}${h}${e === "end" ? t : ""}`;
|
|
785
792
|
}
|
|
786
793
|
};
|
|
787
794
|
A = new WeakSet(), S = function(t, ...e) {
|
|
788
|
-
const
|
|
795
|
+
const s = m(this, N, dt).call(this, this, ...e), n = $(s), i = e.reduce(
|
|
789
796
|
(a, u) => {
|
|
790
|
-
const l = this.getBigIntValue(u,
|
|
797
|
+
const l = this.getBigIntValue(u, s);
|
|
791
798
|
switch (t) {
|
|
792
799
|
case "add":
|
|
793
800
|
return a + l;
|
|
@@ -807,50 +814,51 @@ A = new WeakSet(), S = function(t, ...e) {
|
|
|
807
814
|
//normalize is to precision multiplier base
|
|
808
815
|
this.bigIntValue * n / this.decimalMultiplier
|
|
809
816
|
), c = x({
|
|
810
|
-
bigIntDecimal:
|
|
811
|
-
decimal: Math.max(
|
|
817
|
+
bigIntDecimal: s,
|
|
818
|
+
decimal: Math.max(s, R(this.decimalMultiplier)),
|
|
812
819
|
value: i
|
|
813
820
|
});
|
|
814
821
|
return new this.constructor({ decimal: this.decimal, value: c, identifier: this.toString() });
|
|
815
|
-
}, P = new WeakSet(),
|
|
822
|
+
}, P = new WeakSet(), ht = function(t) {
|
|
816
823
|
const e = m(this, v, C).call(this, t) || "0";
|
|
817
824
|
this.bigIntValue = m(this, O, W).call(this, e);
|
|
818
|
-
}, N = new WeakSet(),
|
|
825
|
+
}, N = new WeakSet(), dt = function(...t) {
|
|
819
826
|
const e = t.map(
|
|
820
|
-
(
|
|
827
|
+
(s) => typeof s == "object" ? s.decimal || R(s.decimalMultiplier) : m(this, B, G).call(this, m(this, v, C).call(this, s))
|
|
821
828
|
).filter(Boolean);
|
|
822
829
|
return Math.max(...e, I);
|
|
823
830
|
}, O = new WeakSet(), W = function(t, e) {
|
|
824
|
-
const
|
|
831
|
+
const s = e ? $(e) : this.decimalMultiplier, n = R(s), [i = "", c = ""] = t.split(".");
|
|
825
832
|
return BigInt(`${i}${c.padEnd(n, "0")}`);
|
|
826
833
|
}, v = new WeakSet(), C = function(t) {
|
|
827
|
-
const
|
|
834
|
+
const s = `${typeof t == "number" ? Number(t).toLocaleString("fullwide", {
|
|
828
835
|
useGrouping: !1,
|
|
829
836
|
maximumFractionDigits: 20
|
|
830
837
|
}) : U(t)}`.replaceAll(",", ".").split(".");
|
|
831
|
-
return
|
|
838
|
+
return s.length > 1 ? `${s.slice(0, -1).join("")}.${s.at(-1)}` : s[0];
|
|
832
839
|
}, B = new WeakSet(), G = function(t) {
|
|
833
|
-
var
|
|
834
|
-
const e = ((
|
|
840
|
+
var s;
|
|
841
|
+
const e = ((s = t.split(".")[1]) == null ? void 0 : s.length) || 0;
|
|
835
842
|
return Math.max(e, I);
|
|
836
843
|
};
|
|
837
844
|
let E = K;
|
|
838
|
-
function U(
|
|
839
|
-
return typeof
|
|
845
|
+
function U(r) {
|
|
846
|
+
return typeof r == "object" ? "getValue" in r ? r.getValue("string") : r.value : r;
|
|
840
847
|
}
|
|
841
|
-
const
|
|
848
|
+
const q = (r, t) => typeof r == "bigint" ? x({ value: r, bigIntDecimal: t, decimal: t }) : r;
|
|
842
849
|
let Y;
|
|
843
|
-
const
|
|
850
|
+
const st = (r) => {
|
|
844
851
|
if (!Y)
|
|
845
852
|
throw new Error("Static assets not loaded, call await AssetValue.loadStaticAssets() first");
|
|
846
|
-
return Y.get(
|
|
847
|
-
},
|
|
848
|
-
te(
|
|
849
|
-
const e = await
|
|
850
|
-
return new w({ decimal: e, value:
|
|
853
|
+
return Y.get(r.toUpperCase()) || { decimal: d.THOR, identifier: "" };
|
|
854
|
+
}, rt = async (r, t = 0) => {
|
|
855
|
+
te(r);
|
|
856
|
+
const e = await Ct(z(r)), s = q(t, e);
|
|
857
|
+
return new w({ decimal: e, value: s, identifier: r });
|
|
851
858
|
};
|
|
852
859
|
class w extends E {
|
|
853
860
|
constructor(e) {
|
|
861
|
+
const s = "identifier" in e ? e.identifier : `${e.chain}.${e.symbol}`;
|
|
854
862
|
super(
|
|
855
863
|
e.value instanceof E ? e.value : { decimal: e.decimal, value: e.value }
|
|
856
864
|
);
|
|
@@ -861,45 +869,45 @@ class w extends E {
|
|
|
861
869
|
f(this, "symbol");
|
|
862
870
|
f(this, "ticker");
|
|
863
871
|
f(this, "type");
|
|
864
|
-
const
|
|
872
|
+
const n = z(s);
|
|
865
873
|
this.type = Et(n), this.chain = n.chain, this.ticker = n.ticker, this.symbol = n.symbol, this.address = n.address, this.isSynthetic = n.isSynthetic, this.isGasAsset = n.isGasAsset;
|
|
866
874
|
}
|
|
867
875
|
get assetValue() {
|
|
868
876
|
return `${this.getValue("string")} ${this.ticker}`;
|
|
869
877
|
}
|
|
870
878
|
toString(e = !1) {
|
|
871
|
-
const
|
|
872
|
-
return e ?
|
|
879
|
+
const s = this.isSynthetic ? this.symbol.split("-")[0] : `${this.chain}.${this.ticker}`;
|
|
880
|
+
return e ? s : (
|
|
873
881
|
// THOR.ETH/ETH | ETH.USDT-0x1234567890
|
|
874
882
|
`${this.chain}.${this.symbol}`
|
|
875
883
|
);
|
|
876
884
|
}
|
|
877
|
-
eq({ chain: e, symbol:
|
|
878
|
-
return this.chain === e && this.symbol ===
|
|
885
|
+
eq({ chain: e, symbol: s }) {
|
|
886
|
+
return this.chain === e && this.symbol === s;
|
|
879
887
|
}
|
|
880
|
-
static async fromString(e,
|
|
881
|
-
return
|
|
888
|
+
static async fromString(e, s = 0) {
|
|
889
|
+
return rt(e, s);
|
|
882
890
|
}
|
|
883
|
-
static fromStringSync(e,
|
|
884
|
-
const { isSynthetic: n } = z(e), { decimal: i, identifier: c } =
|
|
891
|
+
static fromStringSync(e, s = 0) {
|
|
892
|
+
const { isSynthetic: n } = z(e), { decimal: i, identifier: c } = st(
|
|
885
893
|
e
|
|
886
|
-
), a =
|
|
894
|
+
), a = q(s, i);
|
|
887
895
|
return c ? new w({ decimal: i, identifier: c, value: a }) : n ? new w({ decimal: 8, identifier: e, value: a }) : void 0;
|
|
888
896
|
}
|
|
889
|
-
static async fromIdentifier(e,
|
|
890
|
-
return
|
|
897
|
+
static async fromIdentifier(e, s = 0) {
|
|
898
|
+
return rt(e, s);
|
|
891
899
|
}
|
|
892
|
-
static fromIdentifierSync(e,
|
|
893
|
-
const { decimal: n, identifier: i } =
|
|
900
|
+
static fromIdentifierSync(e, s = 0) {
|
|
901
|
+
const { decimal: n, identifier: i } = st(e), c = q(s, n);
|
|
894
902
|
return new w({ decimal: n, identifier: i, value: c });
|
|
895
903
|
}
|
|
896
|
-
static fromChainOrSignature(e,
|
|
897
|
-
const { decimal: n, identifier: i } = It(e), c =
|
|
904
|
+
static fromChainOrSignature(e, s = 0) {
|
|
905
|
+
const { decimal: n, identifier: i } = It(e), c = q(s, n);
|
|
898
906
|
return new w({ value: c, decimal: n, identifier: i });
|
|
899
907
|
}
|
|
900
908
|
static async loadStaticAssets() {
|
|
901
909
|
return new Promise(
|
|
902
|
-
async (e,
|
|
910
|
+
async (e, s) => {
|
|
903
911
|
try {
|
|
904
912
|
const {
|
|
905
913
|
// Omit ThorchainList from import to avoid decimals conflict (TC uses 8 for all)
|
|
@@ -916,7 +924,7 @@ class w extends E {
|
|
|
916
924
|
/* @__PURE__ */ new Map()
|
|
917
925
|
), e({ ok: !0 });
|
|
918
926
|
} catch (n) {
|
|
919
|
-
console.error(n),
|
|
927
|
+
console.error(n), s({
|
|
920
928
|
ok: !1,
|
|
921
929
|
error: n,
|
|
922
930
|
message: "Couldn't load static assets. Ensure you have installed @swapkit/tokens package"
|
|
@@ -926,9 +934,9 @@ class w extends E {
|
|
|
926
934
|
);
|
|
927
935
|
}
|
|
928
936
|
}
|
|
929
|
-
const _e = (
|
|
930
|
-
const t = w.fromChainOrSignature(
|
|
931
|
-
switch (
|
|
937
|
+
const _e = (r) => {
|
|
938
|
+
const t = w.fromChainOrSignature(r);
|
|
939
|
+
switch (r) {
|
|
932
940
|
case o.Bitcoin:
|
|
933
941
|
case o.Litecoin:
|
|
934
942
|
case o.BitcoinCash:
|
|
@@ -944,12 +952,12 @@ const _e = (s) => {
|
|
|
944
952
|
default:
|
|
945
953
|
return t.set(1e-8);
|
|
946
954
|
}
|
|
947
|
-
}, z = (
|
|
948
|
-
const t =
|
|
955
|
+
}, z = (r) => {
|
|
956
|
+
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("-");
|
|
949
957
|
return {
|
|
950
958
|
address: u == null ? void 0 : u.toLowerCase(),
|
|
951
959
|
chain: i,
|
|
952
|
-
isGasAsset:
|
|
960
|
+
isGasAsset: it({ chain: i, symbol: c }),
|
|
953
961
|
isSynthetic: t,
|
|
954
962
|
symbol: (t ? `${e}/` : "") + (u ? `${a}-${(u == null ? void 0 : u.toLowerCase()) ?? ""}` : c),
|
|
955
963
|
ticker: a
|
|
@@ -1011,9 +1019,9 @@ const _e = (s) => {
|
|
|
1011
1019
|
*/
|
|
1012
1020
|
helpers_number_different_decimals: 99101
|
|
1013
1021
|
};
|
|
1014
|
-
class
|
|
1022
|
+
class mt extends Error {
|
|
1015
1023
|
constructor(t, e) {
|
|
1016
|
-
console.error(e), super(t, { cause: { code: ee[t], message: t } }), Object.setPrototypeOf(this,
|
|
1024
|
+
console.error(e), super(t, { cause: { code: ee[t], message: t } }), Object.setPrototypeOf(this, mt.prototype);
|
|
1017
1025
|
}
|
|
1018
1026
|
}
|
|
1019
1027
|
class b extends E {
|
|
@@ -1031,7 +1039,7 @@ export {
|
|
|
1031
1039
|
w as AssetValue,
|
|
1032
1040
|
E as BigIntArithmetics,
|
|
1033
1041
|
Zt as RequestClient,
|
|
1034
|
-
|
|
1042
|
+
mt as SwapKitError,
|
|
1035
1043
|
b as SwapKitNumber,
|
|
1036
1044
|
ie as assetFromString,
|
|
1037
1045
|
fe as derivationPathToString,
|
|
@@ -1044,14 +1052,14 @@ export {
|
|
|
1044
1052
|
Mt as getAsymmetricRuneShare,
|
|
1045
1053
|
ae as getAsymmetricRuneWithdrawAmount,
|
|
1046
1054
|
It as getCommonAssetInfo,
|
|
1047
|
-
|
|
1055
|
+
Ct as getDecimal,
|
|
1048
1056
|
le as getEstimatedPoolShare,
|
|
1049
1057
|
he as getLiquiditySlippage,
|
|
1050
1058
|
de as getMemoFor,
|
|
1051
1059
|
_e as getMinAmountByChain,
|
|
1052
|
-
|
|
1060
|
+
qt as getSymmetricPoolShare,
|
|
1053
1061
|
ue as getSymmetricWithdraw,
|
|
1054
1062
|
me as getTHORNameCost,
|
|
1055
|
-
|
|
1063
|
+
it as isGasAsset,
|
|
1056
1064
|
pe as validateTHORName
|
|
1057
1065
|
};
|
package/package.json
CHANGED
|
@@ -42,7 +42,7 @@
|
|
|
42
42
|
"repository": "https://github.com/thorswap/SwapKit.git",
|
|
43
43
|
"type": "module",
|
|
44
44
|
"types": "./dist/index.d.ts",
|
|
45
|
-
"version": "1.0.0-rc.
|
|
45
|
+
"version": "1.0.0-rc.24",
|
|
46
46
|
"scripts": {
|
|
47
47
|
"build": "vite build",
|
|
48
48
|
"clean": "rm -rf dist vite.config.ts.* .turbo node_modules",
|
package/src/helpers/asset.ts
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import type { EVMChain } from '@swapkit/types';
|
|
2
2
|
import { BaseDecimal, Chain, ChainToRPC, EVMChainList, FeeOption } from '@swapkit/types';
|
|
3
3
|
|
|
4
|
-
import {
|
|
4
|
+
import { RequestClient } from '../index.ts';
|
|
5
5
|
|
|
6
6
|
const getDecimalMethodHex = '0x313ce567';
|
|
7
7
|
|
|
@@ -187,16 +187,24 @@ const potentialScamRegex = new RegExp(
|
|
|
187
187
|
'gmi',
|
|
188
188
|
);
|
|
189
189
|
|
|
190
|
-
const evmAssetHasAddress = (
|
|
191
|
-
|
|
190
|
+
const evmAssetHasAddress = (assetString: string) => {
|
|
191
|
+
const [chain, symbol] = assetString.split('.') as [EVMChain, string];
|
|
192
|
+
if (!EVMChainList.includes(chain as EVMChain)) return true;
|
|
193
|
+
const [, address] = symbol.split('-') as [string, string?];
|
|
192
194
|
|
|
193
|
-
return
|
|
195
|
+
return isGasAsset({ chain: chain as Chain, symbol }) || !!address;
|
|
194
196
|
};
|
|
195
197
|
|
|
196
|
-
export const filterAssets = (
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
|
|
198
|
+
export const filterAssets = (
|
|
199
|
+
tokens: {
|
|
200
|
+
value: string;
|
|
201
|
+
decimal: number;
|
|
202
|
+
chain: Chain;
|
|
203
|
+
symbol: string;
|
|
204
|
+
}[],
|
|
205
|
+
) =>
|
|
206
|
+
tokens.filter((token) => {
|
|
207
|
+
const assetString = `${token.chain}.${token.symbol}`;
|
|
208
|
+
|
|
209
|
+
return !potentialScamRegex.test(assetString) && evmAssetHasAddress(assetString);
|
|
210
|
+
});
|
|
@@ -76,16 +76,15 @@ export class AssetValue extends BigIntArithmetics {
|
|
|
76
76
|
type: ReturnType<typeof getAssetType>;
|
|
77
77
|
|
|
78
78
|
constructor(params: AssetValueParams) {
|
|
79
|
+
const identifier =
|
|
80
|
+
'identifier' in params ? params.identifier : `${params.chain}.${params.symbol}`;
|
|
79
81
|
super(
|
|
80
82
|
params.value instanceof BigIntArithmetics
|
|
81
83
|
? params.value
|
|
82
84
|
: { decimal: params.decimal, value: params.value },
|
|
83
85
|
);
|
|
84
86
|
|
|
85
|
-
const identifier =
|
|
86
|
-
'identifier' in params ? params.identifier : `${params.chain}.${params.symbol}`;
|
|
87
87
|
const assetInfo = getAssetInfo(identifier);
|
|
88
|
-
|
|
89
88
|
this.type = getAssetType(assetInfo);
|
|
90
89
|
this.chain = assetInfo.chain;
|
|
91
90
|
this.ticker = assetInfo.ticker;
|
|
@@ -127,11 +126,13 @@ export class AssetValue extends BigIntArithmetics {
|
|
|
127
126
|
|
|
128
127
|
const parsedValue = safeValue(value, decimal);
|
|
129
128
|
|
|
130
|
-
|
|
129
|
+
const asset = tokenIdentifier
|
|
131
130
|
? new AssetValue({ decimal, identifier: tokenIdentifier, value: parsedValue })
|
|
132
131
|
: isSynthetic
|
|
133
132
|
? new AssetValue({ decimal: 8, identifier: assetString, value: parsedValue })
|
|
134
133
|
: undefined;
|
|
134
|
+
|
|
135
|
+
return asset;
|
|
135
136
|
}
|
|
136
137
|
|
|
137
138
|
static async fromIdentifier(
|