From 8ce704595315df713f7069f8910e44da6f4653e4 Mon Sep 17 00:00:00 2001 From: Fabian Date: Mon, 23 Mar 2020 19:43:49 -0500 Subject: [PATCH] release (#506) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * Fabo/fix gas (#250) * fix gas estimate * linted * fixed test * do not keep data sources (#251) * track failing transactions in Sentry (#249) * correctly set the tx schema for a failing tx (#248) * Fabo/remove per block caching as not working (#247) * remove per block caching as not working * fix memoized results Co-authored-by: Ana G. <40721795+Bitcoinera@users.noreply.github.com> * delete perblockcachedatasource (#253) * Ana/fix balances in actionmodal (#255) * fix action modal available balance * include regen * use dictionary for denomlookup * use correct events for received txs (#257) * enable account creation for some networks (#252) * network update time metric added (#256) * network update time metric added * added missing dep Co-authored-by: Fabian * Fix proposal deposit (#261) * Remove denom handling from getDeposit() * Revert undesired change * delete package-lock.json * localtestnet config change (#265) * Ana/handle "address not from this network" error (#263) * add check address function for all queries * apply suggestions * Ana/add fiatvalue to balances query (e-Money) (#262) * preparation * more preparation * add fiatvalue field to balances query * fix get account info * apply suggestions * apply one last suggestion * suggestions+ Co-authored-by: Fabian * Ana/emoney fix expected returns with inflation and totalbacked (#243) * fix expected returns with inflation and supply * minor fixes. dictionary * query exchange rates from emoney api * fix infinite expected returns * convert api url to const * add eur value to totalbackedvalue. totalngm gains * add important comment * finish calculation * lint * catch errors with sentry Co-authored-by: Fabian * readd coin conversion (#268) * delete amount field (#274) * Fabo/increase gas again (#271) * icrease gas again * fixed test * Fabo/load all txs (even if more then first page in response) (#270) * load all txs (even if more then first page in response) * improved handling of txs * missing renaming * fixed paginated load * add pagination fix also to cosmosV0-source Co-authored-by: iambeone Co-authored-by: Ana G. <40721795+Bitcoinera@users.noreply.github.com> * fixing issue with multiple senders in one event (#273) * fixing issue with multiple senders in one event * Update lib/source/cosmosV2-source.js Co-authored-by: Fabian * Fabo/allow signing for terra + emoney (#267) * allow signing for terra * readd coin conversion * enable actions for terra * fix correct terra testnet url * comments and guards * enabled more txs for emoney and fixed broadcasting * added a catch for wrongly formatted broadcast urls * recover default field. change some network titles (#277) * Fabo/add network data to API (#278) * non desctructive introduction of better address prefix wording * added address creator to API * adjusted test * added ledger app to networks config * add icon property to schema (#281) * add icon property to schema * fix network schema validation Co-authored-by: Ana G. <40721795+Bitcoinera@users.noreply.github.com> * filter out validator specific txs (#279) * Ana/balances coinreducer good fix (#269) * balances coinreducer good fix * refactored fiat value logic Co-authored-by: Fabian * Create network_integration.md * Update network_integration.md * Update network_integration.md * Fabo/avoid 500 errors (#288) * avoid using the latest query * cleanup * Ana/filter validator tx cross network and add txvalue reducer (#285) * filter validators cross network * add value reducer. necessary for multi claim txs * add validator txs filter also for cosmosv0 source * filter and make array only claim rewards msg value * filter txs by whitelist * change length in multi claim reward reducer * add withdrawvalidators * replace dictionary for set * refactor transaction snippet. avoid repetition * Ana/emoney upgrade (mergeable) (#282) * update emoney api_url * fix denom. add default fiat currency * fix rpc endpoint * fix value (my bad) (#293) * fix value (my bad) * trigger another ci flow * erase space * set correct new chain id (#294) * restart API * restart API * fix pr alert (#297) * Fabo/298 tendermint reconnect (#300) * reconnect on tendermint disconnect * cleanup * comments * Update cosmos-node-subscription.js * Fabo/299 trigger a chain hangup error (#301) * trigger a chain hangup error * increase chain hangup time * Apply suggestions from code review * Fabo/store validator addresses (#296) * add validator addresses to db * linted * ignore in local dev * revert * fixed fetch * comment * refactored db into constructor * cleanup * add clearTimeout to avoid reconnection hell (#306) * add clearTimeout to avoid reconnection hell * removed console.log * Aleksei/luniedb replaced (#303) * add validator addresses to db * linted * ignore in local dev * revert * fixed fetch * comment * refactored db into constructor * cleanup * replaced luniedb * linted Co-authored-by: Fabian * disable reconnection logic * clear polling interval for tendermint connection * simple api fixes (#310) * Fabo/remove tendermint (#311) * remove tendermint * fixed empty blockHeight issue * small refactoring * catch on fetches to get logging * delay block updates * add retry logic * refactored getBlockByHeight * remove pm2 dep * validator profiles were returned as array (#312) * remove pr github action (#316) * fixing caching issue and more (#315) * fixing caching issue and more * clear chain hangup timeout * timeout fixed * Update lib/block-listeners/cosmos-node-subscription.js Co-authored-by: Jordan Bibla * added terra_mainnet to networks (#309) * added terra_mainnet to networks * errors fix reverted * Ana/add multidenom rewards. necessary for emoney (#308) * add multidenom rewards. necessary for emoney * add rewards to overview. improve code location * lint * add filter rewards for multidenom * important fix * another important fix * fix cannot read propery constructor of undefined (#318) * change terra mainnet title * pushing something to trigger new build and to restart the node * trying out nylira's node * WIP: Ana/More Terra fixes (#323) * fixing my mess * move all rewards logic to terra * clearly signal single denom rewards * Revert "WIP: Ana/More Terra fixes (#323)" (#325) This reverts commit 408186a3ef743ca51d513eb91c937f49960e7492. * catch inside block polling function (#327) * Fabo/disable writing validator addresses for now (#329) * disable writing validator addresses for now * linted * flushing http cache (#332) * Transaction abstraction schema (#333) * tx abstraction proposal using union * Use Coin type * Cleanup, TransactionV2 * Cleanup, not multisend tx * Unsupported tx (like multisend) don't have details * Fabo/switch to docker swarm mode (#330) * swtich to docker swarm mode * typo * Update .github/workflows/development.yml * Ana/more terra fixes (***THE COMEBACK***) (#324) * fixing my mess * move all rewards logic to terra * clearly signal single denom rewards * error structure has changed. need to look into it * also return denom for single denom rewards * manage errors properly * delete comments * Update lib/reducers/terraV3-reducers.js * loop through transaction messages * doing crazy stuff * rewrite the crazy bit Co-authored-by: Fabian * cosmosv0 was missing the retry logic (#334) * add back validator to db logic (#335) * path_prefix added to network data (#338) * path_prefix added to network data * path_prefix replaced to slug * tests fixed * remove regen (#337) Co-authored-by: Jordan Bibla * Fabo+Mario/transaction abstraction (#336) * draft for transaction abstraction * use lunie message types * Add supported tx types * WIP * Draft new reducers * Fix msg types * Need to resolve type for TransactionDetails union * debug resolver * lint * Fix * Cleanup * fix some union issues * Almost done * Small fixes * Add userTransactionAddedV2 * Add userTransactionAddedV2 to resolvers Co-authored-by: Mario Pino * emoney fixes for fiatvalue (#345) * emoney fixes for fiatvalue * refactor with coinreducer * speaking functions are your friends * refactor ugly nested code * lint * add denoms lookups for terra and emoney (#346) * Ana/add only tokens gas prices 2nd attempt (#344) * add terra and emoney gas price. terra reducer * delete fiatvalue from get balances in cosmos * add emoney reducer * hyper important emoney fixes * fix for emoney denoms * change gas price to micro units * add emoney denoms to denomlookup * transform to microunit also for terra tokens * return null for emoney gas prices * add harcoded gas prices * correct emoney hardcoded values * hardcoded terra gas prices. not working * update hardcoded values to working ones * delete unrelated changes to gas prices * apply suggestions except coinreducer * they call me mr coinreducer * change amount for price. add gas price reducer * change naming in gas price reducer * add error message Co-authored-by: Fabian * fix rewards denoms (#351) * updating image on deploy (#352) * fix my mess once more (#353) * Ana/add gas prices to other networks (#350) * add gasprices to cosmos * format gas prices to three decimals * Apply suggestions from code review * Update lib/reducers/cosmosV0-reducers.js Co-authored-by: Fabian Co-authored-by: Jordan Bibla * added a tx success push, fallback (#354) * fix cosmos gas price (#355) * fix terra for new tmbalance (#358) * Fabo/new emoney rewards (#357) * intent to fix the emoney rewards * intent to fix emoney rewards * simplified code * comments * hack to fix reduce function * eligable -> eligible * correct reducer fix Co-authored-by: Ana G. <40721795+Bitcoinera@users.noreply.github.com> Co-authored-by: Jordan Bibla * Aleksei/prevent constant db calls (#304) * add validator addresses to db * linted * ignore in local dev * revert * fixed fetch * comment * refactored db into constructor * cleanup * prevent constant db interaction * stored object structure changed * remove nesting in validators * filter validators list Co-authored-by: Fabian * limit txs pages load by two pages per request (#314) * limit txs pages load by two pages per request * delete block from loadpaginatedtxs * small fixes * Update lib/source/cosmosV2-source.js * linted Co-authored-by: Ana G. <40721795+Bitcoinera@users.noreply.github.com> Co-authored-by: Fabian * linted * linted * Fabo/Use figment nodes (#362) * use api keys * add env variables for nodes * hard code api keys (#365) * fix ngm fiatvalue (#361) * hardcoded urls fix (#366) * WIP: Improve TransactionV2 implementation (#349) * Add from field to SendTx type * add amount to claim rewards transactions * convert to units in string coin reducer * fix typo * add multidenom string coinreducer for claim amount * Add UnknownTx to schema * Add BlockV2 type which returns TransactionV2 txs * Add blockV2 query that returns TransactionV2 txs * kill handling claim rewards amount * Update lib/reducers/cosmosV0-reducers.js Co-Authored-By: Fabian * Update lib/reducers/cosmosV0-reducers.js Co-Authored-By: Fabian * Cleanup * lint * Support claim rewards from multiple validators * Fix, cleanup Co-authored-by: Ana G. <40721795+Bitcoinera@users.noreply.github.com> Co-authored-by: Fabian * Aleksei/fix db insert (#367) * fixed insert function to allow empty schema * Aleksei/statistics in the api (#364) * collecting statistics in the API * small fixes * fixes * changing address to key in clearOverviewedAddresses Co-authored-by: Aleksey Rudometov * add pageNumber to schema (#370) * add pageNumber to schema * file wasn't saved * trigger ci * added pagination to tx v2 api (#372) * Together with 3584: Ana/change fiatvalue to object (#360) * change fiatvalue to object * handle when selected currency is eur * include ngm fiatvalue fix * Ana/amount in claim rewards in transactions v2 (#373) * bring amount in claim rewards back to life * change to regex * simplify * make the regex understandable * Ana/add powered to networks (#377) * add powered by * more logical powered * add provider address for avatar * fix powere validation * Fabo/add network-type for selecting addrss and signing (#378) * add network-type for selecting addrss and signing * adjust according to new network_type param * add network type to network schema Co-authored-by: Ana G. <40721795+Bitcoinera@users.noreply.github.com> * fix staking denom (#379) * fix terra balances and overview (#380) * Fabo/allow to query experimental networks (#382) * all to query experimental networks * fix old small typo Co-authored-by: Ana G. <40721795+Bitcoinera@users.noreply.github.com> * First steps to integrate Polkadot (#376) * Add polkadot-testnet in networks.js * Install polkadot-api, polkadot-node-sub. draft * lint * lint * lint * add polkadotV0 source * add address creator * Update data/networks.js Co-Authored-By: Jordan Bibla * Update data/networks.js Co-Authored-By: Jordan Bibla * blocks, events * Cleanup * polling instead subscription * husky * updateDBValidatorProfiles * no wait for block data fetching, kind of stable * Add reducers file * block subscription works! * Cleanup, fix memory leak * lint, node * comment * Handle polkadot chain reorgs * Cleanup * Optimization, cleanup * Optimization * fixes, validators query working, cleanup * comment * lint * fix block time * handle polkadot chain hangups * cleanup * validator reducer * lint * wip * calculate and include a bunch of validator fields * add bech32_prefix address_prefix to networks.js * add 1 space so we dont break tests * remove chain reorg handling, more stable Co-authored-by: Ana G. <40721795+Bitcoinera@users.noreply.github.com> Co-authored-by: Fabian Co-authored-by: Jordan Bibla * transactions loading time reduced (#383) * transactions loading time reduced * increased page number * add loki to docker-compose (#385) * add network type (#386) * removed livepeer from running in API (#390) * set polkadot to disabled (#392) * Ana/add totalstake-fiatvalue to Overview (#384) * add totalstake fiat value to overview * fix amount in totalstake fiatvalue * make new code more readable * Update lib/reducers/cosmosV0-reducers.js * refactor unit conversion Co-authored-by: Mario Pino * disable polkadot (#395) Co-authored-by: Fabian * Fabo/terra returns (#389) * better error logging * add result selector to query * split emoney getAllValidators from Terra * add expected returns querying to terra * filter out empty returns * remove not used code * missing return * limit decimals * fix not found in terra testnet * temporary hacks * Revert "temporary hacks" This reverts commit 88d0918af70489422d6d5d84909df1186a23fa1c. * Revert "fix not found in terra testnet" This reverts commit 19a4eca6eb4a9eb2050b368b270d4a39847e016a. * add terra testnet api * switch to show all decimals Co-authored-by: Ana G. <40721795+Bitcoinera@users.noreply.github.com> * fix all fiat values to 2 decimals (#399) * Ana/correct terra denoms (#398) * correct terra denoms * variable renaming Co-authored-by: Fabian * Ana/add fiatvalue in rewards (#396) * add fiatvalue to rewards * add fiatcurrency to rewards query * handle unsupported fiat currencies * apply suggestions * delete never used delegations parameter (#404) * fix terra getrewards and gas prices (#409) * reactivate kusama (#411) * Ana/fix repeated claim rewards transactions in transaction abstraction (#400) * fix terra repeated claim rewards transactions * much better fix * add claim rewards messages aggregator * try to apply suggestion * also not working * working 🎉 * change name and add comment * improved implementation by aggregating the claim messags correctly Co-authored-by: Fabian Weber * disable polkadot once more for release (#412) * readd memory limit (#413) * Use polling instead subscription in Kusama (#406) * uncomment polkadot * bug fixes * pollForNewBlock * mod getBlockHeight * add again commented api disconnect to not forget * enqueueAndPublishBlockAdded * re-subscribe on error * stringify error * stringify errors * api.isReady * Add delay to newBlockHandler * Ana/add balances to kusama (#405) * rudimentary balance * add some comment * Ana/switch polkadot to rest calls (#408) * add rewards and overview functions. not working * poll instead of subscribe to blocks * switch over to http provider * fix lint errors * use httpprovider * getting last block hash * get blockhash and header. but no height * back to normal. use mario node subscription * successfully get block height polling with http * get block hash from http. use polling * uncomment all other networks * pass the store to source classes * create the api only once * comment api.disconnect() * added polling fix and quick querying * fixed block height query * clean up * comment * cleanup and optimization Co-authored-by: Fabian Weber Co-authored-by: mariopino * remove unused dependency Co-authored-by: Bitcoinera Co-authored-by: Ana G <40721795+Bitcoinera@users.noreply.github.com> Co-authored-by: Fabian Weber * deactivate polkadot * trigger deploy * trigger CI * swtich to newer caddy version * activate polkadot again * deactivate again * Proposal to enable Kusama network (#424) * working state * cleanup * getBlockHeight() * update polkadot-api (#423) * fixing node_exporter call in Caddyfile (#418) * fixing send amount in statistics (#419) * fixing send amount in statistics * denom fixed * fix validator as selected fiat bug (#415) * Ana/correct terra denoms in activity (#425) * correct fix terra denoms in activity * delete correct terra denom as not needed * Ana/fix amount null in claim rewards (#416) * fix amount null in claim rewards * small refactor * apply suggestion * add release script to api (#426) * Add self stake to validators query (#433) * add self stake * Update lib/reducers/polkadotV0-reducers.js Co-Authored-By: Ana G. <40721795+Bitcoinera@users.noreply.github.com> * lint Co-authored-by: Ana G. <40721795+Bitcoinera@users.noreply.github.com> Co-authored-by: Bitcoinera * fix emoney balances denoms (#436) * [Polkadot] Add delegations query (#435) * first step, simplified query is working * lint * Get validator info from val dictionary * cleanup, fix comission * fix * faster solution * remove types we dont need in store * @Aleksei suggestions * fix * fix * simplify as @imbeone suggested * simplify, thanks @bitcoinera! * re adding array check * delegationReducer * fix * Ana/update polkadot balances (#441) * update polkadot balances * structs are strange * change comment * disable kusama * disable kusama * Ana/427 polkadot single validator query (#440) * save validators with operatoraddress as key * add check to wait to fetch validators * Update lib/resolvers.js Co-Authored-By: Fabian * Update lib/resolvers.js Co-Authored-By: Fabian * lint * fix delegations Co-authored-by: Fabian * Add denom decimal places to networks.js (#434) * lint * add decimals places, refactor POLKADOT_CONVERSION * add to schema * add to tests * refactor with @faboweb suggestions * fix * fix * fix * cleanup * apply suggestions * fix balances * add factor properly to network Co-authored-by: Bitcoinera * fix totalstake fiatvalue only returning euro (#442) * Fix commission for validators in Polkadot network (#447) * fix commission * comment * Fix expectedReturns for validators in Polkadot network (#446) * fix expectedReturns * change -- for null in getrewards and returns Co-authored-by: Bitcoinera * Ana/emoney validators load optimization (#430) * just for testing. hang up on validatorssets latest * fix emoney validators load * resolve conflict * remove experimental line * linted * Fabo/polkadot overview (#450) * add first steps towards overview * correct total * fixed total * fix getaccountinfo is not a funciton * delete hardcoded node rpc url * endpoint back to normal Co-authored-by: Bitcoinera * change polkadot node back to paritys one (#453) * Bump acorn from 5.7.3 to 5.7.4 (#454) Bumps [acorn](https://github.com/acornjs/acorn) from 5.7.3 to 5.7.4. - [Release notes](https://github.com/acornjs/acorn/releases) - [Commits](https://github.com/acornjs/acorn/compare/5.7.3...5.7.4) Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> * Fabo/improve delegations (#455) * improve delegations * removed timer * add hack for accounts with no nominations Co-authored-by: Bitcoinera * update polkadot api to latest (#456) * updated minimist (#457) * add empty getundelegations for polkadot (#458) * Update polkadot api to v1.7.1 (#465) * Ana/fix calculatefiatvalue when fiatcurrency not set (#462) * fix calculatefiatvalue when fiatcurrency not set * improve fix and comment * linted * Upgrade @polkadot/api to v1.8.0-beta.1 (#471) * Add intention validators in Polkadot network (#468) * Add timer to getAllValidators() * Fetch intention addresses for current session * wip * Add validators * working! getAllValidators exec time less than 10s * fix status * Cleanup * fix free balance (#474) * Fix delegations query in Polkadot network (#475) * fetch delegations from stored valid. staking info * Simplify * Cleanup * tx type in v2 subscriptions changed to TransactionV2 (#476) * Ana/add new release script copying fe (#479) * add new release script copying fe * add node executor to circleci * add aliases for circleci * missed one alias * change uluna gas price to recommended one (#481) * fixing claim rewards pubsub publishing (#480) * fixing claim rewards pubsub publishing * only get stakingDenom once Co-authored-by: Fabian Weber * Fabo/fix failed txs parsing (#486) * publish v2 txs and fix failed txs parsing * linted * Fabo/add logs to txs v2 (#487) * add logs to txs v2 * better logic * michiel/move yarn test to separate step for circleci (#482) * migrate test.yml github workflow to circleci config.yml fix executor from web to node * remove test.yml workflow file * refactor address extraction into reducers (#488) * add polkadot prefix (#489) * add polkadot prefix * change address prefix to be a number * Fabo/broadcast polkadot txs (#461) * first steps to broadcast polkadot txs * remove package-lock * fixed api init * remove debugger * working broadcasting * working * ignore polkadot in tests * Update lib/controller/transaction/index.js Co-Authored-By: Jordan Bibla Co-authored-by: Jordan Bibla * Fabo/wait for data ready (#497) * allow to wait for data to be ready (cherry picked from commit 744d9b3b445286a9637fdadbeb5c473165cec58e) * wait for data to be ready (cherry picked from commit b6d665fd88ae22e5e3753249f27730eb12faebcb) * keep store in cosmos source (cherry picked from commit a6bb9f023eb56fb57d9a0f3a3ae12c997f6d04e3) * Update lib/resolvers.js * adds key to identify and sort txs (#492) * improve blockHandler logic (#498) (cherry picked from commit b67fab47adbf5a19caf99e17a9395e62419e8dad) * Fabo/enable terra governance (#501) * enable terra governance * also enable proposals in terra testnet * Ana/send all claimed rewards to fe (#493) * send all claimed rewards to fe * refactor reward coin reducer * Fabo/allow single network run (#495) * allow running a single network * readme * apply fix in networks * Update lib/apollo.js Co-authored-by: Bitcoinera * Ana/refactor network capabilities (#502) * refactor network capabilities * refactor to have just a dictionary * fix terra testnet. deleted accidentally testnet Co-authored-by: Fabian * Fabo/fix emoney reward precision (#504) * fix emoney rewards precision * comment * remove polkadot log spamming * add logging for failing tx parsing * more kusama log removal * Fabo/improve emoney loading (#494) * allow to wait for data to be ready * wait for data to be ready * improve blockHandler logic * keep store in cosmos source * centralize emoney exchange queries * fixed balances nto available * precalculate all exchange rates * remove mock values * add sentry to nested block handler * linted * keep old emoney tokens for now Co-authored-by: Bitcoinera Co-authored-by: Ana G. <40721795+Bitcoinera@users.noreply.github.com> Co-authored-by: iambeone Co-authored-by: Mario Pino Co-authored-by: Jordan Bibla Co-authored-by: Bitcoinera Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> Co-authored-by: Michiel Mulders --- .../polkadot-node-subscription.js | 1 - lib/reducers/emoneyV0-reducers.js | 145 +++++++------- lib/source/emoneyV0-source.js | 187 ++++++++++-------- 3 files changed, 176 insertions(+), 157 deletions(-) diff --git a/lib/block-listeners/polkadot-node-subscription.js b/lib/block-listeners/polkadot-node-subscription.js index cae08cd8b5..1cdc2e73e8 100644 --- a/lib/block-listeners/polkadot-node-subscription.js +++ b/lib/block-listeners/polkadot-node-subscription.js @@ -52,7 +52,6 @@ class PolkadotNodeSubscription { const blockHeight = blockHeader.number.toNumber() if (this.height < blockHeight) { this.height = blockHeight - console.log(`\x1b[36mNew kusama block #${blockHeight}\x1b[0m`) this.newBlockHandler(blockHeight) } }) diff --git a/lib/reducers/emoneyV0-reducers.js b/lib/reducers/emoneyV0-reducers.js index f0bddc57a8..af3a24d816 100644 --- a/lib/reducers/emoneyV0-reducers.js +++ b/lib/reducers/emoneyV0-reducers.js @@ -1,106 +1,105 @@ const terraV3Reducers = require('./terraV3-reducers') const BigNumber = require('bignumber.js') -const fetch = require('node-fetch') const _ = require('lodash') -const EMoneyAPIUrl = `https://api.e-money.com/v1/` -const exchangeAPIURL = `https://api.exchangeratesapi.io/latest?` -const Sentry = require('@sentry/node') -async function totalBackedValueReducer(totalBackedValue) { - const exchangeRates = await fetchTokenExchangeRates() - const token = `e`.concat(totalBackedValue.denom.substring(1)) - const ticker = totalBackedValue.denom.substring(1).toUpperCase() - // First we calculate the fiat net value of the token's total supply in it counterpart - // fiat currency - const fiatValue = exchangeRates[token] - ? BigNumber(totalBackedValue.amount) - .div(1000000) - .times(exchangeRates[token][ticker]) - .toNumber() - : null - // Now that we have its net fiat value, we transform this value into euro - const { rates } = await fetchFiatExchangeRates(`EUR`, ticker) - const eurRate = ticker === `EUR` ? 1 : rates[ticker] - return (totalBackedValue = { - ...totalBackedValue, - amount: exchangeRates[token] - ? BigNumber(totalBackedValue.amount).times( - Object.values(exchangeRates[token])[0] - ) - : BigNumber(totalBackedValue.amount), - // The total net EUR value of the token's total supply equals its net value in its - // counterpart fiat currency times this fiat currency's EUR rate - eurValue: fiatValue * eurRate - }) -} +async function totalBackedValueReducer( + totalBackedValue, + exchangeRates, + reducers +) { + const aggregatingCurrency = `EUR` + const lunieCoin = reducers.coinReducer(totalBackedValue) -async function fetchTokenExchangeRates() { - return await fetch(`${EMoneyAPIUrl}rates.json`) - .then(r => r.json()) - .catch(err => { - Sentry.withScope(function(scope) { - scope.setExtra('fetch', `${EMoneyAPIUrl}rates.json`) - Sentry.captureException(err) - }) - }) + // The total net EUR value of the token's total supply + const fiatValue = BigNumber(lunieCoin.amount) + .times(exchangeRates[lunieCoin.denom][aggregatingCurrency]) + .toNumber() + return { + ...lunieCoin, + eurValue: fiatValue + } } -async function fetchFiatExchangeRates(selectedFiatCurrency, ticker) { - return await fetch( - `${exchangeAPIURL}base=${selectedFiatCurrency}&symbols=${ticker}` +async function getTotalNetworkAnnualRewards(inflations, totalBackedValues) { + // Now we need to multiply each total supply of backed tokens with its corresponding + // inflation + const totalBackedValueDictionary = _.keyBy( + totalBackedValues.map(totalBackedValue => ({ + ...totalBackedValue, + denom: totalBackedValue.denom.toLowerCase() // inflation response uses lower case denoms + })), + 'denom' ) - .then(r => r.json()) - .catch(err => { - Sentry.withScope(function(scope) { - scope.setExtra( - 'fetch', - `${exchangeAPIURL}base=${selectedFiatCurrency}&symbols=${ticker}` - ) - Sentry.captureException(err) - }) - }) + const rewardsSumInEur = inflations.reduce((sum, inflation) => { + return BigNumber(sum).plus( + BigNumber(inflation.inflation).times( + totalBackedValueDictionary[inflation.denom].eurValue // we use the eur value to be able to sum up the individual token values + ) + ) + }, 0) + + return rewardsSumInEur } async function expectedRewardsPerToken( validator, commission, - inflations, - totalBackedValues + totalNetworkAnnualRewards, + exchangeRates ) { + const aggregatingCurrency = 'EUR' + const stakingToken = 'NGM' + const percentOfAllEligibleStake = validator.votingPower const totalStakeToValidator = validator.tokens // used to answer the question "How many rewards per ONE token invested?" const percentOfAllRewardsPerToken = BigNumber(percentOfAllEligibleStake) .times(BigNumber(1).minus(BigNumber(commission))) .div(BigNumber(totalStakeToValidator)) - // Now we need to multiply each total supply of backed tokens with its corresponding - // inflation - const totalBackedValueDictionary = _.keyBy(totalBackedValues, 'denom') - const rewardsSumInEur = inflations.reduce((sum, inflation) => { - return BigNumber(sum).plus( - BigNumber(inflation.inflation).times( - totalBackedValueDictionary[inflation.denom].eurValue // we use the eur value to be able to sum up the individual token values - ) - ) - }, 0) - // now we calculate the total rewards in eur per token delegated to the validator - const totalEURGainsPerTokenInvested = BigNumber(rewardsSumInEur).times( - percentOfAllRewardsPerToken - ) + const totalEURGainsPerTokenInvested = BigNumber( + totalNetworkAnnualRewards + ).times(percentOfAllRewardsPerToken) // How many NGM tokens can we buy with the total gain in EUR we make in a year's time? // 0.50€ is the price the NGM tokens will be first sold. Therefore, this is the official value // until they reach an exchange - const pricePerNGM = 0.5 - const ngmGains = totalEURGainsPerTokenInvested / pricePerNGM + const pricePerNGM = exchangeRates[stakingToken][aggregatingCurrency] + const ngmGains = totalEURGainsPerTokenInvested.div(pricePerNGM) return ngmGains.toFixed(4) // we don't need more then a precision of 2 (0.1 = 10%) } +function calculateTokenExchangeRates( + supportedFiatCurrencies, + emoneyTokenExchangeRates, + fiatExchangeRates, + reducers +) { + return Object.entries(emoneyTokenExchangeRates).reduce( + (all, [denom, emoneyTokenToFiatExchangeRate]) => { + const [fiatCurrency, rate] = Object.entries( + emoneyTokenToFiatExchangeRate + )[0] // TODO dangerous if there will be more rates from the API directly + // precalculate the exchange rates for all denom currency pairs + supportedFiatCurrencies.forEach(supportedCurrency => { + all[reducers.denomLookup(denom)] = + all[reducers.denomLookup(denom)] || {} + all[reducers.denomLookup(denom)][supportedCurrency] = + supportedCurrency === fiatCurrency + ? rate + : rate * fiatExchangeRates[fiatCurrency][supportedCurrency] + }) + return all + }, + {} + ) +} + module.exports = { ...terraV3Reducers, expectedRewardsPerToken, - fetchTokenExchangeRates, - totalBackedValueReducer + totalBackedValueReducer, + getTotalNetworkAnnualRewards, + calculateTokenExchangeRates } diff --git a/lib/source/emoneyV0-source.js b/lib/source/emoneyV0-source.js index 601a98def9..c891df2bbe 100644 --- a/lib/source/emoneyV0-source.js +++ b/lib/source/emoneyV0-source.js @@ -1,9 +1,10 @@ const TerraV3API = require('./terraV3-source') const CosmosV0API = require('./cosmosV0-source') -const BigNumber = require('bignumber.js') const fetch = require('node-fetch') -const apiURL = `https://api.exchangeratesapi.io/latest?` +const Sentry = require('@sentry/node') +const fiatExchangeRateApi = `https://api.exchangeratesapi.io/latest?` +const EMoneyAPIUrl = `https://beta-api.e-money.com/v1/` const gasPrices = [ { denom: 'echf', @@ -34,6 +35,51 @@ class EMoneyV0API extends TerraV3API { this.gasPrices = gasPrices } + // additional block handling by network + async newBlockHandler(block, store) { + try { + // update exchange rates every 5 minutes + if ( + !store.exchangeRatesUpdating && + (!store.exchangeRatesUpdate || + Date.now() - new Date(store.exchangeRatesUpdate).getTime() > + 5 * 60 * 1000) + ) { + console.log('Updating Emoney token exchange rates') + store.exchangeRatesUpdating = true + + const [fiatExchangeRates, tokenExchangeRates] = await Promise.all([ + this.fetchFiatExchangeRates(), + this.fetchEmoneyTokenExchangeRates() + ]) + this.store.exchangeRates = this.reducers.calculateTokenExchangeRates( + supportedFiatCurrencies, + tokenExchangeRates, + fiatExchangeRates, + this.reducers + ) + + await Promise.all([ + this.getTokensInflations(), + this.getTotalBackedValues() + ]).then(async ([inflatations, totalBackedValues]) => { + store.totalNetworkAnnualRewards = await this.reducers.getTotalNetworkAnnualRewards( + inflatations, + totalBackedValues + ) + }) + + // eslint-disable-next-line require-atomic-updates + store.exchangeRatesUpdating = false + // eslint-disable-next-line require-atomic-updates + store.exchangeRatesUpdate = Date.now() + } + } catch (error) { + console.error('EMoney block handler failed', error) + Sentry.captureException(error) + } + } + // Here we query for the current inflation rates for all the backed tokens async getTokensInflations() { const inflations = await this.get(`inflation/current`) @@ -50,11 +96,16 @@ class EMoneyV0API extends TerraV3API { const mapTotalBackedValues = async () => { return Promise.all( totalBackedValues.map(totalBackedValue => - this.reducers.totalBackedValueReducer(totalBackedValue) + this.reducers.totalBackedValueReducer( + totalBackedValue, + this.store.exchangeRates, + this.reducers + ) ) ) } - return await mapTotalBackedValues() + const resolvedBackedValues = await mapTotalBackedValues() + return resolvedBackedValues } getAnnualProvision() { @@ -66,14 +117,12 @@ class EMoneyV0API extends TerraV3API { } async getExpectedReturns(validator) { - const inflations = await this.getTokensInflations() - const totalBackedValues = await this.getTotalBackedValues() // Right now we are displaying only the EUR value of expected returns const expectedReturns = this.reducers.expectedRewardsPerToken( validator, validator.commission, - inflations, - totalBackedValues + this.store.totalNetworkAnnualRewards, + this.store.exchangeRates ) return expectedReturns } @@ -96,87 +145,51 @@ class EMoneyV0API extends TerraV3API { ) } - // When e-Money goes live they will count with a trading platform where the value - // for the different backed tokens will be changing slightly. - // They will provide with an API for us to query these values. - // For now we will assume a 1:1 ratio and treat each token like it were the real - // fiat currency it represents. - const denom = balance.denom.substring(1).toUpperCase() - - // To handle the NGM balance, first we convert to EUR value and then to the selected - // fiat currency value - if (denom === 'NGM') { - const eurValue = this.reducers.coinReducer(balance).amount * 0.5 // 0.50€ is the price the NGM tokens will be first sold. Therefore, the official value until they reach an exchange - if (selectedFiatCurrency === `EUR`) { - return { - amount: parseFloat(eurValue).toFixed(2), - denom: `EUR`, - symbol: `€` - } - } else { - const { rates } = await this.fetchExchangeRates( - selectedFiatCurrency, - `EUR` - ) - const fiatValue = eurValue / rates[`EUR`] - const currencySign = this.getCurrencySign(selectedFiatCurrency) - return { - amount: parseFloat(fiatValue).toFixed(2), - denom: selectedFiatCurrency, - symbol: currencySign - } - } - // For all other balances we use the public API https://exchangeratesapi.io/ to add all balances into - // a single fiat currency value, the selectedFiatCurrency - } else { - const { rates } = await this.fetchExchangeRates( - selectedFiatCurrency, - denom - ) - let totalAsFiat = 0 - // Here we check if the balance we are currently calculating the total fiat value from is - // the same currency we want the fiat value to be displayed in. - // In that case, we simply add it, don't need to convert it. - if (denom !== selectedFiatCurrency) { - totalAsFiat = this.reducers.coinReducer(balance).amount / rates[denom] - } else { - totalAsFiat = this.reducers.coinReducer(balance).amount - } - // Now we do total value in the selected currency times the token fiat value - const totalFiatValue = await this.convertFiatValueToTokenFiatValue( - totalAsFiat, - denom - ) - // Finally we get the proper currency sign to display - const currencySign = this.getCurrencySign(selectedFiatCurrency) - return { - amount: parseFloat(totalFiatValue).toFixed(2), - denom: selectedFiatCurrency, - symbol: currencySign - } + // e-Money acts like a trading platform where the value for the different backed tokens will be changing slightly. + // They are providing us with an API for us to query the exchange rate from their token to the value of that token + // For aggregating all the values of the different tokens we normalize to one currency using the public API https://exchangeratesapi.io/ + const lunieCoin = this.reducers.coinReducer(balance) + const exchangeRate = this.store.exchangeRates[lunieCoin.denom][ + selectedFiatCurrency + ] + const totalAsFiat = lunieCoin.amount * exchangeRate + + // Finally we get the proper currency sign to display + const currencySign = this.getCurrencySign(selectedFiatCurrency) + return { + amount: parseFloat(totalAsFiat).toFixed(2), + denom: selectedFiatCurrency, + symbol: currencySign } } - async fetchExchangeRates(selectedFiatCurrency, ticker) { - return await fetch( - `${apiURL}base=${selectedFiatCurrency}&symbols=${ticker}` - ) + async fetchEmoneyTokenExchangeRates() { + const rates = await fetch(`${EMoneyAPIUrl}rates.json`) .then(r => r.json()) - .catch(error => console.error(error)) + .catch(err => { + Sentry.withScope(function(scope) { + scope.setExtra('fetch', `${EMoneyAPIUrl}rates.json`) + Sentry.captureException(err) + }) + }) + rates['NGM'] = { EUR: 0.5 } + return rates } - async convertFiatValueToTokenFiatValue(totalAsFiat, denom) { - const tokenExchangeRates = await this.reducers.fetchTokenExchangeRates() - const tokenExchangeRatesArray = Object.values(tokenExchangeRates) - const filterDenomFromExchangeRates = tokenExchangeRatesArray.filter( - rate => Object.keys(rate)[0] === denom - )[0] - const selectedFiatCurrencyExchangeRate = Object.values( - filterDenomFromExchangeRates - )[0] - return BigNumber(totalAsFiat) - .times(selectedFiatCurrencyExchangeRate) - .toNumber() + async fetchFiatExchangeRates() { + let all = {} + await Promise.all( + Array.from(supportedFiatCurrencies).map(async fiatCurrency => { + const { rates } = await fetch( + `${fiatExchangeRateApi}base=${fiatCurrency}` + ) + .then(r => r.json()) + .catch(error => console.error(error)) + all[fiatCurrency] = rates + }) + ) + + return all } getCurrencySign(currency) { @@ -195,6 +208,14 @@ class EMoneyV0API extends TerraV3API { return `?` } } + + async getBalancesFromAddress(address, fiatCurrency) { + return TerraV3API.prototype.getBalancesFromAddress.call( + this, + address, + fiatCurrency + ) + } } module.exports = EMoneyV0API