@swapkit/helpers 1.0.0-rc.36 → 1.0.0-rc.37

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 we=Object.create;var k=Object.defineProperty;var Ae=Object.getOwnPropertyDescriptor;var Te=Object.getOwnPropertyNames;var ve=Object.getPrototypeOf,Se=Object.prototype.hasOwnProperty;var Re=(s,e,t)=>e in s?k(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t;var $e=(s,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of Te(e))!Se.call(s,n)&&n!==t&&k(s,n,{get:()=>e[n],enumerable:!(r=Ae(e,n))||r.enumerable});return s};var Ie=(s,e,t)=>(t=s!=null?we(ve(s)):{},$e(e||!s||!s.__esModule?k(t,"default",{value:s,enumerable:!0}):t,s));var m=(s,e,t)=>(Re(s,typeof e!="symbol"?e+"":e,t),t),Be=(s,e,t)=>{if(!e.has(s))throw TypeError("Cannot "+t)};var A=(s,e,t)=>{if(e.has(s))throw TypeError("Cannot add the same private member more than once");e instanceof WeakSet?e.add(s):e.set(s,t)};var p=(s,e,t)=>(Be(s,e,"access private method"),t);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const i=require("@swapkit/types"),Ee="0x313ce567",se=async({chain:s,to:e})=>{try{const{result:t}=await pe.post(i.ChainToRPC[s],{headers:{accept:"*/*","content-type":"application/json","cache-control":"no-cache"},body:JSON.stringify({id:44,jsonrpc:"2.0",method:"eth_call",params:[{to:e.toLowerCase(),data:Ee},"latest"]})});return parseInt(BigInt(t).toString())}catch(t){return console.error(t),i.BaseDecimal[s]}},Me=async s=>{if(s===i.Chain.Ethereum)return i.BaseDecimal.ETH;const[,e]=s.split("-");return e!=null&&e.startsWith("0x")?se({chain:i.Chain.Ethereum,to:e}):i.BaseDecimal.ETH},Oe=async s=>{const[,e]=s.split("-");return e!=null&&e.startsWith("0x")?se({chain:i.Chain.Avalanche,to:e.toLowerCase()}):i.BaseDecimal.AVAX},Ve=async s=>(s===i.Chain.BinanceSmartChain,i.BaseDecimal.BSC),re=async({chain:s,symbol:e})=>{switch(s){case i.Chain.Ethereum:return Me(e);case i.Chain.Avalanche:return Oe(e);case i.Chain.BinanceSmartChain:return Ve(e);default:return i.BaseDecimal[s]}},qe={[i.FeeOption.Average]:1.2,[i.FeeOption.Fast]:1.5,[i.FeeOption.Fastest]:2},U=({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"}},xe=s=>{var o;const[e,...t]=s.split("."),r=s.includes("/"),n=t.join("."),a=(o=n==null?void 0:n.split("-"))==null?void 0:o[0];return{chain:e,symbol:n,ticker:a,synth:r}},Pe=new RegExp(/(.)\1{6}|\.ORG|\.NET|\.FINANCE|\.COM|WWW|HTTP|\\\\|\/\/|[\s$%:[\]]/,"gmi"),ke=s=>{const[e,t]=s.split(".");if(!i.EVMChainList.includes(e))return!0;const[,r]=t.split("-");return U({chain:e,symbol:t})||!!r},Ne=s=>s.filter(e=>{const t=`${e.chain}.${e.symbol}`;return!Pe.test(t)&&ke(t)&&e.value!=="0"}),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),h=r.mul(r),l=n.mul(n).mul(n);return o.mul(c.sub(u).add(h)).div(l)},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),h=r.mul(r),l=o.mul(c.sub(u).add(h)),g=n.mul(n).mul(n);return l.div(g)},De=({percent:s,runeDepth:e,liquidityUnits:t,poolUnits:r})=>ae({runeDepth:e,liquidityUnits:t,poolUnits:r}).mul(s),je=({percent:s,assetDepth:e,liquidityUnits:t,poolUnits:r})=>oe({assetDepth:e,liquidityUnits:t,poolUnits:r}).mul(s),d=s=>f.fromBigInt(BigInt(s),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)}),He=({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=new f({value:s,decimal:8}),c=new f({value:t,decimal:8}),u=new f({value:e,decimal:8}),h=new f({value:n,decimal:8}),l=new f({value:a,decimal:8}),g=h.mul(c),C=l.mul(o),x=h.mul(l),_e=o.mul(c),ye=u.mul(g.add(C.add(x.mul(2)))),be=g.add(C.add(_e.mul(2))),Y=ye.div(be),P=d(r).add(Y);if(Y.getBaseValue("number")===0)return P.div(u).getBaseValue("number");const Ce=u.add(P);return P.div(Ce).getBaseValue("number")},Fe=({runeAmount:s,assetAmount:e,runeDepth:t,assetDepth:r})=>{if(s==="0"||e==="0"||t==="0"||r==="0")return 0;const n=d(t),a=d(r),o=d(e),c=d(s),u=o.mul(n).sub(a.mul(c)),h=a.mul(c).add(n.mul(a));return Math.abs(u.div(h).getBaseValue("number"))},Ue=({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}`:"",h=Ue({chain:t,symbol:n,ticker:r});return`${s}:${t}${c?"/":"."}${h}:${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 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 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 E=s=>s!==null&&typeof s=="object",I=(...s)=>{for(const e of s)if((!E(e)||Array.isArray(e))&&e!==void 0)throw new TypeError("The `options` argument must be an object");return W({},...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},W=(...s)=>{let e={},t={};for(const r of s)if(Array.isArray(r))Array.isArray(e)||(e=[]),e=[...e,...r];else if(E(r)){for(let[n,a]of Object.entries(r))E(a)&&n in e&&(a=W(e[n],a)),e={...e,[n]:a};E(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:"*/*"},N=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},st=s=>he.includes(s)?s.toUpperCase():s,rt=["get","put","head","delete","options","trace"],nt=[408,413,429,500,502,503,504],me=[413,429,503],J={limit:2,methods:rt,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{...J,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{...J,...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 O{static create(e,t){const r=new O(e,t),n=async()=>{if(typeof r._options.timeout=="number"&&r._options.timeout>N)throw new RangeError(`The \`timeout\` option cannot be greater than ${N}`);await Promise.resolve();let c=await r._fetch();for(const u of r._options.hooks.afterResponse){const h=await u(r.request,r._options,r._decorateResponse(c.clone()));h instanceof globalThis.Response&&(c=h)}if(r._decorateResponse(c),!c.ok&&r._options.throwHttpErrors){let u=new z(c,r.request,r._options);for(const h of r._options.hooks.beforeError)u=await h(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 l=(await o).clone();if(c==="json"){if(l.status===204||(await l.clone().arrayBuffer()).byteLength===0)return"";if(t.parseJson)return t.parseJson(await l.text())}return l[c]()};return o}constructor(e,t={}){if(Object.defineProperty(this,"request",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"abortController",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_retryCount",{enumerable:!0,configurable:!0,writable:!0,value:0}),Object.defineProperty(this,"_input",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_options",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this._input=e,this._options={credentials:this._input.credentials||"same-origin",...t,headers:le(this._input.headers,t.headers),hooks:W({beforeRequest:[],beforeRetry:[],beforeError:[],afterResponse:[]},t.hooks),method:st(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 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),N);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:h}=await o.read();if(u){a.close();return}if(t){n+=h.byteLength;const l=r===0?0:n/r;t({percent:l,transferredBytes:n,totalBytes:r},h)}a.enqueue(h),await c()}await c()}}),{status:e.status,statusText:e.statusText,headers:e.headers})}}/*! MIT License © Sindre Sorhus */const D=s=>{const e=(t,r)=>O.create(t,I(s,r));for(const t of he)e[t]=(r,n)=>O.create(r,I(s,n,{method:t}));return e.create=t=>D(I(t)),e.extend=t=>D(I(s,t)),e.stop=de,e},ut=D(),lt=ut,ht=typeof window<"u"?{}:{referrer:"https://sk.thorswap.net",referer:"https://sk.thorswap.net"},Q=lt.create({headers:ht}),pe={get:(s,e)=>Q.get(s,e).json(),post:(s,e)=>Q.post(s,e).json()},X=Object.values(i.Chain),dt=(s="")=>{const e=s.toUpperCase(),[t]=e.split(".");if(X.includes(t))return!0;const[r]=e.split("/");if(X.includes(r))return!0;throw new Error(`Invalid identifier: ${s}. Expected format: <Chain>.<Ticker> or <Chain>.<Ticker>-<ContractAddress>`)},S=8,y=s=>10n**BigInt(s),T=s=>Math.log10(parseFloat(s.toString()));function R({value:s,bigIntDecimal:e=S,decimal:t=S}){const r=s<0n;let n=s.toString().substring(r?1:0);const a=t-(n.length-1);a>0&&(n="0".repeat(a)+n);const o=n.length-t;let c=n.slice(-t);return parseInt(c[e])>=5?c=`${c.substring(0,e-1)}${(parseInt(c[e-1])+1).toString()}`:c=c.substring(0,e),`${r?"-":""}${n.slice(0,o)}.${c}`.replace(/\.?0*$/,"")}var b,v,V,fe,q,ge,$,j;const K=class K{constructor(e){A(this,b);A(this,V);A(this,q);A(this,$);m(this,"decimalMultiplier",10n**8n);m(this,"bigIntValue",0n);m(this,"decimal");const t=H(e),r=typeof e=="object";this.decimal=r?e.decimal:void 0,this.decimalMultiplier=r&&"decimalMultiplier"in e?e.decimalMultiplier:y(Math.max(Z(B(t)),this.decimal||0)),p(this,V,fe).call(this,t)}static fromBigInt(e,t){return new K({decimal:t,value:R({value:e,bigIntDecimal:t,decimal:t})})}static shiftDecimals({value:e,from:t,to:r}){return this.fromBigInt(e.getBaseValue("bigint")*y(r)/y(t),r)}set(e){return new this.constructor({decimal:this.decimal,value:e,identifier:this.toString()})}add(...e){return p(this,b,v).call(this,"add",...e)}sub(...e){return p(this,b,v).call(this,"sub",...e)}mul(...e){return p(this,b,v).call(this,"mul",...e)}div(...e){return p(this,b,v).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;case"bigint":return this.bigIntValue*10n**BigInt(this.decimal||8n)/this.decimalMultiplier}}getBaseValue(e){const t=this.decimalMultiplier/y(this.decimal||i.BaseDecimal.THOR),r=this.bigIntValue/t;switch(e){case"number":return Number(r);case"string":return r.toString();case"bigint":return r}}getBigIntValue(e,t){if(!t&&typeof e=="object")return e.bigIntValue;const r=H(e),n=B(r);return n==="0"||n==="undefined"?0n:p(this,$,j).call(this,n,t)}toSignificant(e=6){const[t,r]=this.getValue("string").split("."),n=t||"",a=r||"";if((parseInt(n)?n.length+a.length:a.length)<=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(e-n.length,"0");const c=parseInt(a),u=`${c}`.slice(0,e);return`0.${u.padStart(a.length-`${c}`.length+u.length,"0")}`}toFixed(e=6){const[t,r]=this.getValue("string").split("."),n=t||"",a=r||"";if(parseInt(n))return`${n}.${a.slice(0,e)}`.padEnd(e,"0");const o=parseInt(a),c=`${o}`.slice(0,e);return`0.${c.padStart(a.length-`${o}`.length+c.length,"0")}`}toAbbreviation(e=2){const t=this.getValue("number"),r=["","K","M","B","T","Q","Qi","S"],n=Math.floor(Math.log10(Math.abs(t))/3),a=r[n];if(!a)return this.getValue("string");const o=10**(n*3);return`${(t/o).toFixed(e)}${a}`}toCurrency(e="$",{currencyPosition:t="start",decimal:r=2,decimalSeparator:n=".",thousandSeparator:a=","}={}){const o=this.getValue("number"),[c,u=""]=o.toFixed(6).split("."),h=c.replace(/\B(?=(\d{3})+(?!\d))/g,a),l=!c&&!u?"0.00":c==="0"?`${parseFloat(`0.${u}`)}`.replace(".",n):`${h}${parseInt(u)?`${n}${u.slice(0,r)}`:""}`;return`${t==="start"?e:""}${l}${t==="end"?e:""}`}formatBigIntToSafeValue(e,t){const r=t||this.decimal||S,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,h=u.length-n;let l=u.slice(-n);return parseInt(l[r])>=5?l=`${l.substring(0,r-1)}${(parseInt(l[r-1])+1).toString()}`:l=l.substring(0,r),`${a?"-":""}${u.slice(0,h)}.${l}`.replace(/\.?0*$/,"")}};b=new WeakSet,v=function(e,...t){const r=p(this,q,ge).call(this,this,...t),n=Math.max(r,T(this.decimalMultiplier)),a=y(n),o=t.reduce((u,h)=>{const l=this.getBigIntValue(h,n);switch(e){case"add":return u+l;case"sub":return u-l;case"mul":return u*l/a;case"div":{if(l===0n)throw new RangeError("Division by zero");return u*a/l}default:return u}},this.bigIntValue*a/this.decimalMultiplier),c=R({bigIntDecimal:n,decimal:n,value:o});return new this.constructor({decimalMultiplier:y(n),decimal:this.decimal,value:c,identifier:this.toString()})},V=new WeakSet,fe=function(e){const t=B(e)||"0";this.bigIntValue=p(this,$,j).call(this,t)},q=new WeakSet,ge=function(...e){const t=e.map(r=>typeof r=="object"?r.decimal||T(r.decimalMultiplier):Z(B(r))).filter(Boolean);return Math.max(...t,S)},$=new WeakSet,j=function(e,t){const r=t?y(t):this.decimalMultiplier,n=T(r),[a="",o=""]=e.split(".");return BigInt(`${a}${o.padEnd(n,"0")}`)};let w=K;const mt=Intl.NumberFormat("fullwide",{useGrouping:!1,maximumFractionDigits:20});function B(s){const t=`${typeof s=="number"?mt.format(s):H(s)}`.replaceAll(",",".").split(".");return t.length>1?`${t.slice(0,-1).join("")}.${t.at(-1)}`:t[0]}function Z(s){var t;const e=((t=s.split(".")[1])==null?void 0:t.length)||0;return Math.max(e,S)}function H(s){return typeof s=="object"?"getValue"in s?s.getValue("string"):s.value:s}const M=(s,e)=>typeof s=="bigint"?R({value:s,bigIntDecimal:e,decimal:e}):s;let L;const ee=s=>{if(!L)throw new Error("Static assets not loaded, call await AssetValue.loadStaticAssets() first");return L.get(s.toUpperCase())||{decimal:i.BaseDecimal.THOR,identifier:""}},te=async(s,e=0)=>{dt(s);const t=await re(F(s)),r=M(e,t);return new _({decimal:t,value:r,identifier:s})};class _ extends w{constructor(t){const r="identifier"in t?t.identifier:`${t.chain}.${t.symbol}`;super(t.value instanceof w?t.value:{decimal:t.decimal,value:t.value});m(this,"address");m(this,"isSynthetic",!1);m(this,"isGasAsset",!1);m(this,"chain");m(this,"symbol");m(this,"ticker");m(this,"type");const n=F(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}toString(t=!1){const r=this.isSynthetic?this.symbol.split("-")[0]: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{isSynthetic:n}=F(t),{decimal:a,identifier:o}=ee(t),c=M(r,a);return o?new _({decimal:a,identifier:o,value:c}):n?new _({decimal:8,identifier:t,value:c}):void 0}static async fromIdentifier(t,r=0){return te(t,r)}static fromIdentifierSync(t,r=0){const{decimal:n,identifier:a}=ee(t),o=M(r,n);return new _({decimal:n,identifier:a,value:o})}static fromChainOrSignature(t,r=0){const{decimal:n,identifier:a}=ne(t),o=M(r,n);return new _({value:o,decimal:n,identifier:a})}static async loadStaticAssets(){return new Promise(async(t,r)=>{try{const{ThorchainList:n,NativeList:a,...o}=await import("@swapkit/tokens");L=[a,...Object.values(o)].reduce((u,{tokens:h})=>(h.forEach(({identifier:l,chain:g,...C})=>{const x="decimals"in C?C.decimals:i.BaseDecimal[g];u.set(l,{identifier:l,decimal:x})}),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 pt=s=>{const e=_.fromChainOrSignature(s);switch(s){case i.Chain.Bitcoin:case i.Chain.Litecoin:case i.Chain.BitcoinCash:return e.set(10001e-8);case i.Chain.Dogecoin:return e.set(1.00000001);case i.Chain.Avalanche:case i.Chain.Ethereum:return e.set(1e-8);case i.Chain.THORChain:case i.Chain.Maya:return e.set(0);default:return e.set(1e-8)}},F=s=>{const e=s.slice(0,14).includes("/"),[t,r]=s.split(".").pop().split("/"),n=s.includes(".")&&!e?s:`${i.Chain.THORChain}.${r}`,[a,o]=n.split("."),[c,u]=(e?r:o).split("-");return{address:u==null?void 0:u.toLowerCase(),chain:a,isGasAsset:U({chain:a,symbol:o}),isSynthetic:e,symbol:(e?`${t}/`:"")+(u?`${c}-${(u==null?void 0:u.toLowerCase())??""}`:o),ticker:c}},ft={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 G extends Error{constructor(e,t){console.error(t),super(e,{cause:{code:ft[e],message:e}}),Object.setPrototypeOf(this,G.prototype)}}class f extends w{eq(e){return this.eqValue(e)}static fromBigInt(e,t){return new f({decimal:t,value:R({value:e,bigIntDecimal:t,decimal:t})})}}exports.AssetValue=_;exports.BigIntArithmetics=w;exports.RequestClient=pe;exports.SwapKitError=G;exports.SwapKitNumber=f;exports.assetFromString=xe;exports.derivationPathToString=Ye;exports.filterAssets=Ne;exports.formatBigIntToSafeValue=R;exports.gasFeeMultiplier=qe;exports.getAssetType=ie;exports.getAsymmetricAssetShare=oe;exports.getAsymmetricAssetWithdrawAmount=je;exports.getAsymmetricRuneShare=ae;exports.getAsymmetricRuneWithdrawAmount=De;exports.getCommonAssetInfo=ne;exports.getDecimal=re;exports.getEstimatedPoolShare=Le;exports.getLiquiditySlippage=Fe;exports.getMemoFor=We;exports.getMinAmountByChain=pt;exports.getSymmetricPoolShare=ce;exports.getSymmetricWithdraw=He;exports.getTHORNameCost=Ge;exports.isGasAsset=U;exports.validateTHORName=Ke;
1
+ "use strict";var Te=Object.create;var D=Object.defineProperty;var ve=Object.getOwnPropertyDescriptor;var Se=Object.getOwnPropertyNames;var Re=Object.getPrototypeOf,$e=Object.prototype.hasOwnProperty;var Be=(s,e,t)=>e in s?D(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t;var Ie=(s,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of Se(e))!$e.call(s,n)&&n!==t&&D(s,n,{get:()=>e[n],enumerable:!(r=ve(e,n))||r.enumerable});return s};var Ee=(s,e,t)=>(t=s!=null?Te(Re(s)):{},Ie(e||!s||!s.__esModule?D(t,"default",{value:s,enumerable:!0}):t,s));var p=(s,e,t)=>(Be(s,typeof e!="symbol"?e+"":e,t),t),Me=(s,e,t)=>{if(!e.has(s))throw TypeError("Cannot "+t)};var A=(s,e,t)=>{if(e.has(s))throw TypeError("Cannot add the same private member more than once");e instanceof WeakSet?e.add(s):e.set(s,t)};var d=(s,e,t)=>(Me(s,e,"access private method"),t);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const i=require("@swapkit/types"),Oe="0x313ce567",ie=async({chain:s,to:e})=>{try{const{result:t}=await _e.post(i.ChainToRPC[s],{headers:{accept:"*/*","content-type":"application/json","cache-control":"no-cache"},body:JSON.stringify({id:44,jsonrpc:"2.0",method:"eth_call",params:[{to:e.toLowerCase(),data:Oe},"latest"]})});return parseInt(BigInt(t).toString())}catch(t){return console.error(t),i.BaseDecimal[s]}},qe=async s=>{if(s===i.Chain.Ethereum)return i.BaseDecimal.ETH;const[,e]=s.split("-");return e!=null&&e.startsWith("0x")?ie({chain:i.Chain.Ethereum,to:e}):i.BaseDecimal.ETH},xe=async s=>{const[,e]=s.split("-");return e!=null&&e.startsWith("0x")?ie({chain:i.Chain.Avalanche,to:e.toLowerCase()}):i.BaseDecimal.AVAX},Ve=async s=>(s===i.Chain.BinanceSmartChain,i.BaseDecimal.BSC),ae=async({chain:s,symbol:e})=>{switch(s){case i.Chain.Ethereum:return qe(e);case i.Chain.Avalanche:return xe(e);case i.Chain.BinanceSmartChain:return Ve(e);default:return i.BaseDecimal[s]}},Pe={[i.FeeOption.Average]:1.2,[i.FeeOption.Fast]:1.5,[i.FeeOption.Fastest]:2},K=({chain:s,symbol:e})=>{switch(s){case i.Chain.Bitcoin:case i.Chain.BitcoinCash:case i.Chain.Litecoin:case i.Chain.Dogecoin:case i.Chain.Binance:case i.Chain.Ethereum:case i.Chain.Avalanche:return e===s;case i.Chain.Arbitrum:case i.Chain.Optimism:return e==="ETH";case i.Chain.Maya:return e==="CACAO";case i.Chain.Kujira:return e==="KUJI";case i.Chain.Cosmos:return e==="ATOM";case i.Chain.Polygon:return e==="MATIC";case i.Chain.BinanceSmartChain:return e==="BNB";case i.Chain.THORChain:return e==="RUNE"}},oe=s=>{switch(s){case"ETH.THOR":return{identifier:"ETH.THOR-0xa5f2211b9b8170f694421f2046281775e8468044",decimal:18};case"ETH.vTHOR":return{identifier:"ETH.vTHOR-0x815c23eca83261b6ec689b60cc4a58b54bc24d8d",decimal:18};case i.Chain.Cosmos:return{identifier:"GAIA.ATOM",decimal:i.BaseDecimal[s]};case i.Chain.THORChain:return{identifier:"THOR.RUNE",decimal:i.BaseDecimal[s]};case i.Chain.BinanceSmartChain:return{identifier:"BSC.BNB",decimal:i.BaseDecimal[s]};case i.Chain.Maya:return{identifier:"MAYA.CACAO",decimal:i.BaseDecimal.MAYA};case"MAYA.MAYA":return{identifier:"MAYA.MAYA",decimal:4};case i.Chain.Kujira:case i.Chain.Arbitrum:case i.Chain.Optimism:case i.Chain.BitcoinCash:case i.Chain.Litecoin:case i.Chain.Dogecoin:case i.Chain.Binance:case i.Chain.Avalanche:case i.Chain.Polygon:case i.Chain.Bitcoin:case i.Chain.Ethereum:return{identifier:`${s}.${s}`,decimal:i.BaseDecimal[s]}}},ce=({chain:s,symbol:e})=>{if(e.includes("/"))return"Synth";switch(s){case i.Chain.Bitcoin:case i.Chain.BitcoinCash:case i.Chain.Dogecoin:case i.Chain.Litecoin:case i.Chain.Maya:case i.Chain.THORChain:return"Native";case i.Chain.Cosmos:return e==="ATOM"?"Native":i.Chain.Cosmos;case i.Chain.Kujira:return e===i.Chain.Kujira?"Native":i.Chain.Kujira;case i.Chain.Binance:return e===i.Chain.Binance?"Native":"BEP2";case i.Chain.BinanceSmartChain:return e===i.Chain.Binance?"Native":"BEP20";case i.Chain.Ethereum:return e===i.Chain.Ethereum?"Native":"ERC20";case i.Chain.Avalanche:return e===i.Chain.Avalanche?"Native":i.Chain.Avalanche;case i.Chain.Polygon:return e===i.Chain.Polygon?"Native":"POLYGON";case i.Chain.Arbitrum:return[i.Chain.Ethereum,i.Chain.Arbitrum].includes(e)?"Native":"ARBITRUM";case i.Chain.Optimism:return[i.Chain.Ethereum,i.Chain.Optimism].includes(e)?"Native":"OPTIMISM"}},ke=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"),De=s=>{const[e,t]=s.split(".");if(!i.EVMChainList.includes(e))return!0;const[,r]=t.split("-");return K({chain:e,symbol:t})||!!r},je=s=>s.filter(e=>{const t=`${e.chain}.${e.symbol}`;return!Ne.test(t)&&De(t)&&e.value!=="0"}),ue=({liquidityUnits:s,poolUnits:e,runeDepth:t})=>{const r=m(s),n=m(e),a=m(t),o=r.mul(a),c=n.mul(n).mul(2),u=n.mul(r).mul(2),h=r.mul(r),l=n.mul(n).mul(n);return o.mul(c.sub(u).add(h)).div(l)},le=({liquidityUnits:s,poolUnits:e,assetDepth:t})=>{const r=m(s),n=m(e),a=m(t),o=r.mul(a),c=n.mul(n).mul(2),u=n.mul(r).mul(2),h=r.mul(r),l=o.mul(c.sub(u).add(h)),g=n.mul(n).mul(n);return l.div(g)},He=({percent:s,runeDepth:e,liquidityUnits:t,poolUnits:r})=>ue({runeDepth:e,liquidityUnits:t,poolUnits:r}).mul(s),Le=({percent:s,assetDepth:e,liquidityUnits:t,poolUnits:r})=>le({assetDepth:e,liquidityUnits:t,poolUnits:r}).mul(s),m=s=>f.fromBigInt(BigInt(s),i.BaseDecimal.THOR),he=({liquidityUnits:s,poolUnits:e,runeDepth:t,assetDepth:r})=>({assetAmount:m(r).mul(s).div(e),runeAmount:m(t).mul(s).div(e)}),Fe=({liquidityUnits:s,poolUnits:e,runeDepth:t,assetDepth:r,percent:n})=>Object.fromEntries(Object.entries(he({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=new f({value:s,decimal:8}),c=new f({value:t,decimal:8}),u=new f({value:e,decimal:8}),h=new f({value:n,decimal:8}),l=new f({value:a,decimal:8}),g=h.mul(c),w=l.mul(o),k=h.mul(l),be=o.mul(c),Ce=u.mul(g.add(w.add(k.mul(2)))),we=g.add(w.add(be.mul(2))),Q=Ce.div(we),N=m(r).add(Q);if(Q.getBaseValue("number")===0)return N.div(u).getBaseValue("number");const Ae=u.add(N);return N.div(Ae).getBaseValue("number")},We=({runeAmount:s,assetAmount:e,runeDepth:t,assetDepth:r})=>{if(s==="0"||e==="0"||t==="0"||r==="0")return 0;const n=m(t),a=m(r),o=m(e),c=m(s),u=o.mul(n).sub(a.mul(c)),h=a.mul(c).add(n.mul(a));return Math.abs(u.div(h).getBaseValue("number"))},Ge=({symbol:s,ticker:e,chain:t})=>t==="ETH"&&e!=="ETH"?`${e}-${s.slice(-3)}`:s,Ke=(s,e)=>{switch(s){case i.MemoType.LEAVE:case i.MemoType.BOND:{const{address:t}=e;return`${s}:${t}`}case i.MemoType.UNBOND:{const{address:t,unbondAmount: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}`:"",h=Ge({chain:t,symbol:n,ticker:r});return`${s}:${t}${c?"/":"."}${h}:${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 X 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 de extends Error{constructor(e){super("Request timed out"),Object.defineProperty(this,"request",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.name="TimeoutError",this.request=e}}const q=s=>s!==null&&typeof s=="object",M=(...s)=>{for(const e of s)if((!q(e)||Array.isArray(e))&&e!==void 0)throw new TypeError("The `options` argument must be an object");return Y({},...s)},me=(s={},e={})=>{const t=new globalThis.Headers(s),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(q(r)){for(let[n,a]of Object.entries(r))q(a)&&n in e&&(a=Y(e[n],a)),e={...e,[n]:a};q(r.headers)&&(t=me(t,r.headers),e.headers=t)}return e},Qe=(()=>{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})(),Xe=typeof globalThis.AbortController=="function",Ze=typeof globalThis.ReadableStream=="function",et=typeof globalThis.FormData=="function",pe=["get","post","put","patch","head","delete"],tt={json:"application/json",text:"text/*",formData:"multipart/form-data",arrayBuffer:"*/*",blob:"*/*"},j=2147483647,fe=Symbol("stop"),st={json:!0,parseJson:!0,searchParams:!0,prefixUrl:!0,retry:!0,timeout:!0,hooks:!0,throwHttpErrors:!0,onDownloadProgress:!0,fetch:!0},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},nt=s=>pe.includes(s)?s.toUpperCase():s,it=["get","put","head","delete","options","trace"],at=[408,413,429,500,502,503,504],ge=[413,429,503],Z={limit:2,methods:it,statusCodes:at,afterStatusCodes:ge,maxRetryAfter:Number.POSITIVE_INFINITY,backoffLimit:Number.POSITIVE_INFINITY,delay:s=>.3*2**(s-1)*1e3},ot=(s={})=>{if(typeof s=="number")return{...Z,limit:s};if(s.methods&&!Array.isArray(s.methods))throw new Error("retry.methods must be an array");if(s.statusCodes&&!Array.isArray(s.statusCodes))throw new Error("retry.statusCodes must be an array");return{...Z,...s,afterStatusCodes:ge}};async function ct(s,e,t,r){return new Promise((n,a)=>{const o=setTimeout(()=>{t&&t.abort(),a(new de(s))},r.timeout);r.fetch(s,e).then(n).catch(a).then(()=>{clearTimeout(o)})})}async function ut(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 lt=(s,e)=>{const t={};for(const r in e)!(r in rt)&&!(r in st)&&!(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 h=await u(r.request,r._options,r._decorateResponse(c.clone()));h instanceof globalThis.Response&&(c=h)}if(r._decorateResponse(c),!c.ok&&r._options.throwHttpErrors){let u=new X(c,r.request,r._options);for(const h of r._options.hooks.beforeError)u=await h(u);throw u}if(r._options.onDownloadProgress){if(typeof r._options.onDownloadProgress!="function")throw new TypeError("The `onDownloadProgress` option must be a function");if(!Ze)throw new Error("Streams are not supported in your environment. `ReadableStream` is missing.");return 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(tt))o[c]=async()=>{r.request.headers.set("accept",r.request.headers.get("accept")||u);const l=(await o).clone();if(c==="json"){if(l.status===204||(await l.clone().arrayBuffer()).byteLength===0)return"";if(t.parseJson)return t.parseJson(await l.text())}return l[c]()};return o}constructor(e,t={}){if(Object.defineProperty(this,"request",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"abortController",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_retryCount",{enumerable:!0,configurable:!0,writable:!0,value:0}),Object.defineProperty(this,"_input",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_options",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this._input=e,this._options={credentials:this._input.credentials||"same-origin",...t,headers:me(this._input.headers,t.headers),hooks:Y({beforeRequest:[],beforeRetry:[],beforeError:[],afterResponse:[]},t.hooks),method:nt(t.method??this._input.method),prefixUrl:String(t.prefixUrl||""),retry:ot(t.retry),throwHttpErrors:t.throwHttpErrors!==!1,timeout:t.timeout??1e4,fetch:t.fetch??globalThis.fetch.bind(globalThis)},typeof this._input!="string"&&!(this._input instanceof URL||this._input instanceof globalThis.Request))throw new TypeError("`input` must be a string, URL, or Request");if(this._options.prefixUrl&&typeof this._input=="string"){if(this._input.startsWith("/"))throw new Error("`input` must not begin with a slash when using `prefixUrl`");this._options.prefixUrl.endsWith("/")||(this._options.prefixUrl+="/"),this._input=this._options.prefixUrl+this._input}if(Xe){if(this.abortController=new globalThis.AbortController,this._options.signal){const r=this._options.signal;this._options.signal.addEventListener("abort",()=>{this.abortController.abort(r.reason)})}this._options.signal=this.abortController.signal}if(Qe&&(this._options.duplex="half"),this.request=new globalThis.Request(this._input,this._options),this._options.searchParams){const n="?"+(typeof this._options.searchParams=="string"?this._options.searchParams.replace(/^\?/,""):new URLSearchParams(this._options.searchParams).toString()),a=this.request.url.replace(/(?:\?.*?)?(?=#|$)/,n);(et&&this._options.body instanceof globalThis.FormData||this._options.body instanceof URLSearchParams)&&!(this._options.headers&&this._options.headers["content-type"])&&this.request.headers.delete("content-type"),this.request=new globalThis.Request(new globalThis.Request(a,{...this.request}),this._options)}this._options.json!==void 0&&(this._options.body=JSON.stringify(this._options.json),this.request.headers.set("content-type",this._options.headers.get("content-type")??"application/json"),this.request=new globalThis.Request(this.request,{body:this._options.body}))}_calculateRetryDelay(e){if(this._retryCount++,this._retryCount<this._options.retry.limit&&!(e instanceof de)){if(e instanceof X){if(!this._options.retry.statusCodes.includes(e.response.status))return 0;const 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 ut(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})===fe)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=lt(this.request,this._options);return this._options.timeout===!1?this._options.fetch(this.request.clone(),e):ct(this.request.clone(),e,this.abortController,this._options)}_stream(e,t){const 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:h}=await o.read();if(u){a.close();return}if(t){n+=h.byteLength;const l=r===0?0:n/r;t({percent:l,transferredBytes:n,totalBytes:r},h)}a.enqueue(h),await c()}await c()}}),{status:e.status,statusText:e.statusText,headers:e.headers})}}/*! MIT License © Sindre Sorhus */const H=s=>{const e=(t,r)=>V.create(t,M(s,r));for(const t of pe)e[t]=(r,n)=>V.create(r,M(s,n,{method:t}));return e.create=t=>H(M(t)),e.extend=t=>H(M(s,t)),e.stop=fe,e},ht=H(),dt=ht,mt=typeof window<"u"?{}:{referrer:"https://sk.thorswap.net",referer:"https://sk.thorswap.net"},ee=dt.create({headers:mt}),_e={get:(s,e)=>ee.get(s,e).json(),post:(s,e)=>ee.post(s,e).json()},te=Object.values(i.Chain),pt=(s="")=>{const e=s.toUpperCase(),[t]=e.split(".");if(te.includes(t))return!0;const[r]=e.split("/");if(te.includes(r))return!0;throw new Error(`Invalid identifier: ${s}. Expected format: <Chain>.<Ticker> or <Chain>.<Ticker>-<ContractAddress>`)},$=8,b=s=>10n**BigInt(s),S=s=>Math.log10(parseFloat(s.toString()));function B({value:s,bigIntDecimal:e=$,decimal:t=$}){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 C,R,_,T,P,ye,I,L,E,F;const J=class J{constructor(e){A(this,C);A(this,_);A(this,P);A(this,I);A(this,E);p(this,"decimalMultiplier",10n**8n);p(this,"bigIntValue",0n);p(this,"decimal");const t=U(e),r=typeof e=="object";this.decimal=r?e.decimal:void 0,this.decimalMultiplier=r&&"decimalMultiplier"in e?e.decimalMultiplier:b(Math.max(se(O(t)),this.decimal||0)),d(this,P,ye).call(this,t)}static fromBigInt(e,t){return new J({decimal:t,value:B({value:e,bigIntDecimal:t,decimal:t})})}static shiftDecimals({value:e,from:t,to:r}){return this.fromBigInt(e.getBaseValue("bigint")*b(r)/b(t),r)}set(e){return new this.constructor({decimal:this.decimal,value:e,identifier:this.toString()})}add(...e){return d(this,C,R).call(this,"add",...e)}sub(...e){return d(this,C,R).call(this,"sub",...e)}mul(...e){return d(this,C,R).call(this,"mul",...e)}div(...e){return d(this,C,R).call(this,"div",...e)}gt(e){return d(this,_,T).call(this,"gt",e)}gte(e){return d(this,_,T).call(this,"gte",e)}lt(e){return d(this,_,T).call(this,"lt",e)}lte(e){return d(this,_,T).call(this,"lte",e)}eqValue(e){return d(this,_,T).call(this,"eqValue",e)}getValue(e){const t=this.formatBigIntToSafeValue(this.bigIntValue,this.decimal||S(this.decimalMultiplier));switch(e){case"number":return Number(t);case"string":return t;case"bigint":return this.bigIntValue*10n**BigInt(this.decimal||8n)/this.decimalMultiplier}}getBaseValue(e){const t=this.decimalMultiplier/b(this.decimal||i.BaseDecimal.THOR),r=this.bigIntValue/t;switch(e){case"number":return Number(r);case"string":return r.toString();case"bigint":return r}}getBigIntValue(e,t){if(!t&&typeof e=="object")return e.bigIntValue;const r=U(e),n=O(r);return n==="0"||n==="undefined"?0n:d(this,E,F).call(this,n,t)}toSignificant(e=6){const[t,r]=this.getValue("string").split("."),n=t||"",a=r||"";if((parseInt(n)?n.length+a.length:a.length)<=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(e-n.length,"0");const c=parseInt(a),u=`${c}`.slice(0,e);return`0.${u.padStart(a.length-`${c}`.length+u.length,"0")}`}toFixed(e=6){const[t,r]=this.getValue("string").split("."),n=t||"",a=r||"";if(parseInt(n))return`${n}.${a.slice(0,e)}`.padEnd(e,"0");const o=parseInt(a),c=`${o}`.slice(0,e);return`0.${c.padStart(a.length-`${o}`.length+c.length,"0")}`}toAbbreviation(e=2){const t=this.getValue("number"),r=["","K","M","B","T","Q","Qi","S"],n=Math.floor(Math.log10(Math.abs(t))/3),a=r[n];if(!a)return this.getValue("string");const o=10**(n*3);return`${(t/o).toFixed(e)}${a}`}toCurrency(e="$",{currencyPosition:t="start",decimal:r=2,decimalSeparator:n=".",thousandSeparator:a=","}={}){const o=this.getValue("number"),[c,u=""]=o.toFixed(6).split("."),h=c.replace(/\B(?=(\d{3})+(?!\d))/g,a),l=!c&&!u?"0.00":c==="0"?`${parseFloat(`0.${u}`)}`.replace(".",n):`${h}${parseInt(u)?`${n}${u.slice(0,r)}`:""}`;return`${t==="start"?e:""}${l}${t==="end"?e:""}`}formatBigIntToSafeValue(e,t){const r=t||this.decimal||$,n=Math.max(r,S(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,h=u.length-n;let l=u.slice(-n);return parseInt(l[r])>=5?l=`${l.substring(0,r-1)}${(parseInt(l[r-1])+1).toString()}`:l=l.substring(0,r),`${a?"-":""}${u.slice(0,h)}.${l}`.replace(/\.?0*$/,"")}};C=new WeakSet,R=function(e,...t){const r=d(this,I,L).call(this,this,...t),n=Math.max(r,S(this.decimalMultiplier)),a=b(n),o=t.reduce((u,h)=>{const l=this.getBigIntValue(h,n);switch(e){case"add":return u+l;case"sub":return u-l;case"mul":return u*l/a;case"div":{if(l===0n)throw new RangeError("Division by zero");return u*a/l}default:return u}},this.bigIntValue*a/this.decimalMultiplier),c=B({bigIntDecimal:n,decimal:n,value:o});return new this.constructor({decimalMultiplier:b(n),decimal:this.decimal,value:c,identifier:this.toString()})},_=new WeakSet,T=function(e,...t){const r=d(this,I,L).call(this,this,...t),n=this.getBigIntValue(t[0],r),a=this.getBigIntValue(this,r);switch(e){case"gt":return a>n;case"gte":return a>=n;case"lt":return a<n;case"lte":return a<=n;case"eqValue":return a===n}},P=new WeakSet,ye=function(e){const t=O(e)||"0";this.bigIntValue=d(this,E,F).call(this,t)},I=new WeakSet,L=function(...e){const t=e.map(r=>typeof r=="object"?r.decimal||S(r.decimalMultiplier):se(O(r))).filter(Boolean);return Math.max(...t,$)},E=new WeakSet,F=function(e,t){const r=t?b(t):this.decimalMultiplier,n=S(r),[a="",o=""]=e.split(".");return BigInt(`${a}${o.padEnd(n,"0")}`)};let v=J;const ft=Intl.NumberFormat("fullwide",{useGrouping:!1,maximumFractionDigits:20});function O(s){const t=`${typeof s=="number"?ft.format(s):U(s)}`.replaceAll(",",".").split(".");return t.length>1?`${t.slice(0,-1).join("")}.${t.at(-1)}`:t[0]}function se(s){var t;const e=((t=s.split(".")[1])==null?void 0:t.length)||0;return Math.max(e,$)}function U(s){return typeof s=="object"?"getValue"in s?s.getValue("string"):s.value:s}const x=(s,e)=>typeof s=="bigint"?B({value:s,bigIntDecimal:e,decimal:e}):s;let W;const re=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:""}},ne=async(s,e=0)=>{pt(s);const t=await ae(G(s)),r=x(e,t);return new y({decimal:t,value:r,identifier:s})};class y extends v{constructor(t){const r="identifier"in t?t.identifier:`${t.chain}.${t.symbol}`;super(t.value instanceof v?t.value:{decimal:t.decimal,value:t.value});p(this,"address");p(this,"chain");p(this,"isGasAsset",!1);p(this,"isSynthetic",!1);p(this,"symbol");p(this,"tax");p(this,"ticker");p(this,"type");const n=G(r);this.type=ce(n),this.chain=n.chain,this.ticker=n.ticker,this.symbol=n.symbol,this.address=n.address,this.isSynthetic=n.isSynthetic,this.isGasAsset=n.isGasAsset,this.tax=t.tax}toString(t=!1){const r=this.isSynthetic?this.symbol.split("-")[0]: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 ne(t,r)}static fromStringSync(t,r=0){const{isSynthetic:n}=G(t),{tax:a,decimal:o,identifier:c}=re(t),u=x(r,o);return c?new y({tax:a,decimal:o,identifier:c,value:u}):n?new y({tax:a,decimal:8,identifier:t,value:u}):void 0}static async fromIdentifier(t,r=0){return ne(t,r)}static fromIdentifierSync(t,r=0){const{decimal:n,identifier:a}=re(t),o=x(r,n);return new y({decimal:n,identifier:a,value:o})}static fromChainOrSignature(t,r=0){const{decimal:n,identifier:a}=oe(t),o=x(r,n);return new y({value:o,decimal:n,identifier: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:h})=>(h.forEach(({identifier:l,chain:g,...w})=>{const k="decimals"in w?w.decimals:i.BaseDecimal[g];u.set(l,{identifier:l,decimal:k})}),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 gt=s=>{const e=y.fromChainOrSignature(s);switch(s){case i.Chain.Bitcoin:case i.Chain.Litecoin:case i.Chain.BitcoinCash:return e.set(10001e-8);case i.Chain.Dogecoin:return e.set(1.00000001);case i.Chain.Avalanche:case i.Chain.Ethereum:return e.set(1e-8);case i.Chain.THORChain:case i.Chain.Maya:return e.set(0);default:return e.set(1e-8)}},G=s=>{const e=s.slice(0,14).includes("/"),[t,r]=s.split(".").pop().split("/"),n=s.includes(".")&&!e?s:`${i.Chain.THORChain}.${r}`,[a,o]=n.split("."),[c,u]=(e?r:o).split("-");return{address:u==null?void 0:u.toLowerCase(),chain:a,isGasAsset:K({chain:a,symbol:o}),isSynthetic:e,symbol:(e?`${t}/`:"")+(u?`${c}-${(u==null?void 0:u.toLowerCase())??""}`:o),ticker:c}},_t={core_wallet_connection_not_found:10001,core_estimated_max_spendable_chain_not_supported:10002,core_extend_error:10003,core_inbound_data_not_found:10004,core_approve_asset_address_or_from_not_found:10005,core_chain_halted:10099,core_wallet_xdefi_not_installed:10101,core_wallet_evmwallet_not_installed:10102,core_wallet_walletconnect_not_installed:10103,core_wallet_keystore_not_installed:10104,core_wallet_ledger_not_installed:10105,core_wallet_trezor_not_installed:10106,core_wallet_keplr_not_installed:10107,core_wallet_okx_not_installed:10108,core_swap_invalid_params:10200,core_swap_route_not_complete:10201,core_swap_asset_not_recognized:10202,core_swap_contract_not_found:10203,core_swap_route_transaction_not_found:10204,core_swap_contract_not_supported:10205,core_swap_transaction_error:10206,core_swap_quote_mode_not_supported:10207,core_transaction_deposit_error:10301,core_transaction_create_liquidity_rune_error:10302,core_transaction_create_liquidity_asset_error:10303,core_transaction_create_liquidity_invalid_params:10304,core_transaction_add_liquidity_invalid_params:10305,core_transaction_add_liquidity_no_rune_address:10306,core_transaction_add_liquidity_rune_error:10307,core_transaction_add_liquidity_asset_error:10308,core_transaction_withdraw_error:10309,core_transaction_deposit_to_pool_error:10310,core_transaction_deposit_insufficient_funds_error:10311,core_transaction_deposit_gas_error:10312,core_transaction_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:_t[e],message:e}}),Object.setPrototypeOf(this,z.prototype)}}class f extends v{eq(e){return this.eqValue(e)}static fromBigInt(e,t){return new f({decimal:t,value:B({value:e,bigIntDecimal:t,decimal:t})})}}exports.AssetValue=y;exports.BigIntArithmetics=v;exports.RequestClient=_e;exports.SwapKitError=z;exports.SwapKitNumber=f;exports.assetFromString=ke;exports.derivationPathToString=Je;exports.filterAssets=je;exports.formatBigIntToSafeValue=B;exports.gasFeeMultiplier=Pe;exports.getAssetType=ce;exports.getAsymmetricAssetShare=le;exports.getAsymmetricAssetWithdrawAmount=Le;exports.getAsymmetricRuneShare=ue;exports.getAsymmetricRuneWithdrawAmount=He;exports.getCommonAssetInfo=oe;exports.getDecimal=ae;exports.getEstimatedPoolShare=Ue;exports.getLiquiditySlippage=We;exports.getMemoFor=Ke;exports.getMinAmountByChain=gt;exports.getSymmetricPoolShare=he;exports.getSymmetricWithdraw=Fe;exports.getTHORNameCost=Ye;exports.isGasAsset=K;exports.validateTHORName=ze;
package/dist/index.d.ts CHANGED
@@ -24,14 +24,15 @@ export declare const assetFromString: (assetString: string) => {
24
24
  };
25
25
 
26
26
  export declare class AssetValue extends BigIntArithmetics {
27
- constructor(params: AssetValueParams);
28
27
  address?: string;
29
- isSynthetic: boolean;
30
- isGasAsset: boolean;
31
28
  chain: Chain;
29
+ isGasAsset: boolean;
30
+ isSynthetic: boolean;
32
31
  symbol: string;
32
+ tax?: TokenTax;
33
33
  ticker: string;
34
34
  type: ReturnType<typeof getAssetType>;
35
+ constructor(params: AssetValueParams);
35
36
  toString(short?: boolean): string;
36
37
  eq({ chain, symbol }: {
37
38
  chain: Chain;
@@ -54,6 +55,7 @@ export declare class AssetValue extends BigIntArithmetics {
54
55
  declare type AssetValueParams = {
55
56
  decimal: number;
56
57
  value: SwapKitValueType;
58
+ tax?: TokenTax;
57
59
  } & ({
58
60
  chain: Chain;
59
61
  symbol: string;
@@ -347,6 +349,11 @@ export declare type ThornameRegisterParam = {
347
349
 
348
350
  declare type TokenNames = TCTokenNames | (typeof CoinGeckoList)['tokens'][number]['identifier'] | (typeof MayaList)['tokens'][number]['identifier'] | (typeof PancakeswapETHList)['tokens'][number]['identifier'] | (typeof PancakeswapList)['tokens'][number]['identifier'] | (typeof PangolinList)['tokens'][number]['identifier'] | (typeof StargateARBList)['tokens'][number]['identifier'] | (typeof SushiswapList)['tokens'][number]['identifier'] | (typeof TraderjoeList)['tokens'][number]['identifier'] | (typeof WoofiList)['tokens'][number]['identifier'] | (typeof UniswapList)['tokens'][number]['identifier'];
349
351
 
352
+ declare type TokenTax = {
353
+ buy: number;
354
+ sell: number;
355
+ };
356
+
350
357
  export declare const validateTHORName: (name: string) => boolean;
351
358
 
352
359
  declare type WithAddress<T = {}> = T & {