@pooltogether/utilities
Advanced tools
Comparing version 0.5.2-beta.2 to 0.6.0
@@ -7,3 +7,2 @@ export * from './address'; | ||
export * from './pods'; | ||
export * from './providers'; | ||
export * from './math'; | ||
@@ -10,0 +9,0 @@ export * from './time'; |
@@ -8,5 +8,2 @@ 'use strict'; | ||
var units = require('@ethersproject/units'); | ||
var providers = require('@ethersproject/providers'); | ||
var networks = require('@ethersproject/networks'); | ||
var evmChainsExtended = require('@pooltogether/evm-chains-extended'); | ||
@@ -665,133 +662,3 @@ var expression = /^(\w{6})\w*(\w{4})$/; | ||
var ALCHEMY_CHAIN_IDS = /*#__PURE__*/Object.freeze([// Ethereum | ||
1, 3, 4, 5, 42, // Polygon | ||
137, 80001, // Optimism | ||
10, 420, // Arbitrum | ||
42161, 421613]); | ||
var ETHERSCAN_CHAIN_IDS = /*#__PURE__*/Object.freeze([// Ethereum | ||
1, 3, 4, 5, 42]); | ||
var INFURA_CHAIN_IDS = /*#__PURE__*/Object.freeze([// Ethereum | ||
1, 3, 4, 5, // Polygon | ||
137, 80001, // Optimism | ||
10, 420, // Arbitrum | ||
42161, 421613]); | ||
var API_KEYS = { | ||
alchemy: undefined, | ||
etherscan: undefined, | ||
infura: undefined | ||
}; | ||
/** | ||
* Initializes the store of API keys for different providers. | ||
* @param apiKeys | ||
*/ | ||
var initProviderApiKeys = function initProviderApiKeys(apiKeys) { | ||
API_KEYS.alchemy = apiKeys.alchemy; | ||
API_KEYS.etherscan = apiKeys.etherscan; | ||
API_KEYS.infura = apiKeys.infura; | ||
}; | ||
/** | ||
* Creates a provider for the given chain id if available. | ||
* Attempts to use any initialized api keys for RPC providers first. | ||
* @param chainId | ||
* @returns | ||
*/ | ||
var getReadProvider = function getReadProvider(chainId) { | ||
var chainData = evmChainsExtended.getChain(chainId); | ||
var provider; | ||
try { | ||
if (API_KEYS.alchemy && ALCHEMY_CHAIN_IDS.includes(chainId)) { | ||
provider = new providers.AlchemyProvider(chainId, API_KEYS.alchemy); | ||
} else if (API_KEYS.infura && INFURA_CHAIN_IDS.includes(chainId)) { | ||
provider = new providers.InfuraProvider(chainId, API_KEYS.infura); | ||
} else if (API_KEYS.etherscan && ETHERSCAN_CHAIN_IDS.includes(chainId)) { | ||
provider = new providers.EtherscanProvider(chainId, API_KEYS.etherscan); | ||
} else if (!!chainData && !!chainData.rpc[0]) { | ||
provider = new providers.JsonRpcProvider(chainData.rpc[0], chainId); | ||
} else { | ||
console.warn("Chain id " + chainId + " not supported."); | ||
} | ||
} catch (e) { | ||
console.error(e); | ||
} | ||
return provider; | ||
}; | ||
/** | ||
* Creates several providers for the given chain ids if available. | ||
* Attempts to use any initialized api keys for RPC providers first. | ||
* @param chainIds | ||
* @returns an object of providers keyed by chain id | ||
*/ | ||
var getReadProviders = function getReadProviders(chainIds) { | ||
var readProviders = {}; | ||
chainIds.forEach(function (chainId) { | ||
var provider = getReadProvider(chainId); | ||
if (provider) { | ||
readProviders[chainId] = provider; | ||
} | ||
}); | ||
return readProviders; | ||
}; | ||
/** | ||
* Returns an RPC URL using configured API keys if possible. | ||
* @param chainId | ||
*/ | ||
var getRpcUrl = function getRpcUrl(chainId, apiKeys) { | ||
var alchemyApiKey = API_KEYS.alchemy || (apiKeys == null ? void 0 : apiKeys.alchemy); | ||
var infuraApiKey = API_KEYS.infura || (apiKeys == null ? void 0 : apiKeys.infura); | ||
try { | ||
var _chainData$rpc; | ||
if (!!alchemyApiKey && ALCHEMY_CHAIN_IDS.includes(chainId)) { | ||
var connectionInfo = providers.AlchemyProvider.getUrl(networks.getNetwork(chainId), alchemyApiKey); | ||
return connectionInfo.url; | ||
} else if (!!infuraApiKey && INFURA_CHAIN_IDS.includes(chainId)) { | ||
var _connectionInfo = providers.InfuraProvider.getUrl(networks.getNetwork(chainId), typeof infuraApiKey === 'string' ? { | ||
projectId: infuraApiKey | ||
} : infuraApiKey); | ||
return _connectionInfo.url; | ||
} | ||
var chainData = evmChainsExtended.getChain(chainId); | ||
var rpcUrl = chainData == null ? void 0 : (_chainData$rpc = chainData.rpc) == null ? void 0 : _chainData$rpc[0]; | ||
if (!!rpcUrl) { | ||
return rpcUrl; | ||
} else { | ||
console.warn("getRpcUrl | Chain id " + chainId + " not supported."); | ||
var _chainData = evmChainsExtended.getChain(NETWORK.mainnet); | ||
return _chainData.rpc[0]; | ||
} | ||
} catch (e) { | ||
console.error(e); | ||
var _chainData2 = evmChainsExtended.getChain(NETWORK.mainnet); | ||
return _chainData2.rpc[0]; | ||
} | ||
}; | ||
/** | ||
* Returns multiple RPC URLS using configured API keys if possible. | ||
* @param chainIds | ||
* @returns | ||
*/ | ||
var getRpcUrls = function getRpcUrls(chainIds, apiKeys) { | ||
return chainIds.reduce(function (rpcUrls, chainId) { | ||
rpcUrls[chainId] = getRpcUrl(chainId, apiKeys); | ||
return rpcUrls; | ||
}, {}); | ||
}; | ||
/** | ||
* Breaks down a number of seconds into years, months, days, hours, minutes, seconds | ||
@@ -1125,6 +992,2 @@ * @param totalSeconds | ||
exports.getPrizePoolSymbol = getPrizePoolSymbol; | ||
exports.getReadProvider = getReadProvider; | ||
exports.getReadProviders = getReadProviders; | ||
exports.getRpcUrl = getRpcUrl; | ||
exports.getRpcUrls = getRpcUrls; | ||
exports.getSecondsRemainingInPrizePeriod = getSecondsRemainingInPrizePeriod; | ||
@@ -1134,3 +997,2 @@ exports.getSecondsSinceEpoch = getSecondsSinceEpoch; | ||
exports.getTokenColour = getTokenColour; | ||
exports.initProviderApiKeys = initProviderApiKeys; | ||
exports.msToD = msToD; | ||
@@ -1137,0 +999,0 @@ exports.msToS = msToS; |
@@ -1,2 +0,2 @@ | ||
"use strict";Object.defineProperty(exports,"__esModule",{value:!0});var e=require("ethers"),r=require("ethers/lib/utils"),t=require("@ethersproject/units"),n=require("@ethersproject/providers"),o=require("@ethersproject/networks"),i=require("@pooltogether/evm-chains-extended"),s=/^(\w{6})\w*(\w{4})$/;function u(e,r){void 0===r&&(r={precision:2});var t=r.precision;if(e&&"function"==typeof e.indexOf){var n=t?t+1:0;return e.substr(0,e.indexOf(".")+n)}return e}var a=function(e){return t.parseUnits(u(e,{precision:2}),2)},c=function(r,t){if(void 0===t&&(t={}),t.decimals||(t.decimals=18),null!=r){var n=r._isBigNumber?e.ethers.utils.formatUnits(r,t.decimals):r;return!t.precision&&0!==t.precision&&n&&(t.precision=l(n)),function(e,r){if(void 0===r&&(r={}),!e)return"number"==typeof e?e:"";var t=2;void 0!==r.precision&&(t=r.precision);var n="en-GB";r.currentLang&&"es"===r.currentLang&&(n="es-ES"),0===t&&(e=Math.floor(Number(e))),2===t&&(e=Math.round(100*(parseFloat(e)+Number.EPSILON))/100),e.toString().match("e")&&(e=Number.parseFloat(e).toFixed(0));var o=e.toString().split(".");o[0]=o[0].replace(",","");var i="";return i=o.length>1&&t>0?u(o.join("."),{precision:t}):o[0],r.removeTrailingZeros&&(i=i.replace(/(\.0+|0+)$/,"")),Number(i).toLocaleString(n,{minimumFractionDigits:r.removeTrailingZeros?0:t})}(n,t)}},l=function(e){return(e=parseFloat(e))>1e4?0:e>=.1?2:d(e)},d=function(e,r){void 0===r&&(r={additionalDigits:2});var t=r.additionalDigits,n=String(e).split(".")[1];return"0"===n?0:n?n.match(/^0*/)[0].length+t:t},m=function(e,r){return e.mul(Math.round(100*r)).div(100)},p=function(r){return r.reduce((function(e,r){return r.add(e)}),e.ethers.constants.Zero)},f=function(e,r,n){return void 0===n&&(n=4),e.isZero()||r.isZero()?0:Number(t.formatUnits(e.mul(Math.pow(10,n)).div(r),String(n)))},h=Object.freeze({mainnet:1,homestead:1,ropsten:3,rinkeby:4,goerli:5,kovan:42,bsc:56,"poa-sokol":77,"bsc-testnet":97,poa:99,xdai:100,polygon:137,matic:137,mumbai:80001,optimism:10,"optimism-goerli":420,avalanche:43114,fuji:43113,celo:42220,"celo-testnet":44787,arbitrum:42161,"arbitrum-goerli":421613}),v=Object.freeze([h.mainnet,h.goerli]),g=Object.freeze([h.polygon,h.mumbai]),x=Object.freeze([h.avalanche,h.fuji]),b=Object.freeze([h.celo,h["celo-testnet"]]),N=Object.freeze([h.optimism,h["optimism-goerli"]]),y=Object.freeze([h.arbitrum,h["arbitrum-goerli"]]),U=function(e){var r=Object.keys(h).find((function(r){return h[r]===e}));if(void 0!==r)return r},T=Object.freeze([1,3,4,5,42,137,80001,10,420,42161,421613]),O=Object.freeze([1,3,4,5,42]),M=Object.freeze([1,3,4,5,137,80001,10,420,42161,421613]),S={alchemy:void 0,etherscan:void 0,infura:void 0},P=function(e){var r,t=i.getChain(e);try{S.alchemy&&T.includes(e)?r=new n.AlchemyProvider(e,S.alchemy):S.infura&&M.includes(e)?r=new n.InfuraProvider(e,S.infura):S.etherscan&&O.includes(e)?r=new n.EtherscanProvider(e,S.etherscan):t&&t.rpc[0]?r=new n.JsonRpcProvider(t.rpc[0],e):console.warn("Chain id "+e+" not supported.")}catch(e){console.error(e)}return r},w=function(e,r){var t=S.alchemy||(null==r?void 0:r.alchemy),s=S.infura||(null==r?void 0:r.infura);try{var u;if(t&&T.includes(e))return n.AlchemyProvider.getUrl(o.getNetwork(e),t).url;if(s&&M.includes(e))return n.InfuraProvider.getUrl(o.getNetwork(e),"string"==typeof s?{projectId:s}:s).url;var a=i.getChain(e);return(null==a||null==(u=a.rpc)?void 0:u[0])||(console.warn("getRpcUrl | Chain id "+e+" not supported."),i.getChain(h.mainnet).rpc[0])}catch(e){return console.error(e),i.getChain(h.mainnet).rpc[0]}},E=function(){return Number((Date.now()/1e3).toFixed(0))},j=Object.freeze({}),A=Object.freeze({});exports.ARBITRUM_NETWORKS=y,exports.AVALANCHE_NETWORKS=x,exports.CELO_NETWORKS=b,exports.ETHEREUM_NETWORKS=v,exports.NETWORK=h,exports.OPTIMISM_NETWORKS=N,exports.POLYGON_NETWORKS=g,exports.addBigNumbers=p,exports.addTokenTotalUsdValue=function(e,t){var n=t[e.address];if(n){if(e.usd=n.usd||0,e.derivedETH=n.derivedETH||"0",e.amountUnformatted){var o=m(e.amountUnformatted,e.usd);e.totalValueUsd=r.formatUnits(o,e.decimals),e.totalValueUsdScaled=a(e.totalValueUsd)}}else e.usd=0,e.derivedETH="0"},exports.amountMultByUsd=m,exports.calculateApr=function(e,r,t){if(void 0===t&&(t=4),e.isZero()||r.isZero())return 0;var n=r.mul(365);return 100*f(n,e,t)},exports.calculateCreamBorrowApy=function(e,r,n,o,i,s,u){var a=Number(t.formatUnits(e,18)),c=Number(t.formatUnits(r,18)),l=Number(t.formatUnits(n,18)),d=Number(t.formatUnits(o,18)),m=Number(t.formatUnits(i,18)),p=Number(t.formatUnits(s,18)),f=u.toNumber();return Math.pow(1+a+c*Math.min(l,d)+Math.max(p*l-m,0),f)-1},exports.calculateCreamSupplyApy=function(e,r,n,o){var i=Number(t.formatUnits(r,18)),s=Number(t.formatUnits(n,18)),u=o.toNumber();return Math.pow(1+(Math.pow(1+e,1/u)-1)*(1-i)*s,u)-1},exports.calculateEstimatedCompoundPrizeWithYieldUnformatted=function(r,t,n,o,i,s){var u=s&&0!==parseFloat(s)?e.ethers.utils.parseUnits(parseFloat(s).toFixed(Number(o)),o):e.ethers.constants.Zero;return(u.isZero()?e.ethers.constants.Zero:t.mul(n).mul(Math.round(parseFloat(i))).mul(u).div(e.ethers.utils.parseUnits("1",18)).div(e.ethers.utils.parseUnits("1",o))).add(r)},exports.calculateLPTokenPrice=function(e,r,n,o,i){var s=p([m(t.parseUnits(e,18),n),m(t.parseUnits(r,18),o)]),u=t.parseUnits(i,18);return s.div(u)},exports.calculateOdds=function(r,t,n,o){if(void 0===o&&(o=1),!r||r.isZero()||!t||t.isZero()||!n||0===o)return 0;var i=Number(e.ethers.utils.formatUnits(r,n)),s=Number(e.ethers.utils.formatUnits(t,n));return 1-Math.pow((s-i)/s,o)},exports.calculatePercentageOfBigNumber=function(e,r,t){return void 0===t&&(t=4),e.mul(r*Math.pow(10,t)).div(Math.pow(10,t))},exports.calculateUsersOdds=function(r,t,n,o){if(!r||r.eq(e.ethers.BigNumber.from(0))||!n)return 0;var i=parseInt(o,10),s=Number(e.ethers.utils.formatUnits(r,Number(n))),u=Number(e.ethers.utils.formatUnits(t,Number(n)));return 1/(1-Math.pow((u-s)/u,i))},exports.calculatedEstimatedAccruedCompTotalValueUsdScaled=function(r,t,n){return r?t.mul(Math.round(100*parseFloat(r))).div(1e4).mul(100).div(31536e3).mul(n).div(100):e.ethers.constants.Zero},exports.chainIdToNetworkName=function(e){return 137===e?"polygon":U(e)},exports.dToM=function(e){return e?1440*e:0},exports.dToMs=function(e){return e?86400*e*1e3:0},exports.dToS=function(e){return e?86400*e:0},exports.deserializeBigNumbers=function r(t){try{return Array.isArray(t)?t.forEach(r):"object"==typeof t&&null!==t&&Object.keys(t).forEach((function(n){if(Array.isArray(t[n]))t[n].forEach(r);else if("object"==typeof t[n]&&null!==t[n]){var o;"BigNumber"===(null==(o=t[n])?void 0:o.type)?t[n]=e.ethers.BigNumber.from(t[n]):r(t[n])}})),t}catch(e){return t}},exports.displayPercentage=function(e){return(e=parseFloat(e).toFixed(2)).toString().replace(/(\.0+$)|(0+$)/,"")},exports.divideBigNumbers=f,exports.getChainIdByAlias=function(e){return null==h?void 0:h[e]},exports.getLootBoxKey=function(e,r){return"lootBox-"+e+"-"+r},exports.getMaxPrecision=function(e){var r;return(null==(r=String(e).split(".")[1])?void 0:r.length)||0},exports.getMinPrecision=d,exports.getNetworkNameAliasByChainId=U,exports.getNetworkNiceNameByChainId=function(e){switch(Number(e)){case h.mainnet:return"Ethereum";case h.matic:return"Polygon";case h.bsc:return"Binance Smart Chain";case h.celo:return"Celo";case h.xdai:return"xDai";default:var r=U(e);return r?r.charAt(0).toUpperCase()+r.slice(1):"--"}},exports.getPrecision=l,exports.getPrizePoolSymbol=function(e,r){return e.toUpperCase()+"-"+r.slice(0,8)},exports.getReadProvider=P,exports.getReadProviders=function(e){var r={};return e.forEach((function(e){var t=P(e);t&&(r[e]=t)})),r},exports.getRpcUrl=w,exports.getRpcUrls=function(e,r){return e.reduce((function(e,t){return e[t]=w(t,r),e}),{})},exports.getSecondsRemainingInPrizePeriod=function(e,r){var t=e.toNumber(),n=r.toNumber();return t-(E()-n)},exports.getSecondsSinceEpoch=E,exports.getTimeBreakdown=function(e){var r=Number(e),t=0;r>=31536e3&&(r-=31536e3*(t=Math.floor(r/31536e3)));var n=0;r>=86400&&(r-=86400*(n=Math.floor(r/86400)));var o=0;(n||r>=3600)&&(r-=3600*(o=Math.floor(r/3600)));var i=0;(o||r>=60)&&(r-=60*(i=Math.floor(r/60)));var s=0;return(i||r>=1)&&(s=r),{years:t,days:n,hours:o,minutes:i,seconds:s}},exports.getTokenColour=function(e,r){return void 0===r&&(r=!1),r?A[e]:j[e]},exports.initProviderApiKeys=function(e){S.alchemy=e.alchemy,S.etherscan=e.etherscan,S.infura=e.infura},exports.msToD=function(e){return e?e/1e3/86400:0},exports.msToS=function(e){return e?e/1e3:0},exports.msToSeconds=function(r){return r?e.ethers.BigNumber.from(r).div(1e3).toNumber():0},exports.numberWithCommas=c,exports.prettyNumber=function(e,r){return c(e,{decimals:r})},exports.sToD=function(e){return e?e/86400:0},exports.sToM=function(e){return e?e/60:0},exports.sToMs=function(e){return e?1e3*e:0},exports.safeParseUnits=function(e,r){try{return t.parseUnits(e,r)}catch(t){return void console.warn("could not run parseUnits on values:",e,r)}},exports.sharesAmountToUnderlyingAmount=function(e,r,t){if(!r.isZero())return e.mul(t).div(r)},exports.shorten=function(e){var r;return e.hash&&(r=s.exec(e.hash))?e.short?r[1]+"...":r[1]+"..."+r[2]:null},exports.stringWithPrecision=u,exports.subtractDates=function(e,r){var t=e.getTime()-r.getTime(),n=0;t>=864e5&&(t-=864e5*(n=t/864e5));var o=0;(n||t>=36e5)&&(t-=36e5*(o=t/36e5));var i=0;(o||t>=6e4)&&(t-=6e4*(i=t/6e4));var s=0;return(i||t>=1e3)&&(s=t/1e3),{days:n,hours:o,minutes:i,seconds:s}},exports.toNonScaledUsdString=function(e){return t.formatUnits(e,2)},exports.toScaledUsdBigNumber=a,exports.underlyingAmountToSharesAmount=function(e,r,t){if(!t.isZero())return e.mul(r).div(t)},exports.unionProbabilities=function(){for(var e=arguments.length<=0?void 0:arguments[0],r=1;r<arguments.length;r++)e=e+(r<0||arguments.length<=r?void 0:arguments[r])-e*(r<0||arguments.length<=r?void 0:arguments[r]);return e}; | ||
"use strict";Object.defineProperty(exports,"__esModule",{value:!0});var e=require("ethers"),r=require("ethers/lib/utils"),t=require("@ethersproject/units"),o=/^(\w{6})\w*(\w{4})$/;function n(e,r){void 0===r&&(r={precision:2});var t=r.precision;if(e&&"function"==typeof e.indexOf){var o=t?t+1:0;return e.substr(0,e.indexOf(".")+o)}return e}var i=function(e){return t.parseUnits(n(e,{precision:2}),2)},s=function(r,t){if(void 0===t&&(t={}),t.decimals||(t.decimals=18),null!=r){var o=r._isBigNumber?e.ethers.utils.formatUnits(r,t.decimals):r;return!t.precision&&0!==t.precision&&o&&(t.precision=u(o)),function(e,r){if(void 0===r&&(r={}),!e)return"number"==typeof e?e:"";var t=2;void 0!==r.precision&&(t=r.precision);var o="en-GB";r.currentLang&&"es"===r.currentLang&&(o="es-ES"),0===t&&(e=Math.floor(Number(e))),2===t&&(e=Math.round(100*(parseFloat(e)+Number.EPSILON))/100),e.toString().match("e")&&(e=Number.parseFloat(e).toFixed(0));var i=e.toString().split(".");i[0]=i[0].replace(",","");var s="";return s=i.length>1&&t>0?n(i.join("."),{precision:t}):i[0],r.removeTrailingZeros&&(s=s.replace(/(\.0+|0+)$/,"")),Number(s).toLocaleString(o,{minimumFractionDigits:r.removeTrailingZeros?0:t})}(o,t)}},u=function(e){return(e=parseFloat(e))>1e4?0:e>=.1?2:a(e)},a=function(e,r){void 0===r&&(r={additionalDigits:2});var t=r.additionalDigits,o=String(e).split(".")[1];return"0"===o?0:o?o.match(/^0*/)[0].length+t:t},c=function(e,r){return e.mul(Math.round(100*r)).div(100)},l=function(r){return r.reduce((function(e,r){return r.add(e)}),e.ethers.constants.Zero)},m=function(e,r,o){return void 0===o&&(o=4),e.isZero()||r.isZero()?0:Number(t.formatUnits(e.mul(Math.pow(10,o)).div(r),String(o)))},p=Object.freeze({mainnet:1,homestead:1,ropsten:3,rinkeby:4,goerli:5,kovan:42,bsc:56,"poa-sokol":77,"bsc-testnet":97,poa:99,xdai:100,polygon:137,matic:137,mumbai:80001,optimism:10,"optimism-goerli":420,avalanche:43114,fuji:43113,celo:42220,"celo-testnet":44787,arbitrum:42161,"arbitrum-goerli":421613}),d=Object.freeze([p.mainnet,p.goerli]),f=Object.freeze([p.polygon,p.mumbai]),h=Object.freeze([p.avalanche,p.fuji]),v=Object.freeze([p.celo,p["celo-testnet"]]),b=Object.freeze([p.optimism,p["optimism-goerli"]]),x=Object.freeze([p.arbitrum,p["arbitrum-goerli"]]),g=function(e){var r=Object.keys(p).find((function(r){return p[r]===e}));if(void 0!==r)return r},N=function(){return Number((Date.now()/1e3).toFixed(0))},U=Object.freeze({}),y=Object.freeze({});exports.ARBITRUM_NETWORKS=x,exports.AVALANCHE_NETWORKS=h,exports.CELO_NETWORKS=v,exports.ETHEREUM_NETWORKS=d,exports.NETWORK=p,exports.OPTIMISM_NETWORKS=b,exports.POLYGON_NETWORKS=f,exports.addBigNumbers=l,exports.addTokenTotalUsdValue=function(e,t){var o=t[e.address];if(o){if(e.usd=o.usd||0,e.derivedETH=o.derivedETH||"0",e.amountUnformatted){var n=c(e.amountUnformatted,e.usd);e.totalValueUsd=r.formatUnits(n,e.decimals),e.totalValueUsdScaled=i(e.totalValueUsd)}}else e.usd=0,e.derivedETH="0"},exports.amountMultByUsd=c,exports.calculateApr=function(e,r,t){if(void 0===t&&(t=4),e.isZero()||r.isZero())return 0;var o=r.mul(365);return 100*m(o,e,t)},exports.calculateCreamBorrowApy=function(e,r,o,n,i,s,u){var a=Number(t.formatUnits(e,18)),c=Number(t.formatUnits(r,18)),l=Number(t.formatUnits(o,18)),m=Number(t.formatUnits(n,18)),p=Number(t.formatUnits(i,18)),d=Number(t.formatUnits(s,18)),f=u.toNumber();return Math.pow(1+a+c*Math.min(l,m)+Math.max(d*l-p,0),f)-1},exports.calculateCreamSupplyApy=function(e,r,o,n){var i=Number(t.formatUnits(r,18)),s=Number(t.formatUnits(o,18)),u=n.toNumber();return Math.pow(1+(Math.pow(1+e,1/u)-1)*(1-i)*s,u)-1},exports.calculateEstimatedCompoundPrizeWithYieldUnformatted=function(r,t,o,n,i,s){var u=s&&0!==parseFloat(s)?e.ethers.utils.parseUnits(parseFloat(s).toFixed(Number(n)),n):e.ethers.constants.Zero;return(u.isZero()?e.ethers.constants.Zero:t.mul(o).mul(Math.round(parseFloat(i))).mul(u).div(e.ethers.utils.parseUnits("1",18)).div(e.ethers.utils.parseUnits("1",n))).add(r)},exports.calculateLPTokenPrice=function(e,r,o,n,i){var s=l([c(t.parseUnits(e,18),o),c(t.parseUnits(r,18),n)]),u=t.parseUnits(i,18);return s.div(u)},exports.calculateOdds=function(r,t,o,n){if(void 0===n&&(n=1),!r||r.isZero()||!t||t.isZero()||!o||0===n)return 0;var i=Number(e.ethers.utils.formatUnits(r,o)),s=Number(e.ethers.utils.formatUnits(t,o));return 1-Math.pow((s-i)/s,n)},exports.calculatePercentageOfBigNumber=function(e,r,t){return void 0===t&&(t=4),e.mul(r*Math.pow(10,t)).div(Math.pow(10,t))},exports.calculateUsersOdds=function(r,t,o,n){if(!r||r.eq(e.ethers.BigNumber.from(0))||!o)return 0;var i=parseInt(n,10),s=Number(e.ethers.utils.formatUnits(r,Number(o))),u=Number(e.ethers.utils.formatUnits(t,Number(o)));return 1/(1-Math.pow((u-s)/u,i))},exports.calculatedEstimatedAccruedCompTotalValueUsdScaled=function(r,t,o){return r?t.mul(Math.round(100*parseFloat(r))).div(1e4).mul(100).div(31536e3).mul(o).div(100):e.ethers.constants.Zero},exports.chainIdToNetworkName=function(e){return 137===e?"polygon":g(e)},exports.dToM=function(e){return e?1440*e:0},exports.dToMs=function(e){return e?86400*e*1e3:0},exports.dToS=function(e){return e?86400*e:0},exports.deserializeBigNumbers=function r(t){try{return Array.isArray(t)?t.forEach(r):"object"==typeof t&&null!==t&&Object.keys(t).forEach((function(o){if(Array.isArray(t[o]))t[o].forEach(r);else if("object"==typeof t[o]&&null!==t[o]){var n;"BigNumber"===(null==(n=t[o])?void 0:n.type)?t[o]=e.ethers.BigNumber.from(t[o]):r(t[o])}})),t}catch(e){return t}},exports.displayPercentage=function(e){return(e=parseFloat(e).toFixed(2)).toString().replace(/(\.0+$)|(0+$)/,"")},exports.divideBigNumbers=m,exports.getChainIdByAlias=function(e){return null==p?void 0:p[e]},exports.getLootBoxKey=function(e,r){return"lootBox-"+e+"-"+r},exports.getMaxPrecision=function(e){var r;return(null==(r=String(e).split(".")[1])?void 0:r.length)||0},exports.getMinPrecision=a,exports.getNetworkNameAliasByChainId=g,exports.getNetworkNiceNameByChainId=function(e){switch(Number(e)){case p.mainnet:return"Ethereum";case p.matic:return"Polygon";case p.bsc:return"Binance Smart Chain";case p.celo:return"Celo";case p.xdai:return"xDai";default:var r=g(e);return r?r.charAt(0).toUpperCase()+r.slice(1):"--"}},exports.getPrecision=u,exports.getPrizePoolSymbol=function(e,r){return e.toUpperCase()+"-"+r.slice(0,8)},exports.getSecondsRemainingInPrizePeriod=function(e,r){var t=e.toNumber(),o=r.toNumber();return t-(N()-o)},exports.getSecondsSinceEpoch=N,exports.getTimeBreakdown=function(e){var r=Number(e),t=0;r>=31536e3&&(r-=31536e3*(t=Math.floor(r/31536e3)));var o=0;r>=86400&&(r-=86400*(o=Math.floor(r/86400)));var n=0;(o||r>=3600)&&(r-=3600*(n=Math.floor(r/3600)));var i=0;(n||r>=60)&&(r-=60*(i=Math.floor(r/60)));var s=0;return(i||r>=1)&&(s=r),{years:t,days:o,hours:n,minutes:i,seconds:s}},exports.getTokenColour=function(e,r){return void 0===r&&(r=!1),r?y[e]:U[e]},exports.msToD=function(e){return e?e/1e3/86400:0},exports.msToS=function(e){return e?e/1e3:0},exports.msToSeconds=function(r){return r?e.ethers.BigNumber.from(r).div(1e3).toNumber():0},exports.numberWithCommas=s,exports.prettyNumber=function(e,r){return s(e,{decimals:r})},exports.sToD=function(e){return e?e/86400:0},exports.sToM=function(e){return e?e/60:0},exports.sToMs=function(e){return e?1e3*e:0},exports.safeParseUnits=function(e,r){try{return t.parseUnits(e,r)}catch(t){return void console.warn("could not run parseUnits on values:",e,r)}},exports.sharesAmountToUnderlyingAmount=function(e,r,t){if(!r.isZero())return e.mul(t).div(r)},exports.shorten=function(e){var r;return e.hash&&(r=o.exec(e.hash))?e.short?r[1]+"...":r[1]+"..."+r[2]:null},exports.stringWithPrecision=n,exports.subtractDates=function(e,r){var t=e.getTime()-r.getTime(),o=0;t>=864e5&&(t-=864e5*(o=t/864e5));var n=0;(o||t>=36e5)&&(t-=36e5*(n=t/36e5));var i=0;(n||t>=6e4)&&(t-=6e4*(i=t/6e4));var s=0;return(i||t>=1e3)&&(s=t/1e3),{days:o,hours:n,minutes:i,seconds:s}},exports.toNonScaledUsdString=function(e){return t.formatUnits(e,2)},exports.toScaledUsdBigNumber=i,exports.underlyingAmountToSharesAmount=function(e,r,t){if(!t.isZero())return e.mul(r).div(t)},exports.unionProbabilities=function(){for(var e=arguments.length<=0?void 0:arguments[0],r=1;r<arguments.length;r++)e=e+(r<0||arguments.length<=r?void 0:arguments[r])-e*(r<0||arguments.length<=r?void 0:arguments[r]);return e}; | ||
//# sourceMappingURL=utilities.cjs.production.min.js.map |
import { ethers } from 'ethers'; | ||
import { formatUnits as formatUnits$1 } from 'ethers/lib/utils'; | ||
import { parseUnits, formatUnits } from '@ethersproject/units'; | ||
import { AlchemyProvider, InfuraProvider, EtherscanProvider, JsonRpcProvider } from '@ethersproject/providers'; | ||
import { getNetwork } from '@ethersproject/networks'; | ||
import { getChain } from '@pooltogether/evm-chains-extended'; | ||
@@ -660,133 +657,3 @@ var expression = /^(\w{6})\w*(\w{4})$/; | ||
var ALCHEMY_CHAIN_IDS = /*#__PURE__*/Object.freeze([// Ethereum | ||
1, 3, 4, 5, 42, // Polygon | ||
137, 80001, // Optimism | ||
10, 420, // Arbitrum | ||
42161, 421613]); | ||
var ETHERSCAN_CHAIN_IDS = /*#__PURE__*/Object.freeze([// Ethereum | ||
1, 3, 4, 5, 42]); | ||
var INFURA_CHAIN_IDS = /*#__PURE__*/Object.freeze([// Ethereum | ||
1, 3, 4, 5, // Polygon | ||
137, 80001, // Optimism | ||
10, 420, // Arbitrum | ||
42161, 421613]); | ||
var API_KEYS = { | ||
alchemy: undefined, | ||
etherscan: undefined, | ||
infura: undefined | ||
}; | ||
/** | ||
* Initializes the store of API keys for different providers. | ||
* @param apiKeys | ||
*/ | ||
var initProviderApiKeys = function initProviderApiKeys(apiKeys) { | ||
API_KEYS.alchemy = apiKeys.alchemy; | ||
API_KEYS.etherscan = apiKeys.etherscan; | ||
API_KEYS.infura = apiKeys.infura; | ||
}; | ||
/** | ||
* Creates a provider for the given chain id if available. | ||
* Attempts to use any initialized api keys for RPC providers first. | ||
* @param chainId | ||
* @returns | ||
*/ | ||
var getReadProvider = function getReadProvider(chainId) { | ||
var chainData = getChain(chainId); | ||
var provider; | ||
try { | ||
if (API_KEYS.alchemy && ALCHEMY_CHAIN_IDS.includes(chainId)) { | ||
provider = new AlchemyProvider(chainId, API_KEYS.alchemy); | ||
} else if (API_KEYS.infura && INFURA_CHAIN_IDS.includes(chainId)) { | ||
provider = new InfuraProvider(chainId, API_KEYS.infura); | ||
} else if (API_KEYS.etherscan && ETHERSCAN_CHAIN_IDS.includes(chainId)) { | ||
provider = new EtherscanProvider(chainId, API_KEYS.etherscan); | ||
} else if (!!chainData && !!chainData.rpc[0]) { | ||
provider = new JsonRpcProvider(chainData.rpc[0], chainId); | ||
} else { | ||
console.warn("Chain id " + chainId + " not supported."); | ||
} | ||
} catch (e) { | ||
console.error(e); | ||
} | ||
return provider; | ||
}; | ||
/** | ||
* Creates several providers for the given chain ids if available. | ||
* Attempts to use any initialized api keys for RPC providers first. | ||
* @param chainIds | ||
* @returns an object of providers keyed by chain id | ||
*/ | ||
var getReadProviders = function getReadProviders(chainIds) { | ||
var readProviders = {}; | ||
chainIds.forEach(function (chainId) { | ||
var provider = getReadProvider(chainId); | ||
if (provider) { | ||
readProviders[chainId] = provider; | ||
} | ||
}); | ||
return readProviders; | ||
}; | ||
/** | ||
* Returns an RPC URL using configured API keys if possible. | ||
* @param chainId | ||
*/ | ||
var getRpcUrl = function getRpcUrl(chainId, apiKeys) { | ||
var alchemyApiKey = API_KEYS.alchemy || (apiKeys == null ? void 0 : apiKeys.alchemy); | ||
var infuraApiKey = API_KEYS.infura || (apiKeys == null ? void 0 : apiKeys.infura); | ||
try { | ||
var _chainData$rpc; | ||
if (!!alchemyApiKey && ALCHEMY_CHAIN_IDS.includes(chainId)) { | ||
var connectionInfo = AlchemyProvider.getUrl(getNetwork(chainId), alchemyApiKey); | ||
return connectionInfo.url; | ||
} else if (!!infuraApiKey && INFURA_CHAIN_IDS.includes(chainId)) { | ||
var _connectionInfo = InfuraProvider.getUrl(getNetwork(chainId), typeof infuraApiKey === 'string' ? { | ||
projectId: infuraApiKey | ||
} : infuraApiKey); | ||
return _connectionInfo.url; | ||
} | ||
var chainData = getChain(chainId); | ||
var rpcUrl = chainData == null ? void 0 : (_chainData$rpc = chainData.rpc) == null ? void 0 : _chainData$rpc[0]; | ||
if (!!rpcUrl) { | ||
return rpcUrl; | ||
} else { | ||
console.warn("getRpcUrl | Chain id " + chainId + " not supported."); | ||
var _chainData = getChain(NETWORK.mainnet); | ||
return _chainData.rpc[0]; | ||
} | ||
} catch (e) { | ||
console.error(e); | ||
var _chainData2 = getChain(NETWORK.mainnet); | ||
return _chainData2.rpc[0]; | ||
} | ||
}; | ||
/** | ||
* Returns multiple RPC URLS using configured API keys if possible. | ||
* @param chainIds | ||
* @returns | ||
*/ | ||
var getRpcUrls = function getRpcUrls(chainIds, apiKeys) { | ||
return chainIds.reduce(function (rpcUrls, chainId) { | ||
rpcUrls[chainId] = getRpcUrl(chainId, apiKeys); | ||
return rpcUrls; | ||
}, {}); | ||
}; | ||
/** | ||
* Breaks down a number of seconds into years, months, days, hours, minutes, seconds | ||
@@ -1086,3 +953,3 @@ * @param totalSeconds | ||
export { ARBITRUM_NETWORKS, AVALANCHE_NETWORKS, CELO_NETWORKS, ETHEREUM_NETWORKS, NETWORK, OPTIMISM_NETWORKS, POLYGON_NETWORKS, addBigNumbers, addTokenTotalUsdValue, amountMultByUsd, calculateApr, calculateCreamBorrowApy, calculateCreamSupplyApy, calculateEstimatedCompoundPrizeWithYieldUnformatted, calculateLPTokenPrice, calculateOdds, calculatePercentageOfBigNumber, calculateUsersOdds, calculatedEstimatedAccruedCompTotalValueUsdScaled, chainIdToNetworkName, dToM, dToMs, dToS, deserializeBigNumbers, displayPercentage, divideBigNumbers, getChainIdByAlias, getLootBoxKey, getMaxPrecision, getMinPrecision, getNetworkNameAliasByChainId, getNetworkNiceNameByChainId, getPrecision, getPrizePoolSymbol, getReadProvider, getReadProviders, getRpcUrl, getRpcUrls, getSecondsRemainingInPrizePeriod, getSecondsSinceEpoch, getTimeBreakdown, getTokenColour, initProviderApiKeys, msToD, msToS, msToSeconds, numberWithCommas, prettyNumber, sToD, sToM, sToMs, safeParseUnits, sharesAmountToUnderlyingAmount, shorten, stringWithPrecision, subtractDates, toNonScaledUsdString, toScaledUsdBigNumber, underlyingAmountToSharesAmount, unionProbabilities }; | ||
export { ARBITRUM_NETWORKS, AVALANCHE_NETWORKS, CELO_NETWORKS, ETHEREUM_NETWORKS, NETWORK, OPTIMISM_NETWORKS, POLYGON_NETWORKS, addBigNumbers, addTokenTotalUsdValue, amountMultByUsd, calculateApr, calculateCreamBorrowApy, calculateCreamSupplyApy, calculateEstimatedCompoundPrizeWithYieldUnformatted, calculateLPTokenPrice, calculateOdds, calculatePercentageOfBigNumber, calculateUsersOdds, calculatedEstimatedAccruedCompTotalValueUsdScaled, chainIdToNetworkName, dToM, dToMs, dToS, deserializeBigNumbers, displayPercentage, divideBigNumbers, getChainIdByAlias, getLootBoxKey, getMaxPrecision, getMinPrecision, getNetworkNameAliasByChainId, getNetworkNiceNameByChainId, getPrecision, getPrizePoolSymbol, getSecondsRemainingInPrizePeriod, getSecondsSinceEpoch, getTimeBreakdown, getTokenColour, msToD, msToS, msToSeconds, numberWithCommas, prettyNumber, sToD, sToM, sToMs, safeParseUnits, sharesAmountToUnderlyingAmount, shorten, stringWithPrecision, subtractDates, toNonScaledUsdString, toScaledUsdBigNumber, underlyingAmountToSharesAmount, unionProbabilities }; | ||
//# sourceMappingURL=utilities.esm.js.map |
{ | ||
"name": "@pooltogether/utilities", | ||
"version": "0.5.2-beta.2", | ||
"version": "0.6.0", | ||
"description": "Shared utility functions across PoolTogether apps", | ||
@@ -30,7 +30,5 @@ "main": "dist/index.js", | ||
"peerDependencies": { | ||
"@pooltogether/evm-chains-extended": "0.7.2-beta.4", | ||
"ethers": "^5.4.6" | ||
}, | ||
"devDependencies": { | ||
"@pooltogether/evm-chains-extended": "0.7.2-beta.4", | ||
"@size-limit/preset-small-lib": "^7.0.3", | ||
@@ -47,3 +45,3 @@ "@types/node": "^15.0.2", | ||
"hooks": { | ||
"pre-commit": "tsdx lint" | ||
"pre-commit": "tsdx lint:fix" | ||
} | ||
@@ -50,0 +48,0 @@ }, |
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
1
8
228749
25
2155