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

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 ve=Object.getOwnPropertyDescriptor;var Se=Object.getOwnPropertyNames;var $e=Object.getPrototypeOf,Re=Object.prototype.hasOwnProperty;var Ie=(r,e,t)=>e in r?D(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t;var Be=(r,e,t,s)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of Se(e))!Re.call(r,n)&&n!==t&&D(r,n,{get:()=>e[n],enumerable:!(s=ve(e,n))||s.enumerable});return r};var Ee=(r,e,t)=>(t=r!=null?Te($e(r)):{},Be(e||!r||!r.__esModule?D(t,"default",{value:r,enumerable:!0}):t,r));var p=(r,e,t)=>(Ie(r,typeof e!="symbol"?e+"":e,t),t),Oe=(r,e,t)=>{if(!e.has(r))throw TypeError("Cannot "+t)};var y=(r,e,t)=>{if(e.has(r))throw TypeError("Cannot add the same private member more than once");e instanceof WeakSet?e.add(r):e.set(r,t)};var d=(r,e,t)=>(Oe(r,e,"access private method"),t);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const i=require("@swapkit/types"),Me="0x313ce567",re=async({chain:r,to:e})=>{try{const{result:t}=await ge.post(i.ChainToRPC[r],{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[r]}},Ve=async r=>{if(r===i.Chain.Ethereum)return i.BaseDecimal.ETH;const[,e]=r.split("-");return e!=null&&e.startsWith("0x")?re({chain:i.Chain.Ethereum,to:e}):i.BaseDecimal.ETH},qe=async r=>{const[,e]=r.split("-");return e!=null&&e.startsWith("0x")?re({chain:i.Chain.Avalanche,to:e.toLowerCase()}):i.BaseDecimal.AVAX},ke=async r=>(r===i.Chain.BinanceSmartChain,i.BaseDecimal.BSC),ne=async({chain:r,symbol:e})=>{switch(r){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[r]}},Pe={[i.FeeOption.Average]:1.2,[i.FeeOption.Fast]:1.5,[i.FeeOption.Fastest]:2},ie=({chain:r,symbol:e})=>{switch(r){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===r;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=r=>{switch(r){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[r]};case i.Chain.THORChain:return{identifier:"THOR.RUNE",decimal:i.BaseDecimal[r]};case i.Chain.BinanceSmartChain:return{identifier:"BSC.BNB",decimal:i.BaseDecimal[r]};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:`${r}.${r}`,decimal:i.BaseDecimal[r]}}},oe=({chain:r,symbol:e})=>{if(e.includes("/"))return"Synth";switch(r){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=r=>{var c;const[e,...t]=r.split("."),s=r.includes("/"),n=t.join("."),a=(c=n==null?void 0:n.split("-"))==null?void 0:c[0];return{chain:e,symbol:n,ticker:a,synth:s}},Ne=new RegExp(/(.)\1{6}|\.ORG|\.NET|\.FINANCE|\.COM|WWW|HTTP|\\\\|\/\/|[\s$%:[\]]/,"gmi"),De=r=>r.filter(e=>!Ne.test(e.toString())&&!e.toString().includes("undefined")),ce=({liquidityUnits:r,poolUnits:e,runeDepth:t})=>{const s=m(r),n=m(e),a=m(t),c=s.mul(a),o=n.mul(n).mul(2),u=n.mul(s).mul(2),l=s.mul(s),h=n.mul(n).mul(n);return c.mul(o.sub(u).add(l)).div(h)},ue=({liquidityUnits:r,poolUnits:e,assetDepth:t})=>{const s=m(r),n=m(e),a=m(t),c=s.mul(a),o=n.mul(n).mul(2),u=n.mul(s).mul(2),l=s.mul(s),h=c.mul(o.sub(u).add(l)),g=n.mul(n).mul(n);return h.div(g)},je=({percent:r,runeDepth:e,liquidityUnits:t,poolUnits:s})=>ce({runeDepth:e,liquidityUnits:t,poolUnits:s}).mul(r),He=({percent:r,assetDepth:e,liquidityUnits:t,poolUnits:s})=>ue({assetDepth:e,liquidityUnits:t,poolUnits:s}).mul(r),m=r=>f.fromBigInt(BigInt(r),i.BaseDecimal.THOR),le=({liquidityUnits:r,poolUnits:e,runeDepth:t,assetDepth:s})=>({assetAmount:m(s).mul(r).div(e),runeAmount:m(t).mul(r).div(e)}),Le=({liquidityUnits:r,poolUnits:e,runeDepth:t,assetDepth:s,percent:n})=>Object.fromEntries(Object.entries(le({liquidityUnits:r,poolUnits:e,runeDepth:t,assetDepth:s})).map(([a,c])=>[a,c.mul(n)])),Fe=({runeDepth:r,poolUnits:e,assetDepth:t,liquidityUnits:s,runeAmount:n,assetAmount:a})=>{const c=new f({value:r,decimal:8}),o=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(o),w=h.mul(c),x=l.mul(h),be=c.mul(o),Ce=u.mul(g.add(w.add(x.mul(2)))),we=g.add(w.add(be.mul(2))),J=Ce.div(we),N=m(s).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:r,assetAmount:e,runeDepth:t,assetDepth:s})=>{if(r==="0"||e==="0"||t==="0"||s==="0")return 0;const n=m(t),a=m(s),c=m(e),o=m(r),u=c.mul(n).sub(a.mul(o)),l=a.mul(o).add(n.mul(a));return Math.abs(u.div(l).getBaseValue("number"))},We=({symbol:r,ticker:e,chain:t})=>t==="ETH"&&e!=="ETH"?`${e}-${r.slice(-3)}`:r,Ge=(r,e)=>{switch(r){case i.MemoType.LEAVE:case i.MemoType.BOND:{const{address:t}=e;return`${r}:${t}`}case i.MemoType.UNBOND:{const{address:t,unbondAmount:s}=e;return`${r}:${t}:${s*10**8}`}case i.MemoType.THORNAME_REGISTER:{const{name:t,chain:s,address:n,owner:a}=e;return`${r}:${t}:${s}:${n}${a?`:${a}`:""}`}case i.MemoType.DEPOSIT:{const{chain:t,symbol:s,address:n,singleSide:a}=e;return a?`${r}:${t}/${s}::t:0`:`${r}:${t}.${s}:${n||""}:t:0`}case i.MemoType.WITHDRAW:{const{chain:t,ticker:s,symbol:n,basisPoints:a,targetAssetString:c,singleSide:o}=e,u=!o&&c?`:${c}`:"",l=We({chain:t,symbol:n,ticker:s});return`${r}:${t}${o?"/":"."}${l}:${a}${u}`}case i.MemoType.OPEN_LOAN:case i.MemoType.CLOSE_LOAN:{const{asset:t,address:s}=e;return`${r}:${t}:${s}`}default:return""}},Ke=r=>{if(r<0)throw new Error("Invalid number of year");return 10+r},Ye=r=>{if(r.length>30)return!1;const e=/^[a-zA-Z0-9+_-]+$/g;return!!r.match(e)},ze=([r,e,t,s,n])=>`${r}'/${e}'/${t}'/${s}${typeof n!="number"?"":`/${n}`}`;class Q extends Error{constructor(e,t,s){const n=e.status||e.status===0?e.status:"",a=e.statusText||"",c=`${n} ${a}`.trim(),o=c?`status code ${c}`:"an unknown error";super(`Request failed with ${o}`),Object.defineProperty(this,"response",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"request",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"options",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.name="HTTPError",this.response=e,this.request=t,this.options=s}}class he extends Error{constructor(e){super("Request timed out"),Object.defineProperty(this,"request",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.name="TimeoutError",this.request=e}}const M=r=>r!==null&&typeof r=="object",O=(...r)=>{for(const e of r)if((!M(e)||Array.isArray(e))&&e!==void 0)throw new TypeError("The `options` argument must be an object");return K({},...r)},de=(r={},e={})=>{const t=new globalThis.Headers(r),s=e instanceof globalThis.Headers,n=new globalThis.Headers(e);for(const[a,c]of n.entries())s&&c==="undefined"||c===void 0?t.delete(a):t.set(a,c);return t},K=(...r)=>{let e={},t={};for(const s of r)if(Array.isArray(s))Array.isArray(e)||(e=[]),e=[...e,...s];else if(M(s)){for(let[n,a]of Object.entries(s))M(a)&&n in e&&(a=K(e[n],a)),e={...e,[n]:a};M(s.headers)&&(t=de(t,s.headers),e.headers=t)}return e},Je=(()=>{let r=!1,e=!1;const t=typeof globalThis.ReadableStream=="function",s=typeof globalThis.Request=="function";return t&&s&&(e=new globalThis.Request("https://empty.invalid",{body:new globalThis.ReadableStream,method:"POST",get duplex(){return r=!0,"half"}}).headers.has("Content-Type")),r&&!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},st={method:!0,headers:!0,body:!0,mode:!0,credentials:!0,cache:!0,redirect:!0,referrer:!0,referrerPolicy:!0,integrity:!0,keepalive:!0,signal:!0,window:!0,dispatcher:!0,duplex:!0},rt=r=>me.includes(r)?r.toUpperCase():r,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:r=>.3*2**(r-1)*1e3},at=(r={})=>{if(typeof r=="number")return{...X,limit:r};if(r.methods&&!Array.isArray(r.methods))throw new Error("retry.methods must be an array");if(r.statusCodes&&!Array.isArray(r.statusCodes))throw new Error("retry.statusCodes must be an array");return{...X,...r,afterStatusCodes:fe}};async function ot(r,e,t,s){return new Promise((n,a)=>{const c=setTimeout(()=>{t&&t.abort(),a(new he(r))},s.timeout);s.fetch(r,e).then(n).catch(a).then(()=>{clearTimeout(c)})})}async function ct(r,{signal:e}){return new Promise((t,s)=>{e&&(e.throwIfAborted(),e.addEventListener("abort",n,{once:!0}));function n(){clearTimeout(a),s(e.reason)}const a=setTimeout(()=>{e==null||e.removeEventListener("abort",n),t()},r)})}const ut=(r,e)=>{const t={};for(const s in e)!(s in st)&&!(s in tt)&&!(s in r)&&(t[s]=e[s]);return t};class q{static create(e,t){const s=new q(e,t),n=async()=>{if(typeof s._options.timeout=="number"&&s._options.timeout>j)throw new RangeError(`The \`timeout\` option cannot be greater than ${j}`);await Promise.resolve();let o=await s._fetch();for(const u of s._options.hooks.afterResponse){const l=await u(s.request,s._options,s._decorateResponse(o.clone()));l instanceof globalThis.Response&&(o=l)}if(s._decorateResponse(o),!o.ok&&s._options.throwHttpErrors){let u=new Q(o,s.request,s._options);for(const l of s._options.hooks.beforeError)u=await l(u);throw u}if(s._options.onDownloadProgress){if(typeof s._options.onDownloadProgress!="function")throw new TypeError("The `onDownloadProgress` option must be a function");if(!Xe)throw new Error("Streams are not supported in your environment. `ReadableStream` is missing.");return s._stream(o.clone(),s._options.onDownloadProgress)}return o},c=s._options.retry.methods.includes(s.request.method.toLowerCase())?s._retry(n):n();for(const[o,u]of Object.entries(et))c[o]=async()=>{s.request.headers.set("accept",s.request.headers.get("accept")||u);const h=(await c).clone();if(o==="json"){if(h.status===204||(await h.clone().arrayBuffer()).byteLength===0)return"";if(t.parseJson)return t.parseJson(await h.text())}return h[o]()};return c}constructor(e,t={}){if(Object.defineProperty(this,"request",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"abortController",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_retryCount",{enumerable:!0,configurable:!0,writable:!0,value:0}),Object.defineProperty(this,"_input",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_options",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this._input=e,this._options={credentials:this._input.credentials||"same-origin",...t,headers:de(this._input.headers,t.headers),hooks:K({beforeRequest:[],beforeRetry:[],beforeError:[],afterResponse:[]},t.hooks),method:rt(t.method??this._input.method),prefixUrl:String(t.prefixUrl||""),retry:at(t.retry),throwHttpErrors:t.throwHttpErrors!==!1,timeout:t.timeout??1e4,fetch:t.fetch??globalThis.fetch.bind(globalThis)},typeof this._input!="string"&&!(this._input instanceof URL||this._input instanceof globalThis.Request))throw new TypeError("`input` must be a string, URL, or Request");if(this._options.prefixUrl&&typeof this._input=="string"){if(this._input.startsWith("/"))throw new Error("`input` must not begin with a slash when using `prefixUrl`");this._options.prefixUrl.endsWith("/")||(this._options.prefixUrl+="/"),this._input=this._options.prefixUrl+this._input}if(Qe){if(this.abortController=new globalThis.AbortController,this._options.signal){const s=this._options.signal;this._options.signal.addEventListener("abort",()=>{this.abortController.abort(s.reason)})}this._options.signal=this.abortController.signal}if(Je&&(this._options.duplex="half"),this.request=new globalThis.Request(this._input,this._options),this._options.searchParams){const 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 s=e.response.headers.get("Retry-After");if(s&&this._options.retry.afterStatusCodes.includes(e.response.status)){let n=Number(s);return Number.isNaN(n)?n=Date.parse(s)-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 s=Math.min(this._calculateRetryDelay(t),j);if(s!==0&&this._retryCount>0){await ct(s,{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 s=await t(this.request,this._options);if(s instanceof Request){this.request=s;break}if(s instanceof Response)return s}const e=ut(this.request,this._options);return this._options.timeout===!1?this._options.fetch(this.request.clone(),e):ot(this.request.clone(),e,this.abortController,this._options)}_stream(e,t){const s=Number(e.headers.get("content-length"))||0;let n=0;return e.status===204?(t&&t({percent:1,totalBytes:s,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 c=e.body.getReader();t&&t({percent:0,transferredBytes:0,totalBytes:s},new Uint8Array);async function o(){const{done:u,value:l}=await c.read();if(u){a.close();return}if(t){n+=l.byteLength;const h=s===0?0:n/s;t({percent:h,transferredBytes:n,totalBytes:s},l)}a.enqueue(l),await o()}await o()}}),{status:e.status,statusText:e.statusText,headers:e.headers})}}/*! MIT License © Sindre Sorhus */const L=r=>{const e=(t,s)=>q.create(t,O(r,s));for(const t of me)e[t]=(s,n)=>q.create(s,O(r,n,{method:t}));return e.create=t=>L(O(t)),e.extend=t=>L(O(r,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:(r,e)=>Z.get(r,e).json(),post:(r,e)=>Z.post(r,e).json()},ee=Object.values(i.Chain),mt=(r="")=>{const e=r.toUpperCase(),[t]=e.split(".");if(ee.includes(t))return!0;const[s]=e.split("/");if(ee.includes(s))return!0;throw new Error(`Invalid identifier: ${r}. Expected format: <Chain>.<Ticker> or <Chain>.<Ticker>-<ContractAddress>`)},R=8,A=r=>10n**BigInt(r),v=r=>Math.log10(parseFloat(r.toString()));function I({value:r,bigIntDecimal:e=R,decimal:t=R}){const s=r<0n;let n=r.toString().substring(s?1:0);const a=t-(n.length-1);a>0&&(n="0".repeat(a)+n);const c=n.length-t;let o=n.slice(-t);return parseInt(o[e])>=5?o=`${o.substring(0,e-1)}${(parseInt(o[e-1])+1).toString()}`:o=o.substring(0,e),`${s?"-":""}${n.slice(0,c)}.${o}`.replace(/\.?0*$/,"")}var b,S,k,_e,P,ye,B,F,C,$,E,U;const z=class z{constructor(e){y(this,b);y(this,k);y(this,P);y(this,B);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,$).call(this,t)),this.decimal||0)),d(this,k,_e).call(this,t)}static fromBigInt(e,t){return new z({decimal:t,value:I({value:e,bigIntDecimal:t,decimal:t})})}static shiftDecimals({value:e,from:t,to:s}){return this.fromBigInt(e.getBaseValue("bigint")*A(s)/A(t),s)}set(e){return new this.constructor({decimal:this.decimal,value:e,identifier:this.toString()})}add(...e){return d(this,b,S).call(this,"add",...e)}sub(...e){return d(this,b,S).call(this,"sub",...e)}mul(...e){return d(this,b,S).call(this,"mul",...e)}div(...e){return d(this,b,S).call(this,"div",...e)}gt(e){return this.bigIntValue>this.getBigIntValue(e)}gte(e){return this.bigIntValue>=this.getBigIntValue(e)}lt(e){return this.bigIntValue<this.getBigIntValue(e)}lte(e){return this.bigIntValue<=this.getBigIntValue(e)}eqValue(e){return this.bigIntValue===this.getBigIntValue(e)}getValue(e){const t=this.formatBigIntToSafeValue(this.bigIntValue,this.decimal||v(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),s=this.bigIntValue/t;switch(e){case"number":return Number(s);case"string":return s.toString();default:return s}}getBigIntValue(e,t){if(!t&&typeof e=="object")return e.bigIntValue;const s=H(e),n=d(this,C,$).call(this,s);return n==="0"||n==="undefined"?0n:d(this,B,F).call(this,n,t)}formatBigIntToSafeValue(e,t){const s=t||this.decimal||R,n=Math.max(s,v(this.decimalMultiplier)),a=e<0n,c=e.toString().substring(a?1:0),o=n-(c.length-1),u=o>0?"0".repeat(o)+c:c,l=u.length-n;let h=u.slice(-n);return parseInt(h[s])>=5?h=`${h.substring(0,s-1)}${(parseInt(h[s-1])+1).toString()}`:h=h.substring(0,s),`${a?"-":""}${u.slice(0,l)}.${h}`.replace(/\.?0*$/,"")}toSignificant(e=6){const[t,s]=this.getValue("string").split("."),n=t||"",a=s||"";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 o=parseInt(a),u=`${o}`.slice(0,e);return`0.${u.padStart(a.length-`${o}`.length+u.length,"0")}`}toFixed(e=6){const[t,s]=this.getValue("string").split("."),n=t||"",a=s||"";if(parseInt(n))return`${n}.${a.slice(0,e)}`.padEnd(e,"0");const c=parseInt(a),o=`${c}`.slice(0,e);return`0.${o.padStart(a.length-`${c}`.length+o.length,"0")}`}toAbbreviation(e=2){const t=this.getValue("number"),s=["","K","M","B","T","Q","Qi","S"],n=Math.floor(Math.log10(Math.abs(t))/3),a=s[n];if(!a)return this.getValue("string");const c=10**(n*3);return`${(t/c).toFixed(e)}${a}`}toCurrency(e="$",{currencyPosition:t="start",decimal:s=2,decimalSeparator:n=".",thousandSeparator:a=","}={}){const c=this.getValue("number"),[o,u=""]=c.toFixed(6).split("."),l=o.replace(/\B(?=(\d{3})+(?!\d))/g,a),h=!o&&!u?"0.00":o==="0"?`${parseFloat(`0.${u}`)}`.replace(".",n):`${l}${u?`${n}${u.slice(0,s)}`:""}`;return`${t==="start"?e:""}${h}${t==="end"?e:""}`}};b=new WeakSet,S=function(e,...t){const s=d(this,P,ye).call(this,this,...t),n=A(s),a=t.reduce((o,u)=>{const l=this.getBigIntValue(u,s);switch(e){case"add":return o+l;case"sub":return o-l;case"mul":return o*l/n;case"div":{if(l===0n)throw new RangeError("Division by zero");return o*n/l}default:return o}},this.bigIntValue*n/this.decimalMultiplier),c=I({bigIntDecimal:s,decimal:Math.max(s,v(this.decimalMultiplier)),value:a});return new this.constructor({decimal:this.decimal,value:c,identifier:this.toString()})},k=new WeakSet,_e=function(e){const t=d(this,C,$).call(this,e)||"0";this.bigIntValue=d(this,B,F).call(this,t)},P=new WeakSet,ye=function(...e){const t=e.map(s=>typeof s=="object"?s.decimal||v(s.decimalMultiplier):d(this,E,U).call(this,d(this,C,$).call(this,s))).filter(Boolean);return Math.max(...t,R)},B=new WeakSet,F=function(e,t){const s=t?A(t):this.decimalMultiplier,n=v(s),[a="",c=""]=e.split(".");return BigInt(`${a}${c.padEnd(n,"0")}`)},C=new WeakSet,$=function(e){const s=`${typeof e=="number"?Number(e).toLocaleString("fullwide",{useGrouping:!1,maximumFractionDigits:20}):H(e)}`.replaceAll(",",".").split(".");return s.length>1?`${s.slice(0,-1).join("")}.${s.at(-1)}`:s[0]},E=new WeakSet,U=function(e){var s;const t=((s=e.split(".")[1])==null?void 0:s.length)||0;return Math.max(t,R)};let T=z;function H(r){return typeof r=="object"?"getValue"in r?r.getValue("string"):r.value:r}const V=(r,e)=>typeof r=="bigint"?I({value:r,bigIntDecimal:e,decimal:e}):r;let W;const te=r=>{if(!W)throw new Error("Static assets not loaded, call await AssetValue.loadStaticAssets() first");return W.get(r.toUpperCase())||{decimal:i.BaseDecimal.THOR,identifier:""}},se=async(r,e=0)=>{mt(r);const t=await ne(G(r)),s=V(e,t);return new _({decimal:t,value:s,identifier:r})};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 s="identifier"in t?t.identifier:`${t.chain}.${t.symbol}`,n=G(s);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 s=this.isSynthetic?this.symbol.split("-")[0]:`${this.chain}.${this.ticker}`;return t?s:`${this.chain}.${this.symbol}`}eq({chain:t,symbol:s}){return this.chain===t&&this.symbol===s}static async fromString(t,s=0){return se(t,s)}static fromStringSync(t,s=0){const{isSynthetic:n}=G(t),{decimal:a,identifier:c}=te(t),o=V(s,a);return c?new _({decimal:a,identifier:c,value:o}):n?new _({decimal:8,identifier:t,value:o}):void 0}static async fromIdentifier(t,s=0){return se(t,s)}static fromIdentifierSync(t,s=0){const{decimal:n,identifier:a}=te(t),c=V(s,n);return new _({decimal:n,identifier:a,value:c})}static fromChainOrSignature(t,s=0){const{decimal:n,identifier:a}=ae(t),c=V(s,n);return new _({value:c,decimal:n,identifier:a})}static async loadStaticAssets(){return new Promise(async(t,s)=>{try{const{ThorchainList:n,NativeList:a,...c}=await import("@swapkit/tokens");W=[a,...Object.values(c)].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),s({ok:!1,error:n,message:"Couldn't load static assets. Ensure you have installed @swapkit/tokens package"})}})}}const pt=r=>{const e=_.fromChainOrSignature(r);switch(r){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=r=>{const e=r.slice(0,14).includes("/"),[t,s]=r.split(".").pop().split("/"),n=r.includes(".")&&!e?r:`${i.Chain.THORChain}.${s}`,[a,c]=n.split("."),[o,u]=(e?s:c).split("-");return{address:u==null?void 0:u.toLowerCase(),chain:a,isGasAsset:ie({chain:a,symbol:c}),isSynthetic:e,symbol:(e?`${t}/`:"")+(u?`${o}-${(u==null?void 0:u.toLowerCase())??""}`:c),ticker:o}},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:I({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=I;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,45 @@ 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;
80
- get baseValue(): string;
81
- get baseValueNumber(): number;
82
- 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;
74
+ constructor(params: SKBigIntParams);
75
+ set(value: SKBigIntParams): this;
76
+ add(...args: InitialisationValueType[]): this;
77
+ sub(...args: InitialisationValueType[]): this;
78
+ mul(...args: InitialisationValueType[]): this;
79
+ div(...args: InitialisationValueType[]): this;
80
+ gt(value: InitialisationValueType): boolean;
81
+ gte(value: InitialisationValueType): boolean;
82
+ lt(value: InitialisationValueType): boolean;
83
+ lte(value: InitialisationValueType): boolean;
84
+ eqValue(value: InitialisationValueType): boolean;
85
+ getValue<T extends 'number' | 'string'>(type: T): NumberPrimitivesType[T];
86
+ getBaseValue<T extends 'number' | 'string' | 'bigint'>(type: T): NumberPrimitivesType[T];
87
+ getBigIntValue(value: InitialisationValueType, decimal?: number): bigint;
94
88
  formatBigIntToSafeValue(value: bigint, decimal?: number): string;
95
89
  toSignificant(significantDigits?: number): string;
90
+ toFixed(fixedDigits?: number): string;
91
+ toAbbreviation(digits?: number): string;
92
+ toCurrency(currency?: string, { currencyPosition, decimal, decimalSeparator, thousandSeparator, }?: {
93
+ currencyPosition?: string | undefined;
94
+ decimal?: number | undefined;
95
+ decimalSeparator?: string | undefined;
96
+ thousandSeparator?: string | undefined;
97
+ }): string;
96
98
  }
97
99
 
98
100
  export declare type CommonAssetString = 'MAYA.MAYA' | 'ETH.THOR' | 'ETH.vTHOR' | Chain;
99
101
 
100
- export declare const DEFAULT_DECIMAL = 8;
101
-
102
102
  export declare const derivationPathToString: ([network, chainId, account, change, index]: number[]) => string;
103
103
 
104
104
  declare const errorMessages: {
@@ -159,18 +159,20 @@ declare const errorMessages: {
159
159
  readonly helpers_number_different_decimals: 99101;
160
160
  };
161
161
 
162
- export declare const formatBigIntToSafeValue: ({ value, bigIntDecimal, decimal, }: {
162
+ export declare const filterAssets: (assets: AssetValue[]) => AssetValue[];
163
+
164
+ export declare function formatBigIntToSafeValue({ value, bigIntDecimal, decimal, }: {
163
165
  value: bigint;
164
- bigIntDecimal?: number | undefined;
165
- decimal?: number | undefined;
166
- }) => string;
166
+ bigIntDecimal?: number;
167
+ decimal?: number;
168
+ }): string;
167
169
 
168
170
  export declare const gasFeeMultiplier: Record<FeeOption, number>;
169
171
 
170
172
  export declare const getAssetType: ({ chain, symbol }: {
171
173
  chain: Chain;
172
174
  symbol: string;
173
- }) => "KUJI" | "Synth" | "Native" | "GAIA" | "BEP2" | "BEP20" | "ERC20" | "AVAX" | "POLYGON" | "ARBITRUM" | "OPTIMISM";
175
+ }) => Chain.Avalanche | Chain.Cosmos | Chain.Kujira | "Synth" | "Native" | "BEP2" | "BEP20" | "ERC20" | "POLYGON" | "ARBITRUM" | "OPTIMISM";
174
176
 
175
177
  export declare const getAsymmetricAssetShare: ({ liquidityUnits, poolUnits, assetDepth, }: ShareParams<{
176
178
  assetDepth: string;
@@ -224,10 +226,6 @@ export declare const getMemoFor: <T extends MemoType>(memoType: T, options: Memo
224
226
 
225
227
  export declare const getMinAmountByChain: (chain: Chain) => AssetValue;
226
228
 
227
- export declare const getRequest: <T>(url: string, params?: {
228
- [x: string]: any;
229
- } | undefined) => Promise<T>;
230
-
231
229
  export declare const getSymmetricPoolShare: ({ liquidityUnits, poolUnits, runeDepth, assetDepth, }: ShareParams<{
232
230
  runeDepth: string;
233
231
  assetDepth: string;
@@ -246,6 +244,8 @@ export declare const getSymmetricWithdraw: ({ liquidityUnits, poolUnits, runeDep
246
244
 
247
245
  export declare const getTHORNameCost: (year: number) => number;
248
246
 
247
+ declare type InitialisationValueType = NumberPrimitives | BigIntArithmetics | SwapKitNumber;
248
+
249
249
  export declare const isGasAsset: ({ chain, symbol }: {
250
250
  chain: Chain;
251
251
  symbol: string;
@@ -282,6 +282,14 @@ export declare type MemoOptions<T extends MemoType> = {
282
282
  [MemoType.THORNAME_REGISTER]: Omit<ThornameRegisterParam, 'preferredAsset' | 'expiryBlock'>;
283
283
  }[T];
284
284
 
285
+ export declare type NumberPrimitives = bigint | number | string;
286
+
287
+ declare type NumberPrimitivesType = {
288
+ bigint: bigint;
289
+ number: number;
290
+ string: string;
291
+ };
292
+
285
293
  declare type PoolParams<T = {}> = T & {
286
294
  runeAmount: string;
287
295
  assetAmount: string;
@@ -289,23 +297,31 @@ declare type PoolParams<T = {}> = T & {
289
297
  assetDepth: string;
290
298
  };
291
299
 
292
- export declare const postRequest: <T>(url: string, body: string, headers?: Record<string, string>, parseAsString?: boolean) => Promise<T>;
300
+ export declare const RequestClient: {
301
+ get: <T>(url: string | URL | Request, options?: Options) => Promise<T>;
302
+ post: <T_1>(url: string | URL | Request, options?: Options) => Promise<T_1>;
303
+ };
293
304
 
294
305
  declare type ShareParams<T = {}> = T & {
295
306
  liquidityUnits: string;
296
307
  poolUnits: string;
297
308
  };
298
309
 
310
+ declare type SKBigIntParams = InitialisationValueType | {
311
+ decimal?: number;
312
+ value: number | string;
313
+ };
314
+
299
315
  export declare class SwapKitError extends Error {
300
316
  constructor(errorKey: Keys, sourceError?: any);
301
317
  }
302
318
 
303
319
  export declare class SwapKitNumber extends BigIntArithmetics {
304
320
  eq(value: SwapKitValueType): boolean;
305
- toString(): string;
321
+ static fromBigInt(value: bigint, decimal?: number): SwapKitNumber;
306
322
  }
307
323
 
308
- declare type SwapKitValueType = BigIntArithmetics | string | number;
324
+ export declare type SwapKitValueType = BigIntArithmetics | string | number;
309
325
 
310
326
  declare type TCTokenNames = (typeof ThorchainList)['tokens'][number]['identifier'];
311
327