@swapkit/helpers 1.0.0-rc.2 → 1.0.0-rc.21

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 le=Object.create;var H=Object.defineProperty;var ue=Object.getOwnPropertyDescriptor;var he=Object.getOwnPropertyNames;var de=Object.getPrototypeOf,me=Object.prototype.hasOwnProperty;var ge=(n,e,t)=>e in n?H(n,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):n[e]=t;var _e=(n,e,t,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of he(e))!me.call(n,s)&&s!==t&&H(n,s,{get:()=>e[s],enumerable:!(i=ue(e,s))||i.enumerable});return n};var pe=(n,e,t)=>(t=n!=null?le(de(n)):{},_e(e||!n||!n.__esModule?H(t,"default",{value:n,enumerable:!0}):t,n));var m=(n,e,t)=>(ge(n,typeof e!="symbol"?e+"":e,t),t),Ce=(n,e,t)=>{if(!e.has(n))throw TypeError("Cannot "+t)};var p=(n,e,t)=>{if(e.has(n))throw TypeError("Cannot add the same private member more than once");e instanceof WeakSet?e.add(n):e.set(n,t)};var h=(n,e,t)=>(Ce(n,e,"access private method"),t);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const a=require("@swapkit/types"),fe=n=>{if(n<0)throw new Error("Invalid number of year");return 10+n},Ae=n=>{if(n.length>30)return!1;const e=/^[a-zA-Z0-9+_-]+$/g;return!!n.match(e)},we=([n,e,t,i,s])=>`${n}'/${e}'/${t}'/${i}${typeof s!="number"?"":`/${s}`}`,Se=async(n,e)=>{const t=Object.entries(e||{}).reduce((s,[r,c])=>(c&&(s[r]=c),s),{});return(await fetch(`${n}${e?`?${new URLSearchParams(t).toString()}`:""}`,{method:"GET",mode:"cors",credentials:"omit",referrer:"https://sk.thorswap.net"})).json()},Y=async(n,e,t,i=!1)=>{const s=await fetch(`${n}`,{body:e,headers:t,method:"POST",referrer:"https://sk.thorswap.net"});return i?s.text():s.json()},$e="0x313ce567",J=async({chain:n,to:e})=>{try{const t=await Y(a.ChainToRPC[n],JSON.stringify({method:"eth_call",params:[{to:e.toLowerCase(),data:$e},"latest"],id:44,jsonrpc:"2.0"}),{accept:"*/*","cache-control":"no-cache","content-type":"application/json"},!0),{result:i}=JSON.parse(t);return parseInt(BigInt(i).toString())}catch(t){return console.error(t),a.BaseDecimal[n]}},be=async n=>{if(n===a.Chain.Ethereum)return a.BaseDecimal.ETH;const[,e]=n.split("-");return e!=null&&e.startsWith("0x")?J({chain:a.Chain.Ethereum,to:e}):a.BaseDecimal.ETH},ye=async n=>{const[,e]=n.split("-");return e!=null&&e.startsWith("0x")?J({chain:a.Chain.Avalanche,to:e.toLowerCase()}):a.BaseDecimal.AVAX},Be=async n=>(n===a.Chain.BinanceSmartChain,a.BaseDecimal.BSC),F=async({chain:n,symbol:e})=>{switch(n){case a.Chain.Ethereum:return be(e);case a.Chain.Avalanche:return ye(e);case a.Chain.BinanceSmartChain:return Be(e);default:return a.BaseDecimal[n]}},Ie={[a.FeeOption.Average]:1.2,[a.FeeOption.Fast]:1.5,[a.FeeOption.Fastest]:2},z=({chain:n,symbol:e})=>{switch(n){case a.Chain.Bitcoin:case a.Chain.BitcoinCash:case a.Chain.Litecoin:case a.Chain.Dogecoin:case a.Chain.Binance:case a.Chain.Ethereum:case a.Chain.Avalanche:return e===n;case a.Chain.Arbitrum:case a.Chain.Optimism:return e==="ETH";case a.Chain.Maya:return e==="CACAO";case a.Chain.Kujira:return e==="KUJI";case a.Chain.Cosmos:return e==="ATOM";case a.Chain.Polygon:return e==="MATIC";case a.Chain.BinanceSmartChain:return e==="BNB";case a.Chain.THORChain:return e==="RUNE"}},X=n=>{switch(n){case"ETH.THOR":return{identifier:"ETH.THOR-0xa5f2211b9b8170f694421f2046281775e8468044",decimal:18};case"ETH.vTHOR":return{identifier:"ETH.vTHOR-0x815c23eca83261b6ec689b60cc4a58b54bc24d8d",decimal:18};case a.Chain.Cosmos:return{identifier:"GAIA.ATOM",decimal:a.BaseDecimal[n]};case a.Chain.THORChain:return{identifier:"THOR.RUNE",decimal:a.BaseDecimal[n]};case a.Chain.BinanceSmartChain:return{identifier:"BSC.BNB",decimal:a.BaseDecimal[n]};case a.Chain.Maya:return{identifier:"MAYA.CACAO",decimal:a.BaseDecimal.MAYA};case"MAYA.MAYA":return{identifier:"MAYA.MAYA",decimal:4};case a.Chain.Kujira:case a.Chain.Arbitrum:case a.Chain.Optimism:case a.Chain.BitcoinCash:case a.Chain.Litecoin:case a.Chain.Dogecoin:case a.Chain.Binance:case a.Chain.Avalanche:case a.Chain.Polygon:case a.Chain.Bitcoin:case a.Chain.Ethereum:return{identifier:`${n}.${n}`,decimal:a.BaseDecimal[n]}}},Q=({chain:n,symbol:e})=>{if(e.includes("/"))return"Synth";switch(n){case a.Chain.Bitcoin:case a.Chain.BitcoinCash:case a.Chain.Dogecoin:case a.Chain.Litecoin:case a.Chain.Maya:case a.Chain.THORChain:return"Native";case a.Chain.Cosmos:return e==="ATOM"?"Native":"GAIA";case a.Chain.Kujira:return e==="KUJI"?"Native":"KUJI";case a.Chain.Binance:return e===a.Chain.Binance?"Native":"BEP2";case a.Chain.BinanceSmartChain:return e===a.Chain.Binance?"Native":"BEP20";case a.Chain.Ethereum:return e===a.Chain.Ethereum?"Native":"ERC20";case a.Chain.Avalanche:return e===a.Chain.Avalanche?"Native":"AVAX";case a.Chain.Polygon:return e===a.Chain.Polygon?"Native":"POLYGON";case a.Chain.Arbitrum:return[a.Chain.Ethereum,a.Chain.Arbitrum].includes(e)?"Native":"ARBITRUM";case a.Chain.Optimism:return[a.Chain.Ethereum,a.Chain.Optimism].includes(e)?"Native":"OPTIMISM"}},Te=n=>{var c;const[e,...t]=n.split("."),i=n.includes("/"),s=t.join("."),r=(c=s==null?void 0:s.split("-"))==null?void 0:c[0];return{chain:e,symbol:s,ticker:r,synth:i}},Z=({liquidityUnits:n,poolUnits:e,runeDepth:t})=>{const i=d(n),s=d(e),r=d(t),c=i.mul(r),o=s.mul(s).mul(2),u=s.mul(i).mul(2),l=i.mul(i),g=s.mul(s).mul(s);return c.mul(o.sub(u).add(l)).div(g)},ee=({liquidityUnits:n,poolUnits:e,assetDepth:t})=>{const i=d(n),s=d(e),r=d(t),c=i.mul(r),o=s.mul(s).mul(2),u=s.mul(i).mul(2),l=i.mul(i),g=c.mul(o.sub(u).add(l)),C=s.mul(s).mul(s);return g.div(C)},ve=({percent:n,runeDepth:e,liquidityUnits:t,poolUnits:i})=>Z({runeDepth:e,liquidityUnits:t,poolUnits:i}).mul(n),Me=({percent:n,assetDepth:e,liquidityUnits:t,poolUnits:i})=>ee({assetDepth:e,liquidityUnits:t,poolUnits:i}).mul(n),d=n=>new ae({value:n,decimal:a.BaseDecimal.THOR}),te=({liquidityUnits:n,poolUnits:e,runeDepth:t,assetDepth:i})=>({assetAmount:d(i).mul(n).div(e),runeAmount:d(t).mul(n).div(e)}),Ee=({liquidityUnits:n,poolUnits:e,runeDepth:t,assetDepth:i,percent:s})=>Object.fromEntries(Object.entries(te({liquidityUnits:n,poolUnits:e,runeDepth:t,assetDepth:i})).map(([r,c])=>[r,c.mul(s)])),Oe=({runeDepth:n,poolUnits:e,assetDepth:t,liquidityUnits:i,runeAmount:s,assetAmount:r})=>{const c=d(n),o=d(t),u=d(e),l=d(s),g=d(r),C=l.mul(o),b=g.mul(c),N=l.mul(g),se=c.mul(o),re=u.mul(C.add(b.add(N.mul(2)))),ce=C.add(b.add(se.mul(2))),G=re.div(ce),R=d(i).add(G);if(G.baseValueNumber===0)return R.div(u).baseValueNumber;const oe=u.add(R);return R.div(oe).baseValueNumber},De=({runeAmount:n,assetAmount:e,runeDepth:t,assetDepth:i})=>{const s=d(t),r=d(i),c=d(e),o=d(n),u=c.mul(s).sub(r.mul(o)),l=r.mul(o).add(s.mul(r));return Math.abs(u.div(l).baseValueNumber)},Ve=({symbol:n,ticker:e,chain:t})=>t==="ETH"&&e!=="ETH"?`${e}-${n.slice(-3)}`:n,Ne=(n,e)=>{switch(n){case a.MemoType.LEAVE:case a.MemoType.BOND:{const{address:t}=e;return`${n}:${t}`}case a.MemoType.UNBOND:{const{address:t,unbondAmount:i}=e;return`${n}:${t}:${i*10**8}`}case a.MemoType.THORNAME_REGISTER:{const{name:t,chain:i,address:s,owner:r}=e;return`${n}:${t}:${i}:${s}${r?`:${r}`:""}`}case a.MemoType.DEPOSIT:{const{chain:t,symbol:i,address:s,singleSide:r}=e;return r?`${n}:${t}/${i}::t:0`:`${n}:${t}.${i}:${s||""}:t:0`}case a.MemoType.WITHDRAW:{const{chain:t,ticker:i,symbol:s,basisPoints:r,targetAssetString:c,singleSide:o}=e,u=!o&&c?`:${c}`:"",l=Ve({chain:t,symbol:s,ticker:i});return`${n}:${t}${o?"/":"."}${l}:${r}${u}`}case a.MemoType.OPEN_LOAN:case a.MemoType.CLOSE_LOAN:{const{asset:t,address:i}=e;return`${n}:${t}:${i}`}default:return""}},S=8,P=({value:n,bigIntDecimal:e=S,decimal:t=S})=>{const i=n<0n;let s=n.toString().substring(i?1:0);const r=t-(s.length-1);r>0&&(s="0".repeat(r)+s);const c=s.length-t;let o=s.slice(-t);return parseInt(o[e])>=5?o=`${o.substring(0,e-1)}${(parseInt(o[e-1])+1).toString()}`:o=o.substring(0,e),`${i?"-":""}${s.slice(0,c)}.${o}`.replace(/\.?0*$/,"")},W=Object.values(a.Chain),Re=(n="")=>{const e=n.toUpperCase(),[t]=e.split(".");if(W.includes(t))return!0;const[i]=e.split("/");if(W.includes(i))return!0;throw new Error(`Invalid identifier: ${n}. Expected format: <Chain>.<Ticker> or <Chain>.<Ticker>-<ContractAddress>`)},w=n=>10n**BigInt(n),y=n=>Math.log10(parseFloat(n.toString()));var f,B,D,ne,V,ie,M,L,A,I,E,x,$,O;const T=class T{constructor(e){p(this,f);p(this,D);p(this,V);p(this,M);p(this,A);p(this,E);p(this,$);m(this,"decimalMultiplier",10n**8n);m(this,"bigIntValue",0n);m(this,"decimal");const t=typeof e=="object",i=t?e.value:e;this.decimal=t?e.decimal:void 0,this.decimalMultiplier=w(Math.max(h(this,E,x).call(this,h(this,A,I).call(this,i)),this.decimal||0)),h(this,D,ne).call(this,i)}static fromBigInt(e,t){return new T({decimal:t,value:P({value:e,bigIntDecimal:t,decimal:t})})}static shiftDecimals({value:e,from:t,to:i}){return T.fromBigInt(new T(e).bigIntValue*w(i)/w(t),i)}get unsafeNumber(){return parseFloat((this.bigIntValue/this.decimalMultiplier).toString())}get baseValue(){return h(this,$,O).call(this,"string")}get baseValueNumber(){return h(this,$,O).call(this,"number")}get baseValueBigInt(){return h(this,$,O).call(this,"number")}get value(){return this.formatBigIntToSafeValue(this.bigIntValue,this.decimal||y(this.decimalMultiplier))}add(...e){return h(this,f,B).call(this,"add",...e)}sub(...e){return h(this,f,B).call(this,"sub",...e)}mul(...e){return h(this,f,B).call(this,"mul",...e)}div(...e){return h(this,f,B).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)}getBigIntValue(e,t){return!t&&typeof e=="object"?e.bigIntValue:(e=typeof e=="object"?e.value:e,h(this,M,L).call(this,h(this,A,I).call(this,e),t))}formatBigIntToSafeValue(e,t){const i=t||this.decimal||S,s=Math.max(i,y(this.decimalMultiplier)),r=e<0n;let c=e.toString().substring(r?1:0);const o=s-(c.length-1);o>0&&(c="0".repeat(o)+c);const u=c.length-s;let l=c.slice(-s);return parseInt(l[i])>=5?l=`${l.substring(0,i-1)}${(parseInt(l[i-1])+1).toString()}`:l=l.substring(0,i),`${r?"-":""}${c.slice(0,u)}.${l}`.replace(/\.?0*$/,"")}toSignificant(e){const t=this.value.split("."),i=t[0],s=t[1];return s?`${i}.${s.slice(0,e||this.decimal)}`.replace(/\.?0*$/,""):i}};f=new WeakSet,B=function(e,...t){const i=h(this,V,ie).call(this,this,...t),s=w(i),r=t.reduce((o,u)=>{const l=this.getBigIntValue(u,i);if(e==="div"&&l===0n)throw new RangeError("Division by zero");return e==="add"?o+l:e==="sub"?o-l:e==="mul"?o*l/s:o*s/l},this.bigIntValue*s/this.decimalMultiplier),c=P({bigIntDecimal:i,decimal:Math.max(i,y(this.decimalMultiplier)),value:r});return new this.constructor({decimal:this.decimal,value:c,identifier:this.toString()})},D=new WeakSet,ne=function(e,t){const i=h(this,A,I).call(this,e)||"0";this.bigIntValue=t||h(this,M,L).call(this,i)},V=new WeakSet,ie=function(...e){const t=e.map(i=>typeof i=="object"?i.decimal||y(i.decimalMultiplier):h(this,E,x).call(this,h(this,A,I).call(this,i))).filter(Boolean);return Math.max(...t,S)},M=new WeakSet,L=function(e,t){const i=t?w(t):this.decimalMultiplier,s=y(i),[r,c=""]=e.split(".");return BigInt(`${r}${c.padEnd(s,"0")}`)},A=new WeakSet,I=function(e){const i=`${typeof e=="number"?Number(e).toLocaleString("fullwide",{useGrouping:!1,maximumFractionDigits:20}):e}`.replaceAll(",",".").split(".");return i.length>1?`${i.slice(0,-1).join("")}.${i.at(-1)}`:i[0]},E=new WeakSet,x=function(e){var i;const t=((i=e.split(".")[1])==null?void 0:i.length)||0;return Math.max(t,S)},$=new WeakSet,O=function(e){const t=this.decimalMultiplier/w(this.decimal||0),i=this.bigIntValue/t;switch(e){case"number":return Number(i);case"string":return i.toString();default:return i}};let v=T,j;const k=n=>{if(!j)throw new Error("Static assets not loaded, call await AssetValue.loadStaticAssets() first");return j.get(n.toUpperCase())||{decimal:a.BaseDecimal.THOR,identifier:""}},K=async(n,e=0)=>{Re(n);const t=await F(q(n));return new _({decimal:t,value:e,identifier:n})};class _ extends v{constructor(t){super(t.value instanceof v?t.value:{decimal:t.decimal,value:t.value});m(this,"address");m(this,"chain");m(this,"isSynthetic",!1);m(this,"isGasAsset",!1);m(this,"symbol");m(this,"ticker");m(this,"type");const i="identifier"in t?t.identifier:`${t.chain}.${t.symbol}`,s=q(i);this.type=Q(s),this.chain=s.chain,this.ticker=s.ticker,this.symbol=s.symbol,this.address=s.address,this.isSynthetic=s.isSynthetic,this.isGasAsset=s.isGasAsset}static async fromString(t,i=0){return K(t,i)}static fromStringSync(t,i=0){const{decimal:s,identifier:r}=k(t);return r?new _({decimal:s,identifier:r,value:i}):void 0}static async fromIdentifier(t,i=0){return K(t,i)}static fromIdentifierSync(t,i=0){const{decimal:s,identifier:r}=k(t);return new _({decimal:s,identifier:r,value:i})}static fromChainOrSignature(t,i=0){const{decimal:s,identifier:r}=X(t);return new _({value:i,decimal:s,identifier:r})}static async fromTCQuote(t,i=0){const s=await F(q(t)),r=this.shiftDecimals({value:i,from:a.BaseDecimal.THOR,to:s});return new _({value:r,identifier:t,decimal:s})}static fromTCQuoteStatic(t,i=0){const s=k(t),r=this.shiftDecimals({value:i,from:a.BaseDecimal.THOR,to:s.decimal});return new _({...s,value:r})}static async loadStaticAssets(){return new Promise(async(t,i)=>{try{const{ThorchainList:s,NativeList:r,...c}=await import("@swapkit/tokens");j=[r,...Object.values(c)].reduce((u,{tokens:l})=>(l.forEach(({identifier:g,chain:C,...b})=>{const N="decimals"in b?b.decimals:a.BaseDecimal[C];u.set(g,{identifier:g,decimal:N})}),u),new Map),t({ok:!0})}catch(s){console.error(s),i({ok:!1,error:s,message:"Couldn't load static assets. Ensure you have installed @swapkit/tokens package"})}})}get assetValue(){return`${this.value} ${this.ticker}`}toString(){return`${this.chain}.${this.symbol}`}eq({chain:t,symbol:i}){return this.chain===t&&this.symbol===i}}const He=n=>{const e=_.fromChainOrSignature(n);switch(n){case a.Chain.Bitcoin:case a.Chain.Litecoin:case a.Chain.BitcoinCash:return e.add(10001);case a.Chain.Dogecoin:return e.add(100000001);case a.Chain.Avalanche:case a.Chain.Ethereum:return e.add(10*10**9);case a.Chain.THORChain:case a.Chain.Maya:return e.add(0);default:return e.add(1)}},q=n=>{const e=n.slice(0,14).includes("/"),t=n.includes(".")?n:`${a.Chain.THORChain}.${n}`,[i,s]=t.split("."),[r,c]=s.split("-");return{address:c==null?void 0:c.toLowerCase(),chain:i,isGasAsset:z({chain:i,symbol:s}),isSynthetic:e,symbol:c?`${r}-${(c==null?void 0:c.toLowerCase())??""}`:s,ticker:e?s:r}},ke={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 U extends Error{constructor(e,t){console.error(t),super(e,{cause:{code:ke[e],message:e}}),Object.setPrototypeOf(this,U.prototype)}}class ae extends v{eq(e){return this.eqValue(e)}toString(){return this.value}}exports.AssetValue=_;exports.DEFAULT_DECIMAL=S;exports.SwapKitError=U;exports.SwapKitNumber=ae;exports.assetFromString=Te;exports.derivationPathToString=we;exports.formatBigIntToSafeValue=P;exports.gasFeeMultiplier=Ie;exports.getAssetType=Q;exports.getAsymmetricAssetShare=ee;exports.getAsymmetricAssetWithdrawAmount=Me;exports.getAsymmetricRuneShare=Z;exports.getAsymmetricRuneWithdrawAmount=ve;exports.getCommonAssetInfo=X;exports.getDecimal=F;exports.getEstimatedPoolShare=Oe;exports.getLiquiditySlippage=De;exports.getMemoFor=Ne;exports.getMinAmountByChain=He;exports.getRequest=Se;exports.getSymmetricPoolShare=te;exports.getSymmetricWithdraw=Ee;exports.getTHORNameCost=fe;exports.isGasAsset=z;exports.postRequest=Y;exports.validateTHORName=Ae;
1
+ "use strict";var Te=Object.create;var D=Object.defineProperty;var Se=Object.getOwnPropertyDescriptor;var ve=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 ve(e))!$e.call(s,n)&&n!==t&&D(s,n,{get:()=>e[n],enumerable:!(r=Se(e,n))||r.enumerable});return s};var Ee=(s,e,t)=>(t=s!=null?Te(Re(s)):{},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),Oe=(s,e,t)=>{if(!e.has(s))throw TypeError("Cannot "+t)};var y=(s,e,t)=>{if(e.has(s))throw TypeError("Cannot add the same private member more than once");e instanceof WeakSet?e.add(s):e.set(s,t)};var d=(s,e,t)=>(Oe(s,e,"access private method"),t);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const i=require("@swapkit/types"),Me="0x313ce567",se=async({chain:s,to:e})=>{try{const{result:t}=await ge.post(i.ChainToRPC[s],{headers:{accept:"*/*","content-type":"application/json","cache-control":"no-cache"},body:JSON.stringify({id:44,jsonrpc:"2.0",method:"eth_call",params:[{to:e.toLowerCase(),data: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")?se({chain:i.Chain.Ethereum,to:e}):i.BaseDecimal.ETH},qe=async s=>{const[,e]=s.split("-");return e!=null&&e.startsWith("0x")?se({chain:i.Chain.Avalanche,to:e.toLowerCase()}):i.BaseDecimal.AVAX},ke=async s=>(s===i.Chain.BinanceSmartChain,i.BaseDecimal.BSC),ne=async({chain:s,symbol:e})=>{switch(s){case i.Chain.Ethereum:return Ve(e);case i.Chain.Avalanche:return qe(e);case i.Chain.BinanceSmartChain:return ke(e);default:return i.BaseDecimal[s]}},Pe={[i.FeeOption.Average]:1.2,[i.FeeOption.Fast]:1.5,[i.FeeOption.Fastest]:2},ie=({chain:s,symbol:e})=>{switch(s){case i.Chain.Bitcoin:case i.Chain.BitcoinCash:case i.Chain.Litecoin:case i.Chain.Dogecoin:case i.Chain.Binance:case i.Chain.Ethereum:case i.Chain.Avalanche:return e===s;case i.Chain.Arbitrum:case i.Chain.Optimism:return e==="ETH";case i.Chain.Maya:return e==="CACAO";case i.Chain.Kujira:return e==="KUJI";case i.Chain.Cosmos:return e==="ATOM";case i.Chain.Polygon:return e==="MATIC";case i.Chain.BinanceSmartChain:return e==="BNB";case i.Chain.THORChain:return e==="RUNE"}},ae=s=>{switch(s){case"ETH.THOR":return{identifier:"ETH.THOR-0xa5f2211b9b8170f694421f2046281775e8468044",decimal:18};case"ETH.vTHOR":return{identifier:"ETH.vTHOR-0x815c23eca83261b6ec689b60cc4a58b54bc24d8d",decimal:18};case i.Chain.Cosmos:return{identifier:"GAIA.ATOM",decimal:i.BaseDecimal[s]};case i.Chain.THORChain:return{identifier:"THOR.RUNE",decimal:i.BaseDecimal[s]};case i.Chain.BinanceSmartChain:return{identifier:"BSC.BNB",decimal:i.BaseDecimal[s]};case i.Chain.Maya:return{identifier:"MAYA.CACAO",decimal:i.BaseDecimal.MAYA};case"MAYA.MAYA":return{identifier:"MAYA.MAYA",decimal:4};case i.Chain.Kujira:case i.Chain.Arbitrum:case i.Chain.Optimism:case i.Chain.BitcoinCash:case i.Chain.Litecoin:case i.Chain.Dogecoin:case i.Chain.Binance:case i.Chain.Avalanche:case i.Chain.Polygon:case i.Chain.Bitcoin:case i.Chain.Ethereum:return{identifier:`${s}.${s}`,decimal:i.BaseDecimal[s]}}},oe=({chain:s,symbol:e})=>{if(e.includes("/"))return"Synth";switch(s){case i.Chain.Bitcoin:case i.Chain.BitcoinCash:case i.Chain.Dogecoin:case i.Chain.Litecoin:case i.Chain.Maya:case i.Chain.THORChain:return"Native";case i.Chain.Cosmos:return e==="ATOM"?"Native":i.Chain.Cosmos;case i.Chain.Kujira:return e===i.Chain.Kujira?"Native":i.Chain.Kujira;case i.Chain.Binance:return e===i.Chain.Binance?"Native":"BEP2";case i.Chain.BinanceSmartChain:return e===i.Chain.Binance?"Native":"BEP20";case i.Chain.Ethereum:return e===i.Chain.Ethereum?"Native":"ERC20";case i.Chain.Avalanche:return e===i.Chain.Avalanche?"Native":i.Chain.Avalanche;case i.Chain.Polygon:return e===i.Chain.Polygon?"Native":"POLYGON";case i.Chain.Arbitrum:return[i.Chain.Ethereum,i.Chain.Arbitrum].includes(e)?"Native":"ARBITRUM";case i.Chain.Optimism:return[i.Chain.Ethereum,i.Chain.Optimism].includes(e)?"Native":"OPTIMISM"}},xe=s=>{var o;const[e,...t]=s.split("."),r=s.includes("/"),n=t.join("."),a=(o=n==null?void 0:n.split("-"))==null?void 0:o[0];return{chain:e,symbol:n,ticker:a,synth:r}},Ne=new RegExp(/(.)\1{6}|\.ORG|\.NET|\.FINANCE|\.COM|WWW|HTTP|\\\\|\/\/|[\s$%:[\]]/,"gmi"),De=s=>s.filter(e=>!Ne.test(e.toString())&&!e.toString().includes("undefined")),ce=({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),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=m(s),n=m(e),a=m(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)},je=({percent:s,runeDepth:e,liquidityUnits:t,poolUnits:r})=>ce({runeDepth:e,liquidityUnits:t,poolUnits:r}).mul(s),He=({percent:s,assetDepth:e,liquidityUnits:t,poolUnits:r})=>ue({assetDepth:e,liquidityUnits:t,poolUnits:r}).mul(s),m=s=>f.fromBigInt(BigInt(s),i.BaseDecimal.THOR),le=({liquidityUnits:s,poolUnits:e,runeDepth:t,assetDepth:r})=>({assetAmount:m(r).mul(s).div(e),runeAmount:m(t).mul(s).div(e)}),Le=({liquidityUnits:s,poolUnits:e,runeDepth:t,assetDepth:r,percent:n})=>Object.fromEntries(Object.entries(le({liquidityUnits:s,poolUnits:e,runeDepth:t,assetDepth:r})).map(([a,o])=>[a,o.mul(n)])),Fe=({runeDepth:s,poolUnits:e,assetDepth:t,liquidityUnits:r,runeAmount:n,assetAmount:a})=>{const o=new f({value:s,decimal:8}),c=new f({value:t,decimal:8}),u=new f({value:e,decimal:8}),l=new f({value:n,decimal:8}),h=new f({value:a,decimal:8}),g=l.mul(c),w=h.mul(o),x=l.mul(h),be=o.mul(c),Ce=u.mul(g.add(w.add(x.mul(2)))),we=g.add(w.add(be.mul(2))),J=Ce.div(we),N=m(r).add(J);if(J.getBaseValue("number")===0)return N.div(u).getBaseValue("number");const Ae=u.add(N);return N.div(Ae).getBaseValue("number")},Ue=({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)),l=a.mul(c).add(n.mul(a));return Math.abs(u.div(l).getBaseValue("number"))},We=({symbol:s,ticker:e,chain:t})=>t==="ETH"&&e!=="ETH"?`${e}-${s.slice(-3)}`:s,Ge=(s,e)=>{switch(s){case i.MemoType.LEAVE:case i.MemoType.BOND:{const{address:t}=e;return`${s}:${t}`}case i.MemoType.UNBOND:{const{address:t,unbondAmount:r}=e;return`${s}:${t}:${r*10**8}`}case i.MemoType.THORNAME_REGISTER:{const{name:t,chain:r,address:n,owner:a}=e;return`${s}:${t}:${r}:${n}${a?`:${a}`:""}`}case i.MemoType.DEPOSIT:{const{chain:t,symbol:r,address:n,singleSide:a}=e;return a?`${s}:${t}/${r}::t:0`:`${s}:${t}.${r}:${n||""}:t:0`}case i.MemoType.WITHDRAW:{const{chain:t,ticker:r,symbol:n,basisPoints:a,targetAssetString:o,singleSide:c}=e,u=!c&&o?`:${o}`:"",l=We({chain:t,symbol:n,ticker:r});return`${s}:${t}${c?"/":"."}${l}:${a}${u}`}case i.MemoType.OPEN_LOAN:case i.MemoType.CLOSE_LOAN:{const{asset:t,address:r}=e;return`${s}:${t}:${r}`}default:return""}},Ke=s=>{if(s<0)throw new Error("Invalid number of year");return 10+s},Ye=s=>{if(s.length>30)return!1;const e=/^[a-zA-Z0-9+_-]+$/g;return!!s.match(e)},ze=([s,e,t,r,n])=>`${s}'/${e}'/${t}'/${r}${typeof n!="number"?"":`/${n}`}`;class 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 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 M=s=>s!==null&&typeof s=="object",O=(...s)=>{for(const e of s)if((!M(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(M(r)){for(let[n,a]of Object.entries(r))M(a)&&n in e&&(a=K(e[n],a)),e={...e,[n]:a};M(r.headers)&&(t=de(t,r.headers),e.headers=t)}return e},Je=(()=>{let s=!1,e=!1;const t=typeof globalThis.ReadableStream=="function",r=typeof globalThis.Request=="function";return t&&r&&(e=new globalThis.Request("https://empty.invalid",{body:new globalThis.ReadableStream,method:"POST",get duplex(){return s=!0,"half"}}).headers.has("Content-Type")),s&&!e})(),Qe=typeof globalThis.AbortController=="function",Xe=typeof globalThis.ReadableStream=="function",Ze=typeof globalThis.FormData=="function",me=["get","post","put","patch","head","delete"],et={json:"application/json",text:"text/*",formData:"multipart/form-data",arrayBuffer:"*/*",blob:"*/*"},j=2147483647,pe=Symbol("stop"),tt={json:!0,parseJson:!0,searchParams:!0,prefixUrl:!0,retry:!0,timeout:!0,hooks:!0,throwHttpErrors:!0,onDownloadProgress:!0,fetch:!0},rt={method:!0,headers:!0,body:!0,mode:!0,credentials:!0,cache:!0,redirect:!0,referrer:!0,referrerPolicy:!0,integrity:!0,keepalive:!0,signal:!0,window:!0,dispatcher:!0,duplex:!0},st=s=>me.includes(s)?s.toUpperCase():s,nt=["get","put","head","delete","options","trace"],it=[408,413,429,500,502,503,504],fe=[413,429,503],X={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{...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: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 q{static create(e,t){const r=new q(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 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(!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(Je&&(this._options.duplex="half"),this.request=new globalThis.Request(this._input,this._options),this._options.searchParams){const n="?"+(typeof this._options.searchParams=="string"?this._options.searchParams.replace(/^\?/,""):new URLSearchParams(this._options.searchParams).toString()),a=this.request.url.replace(/(?:\?.*?)?(?=#|$)/,n);(Ze&&this._options.body instanceof globalThis.FormData||this._options.body instanceof URLSearchParams)&&!(this._options.headers&&this._options.headers["content-type"])&&this.request.headers.delete("content-type"),this.request=new globalThis.Request(new globalThis.Request(a,{...this.request}),this._options)}this._options.json!==void 0&&(this._options.body=JSON.stringify(this._options.json),this.request.headers.set("content-type",this._options.headers.get("content-type")??"application/json"),this.request=new globalThis.Request(this.request,{body:this._options.body}))}_calculateRetryDelay(e){if(this._retryCount++,this._retryCount<this._options.retry.limit&&!(e instanceof he)){if(e instanceof 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),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 L=s=>{const e=(t,r)=>q.create(t,O(s,r));for(const t of me)e[t]=(r,n)=>q.create(r,O(s,n,{method:t}));return e.create=t=>L(O(t)),e.extend=t=>L(O(s,t)),e.stop=pe,e},lt=L(),ht=lt,dt=typeof window<"u"?{}:{referrer:"https://sk.thorswap.net",referer:"https://sk.thorswap.net"},Z=ht.create({headers:dt}),ge={get:(s,e)=>Z.get(s,e).json(),post:(s,e)=>Z.post(s,e).json()},ee=Object.values(i.Chain),mt=(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>`)},$=8,A=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 b,v,k,_e,P,ye,I,F,C,R,E,U;const z=class z{constructor(e){y(this,b);y(this,k);y(this,P);y(this,I);y(this,C);y(this,E);p(this,"decimalMultiplier",10n**8n);p(this,"bigIntValue",0n);p(this,"decimal");const t=H(e);this.decimal=typeof e=="object"?e.decimal:void 0,this.decimalMultiplier=A(Math.max(d(this,E,U).call(this,d(this,C,R).call(this,t)),this.decimal||0)),d(this,k,_e).call(this,t)}static fromBigInt(e,t){return new z({decimal:t,value:B({value:e,bigIntDecimal:t,decimal:t})})}static shiftDecimals({value:e,from:t,to:r}){return this.fromBigInt(e.getBaseValue("bigint")*A(r)/A(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 d(this,b,v).call(this,"add",...e)}sub(...e){return d(this,b,v).call(this,"sub",...e)}mul(...e){return d(this,b,v).call(this,"mul",...e)}div(...e){return d(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||S(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/A(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=H(e),n=d(this,C,R).call(this,r);return n==="0"||n==="undefined"?0n:d(this,I,F).call(this,n,t)}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,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||"";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}`}};b=new WeakSet,v=function(e,...t){const r=d(this,P,ye).call(this,this,...t),n=A(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=B({bigIntDecimal:r,decimal:Math.max(r,S(this.decimalMultiplier)),value:a});return new this.constructor({decimal:this.decimal,value:o,identifier:this.toString()})},k=new WeakSet,_e=function(e){const t=d(this,C,R).call(this,e)||"0";this.bigIntValue=d(this,I,F).call(this,t)},P=new WeakSet,ye=function(...e){const t=e.map(r=>typeof r=="object"?r.decimal||S(r.decimalMultiplier):d(this,E,U).call(this,d(this,C,R).call(this,r))).filter(Boolean);return Math.max(...t,$)},I=new WeakSet,F=function(e,t){const r=t?A(t):this.decimalMultiplier,n=S(r),[a="",o=""]=e.split(".");return BigInt(`${a}${o.padEnd(n,"0")}`)},C=new WeakSet,R=function(e){const r=`${typeof e=="number"?Number(e).toLocaleString("fullwide",{useGrouping:!1,maximumFractionDigits:20}):H(e)}`.replaceAll(",",".").split(".");return r.length>1?`${r.slice(0,-1).join("")}.${r.at(-1)}`:r[0]},E=new WeakSet,U=function(e){var r;const t=((r=e.split(".")[1])==null?void 0:r.length)||0;return Math.max(t,$)};let T=z;function H(s){return typeof s=="object"?"getValue"in s?s.getValue("string"):s.value:s}const V=(s,e)=>typeof s=="bigint"?B({value:s,bigIntDecimal:e,decimal:e}):s;let W;const te=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:""}},re=async(s,e=0)=>{mt(s);const t=await ne(G(s)),r=V(e,t);return new _({decimal:t,value:r,identifier:s})};class _ extends T{constructor(t){super(t.value instanceof T?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=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.symbol.split("-")[0]:`${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 re(t,r)}static fromStringSync(t,r=0){const{isSynthetic:n}=G(t),{decimal:a,identifier:o}=te(t),c=V(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 re(t,r)}static fromIdentifierSync(t,r=0){const{decimal:n,identifier:a}=te(t),o=V(r,n);return new _({decimal:n,identifier:a,value:o})}static fromChainOrSignature(t,r=0){const{decimal:n,identifier:a}=ae(t),o=V(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");W=[a,...Object.values(o)].reduce((u,{tokens:l})=>(l.forEach(({identifier:h,chain:g,...w})=>{const x="decimals"in w?w.decimals:i.BaseDecimal[g];u.set(h,{identifier:h,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)}},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:ie({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 Y extends Error{constructor(e,t){console.error(t),super(e,{cause:{code:ft[e],message:e}}),Object.setPrototypeOf(this,Y.prototype)}}class f extends T{eq(e){return this.eqValue(e)}static fromBigInt(e,t){return new f({decimal:t,value:B({value:e,bigIntDecimal:t,decimal:t})})}}exports.AssetValue=_;exports.BigIntArithmetics=T;exports.RequestClient=ge;exports.SwapKitError=Y;exports.SwapKitNumber=f;exports.assetFromString=xe;exports.derivationPathToString=ze;exports.filterAssets=De;exports.formatBigIntToSafeValue=B;exports.gasFeeMultiplier=Pe;exports.getAssetType=oe;exports.getAsymmetricAssetShare=ue;exports.getAsymmetricAssetWithdrawAmount=He;exports.getAsymmetricRuneShare=ce;exports.getAsymmetricRuneWithdrawAmount=je;exports.getCommonAssetInfo=ae;exports.getDecimal=ne;exports.getEstimatedPoolShare=Fe;exports.getLiquiditySlippage=Ue;exports.getMemoFor=Ge;exports.getMinAmountByChain=pt;exports.getSymmetricPoolShare=le;exports.getSymmetricWithdraw=Le;exports.getTHORNameCost=Ke;exports.isGasAsset=ie;exports.validateTHORName=Ye;
package/dist/index.d.ts CHANGED
@@ -3,6 +3,7 @@ import type { CoinGeckoList } from '@swapkit/tokens';
3
3
  import { FeeOption } from '@swapkit/types';
4
4
  import type { MayaList } from '@swapkit/tokens';
5
5
  import { MemoType } from '@swapkit/types';
6
+ import type { Options } from 'ky';
6
7
  import type { PancakeswapETHList } from '@swapkit/tokens';
7
8
  import type { PancakeswapList } from '@swapkit/tokens';
8
9
  import type { PangolinList } from '@swapkit/tokens';
@@ -21,20 +22,6 @@ export declare const assetFromString: (assetString: string) => {
21
22
  };
22
23
 
23
24
  export declare class AssetValue extends BigIntArithmetics {
24
- static fromString(assetString: string, value?: number | string): Promise<AssetValue>;
25
- static fromStringSync(assetString: string, value?: number | string): AssetValue | undefined;
26
- static fromIdentifier(assetString: `${Chain}.${string}` | `${Chain}/${string}` | `${Chain}.${string}-${string}`, value?: number | string): Promise<AssetValue>;
27
- static fromIdentifierSync(identifier: TokenNames, value?: number | string): AssetValue;
28
- static fromChainOrSignature(assetString: CommonAssetString, value?: number | string): AssetValue;
29
- static fromTCQuote(identifier: TCTokenNames, value?: number | string): Promise<AssetValue>;
30
- static fromTCQuoteStatic(identifier: TCTokenNames, value?: number | string): AssetValue;
31
- static loadStaticAssets(): Promise<{
32
- ok: true;
33
- } | {
34
- ok: false;
35
- message: string;
36
- error: any;
37
- }>;
38
25
  address?: string;
39
26
  chain: Chain;
40
27
  isSynthetic: boolean;
@@ -44,11 +31,23 @@ export declare class AssetValue extends BigIntArithmetics {
44
31
  type: ReturnType<typeof getAssetType>;
45
32
  constructor(params: AssetValueParams);
46
33
  get assetValue(): string;
47
- toString(): string;
34
+ toString(short?: boolean): string;
48
35
  eq({ chain, symbol }: {
49
36
  chain: Chain;
50
37
  symbol: string;
51
38
  }): boolean;
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 loadStaticAssets(): Promise<{
45
+ ok: true;
46
+ } | {
47
+ ok: false;
48
+ message: string;
49
+ error: any;
50
+ }>;
52
51
  }
53
52
 
54
53
  declare type AssetValueParams = {
@@ -61,44 +60,51 @@ declare type AssetValueParams = {
61
60
  identifier: string;
62
61
  });
63
62
 
64
- declare class BigIntArithmetics {
63
+ export declare class BigIntArithmetics {
65
64
 
66
65
  decimalMultiplier: bigint;
67
66
  bigIntValue: bigint;
68
67
  decimal?: number;
69
68
  static fromBigInt(value: bigint, decimal?: number): BigIntArithmetics;
70
69
  static shiftDecimals({ value, from, to, }: {
71
- value: BigIntArithmetics | string | number;
70
+ value: InstanceType<typeof SwapKitNumber>;
72
71
  from: number;
73
72
  to: number;
74
73
  }): BigIntArithmetics;
75
- constructor(valueOrParams: BigIntArithmetics | string | number | {
76
- decimal?: number;
77
- value: number | string;
78
- });
79
- get unsafeNumber(): number;
74
+ constructor(params: SKBigIntParams);
75
+ /**
76
+ * @deprecated Use `getBaseValue('string')` instead
77
+ */
80
78
  get baseValue(): string;
79
+ /**
80
+ * @deprecated Use `getBaseValue('number')` instead
81
+ */
81
82
  get baseValueNumber(): number;
83
+ /**
84
+ * @deprecated Use `getBaseValue('bigint')` instead
85
+ */
82
86
  get baseValueBigInt(): bigint;
83
- get value(): string;
84
- add(...args: (BigIntArithmetics | string | number)[]): this;
85
- sub(...args: (BigIntArithmetics | string | number)[]): this;
86
- mul(...args: (BigIntArithmetics | string | number)[]): this;
87
- div(...args: (BigIntArithmetics | string | number)[]): this;
88
- gt(value: BigIntArithmetics | string | number): boolean;
89
- gte(value: BigIntArithmetics | string | number): boolean;
90
- lt(value: BigIntArithmetics | string | number): boolean;
91
- lte(value: BigIntArithmetics | string | number): boolean;
92
- eqValue(value: BigIntArithmetics | string | number): boolean;
93
- getBigIntValue(value: BigIntArithmetics | string | number, decimal?: number): bigint;
87
+ set(value: SKBigIntParams): this;
88
+ add(...args: InitialisationValueType[]): this;
89
+ sub(...args: InitialisationValueType[]): this;
90
+ mul(...args: InitialisationValueType[]): this;
91
+ div(...args: InitialisationValueType[]): this;
92
+ gt(value: InitialisationValueType): boolean;
93
+ gte(value: InitialisationValueType): boolean;
94
+ lt(value: InitialisationValueType): boolean;
95
+ lte(value: InitialisationValueType): boolean;
96
+ eqValue(value: InitialisationValueType): boolean;
97
+ getValue<T extends 'number' | 'string'>(type: T): NumberPrimitivesType[T];
98
+ getBaseValue<T extends 'number' | 'string' | 'bigint'>(type: T): NumberPrimitivesType[T];
99
+ getBigIntValue(value: InitialisationValueType, decimal?: number): bigint;
94
100
  formatBigIntToSafeValue(value: bigint, decimal?: number): string;
95
101
  toSignificant(significantDigits?: number): string;
102
+ toFixed(fixedDigits?: number): string;
103
+ toAbbreviation(digits?: number): string;
96
104
  }
97
105
 
98
106
  export declare type CommonAssetString = 'MAYA.MAYA' | 'ETH.THOR' | 'ETH.vTHOR' | Chain;
99
107
 
100
- export declare const DEFAULT_DECIMAL = 8;
101
-
102
108
  export declare const derivationPathToString: ([network, chainId, account, change, index]: number[]) => string;
103
109
 
104
110
  declare const errorMessages: {
@@ -159,18 +165,20 @@ declare const errorMessages: {
159
165
  readonly helpers_number_different_decimals: 99101;
160
166
  };
161
167
 
162
- export declare const formatBigIntToSafeValue: ({ value, bigIntDecimal, decimal, }: {
168
+ export declare const filterAssets: (assets: AssetValue[]) => AssetValue[];
169
+
170
+ export declare function formatBigIntToSafeValue({ value, bigIntDecimal, decimal, }: {
163
171
  value: bigint;
164
- bigIntDecimal?: number | undefined;
165
- decimal?: number | undefined;
166
- }) => string;
172
+ bigIntDecimal?: number;
173
+ decimal?: number;
174
+ }): string;
167
175
 
168
176
  export declare const gasFeeMultiplier: Record<FeeOption, number>;
169
177
 
170
178
  export declare const getAssetType: ({ chain, symbol }: {
171
179
  chain: Chain;
172
180
  symbol: string;
173
- }) => "KUJI" | "Synth" | "Native" | "GAIA" | "BEP2" | "BEP20" | "ERC20" | "AVAX" | "POLYGON" | "ARBITRUM" | "OPTIMISM";
181
+ }) => Chain.Avalanche | Chain.Cosmos | Chain.Kujira | "Synth" | "Native" | "BEP2" | "BEP20" | "ERC20" | "POLYGON" | "ARBITRUM" | "OPTIMISM";
174
182
 
175
183
  export declare const getAsymmetricAssetShare: ({ liquidityUnits, poolUnits, assetDepth, }: ShareParams<{
176
184
  assetDepth: string;
@@ -224,10 +232,6 @@ export declare const getMemoFor: <T extends MemoType>(memoType: T, options: Memo
224
232
 
225
233
  export declare const getMinAmountByChain: (chain: Chain) => AssetValue;
226
234
 
227
- export declare const getRequest: <T>(url: string, params?: {
228
- [x: string]: any;
229
- } | undefined) => Promise<T>;
230
-
231
235
  export declare const getSymmetricPoolShare: ({ liquidityUnits, poolUnits, runeDepth, assetDepth, }: ShareParams<{
232
236
  runeDepth: string;
233
237
  assetDepth: string;
@@ -246,6 +250,8 @@ export declare const getSymmetricWithdraw: ({ liquidityUnits, poolUnits, runeDep
246
250
 
247
251
  export declare const getTHORNameCost: (year: number) => number;
248
252
 
253
+ declare type InitialisationValueType = NumberPrimitives | BigIntArithmetics | SwapKitNumber;
254
+
249
255
  export declare const isGasAsset: ({ chain, symbol }: {
250
256
  chain: Chain;
251
257
  symbol: string;
@@ -282,6 +288,14 @@ export declare type MemoOptions<T extends MemoType> = {
282
288
  [MemoType.THORNAME_REGISTER]: Omit<ThornameRegisterParam, 'preferredAsset' | 'expiryBlock'>;
283
289
  }[T];
284
290
 
291
+ export declare type NumberPrimitives = bigint | number | string;
292
+
293
+ declare type NumberPrimitivesType = {
294
+ bigint: bigint;
295
+ number: number;
296
+ string: string;
297
+ };
298
+
285
299
  declare type PoolParams<T = {}> = T & {
286
300
  runeAmount: string;
287
301
  assetAmount: string;
@@ -289,23 +303,31 @@ declare type PoolParams<T = {}> = T & {
289
303
  assetDepth: string;
290
304
  };
291
305
 
292
- export declare const postRequest: <T>(url: string, body: string, headers?: Record<string, string>, parseAsString?: boolean) => Promise<T>;
306
+ export declare const RequestClient: {
307
+ get: <T>(url: string | URL | Request, options?: Options) => Promise<T>;
308
+ post: <T_1>(url: string | URL | Request, options?: Options) => Promise<T_1>;
309
+ };
293
310
 
294
311
  declare type ShareParams<T = {}> = T & {
295
312
  liquidityUnits: string;
296
313
  poolUnits: string;
297
314
  };
298
315
 
316
+ declare type SKBigIntParams = InitialisationValueType | {
317
+ decimal?: number;
318
+ value: number | string;
319
+ };
320
+
299
321
  export declare class SwapKitError extends Error {
300
322
  constructor(errorKey: Keys, sourceError?: any);
301
323
  }
302
324
 
303
325
  export declare class SwapKitNumber extends BigIntArithmetics {
304
326
  eq(value: SwapKitValueType): boolean;
305
- toString(): string;
327
+ static fromBigInt(value: bigint, decimal?: number): SwapKitNumber;
306
328
  }
307
329
 
308
- declare type SwapKitValueType = BigIntArithmetics | string | number;
330
+ export declare type SwapKitValueType = BigIntArithmetics | string | number;
309
331
 
310
332
  declare type TCTokenNames = (typeof ThorchainList)['tokens'][number]['identifier'];
311
333