@swapkit/helpers 1.0.0-rc.46 → 1.0.0-rc.48
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.cjs +1 -1
- package/dist/index.d.ts +2 -1
- package/dist/index.es.js +156 -162
- package/package.json +9 -9
- package/src/modules/__tests__/assetValue.test.ts +37 -31
- package/src/modules/assetValue.ts +28 -30
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 Be=(s,e,t)=>e in s?D(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t;var Ie=(s,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of Se(e))!Re.call(s,r)&&r!==t&&D(s,r,{get:()=>e[r],enumerable:!(n=ve(e,r))||n.enumerable});return s};var Me=(s,e,t)=>(t=s!=null?Te($e(s)):{},Ie(e||!s||!s.__esModule?D(t,"default",{value:s,enumerable:!0}):t,s));var p=(s,e,t)=>(Be(s,typeof e!="symbol"?e+"":e,t),t),Oe=(s,e,t)=>{if(!e.has(s))throw TypeError("Cannot "+t)};var A=(s,e,t)=>{if(e.has(s))throw TypeError("Cannot add the same private member more than once");e instanceof WeakSet?e.add(s):e.set(s,t)};var d=(s,e,t)=>(Oe(s,e,"access private method"),t);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const i=require("@swapkit/types"),Ee="0x313ce567",ie=async({chain:s,to:e})=>{try{const{result:t}=await _e.post(i.ChainToRPC[s],{headers:{accept:"*/*","content-type":"application/json","cache-control":"no-cache"},body:JSON.stringify({id:44,jsonrpc:"2.0",method:"eth_call",params:[{to:e.toLowerCase(),data:Ee},"latest"]})});return parseInt(BigInt(t).toString())}catch(t){return console.error(t),i.BaseDecimal[s]}},qe=async s=>{if(s===i.Chain.Ethereum)return i.BaseDecimal.ETH;const[,e]=s.split("-");return e!=null&&e.startsWith("0x")?ie({chain:i.Chain.Ethereum,to:e}):i.BaseDecimal.ETH},xe=async s=>{const[,e]=s.split("-");return e!=null&&e.startsWith("0x")?ie({chain:i.Chain.Avalanche,to:e.toLowerCase()}):i.BaseDecimal.AVAX},Ve=async s=>(s===i.Chain.BinanceSmartChain,i.BaseDecimal.BSC),ae=async({chain:s,symbol:e})=>{switch(s){case i.Chain.Ethereum:return qe(e);case i.Chain.Avalanche:return xe(e);case i.Chain.BinanceSmartChain:return Ve(e);default:return i.BaseDecimal[s]}},ke={[i.FeeOption.Average]:1.2,[i.FeeOption.Fast]:1.5,[i.FeeOption.Fastest]:2},K=({chain:s,symbol:e})=>{switch(s){case i.Chain.Bitcoin:case i.Chain.BitcoinCash:case i.Chain.Litecoin:case i.Chain.Dogecoin:case i.Chain.Binance:case i.Chain.Ethereum:case i.Chain.Avalanche:return e===s;case i.Chain.Arbitrum:case i.Chain.Optimism:return e==="ETH";case i.Chain.Maya:return e==="CACAO";case i.Chain.Kujira:return e==="KUJI";case i.Chain.Cosmos:return e==="ATOM";case i.Chain.Polygon:return e==="MATIC";case i.Chain.BinanceSmartChain:return e==="BNB";case i.Chain.THORChain:return e==="RUNE"}},oe=s=>{switch(s){case"ETH.THOR":return{identifier:"ETH.THOR-0xa5f2211b9b8170f694421f2046281775e8468044",decimal:18};case"ETH.vTHOR":return{identifier:"ETH.vTHOR-0x815c23eca83261b6ec689b60cc4a58b54bc24d8d",decimal:18};case i.Chain.Cosmos:return{identifier:"GAIA.ATOM",decimal:i.BaseDecimal[s]};case i.Chain.THORChain:return{identifier:"THOR.RUNE",decimal:i.BaseDecimal[s]};case i.Chain.BinanceSmartChain:return{identifier:"BSC.BNB",decimal:i.BaseDecimal[s]};case i.Chain.Maya:return{identifier:"MAYA.CACAO",decimal:i.BaseDecimal.MAYA};case"MAYA.MAYA":return{identifier:"MAYA.MAYA",decimal:4};case i.Chain.Kujira:case i.Chain.Arbitrum:case i.Chain.Optimism:case i.Chain.BitcoinCash:case i.Chain.Litecoin:case i.Chain.Dogecoin:case i.Chain.Binance:case i.Chain.Avalanche:case i.Chain.Polygon:case i.Chain.Bitcoin:case i.Chain.Ethereum:return{identifier:`${s}.${s}`,decimal:i.BaseDecimal[s]}}},ce=({chain:s,symbol:e})=>{if(e.includes("/"))return"Synth";switch(s){case i.Chain.Bitcoin:case i.Chain.BitcoinCash:case i.Chain.Dogecoin:case i.Chain.Litecoin:case i.Chain.Maya:case i.Chain.THORChain:return"Native";case i.Chain.Cosmos:return e==="ATOM"?"Native":i.Chain.Cosmos;case i.Chain.Kujira:return e===i.Chain.Kujira?"Native":i.Chain.Kujira;case i.Chain.Binance:return e===i.Chain.Binance?"Native":"BEP2";case i.Chain.BinanceSmartChain:return e===i.Chain.Binance?"Native":"BEP20";case i.Chain.Ethereum:return e===i.Chain.Ethereum?"Native":"ERC20";case i.Chain.Avalanche:return e===i.Chain.Avalanche?"Native":i.Chain.Avalanche;case i.Chain.Polygon:return e===i.Chain.Polygon?"Native":"POLYGON";case i.Chain.Arbitrum:return[i.Chain.Ethereum,i.Chain.Arbitrum].includes(e)?"Native":"ARBITRUM";case i.Chain.Optimism:return[i.Chain.Ethereum,i.Chain.Optimism].includes(e)?"Native":"OPTIMISM"}},Pe=s=>{var o;const[e,...t]=s.split("."),n=s.includes("/"),r=t.join("."),a=(o=r==null?void 0:r.split("-"))==null?void 0:o[0];return{chain:e,symbol:r,ticker:a,synth:n}},Ne=new RegExp(/(.)\1{6}|\.ORG|\.NET|\.FINANCE|\.COM|WWW|HTTP|\\\\|\/\/|[\s$%:[\]]/,"gmi"),De=s=>{const[e,t]=s.split(".");if(!i.EVMChainList.includes(e))return!0;const[,n]=t.split("-");return K({chain:e,symbol:t})||!!n},je=s=>s.filter(e=>{const t=`${e.chain}.${e.symbol}`;return!Ne.test(t)&&De(t)&&e.value!=="0"}),ue=({liquidityUnits:s,poolUnits:e,runeDepth:t})=>{const n=m(s),r=m(e),a=m(t),o=n.mul(a),c=r.mul(r).mul(2),u=r.mul(n).mul(2),h=n.mul(n),l=r.mul(r).mul(r);return o.mul(c.sub(u).add(h)).div(l)},le=({liquidityUnits:s,poolUnits:e,assetDepth:t})=>{const n=m(s),r=m(e),a=m(t),o=n.mul(a),c=r.mul(r).mul(2),u=r.mul(n).mul(2),h=n.mul(n),l=o.mul(c.sub(u).add(h)),g=r.mul(r).mul(r);return l.div(g)},He=({percent:s,runeDepth:e,liquidityUnits:t,poolUnits:n})=>ue({runeDepth:e,liquidityUnits:t,poolUnits:n}).mul(s),Le=({percent:s,assetDepth:e,liquidityUnits:t,poolUnits:n})=>le({assetDepth:e,liquidityUnits:t,poolUnits:n}).mul(s),m=s=>f.fromBigInt(BigInt(s),i.BaseDecimal.THOR),he=({liquidityUnits:s,poolUnits:e,runeDepth:t,assetDepth:n})=>({assetAmount:m(n).mul(s).div(e),runeAmount:m(t).mul(s).div(e)}),Fe=({liquidityUnits:s,poolUnits:e,runeDepth:t,assetDepth:n,percent:r})=>Object.fromEntries(Object.entries(he({liquidityUnits:s,poolUnits:e,runeDepth:t,assetDepth:n})).map(([a,o])=>[a,o.mul(r)])),Ue=({runeDepth:s,poolUnits:e,assetDepth:t,liquidityUnits:n,runeAmount:r,assetAmount:a})=>{const o=new f({value:s,decimal:8}),c=new f({value:t,decimal:8}),u=new f({value:e,decimal:8}),h=new f({value:r,decimal:8}),l=new f({value:a,decimal:8}),g=h.mul(c),w=l.mul(o),P=h.mul(l),be=o.mul(c),Ce=u.mul(g.add(w.add(P.mul(2)))),we=g.add(w.add(be.mul(2))),Q=Ce.div(we),N=m(n).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:s,assetAmount:e,runeDepth:t,assetDepth:n})=>{if(s==="0"||e==="0"||t==="0"||n==="0")return 0;const r=m(t),a=m(n),o=m(e),c=m(s),u=o.mul(r).sub(a.mul(c)),h=a.mul(c).add(r.mul(a));return Math.abs(u.div(h).getBaseValue("number"))},Ge=({symbol:s,ticker:e,chain:t})=>t==="ETH"&&e!=="ETH"?`${e}-${s.slice(-3)}`:s,Ke=(s,e)=>{switch(s){case i.MemoType.LEAVE:case i.MemoType.BOND:{const{address:t}=e;return`${s}:${t}`}case i.MemoType.UNBOND:{const{address:t,unbondAmount:n}=e;return`${s}:${t}:${n*10**8}`}case i.MemoType.THORNAME_REGISTER:{const{name:t,chain:n,address:r,owner:a}=e;return`${s}:${t}:${n}:${r}${a?`:${a}`:""}`}case i.MemoType.DEPOSIT:{const{chain:t,symbol:n,address:r,singleSide:a}=e;return a?`${s}:${t}/${n}::t:0`:`${s}:${t}.${n}:${r||""}:t:0`}case i.MemoType.WITHDRAW:{const{chain:t,ticker:n,symbol:r,basisPoints:a,targetAssetString:o,singleSide:c}=e,u=!c&&o?`:${o}`:"",h=Ge({chain:t,symbol:r,ticker:n});return`${s}:${t}${c?"/":"."}${h}:${a}${u}`}case i.MemoType.OPEN_LOAN:case i.MemoType.CLOSE_LOAN:{const{asset:t,address:n}=e;return`${s}:${t}:${n}`}default:return""}},Ye=s=>{if(s<0)throw new Error("Invalid number of year");return 10+s},ze=s=>{if(s.length>30)return!1;const e=/^[a-zA-Z0-9+_-]+$/g;return!!s.match(e)},Je=([s,e,t,n,r])=>`${s}'/${e}'/${t}'/${n}${typeof r!="number"?"":`/${r}`}`;class X extends Error{constructor(e,t,n){const r=e.status||e.status===0?e.status:"",a=e.statusText||"",o=`${r} ${a}`.trim(),c=o?`status code ${o}`:"an unknown error";super(`Request failed with ${c}`),Object.defineProperty(this,"response",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"request",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"options",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.name="HTTPError",this.response=e,this.request=t,this.options=n}}class de extends Error{constructor(e){super("Request timed out"),Object.defineProperty(this,"request",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.name="TimeoutError",this.request=e}}const q=s=>s!==null&&typeof s=="object",O=(...s)=>{for(const e of s)if((!q(e)||Array.isArray(e))&&e!==void 0)throw new TypeError("The `options` argument must be an object");return Y({},...s)},me=(s={},e={})=>{const t=new globalThis.Headers(s),n=e instanceof globalThis.Headers,r=new globalThis.Headers(e);for(const[a,o]of r.entries())n&&o==="undefined"||o===void 0?t.delete(a):t.set(a,o);return t},Y=(...s)=>{let e={},t={};for(const n of s)if(Array.isArray(n))Array.isArray(e)||(e=[]),e=[...e,...n];else if(q(n)){for(let[r,a]of Object.entries(n))q(a)&&r in e&&(a=Y(e[r],a)),e={...e,[r]:a};q(n.headers)&&(t=me(t,n.headers),e.headers=t)}return e},Qe=(()=>{let s=!1,e=!1;const t=typeof globalThis.ReadableStream=="function",n=typeof globalThis.Request=="function";return t&&n&&(e=new globalThis.Request("https://empty.invalid",{body:new globalThis.ReadableStream,method:"POST",get duplex(){return s=!0,"half"}}).headers.has("Content-Type")),s&&!e})(),Xe=typeof globalThis.AbortController=="function",Ze=typeof globalThis.ReadableStream=="function",et=typeof globalThis.FormData=="function",pe=["get","post","put","patch","head","delete"],tt={json:"application/json",text:"text/*",formData:"multipart/form-data",arrayBuffer:"*/*",blob:"*/*"},j=2147483647,fe=Symbol("stop"),st={json:!0,parseJson:!0,searchParams:!0,prefixUrl:!0,retry:!0,timeout:!0,hooks:!0,throwHttpErrors:!0,onDownloadProgress:!0,fetch:!0},nt={method:!0,headers:!0,body:!0,mode:!0,credentials:!0,cache:!0,redirect:!0,referrer:!0,referrerPolicy:!0,integrity:!0,keepalive:!0,signal:!0,window:!0,dispatcher:!0,duplex:!0},rt=s=>pe.includes(s)?s.toUpperCase():s,it=["get","put","head","delete","options","trace"],at=[408,413,429,500,502,503,504],ge=[413,429,503],Z={limit:2,methods:it,statusCodes:at,afterStatusCodes:ge,maxRetryAfter:Number.POSITIVE_INFINITY,backoffLimit:Number.POSITIVE_INFINITY,delay:s=>.3*2**(s-1)*1e3},ot=(s={})=>{if(typeof s=="number")return{...Z,limit:s};if(s.methods&&!Array.isArray(s.methods))throw new Error("retry.methods must be an array");if(s.statusCodes&&!Array.isArray(s.statusCodes))throw new Error("retry.statusCodes must be an array");return{...Z,...s,afterStatusCodes:ge}};async function ct(s,e,t,n){return new Promise((r,a)=>{const o=setTimeout(()=>{t&&t.abort(),a(new de(s))},n.timeout);n.fetch(s,e).then(r).catch(a).then(()=>{clearTimeout(o)})})}async function ut(s,{signal:e}){return new Promise((t,n)=>{e&&(e.throwIfAborted(),e.addEventListener("abort",r,{once:!0}));function r(){clearTimeout(a),n(e.reason)}const a=setTimeout(()=>{e==null||e.removeEventListener("abort",r),t()},s)})}const lt=(s,e)=>{const t={};for(const n in e)!(n in nt)&&!(n in st)&&!(n in s)&&(t[n]=e[n]);return t};class V{static create(e,t){const n=new V(e,t),r=async()=>{if(typeof n._options.timeout=="number"&&n._options.timeout>j)throw new RangeError(`The \`timeout\` option cannot be greater than ${j}`);await Promise.resolve();let c=await n._fetch();for(const u of n._options.hooks.afterResponse){const h=await u(n.request,n._options,n._decorateResponse(c.clone()));h instanceof globalThis.Response&&(c=h)}if(n._decorateResponse(c),!c.ok&&n._options.throwHttpErrors){let u=new X(c,n.request,n._options);for(const h of n._options.hooks.beforeError)u=await h(u);throw u}if(n._options.onDownloadProgress){if(typeof n._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 n._stream(c.clone(),n._options.onDownloadProgress)}return c},o=n._options.retry.methods.includes(n.request.method.toLowerCase())?n._retry(r):r();for(const[c,u]of Object.entries(tt))o[c]=async()=>{n.request.headers.set("accept",n.request.headers.get("accept")||u);const l=(await o).clone();if(c==="json"){if(l.status===204||(await l.clone().arrayBuffer()).byteLength===0)return"";if(t.parseJson)return t.parseJson(await l.text())}return l[c]()};return o}constructor(e,t={}){if(Object.defineProperty(this,"request",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"abortController",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_retryCount",{enumerable:!0,configurable:!0,writable:!0,value:0}),Object.defineProperty(this,"_input",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_options",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this._input=e,this._options={credentials:this._input.credentials||"same-origin",...t,headers:me(this._input.headers,t.headers),hooks:Y({beforeRequest:[],beforeRetry:[],beforeError:[],afterResponse:[]},t.hooks),method:rt(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 n=this._options.signal;this._options.signal.addEventListener("abort",()=>{this.abortController.abort(n.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 r="?"+(typeof this._options.searchParams=="string"?this._options.searchParams.replace(/^\?/,""):new URLSearchParams(this._options.searchParams).toString()),a=this.request.url.replace(/(?:\?.*?)?(?=#|$)/,r);(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 de)){if(e instanceof X){if(!this._options.retry.statusCodes.includes(e.response.status))return 0;const n=e.response.headers.get("Retry-After");if(n&&this._options.retry.afterStatusCodes.includes(e.response.status)){let r=Number(n);return Number.isNaN(r)?r=Date.parse(n)-Date.now():r*=1e3,this._options.retry.maxRetryAfter!==void 0&&r>this._options.retry.maxRetryAfter?0:r}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 n=Math.min(this._calculateRetryDelay(t),j);if(n!==0&&this._retryCount>0){await ut(n,{signal:this._options.signal});for(const r of this._options.hooks.beforeRetry)if(await r({request:this.request,options:this._options,error:t,retryCount:this._retryCount})===fe)return;return this._retry(e)}throw t}}async _fetch(){for(const t of this._options.hooks.beforeRequest){const n=await t(this.request,this._options);if(n instanceof Request){this.request=n;break}if(n instanceof Response)return n}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 n=Number(e.headers.get("content-length"))||0;let r=0;return e.status===204?(t&&t({percent:1,totalBytes:n,transferredBytes:r},new Uint8Array),new globalThis.Response(null,{status:e.status,statusText:e.statusText,headers:e.headers})):new globalThis.Response(new globalThis.ReadableStream({async start(a){const o=e.body.getReader();t&&t({percent:0,transferredBytes:0,totalBytes:n},new Uint8Array);async function c(){const{done:u,value:h}=await o.read();if(u){a.close();return}if(t){r+=h.byteLength;const l=n===0?0:r/n;t({percent:l,transferredBytes:r,totalBytes:n},h)}a.enqueue(h),await c()}await c()}}),{status:e.status,statusText:e.statusText,headers:e.headers})}}/*! MIT License © Sindre Sorhus */const H=s=>{const e=(t,n)=>V.create(t,O(s,n));for(const t of pe)e[t]=(n,r)=>V.create(n,O(s,r,{method:t}));return e.create=t=>H(O(t)),e.extend=t=>H(O(s,t)),e.stop=fe,e},ht=H(),dt=ht,mt=typeof window<"u"?{}:{referrer:"https://sk.thorswap.net",referer:"https://sk.thorswap.net"},ee=dt.create({headers:mt}),_e={get:(s,e)=>ee.get(s,e).json(),post:(s,e)=>ee.post(s,e).json()},te=Object.values(i.Chain),pt=(s="")=>{const e=s.toUpperCase(),[t]=e.split(".");if(te.includes(t))return!0;const[n]=e.split("/");if(te.includes(n))return!0;throw new Error(`Invalid identifier: ${s}. Expected format: <Chain>.<Ticker> or <Chain>.<Ticker>-<ContractAddress>`)},R=8,b=s=>10n**BigInt(s),S=s=>Math.log10(parseFloat(s.toString()));function B({value:s,bigIntDecimal:e=R,decimal:t=R}){const n=s<0n;let r=s.toString().substring(n?1:0);const a=t-(r.length-1);a>0&&(r="0".repeat(a)+r);const o=r.length-t;let c=r.slice(-t);return parseInt(c[e])>=5?c=`${c.substring(0,e-1)}${(parseInt(c[e-1])+1).toString()}`:c=c.substring(0,e),`${n?"-":""}${r.slice(0,o)}.${c}`.replace(/\.?0*$/,"")}var C,$,_,T,k,ye,I,L,M,F;const J=class J{constructor(e){A(this,C);A(this,_);A(this,k);A(this,I);A(this,M);p(this,"decimalMultiplier",10n**8n);p(this,"bigIntValue",0n);p(this,"decimal");const t=U(e),n=typeof e=="object";this.decimal=n?e.decimal:void 0,this.decimalMultiplier=n&&"decimalMultiplier"in e?e.decimalMultiplier:b(Math.max(se(E(t)),this.decimal||0)),d(this,k,ye).call(this,t)}static fromBigInt(e,t){return new J({decimal:t,value:B({value:e,bigIntDecimal:t,decimal:t})})}static shiftDecimals({value:e,from:t,to:n}){return this.fromBigInt(e.getBaseValue("bigint")*b(n)/b(t),n)}set(e){return new this.constructor({decimal:this.decimal,value:e,identifier:this.toString()})}add(...e){return d(this,C,$).call(this,"add",...e)}sub(...e){return d(this,C,$).call(this,"sub",...e)}mul(...e){return d(this,C,$).call(this,"mul",...e)}div(...e){return d(this,C,$).call(this,"div",...e)}gt(e){return d(this,_,T).call(this,"gt",e)}gte(e){return d(this,_,T).call(this,"gte",e)}lt(e){return d(this,_,T).call(this,"lt",e)}lte(e){return d(this,_,T).call(this,"lte",e)}eqValue(e){return d(this,_,T).call(this,"eqValue",e)}getValue(e){const t=this.formatBigIntToSafeValue(this.bigIntValue,this.decimal||S(this.decimalMultiplier));switch(e){case"number":return Number(t);case"string":return t;case"bigint":return this.bigIntValue*10n**BigInt(this.decimal||8n)/this.decimalMultiplier}}getBaseValue(e){const t=this.decimalMultiplier/b(this.decimal||i.BaseDecimal.THOR),n=this.bigIntValue/t;switch(e){case"number":return Number(n);case"string":return n.toString();case"bigint":return n}}getBigIntValue(e,t){if(!t&&typeof e=="object")return e.bigIntValue;const n=U(e),r=E(n);return r==="0"||r==="undefined"?0n:d(this,M,F).call(this,r,t)}toSignificant(e=6){const[t,n]=this.getValue("string").split("."),r=t||"",a=n||"";if((parseInt(r)?r.length+a.length:a.length)<=e)return this.getValue("string");if(r.length>=e)return r.slice(0,e).padEnd(r.length,"0");if(parseInt(r))return`${r}.${a.slice(0,e-r.length)}`.padEnd(e-r.length,"0");const c=parseInt(a),u=`${c}`.slice(0,e);return`0.${u.padStart(a.length-`${c}`.length+u.length,"0")}`}toFixed(e=6){const[t,n]=this.getValue("string").split("."),r=t||"",a=n||"";if(parseInt(r))return`${r}.${a.slice(0,e)}`.padEnd(e,"0");const o=parseInt(a),c=`${o}`.slice(0,e);return`0.${c.padStart(a.length-`${o}`.length+c.length,"0")}`}toAbbreviation(e=2){const t=this.getValue("number"),n=["","K","M","B","T","Q","Qi","S"],r=Math.floor(Math.log10(Math.abs(t))/3),a=n[r];if(!a)return this.getValue("string");const o=10**(r*3);return`${(t/o).toFixed(e)}${a}`}toCurrency(e="$",{currencyPosition:t="start",decimal:n=2,decimalSeparator:r=".",thousandSeparator:a=","}={}){const o=this.getValue("number"),[c,u=""]=o.toFixed(6).split("."),h=c.replace(/\B(?=(\d{3})+(?!\d))/g,a),l=!c&&!u?"0.00":c==="0"?`${parseFloat(`0.${u}`)}`.replace(".",r):`${h}${parseInt(u)?`${r}${u.slice(0,n)}`:""}`;return`${t==="start"?e:""}${l}${t==="end"?e:""}`}formatBigIntToSafeValue(e,t){const n=t||this.decimal||R,r=Math.max(n,S(this.decimalMultiplier)),a=e<0n,o=e.toString().substring(a?1:0),c=r-(o.length-1),u=c>0?"0".repeat(c)+o:o,h=u.length-r;let l=u.slice(-r);return parseInt(l[n])>=5?l=`${l.substring(0,n-1)}${(parseInt(l[n-1])+1).toString()}`:l=l.substring(0,n),`${a?"-":""}${u.slice(0,h)}.${l}`.replace(/\.?0*$/,"")}};C=new WeakSet,$=function(e,...t){const n=d(this,I,L).call(this,this,...t),r=Math.max(n,S(this.decimalMultiplier)),a=b(r),o=t.reduce((u,h)=>{const l=this.getBigIntValue(h,r);switch(e){case"add":return u+l;case"sub":return u-l;case"mul":return u*l/a;case"div":{if(l===0n)throw new RangeError("Division by zero");return u*a/l}default:return u}},this.bigIntValue*a/this.decimalMultiplier),c=B({bigIntDecimal:r,decimal:r,value:o});return new this.constructor({decimalMultiplier:b(r),decimal:this.decimal,value:c,identifier:this.toString()})},_=new WeakSet,T=function(e,...t){const n=d(this,I,L).call(this,this,...t),r=this.getBigIntValue(t[0],n),a=this.getBigIntValue(this,n);switch(e){case"gt":return a>r;case"gte":return a>=r;case"lt":return a<r;case"lte":return a<=r;case"eqValue":return a===r}},k=new WeakSet,ye=function(e){const t=E(e)||"0";this.bigIntValue=d(this,M,F).call(this,t)},I=new WeakSet,L=function(...e){const t=e.map(n=>typeof n=="object"?n.decimal||S(n.decimalMultiplier):se(E(n))).filter(Boolean);return Math.max(...t,R)},M=new WeakSet,F=function(e,t){const n=t?b(t):this.decimalMultiplier,r=S(n),[a="",o=""]=e.split(".");return BigInt(`${a}${o.padEnd(r,"0")}`)};let v=J;const ft=Intl.NumberFormat("fullwide",{useGrouping:!1,maximumFractionDigits:20});function E(s){const t=`${typeof s=="number"?ft.format(s):U(s)}`.replaceAll(",",".").split(".");return t.length>1?`${t.slice(0,-1).join("")}.${t.at(-1)}`:t[0]}function se(s){var t;const e=((t=s.split(".")[1])==null?void 0:t.length)||0;return Math.max(e,R)}function U(s){return typeof s=="object"?"getValue"in s?s.getValue("string"):s.value:s}const x=(s,e)=>typeof s=="bigint"?B({value:s,bigIntDecimal:e,decimal:e}):s;let W;const ne=s=>{if(!W)throw new Error("Static assets not loaded, call await AssetValue.loadStaticAssets() first");return W.get(s.toUpperCase())||{decimal:i.BaseDecimal.THOR,identifier:""}},re=async(s,e=0)=>{pt(s);const t=await ae(G(s)),n=x(e,t);return new y({decimal:t,value:n,identifier:s})};class y extends v{constructor(t){const n="identifier"in t?t.identifier:`${t.chain}.${t.symbol}`;super(t.value instanceof v?t.value:{decimal:t.decimal,value:t.value});p(this,"address");p(this,"chain");p(this,"isGasAsset",!1);p(this,"isSynthetic",!1);p(this,"symbol");p(this,"tax");p(this,"ticker");p(this,"type");const r=G(n);this.type=ce(r),this.chain=r.chain,this.ticker=r.ticker,this.symbol=r.symbol,this.address=r.address,this.isSynthetic=r.isSynthetic,this.isGasAsset=r.isGasAsset,this.tax=t.tax}toString(t=!1){const n=this.isSynthetic?this.symbol:this.ticker;return t?n:`${this.chain}.${this.symbol}`}toUrl(){return this.isSynthetic?`${this.chain}.${this.symbol.replace("/",".")}`:this.toString()}eq({chain:t,symbol:n}){return this.chain===t&&this.symbol===n}static async fromString(t,n=0){return re(t,n)}static fromStringSync(t,n=0){const{isSynthetic:r}=G(t),{tax:a,decimal:o,identifier:c}=ne(t),u=x(n,o);return c?new y({tax:a,decimal:o,identifier:c,value:u}):r?new y({tax:a,decimal:8,identifier:t,value:u}):void 0}static async fromIdentifier(t,n=0){return re(t,n)}static fromIdentifierSync(t,n=0){const{decimal:r,identifier:a}=ne(t),o=x(n,r);return new y({decimal:r,identifier:a,value:o})}static fromChainOrSignature(t,n=0){const{decimal:r,identifier:a}=oe(t),o=x(n,r);return new y({value:o,decimal:r,identifier:a})}static async loadStaticAssets(){return new Promise(async(t,n)=>{try{const{ThorchainList:r,NativeList:a,...o}=await import("@swapkit/tokens");W=[a,...Object.values(o)].reduce((u,{tokens:h})=>(h.forEach(({identifier:l,chain:g,...w})=>{const P="decimals"in w?w.decimals:i.BaseDecimal[g];u.set(l,{identifier:l,decimal:P})}),u),new Map),t({ok:!0})}catch(r){console.error(r),n({ok:!1,error:r,message:"Couldn't load static assets. Ensure you have installed @swapkit/tokens package"})}})}}const gt=s=>{const e=y.fromChainOrSignature(s);switch(s){case i.Chain.Bitcoin:case i.Chain.Litecoin:case i.Chain.BitcoinCash:return e.set(10001e-8);case i.Chain.Dogecoin:return e.set(1.00000001);case i.Chain.Avalanche:case i.Chain.Ethereum:return e.set(1e-8);case i.Chain.THORChain:case i.Chain.Maya:return e.set(0);default:return e.set(1e-8)}},G=s=>{const e=s.slice(0,14).includes("/"),[t,n]=s.split(".").pop().split("/"),r=s.includes(".")&&!e?s:`${i.Chain.THORChain}.${n}`,[a,o]=r.split("."),[c,u]=(e?n:o).split("-");return{address:u==null?void 0:u.toLowerCase(),chain:a,isGasAsset:K({chain:a,symbol:o}),isSynthetic:e,symbol:(e?`${t}/`:"")+(u?`${c}-${(u==null?void 0:u.toLowerCase())??""}`:o),ticker:c}},_t={core_wallet_connection_not_found:10001,core_estimated_max_spendable_chain_not_supported:10002,core_extend_error:10003,core_inbound_data_not_found:10004,core_approve_asset_address_or_from_not_found:10005,core_chain_halted:10099,core_wallet_xdefi_not_installed:10101,core_wallet_evmwallet_not_installed:10102,core_wallet_walletconnect_not_installed:10103,core_wallet_keystore_not_installed:10104,core_wallet_ledger_not_installed:10105,core_wallet_trezor_not_installed:10106,core_wallet_keplr_not_installed:10107,core_wallet_okx_not_installed:10108,core_swap_invalid_params:10200,core_swap_route_not_complete:10201,core_swap_asset_not_recognized:10202,core_swap_contract_not_found:10203,core_swap_route_transaction_not_found:10204,core_swap_contract_not_supported:10205,core_swap_transaction_error:10206,core_swap_quote_mode_not_supported:10207,core_transaction_deposit_error:10301,core_transaction_create_liquidity_rune_error:10302,core_transaction_create_liquidity_asset_error:10303,core_transaction_create_liquidity_invalid_params:10304,core_transaction_add_liquidity_invalid_params:10305,core_transaction_add_liquidity_no_rune_address:10306,core_transaction_add_liquidity_rune_error:10307,core_transaction_add_liquidity_asset_error:10308,core_transaction_withdraw_error:10309,core_transaction_deposit_to_pool_error:10310,core_transaction_deposit_insufficient_funds_error:10311,core_transaction_deposit_gas_error:10312,core_transaction_invalid_sender_address:10313,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,{stack:t==null?void 0:t.stack,message:t==null?void 0:t.message}),super(e,{cause:{code:_t[e],message:e}}),Object.setPrototypeOf(this,z.prototype)}}class f extends v{eq(e){return this.eqValue(e)}static fromBigInt(e,t){return new f({decimal:t,value:B({value:e,bigIntDecimal:t,decimal:t})})}}exports.AssetValue=y;exports.BigIntArithmetics=v;exports.RequestClient=_e;exports.SwapKitError=z;exports.SwapKitNumber=f;exports.assetFromString=Pe;exports.derivationPathToString=Je;exports.filterAssets=je;exports.formatBigIntToSafeValue=B;exports.gasFeeMultiplier=ke;exports.getAssetType=ce;exports.getAsymmetricAssetShare=le;exports.getAsymmetricAssetWithdrawAmount=Le;exports.getAsymmetricRuneShare=ue;exports.getAsymmetricRuneWithdrawAmount=He;exports.getCommonAssetInfo=oe;exports.getDecimal=ae;exports.getEstimatedPoolShare=Ue;exports.getLiquiditySlippage=We;exports.getMemoFor=Ke;exports.getMinAmountByChain=gt;exports.getSymmetricPoolShare=he;exports.getSymmetricWithdraw=Fe;exports.getTHORNameCost=Ye;exports.isGasAsset=K;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 Be=(s,e,t)=>e in s?D(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t;var Ie=(s,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of Se(e))!Re.call(s,r)&&r!==t&&D(s,r,{get:()=>e[r],enumerable:!(n=ve(e,r))||n.enumerable});return s};var Me=(s,e,t)=>(t=s!=null?Te($e(s)):{},Ie(e||!s||!s.__esModule?D(t,"default",{value:s,enumerable:!0}):t,s));var p=(s,e,t)=>(Be(s,typeof e!="symbol"?e+"":e,t),t),Oe=(s,e,t)=>{if(!e.has(s))throw TypeError("Cannot "+t)};var w=(s,e,t)=>{if(e.has(s))throw TypeError("Cannot add the same private member more than once");e instanceof WeakSet?e.add(s):e.set(s,t)};var d=(s,e,t)=>(Oe(s,e,"access private method"),t);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const i=require("@swapkit/types"),Ee="0x313ce567",re=async({chain:s,to:e})=>{try{const{result:t}=await ge.post(i.ChainToRPC[s],{headers:{accept:"*/*","content-type":"application/json","cache-control":"no-cache"},body:JSON.stringify({id:44,jsonrpc:"2.0",method:"eth_call",params:[{to:e.toLowerCase(),data:Ee},"latest"]})});return parseInt(BigInt(t).toString())}catch(t){return console.error(t),i.BaseDecimal[s]}},qe=async s=>{if(s===i.Chain.Ethereum)return i.BaseDecimal.ETH;const[,e]=s.split("-");return e!=null&&e.startsWith("0x")?re({chain:i.Chain.Ethereum,to:e}):i.BaseDecimal.ETH},xe=async s=>{const[,e]=s.split("-");return e!=null&&e.startsWith("0x")?re({chain:i.Chain.Avalanche,to:e.toLowerCase()}):i.BaseDecimal.AVAX},Ve=async s=>(s===i.Chain.BinanceSmartChain,i.BaseDecimal.BSC),ie=async({chain:s,symbol:e})=>{switch(s){case i.Chain.Ethereum:return qe(e);case i.Chain.Avalanche:return xe(e);case i.Chain.BinanceSmartChain:return Ve(e);default:return i.BaseDecimal[s]}},ke={[i.FeeOption.Average]:1.2,[i.FeeOption.Fast]:1.5,[i.FeeOption.Fastest]:2},K=({chain:s,symbol:e})=>{switch(s){case i.Chain.Bitcoin:case i.Chain.BitcoinCash:case i.Chain.Litecoin:case i.Chain.Dogecoin:case i.Chain.Binance:case i.Chain.Ethereum:case i.Chain.Avalanche:return e===s;case i.Chain.Arbitrum:case i.Chain.Optimism:return e==="ETH";case i.Chain.Maya:return e==="CACAO";case i.Chain.Kujira:return e==="KUJI";case i.Chain.Cosmos:return e==="ATOM";case i.Chain.Polygon:return e==="MATIC";case i.Chain.BinanceSmartChain:return e==="BNB";case i.Chain.THORChain:return e==="RUNE"}},ae=s=>{switch(s){case"ETH.THOR":return{identifier:"ETH.THOR-0xa5f2211b9b8170f694421f2046281775e8468044",decimal:18};case"ETH.vTHOR":return{identifier:"ETH.vTHOR-0x815c23eca83261b6ec689b60cc4a58b54bc24d8d",decimal:18};case i.Chain.Cosmos:return{identifier:"GAIA.ATOM",decimal:i.BaseDecimal[s]};case i.Chain.THORChain:return{identifier:"THOR.RUNE",decimal:i.BaseDecimal[s]};case i.Chain.BinanceSmartChain:return{identifier:"BSC.BNB",decimal:i.BaseDecimal[s]};case i.Chain.Maya:return{identifier:"MAYA.CACAO",decimal:i.BaseDecimal.MAYA};case"MAYA.MAYA":return{identifier:"MAYA.MAYA",decimal:4};case i.Chain.Kujira:case i.Chain.Arbitrum:case i.Chain.Optimism:case i.Chain.BitcoinCash:case i.Chain.Litecoin:case i.Chain.Dogecoin:case i.Chain.Binance:case i.Chain.Avalanche:case i.Chain.Polygon:case i.Chain.Bitcoin:case i.Chain.Ethereum:return{identifier:`${s}.${s}`,decimal:i.BaseDecimal[s]}}},oe=({chain:s,symbol:e})=>{if(e.includes("/"))return"Synth";switch(s){case i.Chain.Bitcoin:case i.Chain.BitcoinCash:case i.Chain.Dogecoin:case i.Chain.Litecoin:case i.Chain.Maya:case i.Chain.THORChain:return"Native";case i.Chain.Cosmos:return e==="ATOM"?"Native":i.Chain.Cosmos;case i.Chain.Kujira:return e===i.Chain.Kujira?"Native":i.Chain.Kujira;case i.Chain.Binance:return e===i.Chain.Binance?"Native":"BEP2";case i.Chain.BinanceSmartChain:return e===i.Chain.Binance?"Native":"BEP20";case i.Chain.Ethereum:return e===i.Chain.Ethereum?"Native":"ERC20";case i.Chain.Avalanche:return e===i.Chain.Avalanche?"Native":i.Chain.Avalanche;case i.Chain.Polygon:return e===i.Chain.Polygon?"Native":"POLYGON";case i.Chain.Arbitrum:return[i.Chain.Ethereum,i.Chain.Arbitrum].includes(e)?"Native":"ARBITRUM";case i.Chain.Optimism:return[i.Chain.Ethereum,i.Chain.Optimism].includes(e)?"Native":"OPTIMISM"}},Pe=s=>{var o;const[e,...t]=s.split("."),n=s.includes("/"),r=t.join("."),a=(o=r==null?void 0:r.split("-"))==null?void 0:o[0];return{chain:e,symbol:r,ticker:a,synth:n}},De=new RegExp(/(.)\1{6}|\.ORG|\.NET|\.FINANCE|\.COM|WWW|HTTP|\\\\|\/\/|[\s$%:[\]]/,"gmi"),Ne=s=>{const[e,t]=s.split(".");if(!i.EVMChainList.includes(e))return!0;const[,n]=t.split("-");return K({chain:e,symbol:t})||!!n},je=s=>s.filter(e=>{const t=`${e.chain}.${e.symbol}`;return!De.test(t)&&Ne(t)&&e.value!=="0"}),ce=({liquidityUnits:s,poolUnits:e,runeDepth:t})=>{const n=m(s),r=m(e),a=m(t),o=n.mul(a),c=r.mul(r).mul(2),u=r.mul(n).mul(2),h=n.mul(n),l=r.mul(r).mul(r);return o.mul(c.sub(u).add(h)).div(l)},ue=({liquidityUnits:s,poolUnits:e,assetDepth:t})=>{const n=m(s),r=m(e),a=m(t),o=n.mul(a),c=r.mul(r).mul(2),u=r.mul(n).mul(2),h=n.mul(n),l=o.mul(c.sub(u).add(h)),g=r.mul(r).mul(r);return l.div(g)},He=({percent:s,runeDepth:e,liquidityUnits:t,poolUnits:n})=>ce({runeDepth:e,liquidityUnits:t,poolUnits:n}).mul(s),Le=({percent:s,assetDepth:e,liquidityUnits:t,poolUnits:n})=>ue({assetDepth:e,liquidityUnits:t,poolUnits:n}).mul(s),m=s=>f.fromBigInt(BigInt(s),i.BaseDecimal.THOR),le=({liquidityUnits:s,poolUnits:e,runeDepth:t,assetDepth:n})=>({assetAmount:m(n).mul(s).div(e),runeAmount:m(t).mul(s).div(e)}),Fe=({liquidityUnits:s,poolUnits:e,runeDepth:t,assetDepth:n,percent:r})=>Object.fromEntries(Object.entries(le({liquidityUnits:s,poolUnits:e,runeDepth:t,assetDepth:n})).map(([a,o])=>[a,o.mul(r)])),Ue=({runeDepth:s,poolUnits:e,assetDepth:t,liquidityUnits:n,runeAmount:r,assetAmount:a})=>{const o=new f({value:s,decimal:8}),c=new f({value:t,decimal:8}),u=new f({value:e,decimal:8}),h=new f({value:r,decimal:8}),l=new f({value:a,decimal:8}),g=h.mul(c),k=l.mul(o),ye=h.mul(l),be=o.mul(c),Ce=u.mul(g.add(k.add(ye.mul(2)))),we=g.add(k.add(be.mul(2))),Q=Ce.div(we),P=m(n).add(Q);if(Q.getBaseValue("number")===0)return P.div(u).getBaseValue("number");const Ae=u.add(P);return P.div(Ae).getBaseValue("number")},We=({runeAmount:s,assetAmount:e,runeDepth:t,assetDepth:n})=>{if(s==="0"||e==="0"||t==="0"||n==="0")return 0;const r=m(t),a=m(n),o=m(e),c=m(s),u=o.mul(r).sub(a.mul(c)),h=a.mul(c).add(r.mul(a));return Math.abs(u.div(h).getBaseValue("number"))},Ge=({symbol:s,ticker:e,chain:t})=>t==="ETH"&&e!=="ETH"?`${e}-${s.slice(-3)}`:s,Ke=(s,e)=>{switch(s){case i.MemoType.LEAVE:case i.MemoType.BOND:{const{address:t}=e;return`${s}:${t}`}case i.MemoType.UNBOND:{const{address:t,unbondAmount:n}=e;return`${s}:${t}:${n*10**8}`}case i.MemoType.THORNAME_REGISTER:{const{name:t,chain:n,address:r,owner:a}=e;return`${s}:${t}:${n}:${r}${a?`:${a}`:""}`}case i.MemoType.DEPOSIT:{const{chain:t,symbol:n,address:r,singleSide:a}=e;return a?`${s}:${t}/${n}::t:0`:`${s}:${t}.${n}:${r||""}:t:0`}case i.MemoType.WITHDRAW:{const{chain:t,ticker:n,symbol:r,basisPoints:a,targetAssetString:o,singleSide:c}=e,u=!c&&o?`:${o}`:"",h=Ge({chain:t,symbol:r,ticker:n});return`${s}:${t}${c?"/":"."}${h}:${a}${u}`}case i.MemoType.OPEN_LOAN:case i.MemoType.CLOSE_LOAN:{const{asset:t,address:n}=e;return`${s}:${t}:${n}`}default:return""}},Ye=s=>{if(s<0)throw new Error("Invalid number of year");return 10+s},ze=s=>{if(s.length>30)return!1;const e=/^[a-zA-Z0-9+_-]+$/g;return!!s.match(e)},Je=([s,e,t,n,r])=>`${s}'/${e}'/${t}'/${n}${typeof r!="number"?"":`/${r}`}`;class X extends Error{constructor(e,t,n){const r=e.status||e.status===0?e.status:"",a=e.statusText||"",o=`${r} ${a}`.trim(),c=o?`status code ${o}`:"an unknown error";super(`Request failed with ${c}`),Object.defineProperty(this,"response",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"request",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"options",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.name="HTTPError",this.response=e,this.request=t,this.options=n}}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 E=s=>s!==null&&typeof s=="object",M=(...s)=>{for(const e of s)if((!E(e)||Array.isArray(e))&&e!==void 0)throw new TypeError("The `options` argument must be an object");return Y({},...s)},de=(s={},e={})=>{const t=new globalThis.Headers(s),n=e instanceof globalThis.Headers,r=new globalThis.Headers(e);for(const[a,o]of r.entries())n&&o==="undefined"||o===void 0?t.delete(a):t.set(a,o);return t},Y=(...s)=>{let e={},t={};for(const n of s)if(Array.isArray(n))Array.isArray(e)||(e=[]),e=[...e,...n];else if(E(n)){for(let[r,a]of Object.entries(n))E(a)&&r in e&&(a=Y(e[r],a)),e={...e,[r]:a};E(n.headers)&&(t=de(t,n.headers),e.headers=t)}return e},Qe=(()=>{let s=!1,e=!1;const t=typeof globalThis.ReadableStream=="function",n=typeof globalThis.Request=="function";return t&&n&&(e=new globalThis.Request("https://empty.invalid",{body:new globalThis.ReadableStream,method:"POST",get duplex(){return s=!0,"half"}}).headers.has("Content-Type")),s&&!e})(),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:"*/*"},N=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},nt={method:!0,headers:!0,body:!0,mode:!0,credentials:!0,cache:!0,redirect:!0,referrer:!0,referrerPolicy:!0,integrity:!0,keepalive:!0,signal:!0,window:!0,dispatcher:!0,duplex:!0},rt=s=>me.includes(s)?s.toUpperCase():s,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:s=>.3*2**(s-1)*1e3},ot=(s={})=>{if(typeof s=="number")return{...Z,limit:s};if(s.methods&&!Array.isArray(s.methods))throw new Error("retry.methods must be an array");if(s.statusCodes&&!Array.isArray(s.statusCodes))throw new Error("retry.statusCodes must be an array");return{...Z,...s,afterStatusCodes:fe}};async function ct(s,e,t,n){return new Promise((r,a)=>{const o=setTimeout(()=>{t&&t.abort(),a(new he(s))},n.timeout);n.fetch(s,e).then(r).catch(a).then(()=>{clearTimeout(o)})})}async function ut(s,{signal:e}){return new Promise((t,n)=>{e&&(e.throwIfAborted(),e.addEventListener("abort",r,{once:!0}));function r(){clearTimeout(a),n(e.reason)}const a=setTimeout(()=>{e==null||e.removeEventListener("abort",r),t()},s)})}const lt=(s,e)=>{const t={};for(const n in e)!(n in nt)&&!(n in st)&&!(n in s)&&(t[n]=e[n]);return t};class x{static create(e,t){const n=new x(e,t),r=async()=>{if(typeof n._options.timeout=="number"&&n._options.timeout>N)throw new RangeError(`The \`timeout\` option cannot be greater than ${N}`);await Promise.resolve();let c=await n._fetch();for(const u of n._options.hooks.afterResponse){const h=await u(n.request,n._options,n._decorateResponse(c.clone()));h instanceof globalThis.Response&&(c=h)}if(n._decorateResponse(c),!c.ok&&n._options.throwHttpErrors){let u=new X(c,n.request,n._options);for(const h of n._options.hooks.beforeError)u=await h(u);throw u}if(n._options.onDownloadProgress){if(typeof n._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 n._stream(c.clone(),n._options.onDownloadProgress)}return c},o=n._options.retry.methods.includes(n.request.method.toLowerCase())?n._retry(r):r();for(const[c,u]of Object.entries(tt))o[c]=async()=>{n.request.headers.set("accept",n.request.headers.get("accept")||u);const l=(await o).clone();if(c==="json"){if(l.status===204||(await l.clone().arrayBuffer()).byteLength===0)return"";if(t.parseJson)return t.parseJson(await l.text())}return l[c]()};return o}constructor(e,t={}){if(Object.defineProperty(this,"request",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"abortController",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_retryCount",{enumerable:!0,configurable:!0,writable:!0,value:0}),Object.defineProperty(this,"_input",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_options",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this._input=e,this._options={credentials:this._input.credentials||"same-origin",...t,headers:de(this._input.headers,t.headers),hooks:Y({beforeRequest:[],beforeRetry:[],beforeError:[],afterResponse:[]},t.hooks),method:rt(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 n=this._options.signal;this._options.signal.addEventListener("abort",()=>{this.abortController.abort(n.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 r="?"+(typeof this._options.searchParams=="string"?this._options.searchParams.replace(/^\?/,""):new URLSearchParams(this._options.searchParams).toString()),a=this.request.url.replace(/(?:\?.*?)?(?=#|$)/,r);(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 n=e.response.headers.get("Retry-After");if(n&&this._options.retry.afterStatusCodes.includes(e.response.status)){let r=Number(n);return Number.isNaN(r)?r=Date.parse(n)-Date.now():r*=1e3,this._options.retry.maxRetryAfter!==void 0&&r>this._options.retry.maxRetryAfter?0:r}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 n=Math.min(this._calculateRetryDelay(t),N);if(n!==0&&this._retryCount>0){await ut(n,{signal:this._options.signal});for(const r of this._options.hooks.beforeRetry)if(await r({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 n=await t(this.request,this._options);if(n instanceof Request){this.request=n;break}if(n instanceof Response)return n}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 n=Number(e.headers.get("content-length"))||0;let r=0;return e.status===204?(t&&t({percent:1,totalBytes:n,transferredBytes:r},new Uint8Array),new globalThis.Response(null,{status:e.status,statusText:e.statusText,headers:e.headers})):new globalThis.Response(new globalThis.ReadableStream({async start(a){const o=e.body.getReader();t&&t({percent:0,transferredBytes:0,totalBytes:n},new Uint8Array);async function c(){const{done:u,value:h}=await o.read();if(u){a.close();return}if(t){r+=h.byteLength;const l=n===0?0:r/n;t({percent:l,transferredBytes:r,totalBytes:n},h)}a.enqueue(h),await c()}await c()}}),{status:e.status,statusText:e.statusText,headers:e.headers})}}/*! MIT License © Sindre Sorhus */const H=s=>{const e=(t,n)=>x.create(t,M(s,n));for(const t of me)e[t]=(n,r)=>x.create(n,M(s,r,{method:t}));return e.create=t=>H(M(t)),e.extend=t=>H(M(s,t)),e.stop=pe,e},ht=H(),dt=ht,mt=typeof window<"u"?{}:{referrer:"https://sk.thorswap.net",referer:"https://sk.thorswap.net"},ee=dt.create({headers:mt}),ge={get:(s,e)=>ee.get(s,e).json(),post:(s,e)=>ee.post(s,e).json()},te=Object.values(i.Chain),pt=(s="")=>{const e=s.toUpperCase(),[t]=e.split(".");if(te.includes(t))return!0;const[n]=e.split("/");if(te.includes(n))return!0;throw new Error(`Invalid identifier: ${s}. Expected format: <Chain>.<Ticker> or <Chain>.<Ticker>-<ContractAddress>`)},$=8,b=s=>10n**BigInt(s),v=s=>Math.log10(parseFloat(s.toString()));function R({value:s,bigIntDecimal:e=$,decimal:t=$}){const n=s<0n;let r=s.toString().substring(n?1:0);const a=t-(r.length-1);a>0&&(r="0".repeat(a)+r);const o=r.length-t;let c=r.slice(-t);return parseInt(c[e])>=5?c=`${c.substring(0,e-1)}${(parseInt(c[e-1])+1).toString()}`:c=c.substring(0,e),`${n?"-":""}${r.slice(0,o)}.${c}`.replace(/\.?0*$/,"")}var C,S,_,A,V,_e,B,L,I,F;const J=class J{constructor(e){w(this,C);w(this,_);w(this,V);w(this,B);w(this,I);p(this,"decimalMultiplier",10n**8n);p(this,"bigIntValue",0n);p(this,"decimal");const t=U(e),n=typeof e=="object";this.decimal=n?e.decimal:void 0,this.decimalMultiplier=n&&"decimalMultiplier"in e?e.decimalMultiplier:b(Math.max(se(O(t)),this.decimal||0)),d(this,V,_e).call(this,t)}static fromBigInt(e,t){return new J({decimal:t,value:R({value:e,bigIntDecimal:t,decimal:t})})}static shiftDecimals({value:e,from:t,to:n}){return this.fromBigInt(e.getBaseValue("bigint")*b(n)/b(t),n)}set(e){return new this.constructor({decimal:this.decimal,value:e,identifier:this.toString()})}add(...e){return d(this,C,S).call(this,"add",...e)}sub(...e){return d(this,C,S).call(this,"sub",...e)}mul(...e){return d(this,C,S).call(this,"mul",...e)}div(...e){return d(this,C,S).call(this,"div",...e)}gt(e){return d(this,_,A).call(this,"gt",e)}gte(e){return d(this,_,A).call(this,"gte",e)}lt(e){return d(this,_,A).call(this,"lt",e)}lte(e){return d(this,_,A).call(this,"lte",e)}eqValue(e){return d(this,_,A).call(this,"eqValue",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;case"bigint":return this.bigIntValue*10n**BigInt(this.decimal||8n)/this.decimalMultiplier}}getBaseValue(e){const t=this.decimalMultiplier/b(this.decimal||i.BaseDecimal.THOR),n=this.bigIntValue/t;switch(e){case"number":return Number(n);case"string":return n.toString();case"bigint":return n}}getBigIntValue(e,t){if(!t&&typeof e=="object")return e.bigIntValue;const n=U(e),r=O(n);return r==="0"||r==="undefined"?0n:d(this,I,F).call(this,r,t)}toSignificant(e=6){const[t,n]=this.getValue("string").split("."),r=t||"",a=n||"";if((parseInt(r)?r.length+a.length:a.length)<=e)return this.getValue("string");if(r.length>=e)return r.slice(0,e).padEnd(r.length,"0");if(parseInt(r))return`${r}.${a.slice(0,e-r.length)}`.padEnd(e-r.length,"0");const c=parseInt(a),u=`${c}`.slice(0,e);return`0.${u.padStart(a.length-`${c}`.length+u.length,"0")}`}toFixed(e=6){const[t,n]=this.getValue("string").split("."),r=t||"",a=n||"";if(parseInt(r))return`${r}.${a.slice(0,e)}`.padEnd(e,"0");const o=parseInt(a),c=`${o}`.slice(0,e);return`0.${c.padStart(a.length-`${o}`.length+c.length,"0")}`}toAbbreviation(e=2){const t=this.getValue("number"),n=["","K","M","B","T","Q","Qi","S"],r=Math.floor(Math.log10(Math.abs(t))/3),a=n[r];if(!a)return this.getValue("string");const o=10**(r*3);return`${(t/o).toFixed(e)}${a}`}toCurrency(e="$",{currencyPosition:t="start",decimal:n=2,decimalSeparator:r=".",thousandSeparator:a=","}={}){const o=this.getValue("number"),[c,u=""]=o.toFixed(6).split("."),h=c.replace(/\B(?=(\d{3})+(?!\d))/g,a),l=!c&&!u?"0.00":c==="0"?`${parseFloat(`0.${u}`)}`.replace(".",r):`${h}${parseInt(u)?`${r}${u.slice(0,n)}`:""}`;return`${t==="start"?e:""}${l}${t==="end"?e:""}`}formatBigIntToSafeValue(e,t){const n=t||this.decimal||$,r=Math.max(n,v(this.decimalMultiplier)),a=e<0n,o=e.toString().substring(a?1:0),c=r-(o.length-1),u=c>0?"0".repeat(c)+o:o,h=u.length-r;let l=u.slice(-r);return parseInt(l[n])>=5?l=`${l.substring(0,n-1)}${(parseInt(l[n-1])+1).toString()}`:l=l.substring(0,n),`${a?"-":""}${u.slice(0,h)}.${l}`.replace(/\.?0*$/,"")}};C=new WeakSet,S=function(e,...t){const n=d(this,B,L).call(this,this,...t),r=Math.max(n,v(this.decimalMultiplier)),a=b(r),o=t.reduce((u,h)=>{const l=this.getBigIntValue(h,r);switch(e){case"add":return u+l;case"sub":return u-l;case"mul":return u*l/a;case"div":{if(l===0n)throw new RangeError("Division by zero");return u*a/l}default:return u}},this.bigIntValue*a/this.decimalMultiplier),c=R({bigIntDecimal:r,decimal:r,value:o});return new this.constructor({decimalMultiplier:b(r),decimal:this.decimal,value:c,identifier:this.toString()})},_=new WeakSet,A=function(e,...t){const n=d(this,B,L).call(this,this,...t),r=this.getBigIntValue(t[0],n),a=this.getBigIntValue(this,n);switch(e){case"gt":return a>r;case"gte":return a>=r;case"lt":return a<r;case"lte":return a<=r;case"eqValue":return a===r}},V=new WeakSet,_e=function(e){const t=O(e)||"0";this.bigIntValue=d(this,I,F).call(this,t)},B=new WeakSet,L=function(...e){const t=e.map(n=>typeof n=="object"?n.decimal||v(n.decimalMultiplier):se(O(n))).filter(Boolean);return Math.max(...t,$)},I=new WeakSet,F=function(e,t){const n=t?b(t):this.decimalMultiplier,r=v(n),[a="",o=""]=e.split(".");return BigInt(`${a}${o.padEnd(r,"0")}`)};let T=J;const ft=Intl.NumberFormat("fullwide",{useGrouping:!1,maximumFractionDigits:20});function O(s){const t=`${typeof s=="number"?ft.format(s):U(s)}`.replaceAll(",",".").split(".");return t.length>1?`${t.slice(0,-1).join("")}.${t.at(-1)}`:t[0]}function se(s){var t;const e=((t=s.split(".")[1])==null?void 0:t.length)||0;return Math.max(e,$)}function U(s){return typeof s=="object"?"getValue"in s?s.getValue("string"):s.value:s}const q=(s,e)=>typeof s=="bigint"?R({value:s,bigIntDecimal:e,decimal:e}):s;let W;const ne=s=>{if(!W)throw new Error("Static assets not loaded, call await AssetValue.loadStaticAssets() first");return W.get(s.toUpperCase())||{decimal:i.BaseDecimal.THOR,identifier:""}},j=async(s,e=0)=>{pt(s);const t=await ie(G(s)),n=q(e,t);return new y({decimal:t,value:n,identifier:s})};class y extends T{constructor(t){const n="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,"isGasAsset",!1);p(this,"isSynthetic",!1);p(this,"symbol");p(this,"tax");p(this,"ticker");p(this,"type");const r=G(n);this.type=oe(r),this.chain=r.chain,this.ticker=r.ticker,this.symbol=r.symbol,this.address=r.address,this.isSynthetic=r.isSynthetic,this.isGasAsset=r.isGasAsset,this.tax=t.tax}toString(){return this.isSynthetic?this.symbol:`${this.chain}.${this.symbol}`}toUrl(){return this.isSynthetic?`${this.chain}.${this.symbol.replace("/",".")}`:this.toString()}eq({chain:t,symbol:n}){return this.chain===t&&this.symbol===n}static fromUrl(t,n=0){const[r,a,o]=t.split(".");if(!r||!a)throw new Error("Invalid asset url");const c=r===i.Chain.THORChain&&o?`${r}.${a}/${o}`:t;return j(c,n)}static fromString(t,n=0){return j(t,n)}static fromStringSync(t,n=0){const{isSynthetic:r}=G(t),{tax:a,decimal:o,identifier:c}=ne(t),u=q(n,o);return c?new y({tax:a,decimal:o,identifier:c,value:u}):r?new y({tax:a,decimal:8,identifier:t,value:u}):void 0}static fromIdentifier(t,n=0){return j(t,n)}static fromIdentifierSync(t,n=0){const{decimal:r,identifier:a}=ne(t),o=q(n,r);return new y({decimal:r,identifier:a,value:o})}static fromChainOrSignature(t,n=0){const{decimal:r,identifier:a}=ae(t),o=q(n,r);return new y({value:o,decimal:r,identifier:a})}static loadStaticAssets(){return new Promise(async(t,n)=>{try{const r=await import("@swapkit/tokens");W=Object.values(r).reduce((o,{tokens:c})=>(c.forEach(({identifier:u,chain:h,...l})=>{const g="decimals"in l?l.decimals:i.BaseDecimal[h];o.set(u,{identifier:u,decimal:g})}),o),new Map),t({ok:!0})}catch(r){console.error(r),n({ok:!1,error:r,message:"Couldn't load static assets. Ensure you have installed @swapkit/tokens package"})}})}}const gt=s=>{const e=y.fromChainOrSignature(s);switch(s){case i.Chain.Bitcoin:case i.Chain.Litecoin:case i.Chain.BitcoinCash:return e.set(10001e-8);case i.Chain.Dogecoin:return e.set(1.00000001);case i.Chain.Avalanche:case i.Chain.Ethereum:return e.set(1e-8);case i.Chain.THORChain:case i.Chain.Maya:return e.set(0);default:return e.set(1e-8)}},G=s=>{const e=s.slice(0,14).includes("/"),[t,n]=s.split(".").pop().split("/"),r=s.includes(".")&&!e?s:`${i.Chain.THORChain}.${n}`,[a,o]=r.split("."),[c,u]=(e?n:o).split("-");return{address:u==null?void 0:u.toLowerCase(),chain:a,isGasAsset:K({chain:a,symbol:o}),isSynthetic:e,symbol:(e?`${t}/`:"")+(u?`${c}-${(u==null?void 0:u.toLowerCase())??""}`:o),ticker:c}},_t={core_wallet_connection_not_found:10001,core_estimated_max_spendable_chain_not_supported:10002,core_extend_error:10003,core_inbound_data_not_found:10004,core_approve_asset_address_or_from_not_found:10005,core_chain_halted:10099,core_wallet_xdefi_not_installed:10101,core_wallet_evmwallet_not_installed:10102,core_wallet_walletconnect_not_installed:10103,core_wallet_keystore_not_installed:10104,core_wallet_ledger_not_installed:10105,core_wallet_trezor_not_installed:10106,core_wallet_keplr_not_installed:10107,core_wallet_okx_not_installed:10108,core_swap_invalid_params:10200,core_swap_route_not_complete:10201,core_swap_asset_not_recognized:10202,core_swap_contract_not_found:10203,core_swap_route_transaction_not_found:10204,core_swap_contract_not_supported:10205,core_swap_transaction_error:10206,core_swap_quote_mode_not_supported:10207,core_transaction_deposit_error:10301,core_transaction_create_liquidity_rune_error:10302,core_transaction_create_liquidity_asset_error:10303,core_transaction_create_liquidity_invalid_params:10304,core_transaction_add_liquidity_invalid_params:10305,core_transaction_add_liquidity_no_rune_address:10306,core_transaction_add_liquidity_rune_error:10307,core_transaction_add_liquidity_asset_error:10308,core_transaction_withdraw_error:10309,core_transaction_deposit_to_pool_error:10310,core_transaction_deposit_insufficient_funds_error:10311,core_transaction_deposit_gas_error:10312,core_transaction_invalid_sender_address:10313,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,{stack:t==null?void 0:t.stack,message:t==null?void 0:t.message}),super(e,{cause:{code:_t[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:R({value:e,bigIntDecimal:t,decimal:t})})}}exports.AssetValue=y;exports.BigIntArithmetics=T;exports.RequestClient=ge;exports.SwapKitError=z;exports.SwapKitNumber=f;exports.assetFromString=Pe;exports.derivationPathToString=Je;exports.filterAssets=je;exports.formatBigIntToSafeValue=R;exports.gasFeeMultiplier=ke;exports.getAssetType=oe;exports.getAsymmetricAssetShare=ue;exports.getAsymmetricAssetWithdrawAmount=Le;exports.getAsymmetricRuneShare=ce;exports.getAsymmetricRuneWithdrawAmount=He;exports.getCommonAssetInfo=ae;exports.getDecimal=ie;exports.getEstimatedPoolShare=Ue;exports.getLiquiditySlippage=We;exports.getMemoFor=Ke;exports.getMinAmountByChain=gt;exports.getSymmetricPoolShare=le;exports.getSymmetricWithdraw=Fe;exports.getTHORNameCost=Ye;exports.isGasAsset=K;exports.validateTHORName=ze;
|
package/dist/index.d.ts
CHANGED
|
@@ -33,12 +33,13 @@ export declare class AssetValue extends BigIntArithmetics {
|
|
|
33
33
|
ticker: string;
|
|
34
34
|
type: ReturnType<typeof getAssetType>;
|
|
35
35
|
constructor(params: AssetValueParams);
|
|
36
|
-
toString(
|
|
36
|
+
toString(): string;
|
|
37
37
|
toUrl(): string;
|
|
38
38
|
eq({ chain, symbol }: {
|
|
39
39
|
chain: Chain;
|
|
40
40
|
symbol: string;
|
|
41
41
|
}): boolean;
|
|
42
|
+
static fromUrl(urlAsset: string, value?: NumberPrimitives): Promise<AssetValue>;
|
|
42
43
|
static fromString(assetString: string, value?: NumberPrimitives): Promise<AssetValue>;
|
|
43
44
|
static fromStringSync(assetString: string, value?: NumberPrimitives): AssetValue | undefined;
|
|
44
45
|
static fromIdentifier(assetString: `${Chain}.${string}` | `${Chain}/${string}` | `${Chain}.${string}-${string}`, value?: NumberPrimitives): Promise<AssetValue>;
|
package/dist/index.es.js
CHANGED
|
@@ -4,14 +4,14 @@ var f = (r, t, e) => (yt(r, typeof t != "symbol" ? t + "" : t, e), e), wt = (r,
|
|
|
4
4
|
if (!t.has(r))
|
|
5
5
|
throw TypeError("Cannot " + e);
|
|
6
6
|
};
|
|
7
|
-
var
|
|
7
|
+
var T = (r, t, e) => {
|
|
8
8
|
if (t.has(r))
|
|
9
9
|
throw TypeError("Cannot add the same private member more than once");
|
|
10
10
|
t instanceof WeakSet ? t.add(r) : t.set(r, e);
|
|
11
11
|
};
|
|
12
12
|
var m = (r, t, e) => (wt(r, t, "access private method"), e);
|
|
13
|
-
import { FeeOption as
|
|
14
|
-
const Tt = "0x313ce567",
|
|
13
|
+
import { FeeOption as H, BaseDecimal as h, 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
16
|
const { result: e } = await Zt.post(vt[r], {
|
|
17
17
|
headers: {
|
|
@@ -28,17 +28,17 @@ const Tt = "0x313ce567", it = async ({ chain: r, to: t }) => {
|
|
|
28
28
|
});
|
|
29
29
|
return parseInt(BigInt(e).toString());
|
|
30
30
|
} catch (e) {
|
|
31
|
-
return console.error(e),
|
|
31
|
+
return console.error(e), h[r];
|
|
32
32
|
}
|
|
33
33
|
}, $t = async (r) => {
|
|
34
34
|
if (r === o.Ethereum)
|
|
35
|
-
return
|
|
35
|
+
return h.ETH;
|
|
36
36
|
const [, t] = r.split("-");
|
|
37
|
-
return t != null && t.startsWith("0x") ?
|
|
37
|
+
return t != null && t.startsWith("0x") ? nt({ chain: o.Ethereum, to: t }) : h.ETH;
|
|
38
38
|
}, Rt = async (r) => {
|
|
39
39
|
const [, t] = r.split("-");
|
|
40
|
-
return t != null && t.startsWith("0x") ?
|
|
41
|
-
}, St = async (r) => r === o.BinanceSmartChain ?
|
|
40
|
+
return t != null && t.startsWith("0x") ? nt({ chain: o.Avalanche, to: t.toLowerCase() }) : h.AVAX;
|
|
41
|
+
}, St = async (r) => r === o.BinanceSmartChain ? h.BSC : h.BSC, Ct = async ({ chain: r, symbol: t }) => {
|
|
42
42
|
switch (r) {
|
|
43
43
|
case o.Ethereum:
|
|
44
44
|
return $t(t);
|
|
@@ -47,13 +47,13 @@ const Tt = "0x313ce567", it = async ({ chain: r, to: t }) => {
|
|
|
47
47
|
case o.BinanceSmartChain:
|
|
48
48
|
return St(t);
|
|
49
49
|
default:
|
|
50
|
-
return
|
|
50
|
+
return h[r];
|
|
51
51
|
}
|
|
52
52
|
}, ie = {
|
|
53
|
-
[
|
|
54
|
-
[
|
|
55
|
-
[
|
|
56
|
-
},
|
|
53
|
+
[H.Average]: 1.2,
|
|
54
|
+
[H.Fast]: 1.5,
|
|
55
|
+
[H.Fastest]: 2
|
|
56
|
+
}, it = ({ chain: r, symbol: t }) => {
|
|
57
57
|
switch (r) {
|
|
58
58
|
case o.Bitcoin:
|
|
59
59
|
case o.BitcoinCash:
|
|
@@ -86,13 +86,13 @@ const Tt = "0x313ce567", it = async ({ chain: r, to: t }) => {
|
|
|
86
86
|
case "ETH.vTHOR":
|
|
87
87
|
return { identifier: "ETH.vTHOR-0x815c23eca83261b6ec689b60cc4a58b54bc24d8d", decimal: 18 };
|
|
88
88
|
case o.Cosmos:
|
|
89
|
-
return { identifier: "GAIA.ATOM", decimal:
|
|
89
|
+
return { identifier: "GAIA.ATOM", decimal: h[r] };
|
|
90
90
|
case o.THORChain:
|
|
91
|
-
return { identifier: "THOR.RUNE", decimal:
|
|
91
|
+
return { identifier: "THOR.RUNE", decimal: h[r] };
|
|
92
92
|
case o.BinanceSmartChain:
|
|
93
|
-
return { identifier: "BSC.BNB", decimal:
|
|
93
|
+
return { identifier: "BSC.BNB", decimal: h[r] };
|
|
94
94
|
case o.Maya:
|
|
95
|
-
return { identifier: "MAYA.CACAO", decimal:
|
|
95
|
+
return { identifier: "MAYA.CACAO", decimal: h.MAYA };
|
|
96
96
|
case "MAYA.MAYA":
|
|
97
97
|
return { identifier: "MAYA.MAYA", decimal: 4 };
|
|
98
98
|
case o.Kujira:
|
|
@@ -106,7 +106,7 @@ const Tt = "0x313ce567", it = async ({ chain: r, to: t }) => {
|
|
|
106
106
|
case o.Polygon:
|
|
107
107
|
case o.Bitcoin:
|
|
108
108
|
case o.Ethereum:
|
|
109
|
-
return { identifier: `${r}.${r}`, decimal:
|
|
109
|
+
return { identifier: `${r}.${r}`, decimal: h[r] };
|
|
110
110
|
}
|
|
111
111
|
}, Ot = ({ chain: r, symbol: t }) => {
|
|
112
112
|
if (t.includes("/"))
|
|
@@ -150,7 +150,7 @@ const Tt = "0x313ce567", it = async ({ chain: r, to: t }) => {
|
|
|
150
150
|
if (!At.includes(t))
|
|
151
151
|
return !0;
|
|
152
152
|
const [, s] = e.split("-");
|
|
153
|
-
return
|
|
153
|
+
return it({ chain: t, symbol: e }) || !!s;
|
|
154
154
|
}, ae = (r) => r.filter((t) => {
|
|
155
155
|
const e = `${t.chain}.${t.symbol}`;
|
|
156
156
|
return !Et.test(e) && Mt(e) && t.value !== "0";
|
|
@@ -159,14 +159,14 @@ const Tt = "0x313ce567", it = async ({ chain: r, to: t }) => {
|
|
|
159
159
|
poolUnits: t,
|
|
160
160
|
runeDepth: e
|
|
161
161
|
}) => {
|
|
162
|
-
const s = p(r), n = p(t), i = p(e), a = s.mul(i), c = n.mul(n).mul(2), u = n.mul(s).mul(2),
|
|
163
|
-
return a.mul(c.sub(u).add(
|
|
162
|
+
const s = p(r), n = p(t), i = p(e), a = s.mul(i), c = n.mul(n).mul(2), u = n.mul(s).mul(2), d = s.mul(s), l = n.mul(n).mul(n);
|
|
163
|
+
return a.mul(c.sub(u).add(d)).div(l);
|
|
164
164
|
}, xt = ({
|
|
165
165
|
liquidityUnits: r,
|
|
166
166
|
poolUnits: t,
|
|
167
167
|
assetDepth: e
|
|
168
168
|
}) => {
|
|
169
|
-
const s = p(r), n = p(t), i = p(e), a = s.mul(i), c = n.mul(n).mul(2), u = n.mul(s).mul(2),
|
|
169
|
+
const s = p(r), n = p(t), i = p(e), a = s.mul(i), c = n.mul(n).mul(2), u = n.mul(s).mul(2), d = s.mul(s), l = a.mul(c.sub(u).add(d)), _ = n.mul(n).mul(n);
|
|
170
170
|
return l.div(_);
|
|
171
171
|
}, ce = ({
|
|
172
172
|
percent: r,
|
|
@@ -178,7 +178,7 @@ const Tt = "0x313ce567", it = async ({ chain: r, to: t }) => {
|
|
|
178
178
|
assetDepth: t,
|
|
179
179
|
liquidityUnits: e,
|
|
180
180
|
poolUnits: s
|
|
181
|
-
}) => xt({ assetDepth: t, liquidityUnits: e, poolUnits: s }).mul(r), p = (r) => b.fromBigInt(BigInt(r),
|
|
181
|
+
}) => xt({ assetDepth: t, liquidityUnits: e, poolUnits: s }).mul(r), p = (r) => b.fromBigInt(BigInt(r), h.THOR), qt = ({
|
|
182
182
|
liquidityUnits: r,
|
|
183
183
|
poolUnits: t,
|
|
184
184
|
runeDepth: e,
|
|
@@ -196,7 +196,7 @@ const Tt = "0x313ce567", it = async ({ chain: r, to: t }) => {
|
|
|
196
196
|
Object.entries(qt({ liquidityUnits: r, poolUnits: t, runeDepth: e, assetDepth: s })).map(
|
|
197
197
|
([i, a]) => [i, a.mul(n)]
|
|
198
198
|
)
|
|
199
|
-
),
|
|
199
|
+
), de = ({
|
|
200
200
|
runeDepth: r,
|
|
201
201
|
poolUnits: t,
|
|
202
202
|
assetDepth: e,
|
|
@@ -204,12 +204,12 @@ const Tt = "0x313ce567", it = async ({ chain: r, to: t }) => {
|
|
|
204
204
|
runeAmount: n,
|
|
205
205
|
assetAmount: i
|
|
206
206
|
}) => {
|
|
207
|
-
const a = new b({ value: r, decimal: 8 }), c = new b({ value: e, decimal: 8 }), u = new b({ value: t, decimal: 8 }),
|
|
207
|
+
const a = new b({ value: r, decimal: 8 }), c = new b({ value: e, decimal: 8 }), u = new b({ value: t, decimal: 8 }), d = new b({ value: n, decimal: 8 }), l = new b({ value: i, decimal: 8 }), _ = d.mul(c), N = l.mul(a), mt = d.mul(l), pt = a.mul(c), ft = u.mul(_.add(N.add(mt.mul(2)))), _t = _.add(N.add(pt.mul(2))), Q = ft.div(_t), j = p(s).add(Q);
|
|
208
208
|
if (Q.getBaseValue("number") === 0)
|
|
209
|
-
return
|
|
210
|
-
const gt = u.add(
|
|
211
|
-
return
|
|
212
|
-
},
|
|
209
|
+
return j.div(u).getBaseValue("number");
|
|
210
|
+
const gt = u.add(j);
|
|
211
|
+
return j.div(gt).getBaseValue("number");
|
|
212
|
+
}, he = ({
|
|
213
213
|
runeAmount: r,
|
|
214
214
|
assetAmount: t,
|
|
215
215
|
runeDepth: e,
|
|
@@ -217,8 +217,8 @@ const Tt = "0x313ce567", it = async ({ chain: r, to: t }) => {
|
|
|
217
217
|
}) => {
|
|
218
218
|
if (r === "0" || t === "0" || e === "0" || s === "0")
|
|
219
219
|
return 0;
|
|
220
|
-
const n = p(e), i = p(s), a = p(t), c = p(r), u = a.mul(n).sub(i.mul(c)),
|
|
221
|
-
return Math.abs(u.div(
|
|
220
|
+
const n = p(e), i = p(s), a = p(t), c = p(r), u = a.mul(n).sub(i.mul(c)), d = i.mul(c).add(n.mul(i));
|
|
221
|
+
return Math.abs(u.div(d).getBaseValue("number"));
|
|
222
222
|
}, kt = ({
|
|
223
223
|
symbol: r,
|
|
224
224
|
ticker: t,
|
|
@@ -243,8 +243,8 @@ const Tt = "0x313ce567", it = async ({ chain: r, to: t }) => {
|
|
|
243
243
|
return i ? `${r}:${e}/${s}::t:0` : `${r}:${e}.${s}:${n || ""}:t:0`;
|
|
244
244
|
}
|
|
245
245
|
case g.WITHDRAW: {
|
|
246
|
-
const { chain: e, ticker: s, symbol: n, basisPoints: i, targetAssetString: a, singleSide: c } = t, u = !c && a ? `:${a}` : "",
|
|
247
|
-
return `${r}:${e}${c ? "/" : "."}${
|
|
246
|
+
const { chain: e, ticker: s, symbol: n, basisPoints: i, targetAssetString: a, singleSide: c } = t, u = !c && a ? `:${a}` : "", d = kt({ chain: e, symbol: n, ticker: s });
|
|
247
|
+
return `${r}:${e}${c ? "/" : "."}${d}:${i}${u}`;
|
|
248
248
|
}
|
|
249
249
|
case g.OPEN_LOAN:
|
|
250
250
|
case g.CLOSE_LOAN: {
|
|
@@ -285,7 +285,7 @@ class X extends Error {
|
|
|
285
285
|
}), this.name = "HTTPError", this.response = t, this.request = e, this.options = s;
|
|
286
286
|
}
|
|
287
287
|
}
|
|
288
|
-
class
|
|
288
|
+
class ot extends Error {
|
|
289
289
|
constructor(t) {
|
|
290
290
|
super("Request timed out"), Object.defineProperty(this, "request", {
|
|
291
291
|
enumerable: !0,
|
|
@@ -295,12 +295,12 @@ class at extends Error {
|
|
|
295
295
|
}), this.name = "TimeoutError", this.request = t;
|
|
296
296
|
}
|
|
297
297
|
}
|
|
298
|
-
const
|
|
298
|
+
const x = (r) => r !== null && typeof r == "object", M = (...r) => {
|
|
299
299
|
for (const t of r)
|
|
300
|
-
if ((!
|
|
300
|
+
if ((!x(t) || Array.isArray(t)) && t !== void 0)
|
|
301
301
|
throw new TypeError("The `options` argument must be an object");
|
|
302
302
|
return J({}, ...r);
|
|
303
|
-
},
|
|
303
|
+
}, at = (r = {}, t = {}) => {
|
|
304
304
|
const e = new globalThis.Headers(r), s = t instanceof globalThis.Headers, n = new globalThis.Headers(t);
|
|
305
305
|
for (const [i, a] of n.entries())
|
|
306
306
|
s && a === "undefined" || a === void 0 ? e.delete(i) : e.set(i, a);
|
|
@@ -310,10 +310,10 @@ const q = (r) => r !== null && typeof r == "object", B = (...r) => {
|
|
|
310
310
|
for (const s of r)
|
|
311
311
|
if (Array.isArray(s))
|
|
312
312
|
Array.isArray(t) || (t = []), t = [...t, ...s];
|
|
313
|
-
else if (
|
|
313
|
+
else if (x(s)) {
|
|
314
314
|
for (let [n, i] of Object.entries(s))
|
|
315
|
-
|
|
316
|
-
|
|
315
|
+
x(i) && n in t && (i = J(t[n], i)), t = { ...t, [n]: i };
|
|
316
|
+
x(s.headers) && (e = at(e, s.headers), t.headers = e);
|
|
317
317
|
}
|
|
318
318
|
return t;
|
|
319
319
|
}, Vt = (() => {
|
|
@@ -327,13 +327,13 @@ const q = (r) => r !== null && typeof r == "object", B = (...r) => {
|
|
|
327
327
|
return r = !0, "half";
|
|
328
328
|
}
|
|
329
329
|
}).headers.has("Content-Type")), r && !t;
|
|
330
|
-
})(), Pt = typeof globalThis.AbortController == "function", Nt = typeof globalThis.ReadableStream == "function", jt = typeof globalThis.FormData == "function",
|
|
330
|
+
})(), Pt = typeof globalThis.AbortController == "function", Nt = typeof globalThis.ReadableStream == "function", jt = typeof globalThis.FormData == "function", ct = ["get", "post", "put", "patch", "head", "delete"], Ht = {
|
|
331
331
|
json: "application/json",
|
|
332
332
|
text: "text/*",
|
|
333
333
|
formData: "multipart/form-data",
|
|
334
334
|
arrayBuffer: "*/*",
|
|
335
335
|
blob: "*/*"
|
|
336
|
-
},
|
|
336
|
+
}, L = 2147483647, ut = Symbol("stop"), Lt = {
|
|
337
337
|
json: !0,
|
|
338
338
|
parseJson: !0,
|
|
339
339
|
searchParams: !0,
|
|
@@ -360,11 +360,11 @@ const q = (r) => r !== null && typeof r == "object", B = (...r) => {
|
|
|
360
360
|
window: !0,
|
|
361
361
|
dispatcher: !0,
|
|
362
362
|
duplex: !0
|
|
363
|
-
}, Ut = (r) =>
|
|
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 = {
|
|
364
364
|
limit: 2,
|
|
365
365
|
methods: Ft,
|
|
366
366
|
statusCodes: Wt,
|
|
367
|
-
afterStatusCodes:
|
|
367
|
+
afterStatusCodes: lt,
|
|
368
368
|
maxRetryAfter: Number.POSITIVE_INFINITY,
|
|
369
369
|
backoffLimit: Number.POSITIVE_INFINITY,
|
|
370
370
|
delay: (r) => 0.3 * 2 ** (r - 1) * 1e3
|
|
@@ -381,13 +381,13 @@ const q = (r) => r !== null && typeof r == "object", B = (...r) => {
|
|
|
381
381
|
return {
|
|
382
382
|
...Z,
|
|
383
383
|
...r,
|
|
384
|
-
afterStatusCodes:
|
|
384
|
+
afterStatusCodes: lt
|
|
385
385
|
};
|
|
386
386
|
};
|
|
387
387
|
async function Yt(r, t, e, s) {
|
|
388
388
|
return new Promise((n, i) => {
|
|
389
389
|
const a = setTimeout(() => {
|
|
390
|
-
e && e.abort(), i(new
|
|
390
|
+
e && e.abort(), i(new ot(r));
|
|
391
391
|
}, s.timeout);
|
|
392
392
|
s.fetch(r, t).then(n).catch(i).then(() => {
|
|
393
393
|
clearTimeout(a);
|
|
@@ -411,21 +411,21 @@ const Jt = (r, t) => {
|
|
|
411
411
|
!(s in Dt) && !(s in Lt) && !(s in r) && (e[s] = t[s]);
|
|
412
412
|
return e;
|
|
413
413
|
};
|
|
414
|
-
class
|
|
414
|
+
class k {
|
|
415
415
|
static create(t, e) {
|
|
416
|
-
const s = new
|
|
417
|
-
if (typeof s._options.timeout == "number" && s._options.timeout >
|
|
418
|
-
throw new RangeError(`The \`timeout\` option cannot be greater than ${
|
|
416
|
+
const s = new k(t, e), n = async () => {
|
|
417
|
+
if (typeof s._options.timeout == "number" && s._options.timeout > L)
|
|
418
|
+
throw new RangeError(`The \`timeout\` option cannot be greater than ${L}`);
|
|
419
419
|
await Promise.resolve();
|
|
420
420
|
let c = await s._fetch();
|
|
421
421
|
for (const u of s._options.hooks.afterResponse) {
|
|
422
|
-
const
|
|
423
|
-
|
|
422
|
+
const d = await u(s.request, s._options, s._decorateResponse(c.clone()));
|
|
423
|
+
d instanceof globalThis.Response && (c = d);
|
|
424
424
|
}
|
|
425
425
|
if (s._decorateResponse(c), !c.ok && s._options.throwHttpErrors) {
|
|
426
426
|
let u = new X(c, s.request, s._options);
|
|
427
|
-
for (const
|
|
428
|
-
u = await
|
|
427
|
+
for (const d of s._options.hooks.beforeError)
|
|
428
|
+
u = await d(u);
|
|
429
429
|
throw u;
|
|
430
430
|
}
|
|
431
431
|
if (s._options.onDownloadProgress) {
|
|
@@ -482,7 +482,7 @@ class V {
|
|
|
482
482
|
// TODO: credentials can be removed when the spec change is implemented in all browsers. Context: https://www.chromestatus.com/feature/4539473312350208
|
|
483
483
|
credentials: this._input.credentials || "same-origin",
|
|
484
484
|
...e,
|
|
485
|
-
headers:
|
|
485
|
+
headers: at(this._input.headers, e.headers),
|
|
486
486
|
hooks: J({
|
|
487
487
|
beforeRequest: [],
|
|
488
488
|
beforeRetry: [],
|
|
@@ -519,7 +519,7 @@ class V {
|
|
|
519
519
|
this._options.json !== void 0 && (this._options.body = JSON.stringify(this._options.json), this.request.headers.set("content-type", this._options.headers.get("content-type") ?? "application/json"), this.request = new globalThis.Request(this.request, { body: this._options.body }));
|
|
520
520
|
}
|
|
521
521
|
_calculateRetryDelay(t) {
|
|
522
|
-
if (this._retryCount++, this._retryCount < this._options.retry.limit && !(t instanceof
|
|
522
|
+
if (this._retryCount++, this._retryCount < this._options.retry.limit && !(t instanceof ot)) {
|
|
523
523
|
if (t instanceof X) {
|
|
524
524
|
if (!this._options.retry.statusCodes.includes(t.response.status))
|
|
525
525
|
return 0;
|
|
@@ -543,7 +543,7 @@ class V {
|
|
|
543
543
|
try {
|
|
544
544
|
return await t();
|
|
545
545
|
} catch (e) {
|
|
546
|
-
const s = Math.min(this._calculateRetryDelay(e),
|
|
546
|
+
const s = Math.min(this._calculateRetryDelay(e), L);
|
|
547
547
|
if (s !== 0 && this._retryCount > 0) {
|
|
548
548
|
await zt(s, { signal: this._options.signal });
|
|
549
549
|
for (const n of this._options.hooks.beforeRetry)
|
|
@@ -552,7 +552,7 @@ class V {
|
|
|
552
552
|
options: this._options,
|
|
553
553
|
error: e,
|
|
554
554
|
retryCount: this._retryCount
|
|
555
|
-
}) ===
|
|
555
|
+
}) === ut)
|
|
556
556
|
return;
|
|
557
557
|
return this._retry(t);
|
|
558
558
|
}
|
|
@@ -585,17 +585,17 @@ class V {
|
|
|
585
585
|
const a = t.body.getReader();
|
|
586
586
|
e && e({ percent: 0, transferredBytes: 0, totalBytes: s }, new Uint8Array());
|
|
587
587
|
async function c() {
|
|
588
|
-
const { done: u, value:
|
|
588
|
+
const { done: u, value: d } = await a.read();
|
|
589
589
|
if (u) {
|
|
590
590
|
i.close();
|
|
591
591
|
return;
|
|
592
592
|
}
|
|
593
593
|
if (e) {
|
|
594
|
-
n +=
|
|
594
|
+
n += d.byteLength;
|
|
595
595
|
const l = s === 0 ? 0 : n / s;
|
|
596
|
-
e({ percent: l, transferredBytes: n, totalBytes: s },
|
|
596
|
+
e({ percent: l, transferredBytes: n, totalBytes: s }, d);
|
|
597
597
|
}
|
|
598
|
-
i.enqueue(
|
|
598
|
+
i.enqueue(d), await c();
|
|
599
599
|
}
|
|
600
600
|
await c();
|
|
601
601
|
}
|
|
@@ -608,10 +608,10 @@ class V {
|
|
|
608
608
|
}
|
|
609
609
|
/*! MIT License © Sindre Sorhus */
|
|
610
610
|
const U = (r) => {
|
|
611
|
-
const t = (e, s) =>
|
|
612
|
-
for (const e of
|
|
613
|
-
t[e] = (s, n) =>
|
|
614
|
-
return t.create = (e) => U(
|
|
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) => U(M(e)), t.extend = (e) => U(M(r, e)), t.stop = ut, t;
|
|
615
615
|
}, Kt = U(), Qt = Kt, Xt = typeof window < "u" ? {} : { referrer: "https://sk.thorswap.net", referer: "https://sk.thorswap.net" }, tt = Qt.create({ headers: Xt }), Zt = {
|
|
616
616
|
get: (r, t) => tt.get(r, t).json(),
|
|
617
617
|
post: (r, t) => tt.post(r, t).json()
|
|
@@ -625,11 +625,11 @@ const U = (r) => {
|
|
|
625
625
|
throw new Error(
|
|
626
626
|
`Invalid identifier: ${r}. Expected format: <Chain>.<Ticker> or <Chain>.<Ticker>-<ContractAddress>`
|
|
627
627
|
);
|
|
628
|
-
},
|
|
629
|
-
function
|
|
628
|
+
}, C = 8, w = (r) => 10n ** BigInt(r), R = (r) => Math.log10(parseFloat(r.toString()));
|
|
629
|
+
function V({
|
|
630
630
|
value: r,
|
|
631
|
-
bigIntDecimal: t =
|
|
632
|
-
decimal: e =
|
|
631
|
+
bigIntDecimal: t = C,
|
|
632
|
+
decimal: e = C
|
|
633
633
|
}) {
|
|
634
634
|
const s = r < 0n;
|
|
635
635
|
let n = r.toString().substring(s ? 1 : 0);
|
|
@@ -642,24 +642,24 @@ function P({
|
|
|
642
642
|
""
|
|
643
643
|
);
|
|
644
644
|
}
|
|
645
|
-
var v,
|
|
645
|
+
var v, S, y, $, P, dt, O, F, E, W;
|
|
646
646
|
const K = class K {
|
|
647
647
|
constructor(t) {
|
|
648
|
-
|
|
649
|
-
|
|
650
|
-
|
|
651
|
-
|
|
652
|
-
|
|
648
|
+
T(this, v);
|
|
649
|
+
T(this, y);
|
|
650
|
+
T(this, P);
|
|
651
|
+
T(this, O);
|
|
652
|
+
T(this, E);
|
|
653
653
|
f(this, "decimalMultiplier", 10n ** 8n);
|
|
654
654
|
f(this, "bigIntValue", 0n);
|
|
655
655
|
f(this, "decimal");
|
|
656
656
|
const e = G(t), s = typeof t == "object";
|
|
657
|
-
this.decimal = s ? t.decimal : void 0, this.decimalMultiplier = s && "decimalMultiplier" in t ? t.decimalMultiplier : w(Math.max(st(
|
|
657
|
+
this.decimal = s ? t.decimal : void 0, this.decimalMultiplier = s && "decimalMultiplier" in t ? t.decimalMultiplier : w(Math.max(st(B(e)), this.decimal || 0)), m(this, P, dt).call(this, e);
|
|
658
658
|
}
|
|
659
659
|
static fromBigInt(t, e) {
|
|
660
660
|
return new K({
|
|
661
661
|
decimal: e,
|
|
662
|
-
value:
|
|
662
|
+
value: V({ value: t, bigIntDecimal: e, decimal: e })
|
|
663
663
|
});
|
|
664
664
|
}
|
|
665
665
|
static shiftDecimals({
|
|
@@ -676,37 +676,37 @@ const K = class K {
|
|
|
676
676
|
return new this.constructor({ decimal: this.decimal, value: t, identifier: this.toString() });
|
|
677
677
|
}
|
|
678
678
|
add(...t) {
|
|
679
|
-
return m(this, v,
|
|
679
|
+
return m(this, v, S).call(this, "add", ...t);
|
|
680
680
|
}
|
|
681
681
|
sub(...t) {
|
|
682
|
-
return m(this, v,
|
|
682
|
+
return m(this, v, S).call(this, "sub", ...t);
|
|
683
683
|
}
|
|
684
684
|
mul(...t) {
|
|
685
|
-
return m(this, v,
|
|
685
|
+
return m(this, v, S).call(this, "mul", ...t);
|
|
686
686
|
}
|
|
687
687
|
div(...t) {
|
|
688
|
-
return m(this, v,
|
|
688
|
+
return m(this, v, S).call(this, "div", ...t);
|
|
689
689
|
}
|
|
690
690
|
gt(t) {
|
|
691
|
-
return m(this, y,
|
|
691
|
+
return m(this, y, $).call(this, "gt", t);
|
|
692
692
|
}
|
|
693
693
|
gte(t) {
|
|
694
|
-
return m(this, y,
|
|
694
|
+
return m(this, y, $).call(this, "gte", t);
|
|
695
695
|
}
|
|
696
696
|
lt(t) {
|
|
697
|
-
return m(this, y,
|
|
697
|
+
return m(this, y, $).call(this, "lt", t);
|
|
698
698
|
}
|
|
699
699
|
lte(t) {
|
|
700
|
-
return m(this, y,
|
|
700
|
+
return m(this, y, $).call(this, "lte", t);
|
|
701
701
|
}
|
|
702
702
|
eqValue(t) {
|
|
703
|
-
return m(this, y,
|
|
703
|
+
return m(this, y, $).call(this, "eqValue", t);
|
|
704
704
|
}
|
|
705
705
|
// @ts-expect-error False positive
|
|
706
706
|
getValue(t) {
|
|
707
707
|
const e = this.formatBigIntToSafeValue(
|
|
708
708
|
this.bigIntValue,
|
|
709
|
-
this.decimal ||
|
|
709
|
+
this.decimal || R(this.decimalMultiplier)
|
|
710
710
|
);
|
|
711
711
|
switch (t) {
|
|
712
712
|
case "number":
|
|
@@ -719,7 +719,7 @@ const K = class K {
|
|
|
719
719
|
}
|
|
720
720
|
// @ts-expect-error
|
|
721
721
|
getBaseValue(t) {
|
|
722
|
-
const e = this.decimalMultiplier / w(this.decimal ||
|
|
722
|
+
const e = this.decimalMultiplier / w(this.decimal || h.THOR), s = this.bigIntValue / e;
|
|
723
723
|
switch (t) {
|
|
724
724
|
case "number":
|
|
725
725
|
return Number(s);
|
|
@@ -732,8 +732,8 @@ const K = class K {
|
|
|
732
732
|
getBigIntValue(t, e) {
|
|
733
733
|
if (!e && typeof t == "object")
|
|
734
734
|
return t.bigIntValue;
|
|
735
|
-
const s = G(t), n =
|
|
736
|
-
return n === "0" || n === "undefined" ? 0n : m(this,
|
|
735
|
+
const s = G(t), n = B(s);
|
|
736
|
+
return n === "0" || n === "undefined" ? 0n : m(this, E, W).call(this, n, e);
|
|
737
737
|
}
|
|
738
738
|
toSignificant(t = 6) {
|
|
739
739
|
const [e, s] = this.getValue("string").split("."), n = e || "", i = s || "";
|
|
@@ -775,25 +775,25 @@ const K = class K {
|
|
|
775
775
|
decimalSeparator: n = ".",
|
|
776
776
|
thousandSeparator: i = ","
|
|
777
777
|
} = {}) {
|
|
778
|
-
const a = this.getValue("number"), [c, u = ""] = a.toFixed(6).split("."),
|
|
778
|
+
const a = this.getValue("number"), [c, u = ""] = a.toFixed(6).split("."), d = c.replace(/\B(?=(\d{3})+(?!\d))/g, i), l = !c && !u ? "0.00" : c === "0" ? `${parseFloat(`0.${u}`)}`.replace(".", n) : `${d}${parseInt(u) ? `${n}${u.slice(0, s)}` : ""}`;
|
|
779
779
|
return `${e === "start" ? t : ""}${l}${e === "end" ? t : ""}`;
|
|
780
780
|
}
|
|
781
781
|
formatBigIntToSafeValue(t, e) {
|
|
782
|
-
const s = e || this.decimal ||
|
|
782
|
+
const s = e || this.decimal || C, n = Math.max(
|
|
783
783
|
s,
|
|
784
|
-
|
|
785
|
-
), i = t < 0n, a = t.toString().substring(i ? 1 : 0), c = n - (a.length - 1), u = c > 0 ? "0".repeat(c) + a : a,
|
|
784
|
+
R(this.decimalMultiplier)
|
|
785
|
+
), i = t < 0n, a = t.toString().substring(i ? 1 : 0), c = n - (a.length - 1), u = c > 0 ? "0".repeat(c) + a : a, d = u.length - n;
|
|
786
786
|
let l = u.slice(-n);
|
|
787
787
|
return parseInt(l[s]) >= 5 ? l = `${l.substring(0, s - 1)}${(parseInt(l[s - 1]) + 1).toString()}` : l = l.substring(0, s), `${i ? "-" : ""}${u.slice(
|
|
788
788
|
0,
|
|
789
|
-
|
|
789
|
+
d
|
|
790
790
|
)}.${l}`.replace(/\.?0*$/, "");
|
|
791
791
|
}
|
|
792
792
|
};
|
|
793
|
-
v = new WeakSet(),
|
|
794
|
-
const s = m(this,
|
|
795
|
-
(u,
|
|
796
|
-
const l = this.getBigIntValue(
|
|
793
|
+
v = new WeakSet(), S = function(t, ...e) {
|
|
794
|
+
const s = m(this, O, F).call(this, this, ...e), n = Math.max(s, R(this.decimalMultiplier)), i = w(n), a = e.reduce(
|
|
795
|
+
(u, d) => {
|
|
796
|
+
const l = this.getBigIntValue(d, n);
|
|
797
797
|
switch (t) {
|
|
798
798
|
case "add":
|
|
799
799
|
return u + l;
|
|
@@ -812,7 +812,7 @@ v = new WeakSet(), C = function(t, ...e) {
|
|
|
812
812
|
},
|
|
813
813
|
//normalize is to precision multiplier base
|
|
814
814
|
this.bigIntValue * i / this.decimalMultiplier
|
|
815
|
-
), c =
|
|
815
|
+
), c = V({
|
|
816
816
|
bigIntDecimal: n,
|
|
817
817
|
decimal: n,
|
|
818
818
|
value: a
|
|
@@ -823,8 +823,8 @@ v = new WeakSet(), C = function(t, ...e) {
|
|
|
823
823
|
value: c,
|
|
824
824
|
identifier: this.toString()
|
|
825
825
|
});
|
|
826
|
-
}, y = new WeakSet(),
|
|
827
|
-
const s = m(this,
|
|
826
|
+
}, y = new WeakSet(), $ = function(t, ...e) {
|
|
827
|
+
const s = m(this, O, F).call(this, this, ...e), n = this.getBigIntValue(e[0], s), i = this.getBigIntValue(this, s);
|
|
828
828
|
switch (t) {
|
|
829
829
|
case "gt":
|
|
830
830
|
return i > n;
|
|
@@ -837,49 +837,49 @@ v = new WeakSet(), C = function(t, ...e) {
|
|
|
837
837
|
case "eqValue":
|
|
838
838
|
return i === n;
|
|
839
839
|
}
|
|
840
|
-
},
|
|
841
|
-
const e =
|
|
842
|
-
this.bigIntValue = m(this,
|
|
843
|
-
},
|
|
844
|
-
const e = t.map((s) => typeof s == "object" ? s.decimal ||
|
|
845
|
-
return Math.max(...e,
|
|
846
|
-
},
|
|
847
|
-
const s = e ? w(e) : this.decimalMultiplier, n =
|
|
840
|
+
}, P = new WeakSet(), dt = function(t) {
|
|
841
|
+
const e = B(t) || "0";
|
|
842
|
+
this.bigIntValue = m(this, E, W).call(this, e);
|
|
843
|
+
}, O = new WeakSet(), F = function(...t) {
|
|
844
|
+
const e = t.map((s) => typeof s == "object" ? s.decimal || R(s.decimalMultiplier) : st(B(s))).filter(Boolean);
|
|
845
|
+
return Math.max(...e, C);
|
|
846
|
+
}, E = new WeakSet(), W = function(t, e) {
|
|
847
|
+
const s = e ? w(e) : this.decimalMultiplier, n = R(s), [i = "", a = ""] = t.split(".");
|
|
848
848
|
return BigInt(`${i}${a.padEnd(n, "0")}`);
|
|
849
849
|
};
|
|
850
|
-
let
|
|
850
|
+
let I = K;
|
|
851
851
|
const ee = Intl.NumberFormat("fullwide", {
|
|
852
852
|
useGrouping: !1,
|
|
853
853
|
maximumFractionDigits: 20
|
|
854
854
|
});
|
|
855
|
-
function
|
|
855
|
+
function B(r) {
|
|
856
856
|
const e = `${typeof r == "number" ? ee.format(r) : G(r)}`.replaceAll(",", ".").split(".");
|
|
857
857
|
return e.length > 1 ? `${e.slice(0, -1).join("")}.${e.at(-1)}` : e[0];
|
|
858
858
|
}
|
|
859
859
|
function st(r) {
|
|
860
860
|
var e;
|
|
861
861
|
const t = ((e = r.split(".")[1]) == null ? void 0 : e.length) || 0;
|
|
862
|
-
return Math.max(t,
|
|
862
|
+
return Math.max(t, C);
|
|
863
863
|
}
|
|
864
864
|
function G(r) {
|
|
865
865
|
return typeof r == "object" ? "getValue" in r ? r.getValue("string") : r.value : r;
|
|
866
866
|
}
|
|
867
|
-
const
|
|
867
|
+
const q = (r, t) => typeof r == "bigint" ? V({ value: r, bigIntDecimal: t, decimal: t }) : r;
|
|
868
868
|
let Y;
|
|
869
869
|
const rt = (r) => {
|
|
870
870
|
if (!Y)
|
|
871
871
|
throw new Error("Static assets not loaded, call await AssetValue.loadStaticAssets() first");
|
|
872
|
-
return Y.get(r.toUpperCase()) || { decimal:
|
|
873
|
-
},
|
|
872
|
+
return Y.get(r.toUpperCase()) || { decimal: h.THOR, identifier: "" };
|
|
873
|
+
}, D = async (r, t = 0) => {
|
|
874
874
|
te(r);
|
|
875
|
-
const e = await Ct(z(r)), s =
|
|
875
|
+
const e = await Ct(z(r)), s = q(t, e);
|
|
876
876
|
return new A({ decimal: e, value: s, identifier: r });
|
|
877
877
|
};
|
|
878
|
-
class A extends
|
|
878
|
+
class A extends I {
|
|
879
879
|
constructor(e) {
|
|
880
880
|
const s = "identifier" in e ? e.identifier : `${e.chain}.${e.symbol}`;
|
|
881
881
|
super(
|
|
882
|
-
e.value instanceof
|
|
882
|
+
e.value instanceof I ? e.value : { decimal: e.decimal, value: e.value }
|
|
883
883
|
);
|
|
884
884
|
f(this, "address");
|
|
885
885
|
f(this, "chain");
|
|
@@ -892,15 +892,8 @@ class A extends O {
|
|
|
892
892
|
const n = z(s);
|
|
893
893
|
this.type = Ot(n), this.chain = n.chain, this.ticker = n.ticker, this.symbol = n.symbol, this.address = n.address, this.isSynthetic = n.isSynthetic, this.isGasAsset = n.isGasAsset, this.tax = e.tax;
|
|
894
894
|
}
|
|
895
|
-
toString(
|
|
896
|
-
|
|
897
|
-
return e ? (
|
|
898
|
-
// ETH/THOR-0xa5f2211b9b8170f694421f2046281775e8468044 | USDT
|
|
899
|
-
s
|
|
900
|
-
) : (
|
|
901
|
-
// THOR.ETH/ETH | ETH.USDT-0x1234567890
|
|
902
|
-
`${this.chain}.${this.symbol}`
|
|
903
|
-
);
|
|
895
|
+
toString() {
|
|
896
|
+
return this.isSynthetic ? this.symbol : `${this.chain}.${this.symbol}`;
|
|
904
897
|
}
|
|
905
898
|
toUrl() {
|
|
906
899
|
return this.isSynthetic ? `${this.chain}.${this.symbol.replace("/", ".")}` : this.toString();
|
|
@@ -908,46 +901,47 @@ class A extends O {
|
|
|
908
901
|
eq({ chain: e, symbol: s }) {
|
|
909
902
|
return this.chain === e && this.symbol === s;
|
|
910
903
|
}
|
|
911
|
-
|
|
912
|
-
|
|
904
|
+
// THOR.RUNE
|
|
905
|
+
// THOR.ETH.ETH
|
|
906
|
+
// ETH.THOR-0x1234567890
|
|
907
|
+
static fromUrl(e, s = 0) {
|
|
908
|
+
const [n, i, a] = e.split(".");
|
|
909
|
+
if (!n || !i)
|
|
910
|
+
throw new Error("Invalid asset url");
|
|
911
|
+
const c = n === o.THORChain && a ? `${n}.${i}/${a}` : e;
|
|
912
|
+
return D(c, s);
|
|
913
|
+
}
|
|
914
|
+
static fromString(e, s = 0) {
|
|
915
|
+
return D(e, s);
|
|
913
916
|
}
|
|
914
917
|
static fromStringSync(e, s = 0) {
|
|
915
918
|
const { isSynthetic: n } = z(e), {
|
|
916
919
|
tax: i,
|
|
917
920
|
decimal: a,
|
|
918
921
|
identifier: c
|
|
919
|
-
} = rt(e), u =
|
|
922
|
+
} = rt(e), u = q(s, a);
|
|
920
923
|
return c ? new A({ tax: i, decimal: a, identifier: c, value: u }) : n ? new A({ tax: i, decimal: 8, identifier: e, value: u }) : void 0;
|
|
921
924
|
}
|
|
922
|
-
static
|
|
923
|
-
return
|
|
925
|
+
static fromIdentifier(e, s = 0) {
|
|
926
|
+
return D(e, s);
|
|
924
927
|
}
|
|
925
928
|
static fromIdentifierSync(e, s = 0) {
|
|
926
|
-
const { decimal: n, identifier: i } = rt(e), a =
|
|
929
|
+
const { decimal: n, identifier: i } = rt(e), a = q(s, n);
|
|
927
930
|
return new A({ decimal: n, identifier: i, value: a });
|
|
928
931
|
}
|
|
929
932
|
static fromChainOrSignature(e, s = 0) {
|
|
930
|
-
const { decimal: n, identifier: i } = It(e), a =
|
|
933
|
+
const { decimal: n, identifier: i } = It(e), a = q(s, n);
|
|
931
934
|
return new A({ value: a, decimal: n, identifier: i });
|
|
932
935
|
}
|
|
933
|
-
static
|
|
936
|
+
static loadStaticAssets() {
|
|
934
937
|
return new Promise(
|
|
935
938
|
async (e, s) => {
|
|
936
939
|
try {
|
|
937
|
-
const
|
|
938
|
-
|
|
939
|
-
|
|
940
|
-
|
|
941
|
-
|
|
942
|
-
...a
|
|
943
|
-
} = await import("@swapkit/tokens");
|
|
944
|
-
Y = [i, ...Object.values(a)].reduce(
|
|
945
|
-
(u, { tokens: h }) => (h.forEach(({ identifier: l, chain: _, ...T }) => {
|
|
946
|
-
const j = "decimals" in T ? T.decimals : d[_];
|
|
947
|
-
u.set(l, { identifier: l, decimal: j });
|
|
948
|
-
}), u),
|
|
949
|
-
/* @__PURE__ */ new Map()
|
|
950
|
-
), e({ ok: !0 });
|
|
940
|
+
const n = await import("@swapkit/tokens");
|
|
941
|
+
Y = Object.values(n).reduce((a, { tokens: c }) => (c.forEach(({ identifier: u, chain: d, ...l }) => {
|
|
942
|
+
const _ = "decimals" in l ? l.decimals : h[d];
|
|
943
|
+
a.set(u, { identifier: u, decimal: _ });
|
|
944
|
+
}), a), /* @__PURE__ */ new Map()), e({ ok: !0 });
|
|
951
945
|
} catch (n) {
|
|
952
946
|
console.error(n), s({
|
|
953
947
|
ok: !1,
|
|
@@ -982,7 +976,7 @@ const ge = (r) => {
|
|
|
982
976
|
return {
|
|
983
977
|
address: u == null ? void 0 : u.toLowerCase(),
|
|
984
978
|
chain: i,
|
|
985
|
-
isGasAsset:
|
|
979
|
+
isGasAsset: it({ chain: i, symbol: a }),
|
|
986
980
|
isSynthetic: t,
|
|
987
981
|
symbol: (t ? `${e}/` : "") + (u ? `${c}-${(u == null ? void 0 : u.toLowerCase()) ?? ""}` : a),
|
|
988
982
|
ticker: c
|
|
@@ -1045,32 +1039,32 @@ const ge = (r) => {
|
|
|
1045
1039
|
*/
|
|
1046
1040
|
helpers_number_different_decimals: 99101
|
|
1047
1041
|
};
|
|
1048
|
-
class
|
|
1042
|
+
class ht extends Error {
|
|
1049
1043
|
constructor(t, e) {
|
|
1050
|
-
console.error(e, { stack: e == null ? void 0 : e.stack, message: e == null ? void 0 : e.message }), super(t, { cause: { code: se[t], message: t } }), Object.setPrototypeOf(this,
|
|
1044
|
+
console.error(e, { stack: e == null ? void 0 : e.stack, message: e == null ? void 0 : e.message }), super(t, { cause: { code: se[t], message: t } }), Object.setPrototypeOf(this, ht.prototype);
|
|
1051
1045
|
}
|
|
1052
1046
|
}
|
|
1053
|
-
class b extends
|
|
1047
|
+
class b extends I {
|
|
1054
1048
|
eq(t) {
|
|
1055
1049
|
return this.eqValue(t);
|
|
1056
1050
|
}
|
|
1057
1051
|
static fromBigInt(t, e) {
|
|
1058
1052
|
return new b({
|
|
1059
1053
|
decimal: e,
|
|
1060
|
-
value:
|
|
1054
|
+
value: V({ value: t, bigIntDecimal: e, decimal: e })
|
|
1061
1055
|
});
|
|
1062
1056
|
}
|
|
1063
1057
|
}
|
|
1064
1058
|
export {
|
|
1065
1059
|
A as AssetValue,
|
|
1066
|
-
|
|
1060
|
+
I as BigIntArithmetics,
|
|
1067
1061
|
Zt as RequestClient,
|
|
1068
|
-
|
|
1062
|
+
ht as SwapKitError,
|
|
1069
1063
|
b as SwapKitNumber,
|
|
1070
1064
|
oe as assetFromString,
|
|
1071
1065
|
_e as derivationPathToString,
|
|
1072
1066
|
ae as filterAssets,
|
|
1073
|
-
|
|
1067
|
+
V as formatBigIntToSafeValue,
|
|
1074
1068
|
ie as gasFeeMultiplier,
|
|
1075
1069
|
Ot as getAssetType,
|
|
1076
1070
|
xt as getAsymmetricAssetShare,
|
|
@@ -1079,13 +1073,13 @@ export {
|
|
|
1079
1073
|
ce as getAsymmetricRuneWithdrawAmount,
|
|
1080
1074
|
It as getCommonAssetInfo,
|
|
1081
1075
|
Ct as getDecimal,
|
|
1082
|
-
|
|
1083
|
-
|
|
1076
|
+
de as getEstimatedPoolShare,
|
|
1077
|
+
he as getLiquiditySlippage,
|
|
1084
1078
|
me as getMemoFor,
|
|
1085
1079
|
ge as getMinAmountByChain,
|
|
1086
1080
|
qt as getSymmetricPoolShare,
|
|
1087
1081
|
le as getSymmetricWithdraw,
|
|
1088
1082
|
pe as getTHORNameCost,
|
|
1089
|
-
|
|
1083
|
+
it as isGasAsset,
|
|
1090
1084
|
fe as validateTHORName
|
|
1091
1085
|
};
|
package/package.json
CHANGED
|
@@ -5,19 +5,19 @@
|
|
|
5
5
|
"ky": "1.1.3"
|
|
6
6
|
},
|
|
7
7
|
"devDependencies": {
|
|
8
|
-
"@vitest/coverage-istanbul": "0.
|
|
9
|
-
"vite": "
|
|
10
|
-
"vitest": "0.
|
|
11
|
-
"@internal/config": "0.0.0-rc.
|
|
12
|
-
"@swapkit/tokens": "1.0.0-rc.
|
|
13
|
-
"@swapkit/types": "1.0.0-rc.
|
|
8
|
+
"@vitest/coverage-istanbul": "1.0.1",
|
|
9
|
+
"vite": "5.0.6",
|
|
10
|
+
"vitest": "1.0.1",
|
|
11
|
+
"@internal/config": "0.0.0-rc.11",
|
|
12
|
+
"@swapkit/tokens": "1.0.0-rc.27",
|
|
13
|
+
"@swapkit/types": "1.0.0-rc.25"
|
|
14
14
|
},
|
|
15
15
|
"eslintConfig": {
|
|
16
16
|
"extends": "../../../internal/eslint-config"
|
|
17
17
|
},
|
|
18
18
|
"peerDependencies": {
|
|
19
|
-
"@swapkit/tokens": "1.0.0-rc.
|
|
20
|
-
"@swapkit/types": "1.0.0-rc.
|
|
19
|
+
"@swapkit/tokens": "1.0.0-rc.27",
|
|
20
|
+
"@swapkit/types": "1.0.0-rc.25"
|
|
21
21
|
},
|
|
22
22
|
"exports": {
|
|
23
23
|
".": {
|
|
@@ -42,7 +42,7 @@
|
|
|
42
42
|
"repository": "https://github.com/thorswap/SwapKit.git",
|
|
43
43
|
"type": "module",
|
|
44
44
|
"types": "./dist/index.d.ts",
|
|
45
|
-
"version": "1.0.0-rc.
|
|
45
|
+
"version": "1.0.0-rc.48",
|
|
46
46
|
"scripts": {
|
|
47
47
|
"build": "vite build",
|
|
48
48
|
"clean": "rm -rf dist vite.config.ts.* .turbo node_modules",
|
|
@@ -12,14 +12,10 @@ describe('AssetValue', () => {
|
|
|
12
12
|
chain: Chain.Avalanche,
|
|
13
13
|
symbol: 'USDC-0xb97ef9ef8734c71904d8002f8b6bc66dd9c48a6e',
|
|
14
14
|
});
|
|
15
|
-
expect(fakeAvaxUSDCAsset.toString(true)).toBe('USDC');
|
|
16
15
|
expect(fakeAvaxUSDCAsset.toString()).toBe(
|
|
17
16
|
'AVAX.USDC-0xb97ef9ef8734c71904d8002f8b6bc66dd9c48a6e',
|
|
18
17
|
);
|
|
19
18
|
|
|
20
|
-
const thor = AssetValue.fromChainOrSignature('ETH.THOR');
|
|
21
|
-
expect(thor.toString(true)).toBe('THOR');
|
|
22
|
-
|
|
23
19
|
const ethSynth = new AssetValue({
|
|
24
20
|
chain: Chain.THORChain,
|
|
25
21
|
symbol: 'ETH/ETH',
|
|
@@ -27,8 +23,7 @@ describe('AssetValue', () => {
|
|
|
27
23
|
value: 1234567890,
|
|
28
24
|
});
|
|
29
25
|
|
|
30
|
-
expect(ethSynth.toString()).toBe('
|
|
31
|
-
expect(ethSynth.toString(true)).toBe('ETH/ETH');
|
|
26
|
+
expect(ethSynth.toString()).toBe('ETH/ETH');
|
|
32
27
|
expect(ethSynth.mul(21.37).getValue('string')).toBe('26382715809.3');
|
|
33
28
|
|
|
34
29
|
const ethThorSynth = new AssetValue({
|
|
@@ -37,12 +32,7 @@ describe('AssetValue', () => {
|
|
|
37
32
|
decimal: 8,
|
|
38
33
|
value: 1234567890,
|
|
39
34
|
});
|
|
40
|
-
expect(ethThorSynth.toString()).toBe(
|
|
41
|
-
'THOR.ETH/THOR-0xa5f2211b9b8170f694421f2046281775e8468044',
|
|
42
|
-
);
|
|
43
|
-
expect(ethThorSynth.toString(true)).toBe(
|
|
44
|
-
'ETH/THOR-0xa5f2211b9b8170f694421f2046281775e8468044',
|
|
45
|
-
);
|
|
35
|
+
expect(ethThorSynth.toString()).toBe('ETH/THOR-0xa5f2211b9b8170f694421f2046281775e8468044');
|
|
46
36
|
|
|
47
37
|
const atomDerived = new AssetValue({
|
|
48
38
|
identifier: 'THOR.ATOM',
|
|
@@ -50,7 +40,6 @@ describe('AssetValue', () => {
|
|
|
50
40
|
value: 123456789,
|
|
51
41
|
});
|
|
52
42
|
|
|
53
|
-
expect(atomDerived.toString(true)).toBe('ATOM');
|
|
54
43
|
expect(atomDerived.toString()).toBe('THOR.ATOM');
|
|
55
44
|
});
|
|
56
45
|
});
|
|
@@ -144,7 +133,7 @@ describe('AssetValue', () => {
|
|
|
144
133
|
expect(thor.toString()).toBe('ETH.THOR-0xa5f2211b9b8170f694421f2046281775e8468044');
|
|
145
134
|
|
|
146
135
|
const ethSynth = await AssetValue.fromIdentifier('ETH/ETH');
|
|
147
|
-
expect(ethSynth.toString()).toBe('
|
|
136
|
+
expect(ethSynth.toString()).toBe('ETH/ETH');
|
|
148
137
|
});
|
|
149
138
|
});
|
|
150
139
|
|
|
@@ -169,23 +158,40 @@ describe('AssetValue', () => {
|
|
|
169
158
|
});
|
|
170
159
|
|
|
171
160
|
describe('fromString', () => {
|
|
172
|
-
test('creates AssetValue from string', () => {
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
expect
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
|
|
161
|
+
test('creates AssetValue from string', async () => {
|
|
162
|
+
const fakeAvaxAssetString = 'AVAX.ASDF-1234';
|
|
163
|
+
const fakeAvaxAsset = await AssetValue.fromString(fakeAvaxAssetString);
|
|
164
|
+
|
|
165
|
+
expect(fakeAvaxAsset).toEqual(
|
|
166
|
+
expect.objectContaining({
|
|
167
|
+
address: '1234',
|
|
168
|
+
chain: Chain.Avalanche,
|
|
169
|
+
decimal: 18,
|
|
170
|
+
isGasAsset: false,
|
|
171
|
+
isSynthetic: false,
|
|
172
|
+
symbol: 'ASDF-1234',
|
|
173
|
+
ticker: 'ASDF',
|
|
174
|
+
}),
|
|
175
|
+
);
|
|
176
|
+
});
|
|
177
|
+
});
|
|
178
|
+
|
|
179
|
+
describe('fromUrl', () => {
|
|
180
|
+
test('creates AssetValue from url like format', async () => {
|
|
181
|
+
const synthETHString = 'THOR.ETH.ETH';
|
|
182
|
+
const ethString = 'ETH.ETH';
|
|
183
|
+
const thorString = 'ETH.THOR-0xa5f2211b9b8170f694421f2046281775e8468044';
|
|
184
|
+
const synthThorString = 'THOR.ETH.THOR-0xa5f2211b9b8170f694421f2046281775e8468044';
|
|
185
|
+
|
|
186
|
+
const synthETH = await AssetValue.fromUrl(synthETHString);
|
|
187
|
+
const eth = await AssetValue.fromUrl(ethString);
|
|
188
|
+
const thor = await AssetValue.fromUrl(thorString);
|
|
189
|
+
const synthThor = await AssetValue.fromUrl(synthThorString);
|
|
190
|
+
|
|
191
|
+
expect(synthETH.toString()).toBe('ETH/ETH');
|
|
192
|
+
expect(eth.toString()).toBe('ETH.ETH');
|
|
193
|
+
expect(thor.toString()).toBe('ETH.THOR-0xa5f2211b9b8170f694421f2046281775e8468044');
|
|
194
|
+
expect(synthThor.toString()).toBe('ETH/THOR-0xa5f2211b9b8170f694421f2046281775e8468044');
|
|
189
195
|
});
|
|
190
196
|
});
|
|
191
197
|
|
|
@@ -103,14 +103,8 @@ export class AssetValue extends BigIntArithmetics {
|
|
|
103
103
|
this.tax = params.tax;
|
|
104
104
|
}
|
|
105
105
|
|
|
106
|
-
toString(
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
return short
|
|
110
|
-
? // ETH/THOR-0xa5f2211b9b8170f694421f2046281775e8468044 | USDT
|
|
111
|
-
shortFormat
|
|
112
|
-
: // THOR.ETH/ETH | ETH.USDT-0x1234567890
|
|
113
|
-
`${this.chain}.${this.symbol}`;
|
|
106
|
+
toString() {
|
|
107
|
+
return this.isSynthetic ? this.symbol : `${this.chain}.${this.symbol}`;
|
|
114
108
|
}
|
|
115
109
|
|
|
116
110
|
toUrl() {
|
|
@@ -121,7 +115,20 @@ export class AssetValue extends BigIntArithmetics {
|
|
|
121
115
|
return this.chain === chain && this.symbol === symbol;
|
|
122
116
|
}
|
|
123
117
|
|
|
124
|
-
|
|
118
|
+
// THOR.RUNE
|
|
119
|
+
// THOR.ETH.ETH
|
|
120
|
+
// ETH.THOR-0x1234567890
|
|
121
|
+
static fromUrl(urlAsset: string, value: NumberPrimitives = 0) {
|
|
122
|
+
const [chain, ticker, symbol] = urlAsset.split('.');
|
|
123
|
+
if (!chain || !ticker) throw new Error('Invalid asset url');
|
|
124
|
+
|
|
125
|
+
const assetString =
|
|
126
|
+
chain === Chain.THORChain && symbol ? `${chain}.${ticker}/${symbol}` : urlAsset;
|
|
127
|
+
|
|
128
|
+
return createAssetValue(assetString, value);
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
static fromString(assetString: string, value: NumberPrimitives = 0) {
|
|
125
132
|
return createAssetValue(assetString, value);
|
|
126
133
|
}
|
|
127
134
|
|
|
@@ -144,7 +151,7 @@ export class AssetValue extends BigIntArithmetics {
|
|
|
144
151
|
return asset;
|
|
145
152
|
}
|
|
146
153
|
|
|
147
|
-
static
|
|
154
|
+
static fromIdentifier(
|
|
148
155
|
assetString: `${Chain}.${string}` | `${Chain}/${string}` | `${Chain}.${string}-${string}`,
|
|
149
156
|
value: NumberPrimitives = 0,
|
|
150
157
|
) {
|
|
@@ -165,29 +172,20 @@ export class AssetValue extends BigIntArithmetics {
|
|
|
165
172
|
return new AssetValue({ value: parsedValue, decimal, identifier });
|
|
166
173
|
}
|
|
167
174
|
|
|
168
|
-
static
|
|
175
|
+
static loadStaticAssets() {
|
|
169
176
|
return new Promise<{ ok: true } | { ok: false; message: string; error: any }>(
|
|
170
177
|
async (resolve, reject) => {
|
|
171
178
|
try {
|
|
172
|
-
const
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
const decimal = 'decimals' in rest ? rest.decimals : BaseDecimal[chain as Chain];
|
|
183
|
-
|
|
184
|
-
acc.set(identifier as TokenNames, { identifier, decimal });
|
|
185
|
-
});
|
|
186
|
-
|
|
187
|
-
return acc;
|
|
188
|
-
},
|
|
189
|
-
new Map<TokenNames, { decimal: number; identifier: string }>(),
|
|
190
|
-
);
|
|
179
|
+
const tokenPackages = await import('@swapkit/tokens');
|
|
180
|
+
const tokensMap = Object.values(tokenPackages).reduce((acc, { tokens }) => {
|
|
181
|
+
tokens.forEach(({ identifier, chain, ...rest }) => {
|
|
182
|
+
const decimal = 'decimals' in rest ? rest.decimals : BaseDecimal[chain as Chain];
|
|
183
|
+
|
|
184
|
+
acc.set(identifier as TokenNames, { identifier, decimal });
|
|
185
|
+
});
|
|
186
|
+
|
|
187
|
+
return acc;
|
|
188
|
+
}, new Map<TokenNames, { decimal: number; identifier: string }>());
|
|
191
189
|
|
|
192
190
|
staticTokensMap = tokensMap;
|
|
193
191
|
|