@swapkit/helpers 1.0.0-rc.51 → 1.0.0-rc.52
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
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
"use strict";var Te=Object.create;var D=Object.defineProperty;var ve=Object.getOwnPropertyDescriptor;var Se=Object.getOwnPropertyNames;var $e=Object.getPrototypeOf,Re=Object.prototype.hasOwnProperty;var Ie=(s,e,t)=>e in s?D(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t;var Be=(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)):{},Be(e||!s||!s.__esModule?D(t,"default",{value:s,enumerable:!0}):t,s));var p=(s,e,t)=>(Ie(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},Pe=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 Pe(e);default:return i.BaseDecimal[s]}},Ve={[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"}},ke=s=>{var c;const[e,...t]=s.split("."),n=s.includes("/"),r=t.join("."),a=(c=r==null?void 0:r.split("-"))==null?void 0:c[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),c=n.mul(a),o=r.mul(r).mul(2),u=r.mul(n).mul(2),h=n.mul(n),l=r.mul(r).mul(r);return c.mul(o.sub(u).add(h)).div(l)},ue=({liquidityUnits:s,poolUnits:e,assetDepth:t})=>{const n=m(s),r=m(e),a=m(t),c=n.mul(a),o=r.mul(r).mul(2),u=r.mul(n).mul(2),h=n.mul(n),l=c.mul(o.sub(u).add(h)),f=r.mul(r).mul(r);return l.div(f)},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=>g.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,c])=>[a,c.mul(r)])),Ue=({runeDepth:s,poolUnits:e,assetDepth:t,liquidityUnits:n,runeAmount:r,assetAmount:a})=>{const c=new g({value:s,decimal:8}),o=new g({value:t,decimal:8}),u=new g({value:e,decimal:8}),h=new g({value:r,decimal:8}),l=new g({value:a,decimal:8}),f=h.mul(o),V=l.mul(c),ye=h.mul(l),be=c.mul(o),Ce=u.mul(f.add(V.add(ye.mul(2)))),we=f.add(V.add(be.mul(2))),Q=Ce.div(we),k=m(n).add(Q);if(Q.getBaseValue("number")===0)return k.div(u).getBaseValue("number");const Ae=u.add(k);return k.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),c=m(e),o=m(s),u=c.mul(r).sub(a.mul(o)),h=a.mul(o).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}:${((o,u)=>{switch(o){case i.Chain.Litecoin:return"l";case i.Chain.Dogecoin:return"d";case i.Chain.BitcoinCash:return"c";default:return`${o}.${u}`}})(t,n)}:${r||""}:t:0`}case i.MemoType.WITHDRAW:{const{chain:t,ticker:n,symbol:r,basisPoints:a,targetAssetString:c,singleSide:o}=e,u=!o&&c?`:${c}`:"",h=Ge({chain:t,symbol:r,ticker:n});return`${s}:${t}${o?"/":"."}${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||"",c=`${r} ${a}`.trim(),o=c?`status code ${c}`:"an unknown error";super(`Request failed with ${o}`),Object.defineProperty(this,"response",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"request",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"options",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.name="HTTPError",this.response=e,this.request=t,this.options=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,c]of r.entries())n&&c==="undefined"||c===void 0?t.delete(a):t.set(a,c);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 c=setTimeout(()=>{t&&t.abort(),a(new he(s))},n.timeout);n.fetch(s,e).then(r).catch(a).then(()=>{clearTimeout(c)})})}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 o=await n._fetch();for(const u of n._options.hooks.afterResponse){const h=await u(n.request,n._options,n._decorateResponse(o.clone()));h instanceof globalThis.Response&&(o=h)}if(n._decorateResponse(o),!o.ok&&n._options.throwHttpErrors){let u=new X(o,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(o.clone(),n._options.onDownloadProgress)}return o},c=n._options.retry.methods.includes(n.request.method.toLowerCase())?n._retry(r):r();for(const[o,u]of Object.entries(tt))c[o]=async()=>{n.request.headers.set("accept",n.request.headers.get("accept")||u);const l=(await c).clone();if(o==="json"){if(l.status===204||(await l.clone().arrayBuffer()).byteLength===0)return"";if(t.parseJson)return t.parseJson(await l.text())}return l[o]()};return c}constructor(e,t={}){if(Object.defineProperty(this,"request",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"abortController",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_retryCount",{enumerable:!0,configurable:!0,writable:!0,value:0}),Object.defineProperty(this,"_input",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_options",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this._input=e,this._options={credentials:this._input.credentials||"same-origin",...t,headers:de(this._input.headers,t.headers),hooks:Y({beforeRequest:[],beforeRetry:[],beforeError:[],afterResponse:[]},t.hooks),method: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 c=e.body.getReader();t&&t({percent:0,transferredBytes:0,totalBytes:n},new Uint8Array);async function o(){const{done:u,value:h}=await c.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 o()}await o()}}),{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 c=r.length-t;let o=r.slice(-t);return parseInt(o[e])>=5?o=`${o.substring(0,e-1)}${(parseInt(o[e-1])+1).toString()}`:o=o.substring(0,e),`${n?"-":""}${r.slice(0,c)}.${o}`.replace(/\.?0*$/,"")}var C,S,_,A,P,_e,I,L,B,F;const J=class J{constructor(e){w(this,C);w(this,_);w(this,P);w(this,I);w(this,B);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,P,_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,B,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 o=parseInt(a),u=`${o}`.slice(0,e);return`0.${u.padStart(a.length-`${o}`.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 c=parseInt(a),o=`${c}`.slice(0,e);return`0.${o.padStart(a.length-`${c}`.length+o.length,"0")}`}toAbbreviation(e=2){const t=this.getValue("number"),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 c=10**(r*3);return`${(t/c).toFixed(e)}${a}`}toCurrency(e="$",{currencyPosition:t="start",decimal:n=2,decimalSeparator:r=".",thousandSeparator:a=","}={}){const c=this.getValue("number"),[o,u=""]=c.toFixed(6).split("."),h=o.replace(/\B(?=(\d{3})+(?!\d))/g,a),l=!o&&!u?"0.00":o==="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,c=e.toString().substring(a?1:0),o=r-(c.length-1),u=o>0?"0".repeat(o)+c:c,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,I,L).call(this,this,...t),r=Math.max(n,v(this.decimalMultiplier)),a=b(r),c=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),o=R({bigIntDecimal:r,decimal:r,value:c});return new this.constructor({decimalMultiplier:b(r),decimal:this.decimal,value:o,identifier:this.toString()})},_=new WeakSet,A=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}},P=new WeakSet,_e=function(e){const t=O(e)||"0";this.bigIntValue=d(this,B,F).call(this,t)},I=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,$)},B=new WeakSet,F=function(e,t){const n=t?b(t):this.decimalMultiplier,r=v(n),[a="",c=""]=e.split(".");return BigInt(`${a}${c.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,c]=t.split(".");if(!r||!a)throw new Error("Invalid asset url");const o=r===i.Chain.THORChain&&c?`${r}.${a}/${c}`:t;return j(o,n)}static fromString(t,n=0){return j(t,n)}static fromStringSync(t,n=0){const{isSynthetic:r}=G(t),{tax:a,decimal:c,identifier:o}=ne(t),u=q(n,c);return o?new y({tax:a,decimal:c,identifier:o,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),c=q(n,r);return new y({decimal:r,identifier:a,value:c})}static fromChainOrSignature(t,n=0){const{decimal:r,identifier:a}=ae(t),c=q(n,r);return new y({value:c,decimal:r,identifier:a})}static loadStaticAssets(){return new Promise(async(t,n)=>{try{const r=await import("@swapkit/tokens");W=Object.values(r).reduce((c,o)=>{var u;return(u=o==null?void 0:o.tokens)==null||u.forEach(({identifier:h,chain:l,...f})=>{c.set(h,{identifier:h,decimal:"decimals"in f?f.decimals:i.BaseDecimal[l]})}),c},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,c]=r.split("."),[o,u]=(e?n:c).split("-");return{address:u==null?void 0:u.toLowerCase(),chain:a,isGasAsset:K({chain:a,symbol:c}),isSynthetic:e,symbol:(e?`${t}/`:"")+(u?`${o}-${(u==null?void 0:u.toLowerCase())??""}`:c),ticker:o}},_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 g extends T{eq(e){return this.eqValue(e)}static fromBigInt(e,t){return new g({decimal:t,value:R({value:e,bigIntDecimal:t,decimal:t})})}}exports.AssetValue=y;exports.BigIntArithmetics=T;exports.RequestClient=ge;exports.SwapKitError=z;exports.SwapKitNumber=g;exports.assetFromString=ke;exports.derivationPathToString=Je;exports.filterAssets=je;exports.formatBigIntToSafeValue=R;exports.gasFeeMultiplier=Ve;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;
|
|
1
|
+
"use strict";var Te=Object.create;var D=Object.defineProperty;var ve=Object.getOwnPropertyDescriptor;var Se=Object.getOwnPropertyNames;var $e=Object.getPrototypeOf,Re=Object.prototype.hasOwnProperty;var Ie=(s,e,t)=>e in s?D(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t;var Be=(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)):{},Be(e||!s||!s.__esModule?D(t,"default",{value:s,enumerable:!0}):t,s));var p=(s,e,t)=>(Ie(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},Pe=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 Pe(e);default:return i.BaseDecimal[s]}},Ve={[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"}},ke=s=>{var c;const[e,...t]=s.split("."),n=s.includes("/"),r=t.join("."),a=(c=r==null?void 0:r.split("-"))==null?void 0:c[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),c=n.mul(a),o=r.mul(r).mul(2),u=r.mul(n).mul(2),h=n.mul(n),l=r.mul(r).mul(r);return c.mul(o.sub(u).add(h)).div(l)},ue=({liquidityUnits:s,poolUnits:e,assetDepth:t})=>{const n=m(s),r=m(e),a=m(t),c=n.mul(a),o=r.mul(r).mul(2),u=r.mul(n).mul(2),h=n.mul(n),l=c.mul(o.sub(u).add(h)),f=r.mul(r).mul(r);return l.div(f)},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=>g.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,c])=>[a,c.mul(r)])),Ue=({runeDepth:s,poolUnits:e,assetDepth:t,liquidityUnits:n,runeAmount:r,assetAmount:a})=>{const c=new g({value:s,decimal:8}),o=new g({value:t,decimal:8}),u=new g({value:e,decimal:8}),h=new g({value:r,decimal:8}),l=new g({value:a,decimal:8}),f=h.mul(o),V=l.mul(c),ye=h.mul(l),be=c.mul(o),Ce=u.mul(f.add(V.add(ye.mul(2)))),we=f.add(V.add(be.mul(2))),Q=Ce.div(we),k=m(n).add(Q);if(Q.getBaseValue("number")===0)return k.div(u).getBaseValue("number");const Ae=u.add(k);return k.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),c=m(e),o=m(s),u=c.mul(r).sub(a.mul(o)),h=a.mul(o).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}:${((o,u)=>{switch(o){case i.Chain.Litecoin:return"l";case i.Chain.Dogecoin:return"d";case i.Chain.BitcoinCash:return"c";default:return`${o}.${u}`}})(t,n)}:${r||""}:t:0`}case i.MemoType.WITHDRAW:{const{chain:t,ticker:n,symbol:r,basisPoints:a,targetAssetString:c,singleSide:o}=e,u=!o&&c?`:${c}`:"",h=Ge({chain:t,symbol:r,ticker:n});return`${s}:${t}${o?"/":"."}${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||"",c=`${r} ${a}`.trim(),o=c?`status code ${c}`:"an unknown error";super(`Request failed with ${o}`),Object.defineProperty(this,"response",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"request",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"options",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.name="HTTPError",this.response=e,this.request=t,this.options=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,c]of r.entries())n&&c==="undefined"||c===void 0?t.delete(a):t.set(a,c);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 c=setTimeout(()=>{t&&t.abort(),a(new he(s))},n.timeout);n.fetch(s,e).then(r).catch(a).then(()=>{clearTimeout(c)})})}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 o=await n._fetch();for(const u of n._options.hooks.afterResponse){const h=await u(n.request,n._options,n._decorateResponse(o.clone()));h instanceof globalThis.Response&&(o=h)}if(n._decorateResponse(o),!o.ok&&n._options.throwHttpErrors){let u=new X(o,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(o.clone(),n._options.onDownloadProgress)}return o},c=n._options.retry.methods.includes(n.request.method.toLowerCase())?n._retry(r):r();for(const[o,u]of Object.entries(tt))c[o]=async()=>{n.request.headers.set("accept",n.request.headers.get("accept")||u);const l=(await c).clone();if(o==="json"){if(l.status===204||(await l.clone().arrayBuffer()).byteLength===0)return"";if(t.parseJson)return t.parseJson(await l.text())}return l[o]()};return c}constructor(e,t={}){if(Object.defineProperty(this,"request",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"abortController",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_retryCount",{enumerable:!0,configurable:!0,writable:!0,value:0}),Object.defineProperty(this,"_input",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_options",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this._input=e,this._options={credentials:this._input.credentials||"same-origin",...t,headers:de(this._input.headers,t.headers),hooks:Y({beforeRequest:[],beforeRetry:[],beforeError:[],afterResponse:[]},t.hooks),method: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 c=e.body.getReader();t&&t({percent:0,transferredBytes:0,totalBytes:n},new Uint8Array);async function o(){const{done:u,value:h}=await c.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 o()}await o()}}),{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=$}){if(t===0)return s.toString();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 c=r.length-t;let o=r.slice(-t);return parseInt(o[e])>=5?o=`${o.substring(0,e-1)}${(parseInt(o[e-1])+1).toString()}`:o=o.substring(0,e),`${n?"-":""}${r.slice(0,c)}.${o}`.replace(/\.?0*$/,"")}var C,S,_,A,P,_e,I,L,B,F;const J=class J{constructor(e){w(this,C);w(this,_);w(this,P);w(this,I);w(this,B);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,P,_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,B,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 o=parseInt(a),u=`${o}`.slice(0,e);return`0.${u.padStart(a.length-`${o}`.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 c=parseInt(a),o=`${c}`.slice(0,e);return`0.${o.padStart(a.length-`${c}`.length+o.length,"0")}`}toAbbreviation(e=2){const t=this.getValue("number"),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 c=10**(r*3);return`${(t/c).toFixed(e)}${a}`}toCurrency(e="$",{currencyPosition:t="start",decimal:n=2,decimalSeparator:r=".",thousandSeparator:a=","}={}){const c=this.getValue("number"),[o,u=""]=c.toFixed(6).split("."),h=o.replace(/\B(?=(\d{3})+(?!\d))/g,a),l=!o&&!u?"0.00":o==="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,c=e.toString().substring(a?1:0),o=r-(c.length-1),u=o>0?"0".repeat(o)+c:c,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,I,L).call(this,this,...t),r=Math.max(n,v(this.decimalMultiplier)),a=b(r),c=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),o=R({bigIntDecimal:r,decimal:r,value:c});return new this.constructor({decimalMultiplier:b(r),decimal:this.decimal,value:o,identifier:this.toString()})},_=new WeakSet,A=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}},P=new WeakSet,_e=function(e){const t=O(e)||"0";this.bigIntValue=d(this,B,F).call(this,t)},I=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,$)},B=new WeakSet,F=function(e,t){const n=t?b(t):this.decimalMultiplier,r=v(n),[a="",c=""]=e.split(".");return BigInt(`${a}${c.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,c]=t.split(".");if(!r||!a)throw new Error("Invalid asset url");const o=r===i.Chain.THORChain&&c?`${r}.${a}/${c}`:t;return j(o,n)}static fromString(t,n=0){return j(t,n)}static fromStringSync(t,n=0){const{isSynthetic:r}=G(t),{tax:a,decimal:c,identifier:o}=ne(t),u=q(n,c);return o?new y({tax:a,decimal:c,identifier:o,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),c=q(n,r);return new y({decimal:r,identifier:a,value:c})}static fromChainOrSignature(t,n=0){const{decimal:r,identifier:a}=ae(t),c=q(n,r);return new y({value:c,decimal:r,identifier:a})}static loadStaticAssets(){return new Promise(async(t,n)=>{try{const r=await import("@swapkit/tokens");W=Object.values(r).reduce((c,o)=>{var u;return(u=o==null?void 0:o.tokens)==null||u.forEach(({identifier:h,chain:l,...f})=>{c.set(h,{identifier:h,decimal:"decimals"in f?f.decimals:i.BaseDecimal[l]})}),c},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,c]=r.split("."),[o,u]=(e?n:c).split("-");return{address:u==null?void 0:u.toLowerCase(),chain:a,isGasAsset:K({chain:a,symbol:c}),isSynthetic:e,symbol:(e?`${t}/`:"")+(u?`${o}-${(u==null?void 0:u.toLowerCase())??""}`:c),ticker:o}},_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 g extends T{eq(e){return this.eqValue(e)}static fromBigInt(e,t){return new g({decimal:t,value:R({value:e,bigIntDecimal:t,decimal:t})})}}exports.AssetValue=y;exports.BigIntArithmetics=T;exports.RequestClient=ge;exports.SwapKitError=z;exports.SwapKitNumber=g;exports.assetFromString=ke;exports.derivationPathToString=Je;exports.filterAssets=je;exports.formatBigIntToSafeValue=R;exports.gasFeeMultiplier=Ve;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;
|
|
2
2
|
//# sourceMappingURL=index.cjs.map
|