@swapkit/helpers 1.0.0-rc.54 → 1.0.0-rc.55

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 At=Object.create;var N=Object.defineProperty;var Tt=Object.getOwnPropertyDescriptor;var vt=Object.getOwnPropertyNames;var St=Object.getPrototypeOf,$t=Object.prototype.hasOwnProperty;var Rt=(n,t,e)=>t in n?N(n,t,{enumerable:!0,configurable:!0,writable:!0,value:e}):n[t]=e;var Bt=(n,t,e,s)=>{if(t&&typeof t=="object"||typeof t=="function")for(let r of vt(t))!$t.call(n,r)&&r!==e&&N(n,r,{get:()=>t[r],enumerable:!(s=Tt(t,r))||s.enumerable});return n};var It=(n,t,e)=>(e=n!=null?At(St(n)):{},Bt(t||!n||!n.__esModule?N(e,"default",{value:n,enumerable:!0}):e,n));var p=(n,t,e)=>(Rt(n,typeof t!="symbol"?t+"":t,e),e),Ot=(n,t,e)=>{if(!t.has(n))throw TypeError("Cannot "+e)};var w=(n,t,e)=>{if(t.has(n))throw TypeError("Cannot add the same private member more than once");t instanceof WeakSet?t.add(n):t.set(n,e)};var d=(n,t,e)=>(Ot(n,t,"access private method"),e);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const i=require("@swapkit/types"),Mt="0x313ce567",nt=async({chain:n,to:t})=>{try{const{result:e}=await ft.post(i.ChainToRPC[n],{headers:{accept:"*/*","content-type":"application/json","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[n]}},Et=async n=>{if(n===i.Chain.Ethereum)return i.BaseDecimal.ETH;const[,t]=n.split("-");return t!=null&&t.startsWith("0x")?nt({chain:i.Chain.Ethereum,to:t}):i.BaseDecimal.ETH},qt=async n=>{const[,t]=n.split("-");return t!=null&&t.startsWith("0x")?nt({chain:i.Chain.Avalanche,to:t.toLowerCase()}):i.BaseDecimal.AVAX},xt=async n=>(n===i.Chain.BinanceSmartChain,i.BaseDecimal.BSC),rt=async({chain:n,symbol:t})=>{switch(n){case i.Chain.Ethereum:return Et(t);case i.Chain.Avalanche:return qt(t);case i.Chain.BinanceSmartChain:return xt(t);default:return i.BaseDecimal[n]}},Pt={[i.FeeOption.Average]:1.2,[i.FeeOption.Fast]:1.5,[i.FeeOption.Fastest]:2},K=({chain:n,symbol:t})=>{switch(n){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===n;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"}},it=n=>{switch(n){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[n]};case i.Chain.THORChain:return{identifier:"THOR.RUNE",decimal:i.BaseDecimal[n]};case i.Chain.BinanceSmartChain:return{identifier:"BSC.BNB",decimal:i.BaseDecimal[n]};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:`${n}.${n}`,decimal:i.BaseDecimal[n]}}},at=({chain:n,symbol:t})=>{if(t.includes("/"))return"Synth";switch(n){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"}},Vt=n=>{var c;const[t,...e]=n.split("."),s=n.includes("/"),r=e.join("."),a=(c=r==null?void 0:r.split("-"))==null?void 0:c[0];return{chain:t,symbol:r,ticker:a,synth:s}},kt=new RegExp(/(.)\1{6}|\.ORG|\.NET|\.FINANCE|\.COM|WWW|HTTP|\\\\|\/\/|[\s$%:[\]]/,"gmi"),Dt=n=>{const[t,e]=n.split(".");if(!i.EVMChainList.includes(t))return!0;const[,s]=e.split("-");return K({chain:t,symbol:e})||!!s},Nt=n=>n.filter(t=>{const e=`${t.chain}.${t.symbol}`;return!kt.test(e)&&Dt(e)&&t.value!=="0"});function ot({liquidityUnits:n,poolUnits:t,runeDepth:e}){const s=m(n),r=m(t),a=m(e),c=s.mul(a),o=r.mul(r).mul(2),u=r.mul(s).mul(2),h=s.mul(s),l=r.mul(r).mul(r);return c.mul(o.sub(u).add(h)).div(l)}function ct({liquidityUnits:n,poolUnits:t,assetDepth:e}){const s=m(n),r=m(t),a=m(e),c=s.mul(a),o=r.mul(r).mul(2),u=r.mul(s).mul(2),h=s.mul(s),l=c.mul(o.sub(u).add(h)),C=r.mul(r).mul(r);return l.div(C)}function jt({percent:n,runeDepth:t,liquidityUnits:e,poolUnits:s}){return ot({runeDepth:t,liquidityUnits:e,poolUnits:s}).mul(n)}function Ht({percent:n,assetDepth:t,liquidityUnits:e,poolUnits:s}){return ct({assetDepth:t,liquidityUnits:e,poolUnits:s}).mul(n)}function m(n){return f.fromBigInt(BigInt(n),i.BaseDecimal.THOR)}function ut({liquidityUnits:n,poolUnits:t,runeDepth:e,assetDepth:s}){return{assetAmount:m(s).mul(n).div(t),runeAmount:m(e).mul(n).div(t)}}function Ut({liquidityUnits:n,poolUnits:t,runeDepth:e,assetDepth:s,percent:r}){return Object.fromEntries(Object.entries(ut({liquidityUnits:n,poolUnits:t,runeDepth:e,assetDepth:s})).map(([a,c])=>[a,c.mul(r)]))}function Lt({runeDepth:n,poolUnits:t,assetDepth:e,liquidityUnits:s,runeAmount:r,assetAmount:a}){const c=new f({value:n,decimal:8}),o=new f({value:e,decimal:8}),u=new f({value:t,decimal:8}),h=new f({value:r,decimal:8}),l=new f({value:a,decimal:8}),C=h.mul(o),k=l.mul(c),_t=h.mul(l),yt=c.mul(o),bt=u.mul(C.add(k.add(_t.mul(2)))),Ct=C.add(k.add(yt.mul(2))),Q=bt.div(Ct),D=m(s).add(Q);if(Q.getBaseValue("number")===0)return D.div(u).getBaseValue("number");const wt=u.add(D);return D.div(wt).getBaseValue("number")}function Ft({runeAmount:n,assetAmount:t,runeDepth:e,assetDepth:s}){if(n==="0"||t==="0"||e==="0"||s==="0")return 0;const r=m(e),a=m(s),c=m(t),o=m(n),u=c.mul(r).sub(a.mul(o)),h=a.mul(o).add(r.mul(a));return Math.abs(u.div(h).getBaseValue("number"))}const Wt=(n,t)=>{switch(n){case i.MemoType.LEAVE:case i.MemoType.BOND:{const{address:e}=t;return`${n}:${e}`}case i.MemoType.UNBOND:{const{address:e,unbondAmount:s}=t;return`${n}:${e}:${s*10**8}`}case i.MemoType.THORNAME_REGISTER:{const{name:e,chain:s,address:r,owner:a}=t;return`${n}:${e}:${s}:${r}${a?`:${a}`:""}`}case i.MemoType.DEPOSIT:{const{chain:e,symbol:s,address:r,singleSide:a}=t;return a?`${n}:${e}/${s}::t:0`:`${n}:${((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}`}})(e,s)}:${r||""}:t:0`}case i.MemoType.WITHDRAW:{const{chain:e,ticker:s,symbol:r,basisPoints:a,targetAssetString:c,singleSide:o}=t,u=e==="ETH"&&s!=="ETH"?`${s}-${r.slice(-3)}`:r,h=!o&&c?`:${c}`:"";return`${n}:${e}${o?"/":"."}${u}:${a}${h}`}case i.MemoType.OPEN_LOAN:case i.MemoType.CLOSE_LOAN:{const{asset:e,address:s}=t;return`${n}:${e}:${s}`}default:return""}};function Gt(n){if(n<0)throw new Error("Invalid number of year");return 10+n}function Kt(n){if(n.length>30)return!1;const t=/^[a-zA-Z0-9+_-]+$/g;return!!n.match(t)}function Yt([n,t,e,s,r]){return`${n}'/${t}'/${e}'/${s}${typeof r!="number"?"":`/${r}`}`}class X extends Error{constructor(t,e,s){const r=t.status||t.status===0?t.status:"",a=t.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=t,this.request=e,this.options=s}}class lt 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 q=n=>n!==null&&typeof n=="object",M=(...n)=>{for(const t of n)if((!q(t)||Array.isArray(t))&&t!==void 0)throw new TypeError("The `options` argument must be an object");return Y({},...n)},ht=(n={},t={})=>{const e=new globalThis.Headers(n),s=t instanceof globalThis.Headers,r=new globalThis.Headers(t);for(const[a,c]of r.entries())s&&c==="undefined"||c===void 0?e.delete(a):e.set(a,c);return e},Y=(...n)=>{let t={},e={};for(const s of n)if(Array.isArray(s))Array.isArray(t)||(t=[]),t=[...t,...s];else if(q(s)){for(let[r,a]of Object.entries(s))q(a)&&r in t&&(a=Y(t[r],a)),t={...t,[r]:a};q(s.headers)&&(e=ht(e,s.headers),t.headers=e)}return t},zt=(()=>{let n=!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 n=!0,"half"}}).headers.has("Content-Type")),n&&!t})(),Jt=typeof globalThis.AbortController=="function",Qt=typeof globalThis.ReadableStream=="function",Xt=typeof globalThis.FormData=="function",dt=["get","post","put","patch","head","delete"],Zt={json:"application/json",text:"text/*",formData:"multipart/form-data",arrayBuffer:"*/*",blob:"*/*"},j=2147483647,mt=Symbol("stop"),te={json:!0,parseJson:!0,searchParams:!0,prefixUrl:!0,retry:!0,timeout:!0,hooks:!0,throwHttpErrors:!0,onDownloadProgress:!0,fetch:!0},ee={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},se=n=>dt.includes(n)?n.toUpperCase():n,ne=["get","put","head","delete","options","trace"],re=[408,413,429,500,502,503,504],pt=[413,429,503],Z={limit:2,methods:ne,statusCodes:re,afterStatusCodes:pt,maxRetryAfter:Number.POSITIVE_INFINITY,backoffLimit:Number.POSITIVE_INFINITY,delay:n=>.3*2**(n-1)*1e3},ie=(n={})=>{if(typeof n=="number")return{...Z,limit:n};if(n.methods&&!Array.isArray(n.methods))throw new Error("retry.methods must be an array");if(n.statusCodes&&!Array.isArray(n.statusCodes))throw new Error("retry.statusCodes must be an array");return{...Z,...n,afterStatusCodes:pt}};async function ae(n,t,e,s){return new Promise((r,a)=>{const c=setTimeout(()=>{e&&e.abort(),a(new lt(n))},s.timeout);s.fetch(n,t).then(r).catch(a).then(()=>{clearTimeout(c)})})}async function oe(n,{signal:t}){return new Promise((e,s)=>{t&&(t.throwIfAborted(),t.addEventListener("abort",r,{once:!0}));function r(){clearTimeout(a),s(t.reason)}const a=setTimeout(()=>{t==null||t.removeEventListener("abort",r),e()},n)})}const ce=(n,t)=>{const e={};for(const s in t)!(s in ee)&&!(s in te)&&!(s in n)&&(e[s]=t[s]);return e};class P{static create(t,e){const s=new P(t,e),r=async()=>{if(typeof s._options.timeout=="number"&&s._options.timeout>j)throw new RangeError(`The \`timeout\` option cannot be greater than ${j}`);await Promise.resolve();let o=await s._fetch();for(const u of s._options.hooks.afterResponse){const h=await u(s.request,s._options,s._decorateResponse(o.clone()));h instanceof globalThis.Response&&(o=h)}if(s._decorateResponse(o),!o.ok&&s._options.throwHttpErrors){let u=new X(o,s.request,s._options);for(const h of s._options.hooks.beforeError)u=await h(u);throw u}if(s._options.onDownloadProgress){if(typeof s._options.onDownloadProgress!="function")throw new TypeError("The `onDownloadProgress` option must be a function");if(!Qt)throw new Error("Streams are not supported in your environment. `ReadableStream` is missing.");return s._stream(o.clone(),s._options.onDownloadProgress)}return o},c=s._options.retry.methods.includes(s.request.method.toLowerCase())?s._retry(r):r();for(const[o,u]of Object.entries(Zt))c[o]=async()=>{s.request.headers.set("accept",s.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(e.parseJson)return e.parseJson(await l.text())}return l[o]()};return c}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:ht(this._input.headers,e.headers),hooks:Y({beforeRequest:[],beforeRetry:[],beforeError:[],afterResponse:[]},e.hooks),method:se(e.method??this._input.method),prefixUrl:String(e.prefixUrl||""),retry:ie(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(Jt){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(zt&&(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);(Xt&&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 lt)){if(t instanceof X){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 r=Number(s);return Number.isNaN(r)?r=Date.parse(s)-Date.now():r*=1e3,this._options.retry.maxRetryAfter!==void 0&&r>this._options.retry.maxRetryAfter?0:r}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),j);if(s!==0&&this._retryCount>0){await oe(s,{signal:this._options.signal});for(const r of this._options.hooks.beforeRetry)if(await r({request:this.request,options:this._options,error:e,retryCount:this._retryCount})===mt)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=ce(this.request,this._options);return this._options.timeout===!1?this._options.fetch(this.request.clone(),t):ae(this.request.clone(),t,this.abortController,this._options)}_stream(t,e){const s=Number(t.headers.get("content-length"))||0;let r=0;return t.status===204?(e&&e({percent:1,totalBytes:s,transferredBytes:r},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 c=t.body.getReader();e&&e({percent:0,transferredBytes:0,totalBytes:s},new Uint8Array);async function o(){const{done:u,value:h}=await c.read();if(u){a.close();return}if(e){r+=h.byteLength;const l=s===0?0:r/s;e({percent:l,transferredBytes:r,totalBytes:s},h)}a.enqueue(h),await o()}await o()}}),{status:t.status,statusText:t.statusText,headers:t.headers})}}/*! MIT License © Sindre Sorhus */const U=n=>{const t=(e,s)=>P.create(e,M(n,s));for(const e of dt)t[e]=(s,r)=>P.create(s,M(n,r,{method:e}));return t.create=e=>U(M(e)),t.extend=e=>U(M(n,e)),t.stop=mt,t},ue=U(),le=ue,he=typeof window<"u"?{}:{referrer:"https://sk.thorswap.net",referer:"https://sk.thorswap.net"},tt=le.create({headers:he}),ft={get:(n,t)=>tt.get(n,t).json(),post:(n,t)=>tt.post(n,t).json()},et=[...Object.values(i.Chain),"TERRA"];function de(n=""){const t=n.toUpperCase(),[e]=t.split(".");if(et.includes(e))return!0;const[s]=t.split("/");if(et.includes(s))return!0;throw new Error(`Invalid identifier: ${n}. Expected format: <Chain>.<Ticker> or <Chain>.<Ticker>-<ContractAddress>`)}const $=8,_=n=>10n**BigInt(n),T=n=>Math.log10(parseFloat(n.toString()));function R({value:n,bigIntDecimal:t=$,decimal:e=$}){if(e===0)return n.toString();const s=n<0n;let r=n.toString().substring(s?1:0);const a=e-(r.length-1);a>0&&(r="0".repeat(a)+r);const c=r.length-e;let o=r.slice(-e);return parseInt(o[t])>=5?o=`${o.substring(0,t-1)}${(parseInt(o[t-1])+1).toString()}`:o=o.substring(0,t),`${s?"-":""}${r.slice(0,c)}.${o}`.replace(/\.?0*$/,"")}var y,v,g,A,V,gt,I,L,O,F;const J=class J{constructor(t){w(this,y);w(this,g);w(this,V);w(this,I);w(this,O);p(this,"decimalMultiplier",10n**8n);p(this,"bigIntValue",0n);p(this,"decimal");const e=W(t),s=typeof t=="object";this.decimal=s?t.decimal:void 0,this.decimalMultiplier=s&&"decimalMultiplier"in t?t.decimalMultiplier:_(Math.max(st(E(e)),this.decimal||0)),d(this,V,gt).call(this,e)}static fromBigInt(t,e){return new J({decimal:e,value:R({value:t,bigIntDecimal:e,decimal:e})})}static shiftDecimals({value:t,from:e,to:s}){return this.fromBigInt(t.getBaseValue("bigint")*_(s)/_(e),s)}set(t){return new this.constructor({decimal:this.decimal,value:t,identifier:this.toString()})}add(...t){return d(this,y,v).call(this,"add",...t)}sub(...t){return d(this,y,v).call(this,"sub",...t)}mul(...t){return d(this,y,v).call(this,"mul",...t)}div(...t){return d(this,y,v).call(this,"div",...t)}gt(t){return d(this,g,A).call(this,"gt",t)}gte(t){return d(this,g,A).call(this,"gte",t)}lt(t){return d(this,g,A).call(this,"lt",t)}lte(t){return d(this,g,A).call(this,"lte",t)}eqValue(t){return d(this,g,A).call(this,"eqValue",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;case"bigint":return this.bigIntValue*10n**BigInt(this.decimal||8n)/this.decimalMultiplier}}getBaseValue(t){const e=this.decimalMultiplier/_(this.decimal||i.BaseDecimal.THOR),s=this.bigIntValue/e;switch(t){case"number":return Number(s);case"string":return s.toString();case"bigint":return s}}getBigIntValue(t,e){if(!e&&typeof t=="object")return t.bigIntValue;const s=W(t),r=E(s);return r==="0"||r==="undefined"?0n:d(this,O,F).call(this,r,e)}toSignificant(t=6){const[e,s]=this.getValue("string").split("."),r=e||"",a=s||"";if((parseInt(r)?r.length+a.length:a.length)<=t)return this.getValue("string");if(r.length>=t)return r.slice(0,t).padEnd(r.length,"0");if(parseInt(r))return`${r}.${a.slice(0,t-r.length)}`.padEnd(t-r.length,"0");const o=parseInt(a),u=`${o}`.slice(0,t);return`0.${u.padStart(a.length-`${o}`.length+u.length,"0")}`}toFixed(t=6){const[e,s]=this.getValue("string").split("."),r=e||"",a=s||"";if(parseInt(r))return`${r}.${a.slice(0,t)}`.padEnd(t,"0");const c=parseInt(a),o=`${c}`.slice(0,t);return`0.${o.padStart(a.length-`${c}`.length+o.length,"0")}`}toAbbreviation(t=2){const e=this.getValue("number"),s=["","K","M","B","T","Q","Qi","S"],r=Math.floor(Math.log10(Math.abs(e))/3),a=s[r];if(!a)return this.getValue("string");const c=10**(r*3);return`${(e/c).toFixed(t)}${a}`}toCurrency(t="$",{currencyPosition:e="start",decimal:s=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,s)}`:""}`;return`${e==="start"?t:""}${l}${e==="end"?t:""}`}formatBigIntToSafeValue(t,e){const s=e||this.decimal||$,r=Math.max(s,T(this.decimalMultiplier)),a=t<0n,c=t.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[s])>=5?l=`${l.substring(0,s-1)}${(parseInt(l[s-1])+1).toString()}`:l=l.substring(0,s),`${a?"-":""}${u.slice(0,h)}.${l}`.replace(/\.?0*$/,"")}};y=new WeakSet,v=function(t,...e){const s=d(this,I,L).call(this,this,...e),r=Math.max(s,T(this.decimalMultiplier)),a=_(r),c=e.reduce((u,h)=>{const l=this.getBigIntValue(h,r);switch(t){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:_(r),decimal:this.decimal,value:o,identifier:this.toString()})},g=new WeakSet,A=function(t,...e){const s=d(this,I,L).call(this,this,...e),r=this.getBigIntValue(e[0],s),a=this.getBigIntValue(this,s);switch(t){case"gt":return a>r;case"gte":return a>=r;case"lt":return a<r;case"lte":return a<=r;case"eqValue":return a===r}},V=new WeakSet,gt=function(t){const e=E(t)||"0";this.bigIntValue=d(this,O,F).call(this,e)},I=new WeakSet,L=function(...t){const e=t.map(s=>typeof s=="object"?s.decimal||T(s.decimalMultiplier):st(E(s))).filter(Boolean);return Math.max(...e,$)},O=new WeakSet,F=function(t,e){const s=e?_(e):this.decimalMultiplier,r=T(s),[a="",c=""]=t.split(".");return BigInt(`${a}${c.padEnd(r,"0")}`)};let B=J;const me=Intl.NumberFormat("fullwide",{useGrouping:!1,maximumFractionDigits:20});function E(n){const e=`${typeof n=="number"?me.format(n):W(n)}`.replaceAll(",",".").split(".");return e.length>1?`${e.slice(0,-1).join("")}.${e.at(-1)}`:e[0]}function st(n){var e;const t=((e=n.split(".")[1])==null?void 0:e.length)||0;return Math.max(t,$)}function W(n){return typeof n=="object"?"getValue"in n?n.getValue("string"):n.value:n}const S=new Map;class b extends B{constructor({value:e,decimal:s,tax:r,chain:a,symbol:c,identifier:o}){super(typeof e=="object"?e:{decimal:s,value:e});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 u=G(o||`${a}.${c}`);this.type=at(u),this.tax=r,this.chain=u.chain,this.ticker=u.ticker,this.symbol=u.symbol,this.address=u.address,this.isSynthetic=u.isSynthetic,this.isGasAsset=u.isGasAsset}toString(){return this.isSynthetic?this.symbol:`${this.chain}.${this.symbol}`}toUrl(){return this.isSynthetic?`${this.chain}.${this.symbol.replace("/",".")}`:this.toString()}eq({chain:e,symbol:s}){return this.chain===e&&this.symbol===s}static fromUrl(e,s=0){const[r,a,c]=e.split(".");if(!r||!a)throw new Error("Invalid asset url");const o=r===i.Chain.THORChain&&c?`${r}.${a}/${c}`:e;return H(o,s)}static fromString(e,s=0){return H(e,s)}static fromIdentifier(e,s=0){return H(e,s)}static fromStringSync(e,s=0){const{isSynthetic:r}=G(e),a=S.get(e.toUpperCase());if(!a){console.error(`Asset ${e} is not loaded. Use AssetValue.loadStaticAssets() to load it`);return}const{tax:c,decimal:o,identifier:u}=a;return new b({tax:c,value:x(s,o),identifier:r?e:u,decimal:r?8:o})}static fromIdentifierSync(e,s=0){const r=S.get(e);if(!r){console.error(`Asset ${e} is not loaded. Use AssetValue.loadStaticAssets() to load it`);return}const{tax:a,decimal:c,identifier:o}=r;return new b({tax:a,decimal:c,identifier:o,value:x(s,c)})}static fromChainOrSignature(e,s=0){const{decimal:r,identifier:a}=it(e);return new b({value:x(s,r),decimal:r,identifier:a})}static loadStaticAssets(){return new Promise(async(e,s)=>{try{const r=await import("@swapkit/tokens");Object.values(r).forEach(a=>{var c;(c=a==null?void 0:a.tokens)==null||c.forEach(({identifier:o,chain:u,...h})=>{S.set(o.toUpperCase(),{identifier:o,decimal:"decimals"in h?h.decimals:i.BaseDecimal[u]})})}),e({ok:!0})}catch(r){console.error(r),s({ok:!1,error:r,message:"Couldn't load static assets. Ensure you have installed @swapkit/tokens package"})}})}}function pe(n){const t=b.fromChainOrSignature(n);switch(n){case i.Chain.Bitcoin:case i.Chain.Litecoin:case i.Chain.BitcoinCash:return t.set(10001e-8);case i.Chain.Dogecoin:return t.set(1.00000001);case i.Chain.Avalanche:case i.Chain.Ethereum:return t.set(1e-8);case i.Chain.THORChain:case i.Chain.Maya:return t.set(0);default:return t.set(1e-8)}}async function H(n,t=0){de(n);const e=S.get(n.toUpperCase()),s=(e==null?void 0:e.decimal)||await rt(G(n));return e||S.set(n.toUpperCase(),{identifier:n,decimal:s}),new b({decimal:s,value:x(t,s),identifier:n})}function x(n,t){return typeof n=="bigint"?R({value:n,bigIntDecimal:t,decimal:t}):n}function G(n){const t=n.slice(0,14).includes("/"),[e,s]=n.split(".").pop().split("/"),r=n.includes(".")&&!t?n:`${i.Chain.THORChain}.${s}`,[a,c]=r.split("."),[o,u]=(t?s:c).split("-");return{address:u==null?void 0:u.toLowerCase(),chain:a,isGasAsset:K({chain:a,symbol:c}),isSynthetic:t,symbol:(t?`${e}/`:"")+(u?`${o}-${(u==null?void 0:u.toLowerCase())??""}`:c),ticker:o}}const fe={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(t,e){console.error(e,{stack:e==null?void 0:e.stack,message:e==null?void 0:e.message}),super(t,{cause:{code:fe[t],message:t}}),Object.setPrototypeOf(this,z.prototype)}}class f extends B{eq(t){return this.eqValue(t)}static fromBigInt(t,e){return new f({decimal:e,value:R({value:t,bigIntDecimal:e,decimal:e})})}}exports.AssetValue=b;exports.BigIntArithmetics=B;exports.RequestClient=ft;exports.SwapKitError=z;exports.SwapKitNumber=f;exports.assetFromString=Vt;exports.derivationPathToString=Yt;exports.filterAssets=Nt;exports.formatBigIntToSafeValue=R;exports.gasFeeMultiplier=Pt;exports.getAssetType=at;exports.getAsymmetricAssetShare=ct;exports.getAsymmetricAssetWithdrawAmount=Ht;exports.getAsymmetricRuneShare=ot;exports.getAsymmetricRuneWithdrawAmount=jt;exports.getCommonAssetInfo=it;exports.getDecimal=rt;exports.getEstimatedPoolShare=Lt;exports.getLiquiditySlippage=Ft;exports.getMemoFor=Wt;exports.getMinAmountByChain=pe;exports.getSymmetricPoolShare=ut;exports.getSymmetricWithdraw=Ut;exports.getTHORNameCost=Gt;exports.isGasAsset=K;exports.validateTHORName=Kt;
1
+ "use strict";var Te=Object.create;var j=Object.defineProperty;var $e=Object.getOwnPropertyDescriptor;var ve=Object.getOwnPropertyNames;var Se=Object.getPrototypeOf,Re=Object.prototype.hasOwnProperty;var Be=(n,e,t)=>e in n?j(n,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):n[e]=t;var Ie=(n,e,t,s)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of ve(e))!Re.call(n,r)&&r!==t&&j(n,r,{get:()=>e[r],enumerable:!(s=$e(e,r))||s.enumerable});return n};var Oe=(n,e,t)=>(t=n!=null?Te(Se(n)):{},Ie(e||!n||!n.__esModule?j(t,"default",{value:n,enumerable:!0}):t,n));var p=(n,e,t)=>(Be(n,typeof e!="symbol"?e+"":e,t),t),Me=(n,e,t)=>{if(!e.has(n))throw TypeError("Cannot "+t)};var w=(n,e,t)=>{if(e.has(n))throw TypeError("Cannot add the same private member more than once");e instanceof WeakSet?e.add(n):e.set(n,t)};var d=(n,e,t)=>(Me(n,e,"access private method"),t);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const i=require("@swapkit/types"),Ee="0x313ce567",re=async({chain:n,to:e})=>{try{const{result:t}=await ge.post(i.ChainToRPC[n],{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[n]}},qe=async n=>{if(n===i.Chain.Ethereum)return i.BaseDecimal.ETH;const[,e]=n.split("-");return e!=null&&e.startsWith("0x")?re({chain:i.Chain.Ethereum,to:e}):i.BaseDecimal.ETH},xe=async n=>{const[,e]=n.split("-");return e!=null&&e.startsWith("0x")?re({chain:i.Chain.Avalanche,to:e.toLowerCase()}):i.BaseDecimal.AVAX},Pe=async n=>(n===i.Chain.BinanceSmartChain,i.BaseDecimal.BSC),ie=async({chain:n,symbol:e})=>{switch(n){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[n]}},Ve={[i.FeeOption.Average]:1.2,[i.FeeOption.Fast]:1.5,[i.FeeOption.Fastest]:2},K=({chain:n,symbol:e})=>{switch(n){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===n;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=n=>{switch(n){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[n]};case i.Chain.THORChain:return{identifier:"THOR.RUNE",decimal:i.BaseDecimal[n]};case i.Chain.BinanceSmartChain:return{identifier:"BSC.BNB",decimal:i.BaseDecimal[n]};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:`${n}.${n}`,decimal:i.BaseDecimal[n]}}},oe=({chain:n,symbol:e})=>{if(e.includes("/"))return"Synth";switch(n){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=n=>{var c;const[e,...t]=n.split("."),s=n.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:s}},De=new RegExp(/(.)\1{6}|\.ORG|\.NET|\.FINANCE|\.COM|WWW|HTTP|\\\\|\/\/|[\s$%:[\]]/,"gmi"),Ne=n=>{const[e,t]=n.split(".");if(!i.EVMChainList.includes(e))return!0;const[,s]=t.split("-");return K({chain:e,symbol:t})||!!s},je=n=>n.filter(e=>{const t=`${e.chain}.${e.symbol}`;return!De.test(t)&&Ne(t)&&e.value!=="0"});function ce({liquidityUnits:n,poolUnits:e,runeDepth:t}){const s=m(n),r=m(e),a=m(t),c=s.mul(a),o=r.mul(r).mul(2),u=r.mul(s).mul(2),l=s.mul(s),h=r.mul(r).mul(r);return c.mul(o.sub(u).add(l)).div(h)}function ue({liquidityUnits:n,poolUnits:e,assetDepth:t}){const s=m(n),r=m(e),a=m(t),c=s.mul(a),o=r.mul(r).mul(2),u=r.mul(s).mul(2),l=s.mul(s),h=c.mul(o.sub(u).add(l)),C=r.mul(r).mul(r);return h.div(C)}function He({percent:n,runeDepth:e,liquidityUnits:t,poolUnits:s}){return ce({runeDepth:e,liquidityUnits:t,poolUnits:s}).mul(n)}function Le({percent:n,assetDepth:e,liquidityUnits:t,poolUnits:s}){return ue({assetDepth:e,liquidityUnits:t,poolUnits:s}).mul(n)}function m(n){return f.fromBigInt(BigInt(n),i.BaseDecimal.THOR)}function le({liquidityUnits:n,poolUnits:e,runeDepth:t,assetDepth:s}){return{assetAmount:m(s).mul(n).div(e),runeAmount:m(t).mul(n).div(e)}}function Ue({liquidityUnits:n,poolUnits:e,runeDepth:t,assetDepth:s,percent:r}){return Object.fromEntries(Object.entries(le({liquidityUnits:n,poolUnits:e,runeDepth:t,assetDepth:s})).map(([a,c])=>[a,c.mul(r)]))}function Fe({runeDepth:n,poolUnits:e,assetDepth:t,liquidityUnits:s,runeAmount:r,assetAmount:a}){const c=new f({value:n,decimal:8}),o=new f({value:t,decimal:8}),u=new f({value:e,decimal:8}),l=new f({value:r,decimal:8}),h=new f({value:a,decimal:8}),C=l.mul(o),D=h.mul(c),ye=l.mul(h),be=c.mul(o),Ce=u.mul(C.add(D.add(ye.mul(2)))),we=C.add(D.add(be.mul(2))),Q=Ce.div(we),N=m(s).add(Q);if(Q.getBaseValue("number")===0)return N.div(u).getBaseValue("number");const Ae=u.add(N);return N.div(Ae).getBaseValue("number")}function We({runeAmount:n,assetAmount:e,runeDepth:t,assetDepth:s}){if(n==="0"||e==="0"||t==="0"||s==="0")return 0;const r=m(t),a=m(s),c=m(e),o=m(n),u=c.mul(r).sub(a.mul(o)),l=a.mul(o).add(r.mul(a));return Math.abs(u.div(l).getBaseValue("number"))}const Ge=(n,e)=>{switch(n){case i.MemoType.LEAVE:case i.MemoType.BOND:{const{address:t}=e;return`${n}:${t}`}case i.MemoType.UNBOND:{const{address:t,unbondAmount:s}=e;return`${n}:${t}:${s*10**8}`}case i.MemoType.THORNAME_REGISTER:{const{name:t,chain:s,address:r,owner:a}=e;return`${n}:${t}:${s}:${r}${a?`:${a}`:""}`}case i.MemoType.DEPOSIT:{const{chain:t,symbol:s,address:r,singleSide:a}=e;return a?`${n}:${t}/${s}::t:0`:`${n}:${((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,s)}:${r||""}:t:0`}case i.MemoType.WITHDRAW:{const{chain:t,ticker:s,symbol:r,basisPoints:a,targetAssetString:c,singleSide:o}=e,u=t==="ETH"&&s!=="ETH"?`${s}-${r.slice(-3)}`:r,l=!o&&c?`:${c}`:"";return`${n}:${t}${o?"/":"."}${u}:${a}${l}`}case i.MemoType.OPEN_LOAN:case i.MemoType.CLOSE_LOAN:{const{asset:t,address:s}=e;return`${n}:${t}:${s}`}default:return""}};function Ke(n){if(n<0)throw new Error("Invalid number of year");return 10+n}function Ye(n){if(n.length>30)return!1;const e=/^[a-zA-Z0-9+_-]+$/g;return!!n.match(e)}function ze([n,e,t,s,r]){return`${n}'/${e}'/${t}'/${s}${typeof r!="number"?"":`/${r}`}`}class X extends Error{constructor(e,t,s){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=s}}class he extends Error{constructor(e){super("Request timed out"),Object.defineProperty(this,"request",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.name="TimeoutError",this.request=e}}const x=n=>n!==null&&typeof n=="object",E=(...n)=>{for(const e of n)if((!x(e)||Array.isArray(e))&&e!==void 0)throw new TypeError("The `options` argument must be an object");return Y({},...n)},de=(n={},e={})=>{const t=new globalThis.Headers(n),s=e instanceof globalThis.Headers,r=new globalThis.Headers(e);for(const[a,c]of r.entries())s&&c==="undefined"||c===void 0?t.delete(a):t.set(a,c);return t},Y=(...n)=>{let e={},t={};for(const s of n)if(Array.isArray(s))Array.isArray(e)||(e=[]),e=[...e,...s];else if(x(s)){for(let[r,a]of Object.entries(s))x(a)&&r in e&&(a=Y(e[r],a)),e={...e,[r]:a};x(s.headers)&&(t=de(t,s.headers),e.headers=t)}return e},Je=(()=>{let n=!1,e=!1;const t=typeof globalThis.ReadableStream=="function",s=typeof globalThis.Request=="function";return t&&s&&(e=new globalThis.Request("https://empty.invalid",{body:new globalThis.ReadableStream,method:"POST",get duplex(){return n=!0,"half"}}).headers.has("Content-Type")),n&&!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:"*/*"},H=2147483647,pe=Symbol("stop"),tt={json:!0,parseJson:!0,searchParams:!0,prefixUrl:!0,retry:!0,timeout:!0,hooks:!0,throwHttpErrors:!0,onDownloadProgress:!0,fetch:!0},st={method:!0,headers:!0,body:!0,mode:!0,credentials:!0,cache:!0,redirect:!0,referrer:!0,referrerPolicy:!0,integrity:!0,keepalive:!0,signal:!0,window:!0,dispatcher:!0,duplex:!0},nt=n=>me.includes(n)?n.toUpperCase():n,rt=["get","put","head","delete","options","trace"],it=[408,413,429,500,502,503,504],fe=[413,429,503],Z={limit:2,methods:rt,statusCodes:it,afterStatusCodes:fe,maxRetryAfter:Number.POSITIVE_INFINITY,backoffLimit:Number.POSITIVE_INFINITY,delay:n=>.3*2**(n-1)*1e3},at=(n={})=>{if(typeof n=="number")return{...Z,limit:n};if(n.methods&&!Array.isArray(n.methods))throw new Error("retry.methods must be an array");if(n.statusCodes&&!Array.isArray(n.statusCodes))throw new Error("retry.statusCodes must be an array");return{...Z,...n,afterStatusCodes:fe}};async function ot(n,e,t,s){return new Promise((r,a)=>{const c=setTimeout(()=>{t&&t.abort(),a(new he(n))},s.timeout);s.fetch(n,e).then(r).catch(a).then(()=>{clearTimeout(c)})})}async function ct(n,{signal:e}){return new Promise((t,s)=>{e&&(e.throwIfAborted(),e.addEventListener("abort",r,{once:!0}));function r(){clearTimeout(a),s(e.reason)}const a=setTimeout(()=>{e==null||e.removeEventListener("abort",r),t()},n)})}const ut=(n,e)=>{const t={};for(const s in e)!(s in st)&&!(s in tt)&&!(s in n)&&(t[s]=e[s]);return t};class V{static create(e,t){const s=new V(e,t),r=async()=>{if(typeof s._options.timeout=="number"&&s._options.timeout>H)throw new RangeError(`The \`timeout\` option cannot be greater than ${H}`);await Promise.resolve();let o=await s._fetch();for(const u of s._options.hooks.afterResponse){const l=await u(s.request,s._options,s._decorateResponse(o.clone()));l instanceof globalThis.Response&&(o=l)}if(s._decorateResponse(o),!o.ok&&s._options.throwHttpErrors){let u=new X(o,s.request,s._options);for(const l of s._options.hooks.beforeError)u=await l(u);throw u}if(s._options.onDownloadProgress){if(typeof s._options.onDownloadProgress!="function")throw new TypeError("The `onDownloadProgress` option must be a function");if(!Xe)throw new Error("Streams are not supported in your environment. `ReadableStream` is missing.");return s._stream(o.clone(),s._options.onDownloadProgress)}return o},c=s._options.retry.methods.includes(s.request.method.toLowerCase())?s._retry(r):r();for(const[o,u]of Object.entries(et))c[o]=async()=>{s.request.headers.set("accept",s.request.headers.get("accept")||u);const h=(await c).clone();if(o==="json"){if(h.status===204||(await h.clone().arrayBuffer()).byteLength===0)return"";if(t.parseJson)return t.parseJson(await h.text())}return h[o]()};return c}constructor(e,t={}){if(Object.defineProperty(this,"request",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"abortController",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_retryCount",{enumerable:!0,configurable:!0,writable:!0,value:0}),Object.defineProperty(this,"_input",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_options",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this._input=e,this._options={credentials:this._input.credentials||"same-origin",...t,headers:de(this._input.headers,t.headers),hooks:Y({beforeRequest:[],beforeRetry:[],beforeError:[],afterResponse:[]},t.hooks),method:nt(t.method??this._input.method),prefixUrl:String(t.prefixUrl||""),retry: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 s=this._options.signal;this._options.signal.addEventListener("abort",()=>{this.abortController.abort(s.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 r="?"+(typeof this._options.searchParams=="string"?this._options.searchParams.replace(/^\?/,""):new URLSearchParams(this._options.searchParams).toString()),a=this.request.url.replace(/(?:\?.*?)?(?=#|$)/,r);(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 X){if(!this._options.retry.statusCodes.includes(e.response.status))return 0;const s=e.response.headers.get("Retry-After");if(s&&this._options.retry.afterStatusCodes.includes(e.response.status)){let r=Number(s);return Number.isNaN(r)?r=Date.parse(s)-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 s=Math.min(this._calculateRetryDelay(t),H);if(s!==0&&this._retryCount>0){await ct(s,{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 s=await t(this.request,this._options);if(s instanceof Request){this.request=s;break}if(s instanceof Response)return s}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 s=Number(e.headers.get("content-length"))||0;let r=0;return e.status===204?(t&&t({percent:1,totalBytes:s,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:s},new Uint8Array);async function o(){const{done:u,value:l}=await c.read();if(u){a.close();return}if(t){r+=l.byteLength;const h=s===0?0:r/s;t({percent:h,transferredBytes:r,totalBytes:s},l)}a.enqueue(l),await o()}await o()}}),{status:e.status,statusText:e.statusText,headers:e.headers})}}/*! MIT License © Sindre Sorhus */const U=n=>{const e=(t,s)=>V.create(t,E(n,s));for(const t of me)e[t]=(s,r)=>V.create(s,E(n,r,{method:t}));return e.create=t=>U(E(t)),e.extend=t=>U(E(n,t)),e.stop=pe,e},lt=U(),ht=lt,dt=typeof window<"u"?{}:{referrer:"https://sk.thorswap.net",referer:"https://sk.thorswap.net"},ee=ht.create({headers:dt}),ge={get:(n,e)=>ee.get(n,e).json(),post:(n,e)=>ee.post(n,e).json()},te=[...Object.values(i.Chain),"TERRA"];function mt(n=""){const e=n.toUpperCase(),[t]=e.split(".");if(te.includes(t))return!0;const[s]=e.split("/");if(te.includes(s))return!0;throw new Error(`Invalid identifier: ${n}. Expected format: <Chain>.<Ticker> or <Chain>.<Ticker>-<ContractAddress>`)}const R=8,y=n=>10n**BigInt(n),T=n=>Math.log10(parseFloat(n.toString()));function B({value:n,bigIntDecimal:e=R,decimal:t=R}){if(t===0)return n.toString();const s=n<0n;let r=n.toString().substring(s?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),`${s?"-":""}${r.slice(0,c)}.${o}`.replace(/\.?0*$/,"")}var b,$,g,A,k,_e,O,F,M,W;const J=class J{constructor(e){w(this,b);w(this,g);w(this,k);w(this,O);w(this,M);p(this,"decimalMultiplier",10n**8n);p(this,"bigIntValue",0n);p(this,"decimal");const t=G(e),s=typeof e=="object";this.decimal=s?e.decimal:void 0,this.decimalMultiplier=s&&"decimalMultiplier"in e?e.decimalMultiplier:y(Math.max(se(q(t)),this.decimal||0)),d(this,k,_e).call(this,t)}static fromBigInt(e,t){return new J({decimal:t,value:B({value:e,bigIntDecimal:t,decimal:t})})}static shiftDecimals({value:e,from:t,to:s}){return this.fromBigInt(e.getBaseValue("bigint")*y(s)/y(t),s)}set(e){return new this.constructor({decimal:this.decimal,value:e,identifier:this.toString()})}add(...e){return d(this,b,$).call(this,"add",...e)}sub(...e){return d(this,b,$).call(this,"sub",...e)}mul(...e){return d(this,b,$).call(this,"mul",...e)}div(...e){return d(this,b,$).call(this,"div",...e)}gt(e){return d(this,g,A).call(this,"gt",e)}gte(e){return d(this,g,A).call(this,"gte",e)}lt(e){return d(this,g,A).call(this,"lt",e)}lte(e){return d(this,g,A).call(this,"lte",e)}eqValue(e){return d(this,g,A).call(this,"eqValue",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;case"bigint":return this.bigIntValue*10n**BigInt(this.decimal||8n)/this.decimalMultiplier}}getBaseValue(e){const t=this.decimalMultiplier/y(this.decimal||i.BaseDecimal.THOR),s=this.bigIntValue/t;switch(e){case"number":return Number(s);case"string":return s.toString();case"bigint":return s}}getBigIntValue(e,t){if(!t&&typeof e=="object")return e.bigIntValue;const s=G(e),r=q(s);return r==="0"||r==="undefined"?0n:d(this,M,W).call(this,r,t)}toSignificant(e=6){const[t,s]=this.getValue("string").split("."),r=t||"",a=s||"";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,s]=this.getValue("string").split("."),r=t||"",a=s||"";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"),s=["","K","M","B","T","Q","Qi","S"],r=Math.floor(Math.log10(Math.abs(t))/3),a=s[r];if(!a)return this.getValue("string");const c=10**(r*3);return`${(t/c).toFixed(e)}${a}`}toCurrency(e="$",{currencyPosition:t="start",decimal:s=2,decimalSeparator:r=".",thousandSeparator:a=","}={}){const c=this.getValue("number"),[o,u=""]=c.toFixed(6).split("."),l=o.replace(/\B(?=(\d{3})+(?!\d))/g,a),h=!o&&!u?"0.00":o==="0"?`${parseFloat(`0.${u}`)}`.replace(".",r):`${l}${parseInt(u)?`${r}${u.slice(0,s)}`:""}`;return`${t==="start"?e:""}${h}${t==="end"?e:""}`}formatBigIntToSafeValue(e,t){const s=t||this.decimal||R,r=Math.max(s,T(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,l=u.length-r;let h=u.slice(-r);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*$/,"")}};b=new WeakSet,$=function(e,...t){const s=d(this,O,F).call(this,this,...t),r=Math.max(s,T(this.decimalMultiplier)),a=y(r),c=t.reduce((u,l)=>{const h=this.getBigIntValue(l,r);switch(e){case"add":return u+h;case"sub":return u-h;case"mul":return u*h/a;case"div":{if(h===0n)throw new RangeError("Division by zero");return u*a/h}default:return u}},this.bigIntValue*a/this.decimalMultiplier),o=B({bigIntDecimal:r,decimal:r,value:c});return new this.constructor({decimalMultiplier:y(r),decimal:this.decimal,value:o,identifier:this.toString()})},g=new WeakSet,A=function(e,...t){const s=d(this,O,F).call(this,this,...t),r=this.getBigIntValue(t[0],s),a=this.getBigIntValue(this,s);switch(e){case"gt":return a>r;case"gte":return a>=r;case"lt":return a<r;case"lte":return a<=r;case"eqValue":return a===r}},k=new WeakSet,_e=function(e){const t=q(e)||"0";this.bigIntValue=d(this,M,W).call(this,t)},O=new WeakSet,F=function(...e){const t=e.map(s=>typeof s=="object"?s.decimal||T(s.decimalMultiplier):se(q(s))).filter(Boolean);return Math.max(...t,R)},M=new WeakSet,W=function(e,t){const s=t?y(t):this.decimalMultiplier,r=T(s),[a="",c=""]=e.split(".");return BigInt(`${a}${c.padEnd(r,"0")}`)};let I=J;const pt=Intl.NumberFormat("fullwide",{useGrouping:!1,maximumFractionDigits:20});function q(n){const t=`${typeof n=="number"?pt.format(n):G(n)}`.replaceAll(",",".").split(".");return t.length>1?`${t.slice(0,-1).join("")}.${t.at(-1)}`:t[0]}function se(n){var t;const e=((t=n.split(".")[1])==null?void 0:t.length)||0;return Math.max(e,R)}function G(n){return typeof n=="object"?"getValue"in n?n.getValue("string"):n.value:n}const v=new Map;class _ extends I{constructor({value:t,decimal:s,tax:r,chain:a,symbol:c,identifier:o}){super(typeof t=="object"?t:{decimal:s,value:t});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 u=P(o||`${a}.${c}`);this.type=oe(u),this.tax=r,this.chain=u.chain,this.ticker=u.ticker,this.symbol=u.symbol,this.address=u.address,this.isSynthetic=u.isSynthetic,this.isGasAsset=u.isGasAsset}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:s}){return this.chain===t&&this.symbol===s}static fromUrl(t,s=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 L(o,s)}static fromString(t,s=0){return L(t,s)}static fromIdentifier(t,s=0){return L(t,s)}static fromStringSync(t,s=0){const{chain:r,isSynthetic:a}=P(t),c=v.get(t.toUpperCase());if(a)return ne(t,s);c||console.error(`Asset ${t} is not loaded. Use AssetValue.loadStaticAssets() to load it`);const{tax:o,decimal:u,identifier:l}=c||{decimal:i.BaseDecimal[r],identifier:t};return new _({tax:o,value:S(s,u),identifier:a?t:l,decimal:a?8:u})}static fromIdentifierSync(t,s=0){const{chain:r,isSynthetic:a}=P(t),c=v.get(t);if(a)return ne(t,s);c||console.error(`Asset ${t} is not loaded. - Loading with base Chain. Use AssetValue.loadStaticAssets() to load it`);const{tax:o,decimal:u,identifier:l}=c||{decimal:i.BaseDecimal[r],identifier:t};return new _({tax:o,decimal:u,identifier:l,value:S(s,u)})}static fromChainOrSignature(t,s=0){const{decimal:r,identifier:a}=ae(t);return new _({value:S(s,r),decimal:r,identifier:a})}static loadStaticAssets(){return new Promise(async(t,s)=>{try{const r=await import("@swapkit/tokens");Object.values(r).forEach(a=>{var c;(c=a==null?void 0:a.tokens)==null||c.forEach(({identifier:o,chain:u,...l})=>{v.set(o.toUpperCase(),{identifier:o,decimal:"decimals"in l?l.decimals:i.BaseDecimal[u]})})}),t({ok:!0})}catch(r){console.error(r),s({ok:!1,error:r,message:"Couldn't load static assets. Ensure you have installed @swapkit/tokens package"})}})}}function ft(n){const e=_.fromChainOrSignature(n);switch(n){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)}}async function L(n,e=0){mt(n);const t=v.get(n.toUpperCase()),s=(t==null?void 0:t.decimal)||await ie(P(n));return t||v.set(n.toUpperCase(),{identifier:n,decimal:s}),new _({decimal:s,value:S(e,s),identifier:n})}function ne(n,e=0){const[t,s]=n.split("/");return new _({decimal:8,value:S(e,8),identifier:`${i.Chain.THORChain}.${t}/${s}`})}function S(n,e){return typeof n=="bigint"?B({value:n,bigIntDecimal:e,decimal:e}):n}function P(n){const e=n.slice(0,14).includes("/"),[t,s]=n.split(".").pop().split("/"),r=n.includes(".")&&!e?n:`${i.Chain.THORChain}.${s}`,[a,c]=r.split("."),[o,u]=(e?s:c).split("-");return{address:u==null?void 0:u.toLowerCase(),chain:a,isGasAsset:K({chain:a,symbol:c}),isSynthetic:e,symbol:(e?`${t}/`:"")+(u?`${o}-${(u==null?void 0:u.toLowerCase())??""}`:c),ticker:o}}const gt={core_wallet_connection_not_found:10001,core_estimated_max_spendable_chain_not_supported:10002,core_extend_error:10003,core_inbound_data_not_found:10004,core_approve_asset_address_or_from_not_found:10005,core_chain_halted:10099,core_wallet_xdefi_not_installed:10101,core_wallet_evmwallet_not_installed:10102,core_wallet_walletconnect_not_installed:10103,core_wallet_keystore_not_installed:10104,core_wallet_ledger_not_installed:10105,core_wallet_trezor_not_installed:10106,core_wallet_keplr_not_installed:10107,core_wallet_okx_not_installed:10108,core_swap_invalid_params:10200,core_swap_route_not_complete:10201,core_swap_asset_not_recognized:10202,core_swap_contract_not_found:10203,core_swap_route_transaction_not_found:10204,core_swap_contract_not_supported:10205,core_swap_transaction_error:10206,core_swap_quote_mode_not_supported:10207,core_transaction_deposit_error:10301,core_transaction_create_liquidity_rune_error:10302,core_transaction_create_liquidity_asset_error:10303,core_transaction_create_liquidity_invalid_params:10304,core_transaction_add_liquidity_invalid_params:10305,core_transaction_add_liquidity_no_rune_address:10306,core_transaction_add_liquidity_rune_error:10307,core_transaction_add_liquidity_asset_error:10308,core_transaction_withdraw_error:10309,core_transaction_deposit_to_pool_error:10310,core_transaction_deposit_insufficient_funds_error:10311,core_transaction_deposit_gas_error:10312,core_transaction_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:gt[e],message:e}}),Object.setPrototypeOf(this,z.prototype)}}class f extends I{eq(e){return this.eqValue(e)}static fromBigInt(e,t){return new f({decimal:t,value:B({value:e,bigIntDecimal:t,decimal:t})})}}exports.AssetValue=_;exports.BigIntArithmetics=I;exports.RequestClient=ge;exports.SwapKitError=z;exports.SwapKitNumber=f;exports.assetFromString=ke;exports.derivationPathToString=ze;exports.filterAssets=je;exports.formatBigIntToSafeValue=B;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=Fe;exports.getLiquiditySlippage=We;exports.getMemoFor=Ge;exports.getMinAmountByChain=ft;exports.getSymmetricPoolShare=le;exports.getSymmetricWithdraw=Ue;exports.getTHORNameCost=Ke;exports.isGasAsset=K;exports.validateTHORName=Ye;
2
2
  //# sourceMappingURL=index.cjs.map