@swapkit/helpers 1.0.0-rc.10 → 1.0.0-rc.11

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 +1 @@
1
- "use strict";var Ae=Object.create;var N=Object.defineProperty;var Te=Object.getOwnPropertyDescriptor;var Se=Object.getOwnPropertyNames;var Re=Object.getPrototypeOf,ve=Object.prototype.hasOwnProperty;var $e=(s,e,t)=>e in s?N(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t;var Ie=(s,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of Se(e))!ve.call(s,n)&&n!==t&&N(s,n,{get:()=>e[n],enumerable:!(r=Te(e,n))||r.enumerable});return s};var Be=(s,e,t)=>(t=s!=null?Ae(Re(s)):{},Ie(e||!s||!s.__esModule?N(t,"default",{value:s,enumerable:!0}):t,s));var p=(s,e,t)=>($e(s,typeof e!="symbol"?e+"":e,t),t),Ee=(s,e,t)=>{if(!e.has(s))throw TypeError("Cannot "+t)};var _=(s,e,t)=>{if(e.has(s))throw TypeError("Cannot add the same private member more than once");e instanceof WeakSet?e.add(s):e.set(s,t)};var m=(s,e,t)=>(Ee(s,e,"access private method"),t);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const i=require("@swapkit/types"),Oe="0x313ce567",re=async({chain:s,to:e})=>{try{const{result:t}=await pe.post(i.ChainToRPC[s],{headers:{accept:"*/*","cache-control":"no-cache"},body:JSON.stringify({id:44,jsonrpc:"2.0",method:"eth_call",params:[{to:e.toLowerCase(),data:Oe},"latest"]})});return parseInt(BigInt(t).toString())}catch(t){return console.error(t),i.BaseDecimal[s]}},Me=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},Ve=async s=>{const[,e]=s.split("-");return e!=null&&e.startsWith("0x")?re({chain:i.Chain.Avalanche,to:e.toLowerCase()}):i.BaseDecimal.AVAX},ke=async s=>(s===i.Chain.BinanceSmartChain,i.BaseDecimal.BSC),K=async({chain:s,symbol:e})=>{switch(s){case i.Chain.Ethereum:return Me(e);case i.Chain.Avalanche:return Ve(e);case i.Chain.BinanceSmartChain:return ke(e);default:return i.BaseDecimal[s]}},qe={[i.FeeOption.Average]:1.2,[i.FeeOption.Fast]:1.5,[i.FeeOption.Fastest]:2},se=({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"}},ne=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]}}},ie=({chain:s,symbol:e})=>{if(e.includes("/"))return"Synth";switch(s){case i.Chain.Bitcoin:case i.Chain.BitcoinCash:case i.Chain.Dogecoin:case i.Chain.Litecoin:case i.Chain.Maya:case i.Chain.THORChain:return"Native";case i.Chain.Cosmos:return e==="ATOM"?"Native":i.Chain.Cosmos;case i.Chain.Kujira:return e===i.Chain.Kujira?"Native":i.Chain.Kujira;case i.Chain.Binance:return e===i.Chain.Binance?"Native":"BEP2";case i.Chain.BinanceSmartChain:return e===i.Chain.Binance?"Native":"BEP20";case i.Chain.Ethereum:return e===i.Chain.Ethereum?"Native":"ERC20";case i.Chain.Avalanche:return e===i.Chain.Avalanche?"Native":i.Chain.Avalanche;case i.Chain.Polygon:return e===i.Chain.Polygon?"Native":"POLYGON";case i.Chain.Arbitrum:return[i.Chain.Ethereum,i.Chain.Arbitrum].includes(e)?"Native":"ARBITRUM";case i.Chain.Optimism:return[i.Chain.Ethereum,i.Chain.Optimism].includes(e)?"Native":"OPTIMISM"}},Pe=s=>{var o;const[e,...t]=s.split("."),r=s.includes("/"),n=t.join("."),a=(o=n==null?void 0:n.split("-"))==null?void 0:o[0];return{chain:e,symbol:n,ticker:a,synth:r}},Ne=new RegExp(/(.)\1{6}|\.ORG|\.NET|\.FINANCE|\.COM|WWW|HTTP|\\\\|\/\/|[\s$%:[\]]/,"gmi"),xe=s=>s.filter(e=>!Ne.test(e.toString())&&!e.toString().includes("undefined")),ae=({liquidityUnits:s,poolUnits:e,runeDepth:t})=>{const r=d(s),n=d(e),a=d(t),o=r.mul(a),c=n.mul(n).mul(2),u=n.mul(r).mul(2),l=r.mul(r),h=n.mul(n).mul(n);return o.mul(c.sub(u).add(l)).div(h)},oe=({liquidityUnits:s,poolUnits:e,assetDepth:t})=>{const r=d(s),n=d(e),a=d(t),o=r.mul(a),c=n.mul(n).mul(2),u=n.mul(r).mul(2),l=r.mul(r),h=o.mul(c.sub(u).add(l)),g=n.mul(n).mul(n);return h.div(g)},De=({percent:s,runeDepth:e,liquidityUnits:t,poolUnits:r})=>ae({runeDepth:e,liquidityUnits:t,poolUnits:r}).mul(s),He=({percent:s,assetDepth:e,liquidityUnits:t,poolUnits:r})=>oe({assetDepth:e,liquidityUnits:t,poolUnits:r}).mul(s),d=s=>new _e({value:s,decimal:i.BaseDecimal.THOR}),ce=({liquidityUnits:s,poolUnits:e,runeDepth:t,assetDepth:r})=>({assetAmount:d(r).mul(s).div(e),runeAmount:d(t).mul(s).div(e)}),je=({liquidityUnits:s,poolUnits:e,runeDepth:t,assetDepth:r,percent:n})=>Object.fromEntries(Object.entries(ce({liquidityUnits:s,poolUnits:e,runeDepth:t,assetDepth:r})).map(([a,o])=>[a,o.mul(n)])),Le=({runeDepth:s,poolUnits:e,assetDepth:t,liquidityUnits:r,runeAmount:n,assetAmount:a})=>{const o=d(s),c=d(t),u=d(e),l=d(n),h=d(a),g=l.mul(c),C=h.mul(o),q=l.mul(h),ye=o.mul(c),be=u.mul(g.add(C.add(q.mul(2)))),Ce=g.add(C.add(ye.mul(2))),J=be.div(Ce),P=d(r).add(J);if(J.baseValueNumber===0)return P.div(u).baseValueNumber;const we=u.add(P);return P.div(we).baseValueNumber},Ue=({runeAmount:s,assetAmount:e,runeDepth:t,assetDepth:r})=>{const n=d(t),a=d(r),o=d(e),c=d(s),u=o.mul(n).sub(a.mul(c)),l=a.mul(c).add(n.mul(a));return Math.abs(u.div(l).baseValueNumber)},Fe=({symbol:s,ticker:e,chain:t})=>t==="ETH"&&e!=="ETH"?`${e}-${s.slice(-3)}`:s,We=(s,e)=>{switch(s){case i.MemoType.LEAVE:case i.MemoType.BOND:{const{address:t}=e;return`${s}:${t}`}case i.MemoType.UNBOND:{const{address:t,unbondAmount:r}=e;return`${s}:${t}:${r*10**8}`}case i.MemoType.THORNAME_REGISTER:{const{name:t,chain:r,address:n,owner:a}=e;return`${s}:${t}:${r}:${n}${a?`:${a}`:""}`}case i.MemoType.DEPOSIT:{const{chain:t,symbol:r,address:n,singleSide:a}=e;return a?`${s}:${t}/${r}::t:0`:`${s}:${t}.${r}:${n||""}:t:0`}case i.MemoType.WITHDRAW:{const{chain:t,ticker:r,symbol:n,basisPoints:a,targetAssetString:o,singleSide:c}=e,u=!c&&o?`:${o}`:"",l=Fe({chain:t,symbol:n,ticker:r});return`${s}:${t}${c?"/":"."}${l}:${a}${u}`}case i.MemoType.OPEN_LOAN:case i.MemoType.CLOSE_LOAN:{const{asset:t,address:r}=e;return`${s}:${t}:${r}`}default:return""}},Ge=s=>{if(s<0)throw new Error("Invalid number of year");return 10+s},Ke=s=>{if(s.length>30)return!1;const e=/^[a-zA-Z0-9+_-]+$/g;return!!s.match(e)},Ye=([s,e,t,r,n])=>`${s}'/${e}'/${t}'/${r}${typeof n!="number"?"":`/${n}`}`;class Q extends Error{constructor(e,t,r){const n=e.status||e.status===0?e.status:"",a=e.statusText||"",o=`${n} ${a}`.trim(),c=o?`status code ${o}`:"an unknown error";super(`Request failed with ${c}`),Object.defineProperty(this,"response",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"request",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"options",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.name="HTTPError",this.response=e,this.request=t,this.options=r}}class ue extends Error{constructor(e){super("Request timed out"),Object.defineProperty(this,"request",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.name="TimeoutError",this.request=e}}const O=s=>s!==null&&typeof s=="object",E=(...s)=>{for(const e of s)if((!O(e)||Array.isArray(e))&&e!==void 0)throw new TypeError("The `options` argument must be an object");return Y({},...s)},le=(s={},e={})=>{const t=new globalThis.Headers(s),r=e instanceof globalThis.Headers,n=new globalThis.Headers(e);for(const[a,o]of n.entries())r&&o==="undefined"||o===void 0?t.delete(a):t.set(a,o);return t},Y=(...s)=>{let e={},t={};for(const r of s)if(Array.isArray(r))Array.isArray(e)||(e=[]),e=[...e,...r];else if(O(r)){for(let[n,a]of Object.entries(r))O(a)&&n in e&&(a=Y(e[n],a)),e={...e,[n]:a};O(r.headers)&&(t=le(t,r.headers),e.headers=t)}return e},ze=(()=>{let s=!1,e=!1;const t=typeof globalThis.ReadableStream=="function",r=typeof globalThis.Request=="function";return t&&r&&(e=new globalThis.Request("https://empty.invalid",{body:new globalThis.ReadableStream,method:"POST",get duplex(){return s=!0,"half"}}).headers.has("Content-Type")),s&&!e})(),Je=typeof globalThis.AbortController=="function",Qe=typeof globalThis.ReadableStream=="function",Xe=typeof globalThis.FormData=="function",he=["get","post","put","patch","head","delete"],Ze={json:"application/json",text:"text/*",formData:"multipart/form-data",arrayBuffer:"*/*",blob:"*/*"},x=2147483647,de=Symbol("stop"),et={json:!0,parseJson:!0,searchParams:!0,prefixUrl:!0,retry:!0,timeout:!0,hooks:!0,throwHttpErrors:!0,onDownloadProgress:!0,fetch:!0},tt={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=>he.includes(s)?s.toUpperCase():s,st=["get","put","head","delete","options","trace"],nt=[408,413,429,500,502,503,504],me=[413,429,503],X={limit:2,methods:st,statusCodes:nt,afterStatusCodes:me,maxRetryAfter:Number.POSITIVE_INFINITY,backoffLimit:Number.POSITIVE_INFINITY,delay:s=>.3*2**(s-1)*1e3},it=(s={})=>{if(typeof s=="number")return{...X,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{...X,...s,afterStatusCodes:me}};async function at(s,e,t,r){return new Promise((n,a)=>{const o=setTimeout(()=>{t&&t.abort(),a(new ue(s))},r.timeout);r.fetch(s,e).then(n).catch(a).then(()=>{clearTimeout(o)})})}async function ot(s,{signal:e}){return new Promise((t,r)=>{e&&(e.throwIfAborted(),e.addEventListener("abort",n,{once:!0}));function n(){clearTimeout(a),r(e.reason)}const a=setTimeout(()=>{e==null||e.removeEventListener("abort",n),t()},s)})}const ct=(s,e)=>{const t={};for(const r in e)!(r in tt)&&!(r in et)&&!(r in s)&&(t[r]=e[r]);return t};class M{static create(e,t){const r=new M(e,t),n=async()=>{if(typeof r._options.timeout=="number"&&r._options.timeout>x)throw new RangeError(`The \`timeout\` option cannot be greater than ${x}`);await Promise.resolve();let c=await r._fetch();for(const u of r._options.hooks.afterResponse){const l=await u(r.request,r._options,r._decorateResponse(c.clone()));l instanceof globalThis.Response&&(c=l)}if(r._decorateResponse(c),!c.ok&&r._options.throwHttpErrors){let u=new Q(c,r.request,r._options);for(const l of r._options.hooks.beforeError)u=await l(u);throw u}if(r._options.onDownloadProgress){if(typeof r._options.onDownloadProgress!="function")throw new TypeError("The `onDownloadProgress` option must be a function");if(!Qe)throw new Error("Streams are not supported in your environment. `ReadableStream` is missing.");return r._stream(c.clone(),r._options.onDownloadProgress)}return c},o=r._options.retry.methods.includes(r.request.method.toLowerCase())?r._retry(n):n();for(const[c,u]of Object.entries(Ze))o[c]=async()=>{r.request.headers.set("accept",r.request.headers.get("accept")||u);const h=(await o).clone();if(c==="json"){if(h.status===204||(await h.clone().arrayBuffer()).byteLength===0)return"";if(t.parseJson)return t.parseJson(await h.text())}return h[c]()};return o}constructor(e,t={}){if(Object.defineProperty(this,"request",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"abortController",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_retryCount",{enumerable:!0,configurable:!0,writable:!0,value:0}),Object.defineProperty(this,"_input",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_options",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this._input=e,this._options={credentials:this._input.credentials||"same-origin",...t,headers:le(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:it(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(Je){if(this.abortController=new globalThis.AbortController,this._options.signal){const r=this._options.signal;this._options.signal.addEventListener("abort",()=>{this.abortController.abort(r.reason)})}this._options.signal=this.abortController.signal}if(ze&&(this._options.duplex="half"),this.request=new globalThis.Request(this._input,this._options),this._options.searchParams){const n="?"+(typeof this._options.searchParams=="string"?this._options.searchParams.replace(/^\?/,""):new URLSearchParams(this._options.searchParams).toString()),a=this.request.url.replace(/(?:\?.*?)?(?=#|$)/,n);(Xe&&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 ue)){if(e instanceof Q){if(!this._options.retry.statusCodes.includes(e.response.status))return 0;const r=e.response.headers.get("Retry-After");if(r&&this._options.retry.afterStatusCodes.includes(e.response.status)){let n=Number(r);return Number.isNaN(n)?n=Date.parse(r)-Date.now():n*=1e3,this._options.retry.maxRetryAfter!==void 0&&n>this._options.retry.maxRetryAfter?0:n}if(e.response.status===413)return 0}const t=this._options.retry.delay(this._retryCount);return Math.min(this._options.retry.backoffLimit,t)}return 0}_decorateResponse(e){return this._options.parseJson&&(e.json=async()=>this._options.parseJson(await e.text())),e}async _retry(e){try{return await e()}catch(t){const r=Math.min(this._calculateRetryDelay(t),x);if(r!==0&&this._retryCount>0){await ot(r,{signal:this._options.signal});for(const n of this._options.hooks.beforeRetry)if(await n({request:this.request,options:this._options,error:t,retryCount:this._retryCount})===de)return;return this._retry(e)}throw t}}async _fetch(){for(const t of this._options.hooks.beforeRequest){const r=await t(this.request,this._options);if(r instanceof Request){this.request=r;break}if(r instanceof Response)return r}const e=ct(this.request,this._options);return this._options.timeout===!1?this._options.fetch(this.request.clone(),e):at(this.request.clone(),e,this.abortController,this._options)}_stream(e,t){const r=Number(e.headers.get("content-length"))||0;let n=0;return e.status===204?(t&&t({percent:1,totalBytes:r,transferredBytes:n},new Uint8Array),new globalThis.Response(null,{status:e.status,statusText:e.statusText,headers:e.headers})):new globalThis.Response(new globalThis.ReadableStream({async start(a){const o=e.body.getReader();t&&t({percent:0,transferredBytes:0,totalBytes:r},new Uint8Array);async function c(){const{done:u,value:l}=await o.read();if(u){a.close();return}if(t){n+=l.byteLength;const h=r===0?0:n/r;t({percent:h,transferredBytes:n,totalBytes:r},l)}a.enqueue(l),await c()}await c()}}),{status:e.status,statusText:e.statusText,headers:e.headers})}}/*! MIT License © Sindre Sorhus */const j=s=>{const e=(t,r)=>M.create(t,E(s,r));for(const t of he)e[t]=(r,n)=>M.create(r,E(s,n,{method:t}));return e.create=t=>j(E(t)),e.extend=t=>j(E(s,t)),e.stop=de,e},ut=j(),lt=ut,Z=lt.create({headers:{referrer:"https://sk.thorswap.net",referer:"https://sk.thorswap.net","Content-Type":"application/json"}}),pe={get:(s,e)=>Z.get(s,e).json(),post:(s,e)=>Z.post(s,e).json()},ee=Object.values(i.Chain),ht=(s="")=>{const e=s.toUpperCase(),[t]=e.split(".");if(ee.includes(t))return!0;const[r]=e.split("/");if(ee.includes(r))return!0;throw new Error(`Invalid identifier: ${s}. Expected format: <Chain>.<Ticker> or <Chain>.<Ticker>-<ContractAddress>`)},v=8,w=s=>10n**BigInt(s),T=s=>Math.log10(parseFloat(s.toString()));function L({value:s,bigIntDecimal:e=v,decimal:t=v}){const r=s<0n;let n=s.toString().substring(r?1:0);const a=t-(n.length-1);a>0&&(n="0".repeat(a)+n);const o=n.length-t;let c=n.slice(-t);return parseInt(c[e])>=5?c=`${c.substring(0,e-1)}${(parseInt(c[e-1])+1).toString()}`:c=c.substring(0,e),`${r?"-":""}${n.slice(0,o)}.${c}`.replace(/\.?0*$/,"")}var y,S,V,fe,k,ge,I,U,b,R,B,F;const $=class ${constructor(e){_(this,y);_(this,V);_(this,k);_(this,I);_(this,b);_(this,B);p(this,"decimalMultiplier",10n**8n);p(this,"bigIntValue",0n);p(this,"decimal");const t=D(e);this.decimal=typeof e=="object"?e.decimal:void 0,this.decimalMultiplier=w(Math.max(m(this,B,F).call(this,m(this,b,R).call(this,t)),this.decimal||0)),m(this,V,fe).call(this,t)}static fromBigInt(e,t){return new $({decimal:t,value:L({value:e,bigIntDecimal:t,decimal:t})})}static shiftDecimals({value:e,from:t,to:r}){return $.fromBigInt(new $(e).bigIntValue*w(r)/w(t),r)}get baseValue(){return this.getBaseValue("string")}get baseValueNumber(){return this.getBaseValue("number")}get baseValueBigInt(){return this.getBaseValue("bigint")}set(e){return new this.constructor({decimal:this.decimal,value:e,identifier:this.toString()})}add(...e){return m(this,y,S).call(this,"add",...e)}sub(...e){return m(this,y,S).call(this,"sub",...e)}mul(...e){return m(this,y,S).call(this,"mul",...e)}div(...e){return m(this,y,S).call(this,"div",...e)}gt(e){return this.bigIntValue>this.getBigIntValue(e)}gte(e){return this.bigIntValue>=this.getBigIntValue(e)}lt(e){return this.bigIntValue<this.getBigIntValue(e)}lte(e){return this.bigIntValue<=this.getBigIntValue(e)}eqValue(e){return this.bigIntValue===this.getBigIntValue(e)}getValue(e){const t=this.formatBigIntToSafeValue(this.bigIntValue,this.decimal||T(this.decimalMultiplier));switch(e){case"number":return Number(t);case"string":return t;default:return this.bigIntValue*BigInt(this.decimal||8n)/this.decimalMultiplier}}getBaseValue(e){const t=this.decimalMultiplier/w(this.decimal||i.BaseDecimal.THOR),r=this.bigIntValue/t;switch(e){case"number":return Number(r);case"string":return r.toString();default:return r}}getBigIntValue(e,t){if(!t&&typeof e=="object")return e.bigIntValue;const r=D(e),n=m(this,b,R).call(this,r);return n==="0"||n==="undefined"?0n:m(this,I,U).call(this,n,t)}formatBigIntToSafeValue(e,t){const r=t||this.decimal||v,n=Math.max(r,T(this.decimalMultiplier)),a=e<0n,o=e.toString().substring(a?1:0),c=n-(o.length-1),u=c>0?"0".repeat(c)+o:o,l=u.length-n;let h=u.slice(-n);return parseInt(h[r])>=5?h=`${h.substring(0,r-1)}${(parseInt(h[r-1])+1).toString()}`:h=h.substring(0,r),`${a?"-":""}${u.slice(0,l)}.${h}`.replace(/\.?0*$/,"")}toSignificant(e=6){const[t,r]=this.getValue("string").split("."),n=t||"",a=r||"",o=parseInt(n)?n.length+a.length:a.length;if(o<=e)return this.getValue("string");if(n.length>=e)return n.slice(0,e).padEnd(n.length,"0");if(parseInt(n))return`${n}.${a.slice(0,e-n.length)}`.padEnd(o-e,"0");const c=parseInt(a),u=`${c}`.slice(0,e);return`0.${u.padStart(a.length-`${c}`.length+u.length,"0")}`}toFixed(e=6){const[t,r]=this.getValue("string").split("."),n=t||"",a=r||"";if(parseInt(n))return`${n}.${a.slice(0,e)}`.padEnd(e,"0");const o=parseInt(a),c=`${o}`.slice(0,e);return`0.${c.padStart(a.length-`${o}`.length+c.length,"0")}`}};y=new WeakSet,S=function(e,...t){const r=m(this,k,ge).call(this,this,...t),n=w(r),a=t.reduce((c,u)=>{const l=this.getBigIntValue(u,r);switch(e){case"add":return c+l;case"sub":return c-l;case"mul":return c*l/n;case"div":{if(l===0n)throw new RangeError("Division by zero");return c*n/l}default:return c}},this.bigIntValue*n/this.decimalMultiplier),o=L({bigIntDecimal:r,decimal:Math.max(r,T(this.decimalMultiplier)),value:a});return new this.constructor({decimal:this.decimal,value:o,identifier:this.toString()})},V=new WeakSet,fe=function(e){const t=m(this,b,R).call(this,e)||"0";this.bigIntValue=m(this,I,U).call(this,t)},k=new WeakSet,ge=function(...e){const t=e.map(r=>typeof r=="object"?r.decimal||T(r.decimalMultiplier):m(this,B,F).call(this,m(this,b,R).call(this,r))).filter(Boolean);return Math.max(...t,v)},I=new WeakSet,U=function(e,t){const r=t?w(t):this.decimalMultiplier,n=T(r),[a="",o=""]=e.split(".");return BigInt(`${a}${o.padEnd(n,"0")}`)},b=new WeakSet,R=function(e){const r=`${typeof e=="number"?Number(e).toLocaleString("fullwide",{useGrouping:!1,maximumFractionDigits:20}):D(e)}`.replaceAll(",",".").split(".");return r.length>1?`${r.slice(0,-1).join("")}.${r.at(-1)}`:r[0]},B=new WeakSet,F=function(e){var r;const t=((r=e.split(".")[1])==null?void 0:r.length)||0;return Math.max(t,v)};let A=$;function D(s){return typeof s=="object"?"getValue"in s?s.getValue("string"):s.value:s}let W;const H=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:""}},te=async(s,e=0)=>{ht(s);const t=await K(G(s));return new f({decimal:t,value:e,identifier:s})};class f extends A{constructor(t){super(t.value instanceof A?t.value:{decimal:t.decimal,value:t.value});p(this,"address");p(this,"chain");p(this,"isSynthetic",!1);p(this,"isGasAsset",!1);p(this,"symbol");p(this,"ticker");p(this,"type");const r="identifier"in t?t.identifier:`${t.chain}.${t.symbol}`,n=G(r);this.type=ie(n),this.chain=n.chain,this.ticker=n.ticker,this.symbol=n.symbol,this.address=n.address,this.isSynthetic=n.isSynthetic,this.isGasAsset=n.isGasAsset}get assetValue(){return`${this.getValue("string")} ${this.ticker}`}toString(t=!1){const r=this.isSynthetic?this.ticker:`${this.chain}.${this.ticker}`;return t?r:`${this.chain}.${this.symbol}`}eq({chain:t,symbol:r}){return this.chain===t&&this.symbol===r}static async fromString(t,r=0){return te(t,r)}static fromStringSync(t,r=0){const{decimal:n,identifier:a}=H(t);return a?new f({decimal:n,identifier:a,value:r}):void 0}static async fromIdentifier(t,r=0){return te(t,r)}static fromIdentifierSync(t,r=0){const{decimal:n,identifier:a}=H(t);return new f({decimal:n,identifier:a,value:r})}static fromChainOrSignature(t,r=0){const{decimal:n,identifier:a}=ne(t);return new f({value:r,decimal:n,identifier:a})}static async fromTCQuote(t,r=0){const n=await K(G(t)),a=this.shiftDecimals({value:r,from:i.BaseDecimal.THOR,to:n});return new f({value:a,identifier:t,decimal:n})}static fromTCQuoteStatic(t,r=0){const n=H(t),a=this.shiftDecimals({value:r,from:i.BaseDecimal.THOR,to:n.decimal});return new f({...n,value:a})}static async loadStaticAssets(){return new Promise(async(t,r)=>{try{const{ThorchainList:n,NativeList:a,...o}=await import("@swapkit/tokens");W=[a,...Object.values(o)].reduce((u,{tokens:l})=>(l.forEach(({identifier:h,chain:g,...C})=>{const q="decimals"in C?C.decimals:i.BaseDecimal[g];u.set(h,{identifier:h,decimal:q})}),u),new Map),t({ok:!0})}catch(n){console.error(n),r({ok:!1,error:n,message:"Couldn't load static assets. Ensure you have installed @swapkit/tokens package"})}})}}const dt=s=>{const e=f.fromChainOrSignature(s);switch(s){case i.Chain.Bitcoin:case i.Chain.Litecoin:case i.Chain.BitcoinCash:return e.add(10001);case i.Chain.Dogecoin:return e.add(100000001);case i.Chain.Avalanche:case i.Chain.Ethereum:return e.add(10*10**9);case i.Chain.THORChain:case i.Chain.Maya:return e.add(0);default:return e.add(1)}},G=s=>{const e=s.slice(0,14).includes("/"),t=s.includes(".")?s:`${i.Chain.THORChain}.${s}`,[r,n]=t.split("."),[a,o]=n.split("-");return{address:o==null?void 0:o.toLowerCase(),chain:r,isGasAsset:se({chain:r,symbol:n}),isSynthetic:e,symbol:o?`${a}-${(o==null?void 0:o.toLowerCase())??""}`:n,ticker:e?n:a}},mt={core_wallet_connection_not_found:10001,core_estimated_max_spendable_chain_not_supported:10002,core_extend_error:10003,core_inbound_data_not_found:10004,core_approve_asset_address_or_from_not_found:10005,core_chain_halted:10099,core_wallet_xdefi_not_installed:10101,core_wallet_evmwallet_not_installed:10102,core_wallet_walletconnect_not_installed:10103,core_wallet_keystore_not_installed:10104,core_wallet_ledger_not_installed:10105,core_wallet_trezor_not_installed:10106,core_wallet_keplr_not_installed:10107,core_wallet_okx_not_installed:10108,core_swap_invalid_params:10200,core_swap_route_not_complete:10201,core_swap_asset_not_recognized:10202,core_swap_contract_not_found:10203,core_swap_route_transaction_not_found:10204,core_swap_contract_not_supported:10205,core_swap_transaction_error:10206,core_swap_quote_mode_not_supported:10207,core_transaction_deposit_error:10301,core_transaction_create_liquidity_rune_error:10302,core_transaction_create_liquidity_asset_error:10303,core_transaction_create_liquidity_invalid_params:10304,core_transaction_add_liquidity_invalid_params:10305,core_transaction_add_liquidity_no_rune_address:10306,core_transaction_add_liquidity_rune_error:10307,core_transaction_add_liquidity_asset_error:10308,core_transaction_withdraw_error:10309,core_transaction_deposit_to_pool_error:10310,core_transaction_deposit_insufficient_funds_error:10311,core_transaction_deposit_gas_error:10312,core_transaction_deposit_server_error:10313,wallet_ledger_connection_error:20001,helpers_number_different_decimals:99101};class z extends Error{constructor(e,t){console.error(t),super(e,{cause:{code:mt[e],message:e}}),Object.setPrototypeOf(this,z.prototype)}}class _e extends A{eq(e){return this.eqValue(e)}}exports.AssetValue=f;exports.BigIntArithmetics=A;exports.RequestClient=pe;exports.SwapKitError=z;exports.SwapKitNumber=_e;exports.assetFromString=Pe;exports.derivationPathToString=Ye;exports.filterAssets=xe;exports.formatBigIntToSafeValue=L;exports.gasFeeMultiplier=qe;exports.getAssetType=ie;exports.getAsymmetricAssetShare=oe;exports.getAsymmetricAssetWithdrawAmount=He;exports.getAsymmetricRuneShare=ae;exports.getAsymmetricRuneWithdrawAmount=De;exports.getCommonAssetInfo=ne;exports.getDecimal=K;exports.getEstimatedPoolShare=Le;exports.getLiquiditySlippage=Ue;exports.getMemoFor=We;exports.getMinAmountByChain=dt;exports.getSymmetricPoolShare=ce;exports.getSymmetricWithdraw=je;exports.getTHORNameCost=Ge;exports.isGasAsset=se;exports.validateTHORName=Ke;
1
+ "use strict";var Te=Object.create;var H=Object.defineProperty;var Se=Object.getOwnPropertyDescriptor;var Re=Object.getOwnPropertyNames;var ve=Object.getPrototypeOf,Ie=Object.prototype.hasOwnProperty;var $e=(s,e,t)=>e in s?H(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t;var Be=(s,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of Re(e))!Ie.call(s,n)&&n!==t&&H(s,n,{get:()=>e[n],enumerable:!(r=Se(e,n))||r.enumerable});return s};var Ee=(s,e,t)=>(t=s!=null?Te(ve(s)):{},Be(e||!s||!s.__esModule?H(t,"default",{value:s,enumerable:!0}):t,s));var p=(s,e,t)=>($e(s,typeof e!="symbol"?e+"":e,t),t),Oe=(s,e,t)=>{if(!e.has(s))throw TypeError("Cannot "+t)};var _=(s,e,t)=>{if(e.has(s))throw TypeError("Cannot add the same private member more than once");e instanceof WeakSet?e.add(s):e.set(s,t)};var m=(s,e,t)=>(Oe(s,e,"access private method"),t);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const i=require("@swapkit/types"),Me="0x313ce567",ne=async({chain:s,to:e})=>{try{const{result:t}=await ge.post(i.ChainToRPC[s],{headers:{accept:"*/*","cache-control":"no-cache"},body:JSON.stringify({id:44,jsonrpc:"2.0",method:"eth_call",params:[{to:e.toLowerCase(),data:Me},"latest"]})});return parseInt(BigInt(t).toString())}catch(t){return console.error(t),i.BaseDecimal[s]}},Ve=async s=>{if(s===i.Chain.Ethereum)return i.BaseDecimal.ETH;const[,e]=s.split("-");return e!=null&&e.startsWith("0x")?ne({chain:i.Chain.Ethereum,to:e}):i.BaseDecimal.ETH},ke=async s=>{const[,e]=s.split("-");return e!=null&&e.startsWith("0x")?ne({chain:i.Chain.Avalanche,to:e.toLowerCase()}):i.BaseDecimal.AVAX},qe=async s=>(s===i.Chain.BinanceSmartChain,i.BaseDecimal.BSC),J=async({chain:s,symbol:e})=>{switch(s){case i.Chain.Ethereum:return Ve(e);case i.Chain.Avalanche:return ke(e);case i.Chain.BinanceSmartChain:return qe(e);default:return i.BaseDecimal[s]}},Pe={[i.FeeOption.Average]:1.2,[i.FeeOption.Fast]:1.5,[i.FeeOption.Fastest]:2},ie=({chain:s,symbol:e})=>{switch(s){case i.Chain.Bitcoin:case i.Chain.BitcoinCash:case i.Chain.Litecoin:case i.Chain.Dogecoin:case i.Chain.Binance:case i.Chain.Ethereum:case i.Chain.Avalanche:return e===s;case i.Chain.Arbitrum:case i.Chain.Optimism:return e==="ETH";case i.Chain.Maya:return e==="CACAO";case i.Chain.Kujira:return e==="KUJI";case i.Chain.Cosmos:return e==="ATOM";case i.Chain.Polygon:return e==="MATIC";case i.Chain.BinanceSmartChain:return e==="BNB";case i.Chain.THORChain:return e==="RUNE"}},ae=s=>{switch(s){case"ETH.THOR":return{identifier:"ETH.THOR-0xa5f2211b9b8170f694421f2046281775e8468044",decimal:18};case"ETH.vTHOR":return{identifier:"ETH.vTHOR-0x815c23eca83261b6ec689b60cc4a58b54bc24d8d",decimal:18};case i.Chain.Cosmos:return{identifier:"GAIA.ATOM",decimal:i.BaseDecimal[s]};case i.Chain.THORChain:return{identifier:"THOR.RUNE",decimal:i.BaseDecimal[s]};case i.Chain.BinanceSmartChain:return{identifier:"BSC.BNB",decimal:i.BaseDecimal[s]};case i.Chain.Maya:return{identifier:"MAYA.CACAO",decimal:i.BaseDecimal.MAYA};case"MAYA.MAYA":return{identifier:"MAYA.MAYA",decimal:4};case i.Chain.Kujira:case i.Chain.Arbitrum:case i.Chain.Optimism:case i.Chain.BitcoinCash:case i.Chain.Litecoin:case i.Chain.Dogecoin:case i.Chain.Binance:case i.Chain.Avalanche:case i.Chain.Polygon:case i.Chain.Bitcoin:case i.Chain.Ethereum:return{identifier:`${s}.${s}`,decimal:i.BaseDecimal[s]}}},oe=({chain:s,symbol:e})=>{if(e.includes("/"))return"Synth";switch(s){case i.Chain.Bitcoin:case i.Chain.BitcoinCash:case i.Chain.Dogecoin:case i.Chain.Litecoin:case i.Chain.Maya:case i.Chain.THORChain:return"Native";case i.Chain.Cosmos:return e==="ATOM"?"Native":i.Chain.Cosmos;case i.Chain.Kujira:return e===i.Chain.Kujira?"Native":i.Chain.Kujira;case i.Chain.Binance:return e===i.Chain.Binance?"Native":"BEP2";case i.Chain.BinanceSmartChain:return e===i.Chain.Binance?"Native":"BEP20";case i.Chain.Ethereum:return e===i.Chain.Ethereum?"Native":"ERC20";case i.Chain.Avalanche:return e===i.Chain.Avalanche?"Native":i.Chain.Avalanche;case i.Chain.Polygon:return e===i.Chain.Polygon?"Native":"POLYGON";case i.Chain.Arbitrum:return[i.Chain.Ethereum,i.Chain.Arbitrum].includes(e)?"Native":"ARBITRUM";case i.Chain.Optimism:return[i.Chain.Ethereum,i.Chain.Optimism].includes(e)?"Native":"OPTIMISM"}},De=s=>{var o;const[e,...t]=s.split("."),r=s.includes("/"),n=t.join("."),a=(o=n==null?void 0:n.split("-"))==null?void 0:o[0];return{chain:e,symbol:n,ticker:a,synth:r}},Ne=new RegExp(/(.)\1{6}|\.ORG|\.NET|\.FINANCE|\.COM|WWW|HTTP|\\\\|\/\/|[\s$%:[\]]/,"gmi"),xe=s=>s.filter(e=>!Ne.test(e.toString())&&!e.toString().includes("undefined")),ce=({liquidityUnits:s,poolUnits:e,runeDepth:t})=>{const r=d(s),n=d(e),a=d(t),o=r.mul(a),c=n.mul(n).mul(2),u=n.mul(r).mul(2),l=r.mul(r),h=n.mul(n).mul(n);return o.mul(c.sub(u).add(l)).div(h)},ue=({liquidityUnits:s,poolUnits:e,assetDepth:t})=>{const r=d(s),n=d(e),a=d(t),o=r.mul(a),c=n.mul(n).mul(2),u=n.mul(r).mul(2),l=r.mul(r),h=o.mul(c.sub(u).add(l)),g=n.mul(n).mul(n);return h.div(g)},He=({percent:s,runeDepth:e,liquidityUnits:t,poolUnits:r})=>ce({runeDepth:e,liquidityUnits:t,poolUnits:r}).mul(s),je=({percent:s,assetDepth:e,liquidityUnits:t,poolUnits:r})=>ue({assetDepth:e,liquidityUnits:t,poolUnits:r}).mul(s),d=s=>new D({value:s,decimal:i.BaseDecimal.THOR}),le=({liquidityUnits:s,poolUnits:e,runeDepth:t,assetDepth:r})=>({assetAmount:d(r).mul(s).div(e),runeAmount:d(t).mul(s).div(e)}),Le=({liquidityUnits:s,poolUnits:e,runeDepth:t,assetDepth:r,percent:n})=>Object.fromEntries(Object.entries(le({liquidityUnits:s,poolUnits:e,runeDepth:t,assetDepth:r})).map(([a,o])=>[a,o.mul(n)])),Ue=({runeDepth:s,poolUnits:e,assetDepth:t,liquidityUnits:r,runeAmount:n,assetAmount:a})=>{const o=d(s),c=d(t),u=d(e),l=d(n),h=d(a),g=l.mul(c),C=h.mul(o),N=l.mul(h),be=o.mul(c),Ce=u.mul(g.add(C.add(N.mul(2)))),we=g.add(C.add(be.mul(2))),X=Ce.div(we),x=d(r).add(X);if(X.baseValueNumber===0)return x.div(u).baseValueNumber;const Ae=u.add(x);return x.div(Ae).baseValueNumber},Fe=({runeAmount:s,assetAmount:e,runeDepth:t,assetDepth:r})=>{const n=d(t),a=d(r),o=d(e),c=d(s),u=o.mul(n).sub(a.mul(c)),l=a.mul(c).add(n.mul(a));return Math.abs(u.div(l).baseValueNumber)},We=({symbol:s,ticker:e,chain:t})=>t==="ETH"&&e!=="ETH"?`${e}-${s.slice(-3)}`:s,Ge=(s,e)=>{switch(s){case i.MemoType.LEAVE:case i.MemoType.BOND:{const{address:t}=e;return`${s}:${t}`}case i.MemoType.UNBOND:{const{address:t,unbondAmount:r}=e;return`${s}:${t}:${r*10**8}`}case i.MemoType.THORNAME_REGISTER:{const{name:t,chain:r,address:n,owner:a}=e;return`${s}:${t}:${r}:${n}${a?`:${a}`:""}`}case i.MemoType.DEPOSIT:{const{chain:t,symbol:r,address:n,singleSide:a}=e;return a?`${s}:${t}/${r}::t:0`:`${s}:${t}.${r}:${n||""}:t:0`}case i.MemoType.WITHDRAW:{const{chain:t,ticker:r,symbol:n,basisPoints:a,targetAssetString:o,singleSide:c}=e,u=!c&&o?`:${o}`:"",l=We({chain:t,symbol:n,ticker:r});return`${s}:${t}${c?"/":"."}${l}:${a}${u}`}case i.MemoType.OPEN_LOAN:case i.MemoType.CLOSE_LOAN:{const{asset:t,address:r}=e;return`${s}:${t}:${r}`}default:return""}},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,r,n])=>`${s}'/${e}'/${t}'/${r}${typeof n!="number"?"":`/${n}`}`;class Z extends Error{constructor(e,t,r){const n=e.status||e.status===0?e.status:"",a=e.statusText||"",o=`${n} ${a}`.trim(),c=o?`status code ${o}`:"an unknown error";super(`Request failed with ${c}`),Object.defineProperty(this,"response",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"request",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"options",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.name="HTTPError",this.response=e,this.request=t,this.options=r}}class he extends Error{constructor(e){super("Request timed out"),Object.defineProperty(this,"request",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.name="TimeoutError",this.request=e}}const O=s=>s!==null&&typeof s=="object",E=(...s)=>{for(const e of s)if((!O(e)||Array.isArray(e))&&e!==void 0)throw new TypeError("The `options` argument must be an object");return K({},...s)},de=(s={},e={})=>{const t=new globalThis.Headers(s),r=e instanceof globalThis.Headers,n=new globalThis.Headers(e);for(const[a,o]of n.entries())r&&o==="undefined"||o===void 0?t.delete(a):t.set(a,o);return t},K=(...s)=>{let e={},t={};for(const r of s)if(Array.isArray(r))Array.isArray(e)||(e=[]),e=[...e,...r];else if(O(r)){for(let[n,a]of Object.entries(r))O(a)&&n in e&&(a=K(e[n],a)),e={...e,[n]:a};O(r.headers)&&(t=de(t,r.headers),e.headers=t)}return e},Ke=(()=>{let s=!1,e=!1;const t=typeof globalThis.ReadableStream=="function",r=typeof globalThis.Request=="function";return t&&r&&(e=new globalThis.Request("https://empty.invalid",{body:new globalThis.ReadableStream,method:"POST",get duplex(){return s=!0,"half"}}).headers.has("Content-Type")),s&&!e})(),Qe=typeof globalThis.AbortController=="function",Xe=typeof globalThis.ReadableStream=="function",Ze=typeof globalThis.FormData=="function",me=["get","post","put","patch","head","delete"],et={json:"application/json",text:"text/*",formData:"multipart/form-data",arrayBuffer:"*/*",blob:"*/*"},j=2147483647,pe=Symbol("stop"),tt={json:!0,parseJson:!0,searchParams:!0,prefixUrl:!0,retry:!0,timeout:!0,hooks:!0,throwHttpErrors:!0,onDownloadProgress:!0,fetch:!0},rt={method:!0,headers:!0,body:!0,mode:!0,credentials:!0,cache:!0,redirect:!0,referrer:!0,referrerPolicy:!0,integrity:!0,keepalive:!0,signal:!0,window:!0,dispatcher:!0,duplex:!0},st=s=>me.includes(s)?s.toUpperCase():s,nt=["get","put","head","delete","options","trace"],it=[408,413,429,500,502,503,504],fe=[413,429,503],ee={limit:2,methods:nt,statusCodes:it,afterStatusCodes:fe,maxRetryAfter:Number.POSITIVE_INFINITY,backoffLimit:Number.POSITIVE_INFINITY,delay:s=>.3*2**(s-1)*1e3},at=(s={})=>{if(typeof s=="number")return{...ee,limit:s};if(s.methods&&!Array.isArray(s.methods))throw new Error("retry.methods must be an array");if(s.statusCodes&&!Array.isArray(s.statusCodes))throw new Error("retry.statusCodes must be an array");return{...ee,...s,afterStatusCodes:fe}};async function ot(s,e,t,r){return new Promise((n,a)=>{const o=setTimeout(()=>{t&&t.abort(),a(new he(s))},r.timeout);r.fetch(s,e).then(n).catch(a).then(()=>{clearTimeout(o)})})}async function ct(s,{signal:e}){return new Promise((t,r)=>{e&&(e.throwIfAborted(),e.addEventListener("abort",n,{once:!0}));function n(){clearTimeout(a),r(e.reason)}const a=setTimeout(()=>{e==null||e.removeEventListener("abort",n),t()},s)})}const ut=(s,e)=>{const t={};for(const r in e)!(r in rt)&&!(r in tt)&&!(r in s)&&(t[r]=e[r]);return t};class V{static create(e,t){const r=new V(e,t),n=async()=>{if(typeof r._options.timeout=="number"&&r._options.timeout>j)throw new RangeError(`The \`timeout\` option cannot be greater than ${j}`);await Promise.resolve();let c=await r._fetch();for(const u of r._options.hooks.afterResponse){const l=await u(r.request,r._options,r._decorateResponse(c.clone()));l instanceof globalThis.Response&&(c=l)}if(r._decorateResponse(c),!c.ok&&r._options.throwHttpErrors){let u=new Z(c,r.request,r._options);for(const l of r._options.hooks.beforeError)u=await l(u);throw u}if(r._options.onDownloadProgress){if(typeof r._options.onDownloadProgress!="function")throw new TypeError("The `onDownloadProgress` option must be a function");if(!Xe)throw new Error("Streams are not supported in your environment. `ReadableStream` is missing.");return r._stream(c.clone(),r._options.onDownloadProgress)}return c},o=r._options.retry.methods.includes(r.request.method.toLowerCase())?r._retry(n):n();for(const[c,u]of Object.entries(et))o[c]=async()=>{r.request.headers.set("accept",r.request.headers.get("accept")||u);const h=(await o).clone();if(c==="json"){if(h.status===204||(await h.clone().arrayBuffer()).byteLength===0)return"";if(t.parseJson)return t.parseJson(await h.text())}return h[c]()};return o}constructor(e,t={}){if(Object.defineProperty(this,"request",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"abortController",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_retryCount",{enumerable:!0,configurable:!0,writable:!0,value:0}),Object.defineProperty(this,"_input",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_options",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this._input=e,this._options={credentials:this._input.credentials||"same-origin",...t,headers:de(this._input.headers,t.headers),hooks:K({beforeRequest:[],beforeRetry:[],beforeError:[],afterResponse:[]},t.hooks),method:st(t.method??this._input.method),prefixUrl:String(t.prefixUrl||""),retry:at(t.retry),throwHttpErrors:t.throwHttpErrors!==!1,timeout:t.timeout??1e4,fetch:t.fetch??globalThis.fetch.bind(globalThis)},typeof this._input!="string"&&!(this._input instanceof URL||this._input instanceof globalThis.Request))throw new TypeError("`input` must be a string, URL, or Request");if(this._options.prefixUrl&&typeof this._input=="string"){if(this._input.startsWith("/"))throw new Error("`input` must not begin with a slash when using `prefixUrl`");this._options.prefixUrl.endsWith("/")||(this._options.prefixUrl+="/"),this._input=this._options.prefixUrl+this._input}if(Qe){if(this.abortController=new globalThis.AbortController,this._options.signal){const r=this._options.signal;this._options.signal.addEventListener("abort",()=>{this.abortController.abort(r.reason)})}this._options.signal=this.abortController.signal}if(Ke&&(this._options.duplex="half"),this.request=new globalThis.Request(this._input,this._options),this._options.searchParams){const n="?"+(typeof this._options.searchParams=="string"?this._options.searchParams.replace(/^\?/,""):new URLSearchParams(this._options.searchParams).toString()),a=this.request.url.replace(/(?:\?.*?)?(?=#|$)/,n);(Ze&&this._options.body instanceof globalThis.FormData||this._options.body instanceof URLSearchParams)&&!(this._options.headers&&this._options.headers["content-type"])&&this.request.headers.delete("content-type"),this.request=new globalThis.Request(new globalThis.Request(a,{...this.request}),this._options)}this._options.json!==void 0&&(this._options.body=JSON.stringify(this._options.json),this.request.headers.set("content-type",this._options.headers.get("content-type")??"application/json"),this.request=new globalThis.Request(this.request,{body:this._options.body}))}_calculateRetryDelay(e){if(this._retryCount++,this._retryCount<this._options.retry.limit&&!(e instanceof he)){if(e instanceof Z){if(!this._options.retry.statusCodes.includes(e.response.status))return 0;const r=e.response.headers.get("Retry-After");if(r&&this._options.retry.afterStatusCodes.includes(e.response.status)){let n=Number(r);return Number.isNaN(n)?n=Date.parse(r)-Date.now():n*=1e3,this._options.retry.maxRetryAfter!==void 0&&n>this._options.retry.maxRetryAfter?0:n}if(e.response.status===413)return 0}const t=this._options.retry.delay(this._retryCount);return Math.min(this._options.retry.backoffLimit,t)}return 0}_decorateResponse(e){return this._options.parseJson&&(e.json=async()=>this._options.parseJson(await e.text())),e}async _retry(e){try{return await e()}catch(t){const r=Math.min(this._calculateRetryDelay(t),j);if(r!==0&&this._retryCount>0){await ct(r,{signal:this._options.signal});for(const n of this._options.hooks.beforeRetry)if(await n({request:this.request,options:this._options,error:t,retryCount:this._retryCount})===pe)return;return this._retry(e)}throw t}}async _fetch(){for(const t of this._options.hooks.beforeRequest){const r=await t(this.request,this._options);if(r instanceof Request){this.request=r;break}if(r instanceof Response)return r}const e=ut(this.request,this._options);return this._options.timeout===!1?this._options.fetch(this.request.clone(),e):ot(this.request.clone(),e,this.abortController,this._options)}_stream(e,t){const r=Number(e.headers.get("content-length"))||0;let n=0;return e.status===204?(t&&t({percent:1,totalBytes:r,transferredBytes:n},new Uint8Array),new globalThis.Response(null,{status:e.status,statusText:e.statusText,headers:e.headers})):new globalThis.Response(new globalThis.ReadableStream({async start(a){const o=e.body.getReader();t&&t({percent:0,transferredBytes:0,totalBytes:r},new Uint8Array);async function c(){const{done:u,value:l}=await o.read();if(u){a.close();return}if(t){n+=l.byteLength;const h=r===0?0:n/r;t({percent:h,transferredBytes:n,totalBytes:r},l)}a.enqueue(l),await c()}await c()}}),{status:e.status,statusText:e.statusText,headers:e.headers})}}/*! MIT License © Sindre Sorhus */const F=s=>{const e=(t,r)=>V.create(t,E(s,r));for(const t of me)e[t]=(r,n)=>V.create(r,E(s,n,{method:t}));return e.create=t=>F(E(t)),e.extend=t=>F(E(s,t)),e.stop=pe,e},lt=F(),ht=lt,te=ht.create({headers:{referrer:"https://sk.thorswap.net",referer:"https://sk.thorswap.net","Content-Type":"application/json"}}),ge={get:(s,e)=>te.get(s,e).json(),post:(s,e)=>te.post(s,e).json()},re=Object.values(i.Chain),dt=(s="")=>{const e=s.toUpperCase(),[t]=e.split(".");if(re.includes(t))return!0;const[r]=e.split("/");if(re.includes(r))return!0;throw new Error(`Invalid identifier: ${s}. Expected format: <Chain>.<Ticker> or <Chain>.<Ticker>-<ContractAddress>`)},v=8,w=s=>10n**BigInt(s),T=s=>Math.log10(parseFloat(s.toString()));function I({value:s,bigIntDecimal:e=v,decimal:t=v}){const r=s<0n;let n=s.toString().substring(r?1:0);const a=t-(n.length-1);a>0&&(n="0".repeat(a)+n);const o=n.length-t;let c=n.slice(-t);return parseInt(c[e])>=5?c=`${c.substring(0,e-1)}${(parseInt(c[e-1])+1).toString()}`:c=c.substring(0,e),`${r?"-":""}${n.slice(0,o)}.${c}`.replace(/\.?0*$/,"")}var y,S,k,_e,q,ye,$,W,b,R,B,G;const P=class P{constructor(e){_(this,y);_(this,k);_(this,q);_(this,$);_(this,b);_(this,B);p(this,"decimalMultiplier",10n**8n);p(this,"bigIntValue",0n);p(this,"decimal");const t=L(e);this.decimal=typeof e=="object"?e.decimal:void 0,this.decimalMultiplier=w(Math.max(m(this,B,G).call(this,m(this,b,R).call(this,t)),this.decimal||0)),m(this,k,_e).call(this,t)}static fromBigInt(e,t){return new P({decimal:t,value:I({value:e,bigIntDecimal:t,decimal:t})})}static shiftDecimals({value:e,from:t,to:r}){return this.fromBigInt(new P(e).bigIntValue*w(r)/w(t),r)}get baseValue(){return this.getBaseValue("string")}get baseValueNumber(){return this.getBaseValue("number")}get baseValueBigInt(){return this.getBaseValue("bigint")}set(e){return new this.constructor({decimal:this.decimal,value:e,identifier:this.toString()})}add(...e){return m(this,y,S).call(this,"add",...e)}sub(...e){return m(this,y,S).call(this,"sub",...e)}mul(...e){return m(this,y,S).call(this,"mul",...e)}div(...e){return m(this,y,S).call(this,"div",...e)}gt(e){return this.bigIntValue>this.getBigIntValue(e)}gte(e){return this.bigIntValue>=this.getBigIntValue(e)}lt(e){return this.bigIntValue<this.getBigIntValue(e)}lte(e){return this.bigIntValue<=this.getBigIntValue(e)}eqValue(e){return this.bigIntValue===this.getBigIntValue(e)}getValue(e){const t=this.formatBigIntToSafeValue(this.bigIntValue,this.decimal||T(this.decimalMultiplier));switch(e){case"number":return Number(t);case"string":return t;default:return this.bigIntValue*BigInt(this.decimal||8n)/this.decimalMultiplier}}getBaseValue(e){const t=this.decimalMultiplier/w(this.decimal||i.BaseDecimal.THOR),r=this.bigIntValue/t;switch(e){case"number":return Number(r);case"string":return r.toString();default:return r}}getBigIntValue(e,t){if(!t&&typeof e=="object")return e.bigIntValue;const r=L(e),n=m(this,b,R).call(this,r);return n==="0"||n==="undefined"?0n:m(this,$,W).call(this,n,t)}formatBigIntToSafeValue(e,t){const r=t||this.decimal||v,n=Math.max(r,T(this.decimalMultiplier)),a=e<0n,o=e.toString().substring(a?1:0),c=n-(o.length-1),u=c>0?"0".repeat(c)+o:o,l=u.length-n;let h=u.slice(-n);return parseInt(h[r])>=5?h=`${h.substring(0,r-1)}${(parseInt(h[r-1])+1).toString()}`:h=h.substring(0,r),`${a?"-":""}${u.slice(0,l)}.${h}`.replace(/\.?0*$/,"")}toSignificant(e=6){const[t,r]=this.getValue("string").split("."),n=t||"",a=r||"",o=parseInt(n)?n.length+a.length:a.length;if(o<=e)return this.getValue("string");if(n.length>=e)return n.slice(0,e).padEnd(n.length,"0");if(parseInt(n))return`${n}.${a.slice(0,e-n.length)}`.padEnd(o-e,"0");const c=parseInt(a),u=`${c}`.slice(0,e);return`0.${u.padStart(a.length-`${c}`.length+u.length,"0")}`}toFixed(e=6){const[t,r]=this.getValue("string").split("."),n=t||"",a=r||"";if(parseInt(n))return`${n}.${a.slice(0,e)}`.padEnd(e,"0");const o=parseInt(a),c=`${o}`.slice(0,e);return`0.${c.padStart(a.length-`${o}`.length+c.length,"0")}`}};y=new WeakSet,S=function(e,...t){const r=m(this,q,ye).call(this,this,...t),n=w(r),a=t.reduce((c,u)=>{const l=this.getBigIntValue(u,r);switch(e){case"add":return c+l;case"sub":return c-l;case"mul":return c*l/n;case"div":{if(l===0n)throw new RangeError("Division by zero");return c*n/l}default:return c}},this.bigIntValue*n/this.decimalMultiplier),o=I({bigIntDecimal:r,decimal:Math.max(r,T(this.decimalMultiplier)),value:a});return new this.constructor({decimal:this.decimal,value:o,identifier:this.toString()})},k=new WeakSet,_e=function(e){const t=m(this,b,R).call(this,e)||"0";this.bigIntValue=m(this,$,W).call(this,t)},q=new WeakSet,ye=function(...e){const t=e.map(r=>typeof r=="object"?r.decimal||T(r.decimalMultiplier):m(this,B,G).call(this,m(this,b,R).call(this,r))).filter(Boolean);return Math.max(...t,v)},$=new WeakSet,W=function(e,t){const r=t?w(t):this.decimalMultiplier,n=T(r),[a="",o=""]=e.split(".");return BigInt(`${a}${o.padEnd(n,"0")}`)},b=new WeakSet,R=function(e){const r=`${typeof e=="number"?Number(e).toLocaleString("fullwide",{useGrouping:!1,maximumFractionDigits:20}):L(e)}`.replaceAll(",",".").split(".");return r.length>1?`${r.slice(0,-1).join("")}.${r.at(-1)}`:r[0]},B=new WeakSet,G=function(e){var r;const t=((r=e.split(".")[1])==null?void 0:r.length)||0;return Math.max(t,v)};let A=P;function L(s){return typeof s=="object"?"getValue"in s?s.getValue("string"):s.value:s}const M=(s,e)=>typeof s=="bigint"?I({value:s,bigIntDecimal:e,decimal:e}):s;let Y;const U=s=>{if(!Y)throw new Error("Static assets not loaded, call await AssetValue.loadStaticAssets() first");return Y.get(s.toUpperCase())||{decimal:i.BaseDecimal.THOR,identifier:""}},se=async(s,e=0)=>{dt(s);const t=await J(z(s)),r=M(e,t);return new f({decimal:t,value:r,identifier:s})};class f extends A{constructor(t){super(t.value instanceof A?t.value:{decimal:t.decimal,value:t.value});p(this,"address");p(this,"chain");p(this,"isSynthetic",!1);p(this,"isGasAsset",!1);p(this,"symbol");p(this,"ticker");p(this,"type");const r="identifier"in t?t.identifier:`${t.chain}.${t.symbol}`,n=z(r);this.type=oe(n),this.chain=n.chain,this.ticker=n.ticker,this.symbol=n.symbol,this.address=n.address,this.isSynthetic=n.isSynthetic,this.isGasAsset=n.isGasAsset}get assetValue(){return`${this.getValue("string")} ${this.ticker}`}toString(t=!1){const r=this.isSynthetic?this.ticker:`${this.chain}.${this.ticker}`;return t?r:`${this.chain}.${this.symbol}`}eq({chain:t,symbol:r}){return this.chain===t&&this.symbol===r}static async fromString(t,r=0){return se(t,r)}static fromStringSync(t,r=0){const{decimal:n,identifier:a}=U(t),o=M(r,n);return a?new f({decimal:n,identifier:a,value:o}):void 0}static async fromIdentifier(t,r=0){return se(t,r)}static fromIdentifierSync(t,r=0){const{decimal:n,identifier:a}=U(t),o=M(r,n);return new f({decimal:n,identifier:a,value:o})}static fromChainOrSignature(t,r=0){const{decimal:n,identifier:a}=ae(t),o=M(r,n);return new f({value:o,decimal:n,identifier:a})}static async fromTCQuote(t,r=0){const n=await J(z(t)),a=this.shiftDecimals({value:r,from:i.BaseDecimal.THOR,to:n});return new f({value:a,identifier:t,decimal:n})}static fromTCQuoteStatic(t,r=0){const n=U(t),a=this.shiftDecimals({value:r,from:i.BaseDecimal.THOR,to:n.decimal});return new f({...n,value:a})}static async loadStaticAssets(){return new Promise(async(t,r)=>{try{const{ThorchainList:n,NativeList:a,...o}=await import("@swapkit/tokens");Y=[a,...Object.values(o)].reduce((u,{tokens:l})=>(l.forEach(({identifier:h,chain:g,...C})=>{const N="decimals"in C?C.decimals:i.BaseDecimal[g];u.set(h,{identifier:h,decimal:N})}),u),new Map),t({ok:!0})}catch(n){console.error(n),r({ok:!1,error:n,message:"Couldn't load static assets. Ensure you have installed @swapkit/tokens package"})}})}}const mt=s=>{const e=f.fromChainOrSignature(s);switch(s){case i.Chain.Bitcoin:case i.Chain.Litecoin:case i.Chain.BitcoinCash:return e.add(10001);case i.Chain.Dogecoin:return e.add(100000001);case i.Chain.Avalanche:case i.Chain.Ethereum:return e.add(10*10**9);case i.Chain.THORChain:case i.Chain.Maya:return e.add(0);default:return e.add(1)}},z=s=>{const e=s.slice(0,14).includes("/"),t=s.includes(".")?s:`${i.Chain.THORChain}.${s}`,[r,n]=t.split("."),[a,o]=n.split("-");return{address:o==null?void 0:o.toLowerCase(),chain:r,isGasAsset:ie({chain:r,symbol:n}),isSynthetic:e,symbol:o?`${a}-${(o==null?void 0:o.toLowerCase())??""}`:n,ticker:e?n:a}},pt={core_wallet_connection_not_found:10001,core_estimated_max_spendable_chain_not_supported:10002,core_extend_error:10003,core_inbound_data_not_found:10004,core_approve_asset_address_or_from_not_found:10005,core_chain_halted:10099,core_wallet_xdefi_not_installed:10101,core_wallet_evmwallet_not_installed:10102,core_wallet_walletconnect_not_installed:10103,core_wallet_keystore_not_installed:10104,core_wallet_ledger_not_installed:10105,core_wallet_trezor_not_installed:10106,core_wallet_keplr_not_installed:10107,core_wallet_okx_not_installed:10108,core_swap_invalid_params:10200,core_swap_route_not_complete:10201,core_swap_asset_not_recognized:10202,core_swap_contract_not_found:10203,core_swap_route_transaction_not_found:10204,core_swap_contract_not_supported:10205,core_swap_transaction_error:10206,core_swap_quote_mode_not_supported:10207,core_transaction_deposit_error:10301,core_transaction_create_liquidity_rune_error:10302,core_transaction_create_liquidity_asset_error:10303,core_transaction_create_liquidity_invalid_params:10304,core_transaction_add_liquidity_invalid_params:10305,core_transaction_add_liquidity_no_rune_address:10306,core_transaction_add_liquidity_rune_error:10307,core_transaction_add_liquidity_asset_error:10308,core_transaction_withdraw_error:10309,core_transaction_deposit_to_pool_error:10310,core_transaction_deposit_insufficient_funds_error:10311,core_transaction_deposit_gas_error:10312,core_transaction_deposit_server_error:10313,wallet_ledger_connection_error:20001,helpers_number_different_decimals:99101};class Q extends Error{constructor(e,t){console.error(t),super(e,{cause:{code:pt[e],message:e}}),Object.setPrototypeOf(this,Q.prototype)}}class D extends A{eq(e){return this.eqValue(e)}static fromBigInt(e,t){return new D({decimal:t,value:I({value:e,bigIntDecimal:t,decimal:t})})}}exports.AssetValue=f;exports.BigIntArithmetics=A;exports.RequestClient=ge;exports.SwapKitError=Q;exports.SwapKitNumber=D;exports.assetFromString=De;exports.derivationPathToString=Je;exports.filterAssets=xe;exports.formatBigIntToSafeValue=I;exports.gasFeeMultiplier=Pe;exports.getAssetType=oe;exports.getAsymmetricAssetShare=ue;exports.getAsymmetricAssetWithdrawAmount=je;exports.getAsymmetricRuneShare=ce;exports.getAsymmetricRuneWithdrawAmount=He;exports.getCommonAssetInfo=ae;exports.getDecimal=J;exports.getEstimatedPoolShare=Ue;exports.getLiquiditySlippage=Fe;exports.getMemoFor=Ge;exports.getMinAmountByChain=mt;exports.getSymmetricPoolShare=le;exports.getSymmetricWithdraw=Le;exports.getTHORNameCost=Ye;exports.isGasAsset=ie;exports.validateTHORName=ze;
package/dist/index.d.ts CHANGED
@@ -36,13 +36,13 @@ export declare class AssetValue extends BigIntArithmetics {
36
36
  chain: Chain;
37
37
  symbol: string;
38
38
  }): boolean;
39
- static fromString(assetString: string, value?: number | string): Promise<AssetValue>;
40
- static fromStringSync(assetString: string, value?: number | string): AssetValue | undefined;
41
- static fromIdentifier(assetString: `${Chain}.${string}` | `${Chain}/${string}` | `${Chain}.${string}-${string}`, value?: number | string): Promise<AssetValue>;
42
- static fromIdentifierSync(identifier: TokenNames, value?: number | string): AssetValue;
43
- static fromChainOrSignature(assetString: CommonAssetString, value?: number | string): AssetValue;
44
- static fromTCQuote(identifier: TCTokenNames, value?: number | string): Promise<AssetValue>;
45
- static fromTCQuoteStatic(identifier: TCTokenNames, value?: number | string): AssetValue;
39
+ static fromString(assetString: string, value?: NumberPrimitives): Promise<AssetValue>;
40
+ static fromStringSync(assetString: string, value?: NumberPrimitives): AssetValue | undefined;
41
+ static fromIdentifier(assetString: `${Chain}.${string}` | `${Chain}/${string}` | `${Chain}.${string}-${string}`, value?: NumberPrimitives): Promise<AssetValue>;
42
+ static fromIdentifierSync(identifier: TokenNames, value?: NumberPrimitives): AssetValue;
43
+ static fromChainOrSignature(assetString: CommonAssetString, value?: NumberPrimitives): AssetValue;
44
+ static fromTCQuote(identifier: TCTokenNames, value?: NumberPrimitives): Promise<AssetValue>;
45
+ static fromTCQuoteStatic(identifier: TCTokenNames, value?: NumberPrimitives): AssetValue;
46
46
  static loadStaticAssets(): Promise<{
47
47
  ok: true;
48
48
  } | {
@@ -289,7 +289,7 @@ export declare type MemoOptions<T extends MemoType> = {
289
289
  [MemoType.THORNAME_REGISTER]: Omit<ThornameRegisterParam, 'preferredAsset' | 'expiryBlock'>;
290
290
  }[T];
291
291
 
292
- declare type NumberPrimitives = bigint | number | string;
292
+ export declare type NumberPrimitives = bigint | number | string;
293
293
 
294
294
  declare type NumberPrimitivesType = {
295
295
  bigint: bigint;
@@ -325,6 +325,7 @@ export declare class SwapKitError extends Error {
325
325
 
326
326
  export declare class SwapKitNumber extends BigIntArithmetics {
327
327
  eq(value: SwapKitValueType): boolean;
328
+ static fromBigInt(value: bigint, decimal?: number): SwapKitNumber;
328
329
  }
329
330
 
330
331
  export declare type SwapKitValueType = BigIntArithmetics | string | number;
package/dist/index.es.js CHANGED
@@ -1,6 +1,6 @@
1
- var _t = Object.defineProperty;
2
- var gt = (s, t, e) => t in s ? _t(s, t, { enumerable: !0, configurable: !0, writable: !0, value: e }) : s[t] = e;
3
- var p = (s, t, e) => (gt(s, typeof t != "symbol" ? t + "" : t, e), e), bt = (s, t, e) => {
1
+ var bt = Object.defineProperty;
2
+ var yt = (s, t, e) => t in s ? bt(s, t, { enumerable: !0, configurable: !0, writable: !0, value: e }) : s[t] = e;
3
+ var p = (s, t, e) => (yt(s, typeof t != "symbol" ? t + "" : t, e), e), wt = (s, t, e) => {
4
4
  if (!t.has(s))
5
5
  throw TypeError("Cannot " + e);
6
6
  };
@@ -9,47 +9,47 @@ var y = (s, t, e) => {
9
9
  throw TypeError("Cannot add the same private member more than once");
10
10
  t instanceof WeakSet ? t.add(s) : t.set(s, e);
11
11
  };
12
- var f = (s, t, e) => (bt(s, t, "access private method"), e);
13
- import { FeeOption as H, BaseDecimal as m, Chain as o, ChainToRPC as yt, MemoType as g } from "@swapkit/types";
14
- const wt = "0x313ce567", rt = async ({ chain: s, to: t }) => {
12
+ var f = (s, t, e) => (wt(s, t, "access private method"), e);
13
+ import { FeeOption as D, BaseDecimal as m, Chain as o, ChainToRPC as At, MemoType as g } from "@swapkit/types";
14
+ const Tt = "0x313ce567", nt = async ({ chain: s, to: t }) => {
15
15
  try {
16
- const { result: e } = await zt.post(yt[s], {
16
+ const { result: e } = await Kt.post(At[s], {
17
17
  headers: { accept: "*/*", "cache-control": "no-cache" },
18
18
  body: JSON.stringify({
19
19
  id: 44,
20
20
  jsonrpc: "2.0",
21
21
  method: "eth_call",
22
- params: [{ to: t.toLowerCase(), data: wt }, "latest"]
22
+ params: [{ to: t.toLowerCase(), data: Tt }, "latest"]
23
23
  })
24
24
  });
25
25
  return parseInt(BigInt(e).toString());
26
26
  } catch (e) {
27
27
  return console.error(e), m[s];
28
28
  }
29
- }, At = async (s) => {
29
+ }, vt = async (s) => {
30
30
  if (s === o.Ethereum)
31
31
  return m.ETH;
32
32
  const [, t] = s.split("-");
33
- return t != null && t.startsWith("0x") ? rt({ chain: o.Ethereum, to: t }) : m.ETH;
34
- }, Tt = async (s) => {
33
+ return t != null && t.startsWith("0x") ? nt({ chain: o.Ethereum, to: t }) : m.ETH;
34
+ }, Rt = async (s) => {
35
35
  const [, t] = s.split("-");
36
- return t != null && t.startsWith("0x") ? rt({ chain: o.Avalanche, to: t.toLowerCase() }) : m.AVAX;
37
- }, Rt = async (s) => s === o.BinanceSmartChain ? m.BSC : m.BSC, st = async ({ chain: s, symbol: t }) => {
36
+ return t != null && t.startsWith("0x") ? nt({ chain: o.Avalanche, to: t.toLowerCase() }) : m.AVAX;
37
+ }, St = async (s) => s === o.BinanceSmartChain ? m.BSC : m.BSC, it = async ({ chain: s, symbol: t }) => {
38
38
  switch (s) {
39
39
  case o.Ethereum:
40
- return At(t);
40
+ return vt(t);
41
41
  case o.Avalanche:
42
- return Tt(t);
43
- case o.BinanceSmartChain:
44
42
  return Rt(t);
43
+ case o.BinanceSmartChain:
44
+ return St(t);
45
45
  default:
46
46
  return m[s];
47
47
  }
48
- }, te = {
49
- [H.Average]: 1.2,
50
- [H.Fast]: 1.5,
51
- [H.Fastest]: 2
52
- }, St = ({ chain: s, symbol: t }) => {
48
+ }, ee = {
49
+ [D.Average]: 1.2,
50
+ [D.Fast]: 1.5,
51
+ [D.Fastest]: 2
52
+ }, Ct = ({ chain: s, symbol: t }) => {
53
53
  switch (s) {
54
54
  case o.Bitcoin:
55
55
  case o.BitcoinCash:
@@ -75,7 +75,7 @@ const wt = "0x313ce567", rt = async ({ chain: s, to: t }) => {
75
75
  case o.THORChain:
76
76
  return t === "RUNE";
77
77
  }
78
- }, vt = (s) => {
78
+ }, $t = (s) => {
79
79
  switch (s) {
80
80
  case "ETH.THOR":
81
81
  return { identifier: "ETH.THOR-0xa5f2211b9b8170f694421f2046281775e8468044", decimal: 18 };
@@ -104,7 +104,7 @@ const wt = "0x313ce567", rt = async ({ chain: s, to: t }) => {
104
104
  case o.Ethereum:
105
105
  return { identifier: `${s}.${s}`, decimal: m[s] };
106
106
  }
107
- }, Ct = ({ chain: s, symbol: t }) => {
107
+ }, It = ({ chain: s, symbol: t }) => {
108
108
  if (t.includes("/"))
109
109
  return "Synth";
110
110
  switch (s) {
@@ -134,40 +134,40 @@ const wt = "0x313ce567", rt = async ({ chain: s, to: t }) => {
134
134
  case o.Optimism:
135
135
  return [o.Ethereum, o.Optimism].includes(t) ? "Native" : "OPTIMISM";
136
136
  }
137
- }, ee = (s) => {
137
+ }, re = (s) => {
138
138
  var a;
139
139
  const [t, ...e] = s.split("."), r = s.includes("/"), n = e.join("."), i = (a = n == null ? void 0 : n.split("-")) == null ? void 0 : a[0];
140
140
  return { chain: t, symbol: n, ticker: i, synth: r };
141
- }, $t = new RegExp(
141
+ }, Et = new RegExp(
142
142
  /(.)\1{6}|\.ORG|\.NET|\.FINANCE|\.COM|WWW|HTTP|\\\\|\/\/|[\s$%:[\]]/,
143
143
  "gmi"
144
- ), re = (s) => s.filter(
145
- (t) => !$t.test(t.toString()) && !t.toString().includes("undefined")
146
- ), It = ({
144
+ ), se = (s) => s.filter(
145
+ (t) => !Et.test(t.toString()) && !t.toString().includes("undefined")
146
+ ), Ot = ({
147
147
  liquidityUnits: s,
148
148
  poolUnits: t,
149
149
  runeDepth: e
150
150
  }) => {
151
151
  const r = d(s), n = d(t), i = d(e), a = r.mul(i), c = n.mul(n).mul(2), u = n.mul(r).mul(2), l = r.mul(r), h = n.mul(n).mul(n);
152
152
  return a.mul(c.sub(u).add(l)).div(h);
153
- }, Et = ({
153
+ }, Vt = ({
154
154
  liquidityUnits: s,
155
155
  poolUnits: t,
156
156
  assetDepth: e
157
157
  }) => {
158
158
  const r = d(s), n = d(t), i = d(e), a = r.mul(i), c = n.mul(n).mul(2), u = n.mul(r).mul(2), l = r.mul(r), h = a.mul(c.sub(u).add(l)), _ = n.mul(n).mul(n);
159
159
  return h.div(_);
160
- }, se = ({
160
+ }, ne = ({
161
161
  percent: s,
162
162
  runeDepth: t,
163
163
  liquidityUnits: e,
164
164
  poolUnits: r
165
- }) => It({ runeDepth: t, liquidityUnits: e, poolUnits: r }).mul(s), ne = ({
165
+ }) => Ot({ runeDepth: t, liquidityUnits: e, poolUnits: r }).mul(s), ie = ({
166
166
  percent: s,
167
167
  assetDepth: t,
168
168
  liquidityUnits: e,
169
169
  poolUnits: r
170
- }) => Et({ assetDepth: t, liquidityUnits: e, poolUnits: r }).mul(s), d = (s) => new Qt({ value: s, decimal: m.THOR }), Ot = ({
170
+ }) => Vt({ assetDepth: t, liquidityUnits: e, poolUnits: r }).mul(s), d = (s) => new Q({ value: s, decimal: m.THOR }), Bt = ({
171
171
  liquidityUnits: s,
172
172
  poolUnits: t,
173
173
  runeDepth: e,
@@ -175,17 +175,17 @@ const wt = "0x313ce567", rt = async ({ chain: s, to: t }) => {
175
175
  }) => ({
176
176
  assetAmount: d(r).mul(s).div(t),
177
177
  runeAmount: d(e).mul(s).div(t)
178
- }), ie = ({
178
+ }), oe = ({
179
179
  liquidityUnits: s,
180
180
  poolUnits: t,
181
181
  runeDepth: e,
182
182
  assetDepth: r,
183
183
  percent: n
184
184
  }) => Object.fromEntries(
185
- Object.entries(Ot({ liquidityUnits: s, poolUnits: t, runeDepth: e, assetDepth: r })).map(
185
+ Object.entries(Bt({ liquidityUnits: s, poolUnits: t, runeDepth: e, assetDepth: r })).map(
186
186
  ([i, a]) => [i, a.mul(n)]
187
187
  )
188
- ), oe = ({
188
+ ), ae = ({
189
189
  runeDepth: s,
190
190
  poolUnits: t,
191
191
  assetDepth: e,
@@ -193,12 +193,12 @@ const wt = "0x313ce567", rt = async ({ chain: s, to: t }) => {
193
193
  runeAmount: n,
194
194
  assetAmount: i
195
195
  }) => {
196
- const a = d(s), c = d(e), u = d(t), l = d(n), h = d(i), _ = l.mul(c), T = h.mul(a), P = l.mul(h), dt = a.mul(c), mt = u.mul(_.add(T.add(P.mul(2)))), ft = _.add(T.add(dt.mul(2))), J = mt.div(ft), N = d(r).add(J);
197
- if (J.baseValueNumber === 0)
198
- return N.div(u).baseValueNumber;
199
- const pt = u.add(N);
200
- return N.div(pt).baseValueNumber;
201
- }, ae = ({
196
+ const a = d(s), c = d(e), u = d(t), l = d(n), h = d(i), _ = l.mul(c), T = h.mul(a), H = l.mul(h), ft = a.mul(c), pt = u.mul(_.add(T.add(H.mul(2)))), _t = _.add(T.add(ft.mul(2))), X = pt.div(_t), j = d(r).add(X);
197
+ if (X.baseValueNumber === 0)
198
+ return j.div(u).baseValueNumber;
199
+ const gt = u.add(j);
200
+ return j.div(gt).baseValueNumber;
201
+ }, ce = ({
202
202
  runeAmount: s,
203
203
  assetAmount: t,
204
204
  runeDepth: e,
@@ -210,7 +210,7 @@ const wt = "0x313ce567", rt = async ({ chain: s, to: t }) => {
210
210
  symbol: s,
211
211
  ticker: t,
212
212
  chain: e
213
- }) => e === "ETH" && t !== "ETH" ? `${t}-${s.slice(-3)}` : s, ce = (s, t) => {
213
+ }) => e === "ETH" && t !== "ETH" ? `${t}-${s.slice(-3)}` : s, ue = (s, t) => {
214
214
  switch (s) {
215
215
  case g.LEAVE:
216
216
  case g.BOND: {
@@ -241,17 +241,17 @@ const wt = "0x313ce567", rt = async ({ chain: s, to: t }) => {
241
241
  default:
242
242
  return "";
243
243
  }
244
- }, ue = (s) => {
244
+ }, le = (s) => {
245
245
  if (s < 0)
246
246
  throw new Error("Invalid number of year");
247
247
  return 10 + s;
248
- }, le = (s) => {
248
+ }, he = (s) => {
249
249
  if (s.length > 30)
250
250
  return !1;
251
251
  const t = /^[a-zA-Z0-9+_-]+$/g;
252
252
  return !!s.match(t);
253
- }, he = ([s, t, e, r, n]) => `${s}'/${t}'/${e}'/${r}${typeof n != "number" ? "" : `/${n}`}`;
254
- class K extends Error {
253
+ }, de = ([s, t, e, r, n]) => `${s}'/${t}'/${e}'/${r}${typeof n != "number" ? "" : `/${n}`}`;
254
+ class Z extends Error {
255
255
  constructor(t, e, r) {
256
256
  const n = t.status || t.status === 0 ? t.status : "", i = t.statusText || "", a = `${n} ${i}`.trim(), c = a ? `status code ${a}` : "an unknown error";
257
257
  super(`Request failed with ${c}`), Object.defineProperty(this, "response", {
@@ -272,7 +272,7 @@ class K extends Error {
272
272
  }), this.name = "HTTPError", this.response = t, this.request = e, this.options = r;
273
273
  }
274
274
  }
275
- class nt extends Error {
275
+ class ot extends Error {
276
276
  constructor(t) {
277
277
  super("Request timed out"), Object.defineProperty(this, "request", {
278
278
  enumerable: !0,
@@ -282,28 +282,28 @@ class nt extends Error {
282
282
  }), this.name = "TimeoutError", this.request = t;
283
283
  }
284
284
  }
285
- const V = (s) => s !== null && typeof s == "object", B = (...s) => {
285
+ const B = (s) => s !== null && typeof s == "object", V = (...s) => {
286
286
  for (const t of s)
287
- if ((!V(t) || Array.isArray(t)) && t !== void 0)
287
+ if ((!B(t) || Array.isArray(t)) && t !== void 0)
288
288
  throw new TypeError("The `options` argument must be an object");
289
- return z({}, ...s);
290
- }, it = (s = {}, t = {}) => {
289
+ return K({}, ...s);
290
+ }, at = (s = {}, t = {}) => {
291
291
  const e = new globalThis.Headers(s), r = t instanceof globalThis.Headers, n = new globalThis.Headers(t);
292
292
  for (const [i, a] of n.entries())
293
293
  r && a === "undefined" || a === void 0 ? e.delete(i) : e.set(i, a);
294
294
  return e;
295
- }, z = (...s) => {
295
+ }, K = (...s) => {
296
296
  let t = {}, e = {};
297
297
  for (const r of s)
298
298
  if (Array.isArray(r))
299
299
  Array.isArray(t) || (t = []), t = [...t, ...r];
300
- else if (V(r)) {
300
+ else if (B(r)) {
301
301
  for (let [n, i] of Object.entries(r))
302
- V(i) && n in t && (i = z(t[n], i)), t = { ...t, [n]: i };
303
- V(r.headers) && (e = it(e, r.headers), t.headers = e);
302
+ B(i) && n in t && (i = K(t[n], i)), t = { ...t, [n]: i };
303
+ B(r.headers) && (e = at(e, r.headers), t.headers = e);
304
304
  }
305
305
  return t;
306
- }, Bt = (() => {
306
+ }, qt = (() => {
307
307
  let s = !1, t = !1;
308
308
  const e = typeof globalThis.ReadableStream == "function", r = typeof globalThis.Request == "function";
309
309
  return e && r && (t = new globalThis.Request("https://empty.invalid", {
@@ -314,13 +314,13 @@ const V = (s) => s !== null && typeof s == "object", B = (...s) => {
314
314
  return s = !0, "half";
315
315
  }
316
316
  }).headers.has("Content-Type")), s && !t;
317
- })(), Vt = typeof globalThis.AbortController == "function", qt = typeof globalThis.ReadableStream == "function", Mt = typeof globalThis.FormData == "function", ot = ["get", "post", "put", "patch", "head", "delete"], xt = {
317
+ })(), Mt = typeof globalThis.AbortController == "function", xt = typeof globalThis.ReadableStream == "function", Pt = typeof globalThis.FormData == "function", ct = ["get", "post", "put", "patch", "head", "delete"], Nt = {
318
318
  json: "application/json",
319
319
  text: "text/*",
320
320
  formData: "multipart/form-data",
321
321
  arrayBuffer: "*/*",
322
322
  blob: "*/*"
323
- }, j = 2147483647, at = Symbol("stop"), Pt = {
323
+ }, L = 2147483647, ut = Symbol("stop"), Ht = {
324
324
  json: !0,
325
325
  parseJson: !0,
326
326
  searchParams: !0,
@@ -331,7 +331,7 @@ const V = (s) => s !== null && typeof s == "object", B = (...s) => {
331
331
  throwHttpErrors: !0,
332
332
  onDownloadProgress: !0,
333
333
  fetch: !0
334
- }, Nt = {
334
+ }, jt = {
335
335
  method: !0,
336
336
  headers: !0,
337
337
  body: !0,
@@ -347,18 +347,18 @@ const V = (s) => s !== null && typeof s == "object", B = (...s) => {
347
347
  window: !0,
348
348
  dispatcher: !0,
349
349
  duplex: !0
350
- }, Ht = (s) => ot.includes(s) ? s.toUpperCase() : s, jt = ["get", "put", "head", "delete", "options", "trace"], Lt = [408, 413, 429, 500, 502, 503, 504], ct = [413, 429, 503], Q = {
350
+ }, Dt = (s) => ct.includes(s) ? s.toUpperCase() : s, Lt = ["get", "put", "head", "delete", "options", "trace"], Ut = [408, 413, 429, 500, 502, 503, 504], lt = [413, 429, 503], tt = {
351
351
  limit: 2,
352
- methods: jt,
353
- statusCodes: Lt,
354
- afterStatusCodes: ct,
352
+ methods: Lt,
353
+ statusCodes: Ut,
354
+ afterStatusCodes: lt,
355
355
  maxRetryAfter: Number.POSITIVE_INFINITY,
356
356
  backoffLimit: Number.POSITIVE_INFINITY,
357
357
  delay: (s) => 0.3 * 2 ** (s - 1) * 1e3
358
- }, Dt = (s = {}) => {
358
+ }, Ft = (s = {}) => {
359
359
  if (typeof s == "number")
360
360
  return {
361
- ...Q,
361
+ ...tt,
362
362
  limit: s
363
363
  };
364
364
  if (s.methods && !Array.isArray(s.methods))
@@ -366,22 +366,22 @@ const V = (s) => s !== null && typeof s == "object", B = (...s) => {
366
366
  if (s.statusCodes && !Array.isArray(s.statusCodes))
367
367
  throw new Error("retry.statusCodes must be an array");
368
368
  return {
369
- ...Q,
369
+ ...tt,
370
370
  ...s,
371
- afterStatusCodes: ct
371
+ afterStatusCodes: lt
372
372
  };
373
373
  };
374
- async function Ut(s, t, e, r) {
374
+ async function Wt(s, t, e, r) {
375
375
  return new Promise((n, i) => {
376
376
  const a = setTimeout(() => {
377
- e && e.abort(), i(new nt(s));
377
+ e && e.abort(), i(new ot(s));
378
378
  }, r.timeout);
379
379
  r.fetch(s, t).then(n).catch(i).then(() => {
380
380
  clearTimeout(a);
381
381
  });
382
382
  });
383
383
  }
384
- async function Ft(s, { signal: t }) {
384
+ async function Gt(s, { signal: t }) {
385
385
  return new Promise((e, r) => {
386
386
  t && (t.throwIfAborted(), t.addEventListener("abort", n, { once: !0 }));
387
387
  function n() {
@@ -392,17 +392,17 @@ async function Ft(s, { signal: t }) {
392
392
  }, s);
393
393
  });
394
394
  }
395
- const Wt = (s, t) => {
395
+ const Yt = (s, t) => {
396
396
  const e = {};
397
397
  for (const r in t)
398
- !(r in Nt) && !(r in Pt) && !(r in s) && (e[r] = t[r]);
398
+ !(r in jt) && !(r in Ht) && !(r in s) && (e[r] = t[r]);
399
399
  return e;
400
400
  };
401
401
  class q {
402
402
  static create(t, e) {
403
403
  const r = new q(t, e), n = async () => {
404
- if (typeof r._options.timeout == "number" && r._options.timeout > j)
405
- throw new RangeError(`The \`timeout\` option cannot be greater than ${j}`);
404
+ if (typeof r._options.timeout == "number" && r._options.timeout > L)
405
+ throw new RangeError(`The \`timeout\` option cannot be greater than ${L}`);
406
406
  await Promise.resolve();
407
407
  let c = await r._fetch();
408
408
  for (const u of r._options.hooks.afterResponse) {
@@ -410,7 +410,7 @@ class q {
410
410
  l instanceof globalThis.Response && (c = l);
411
411
  }
412
412
  if (r._decorateResponse(c), !c.ok && r._options.throwHttpErrors) {
413
- let u = new K(c, r.request, r._options);
413
+ let u = new Z(c, r.request, r._options);
414
414
  for (const l of r._options.hooks.beforeError)
415
415
  u = await l(u);
416
416
  throw u;
@@ -418,13 +418,13 @@ class q {
418
418
  if (r._options.onDownloadProgress) {
419
419
  if (typeof r._options.onDownloadProgress != "function")
420
420
  throw new TypeError("The `onDownloadProgress` option must be a function");
421
- if (!qt)
421
+ if (!xt)
422
422
  throw new Error("Streams are not supported in your environment. `ReadableStream` is missing.");
423
423
  return r._stream(c.clone(), r._options.onDownloadProgress);
424
424
  }
425
425
  return c;
426
426
  }, a = r._options.retry.methods.includes(r.request.method.toLowerCase()) ? r._retry(n) : n();
427
- for (const [c, u] of Object.entries(xt))
427
+ for (const [c, u] of Object.entries(Nt))
428
428
  a[c] = async () => {
429
429
  r.request.headers.set("accept", r.request.headers.get("accept") || u);
430
430
  const h = (await a).clone();
@@ -469,17 +469,17 @@ class q {
469
469
  // TODO: credentials can be removed when the spec change is implemented in all browsers. Context: https://www.chromestatus.com/feature/4539473312350208
470
470
  credentials: this._input.credentials || "same-origin",
471
471
  ...e,
472
- headers: it(this._input.headers, e.headers),
473
- hooks: z({
472
+ headers: at(this._input.headers, e.headers),
473
+ hooks: K({
474
474
  beforeRequest: [],
475
475
  beforeRetry: [],
476
476
  beforeError: [],
477
477
  afterResponse: []
478
478
  }, e.hooks),
479
- method: Ht(e.method ?? this._input.method),
479
+ method: Dt(e.method ?? this._input.method),
480
480
  // eslint-disable-next-line @typescript-eslint/prefer-nullish-coalescing
481
481
  prefixUrl: String(e.prefixUrl || ""),
482
- retry: Dt(e.retry),
482
+ retry: Ft(e.retry),
483
483
  throwHttpErrors: e.throwHttpErrors !== !1,
484
484
  timeout: e.timeout ?? 1e4,
485
485
  fetch: e.fetch ?? globalThis.fetch.bind(globalThis)
@@ -490,7 +490,7 @@ class q {
490
490
  throw new Error("`input` must not begin with a slash when using `prefixUrl`");
491
491
  this._options.prefixUrl.endsWith("/") || (this._options.prefixUrl += "/"), this._input = this._options.prefixUrl + this._input;
492
492
  }
493
- if (Vt) {
493
+ if (Mt) {
494
494
  if (this.abortController = new globalThis.AbortController(), this._options.signal) {
495
495
  const r = this._options.signal;
496
496
  this._options.signal.addEventListener("abort", () => {
@@ -499,15 +499,15 @@ class q {
499
499
  }
500
500
  this._options.signal = this.abortController.signal;
501
501
  }
502
- if (Bt && (this._options.duplex = "half"), this.request = new globalThis.Request(this._input, this._options), this._options.searchParams) {
502
+ if (qt && (this._options.duplex = "half"), this.request = new globalThis.Request(this._input, this._options), this._options.searchParams) {
503
503
  const n = "?" + (typeof this._options.searchParams == "string" ? this._options.searchParams.replace(/^\?/, "") : new URLSearchParams(this._options.searchParams).toString()), i = this.request.url.replace(/(?:\?.*?)?(?=#|$)/, n);
504
- (Mt && 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(i, { ...this.request }), this._options);
504
+ (Pt && 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(i, { ...this.request }), this._options);
505
505
  }
506
506
  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 }));
507
507
  }
508
508
  _calculateRetryDelay(t) {
509
- if (this._retryCount++, this._retryCount < this._options.retry.limit && !(t instanceof nt)) {
510
- if (t instanceof K) {
509
+ if (this._retryCount++, this._retryCount < this._options.retry.limit && !(t instanceof ot)) {
510
+ if (t instanceof Z) {
511
511
  if (!this._options.retry.statusCodes.includes(t.response.status))
512
512
  return 0;
513
513
  const r = t.response.headers.get("Retry-After");
@@ -530,16 +530,16 @@ class q {
530
530
  try {
531
531
  return await t();
532
532
  } catch (e) {
533
- const r = Math.min(this._calculateRetryDelay(e), j);
533
+ const r = Math.min(this._calculateRetryDelay(e), L);
534
534
  if (r !== 0 && this._retryCount > 0) {
535
- await Ft(r, { signal: this._options.signal });
535
+ await Gt(r, { signal: this._options.signal });
536
536
  for (const n of this._options.hooks.beforeRetry)
537
537
  if (await n({
538
538
  request: this.request,
539
539
  options: this._options,
540
540
  error: e,
541
541
  retryCount: this._retryCount
542
- }) === at)
542
+ }) === ut)
543
543
  return;
544
544
  return this._retry(t);
545
545
  }
@@ -556,8 +556,8 @@ class q {
556
556
  if (r instanceof Response)
557
557
  return r;
558
558
  }
559
- const t = Wt(this.request, this._options);
560
- return this._options.timeout === !1 ? this._options.fetch(this.request.clone(), t) : Ut(this.request.clone(), t, this.abortController, this._options);
559
+ const t = Yt(this.request, this._options);
560
+ return this._options.timeout === !1 ? this._options.fetch(this.request.clone(), t) : Wt(this.request.clone(), t, this.abortController, this._options);
561
561
  }
562
562
  /* istanbul ignore next */
563
563
  _stream(t, e) {
@@ -594,32 +594,32 @@ class q {
594
594
  }
595
595
  }
596
596
  /*! MIT License © Sindre Sorhus */
597
- const U = (s) => {
598
- const t = (e, r) => q.create(e, B(s, r));
599
- for (const e of ot)
600
- t[e] = (r, n) => q.create(r, B(s, n, { method: e }));
601
- return t.create = (e) => U(B(e)), t.extend = (e) => U(B(s, e)), t.stop = at, t;
602
- }, Gt = U(), Yt = Gt, X = Yt.create({
597
+ const W = (s) => {
598
+ const t = (e, r) => q.create(e, V(s, r));
599
+ for (const e of ct)
600
+ t[e] = (r, n) => q.create(r, V(s, n, { method: e }));
601
+ return t.create = (e) => W(V(e)), t.extend = (e) => W(V(s, e)), t.stop = ut, t;
602
+ }, zt = W(), Jt = zt, et = Jt.create({
603
603
  headers: {
604
604
  referrer: "https://sk.thorswap.net",
605
605
  referer: "https://sk.thorswap.net",
606
606
  "Content-Type": "application/json"
607
607
  }
608
- }), zt = {
609
- get: (s, t) => X.get(s, t).json(),
610
- post: (s, t) => X.post(s, t).json()
611
- }, Z = Object.values(o), Jt = (s = "") => {
608
+ }), Kt = {
609
+ get: (s, t) => et.get(s, t).json(),
610
+ post: (s, t) => et.post(s, t).json()
611
+ }, rt = Object.values(o), Qt = (s = "") => {
612
612
  const t = s.toUpperCase(), [e] = t.split(".");
613
- if (Z.includes(e))
613
+ if (rt.includes(e))
614
614
  return !0;
615
615
  const [r] = t.split("/");
616
- if (Z.includes(r))
616
+ if (rt.includes(r))
617
617
  return !0;
618
618
  throw new Error(
619
619
  `Invalid identifier: ${s}. Expected format: <Chain>.<Ticker> or <Chain>.<Ticker>-<ContractAddress>`
620
620
  );
621
- }, $ = 8, R = (s) => 10n ** BigInt(s), S = (s) => Math.log10(parseFloat(s.toString()));
622
- function tt({
621
+ }, $ = 8, v = (s) => 10n ** BigInt(s), R = (s) => Math.log10(parseFloat(s.toString()));
622
+ function M({
623
623
  value: s,
624
624
  bigIntDecimal: t = $,
625
625
  decimal: e = $
@@ -635,27 +635,27 @@ function tt({
635
635
  ""
636
636
  );
637
637
  }
638
- var w, v, M, ut, x, lt, O, F, A, C, k, W;
639
- const I = class I {
638
+ var w, S, x, ht, P, dt, E, G, A, C, O, Y;
639
+ const N = class N {
640
640
  constructor(t) {
641
641
  y(this, w);
642
- y(this, M);
643
642
  y(this, x);
644
- y(this, O);
643
+ y(this, P);
644
+ y(this, E);
645
645
  y(this, A);
646
- y(this, k);
646
+ y(this, O);
647
647
  p(this, "decimalMultiplier", 10n ** 8n);
648
648
  p(this, "bigIntValue", 0n);
649
649
  p(this, "decimal");
650
- const e = L(t);
651
- this.decimal = typeof t == "object" ? t.decimal : void 0, this.decimalMultiplier = R(
652
- Math.max(f(this, k, W).call(this, f(this, A, C).call(this, e)), this.decimal || 0)
653
- ), f(this, M, ut).call(this, e);
650
+ const e = U(t);
651
+ this.decimal = typeof t == "object" ? t.decimal : void 0, this.decimalMultiplier = v(
652
+ Math.max(f(this, O, Y).call(this, f(this, A, C).call(this, e)), this.decimal || 0)
653
+ ), f(this, x, ht).call(this, e);
654
654
  }
655
655
  static fromBigInt(t, e) {
656
- return new I({
656
+ return new N({
657
657
  decimal: e,
658
- value: tt({ value: t, bigIntDecimal: e, decimal: e })
658
+ value: M({ value: t, bigIntDecimal: e, decimal: e })
659
659
  });
660
660
  }
661
661
  static shiftDecimals({
@@ -663,8 +663,8 @@ const I = class I {
663
663
  from: e,
664
664
  to: r
665
665
  }) {
666
- return I.fromBigInt(
667
- new I(t).bigIntValue * R(r) / R(e),
666
+ return this.fromBigInt(
667
+ new N(t).bigIntValue * v(r) / v(e),
668
668
  r
669
669
  );
670
670
  }
@@ -690,16 +690,16 @@ const I = class I {
690
690
  return new this.constructor({ decimal: this.decimal, value: t, identifier: this.toString() });
691
691
  }
692
692
  add(...t) {
693
- return f(this, w, v).call(this, "add", ...t);
693
+ return f(this, w, S).call(this, "add", ...t);
694
694
  }
695
695
  sub(...t) {
696
- return f(this, w, v).call(this, "sub", ...t);
696
+ return f(this, w, S).call(this, "sub", ...t);
697
697
  }
698
698
  mul(...t) {
699
- return f(this, w, v).call(this, "mul", ...t);
699
+ return f(this, w, S).call(this, "mul", ...t);
700
700
  }
701
701
  div(...t) {
702
- return f(this, w, v).call(this, "div", ...t);
702
+ return f(this, w, S).call(this, "div", ...t);
703
703
  }
704
704
  gt(t) {
705
705
  return this.bigIntValue > this.getBigIntValue(t);
@@ -719,7 +719,7 @@ const I = class I {
719
719
  getValue(t) {
720
720
  const e = this.formatBigIntToSafeValue(
721
721
  this.bigIntValue,
722
- this.decimal || S(this.decimalMultiplier)
722
+ this.decimal || R(this.decimalMultiplier)
723
723
  );
724
724
  switch (t) {
725
725
  case "number":
@@ -731,7 +731,7 @@ const I = class I {
731
731
  }
732
732
  }
733
733
  getBaseValue(t) {
734
- const e = this.decimalMultiplier / R(this.decimal || m.THOR), r = this.bigIntValue / e;
734
+ const e = this.decimalMultiplier / v(this.decimal || m.THOR), r = this.bigIntValue / e;
735
735
  switch (t) {
736
736
  case "number":
737
737
  return Number(r);
@@ -744,13 +744,13 @@ const I = class I {
744
744
  getBigIntValue(t, e) {
745
745
  if (!e && typeof t == "object")
746
746
  return t.bigIntValue;
747
- const r = L(t), n = f(this, A, C).call(this, r);
748
- return n === "0" || n === "undefined" ? 0n : f(this, O, F).call(this, n, e);
747
+ const r = U(t), n = f(this, A, C).call(this, r);
748
+ return n === "0" || n === "undefined" ? 0n : f(this, E, G).call(this, n, e);
749
749
  }
750
750
  formatBigIntToSafeValue(t, e) {
751
751
  const r = e || this.decimal || $, n = Math.max(
752
752
  r,
753
- S(this.decimalMultiplier)
753
+ R(this.decimalMultiplier)
754
754
  ), i = t < 0n, a = t.toString().substring(i ? 1 : 0), c = n - (a.length - 1), u = c > 0 ? "0".repeat(c) + a : a, l = u.length - n;
755
755
  let h = u.slice(-n);
756
756
  return parseInt(h[r]) >= 5 ? h = `${h.substring(0, r - 1)}${(parseInt(h[r - 1]) + 1).toString()}` : h = h.substring(0, r), `${i ? "-" : ""}${u.slice(
@@ -786,8 +786,8 @@ const I = class I {
786
786
  )}`;
787
787
  }
788
788
  };
789
- w = new WeakSet(), v = function(t, ...e) {
790
- const r = f(this, x, lt).call(this, this, ...e), n = R(r), i = e.reduce(
789
+ w = new WeakSet(), S = function(t, ...e) {
790
+ const r = f(this, P, dt).call(this, this, ...e), n = v(r), i = e.reduce(
791
791
  (c, u) => {
792
792
  const l = this.getBigIntValue(u, r);
793
793
  switch (t) {
@@ -808,52 +808,53 @@ w = new WeakSet(), v = function(t, ...e) {
808
808
  },
809
809
  //normalize is to precision multiplier base
810
810
  this.bigIntValue * n / this.decimalMultiplier
811
- ), a = tt({
811
+ ), a = M({
812
812
  bigIntDecimal: r,
813
- decimal: Math.max(r, S(this.decimalMultiplier)),
813
+ decimal: Math.max(r, R(this.decimalMultiplier)),
814
814
  value: i
815
815
  });
816
816
  return new this.constructor({ decimal: this.decimal, value: a, identifier: this.toString() });
817
- }, M = new WeakSet(), ut = function(t) {
817
+ }, x = new WeakSet(), ht = function(t) {
818
818
  const e = f(this, A, C).call(this, t) || "0";
819
- this.bigIntValue = f(this, O, F).call(this, e);
820
- }, x = new WeakSet(), lt = function(...t) {
819
+ this.bigIntValue = f(this, E, G).call(this, e);
820
+ }, P = new WeakSet(), dt = function(...t) {
821
821
  const e = t.map(
822
- (r) => typeof r == "object" ? r.decimal || S(r.decimalMultiplier) : f(this, k, W).call(this, f(this, A, C).call(this, r))
822
+ (r) => typeof r == "object" ? r.decimal || R(r.decimalMultiplier) : f(this, O, Y).call(this, f(this, A, C).call(this, r))
823
823
  ).filter(Boolean);
824
824
  return Math.max(...e, $);
825
- }, O = new WeakSet(), F = function(t, e) {
826
- const r = e ? R(e) : this.decimalMultiplier, n = S(r), [i = "", a = ""] = t.split(".");
825
+ }, E = new WeakSet(), G = function(t, e) {
826
+ const r = e ? v(e) : this.decimalMultiplier, n = R(r), [i = "", a = ""] = t.split(".");
827
827
  return BigInt(`${i}${a.padEnd(n, "0")}`);
828
828
  }, A = new WeakSet(), C = function(t) {
829
829
  const r = `${typeof t == "number" ? Number(t).toLocaleString("fullwide", {
830
830
  useGrouping: !1,
831
831
  maximumFractionDigits: 20
832
- }) : L(t)}`.replaceAll(",", ".").split(".");
832
+ }) : U(t)}`.replaceAll(",", ".").split(".");
833
833
  return r.length > 1 ? `${r.slice(0, -1).join("")}.${r.at(-1)}` : r[0];
834
- }, k = new WeakSet(), W = function(t) {
834
+ }, O = new WeakSet(), Y = function(t) {
835
835
  var r;
836
836
  const e = ((r = t.split(".")[1]) == null ? void 0 : r.length) || 0;
837
837
  return Math.max(e, $);
838
838
  };
839
- let E = I;
840
- function L(s) {
839
+ let I = N;
840
+ function U(s) {
841
841
  return typeof s == "object" ? "getValue" in s ? s.getValue("string") : s.value : s;
842
842
  }
843
- let G;
844
- const D = (s) => {
845
- if (!G)
843
+ const k = (s, t) => typeof s == "bigint" ? M({ value: s, bigIntDecimal: t, decimal: t }) : s;
844
+ let z;
845
+ const F = (s) => {
846
+ if (!z)
846
847
  throw new Error("Static assets not loaded, call await AssetValue.loadStaticAssets() first");
847
- return G.get(s.toUpperCase()) || { decimal: m.THOR, identifier: "" };
848
- }, et = async (s, t = 0) => {
849
- Jt(s);
850
- const e = await st(Y(s));
851
- return new b({ decimal: e, value: t, identifier: s });
848
+ return z.get(s.toUpperCase()) || { decimal: m.THOR, identifier: "" };
849
+ }, st = async (s, t = 0) => {
850
+ Qt(s);
851
+ const e = await it(J(s)), r = k(t, e);
852
+ return new b({ decimal: e, value: r, identifier: s });
852
853
  };
853
- class b extends E {
854
+ class b extends I {
854
855
  constructor(e) {
855
856
  super(
856
- e.value instanceof E ? e.value : { decimal: e.decimal, value: e.value }
857
+ e.value instanceof I ? e.value : { decimal: e.decimal, value: e.value }
857
858
  );
858
859
  p(this, "address");
859
860
  p(this, "chain");
@@ -862,8 +863,8 @@ class b extends E {
862
863
  p(this, "symbol");
863
864
  p(this, "ticker");
864
865
  p(this, "type");
865
- const r = "identifier" in e ? e.identifier : `${e.chain}.${e.symbol}`, n = Y(r);
866
- this.type = Ct(n), this.chain = n.chain, this.ticker = n.ticker, this.symbol = n.symbol, this.address = n.address, this.isSynthetic = n.isSynthetic, this.isGasAsset = n.isGasAsset;
866
+ const r = "identifier" in e ? e.identifier : `${e.chain}.${e.symbol}`, n = J(r);
867
+ this.type = It(n), this.chain = n.chain, this.ticker = n.ticker, this.symbol = n.symbol, this.address = n.address, this.isSynthetic = n.isSynthetic, this.isGasAsset = n.isGasAsset;
867
868
  }
868
869
  get assetValue() {
869
870
  return `${this.getValue("string")} ${this.ticker}`;
@@ -879,31 +880,31 @@ class b extends E {
879
880
  return this.chain === e && this.symbol === r;
880
881
  }
881
882
  static async fromString(e, r = 0) {
882
- return et(e, r);
883
+ return st(e, r);
883
884
  }
884
885
  static fromStringSync(e, r = 0) {
885
- const { decimal: n, identifier: i } = D(
886
+ const { decimal: n, identifier: i } = F(
886
887
  e
887
- );
888
- return i ? new b({ decimal: n, identifier: i, value: r }) : void 0;
888
+ ), a = k(r, n);
889
+ return i ? new b({ decimal: n, identifier: i, value: a }) : void 0;
889
890
  }
890
891
  static async fromIdentifier(e, r = 0) {
891
- return et(e, r);
892
+ return st(e, r);
892
893
  }
893
894
  static fromIdentifierSync(e, r = 0) {
894
- const { decimal: n, identifier: i } = D(e);
895
- return new b({ decimal: n, identifier: i, value: r });
895
+ const { decimal: n, identifier: i } = F(e), a = k(r, n);
896
+ return new b({ decimal: n, identifier: i, value: a });
896
897
  }
897
898
  static fromChainOrSignature(e, r = 0) {
898
- const { decimal: n, identifier: i } = vt(e);
899
- return new b({ value: r, decimal: n, identifier: i });
899
+ const { decimal: n, identifier: i } = $t(e), a = k(r, n);
900
+ return new b({ value: a, decimal: n, identifier: i });
900
901
  }
901
902
  static async fromTCQuote(e, r = 0) {
902
- const n = await st(Y(e)), i = this.shiftDecimals({ value: r, from: m.THOR, to: n });
903
+ const n = await it(J(e)), i = this.shiftDecimals({ value: r, from: m.THOR, to: n });
903
904
  return new b({ value: i, identifier: e, decimal: n });
904
905
  }
905
906
  static fromTCQuoteStatic(e, r = 0) {
906
- const n = D(e), i = this.shiftDecimals({
907
+ const n = F(e), i = this.shiftDecimals({
907
908
  value: r,
908
909
  from: m.THOR,
909
910
  to: n.decimal
@@ -921,10 +922,10 @@ class b extends E {
921
922
  NativeList: i,
922
923
  ...a
923
924
  } = await import("@swapkit/tokens");
924
- G = [i, ...Object.values(a)].reduce(
925
+ z = [i, ...Object.values(a)].reduce(
925
926
  (u, { tokens: l }) => (l.forEach(({ identifier: h, chain: _, ...T }) => {
926
- const P = "decimals" in T ? T.decimals : m[_];
927
- u.set(h, { identifier: h, decimal: P });
927
+ const H = "decimals" in T ? T.decimals : m[_];
928
+ u.set(h, { identifier: h, decimal: H });
928
929
  }), u),
929
930
  /* @__PURE__ */ new Map()
930
931
  ), e({ ok: !0 });
@@ -939,7 +940,7 @@ class b extends E {
939
940
  );
940
941
  }
941
942
  }
942
- const de = (s) => {
943
+ const me = (s) => {
943
944
  const t = b.fromChainOrSignature(s);
944
945
  switch (s) {
945
946
  case o.Bitcoin:
@@ -957,17 +958,17 @@ const de = (s) => {
957
958
  default:
958
959
  return t.add(1);
959
960
  }
960
- }, Y = (s) => {
961
+ }, J = (s) => {
961
962
  const t = s.slice(0, 14).includes("/"), e = s.includes(".") ? s : `${o.THORChain}.${s}`, [r, n] = e.split("."), [i, a] = n.split("-");
962
963
  return {
963
964
  address: a == null ? void 0 : a.toLowerCase(),
964
965
  chain: r,
965
- isGasAsset: St({ chain: r, symbol: n }),
966
+ isGasAsset: Ct({ chain: r, symbol: n }),
966
967
  isSynthetic: t,
967
968
  symbol: a ? `${i}-${(a == null ? void 0 : a.toLowerCase()) ?? ""}` : n,
968
969
  ticker: t ? n : i
969
970
  };
970
- }, Kt = {
971
+ }, Xt = {
971
972
  /**
972
973
  * Core
973
974
  */
@@ -1024,41 +1025,47 @@ const de = (s) => {
1024
1025
  */
1025
1026
  helpers_number_different_decimals: 99101
1026
1027
  };
1027
- class ht extends Error {
1028
+ class mt extends Error {
1028
1029
  constructor(t, e) {
1029
- console.error(e), super(t, { cause: { code: Kt[t], message: t } }), Object.setPrototypeOf(this, ht.prototype);
1030
+ console.error(e), super(t, { cause: { code: Xt[t], message: t } }), Object.setPrototypeOf(this, mt.prototype);
1030
1031
  }
1031
1032
  }
1032
- class Qt extends E {
1033
+ class Q extends I {
1033
1034
  eq(t) {
1034
1035
  return this.eqValue(t);
1035
1036
  }
1037
+ static fromBigInt(t, e) {
1038
+ return new Q({
1039
+ decimal: e,
1040
+ value: M({ value: t, bigIntDecimal: e, decimal: e })
1041
+ });
1042
+ }
1036
1043
  }
1037
1044
  export {
1038
1045
  b as AssetValue,
1039
- E as BigIntArithmetics,
1040
- zt as RequestClient,
1041
- ht as SwapKitError,
1042
- Qt as SwapKitNumber,
1043
- ee as assetFromString,
1044
- he as derivationPathToString,
1045
- re as filterAssets,
1046
- tt as formatBigIntToSafeValue,
1047
- te as gasFeeMultiplier,
1048
- Ct as getAssetType,
1049
- Et as getAsymmetricAssetShare,
1050
- ne as getAsymmetricAssetWithdrawAmount,
1051
- It as getAsymmetricRuneShare,
1052
- se as getAsymmetricRuneWithdrawAmount,
1053
- vt as getCommonAssetInfo,
1054
- st as getDecimal,
1055
- oe as getEstimatedPoolShare,
1056
- ae as getLiquiditySlippage,
1057
- ce as getMemoFor,
1058
- de as getMinAmountByChain,
1059
- Ot as getSymmetricPoolShare,
1060
- ie as getSymmetricWithdraw,
1061
- ue as getTHORNameCost,
1062
- St as isGasAsset,
1063
- le as validateTHORName
1046
+ I as BigIntArithmetics,
1047
+ Kt as RequestClient,
1048
+ mt as SwapKitError,
1049
+ Q as SwapKitNumber,
1050
+ re as assetFromString,
1051
+ de as derivationPathToString,
1052
+ se as filterAssets,
1053
+ M as formatBigIntToSafeValue,
1054
+ ee as gasFeeMultiplier,
1055
+ It as getAssetType,
1056
+ Vt as getAsymmetricAssetShare,
1057
+ ie as getAsymmetricAssetWithdrawAmount,
1058
+ Ot as getAsymmetricRuneShare,
1059
+ ne as getAsymmetricRuneWithdrawAmount,
1060
+ $t as getCommonAssetInfo,
1061
+ it as getDecimal,
1062
+ ae as getEstimatedPoolShare,
1063
+ ce as getLiquiditySlippage,
1064
+ ue as getMemoFor,
1065
+ me as getMinAmountByChain,
1066
+ Bt as getSymmetricPoolShare,
1067
+ oe as getSymmetricWithdraw,
1068
+ le as getTHORNameCost,
1069
+ Ct as isGasAsset,
1070
+ he as validateTHORName
1064
1071
  };
package/package.json CHANGED
@@ -42,7 +42,7 @@
42
42
  "repository": "https://github.com/thorswap/SwapKit.git",
43
43
  "type": "module",
44
44
  "types": "./dist/index.d.ts",
45
- "version": "1.0.0-rc.10",
45
+ "version": "1.0.0-rc.11",
46
46
  "scripts": {
47
47
  "build": "vite build",
48
48
  "clean": "rm -rf dist vite.config.ts.* .turbo node_modules",
@@ -77,6 +77,16 @@ describe('AssetValue', () => {
77
77
  });
78
78
  });
79
79
 
80
+ describe('from bigint', () => {
81
+ test('returns asset value with correct decimal', async () => {
82
+ const avaxUSDCAsset = await AssetValue.fromIdentifier(
83
+ `${Chain.Avalanche}.USDC-0xb97ef9ef8734c71904d8002f8b6bc66dd9c48a6e`,
84
+ 1234567800n,
85
+ );
86
+ expect(avaxUSDCAsset.getValue('string')).toBe('1234.5678');
87
+ });
88
+ });
89
+
80
90
  describe('toString', () => {
81
91
  test('returns asset value string/identifier', async () => {
82
92
  const avaxUSDCAsset = new AssetValue({
@@ -17,9 +17,15 @@ import type { CommonAssetString } from '../helpers/asset.ts';
17
17
  import { getAssetType, getCommonAssetInfo, getDecimal, isGasAsset } from '../helpers/asset.ts';
18
18
  import { validateIdentifier } from '../helpers/validators.ts';
19
19
 
20
- import { BigIntArithmetics } from './bigIntArithmetics.ts';
20
+ import type { NumberPrimitives } from './bigIntArithmetics.ts';
21
+ import { BigIntArithmetics, formatBigIntToSafeValue } from './bigIntArithmetics.ts';
21
22
  import type { SwapKitValueType } from './swapKitNumber.ts';
22
23
 
24
+ const safeValue = (value: NumberPrimitives, decimal: number) =>
25
+ typeof value === 'bigint'
26
+ ? formatBigIntToSafeValue({ value, bigIntDecimal: decimal, decimal })
27
+ : value;
28
+
23
29
  type AssetValueParams = { decimal: number; value: SwapKitValueType } & (
24
30
  | { chain: Chain; symbol: string }
25
31
  | { identifier: string }
@@ -51,11 +57,13 @@ const getStaticToken = (identifier: TokenNames) => {
51
57
  return tokenInfo || { decimal: BaseDecimal.THOR, identifier: '' };
52
58
  };
53
59
 
54
- const createAssetValue = async (assetString: string, value: number | string = 0) => {
60
+ const createAssetValue = async (assetString: string, value: NumberPrimitives = 0) => {
55
61
  validateIdentifier(assetString);
56
62
 
57
63
  const decimal = await getDecimal(getAssetInfo(assetString));
58
- return new AssetValue({ decimal, value, identifier: assetString });
64
+ const parsedValue = safeValue(value, decimal);
65
+
66
+ return new AssetValue({ decimal, value: parsedValue, identifier: assetString });
59
67
  };
60
68
 
61
69
  export class AssetValue extends BigIntArithmetics {
@@ -105,47 +113,51 @@ export class AssetValue extends BigIntArithmetics {
105
113
  return this.chain === chain && this.symbol === symbol;
106
114
  }
107
115
 
108
- static async fromString(assetString: string, value: number | string = 0) {
116
+ static async fromString(assetString: string, value: NumberPrimitives = 0) {
109
117
  return createAssetValue(assetString, value);
110
118
  }
111
119
 
112
- static fromStringSync(assetString: string, value: number | string = 0) {
120
+ static fromStringSync(assetString: string, value: NumberPrimitives = 0) {
113
121
  const { decimal, identifier: tokenIdentifier } = getStaticToken(
114
122
  assetString as unknown as TokenNames,
115
123
  );
116
124
 
125
+ const parsedValue = safeValue(value, decimal);
126
+
117
127
  return tokenIdentifier
118
- ? new AssetValue({ decimal, identifier: tokenIdentifier, value })
128
+ ? new AssetValue({ decimal, identifier: tokenIdentifier, value: parsedValue })
119
129
  : undefined;
120
130
  }
121
131
 
122
132
  static async fromIdentifier(
123
133
  assetString: `${Chain}.${string}` | `${Chain}/${string}` | `${Chain}.${string}-${string}`,
124
- value: number | string = 0,
134
+ value: NumberPrimitives = 0,
125
135
  ) {
126
136
  return createAssetValue(assetString, value);
127
137
  }
128
138
 
129
- static fromIdentifierSync(identifier: TokenNames, value: number | string = 0) {
139
+ static fromIdentifierSync(identifier: TokenNames, value: NumberPrimitives = 0) {
130
140
  const { decimal, identifier: tokenIdentifier } = getStaticToken(identifier);
141
+ const parsedValue = safeValue(value, decimal);
131
142
 
132
- return new AssetValue({ decimal, identifier: tokenIdentifier, value });
143
+ return new AssetValue({ decimal, identifier: tokenIdentifier, value: parsedValue });
133
144
  }
134
145
 
135
- static fromChainOrSignature(assetString: CommonAssetString, value: number | string = 0) {
146
+ static fromChainOrSignature(assetString: CommonAssetString, value: NumberPrimitives = 0) {
136
147
  const { decimal, identifier } = getCommonAssetInfo(assetString);
148
+ const parsedValue = safeValue(value, decimal);
137
149
 
138
- return new AssetValue({ value, decimal, identifier });
150
+ return new AssetValue({ value: parsedValue, decimal, identifier });
139
151
  }
140
152
 
141
- static async fromTCQuote(identifier: TCTokenNames, value: number | string = 0) {
153
+ static async fromTCQuote(identifier: TCTokenNames, value: NumberPrimitives = 0) {
142
154
  const decimal = await getDecimal(getAssetInfo(identifier));
143
155
  const shiftedValue = this.shiftDecimals({ value, from: BaseDecimal.THOR, to: decimal });
144
156
 
145
157
  return new AssetValue({ value: shiftedValue, identifier, decimal });
146
158
  }
147
159
 
148
- static fromTCQuoteStatic(identifier: TCTokenNames, value: number | string = 0) {
160
+ static fromTCQuoteStatic(identifier: TCTokenNames, value: NumberPrimitives = 0) {
149
161
  const tokenInfo = getStaticToken(identifier);
150
162
  const shiftedValue = this.shiftDecimals({
151
163
  value,
@@ -7,7 +7,7 @@ type NumberPrimitivesType = {
7
7
  number: number;
8
8
  string: string;
9
9
  };
10
- type NumberPrimitives = bigint | number | string;
10
+ export type NumberPrimitives = bigint | number | string;
11
11
  type InitialisationValueType = NumberPrimitives | BigIntArithmetics | SwapKitNumber;
12
12
 
13
13
  type SKBigIntParams = InitialisationValueType | { decimal?: number; value: number | string };
@@ -75,7 +75,7 @@ export class BigIntArithmetics {
75
75
  from: number;
76
76
  to: number;
77
77
  }) {
78
- return BigIntArithmetics.fromBigInt(
78
+ return this.fromBigInt(
79
79
  (new BigIntArithmetics(value).bigIntValue * toMultiplier(to)) / toMultiplier(from),
80
80
  to,
81
81
  );
@@ -1,4 +1,4 @@
1
- import { BigIntArithmetics } from './bigIntArithmetics.ts';
1
+ import { BigIntArithmetics, formatBigIntToSafeValue } from './bigIntArithmetics.ts';
2
2
 
3
3
  export type SwapKitValueType = BigIntArithmetics | string | number;
4
4
 
@@ -6,4 +6,11 @@ export class SwapKitNumber extends BigIntArithmetics {
6
6
  eq(value: SwapKitValueType) {
7
7
  return this.eqValue(value);
8
8
  }
9
+
10
+ static fromBigInt(value: bigint, decimal?: number) {
11
+ return new SwapKitNumber({
12
+ decimal,
13
+ value: formatBigIntToSafeValue({ value, bigIntDecimal: decimal, decimal }),
14
+ });
15
+ }
9
16
  }