@swapkit/helpers 1.0.0-rc.14 → 1.0.0-rc.15
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.cjs +1 -1
- package/dist/index.es.js +87 -87
- package/package.json +1 -1
- package/src/modules/__tests__/assetValue.test.ts +1 -1
- package/src/modules/assetValue.ts +14 -7
package/dist/index.cjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";var Te=Object.create;var H=Object.defineProperty;var Se=Object.getOwnPropertyDescriptor;var ve=Object.getOwnPropertyNames;var Re=Object.getPrototypeOf,Ie=Object.prototype.hasOwnProperty;var $e=(s,e,t)=>e in s?H(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t;var Be=(s,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of ve(e))!Ie.call(s,n)&&n!==t&&H(s,n,{get:()=>e[n],enumerable:!(r=Se(e,n))||r.enumerable});return s};var Ee=(s,e,t)=>(t=s!=null?Te(Re(s)):{},Be(e||!s||!s.__esModule?H(t,"default",{value:s,enumerable:!0}):t,s));var p=(s,e,t)=>($e(s,typeof e!="symbol"?e+"":e,t),t),Oe=(s,e,t)=>{if(!e.has(s))throw TypeError("Cannot "+t)};var _=(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 m=(s,e,t)=>(Oe(s,e,"access private method"),t);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const i=require("@swapkit/types"),Me="0x313ce567",ne=async({chain:s,to:e})=>{try{const{result:t}=await ge.post(i.ChainToRPC[s],{headers:{accept:"*/*","cache-control":"no-cache"},body:JSON.stringify({id:44,jsonrpc:"2.0",method:"eth_call",params:[{to:e.toLowerCase(),data:Me},"latest"]})});return parseInt(BigInt(t).toString())}catch(t){return console.error(t),i.BaseDecimal[s]}},Ve=async s=>{if(s===i.Chain.Ethereum)return i.BaseDecimal.ETH;const[,e]=s.split("-");return e!=null&&e.startsWith("0x")?ne({chain:i.Chain.Ethereum,to:e}):i.BaseDecimal.ETH},ke=async s=>{const[,e]=s.split("-");return e!=null&&e.startsWith("0x")?ne({chain:i.Chain.Avalanche,to:e.toLowerCase()}):i.BaseDecimal.AVAX},qe=async s=>(s===i.Chain.BinanceSmartChain,i.BaseDecimal.BSC),z=async({chain:s,symbol:e})=>{switch(s){case i.Chain.Ethereum:return Ve(e);case i.Chain.Avalanche:return ke(e);case i.Chain.BinanceSmartChain:return qe(e);default:return i.BaseDecimal[s]}},Pe={[i.FeeOption.Average]:1.2,[i.FeeOption.Fast]:1.5,[i.FeeOption.Fastest]:2},ie=({chain:s,symbol:e})=>{switch(s){case i.Chain.Bitcoin:case i.Chain.BitcoinCash:case i.Chain.Litecoin:case i.Chain.Dogecoin:case i.Chain.Binance:case i.Chain.Ethereum:case i.Chain.Avalanche:return e===s;case i.Chain.Arbitrum:case i.Chain.Optimism:return e==="ETH";case i.Chain.Maya:return e==="CACAO";case i.Chain.Kujira:return e==="KUJI";case i.Chain.Cosmos:return e==="ATOM";case i.Chain.Polygon:return e==="MATIC";case i.Chain.BinanceSmartChain:return e==="BNB";case i.Chain.THORChain:return e==="RUNE"}},ae=s=>{switch(s){case"ETH.THOR":return{identifier:"ETH.THOR-0xa5f2211b9b8170f694421f2046281775e8468044",decimal:18};case"ETH.vTHOR":return{identifier:"ETH.vTHOR-0x815c23eca83261b6ec689b60cc4a58b54bc24d8d",decimal:18};case i.Chain.Cosmos:return{identifier:"GAIA.ATOM",decimal:i.BaseDecimal[s]};case i.Chain.THORChain:return{identifier:"THOR.RUNE",decimal:i.BaseDecimal[s]};case i.Chain.BinanceSmartChain:return{identifier:"BSC.BNB",decimal:i.BaseDecimal[s]};case i.Chain.Maya:return{identifier:"MAYA.CACAO",decimal:i.BaseDecimal.MAYA};case"MAYA.MAYA":return{identifier:"MAYA.MAYA",decimal:4};case i.Chain.Kujira:case i.Chain.Arbitrum:case i.Chain.Optimism:case i.Chain.BitcoinCash:case i.Chain.Litecoin:case i.Chain.Dogecoin:case i.Chain.Binance:case i.Chain.Avalanche:case i.Chain.Polygon:case i.Chain.Bitcoin:case i.Chain.Ethereum:return{identifier:`${s}.${s}`,decimal:i.BaseDecimal[s]}}},oe=({chain:s,symbol:e})=>{if(e.includes("/"))return"Synth";switch(s){case i.Chain.Bitcoin:case i.Chain.BitcoinCash:case i.Chain.Dogecoin:case i.Chain.Litecoin:case i.Chain.Maya:case i.Chain.THORChain:return"Native";case i.Chain.Cosmos:return e==="ATOM"?"Native":i.Chain.Cosmos;case i.Chain.Kujira:return e===i.Chain.Kujira?"Native":i.Chain.Kujira;case i.Chain.Binance:return e===i.Chain.Binance?"Native":"BEP2";case i.Chain.BinanceSmartChain:return e===i.Chain.Binance?"Native":"BEP20";case i.Chain.Ethereum:return e===i.Chain.Ethereum?"Native":"ERC20";case i.Chain.Avalanche:return e===i.Chain.Avalanche?"Native":i.Chain.Avalanche;case i.Chain.Polygon:return e===i.Chain.Polygon?"Native":"POLYGON";case i.Chain.Arbitrum:return[i.Chain.Ethereum,i.Chain.Arbitrum].includes(e)?"Native":"ARBITRUM";case i.Chain.Optimism:return[i.Chain.Ethereum,i.Chain.Optimism].includes(e)?"Native":"OPTIMISM"}},xe=s=>{var o;const[e,...t]=s.split("."),r=s.includes("/"),n=t.join("."),a=(o=n==null?void 0:n.split("-"))==null?void 0:o[0];return{chain:e,symbol:n,ticker:a,synth:r}},De=new RegExp(/(.)\1{6}|\.ORG|\.NET|\.FINANCE|\.COM|WWW|HTTP|\\\\|\/\/|[\s$%:[\]]/,"gmi"),Ne=s=>s.filter(e=>!De.test(e.toString())&&!e.toString().includes("undefined")),ce=({liquidityUnits:s,poolUnits:e,runeDepth:t})=>{const r=d(s),n=d(e),a=d(t),o=r.mul(a),c=n.mul(n).mul(2),u=n.mul(r).mul(2),l=r.mul(r),h=n.mul(n).mul(n);return o.mul(c.sub(u).add(l)).div(h)},ue=({liquidityUnits:s,poolUnits:e,assetDepth:t})=>{const r=d(s),n=d(e),a=d(t),o=r.mul(a),c=n.mul(n).mul(2),u=n.mul(r).mul(2),l=r.mul(r),h=o.mul(c.sub(u).add(l)),g=n.mul(n).mul(n);return h.div(g)},He=({percent:s,runeDepth:e,liquidityUnits:t,poolUnits:r})=>ce({runeDepth:e,liquidityUnits:t,poolUnits:r}).mul(s),je=({percent:s,assetDepth:e,liquidityUnits:t,poolUnits:r})=>ue({assetDepth:e,liquidityUnits:t,poolUnits:r}).mul(s),d=s=>new x({value:s,decimal:i.BaseDecimal.THOR}),le=({liquidityUnits:s,poolUnits:e,runeDepth:t,assetDepth:r})=>({assetAmount:d(r).mul(s).div(e),runeAmount:d(t).mul(s).div(e)}),Le=({liquidityUnits:s,poolUnits:e,runeDepth:t,assetDepth:r,percent:n})=>Object.fromEntries(Object.entries(le({liquidityUnits:s,poolUnits:e,runeDepth:t,assetDepth:r})).map(([a,o])=>[a,o.mul(n)])),Fe=({runeDepth:s,poolUnits:e,assetDepth:t,liquidityUnits:r,runeAmount:n,assetAmount:a})=>{const o=d(s),c=d(t),u=d(e),l=d(n),h=d(a),g=l.mul(c),C=h.mul(o),D=l.mul(h),ye=o.mul(c),Ce=u.mul(g.add(C.add(D.mul(2)))),we=g.add(C.add(ye.mul(2))),X=Ce.div(we),N=d(r).add(X);if(X.baseValueNumber===0)return N.div(u).baseValueNumber;const Ae=u.add(N);return N.div(Ae).baseValueNumber},Ue=({runeAmount:s,assetAmount:e,runeDepth:t,assetDepth:r})=>{const n=d(t),a=d(r),o=d(e),c=d(s),u=o.mul(n).sub(a.mul(c)),l=a.mul(c).add(n.mul(a));return Math.abs(u.div(l).baseValueNumber)},We=({symbol:s,ticker:e,chain:t})=>t==="ETH"&&e!=="ETH"?`${e}-${s.slice(-3)}`:s,Ge=(s,e)=>{switch(s){case i.MemoType.LEAVE:case i.MemoType.BOND:{const{address:t}=e;return`${s}:${t}`}case i.MemoType.UNBOND:{const{address:t,unbondAmount:r}=e;return`${s}:${t}:${r*10**8}`}case i.MemoType.THORNAME_REGISTER:{const{name:t,chain:r,address:n,owner:a}=e;return`${s}:${t}:${r}:${n}${a?`:${a}`:""}`}case i.MemoType.DEPOSIT:{const{chain:t,symbol:r,address:n,singleSide:a}=e;return a?`${s}:${t}/${r}::t:0`:`${s}:${t}.${r}:${n||""}:t:0`}case i.MemoType.WITHDRAW:{const{chain:t,ticker:r,symbol:n,basisPoints:a,targetAssetString:o,singleSide:c}=e,u=!c&&o?`:${o}`:"",l=We({chain:t,symbol:n,ticker:r});return`${s}:${t}${c?"/":"."}${l}:${a}${u}`}case i.MemoType.OPEN_LOAN:case i.MemoType.CLOSE_LOAN:{const{asset:t,address:r}=e;return`${s}:${t}:${r}`}default:return""}},Ke=s=>{if(s<0)throw new Error("Invalid number of year");return 10+s},Ye=s=>{if(s.length>30)return!1;const e=/^[a-zA-Z0-9+_-]+$/g;return!!s.match(e)},ze=([s,e,t,r,n])=>`${s}'/${e}'/${t}'/${r}${typeof n!="number"?"":`/${n}`}`;class Z extends Error{constructor(e,t,r){const n=e.status||e.status===0?e.status:"",a=e.statusText||"",o=`${n} ${a}`.trim(),c=o?`status code ${o}`:"an unknown error";super(`Request failed with ${c}`),Object.defineProperty(this,"response",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"request",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"options",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.name="HTTPError",this.response=e,this.request=t,this.options=r}}class he extends Error{constructor(e){super("Request timed out"),Object.defineProperty(this,"request",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.name="TimeoutError",this.request=e}}const O=s=>s!==null&&typeof s=="object",E=(...s)=>{for(const e of s)if((!O(e)||Array.isArray(e))&&e!==void 0)throw new TypeError("The `options` argument must be an object");return J({},...s)},de=(s={},e={})=>{const t=new globalThis.Headers(s),r=e instanceof globalThis.Headers,n=new globalThis.Headers(e);for(const[a,o]of n.entries())r&&o==="undefined"||o===void 0?t.delete(a):t.set(a,o);return t},J=(...s)=>{let e={},t={};for(const r of s)if(Array.isArray(r))Array.isArray(e)||(e=[]),e=[...e,...r];else if(O(r)){for(let[n,a]of Object.entries(r))O(a)&&n in e&&(a=J(e[n],a)),e={...e,[n]:a};O(r.headers)&&(t=de(t,r.headers),e.headers=t)}return e},Je=(()=>{let s=!1,e=!1;const t=typeof globalThis.ReadableStream=="function",r=typeof globalThis.Request=="function";return t&&r&&(e=new globalThis.Request("https://empty.invalid",{body:new globalThis.ReadableStream,method:"POST",get duplex(){return s=!0,"half"}}).headers.has("Content-Type")),s&&!e})(),Qe=typeof globalThis.AbortController=="function",Xe=typeof globalThis.ReadableStream=="function",Ze=typeof globalThis.FormData=="function",me=["get","post","put","patch","head","delete"],et={json:"application/json",text:"text/*",formData:"multipart/form-data",arrayBuffer:"*/*",blob:"*/*"},j=2147483647,pe=Symbol("stop"),tt={json:!0,parseJson:!0,searchParams:!0,prefixUrl:!0,retry:!0,timeout:!0,hooks:!0,throwHttpErrors:!0,onDownloadProgress:!0,fetch:!0},rt={method:!0,headers:!0,body:!0,mode:!0,credentials:!0,cache:!0,redirect:!0,referrer:!0,referrerPolicy:!0,integrity:!0,keepalive:!0,signal:!0,window:!0,dispatcher:!0,duplex:!0},st=s=>me.includes(s)?s.toUpperCase():s,nt=["get","put","head","delete","options","trace"],it=[408,413,429,500,502,503,504],fe=[413,429,503],ee={limit:2,methods:nt,statusCodes:it,afterStatusCodes:fe,maxRetryAfter:Number.POSITIVE_INFINITY,backoffLimit:Number.POSITIVE_INFINITY,delay:s=>.3*2**(s-1)*1e3},at=(s={})=>{if(typeof s=="number")return{...ee,limit:s};if(s.methods&&!Array.isArray(s.methods))throw new Error("retry.methods must be an array");if(s.statusCodes&&!Array.isArray(s.statusCodes))throw new Error("retry.statusCodes must be an array");return{...ee,...s,afterStatusCodes:fe}};async function ot(s,e,t,r){return new Promise((n,a)=>{const o=setTimeout(()=>{t&&t.abort(),a(new he(s))},r.timeout);r.fetch(s,e).then(n).catch(a).then(()=>{clearTimeout(o)})})}async function ct(s,{signal:e}){return new Promise((t,r)=>{e&&(e.throwIfAborted(),e.addEventListener("abort",n,{once:!0}));function n(){clearTimeout(a),r(e.reason)}const a=setTimeout(()=>{e==null||e.removeEventListener("abort",n),t()},s)})}const ut=(s,e)=>{const t={};for(const r in e)!(r in rt)&&!(r in tt)&&!(r in s)&&(t[r]=e[r]);return t};class V{static create(e,t){const r=new V(e,t),n=async()=>{if(typeof r._options.timeout=="number"&&r._options.timeout>j)throw new RangeError(`The \`timeout\` option cannot be greater than ${j}`);await Promise.resolve();let c=await r._fetch();for(const u of r._options.hooks.afterResponse){const l=await u(r.request,r._options,r._decorateResponse(c.clone()));l instanceof globalThis.Response&&(c=l)}if(r._decorateResponse(c),!c.ok&&r._options.throwHttpErrors){let u=new Z(c,r.request,r._options);for(const l of r._options.hooks.beforeError)u=await l(u);throw u}if(r._options.onDownloadProgress){if(typeof r._options.onDownloadProgress!="function")throw new TypeError("The `onDownloadProgress` option must be a function");if(!Xe)throw new Error("Streams are not supported in your environment. `ReadableStream` is missing.");return r._stream(c.clone(),r._options.onDownloadProgress)}return c},o=r._options.retry.methods.includes(r.request.method.toLowerCase())?r._retry(n):n();for(const[c,u]of Object.entries(et))o[c]=async()=>{r.request.headers.set("accept",r.request.headers.get("accept")||u);const h=(await o).clone();if(c==="json"){if(h.status===204||(await h.clone().arrayBuffer()).byteLength===0)return"";if(t.parseJson)return t.parseJson(await h.text())}return h[c]()};return o}constructor(e,t={}){if(Object.defineProperty(this,"request",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"abortController",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_retryCount",{enumerable:!0,configurable:!0,writable:!0,value:0}),Object.defineProperty(this,"_input",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_options",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this._input=e,this._options={credentials:this._input.credentials||"same-origin",...t,headers:de(this._input.headers,t.headers),hooks:J({beforeRequest:[],beforeRetry:[],beforeError:[],afterResponse:[]},t.hooks),method:st(t.method??this._input.method),prefixUrl:String(t.prefixUrl||""),retry:at(t.retry),throwHttpErrors:t.throwHttpErrors!==!1,timeout:t.timeout??1e4,fetch:t.fetch??globalThis.fetch.bind(globalThis)},typeof this._input!="string"&&!(this._input instanceof URL||this._input instanceof globalThis.Request))throw new TypeError("`input` must be a string, URL, or Request");if(this._options.prefixUrl&&typeof this._input=="string"){if(this._input.startsWith("/"))throw new Error("`input` must not begin with a slash when using `prefixUrl`");this._options.prefixUrl.endsWith("/")||(this._options.prefixUrl+="/"),this._input=this._options.prefixUrl+this._input}if(Qe){if(this.abortController=new globalThis.AbortController,this._options.signal){const r=this._options.signal;this._options.signal.addEventListener("abort",()=>{this.abortController.abort(r.reason)})}this._options.signal=this.abortController.signal}if(Je&&(this._options.duplex="half"),this.request=new globalThis.Request(this._input,this._options),this._options.searchParams){const n="?"+(typeof this._options.searchParams=="string"?this._options.searchParams.replace(/^\?/,""):new URLSearchParams(this._options.searchParams).toString()),a=this.request.url.replace(/(?:\?.*?)?(?=#|$)/,n);(Ze&&this._options.body instanceof globalThis.FormData||this._options.body instanceof URLSearchParams)&&!(this._options.headers&&this._options.headers["content-type"])&&this.request.headers.delete("content-type"),this.request=new globalThis.Request(new globalThis.Request(a,{...this.request}),this._options)}this._options.json!==void 0&&(this._options.body=JSON.stringify(this._options.json),this.request.headers.set("content-type",this._options.headers.get("content-type")??"application/json"),this.request=new globalThis.Request(this.request,{body:this._options.body}))}_calculateRetryDelay(e){if(this._retryCount++,this._retryCount<this._options.retry.limit&&!(e instanceof he)){if(e instanceof Z){if(!this._options.retry.statusCodes.includes(e.response.status))return 0;const r=e.response.headers.get("Retry-After");if(r&&this._options.retry.afterStatusCodes.includes(e.response.status)){let n=Number(r);return Number.isNaN(n)?n=Date.parse(r)-Date.now():n*=1e3,this._options.retry.maxRetryAfter!==void 0&&n>this._options.retry.maxRetryAfter?0:n}if(e.response.status===413)return 0}const t=this._options.retry.delay(this._retryCount);return Math.min(this._options.retry.backoffLimit,t)}return 0}_decorateResponse(e){return this._options.parseJson&&(e.json=async()=>this._options.parseJson(await e.text())),e}async _retry(e){try{return await e()}catch(t){const r=Math.min(this._calculateRetryDelay(t),j);if(r!==0&&this._retryCount>0){await ct(r,{signal:this._options.signal});for(const n of this._options.hooks.beforeRetry)if(await n({request:this.request,options:this._options,error:t,retryCount:this._retryCount})===pe)return;return this._retry(e)}throw t}}async _fetch(){for(const t of this._options.hooks.beforeRequest){const r=await t(this.request,this._options);if(r instanceof Request){this.request=r;break}if(r instanceof Response)return r}const e=ut(this.request,this._options);return this._options.timeout===!1?this._options.fetch(this.request.clone(),e):ot(this.request.clone(),e,this.abortController,this._options)}_stream(e,t){const r=Number(e.headers.get("content-length"))||0;let n=0;return e.status===204?(t&&t({percent:1,totalBytes:r,transferredBytes:n},new Uint8Array),new globalThis.Response(null,{status:e.status,statusText:e.statusText,headers:e.headers})):new globalThis.Response(new globalThis.ReadableStream({async start(a){const o=e.body.getReader();t&&t({percent:0,transferredBytes:0,totalBytes:r},new Uint8Array);async function c(){const{done:u,value:l}=await o.read();if(u){a.close();return}if(t){n+=l.byteLength;const h=r===0?0:n/r;t({percent:h,transferredBytes:n,totalBytes:r},l)}a.enqueue(l),await c()}await c()}}),{status:e.status,statusText:e.statusText,headers:e.headers})}}/*! MIT License © Sindre Sorhus */const U=s=>{const e=(t,r)=>V.create(t,E(s,r));for(const t of me)e[t]=(r,n)=>V.create(r,E(s,n,{method:t}));return e.create=t=>U(E(t)),e.extend=t=>U(E(s,t)),e.stop=pe,e},lt=U(),ht=lt,te=ht.create({headers:{referrer:"https://sk.thorswap.net",referer:"https://sk.thorswap.net","Content-Type":"application/json"}}),ge={get:(s,e)=>te.get(s,e).json(),post:(s,e)=>te.post(s,e).json()},re=Object.values(i.Chain),dt=(s="")=>{const e=s.toUpperCase(),[t]=e.split(".");if(re.includes(t))return!0;const[r]=e.split("/");if(re.includes(r))return!0;throw new Error(`Invalid identifier: ${s}. Expected format: <Chain>.<Ticker> or <Chain>.<Ticker>-<ContractAddress>`)},R=8,w=s=>10n**BigInt(s),T=s=>Math.log10(parseFloat(s.toString()));function I({value:s,bigIntDecimal:e=R,decimal:t=R}){const r=s<0n;let n=s.toString().substring(r?1:0);const a=t-(n.length-1);a>0&&(n="0".repeat(a)+n);const o=n.length-t;let c=n.slice(-t);return parseInt(c[e])>=5?c=`${c.substring(0,e-1)}${(parseInt(c[e-1])+1).toString()}`:c=c.substring(0,e),`${r?"-":""}${n.slice(0,o)}.${c}`.replace(/\.?0*$/,"")}var b,S,k,_e,q,be,$,W,y,v,B,G;const P=class P{constructor(e){_(this,b);_(this,k);_(this,q);_(this,$);_(this,y);_(this,B);p(this,"decimalMultiplier",10n**8n);p(this,"bigIntValue",0n);p(this,"decimal");const t=L(e);this.decimal=typeof e=="object"?e.decimal:void 0,this.decimalMultiplier=w(Math.max(m(this,B,G).call(this,m(this,y,v).call(this,t)),this.decimal||0)),m(this,k,_e).call(this,t)}static fromBigInt(e,t){return new P({decimal:t,value:I({value:e,bigIntDecimal:t,decimal:t})})}static shiftDecimals({value:e,from:t,to:r}){return this.fromBigInt(new P(e).bigIntValue*w(r)/w(t),r)}get baseValue(){return this.getBaseValue("string")}get baseValueNumber(){return this.getBaseValue("number")}get baseValueBigInt(){return this.getBaseValue("bigint")}set(e){return new this.constructor({decimal:this.decimal,value:e,identifier:this.toString()})}add(...e){return m(this,b,S).call(this,"add",...e)}sub(...e){return m(this,b,S).call(this,"sub",...e)}mul(...e){return m(this,b,S).call(this,"mul",...e)}div(...e){return m(this,b,S).call(this,"div",...e)}gt(e){return this.bigIntValue>this.getBigIntValue(e)}gte(e){return this.bigIntValue>=this.getBigIntValue(e)}lt(e){return this.bigIntValue<this.getBigIntValue(e)}lte(e){return this.bigIntValue<=this.getBigIntValue(e)}eqValue(e){return this.bigIntValue===this.getBigIntValue(e)}getValue(e){const t=this.formatBigIntToSafeValue(this.bigIntValue,this.decimal||T(this.decimalMultiplier));switch(e){case"number":return Number(t);case"string":return t;default:return this.bigIntValue*BigInt(this.decimal||8n)/this.decimalMultiplier}}getBaseValue(e){const t=this.decimalMultiplier/w(this.decimal||i.BaseDecimal.THOR),r=this.bigIntValue/t;switch(e){case"number":return Number(r);case"string":return r.toString();default:return r}}getBigIntValue(e,t){if(!t&&typeof e=="object")return e.bigIntValue;const r=L(e),n=m(this,y,v).call(this,r);return n==="0"||n==="undefined"?0n:m(this,$,W).call(this,n,t)}formatBigIntToSafeValue(e,t){const r=t||this.decimal||R,n=Math.max(r,T(this.decimalMultiplier)),a=e<0n,o=e.toString().substring(a?1:0),c=n-(o.length-1),u=c>0?"0".repeat(c)+o:o,l=u.length-n;let h=u.slice(-n);return parseInt(h[r])>=5?h=`${h.substring(0,r-1)}${(parseInt(h[r-1])+1).toString()}`:h=h.substring(0,r),`${a?"-":""}${u.slice(0,l)}.${h}`.replace(/\.?0*$/,"")}toSignificant(e=6){const[t,r]=this.getValue("string").split("."),n=t||"",a=r||"",o=parseInt(n)?n.length+a.length:a.length;if(o<=e)return this.getValue("string");if(n.length>=e)return n.slice(0,e).padEnd(n.length,"0");if(parseInt(n))return`${n}.${a.slice(0,e-n.length)}`.padEnd(o-e,"0");const c=parseInt(a),u=`${c}`.slice(0,e);return`0.${u.padStart(a.length-`${c}`.length+u.length,"0")}`}toFixed(e=6){const[t,r]=this.getValue("string").split("."),n=t||"",a=r||"";if(parseInt(n))return`${n}.${a.slice(0,e)}`.padEnd(e,"0");const o=parseInt(a),c=`${o}`.slice(0,e);return`0.${c.padStart(a.length-`${o}`.length+c.length,"0")}`}toAbbreviation(e=2){const t=this.getValue("number"),r=["","K","M","B","T","Q","Qi","S"],n=Math.floor(Math.log10(Math.abs(t))/3),a=r[n];if(!a)return this.getValue("string");const o=10**(n*3);return`${(t/o).toFixed(e)}${a}`}};b=new WeakSet,S=function(e,...t){const r=m(this,q,be).call(this,this,...t),n=w(r),a=t.reduce((c,u)=>{const l=this.getBigIntValue(u,r);switch(e){case"add":return c+l;case"sub":return c-l;case"mul":return c*l/n;case"div":{if(l===0n)throw new RangeError("Division by zero");return c*n/l}default:return c}},this.bigIntValue*n/this.decimalMultiplier),o=I({bigIntDecimal:r,decimal:Math.max(r,T(this.decimalMultiplier)),value:a});return new this.constructor({decimal:this.decimal,value:o,identifier:this.toString()})},k=new WeakSet,_e=function(e){const t=m(this,y,v).call(this,e)||"0";this.bigIntValue=m(this,$,W).call(this,t)},q=new WeakSet,be=function(...e){const t=e.map(r=>typeof r=="object"?r.decimal||T(r.decimalMultiplier):m(this,B,G).call(this,m(this,y,v).call(this,r))).filter(Boolean);return Math.max(...t,R)},$=new WeakSet,W=function(e,t){const r=t?w(t):this.decimalMultiplier,n=T(r),[a="",o=""]=e.split(".");return BigInt(`${a}${o.padEnd(n,"0")}`)},y=new WeakSet,v=function(e){const r=`${typeof e=="number"?Number(e).toLocaleString("fullwide",{useGrouping:!1,maximumFractionDigits:20}):L(e)}`.replaceAll(",",".").split(".");return r.length>1?`${r.slice(0,-1).join("")}.${r.at(-1)}`:r[0]},B=new WeakSet,G=function(e){var r;const t=((r=e.split(".")[1])==null?void 0:r.length)||0;return Math.max(t,R)};let A=P;function L(s){return typeof s=="object"?"getValue"in s?s.getValue("string"):s.value:s}const M=(s,e)=>typeof s=="bigint"?I({value:s,bigIntDecimal:e,decimal:e}):s;let K;const F=s=>{if(!K)throw new Error("Static assets not loaded, call await AssetValue.loadStaticAssets() first");return K.get(s.toUpperCase())||{decimal:i.BaseDecimal.THOR,identifier:""}},se=async(s,e=0)=>{dt(s);const t=await z(Y(s)),r=M(e,t);return new f({decimal:t,value:r,identifier:s})};class f extends A{constructor(t){super(t.value instanceof A?t.value:{decimal:t.decimal,value:t.value});p(this,"address");p(this,"chain");p(this,"isSynthetic",!1);p(this,"isGasAsset",!1);p(this,"symbol");p(this,"ticker");p(this,"type");const r="identifier"in t?t.identifier:`${t.chain}.${t.symbol}`,n=Y(r);this.type=oe(n),this.chain=n.chain,this.ticker=n.ticker,this.symbol=n.symbol,this.address=n.address,this.isSynthetic=n.isSynthetic,this.isGasAsset=n.isGasAsset}get assetValue(){return`${this.getValue("string")} ${this.ticker}`}toString(t=!1){const r=this.isSynthetic?this.ticker:`${this.chain}.${this.ticker}`;return t?r:`${this.chain}.${this.symbol}`}eq({chain:t,symbol:r}){return this.chain===t&&this.symbol===r}static async fromString(t,r=0){return se(t,r)}static fromStringSync(t,r=0){const{decimal:n,identifier:a}=F(t),o=M(r,n);return a?new f({decimal:n,identifier:a,value:o}):void 0}static async fromIdentifier(t,r=0){return se(t,r)}static fromIdentifierSync(t,r=0){const{decimal:n,identifier:a}=F(t),o=M(r,n);return new f({decimal:n,identifier:a,value:o})}static fromChainOrSignature(t,r=0){const{decimal:n,identifier:a}=ae(t),o=M(r,n);return new f({value:o,decimal:n,identifier:a})}static async fromTCQuote(t,r=0){const n=await z(Y(t)),a=this.shiftDecimals({value:r,from:i.BaseDecimal.THOR,to:n});return new f({value:a,identifier:t,decimal:n})}static fromTCQuoteStatic(t,r=0){const n=F(t),a=this.shiftDecimals({value:r,from:i.BaseDecimal.THOR,to:n.decimal});return new f({...n,value:a})}static async loadStaticAssets(){return new Promise(async(t,r)=>{try{const{ThorchainList:n,NativeList:a,...o}=await import("@swapkit/tokens");K=[a,...Object.values(o)].reduce((u,{tokens:l})=>(l.forEach(({identifier:h,chain:g,...C})=>{const D="decimals"in C?C.decimals:i.BaseDecimal[g];u.set(h,{identifier:h,decimal:D})}),u),new Map),t({ok:!0})}catch(n){console.error(n),r({ok:!1,error:n,message:"Couldn't load static assets. Ensure you have installed @swapkit/tokens package"})}})}}const mt=s=>{const e=f.fromChainOrSignature(s);switch(s){case i.Chain.Bitcoin:case i.Chain.Litecoin:case i.Chain.BitcoinCash:return e.add(10001);case i.Chain.Dogecoin:return e.add(100000001);case i.Chain.Avalanche:case i.Chain.Ethereum:return e.add(10*10**9);case i.Chain.THORChain:case i.Chain.Maya:return e.add(0);default:return e.add(1)}},Y=s=>{const e=s.slice(0,14).includes("/"),t=s.includes(".")?s:`${i.Chain.THORChain}.${s}`,[r,n]=t.split("."),[a,o]=n.split("-");return{address:o==null?void 0:o.toLowerCase(),chain:r,isGasAsset:ie({chain:r,symbol:n}),isSynthetic:e,symbol:o?`${a}-${(o==null?void 0:o.toLowerCase())??""}`:n,ticker:e?n:a}},pt={core_wallet_connection_not_found:10001,core_estimated_max_spendable_chain_not_supported:10002,core_extend_error:10003,core_inbound_data_not_found:10004,core_approve_asset_address_or_from_not_found:10005,core_chain_halted:10099,core_wallet_xdefi_not_installed:10101,core_wallet_evmwallet_not_installed:10102,core_wallet_walletconnect_not_installed:10103,core_wallet_keystore_not_installed:10104,core_wallet_ledger_not_installed:10105,core_wallet_trezor_not_installed:10106,core_wallet_keplr_not_installed:10107,core_wallet_okx_not_installed:10108,core_swap_invalid_params:10200,core_swap_route_not_complete:10201,core_swap_asset_not_recognized:10202,core_swap_contract_not_found:10203,core_swap_route_transaction_not_found:10204,core_swap_contract_not_supported:10205,core_swap_transaction_error:10206,core_swap_quote_mode_not_supported:10207,core_transaction_deposit_error:10301,core_transaction_create_liquidity_rune_error:10302,core_transaction_create_liquidity_asset_error:10303,core_transaction_create_liquidity_invalid_params:10304,core_transaction_add_liquidity_invalid_params:10305,core_transaction_add_liquidity_no_rune_address:10306,core_transaction_add_liquidity_rune_error:10307,core_transaction_add_liquidity_asset_error:10308,core_transaction_withdraw_error:10309,core_transaction_deposit_to_pool_error:10310,core_transaction_deposit_insufficient_funds_error:10311,core_transaction_deposit_gas_error:10312,core_transaction_deposit_server_error:10313,wallet_ledger_connection_error:20001,helpers_number_different_decimals:99101};class Q extends Error{constructor(e,t){console.error(t),super(e,{cause:{code:pt[e],message:e}}),Object.setPrototypeOf(this,Q.prototype)}}class x extends A{eq(e){return this.eqValue(e)}static fromBigInt(e,t){return new x({decimal:t,value:I({value:e,bigIntDecimal:t,decimal:t})})}}exports.AssetValue=f;exports.BigIntArithmetics=A;exports.RequestClient=ge;exports.SwapKitError=Q;exports.SwapKitNumber=x;exports.assetFromString=xe;exports.derivationPathToString=ze;exports.filterAssets=Ne;exports.formatBigIntToSafeValue=I;exports.gasFeeMultiplier=Pe;exports.getAssetType=oe;exports.getAsymmetricAssetShare=ue;exports.getAsymmetricAssetWithdrawAmount=je;exports.getAsymmetricRuneShare=ce;exports.getAsymmetricRuneWithdrawAmount=He;exports.getCommonAssetInfo=ae;exports.getDecimal=z;exports.getEstimatedPoolShare=Fe;exports.getLiquiditySlippage=Ue;exports.getMemoFor=Ge;exports.getMinAmountByChain=mt;exports.getSymmetricPoolShare=le;exports.getSymmetricWithdraw=Le;exports.getTHORNameCost=Ke;exports.isGasAsset=ie;exports.validateTHORName=Ye;
|
|
1
|
+
"use strict";var Tt=Object.create;var j=Object.defineProperty;var St=Object.getOwnPropertyDescriptor;var vt=Object.getOwnPropertyNames;var Rt=Object.getPrototypeOf,$t=Object.prototype.hasOwnProperty;var It=(r,t,e)=>t in r?j(r,t,{enumerable:!0,configurable:!0,writable:!0,value:e}):r[t]=e;var Bt=(r,t,e,s)=>{if(t&&typeof t=="object"||typeof t=="function")for(let n of vt(t))!$t.call(r,n)&&n!==e&&j(r,n,{get:()=>t[n],enumerable:!(s=St(t,n))||s.enumerable});return r};var Et=(r,t,e)=>(e=r!=null?Tt(Rt(r)):{},Bt(t||!r||!r.__esModule?j(e,"default",{value:r,enumerable:!0}):e,r));var p=(r,t,e)=>(It(r,typeof t!="symbol"?t+"":t,e),e),Ot=(r,t,e)=>{if(!t.has(r))throw TypeError("Cannot "+e)};var _=(r,t,e)=>{if(t.has(r))throw TypeError("Cannot add the same private member more than once");t instanceof WeakSet?t.add(r):t.set(r,e)};var m=(r,t,e)=>(Ot(r,t,"access private method"),e);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const i=require("@swapkit/types"),Mt="0x313ce567",nt=async({chain:r,to:t})=>{try{const{result:e}=await gt.post(i.ChainToRPC[r],{headers:{accept:"*/*","cache-control":"no-cache"},body:JSON.stringify({id:44,jsonrpc:"2.0",method:"eth_call",params:[{to:t.toLowerCase(),data:Mt},"latest"]})});return parseInt(BigInt(e).toString())}catch(e){return console.error(e),i.BaseDecimal[r]}},Vt=async r=>{if(r===i.Chain.Ethereum)return i.BaseDecimal.ETH;const[,t]=r.split("-");return t!=null&&t.startsWith("0x")?nt({chain:i.Chain.Ethereum,to:t}):i.BaseDecimal.ETH},qt=async r=>{const[,t]=r.split("-");return t!=null&&t.startsWith("0x")?nt({chain:i.Chain.Avalanche,to:t.toLowerCase()}):i.BaseDecimal.AVAX},kt=async r=>(r===i.Chain.BinanceSmartChain,i.BaseDecimal.BSC),z=async({chain:r,symbol:t})=>{switch(r){case i.Chain.Ethereum:return Vt(t);case i.Chain.Avalanche:return qt(t);case i.Chain.BinanceSmartChain:return kt(t);default:return i.BaseDecimal[r]}},Pt={[i.FeeOption.Average]:1.2,[i.FeeOption.Fast]:1.5,[i.FeeOption.Fastest]:2},it=({chain:r,symbol:t})=>{switch(r){case i.Chain.Bitcoin:case i.Chain.BitcoinCash:case i.Chain.Litecoin:case i.Chain.Dogecoin:case i.Chain.Binance:case i.Chain.Ethereum:case i.Chain.Avalanche:return t===r;case i.Chain.Arbitrum:case i.Chain.Optimism:return t==="ETH";case i.Chain.Maya:return t==="CACAO";case i.Chain.Kujira:return t==="KUJI";case i.Chain.Cosmos:return t==="ATOM";case i.Chain.Polygon:return t==="MATIC";case i.Chain.BinanceSmartChain:return t==="BNB";case i.Chain.THORChain:return t==="RUNE"}},at=r=>{switch(r){case"ETH.THOR":return{identifier:"ETH.THOR-0xa5f2211b9b8170f694421f2046281775e8468044",decimal:18};case"ETH.vTHOR":return{identifier:"ETH.vTHOR-0x815c23eca83261b6ec689b60cc4a58b54bc24d8d",decimal:18};case i.Chain.Cosmos:return{identifier:"GAIA.ATOM",decimal:i.BaseDecimal[r]};case i.Chain.THORChain:return{identifier:"THOR.RUNE",decimal:i.BaseDecimal[r]};case i.Chain.BinanceSmartChain:return{identifier:"BSC.BNB",decimal:i.BaseDecimal[r]};case i.Chain.Maya:return{identifier:"MAYA.CACAO",decimal:i.BaseDecimal.MAYA};case"MAYA.MAYA":return{identifier:"MAYA.MAYA",decimal:4};case i.Chain.Kujira:case i.Chain.Arbitrum:case i.Chain.Optimism:case i.Chain.BitcoinCash:case i.Chain.Litecoin:case i.Chain.Dogecoin:case i.Chain.Binance:case i.Chain.Avalanche:case i.Chain.Polygon:case i.Chain.Bitcoin:case i.Chain.Ethereum:return{identifier:`${r}.${r}`,decimal:i.BaseDecimal[r]}}},ot=({chain:r,symbol:t})=>{if(t.includes("/"))return"Synth";switch(r){case i.Chain.Bitcoin:case i.Chain.BitcoinCash:case i.Chain.Dogecoin:case i.Chain.Litecoin:case i.Chain.Maya:case i.Chain.THORChain:return"Native";case i.Chain.Cosmos:return t==="ATOM"?"Native":i.Chain.Cosmos;case i.Chain.Kujira:return t===i.Chain.Kujira?"Native":i.Chain.Kujira;case i.Chain.Binance:return t===i.Chain.Binance?"Native":"BEP2";case i.Chain.BinanceSmartChain:return t===i.Chain.Binance?"Native":"BEP20";case i.Chain.Ethereum:return t===i.Chain.Ethereum?"Native":"ERC20";case i.Chain.Avalanche:return t===i.Chain.Avalanche?"Native":i.Chain.Avalanche;case i.Chain.Polygon:return t===i.Chain.Polygon?"Native":"POLYGON";case i.Chain.Arbitrum:return[i.Chain.Ethereum,i.Chain.Arbitrum].includes(t)?"Native":"ARBITRUM";case i.Chain.Optimism:return[i.Chain.Ethereum,i.Chain.Optimism].includes(t)?"Native":"OPTIMISM"}},xt=r=>{var o;const[t,...e]=r.split("."),s=r.includes("/"),n=e.join("."),a=(o=n==null?void 0:n.split("-"))==null?void 0:o[0];return{chain:t,symbol:n,ticker:a,synth:s}},Dt=new RegExp(/(.)\1{6}|\.ORG|\.NET|\.FINANCE|\.COM|WWW|HTTP|\\\\|\/\/|[\s$%:[\]]/,"gmi"),Nt=r=>r.filter(t=>!Dt.test(t.toString())&&!t.toString().includes("undefined")),ct=({liquidityUnits:r,poolUnits:t,runeDepth:e})=>{const s=d(r),n=d(t),a=d(e),o=s.mul(a),c=n.mul(n).mul(2),u=n.mul(s).mul(2),l=s.mul(s),h=n.mul(n).mul(n);return o.mul(c.sub(u).add(l)).div(h)},ut=({liquidityUnits:r,poolUnits:t,assetDepth:e})=>{const s=d(r),n=d(t),a=d(e),o=s.mul(a),c=n.mul(n).mul(2),u=n.mul(s).mul(2),l=s.mul(s),h=o.mul(c.sub(u).add(l)),g=n.mul(n).mul(n);return h.div(g)},Ht=({percent:r,runeDepth:t,liquidityUnits:e,poolUnits:s})=>ct({runeDepth:t,liquidityUnits:e,poolUnits:s}).mul(r),jt=({percent:r,assetDepth:t,liquidityUnits:e,poolUnits:s})=>ut({assetDepth:t,liquidityUnits:e,poolUnits:s}).mul(r),d=r=>new D({value:r,decimal:i.BaseDecimal.THOR}),lt=({liquidityUnits:r,poolUnits:t,runeDepth:e,assetDepth:s})=>({assetAmount:d(s).mul(r).div(t),runeAmount:d(e).mul(r).div(t)}),Lt=({liquidityUnits:r,poolUnits:t,runeDepth:e,assetDepth:s,percent:n})=>Object.fromEntries(Object.entries(lt({liquidityUnits:r,poolUnits:t,runeDepth:e,assetDepth:s})).map(([a,o])=>[a,o.mul(n)])),Ft=({runeDepth:r,poolUnits:t,assetDepth:e,liquidityUnits:s,runeAmount:n,assetAmount:a})=>{const o=d(r),c=d(e),u=d(t),l=d(n),h=d(a),g=l.mul(c),C=h.mul(o),N=l.mul(h),yt=o.mul(c),Ct=u.mul(g.add(C.add(N.mul(2)))),wt=g.add(C.add(yt.mul(2))),X=Ct.div(wt),H=d(s).add(X);if(X.baseValueNumber===0)return H.div(u).baseValueNumber;const At=u.add(H);return H.div(At).baseValueNumber},Ut=({runeAmount:r,assetAmount:t,runeDepth:e,assetDepth:s})=>{const n=d(e),a=d(s),o=d(t),c=d(r),u=o.mul(n).sub(a.mul(c)),l=a.mul(c).add(n.mul(a));return Math.abs(u.div(l).baseValueNumber)},Wt=({symbol:r,ticker:t,chain:e})=>e==="ETH"&&t!=="ETH"?`${t}-${r.slice(-3)}`:r,Gt=(r,t)=>{switch(r){case i.MemoType.LEAVE:case i.MemoType.BOND:{const{address:e}=t;return`${r}:${e}`}case i.MemoType.UNBOND:{const{address:e,unbondAmount:s}=t;return`${r}:${e}:${s*10**8}`}case i.MemoType.THORNAME_REGISTER:{const{name:e,chain:s,address:n,owner:a}=t;return`${r}:${e}:${s}:${n}${a?`:${a}`:""}`}case i.MemoType.DEPOSIT:{const{chain:e,symbol:s,address:n,singleSide:a}=t;return a?`${r}:${e}/${s}::t:0`:`${r}:${e}.${s}:${n||""}:t:0`}case i.MemoType.WITHDRAW:{const{chain:e,ticker:s,symbol:n,basisPoints:a,targetAssetString:o,singleSide:c}=t,u=!c&&o?`:${o}`:"",l=Wt({chain:e,symbol:n,ticker:s});return`${r}:${e}${c?"/":"."}${l}:${a}${u}`}case i.MemoType.OPEN_LOAN:case i.MemoType.CLOSE_LOAN:{const{asset:e,address:s}=t;return`${r}:${e}:${s}`}default:return""}},Kt=r=>{if(r<0)throw new Error("Invalid number of year");return 10+r},Yt=r=>{if(r.length>30)return!1;const t=/^[a-zA-Z0-9+_-]+$/g;return!!r.match(t)},zt=([r,t,e,s,n])=>`${r}'/${t}'/${e}'/${s}${typeof n!="number"?"":`/${n}`}`;class Z extends Error{constructor(t,e,s){const n=t.status||t.status===0?t.status:"",a=t.statusText||"",o=`${n} ${a}`.trim(),c=o?`status code ${o}`:"an unknown error";super(`Request failed with ${c}`),Object.defineProperty(this,"response",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"request",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"options",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.name="HTTPError",this.response=t,this.request=e,this.options=s}}class ht extends Error{constructor(t){super("Request timed out"),Object.defineProperty(this,"request",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.name="TimeoutError",this.request=t}}const O=r=>r!==null&&typeof r=="object",E=(...r)=>{for(const t of r)if((!O(t)||Array.isArray(t))&&t!==void 0)throw new TypeError("The `options` argument must be an object");return J({},...r)},dt=(r={},t={})=>{const e=new globalThis.Headers(r),s=t instanceof globalThis.Headers,n=new globalThis.Headers(t);for(const[a,o]of n.entries())s&&o==="undefined"||o===void 0?e.delete(a):e.set(a,o);return e},J=(...r)=>{let t={},e={};for(const s of r)if(Array.isArray(s))Array.isArray(t)||(t=[]),t=[...t,...s];else if(O(s)){for(let[n,a]of Object.entries(s))O(a)&&n in t&&(a=J(t[n],a)),t={...t,[n]:a};O(s.headers)&&(e=dt(e,s.headers),t.headers=e)}return t},Jt=(()=>{let r=!1,t=!1;const e=typeof globalThis.ReadableStream=="function",s=typeof globalThis.Request=="function";return e&&s&&(t=new globalThis.Request("https://empty.invalid",{body:new globalThis.ReadableStream,method:"POST",get duplex(){return r=!0,"half"}}).headers.has("Content-Type")),r&&!t})(),Qt=typeof globalThis.AbortController=="function",Xt=typeof globalThis.ReadableStream=="function",Zt=typeof globalThis.FormData=="function",mt=["get","post","put","patch","head","delete"],te={json:"application/json",text:"text/*",formData:"multipart/form-data",arrayBuffer:"*/*",blob:"*/*"},L=2147483647,pt=Symbol("stop"),ee={json:!0,parseJson:!0,searchParams:!0,prefixUrl:!0,retry:!0,timeout:!0,hooks:!0,throwHttpErrors:!0,onDownloadProgress:!0,fetch:!0},se={method:!0,headers:!0,body:!0,mode:!0,credentials:!0,cache:!0,redirect:!0,referrer:!0,referrerPolicy:!0,integrity:!0,keepalive:!0,signal:!0,window:!0,dispatcher:!0,duplex:!0},re=r=>mt.includes(r)?r.toUpperCase():r,ne=["get","put","head","delete","options","trace"],ie=[408,413,429,500,502,503,504],ft=[413,429,503],tt={limit:2,methods:ne,statusCodes:ie,afterStatusCodes:ft,maxRetryAfter:Number.POSITIVE_INFINITY,backoffLimit:Number.POSITIVE_INFINITY,delay:r=>.3*2**(r-1)*1e3},ae=(r={})=>{if(typeof r=="number")return{...tt,limit:r};if(r.methods&&!Array.isArray(r.methods))throw new Error("retry.methods must be an array");if(r.statusCodes&&!Array.isArray(r.statusCodes))throw new Error("retry.statusCodes must be an array");return{...tt,...r,afterStatusCodes:ft}};async function oe(r,t,e,s){return new Promise((n,a)=>{const o=setTimeout(()=>{e&&e.abort(),a(new ht(r))},s.timeout);s.fetch(r,t).then(n).catch(a).then(()=>{clearTimeout(o)})})}async function ce(r,{signal:t}){return new Promise((e,s)=>{t&&(t.throwIfAborted(),t.addEventListener("abort",n,{once:!0}));function n(){clearTimeout(a),s(t.reason)}const a=setTimeout(()=>{t==null||t.removeEventListener("abort",n),e()},r)})}const ue=(r,t)=>{const e={};for(const s in t)!(s in se)&&!(s in ee)&&!(s in r)&&(e[s]=t[s]);return e};class q{static create(t,e){const s=new q(t,e),n=async()=>{if(typeof s._options.timeout=="number"&&s._options.timeout>L)throw new RangeError(`The \`timeout\` option cannot be greater than ${L}`);await Promise.resolve();let c=await s._fetch();for(const u of s._options.hooks.afterResponse){const l=await u(s.request,s._options,s._decorateResponse(c.clone()));l instanceof globalThis.Response&&(c=l)}if(s._decorateResponse(c),!c.ok&&s._options.throwHttpErrors){let u=new Z(c,s.request,s._options);for(const l of s._options.hooks.beforeError)u=await l(u);throw u}if(s._options.onDownloadProgress){if(typeof s._options.onDownloadProgress!="function")throw new TypeError("The `onDownloadProgress` option must be a function");if(!Xt)throw new Error("Streams are not supported in your environment. `ReadableStream` is missing.");return s._stream(c.clone(),s._options.onDownloadProgress)}return c},o=s._options.retry.methods.includes(s.request.method.toLowerCase())?s._retry(n):n();for(const[c,u]of Object.entries(te))o[c]=async()=>{s.request.headers.set("accept",s.request.headers.get("accept")||u);const h=(await o).clone();if(c==="json"){if(h.status===204||(await h.clone().arrayBuffer()).byteLength===0)return"";if(e.parseJson)return e.parseJson(await h.text())}return h[c]()};return o}constructor(t,e={}){if(Object.defineProperty(this,"request",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"abortController",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_retryCount",{enumerable:!0,configurable:!0,writable:!0,value:0}),Object.defineProperty(this,"_input",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_options",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this._input=t,this._options={credentials:this._input.credentials||"same-origin",...e,headers:dt(this._input.headers,e.headers),hooks:J({beforeRequest:[],beforeRetry:[],beforeError:[],afterResponse:[]},e.hooks),method:re(e.method??this._input.method),prefixUrl:String(e.prefixUrl||""),retry:ae(e.retry),throwHttpErrors:e.throwHttpErrors!==!1,timeout:e.timeout??1e4,fetch:e.fetch??globalThis.fetch.bind(globalThis)},typeof this._input!="string"&&!(this._input instanceof URL||this._input instanceof globalThis.Request))throw new TypeError("`input` must be a string, URL, or Request");if(this._options.prefixUrl&&typeof this._input=="string"){if(this._input.startsWith("/"))throw new Error("`input` must not begin with a slash when using `prefixUrl`");this._options.prefixUrl.endsWith("/")||(this._options.prefixUrl+="/"),this._input=this._options.prefixUrl+this._input}if(Qt){if(this.abortController=new globalThis.AbortController,this._options.signal){const s=this._options.signal;this._options.signal.addEventListener("abort",()=>{this.abortController.abort(s.reason)})}this._options.signal=this.abortController.signal}if(Jt&&(this._options.duplex="half"),this.request=new globalThis.Request(this._input,this._options),this._options.searchParams){const n="?"+(typeof this._options.searchParams=="string"?this._options.searchParams.replace(/^\?/,""):new URLSearchParams(this._options.searchParams).toString()),a=this.request.url.replace(/(?:\?.*?)?(?=#|$)/,n);(Zt&&this._options.body instanceof globalThis.FormData||this._options.body instanceof URLSearchParams)&&!(this._options.headers&&this._options.headers["content-type"])&&this.request.headers.delete("content-type"),this.request=new globalThis.Request(new globalThis.Request(a,{...this.request}),this._options)}this._options.json!==void 0&&(this._options.body=JSON.stringify(this._options.json),this.request.headers.set("content-type",this._options.headers.get("content-type")??"application/json"),this.request=new globalThis.Request(this.request,{body:this._options.body}))}_calculateRetryDelay(t){if(this._retryCount++,this._retryCount<this._options.retry.limit&&!(t instanceof ht)){if(t instanceof Z){if(!this._options.retry.statusCodes.includes(t.response.status))return 0;const s=t.response.headers.get("Retry-After");if(s&&this._options.retry.afterStatusCodes.includes(t.response.status)){let n=Number(s);return Number.isNaN(n)?n=Date.parse(s)-Date.now():n*=1e3,this._options.retry.maxRetryAfter!==void 0&&n>this._options.retry.maxRetryAfter?0:n}if(t.response.status===413)return 0}const e=this._options.retry.delay(this._retryCount);return Math.min(this._options.retry.backoffLimit,e)}return 0}_decorateResponse(t){return this._options.parseJson&&(t.json=async()=>this._options.parseJson(await t.text())),t}async _retry(t){try{return await t()}catch(e){const s=Math.min(this._calculateRetryDelay(e),L);if(s!==0&&this._retryCount>0){await ce(s,{signal:this._options.signal});for(const n of this._options.hooks.beforeRetry)if(await n({request:this.request,options:this._options,error:e,retryCount:this._retryCount})===pt)return;return this._retry(t)}throw e}}async _fetch(){for(const e of this._options.hooks.beforeRequest){const s=await e(this.request,this._options);if(s instanceof Request){this.request=s;break}if(s instanceof Response)return s}const t=ue(this.request,this._options);return this._options.timeout===!1?this._options.fetch(this.request.clone(),t):oe(this.request.clone(),t,this.abortController,this._options)}_stream(t,e){const s=Number(t.headers.get("content-length"))||0;let n=0;return t.status===204?(e&&e({percent:1,totalBytes:s,transferredBytes:n},new Uint8Array),new globalThis.Response(null,{status:t.status,statusText:t.statusText,headers:t.headers})):new globalThis.Response(new globalThis.ReadableStream({async start(a){const o=t.body.getReader();e&&e({percent:0,transferredBytes:0,totalBytes:s},new Uint8Array);async function c(){const{done:u,value:l}=await o.read();if(u){a.close();return}if(e){n+=l.byteLength;const h=s===0?0:n/s;e({percent:h,transferredBytes:n,totalBytes:s},l)}a.enqueue(l),await c()}await c()}}),{status:t.status,statusText:t.statusText,headers:t.headers})}}/*! MIT License © Sindre Sorhus */const W=r=>{const t=(e,s)=>q.create(e,E(r,s));for(const e of mt)t[e]=(s,n)=>q.create(s,E(r,n,{method:e}));return t.create=e=>W(E(e)),t.extend=e=>W(E(r,e)),t.stop=pt,t},le=W(),he=le,et=he.create({headers:{referrer:"https://sk.thorswap.net",referer:"https://sk.thorswap.net","Content-Type":"application/json"}}),gt={get:(r,t)=>et.get(r,t).json(),post:(r,t)=>et.post(r,t).json()},st=Object.values(i.Chain),de=(r="")=>{const t=r.toUpperCase(),[e]=t.split(".");if(st.includes(e))return!0;const[s]=t.split("/");if(st.includes(s))return!0;throw new Error(`Invalid identifier: ${r}. Expected format: <Chain>.<Ticker> or <Chain>.<Ticker>-<ContractAddress>`)},R=8,w=r=>10n**BigInt(r),T=r=>Math.log10(parseFloat(r.toString()));function $({value:r,bigIntDecimal:t=R,decimal:e=R}){const s=r<0n;let n=r.toString().substring(s?1:0);const a=e-(n.length-1);a>0&&(n="0".repeat(a)+n);const o=n.length-e;let c=n.slice(-e);return parseInt(c[t])>=5?c=`${c.substring(0,t-1)}${(parseInt(c[t-1])+1).toString()}`:c=c.substring(0,t),`${s?"-":""}${n.slice(0,o)}.${c}`.replace(/\.?0*$/,"")}var b,S,k,_t,P,bt,I,G,y,v,B,K;const x=class x{constructor(t){_(this,b);_(this,k);_(this,P);_(this,I);_(this,y);_(this,B);p(this,"decimalMultiplier",10n**8n);p(this,"bigIntValue",0n);p(this,"decimal");const e=F(t);this.decimal=typeof t=="object"?t.decimal:void 0,this.decimalMultiplier=w(Math.max(m(this,B,K).call(this,m(this,y,v).call(this,e)),this.decimal||0)),m(this,k,_t).call(this,e)}static fromBigInt(t,e){return new x({decimal:e,value:$({value:t,bigIntDecimal:e,decimal:e})})}static shiftDecimals({value:t,from:e,to:s}){return this.fromBigInt(new x(t).bigIntValue*w(s)/w(e),s)}get baseValue(){return this.getBaseValue("string")}get baseValueNumber(){return this.getBaseValue("number")}get baseValueBigInt(){return this.getBaseValue("bigint")}set(t){return new this.constructor({decimal:this.decimal,value:t,identifier:this.toString()})}add(...t){return m(this,b,S).call(this,"add",...t)}sub(...t){return m(this,b,S).call(this,"sub",...t)}mul(...t){return m(this,b,S).call(this,"mul",...t)}div(...t){return m(this,b,S).call(this,"div",...t)}gt(t){return this.bigIntValue>this.getBigIntValue(t)}gte(t){return this.bigIntValue>=this.getBigIntValue(t)}lt(t){return this.bigIntValue<this.getBigIntValue(t)}lte(t){return this.bigIntValue<=this.getBigIntValue(t)}eqValue(t){return this.bigIntValue===this.getBigIntValue(t)}getValue(t){const e=this.formatBigIntToSafeValue(this.bigIntValue,this.decimal||T(this.decimalMultiplier));switch(t){case"number":return Number(e);case"string":return e;default:return this.bigIntValue*BigInt(this.decimal||8n)/this.decimalMultiplier}}getBaseValue(t){const e=this.decimalMultiplier/w(this.decimal||i.BaseDecimal.THOR),s=this.bigIntValue/e;switch(t){case"number":return Number(s);case"string":return s.toString();default:return s}}getBigIntValue(t,e){if(!e&&typeof t=="object")return t.bigIntValue;const s=F(t),n=m(this,y,v).call(this,s);return n==="0"||n==="undefined"?0n:m(this,I,G).call(this,n,e)}formatBigIntToSafeValue(t,e){const s=e||this.decimal||R,n=Math.max(s,T(this.decimalMultiplier)),a=t<0n,o=t.toString().substring(a?1:0),c=n-(o.length-1),u=c>0?"0".repeat(c)+o:o,l=u.length-n;let h=u.slice(-n);return parseInt(h[s])>=5?h=`${h.substring(0,s-1)}${(parseInt(h[s-1])+1).toString()}`:h=h.substring(0,s),`${a?"-":""}${u.slice(0,l)}.${h}`.replace(/\.?0*$/,"")}toSignificant(t=6){const[e,s]=this.getValue("string").split("."),n=e||"",a=s||"",o=parseInt(n)?n.length+a.length:a.length;if(o<=t)return this.getValue("string");if(n.length>=t)return n.slice(0,t).padEnd(n.length,"0");if(parseInt(n))return`${n}.${a.slice(0,t-n.length)}`.padEnd(o-t,"0");const c=parseInt(a),u=`${c}`.slice(0,t);return`0.${u.padStart(a.length-`${c}`.length+u.length,"0")}`}toFixed(t=6){const[e,s]=this.getValue("string").split("."),n=e||"",a=s||"";if(parseInt(n))return`${n}.${a.slice(0,t)}`.padEnd(t,"0");const o=parseInt(a),c=`${o}`.slice(0,t);return`0.${c.padStart(a.length-`${o}`.length+c.length,"0")}`}toAbbreviation(t=2){const e=this.getValue("number"),s=["","K","M","B","T","Q","Qi","S"],n=Math.floor(Math.log10(Math.abs(e))/3),a=s[n];if(!a)return this.getValue("string");const o=10**(n*3);return`${(e/o).toFixed(t)}${a}`}};b=new WeakSet,S=function(t,...e){const s=m(this,P,bt).call(this,this,...e),n=w(s),a=e.reduce((c,u)=>{const l=this.getBigIntValue(u,s);switch(t){case"add":return c+l;case"sub":return c-l;case"mul":return c*l/n;case"div":{if(l===0n)throw new RangeError("Division by zero");return c*n/l}default:return c}},this.bigIntValue*n/this.decimalMultiplier),o=$({bigIntDecimal:s,decimal:Math.max(s,T(this.decimalMultiplier)),value:a});return new this.constructor({decimal:this.decimal,value:o,identifier:this.toString()})},k=new WeakSet,_t=function(t){const e=m(this,y,v).call(this,t)||"0";this.bigIntValue=m(this,I,G).call(this,e)},P=new WeakSet,bt=function(...t){const e=t.map(s=>typeof s=="object"?s.decimal||T(s.decimalMultiplier):m(this,B,K).call(this,m(this,y,v).call(this,s))).filter(Boolean);return Math.max(...e,R)},I=new WeakSet,G=function(t,e){const s=e?w(e):this.decimalMultiplier,n=T(s),[a="",o=""]=t.split(".");return BigInt(`${a}${o.padEnd(n,"0")}`)},y=new WeakSet,v=function(t){const s=`${typeof t=="number"?Number(t).toLocaleString("fullwide",{useGrouping:!1,maximumFractionDigits:20}):F(t)}`.replaceAll(",",".").split(".");return s.length>1?`${s.slice(0,-1).join("")}.${s.at(-1)}`:s[0]},B=new WeakSet,K=function(t){var s;const e=((s=t.split(".")[1])==null?void 0:s.length)||0;return Math.max(e,R)};let A=x;function F(r){return typeof r=="object"?"getValue"in r?r.getValue("string"):r.value:r}const M=(r,t)=>typeof r=="bigint"?$({value:r,bigIntDecimal:t,decimal:t}):r;let Y;const U=r=>{if(!Y)throw new Error("Static assets not loaded, call await AssetValue.loadStaticAssets() first");return Y.get(r.toUpperCase())||{decimal:i.BaseDecimal.THOR,identifier:""}},rt=async(r,t=0)=>{de(r);const e=await z(V(r)),s=M(t,e);return new f({decimal:e,value:s,identifier:r})};class f extends A{constructor(e){super(e.value instanceof A?e.value:{decimal:e.decimal,value:e.value});p(this,"address");p(this,"chain");p(this,"isSynthetic",!1);p(this,"isGasAsset",!1);p(this,"symbol");p(this,"ticker");p(this,"type");const s="identifier"in e?e.identifier:`${e.chain}.${e.symbol}`,n=V(s);this.type=ot(n),this.chain=n.chain,this.ticker=n.ticker,this.symbol=n.symbol,this.address=n.address,this.isSynthetic=n.isSynthetic,this.isGasAsset=n.isGasAsset}get assetValue(){return`${this.getValue("string")} ${this.ticker}`}toString(e=!1){const s=this.isSynthetic?this.symbol.split("-")[0]:`${this.chain}.${this.ticker}`;return e?s:`${this.chain}.${this.symbol}`}eq({chain:e,symbol:s}){return this.chain===e&&this.symbol===s}static async fromString(e,s=0){return rt(e,s)}static fromStringSync(e,s=0){const{isSynthetic:n}=V(e),{decimal:a,identifier:o}=U(e),c=M(s,a);return o?new f({decimal:a,identifier:o,value:c}):n?new f({decimal:8,identifier:e,value:c}):void 0}static async fromIdentifier(e,s=0){return rt(e,s)}static fromIdentifierSync(e,s=0){const{decimal:n,identifier:a}=U(e),o=M(s,n);return new f({decimal:n,identifier:a,value:o})}static fromChainOrSignature(e,s=0){const{decimal:n,identifier:a}=at(e),o=M(s,n);return new f({value:o,decimal:n,identifier:a})}static async fromTCQuote(e,s=0){const n=await z(V(e)),a=this.shiftDecimals({value:s,from:i.BaseDecimal.THOR,to:n});return new f({value:a,identifier:e,decimal:n})}static fromTCQuoteStatic(e,s=0){const n=U(e),a=this.shiftDecimals({value:s,from:i.BaseDecimal.THOR,to:n.decimal});return new f({...n,value:a})}static async loadStaticAssets(){return new Promise(async(e,s)=>{try{const{ThorchainList:n,NativeList:a,...o}=await import("@swapkit/tokens");Y=[a,...Object.values(o)].reduce((u,{tokens:l})=>(l.forEach(({identifier:h,chain:g,...C})=>{const N="decimals"in C?C.decimals:i.BaseDecimal[g];u.set(h,{identifier:h,decimal:N})}),u),new Map),e({ok:!0})}catch(n){console.error(n),s({ok:!1,error:n,message:"Couldn't load static assets. Ensure you have installed @swapkit/tokens package"})}})}}const me=r=>{const t=f.fromChainOrSignature(r);switch(r){case i.Chain.Bitcoin:case i.Chain.Litecoin:case i.Chain.BitcoinCash:return t.add(10001);case i.Chain.Dogecoin:return t.add(100000001);case i.Chain.Avalanche:case i.Chain.Ethereum:return t.add(10*10**9);case i.Chain.THORChain:case i.Chain.Maya:return t.add(0);default:return t.add(1)}},V=r=>{const t=r.slice(0,14).includes("/"),[e,s]=r.split(".").pop().split("/"),n=r.includes(".")&&!t?r:`${i.Chain.THORChain}.${s}`,[a,o]=n.split("."),[c,u]=(t?s:o).split("-");return{address:u==null?void 0:u.toLowerCase(),chain:a,isGasAsset:it({chain:a,symbol:o}),isSynthetic:t,symbol:(t?`${e}/`:"")+(u?`${c}-${(u==null?void 0:u.toLowerCase())??""}`:o),ticker:c}},pe={core_wallet_connection_not_found:10001,core_estimated_max_spendable_chain_not_supported:10002,core_extend_error:10003,core_inbound_data_not_found:10004,core_approve_asset_address_or_from_not_found:10005,core_chain_halted:10099,core_wallet_xdefi_not_installed:10101,core_wallet_evmwallet_not_installed:10102,core_wallet_walletconnect_not_installed:10103,core_wallet_keystore_not_installed:10104,core_wallet_ledger_not_installed:10105,core_wallet_trezor_not_installed:10106,core_wallet_keplr_not_installed:10107,core_wallet_okx_not_installed:10108,core_swap_invalid_params:10200,core_swap_route_not_complete:10201,core_swap_asset_not_recognized:10202,core_swap_contract_not_found:10203,core_swap_route_transaction_not_found:10204,core_swap_contract_not_supported:10205,core_swap_transaction_error:10206,core_swap_quote_mode_not_supported:10207,core_transaction_deposit_error:10301,core_transaction_create_liquidity_rune_error:10302,core_transaction_create_liquidity_asset_error:10303,core_transaction_create_liquidity_invalid_params:10304,core_transaction_add_liquidity_invalid_params:10305,core_transaction_add_liquidity_no_rune_address:10306,core_transaction_add_liquidity_rune_error:10307,core_transaction_add_liquidity_asset_error:10308,core_transaction_withdraw_error:10309,core_transaction_deposit_to_pool_error:10310,core_transaction_deposit_insufficient_funds_error:10311,core_transaction_deposit_gas_error:10312,core_transaction_deposit_server_error:10313,wallet_ledger_connection_error:20001,helpers_number_different_decimals:99101};class Q extends Error{constructor(t,e){console.error(e),super(t,{cause:{code:pe[t],message:t}}),Object.setPrototypeOf(this,Q.prototype)}}class D extends A{eq(t){return this.eqValue(t)}static fromBigInt(t,e){return new D({decimal:e,value:$({value:t,bigIntDecimal:e,decimal:e})})}}exports.AssetValue=f;exports.BigIntArithmetics=A;exports.RequestClient=gt;exports.SwapKitError=Q;exports.SwapKitNumber=D;exports.assetFromString=xt;exports.derivationPathToString=zt;exports.filterAssets=Nt;exports.formatBigIntToSafeValue=$;exports.gasFeeMultiplier=Pt;exports.getAssetType=ot;exports.getAsymmetricAssetShare=ut;exports.getAsymmetricAssetWithdrawAmount=jt;exports.getAsymmetricRuneShare=ct;exports.getAsymmetricRuneWithdrawAmount=Ht;exports.getCommonAssetInfo=at;exports.getDecimal=z;exports.getEstimatedPoolShare=Ft;exports.getLiquiditySlippage=Ut;exports.getMemoFor=Gt;exports.getMinAmountByChain=me;exports.getSymmetricPoolShare=lt;exports.getSymmetricWithdraw=Lt;exports.getTHORNameCost=Kt;exports.isGasAsset=it;exports.validateTHORName=Yt;
|
package/dist/index.es.js
CHANGED
|
@@ -10,7 +10,7 @@ var y = (s, t, e) => {
|
|
|
10
10
|
t instanceof WeakSet ? t.add(s) : t.set(s, e);
|
|
11
11
|
};
|
|
12
12
|
var f = (s, t, e) => (wt(s, t, "access private method"), e);
|
|
13
|
-
import { FeeOption as
|
|
13
|
+
import { FeeOption as L, BaseDecimal as m, Chain as o, ChainToRPC as At, MemoType as b } from "@swapkit/types";
|
|
14
14
|
const Tt = "0x313ce567", nt = async ({ chain: s, to: t }) => {
|
|
15
15
|
try {
|
|
16
16
|
const { result: e } = await Kt.post(At[s], {
|
|
@@ -46,9 +46,9 @@ const Tt = "0x313ce567", nt = async ({ chain: s, to: t }) => {
|
|
|
46
46
|
return m[s];
|
|
47
47
|
}
|
|
48
48
|
}, ee = {
|
|
49
|
-
[
|
|
50
|
-
[
|
|
51
|
-
[
|
|
49
|
+
[L.Average]: 1.2,
|
|
50
|
+
[L.Fast]: 1.5,
|
|
51
|
+
[L.Fastest]: 2
|
|
52
52
|
}, $t = ({ chain: s, symbol: t }) => {
|
|
53
53
|
switch (s) {
|
|
54
54
|
case o.Bitcoin:
|
|
@@ -155,8 +155,8 @@ const Tt = "0x313ce567", nt = async ({ chain: s, to: t }) => {
|
|
|
155
155
|
poolUnits: t,
|
|
156
156
|
assetDepth: e
|
|
157
157
|
}) => {
|
|
158
|
-
const r = d(s), n = d(t), i = d(e), a = r.mul(i), c = n.mul(n).mul(2), u = n.mul(r).mul(2), l = r.mul(r), h = a.mul(c.sub(u).add(l)),
|
|
159
|
-
return h.div(
|
|
158
|
+
const r = d(s), n = d(t), i = d(e), a = r.mul(i), c = n.mul(n).mul(2), u = n.mul(r).mul(2), l = r.mul(r), h = a.mul(c.sub(u).add(l)), g = n.mul(n).mul(n);
|
|
159
|
+
return h.div(g);
|
|
160
160
|
}, ne = ({
|
|
161
161
|
percent: s,
|
|
162
162
|
runeDepth: t,
|
|
@@ -193,11 +193,11 @@ const Tt = "0x313ce567", nt = async ({ chain: s, to: t }) => {
|
|
|
193
193
|
runeAmount: n,
|
|
194
194
|
assetAmount: i
|
|
195
195
|
}) => {
|
|
196
|
-
const a = d(s), c = d(e), u = d(t), l = d(n), h = d(i),
|
|
196
|
+
const a = d(s), c = d(e), u = d(t), l = d(n), h = d(i), g = l.mul(c), T = h.mul(a), j = l.mul(h), ft = a.mul(c), pt = u.mul(g.add(T.add(j.mul(2)))), _t = g.add(T.add(ft.mul(2))), X = pt.div(_t), D = d(r).add(X);
|
|
197
197
|
if (X.baseValueNumber === 0)
|
|
198
|
-
return
|
|
199
|
-
const gt = u.add(
|
|
200
|
-
return
|
|
198
|
+
return D.div(u).baseValueNumber;
|
|
199
|
+
const gt = u.add(D);
|
|
200
|
+
return D.div(gt).baseValueNumber;
|
|
201
201
|
}, ce = ({
|
|
202
202
|
runeAmount: s,
|
|
203
203
|
assetAmount: t,
|
|
@@ -212,29 +212,29 @@ const Tt = "0x313ce567", nt = async ({ chain: s, to: t }) => {
|
|
|
212
212
|
chain: e
|
|
213
213
|
}) => e === "ETH" && t !== "ETH" ? `${t}-${s.slice(-3)}` : s, ue = (s, t) => {
|
|
214
214
|
switch (s) {
|
|
215
|
-
case
|
|
216
|
-
case
|
|
215
|
+
case b.LEAVE:
|
|
216
|
+
case b.BOND: {
|
|
217
217
|
const { address: e } = t;
|
|
218
218
|
return `${s}:${e}`;
|
|
219
219
|
}
|
|
220
|
-
case
|
|
220
|
+
case b.UNBOND: {
|
|
221
221
|
const { address: e, unbondAmount: r } = t;
|
|
222
222
|
return `${s}:${e}:${r * 10 ** 8}`;
|
|
223
223
|
}
|
|
224
|
-
case
|
|
224
|
+
case b.THORNAME_REGISTER: {
|
|
225
225
|
const { name: e, chain: r, address: n, owner: i } = t;
|
|
226
226
|
return `${s}:${e}:${r}:${n}${i ? `:${i}` : ""}`;
|
|
227
227
|
}
|
|
228
|
-
case
|
|
228
|
+
case b.DEPOSIT: {
|
|
229
229
|
const { chain: e, symbol: r, address: n, singleSide: i } = t;
|
|
230
230
|
return i ? `${s}:${e}/${r}::t:0` : `${s}:${e}.${r}:${n || ""}:t:0`;
|
|
231
231
|
}
|
|
232
|
-
case
|
|
232
|
+
case b.WITHDRAW: {
|
|
233
233
|
const { chain: e, ticker: r, symbol: n, basisPoints: i, targetAssetString: a, singleSide: c } = t, u = !c && a ? `:${a}` : "", l = Mt({ chain: e, symbol: n, ticker: r });
|
|
234
234
|
return `${s}:${e}${c ? "/" : "."}${l}:${i}${u}`;
|
|
235
235
|
}
|
|
236
|
-
case
|
|
237
|
-
case
|
|
236
|
+
case b.OPEN_LOAN:
|
|
237
|
+
case b.CLOSE_LOAN: {
|
|
238
238
|
const { asset: e, address: r } = t;
|
|
239
239
|
return `${s}:${e}:${r}`;
|
|
240
240
|
}
|
|
@@ -320,7 +320,7 @@ const B = (s) => s !== null && typeof s == "object", V = (...s) => {
|
|
|
320
320
|
formData: "multipart/form-data",
|
|
321
321
|
arrayBuffer: "*/*",
|
|
322
322
|
blob: "*/*"
|
|
323
|
-
},
|
|
323
|
+
}, U = 2147483647, ut = Symbol("stop"), Ht = {
|
|
324
324
|
json: !0,
|
|
325
325
|
parseJson: !0,
|
|
326
326
|
searchParams: !0,
|
|
@@ -398,11 +398,11 @@ const Yt = (s, t) => {
|
|
|
398
398
|
!(r in jt) && !(r in Ht) && !(r in s) && (e[r] = t[r]);
|
|
399
399
|
return e;
|
|
400
400
|
};
|
|
401
|
-
class
|
|
401
|
+
class q {
|
|
402
402
|
static create(t, e) {
|
|
403
|
-
const r = new
|
|
404
|
-
if (typeof r._options.timeout == "number" && r._options.timeout >
|
|
405
|
-
throw new RangeError(`The \`timeout\` option cannot be greater than ${
|
|
403
|
+
const r = new q(t, e), n = async () => {
|
|
404
|
+
if (typeof r._options.timeout == "number" && r._options.timeout > U)
|
|
405
|
+
throw new RangeError(`The \`timeout\` option cannot be greater than ${U}`);
|
|
406
406
|
await Promise.resolve();
|
|
407
407
|
let c = await r._fetch();
|
|
408
408
|
for (const u of r._options.hooks.afterResponse) {
|
|
@@ -530,7 +530,7 @@ class k {
|
|
|
530
530
|
try {
|
|
531
531
|
return await t();
|
|
532
532
|
} catch (e) {
|
|
533
|
-
const r = Math.min(this._calculateRetryDelay(e),
|
|
533
|
+
const r = Math.min(this._calculateRetryDelay(e), U);
|
|
534
534
|
if (r !== 0 && this._retryCount > 0) {
|
|
535
535
|
await Gt(r, { signal: this._options.signal });
|
|
536
536
|
for (const n of this._options.hooks.beforeRetry)
|
|
@@ -594,12 +594,12 @@ class k {
|
|
|
594
594
|
}
|
|
595
595
|
}
|
|
596
596
|
/*! MIT License © Sindre Sorhus */
|
|
597
|
-
const
|
|
598
|
-
const t = (e, r) =>
|
|
597
|
+
const G = (s) => {
|
|
598
|
+
const t = (e, r) => q.create(e, V(s, r));
|
|
599
599
|
for (const e of ct)
|
|
600
|
-
t[e] = (r, n) =>
|
|
601
|
-
return t.create = (e) =>
|
|
602
|
-
}, zt =
|
|
600
|
+
t[e] = (r, n) => q.create(r, V(s, n, { method: e }));
|
|
601
|
+
return t.create = (e) => G(V(e)), t.extend = (e) => G(V(s, e)), t.stop = ut, t;
|
|
602
|
+
}, zt = G(), Jt = zt, et = Jt.create({
|
|
603
603
|
headers: {
|
|
604
604
|
referrer: "https://sk.thorswap.net",
|
|
605
605
|
referer: "https://sk.thorswap.net",
|
|
@@ -619,7 +619,7 @@ const W = (s) => {
|
|
|
619
619
|
`Invalid identifier: ${s}. Expected format: <Chain>.<Ticker> or <Chain>.<Ticker>-<ContractAddress>`
|
|
620
620
|
);
|
|
621
621
|
}, C = 8, v = (s) => 10n ** BigInt(s), R = (s) => Math.log10(parseFloat(s.toString()));
|
|
622
|
-
function
|
|
622
|
+
function x({
|
|
623
623
|
value: s,
|
|
624
624
|
bigIntDecimal: t = C,
|
|
625
625
|
decimal: e = C
|
|
@@ -635,27 +635,27 @@ function q({
|
|
|
635
635
|
""
|
|
636
636
|
);
|
|
637
637
|
}
|
|
638
|
-
var w, S,
|
|
639
|
-
const
|
|
638
|
+
var w, S, P, ht, N, dt, E, Y, A, $, O, z;
|
|
639
|
+
const H = class H {
|
|
640
640
|
constructor(t) {
|
|
641
641
|
y(this, w);
|
|
642
|
-
y(this, x);
|
|
643
642
|
y(this, P);
|
|
643
|
+
y(this, N);
|
|
644
644
|
y(this, E);
|
|
645
645
|
y(this, A);
|
|
646
646
|
y(this, O);
|
|
647
647
|
p(this, "decimalMultiplier", 10n ** 8n);
|
|
648
648
|
p(this, "bigIntValue", 0n);
|
|
649
649
|
p(this, "decimal");
|
|
650
|
-
const e =
|
|
650
|
+
const e = F(t);
|
|
651
651
|
this.decimal = typeof t == "object" ? t.decimal : void 0, this.decimalMultiplier = v(
|
|
652
|
-
Math.max(f(this, O,
|
|
653
|
-
), f(this,
|
|
652
|
+
Math.max(f(this, O, z).call(this, f(this, A, $).call(this, e)), this.decimal || 0)
|
|
653
|
+
), f(this, P, ht).call(this, e);
|
|
654
654
|
}
|
|
655
655
|
static fromBigInt(t, e) {
|
|
656
|
-
return new
|
|
656
|
+
return new H({
|
|
657
657
|
decimal: e,
|
|
658
|
-
value:
|
|
658
|
+
value: x({ value: t, bigIntDecimal: e, decimal: e })
|
|
659
659
|
});
|
|
660
660
|
}
|
|
661
661
|
static shiftDecimals({
|
|
@@ -664,7 +664,7 @@ const N = class N {
|
|
|
664
664
|
to: r
|
|
665
665
|
}) {
|
|
666
666
|
return this.fromBigInt(
|
|
667
|
-
new
|
|
667
|
+
new H(t).bigIntValue * v(r) / v(e),
|
|
668
668
|
r
|
|
669
669
|
);
|
|
670
670
|
}
|
|
@@ -744,8 +744,8 @@ const N = class N {
|
|
|
744
744
|
getBigIntValue(t, e) {
|
|
745
745
|
if (!e && typeof t == "object")
|
|
746
746
|
return t.bigIntValue;
|
|
747
|
-
const r =
|
|
748
|
-
return n === "0" || n === "undefined" ? 0n : f(this, E,
|
|
747
|
+
const r = F(t), n = f(this, A, $).call(this, r);
|
|
748
|
+
return n === "0" || n === "undefined" ? 0n : f(this, E, Y).call(this, n, e);
|
|
749
749
|
}
|
|
750
750
|
formatBigIntToSafeValue(t, e) {
|
|
751
751
|
const r = e || this.decimal || C, n = Math.max(
|
|
@@ -794,7 +794,7 @@ const N = class N {
|
|
|
794
794
|
}
|
|
795
795
|
};
|
|
796
796
|
w = new WeakSet(), S = function(t, ...e) {
|
|
797
|
-
const r = f(this,
|
|
797
|
+
const r = f(this, N, dt).call(this, this, ...e), n = v(r), i = e.reduce(
|
|
798
798
|
(c, u) => {
|
|
799
799
|
const l = this.getBigIntValue(u, r);
|
|
800
800
|
switch (t) {
|
|
@@ -815,50 +815,50 @@ w = new WeakSet(), S = function(t, ...e) {
|
|
|
815
815
|
},
|
|
816
816
|
//normalize is to precision multiplier base
|
|
817
817
|
this.bigIntValue * n / this.decimalMultiplier
|
|
818
|
-
), a =
|
|
818
|
+
), a = x({
|
|
819
819
|
bigIntDecimal: r,
|
|
820
820
|
decimal: Math.max(r, R(this.decimalMultiplier)),
|
|
821
821
|
value: i
|
|
822
822
|
});
|
|
823
823
|
return new this.constructor({ decimal: this.decimal, value: a, identifier: this.toString() });
|
|
824
|
-
},
|
|
824
|
+
}, P = new WeakSet(), ht = function(t) {
|
|
825
825
|
const e = f(this, A, $).call(this, t) || "0";
|
|
826
|
-
this.bigIntValue = f(this, E,
|
|
827
|
-
},
|
|
826
|
+
this.bigIntValue = f(this, E, Y).call(this, e);
|
|
827
|
+
}, N = new WeakSet(), dt = function(...t) {
|
|
828
828
|
const e = t.map(
|
|
829
|
-
(r) => typeof r == "object" ? r.decimal || R(r.decimalMultiplier) : f(this, O,
|
|
829
|
+
(r) => typeof r == "object" ? r.decimal || R(r.decimalMultiplier) : f(this, O, z).call(this, f(this, A, $).call(this, r))
|
|
830
830
|
).filter(Boolean);
|
|
831
831
|
return Math.max(...e, C);
|
|
832
|
-
}, E = new WeakSet(),
|
|
832
|
+
}, E = new WeakSet(), Y = function(t, e) {
|
|
833
833
|
const r = e ? v(e) : this.decimalMultiplier, n = R(r), [i = "", a = ""] = t.split(".");
|
|
834
834
|
return BigInt(`${i}${a.padEnd(n, "0")}`);
|
|
835
835
|
}, A = new WeakSet(), $ = function(t) {
|
|
836
836
|
const r = `${typeof t == "number" ? Number(t).toLocaleString("fullwide", {
|
|
837
837
|
useGrouping: !1,
|
|
838
838
|
maximumFractionDigits: 20
|
|
839
|
-
}) :
|
|
839
|
+
}) : F(t)}`.replaceAll(",", ".").split(".");
|
|
840
840
|
return r.length > 1 ? `${r.slice(0, -1).join("")}.${r.at(-1)}` : r[0];
|
|
841
|
-
}, O = new WeakSet(),
|
|
841
|
+
}, O = new WeakSet(), z = function(t) {
|
|
842
842
|
var r;
|
|
843
843
|
const e = ((r = t.split(".")[1]) == null ? void 0 : r.length) || 0;
|
|
844
844
|
return Math.max(e, C);
|
|
845
845
|
};
|
|
846
|
-
let I =
|
|
847
|
-
function
|
|
846
|
+
let I = H;
|
|
847
|
+
function F(s) {
|
|
848
848
|
return typeof s == "object" ? "getValue" in s ? s.getValue("string") : s.value : s;
|
|
849
849
|
}
|
|
850
|
-
const M = (s, t) => typeof s == "bigint" ?
|
|
851
|
-
let
|
|
852
|
-
const
|
|
853
|
-
if (!
|
|
850
|
+
const M = (s, t) => typeof s == "bigint" ? x({ value: s, bigIntDecimal: t, decimal: t }) : s;
|
|
851
|
+
let J;
|
|
852
|
+
const W = (s) => {
|
|
853
|
+
if (!J)
|
|
854
854
|
throw new Error("Static assets not loaded, call await AssetValue.loadStaticAssets() first");
|
|
855
|
-
return
|
|
855
|
+
return J.get(s.toUpperCase()) || { decimal: m.THOR, identifier: "" };
|
|
856
856
|
}, st = async (s, t = 0) => {
|
|
857
857
|
Qt(s);
|
|
858
|
-
const e = await it(
|
|
859
|
-
return new
|
|
858
|
+
const e = await it(k(s)), r = M(t, e);
|
|
859
|
+
return new _({ decimal: e, value: r, identifier: s });
|
|
860
860
|
};
|
|
861
|
-
class
|
|
861
|
+
class _ extends I {
|
|
862
862
|
constructor(e) {
|
|
863
863
|
super(
|
|
864
864
|
e.value instanceof I ? e.value : { decimal: e.decimal, value: e.value }
|
|
@@ -870,14 +870,14 @@ class b extends I {
|
|
|
870
870
|
p(this, "symbol");
|
|
871
871
|
p(this, "ticker");
|
|
872
872
|
p(this, "type");
|
|
873
|
-
const r = "identifier" in e ? e.identifier : `${e.chain}.${e.symbol}`, n =
|
|
873
|
+
const r = "identifier" in e ? e.identifier : `${e.chain}.${e.symbol}`, n = k(r);
|
|
874
874
|
this.type = It(n), this.chain = n.chain, this.ticker = n.ticker, this.symbol = n.symbol, this.address = n.address, this.isSynthetic = n.isSynthetic, this.isGasAsset = n.isGasAsset;
|
|
875
875
|
}
|
|
876
876
|
get assetValue() {
|
|
877
877
|
return `${this.getValue("string")} ${this.ticker}`;
|
|
878
878
|
}
|
|
879
879
|
toString(e = !1) {
|
|
880
|
-
const r = this.isSynthetic ? this.
|
|
880
|
+
const r = this.isSynthetic ? this.symbol.split("-")[0] : `${this.chain}.${this.ticker}`;
|
|
881
881
|
return e ? r : (
|
|
882
882
|
// THOR.ETH/ETH | ETH.USDT-0x1234567890
|
|
883
883
|
`${this.chain}.${this.symbol}`
|
|
@@ -890,33 +890,33 @@ class b extends I {
|
|
|
890
890
|
return st(e, r);
|
|
891
891
|
}
|
|
892
892
|
static fromStringSync(e, r = 0) {
|
|
893
|
-
const {
|
|
893
|
+
const { isSynthetic: n } = k(e), { decimal: i, identifier: a } = W(
|
|
894
894
|
e
|
|
895
|
-
),
|
|
896
|
-
return i ? new
|
|
895
|
+
), c = M(r, i);
|
|
896
|
+
return a ? new _({ decimal: i, identifier: a, value: c }) : n ? new _({ decimal: 8, identifier: e, value: c }) : void 0;
|
|
897
897
|
}
|
|
898
898
|
static async fromIdentifier(e, r = 0) {
|
|
899
899
|
return st(e, r);
|
|
900
900
|
}
|
|
901
901
|
static fromIdentifierSync(e, r = 0) {
|
|
902
|
-
const { decimal: n, identifier: i } =
|
|
903
|
-
return new
|
|
902
|
+
const { decimal: n, identifier: i } = W(e), a = M(r, n);
|
|
903
|
+
return new _({ decimal: n, identifier: i, value: a });
|
|
904
904
|
}
|
|
905
905
|
static fromChainOrSignature(e, r = 0) {
|
|
906
906
|
const { decimal: n, identifier: i } = Ct(e), a = M(r, n);
|
|
907
|
-
return new
|
|
907
|
+
return new _({ value: a, decimal: n, identifier: i });
|
|
908
908
|
}
|
|
909
909
|
static async fromTCQuote(e, r = 0) {
|
|
910
|
-
const n = await it(
|
|
911
|
-
return new
|
|
910
|
+
const n = await it(k(e)), i = this.shiftDecimals({ value: r, from: m.THOR, to: n });
|
|
911
|
+
return new _({ value: i, identifier: e, decimal: n });
|
|
912
912
|
}
|
|
913
913
|
static fromTCQuoteStatic(e, r = 0) {
|
|
914
|
-
const n =
|
|
914
|
+
const n = W(e), i = this.shiftDecimals({
|
|
915
915
|
value: r,
|
|
916
916
|
from: m.THOR,
|
|
917
917
|
to: n.decimal
|
|
918
918
|
});
|
|
919
|
-
return new
|
|
919
|
+
return new _({ ...n, value: i });
|
|
920
920
|
}
|
|
921
921
|
static async loadStaticAssets() {
|
|
922
922
|
return new Promise(
|
|
@@ -929,10 +929,10 @@ class b extends I {
|
|
|
929
929
|
NativeList: i,
|
|
930
930
|
...a
|
|
931
931
|
} = await import("@swapkit/tokens");
|
|
932
|
-
|
|
933
|
-
(u, { tokens: l }) => (l.forEach(({ identifier: h, chain:
|
|
934
|
-
const
|
|
935
|
-
u.set(h, { identifier: h, decimal:
|
|
932
|
+
J = [i, ...Object.values(a)].reduce(
|
|
933
|
+
(u, { tokens: l }) => (l.forEach(({ identifier: h, chain: g, ...T }) => {
|
|
934
|
+
const j = "decimals" in T ? T.decimals : m[g];
|
|
935
|
+
u.set(h, { identifier: h, decimal: j });
|
|
936
936
|
}), u),
|
|
937
937
|
/* @__PURE__ */ new Map()
|
|
938
938
|
), e({ ok: !0 });
|
|
@@ -948,7 +948,7 @@ class b extends I {
|
|
|
948
948
|
}
|
|
949
949
|
}
|
|
950
950
|
const me = (s) => {
|
|
951
|
-
const t =
|
|
951
|
+
const t = _.fromChainOrSignature(s);
|
|
952
952
|
switch (s) {
|
|
953
953
|
case o.Bitcoin:
|
|
954
954
|
case o.Litecoin:
|
|
@@ -965,15 +965,15 @@ const me = (s) => {
|
|
|
965
965
|
default:
|
|
966
966
|
return t.add(1);
|
|
967
967
|
}
|
|
968
|
-
},
|
|
969
|
-
const t = s.slice(0, 14).includes("/"), e = s.includes(".") ? s : `${o.THORChain}.${
|
|
968
|
+
}, k = (s) => {
|
|
969
|
+
const t = s.slice(0, 14).includes("/"), [e, r] = s.split(".").pop().split("/"), n = s.includes(".") && !t ? s : `${o.THORChain}.${r}`, [i, a] = n.split("."), [c, u] = (t ? r : a).split("-");
|
|
970
970
|
return {
|
|
971
|
-
address:
|
|
972
|
-
chain:
|
|
973
|
-
isGasAsset: $t({ chain:
|
|
971
|
+
address: u == null ? void 0 : u.toLowerCase(),
|
|
972
|
+
chain: i,
|
|
973
|
+
isGasAsset: $t({ chain: i, symbol: a }),
|
|
974
974
|
isSynthetic: t,
|
|
975
|
-
symbol:
|
|
976
|
-
ticker:
|
|
975
|
+
symbol: (t ? `${e}/` : "") + (u ? `${c}-${(u == null ? void 0 : u.toLowerCase()) ?? ""}` : a),
|
|
976
|
+
ticker: c
|
|
977
977
|
};
|
|
978
978
|
}, Xt = {
|
|
979
979
|
/**
|
|
@@ -1044,12 +1044,12 @@ class Q extends I {
|
|
|
1044
1044
|
static fromBigInt(t, e) {
|
|
1045
1045
|
return new Q({
|
|
1046
1046
|
decimal: e,
|
|
1047
|
-
value:
|
|
1047
|
+
value: x({ value: t, bigIntDecimal: e, decimal: e })
|
|
1048
1048
|
});
|
|
1049
1049
|
}
|
|
1050
1050
|
}
|
|
1051
1051
|
export {
|
|
1052
|
-
|
|
1052
|
+
_ as AssetValue,
|
|
1053
1053
|
I as BigIntArithmetics,
|
|
1054
1054
|
Kt as RequestClient,
|
|
1055
1055
|
mt as SwapKitError,
|
|
@@ -1057,7 +1057,7 @@ export {
|
|
|
1057
1057
|
re as assetFromString,
|
|
1058
1058
|
de as derivationPathToString,
|
|
1059
1059
|
se as filterAssets,
|
|
1060
|
-
|
|
1060
|
+
x as formatBigIntToSafeValue,
|
|
1061
1061
|
ee as gasFeeMultiplier,
|
|
1062
1062
|
It as getAssetType,
|
|
1063
1063
|
Vt as getAsymmetricAssetShare,
|
package/package.json
CHANGED
|
@@ -42,7 +42,7 @@
|
|
|
42
42
|
"repository": "https://github.com/thorswap/SwapKit.git",
|
|
43
43
|
"type": "module",
|
|
44
44
|
"types": "./dist/index.d.ts",
|
|
45
|
-
"version": "1.0.0-rc.
|
|
45
|
+
"version": "1.0.0-rc.15",
|
|
46
46
|
"scripts": {
|
|
47
47
|
"build": "vite build",
|
|
48
48
|
"clean": "rm -rf dist vite.config.ts.* .turbo node_modules",
|
|
@@ -28,7 +28,7 @@ describe('AssetValue', () => {
|
|
|
28
28
|
value: 1234567890,
|
|
29
29
|
});
|
|
30
30
|
|
|
31
|
-
expect(ethSynth.assetValue).toBe('1234567890 ETH
|
|
31
|
+
expect(ethSynth.assetValue).toBe('1234567890 ETH');
|
|
32
32
|
expect(ethSynth.toString()).toBe('THOR.ETH/ETH');
|
|
33
33
|
expect(ethSynth.toString(true)).toBe('ETH/ETH');
|
|
34
34
|
expect(ethSynth.mul(21.37).getValue('string')).toBe('26382715809.3');
|
|
@@ -101,7 +101,9 @@ export class AssetValue extends BigIntArithmetics {
|
|
|
101
101
|
|
|
102
102
|
toString(short = false) {
|
|
103
103
|
// THOR.RUNE | ETH/ETH
|
|
104
|
-
const shortFormat = this.isSynthetic
|
|
104
|
+
const shortFormat = this.isSynthetic
|
|
105
|
+
? this.symbol.split('-')[0]
|
|
106
|
+
: `${this.chain}.${this.ticker}`;
|
|
105
107
|
|
|
106
108
|
return short
|
|
107
109
|
? shortFormat
|
|
@@ -118,6 +120,7 @@ export class AssetValue extends BigIntArithmetics {
|
|
|
118
120
|
}
|
|
119
121
|
|
|
120
122
|
static fromStringSync(assetString: string, value: NumberPrimitives = 0) {
|
|
123
|
+
const { isSynthetic } = getAssetInfo(assetString);
|
|
121
124
|
const { decimal, identifier: tokenIdentifier } = getStaticToken(
|
|
122
125
|
assetString as unknown as TokenNames,
|
|
123
126
|
);
|
|
@@ -126,6 +129,8 @@ export class AssetValue extends BigIntArithmetics {
|
|
|
126
129
|
|
|
127
130
|
return tokenIdentifier
|
|
128
131
|
? new AssetValue({ decimal, identifier: tokenIdentifier, value: parsedValue })
|
|
132
|
+
: isSynthetic
|
|
133
|
+
? new AssetValue({ decimal: 8, identifier: assetString, value: parsedValue })
|
|
129
134
|
: undefined;
|
|
130
135
|
}
|
|
131
136
|
|
|
@@ -236,19 +241,21 @@ export const getMinAmountByChain = (chain: Chain) => {
|
|
|
236
241
|
|
|
237
242
|
const getAssetInfo = (identifier: string) => {
|
|
238
243
|
const isSynthetic = identifier.slice(0, 14).includes('/');
|
|
239
|
-
const
|
|
240
|
-
|
|
241
|
-
: `${Chain.THORChain}.${
|
|
244
|
+
const [synthChain, synthSymbol] = identifier.split('.').pop()!.split('/');
|
|
245
|
+
const adjustedIdentifier =
|
|
246
|
+
identifier.includes('.') && !isSynthetic ? identifier : `${Chain.THORChain}.${synthSymbol}`;
|
|
242
247
|
|
|
243
248
|
const [chain, symbol] = adjustedIdentifier.split('.') as [Chain, string];
|
|
244
|
-
const [ticker, address] = symbol.split('-') as [string, string?];
|
|
249
|
+
const [ticker, address] = (isSynthetic ? synthSymbol : symbol).split('-') as [string, string?];
|
|
245
250
|
|
|
246
251
|
return {
|
|
247
252
|
address: address?.toLowerCase(),
|
|
248
253
|
chain,
|
|
249
254
|
isGasAsset: isGasAsset({ chain, symbol }),
|
|
250
255
|
isSynthetic,
|
|
251
|
-
symbol:
|
|
252
|
-
|
|
256
|
+
symbol:
|
|
257
|
+
(isSynthetic ? `${synthChain}/` : '') +
|
|
258
|
+
(address ? `${ticker}-${address?.toLowerCase() ?? ''}` : symbol),
|
|
259
|
+
ticker: ticker,
|
|
253
260
|
};
|
|
254
261
|
};
|