Skip to content

Commit

Permalink
Merge pull request #77 from TrustyFund/new-portfolio-utils
Browse files Browse the repository at this point in the history
Separate History and Market modules
  • Loading branch information
youaresofunny authored Jun 7, 2018
2 parents cad54cd + 142934d commit 5695492
Show file tree
Hide file tree
Showing 8 changed files with 109 additions and 140 deletions.
2 changes: 1 addition & 1 deletion config.js
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ const config = {
defaultNode: 'wss://bitshares.openledger.info/ws'
},
defaultAssetsNames: ['USD', 'OPEN.BTC', 'OPEN.ETH', 'OPEN.DASH', 'OPEN.LTC',
'OPEN.EOS', 'OPEN.STEEM', 'BTS', 'TRUSTY'],
'OPEN.EOS', 'OPEN.STEEM', 'BTS', 'TRUSTY', 'TWENTIX'],
referrer: 'trfnd',
removePrefix: 'OPEN.',
faucetUrl: 'https://faucet.trusty.fund/signup',
Expand Down
8 changes: 2 additions & 6 deletions src/actions/transactions.js
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ export const createOrdersFromDistribution = async (store) => {
if (!distribution) return;
const userId = rootGetters['account/getAccountUserId'];
const balances = rootGetters['account/getCurrentUserBalances'];
const history = rootGetters['market/getMarketHistory'];
const getMarketPriceById = rootGetters['market/getPriceById'];

const defaultAssetsIds = rootGetters['assets/getDefaultAssetsIds'];

Expand All @@ -51,11 +51,7 @@ export const createOrdersFromDistribution = async (store) => {
const baseBalances = {};

assetsIds.forEach(id => {
if (id === '1.3.0') {
baseBalances[id] = combinedBalances[id];
} else {
baseBalances[id] = combinedBalances[id] * history[id].last;
}
baseBalances[id] = combinedBalances[id] * getMarketPriceById(id);
});


Expand Down
2 changes: 2 additions & 0 deletions src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import transactions from './modules/transactions';
import operations from './modules/operations';
import market from './modules/market';
import openledger from './modules/openledger';
import history from './modules/history';

export default function install(store) {
store.registerModule('connection', connection);
Expand All @@ -16,4 +17,5 @@ export default function install(store) {
store.registerModule('operations', operations);
store.registerModule('market', market);
store.registerModule('openledger', openledger);
store.registerModule('history', history);
}
89 changes: 89 additions & 0 deletions src/modules/history.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,89 @@
import Vue from 'vue';
import * as types from '../mutations';
import API from '../services/api';

const actions = {
fetch: (store, { assetsIds, baseId, days }) => {
const { commit, rootGetters } = store;
const assets = rootGetters['assets/getAssets'];
const baseAsset = assets[baseId];

commit(types.FETCH_PRICES_HISTORY_REQUEST, { baseId });
Promise.all(assetsIds.map(async (assetId) => {
const prices = await API.Assets.fetchPriceHistory(baseAsset, assets[assetId], days);
if (!prices) throw new Error('error market history');
return {
assetId,
prices
};
})).then((pricesObjects) => {
const prices = pricesObjects.reduce((result, obj) => {
result[obj.assetId] = obj.prices;
return result;
}, {});
commit(types.FETCH_PRICES_HISTORY_COMPLETE, { days, prices });
}).catch((err) => {
commit(types.FETCH_PRICES_HISTORY_ERROR);
console.log(err);
});
}
};

const getters = {
getByDay: state => {
return (days) => {
return state.days[days] || {};
};
},
isFetching: state => state.fetching,
getAssetHistoryByDay: state => {
return (id, day) => {
if (!state.days[day]) return { first: 0, last: 0 };
return state.days[day][id] || { first: 0, last: 0 };
};
},
getHistoryAssetMultiplier: state => {
return (days, assetId) => {
if (!state.days[days] || !state.days[days][assetId]) {
return {
first: 0,
last: 0
};
}
return {
first: 1 / state.days[days][assetId].first,
last: 1 / state.days[days][assetId].last
};
};
}
};

const initialState = {
days: {},
fetching: false,
error: false,
baseId: ''
};

const mutations = {
[types.FETCH_PRICES_HISTORY_REQUEST](state, { baseId }) {
state.fetching = true;
state.baseAssetId = baseId;
},
[types.FETCH_PRICES_HISTORY_COMPLETE](state, { prices, days }) {
state.fetching = false;
Vue.set(state.days, days, prices);
},
[types.FETCH_PRICES_HISTORY_ERROR](state) {
state.fetching = false;
state.error = true;
}
};

export default {
state: initialState,
actions,
getters,
mutations,
namespaced: true
};
63 changes: 7 additions & 56 deletions src/modules/market.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,30 +5,6 @@ import API from '../services/api';
const BtsMarket = API.Market['1.3.0'];

const actions = {
fetchMarketHistory: (store, { assetsIds, baseId, days }) => {
const { commit, rootGetters } = store;
const assets = rootGetters['assets/getAssets'];
const baseAsset = assets[baseId];

commit(types.FETCH_MARKET_HISTORY_REQUEST, { baseId, days });
Promise.all(assetsIds.map(async (assetId) => {
const prices = await API.Assets.fetchPriceHistory(baseAsset, assets[assetId], days);
if (!prices) throw new Error('error market history');
return {
assetId,
prices
};
})).then((pricesObjects) => {
const prices = pricesObjects.reduce((result, obj) => {
result[obj.assetId] = obj.prices;
return result;
}, {});
commit(types.FETCH_MARKET_HISTORY_COMPLETE, { prices });
}).catch(() => {
commit(types.FETCH_MARKET_HISTORY_ERROR);
});
},

subscribeToMarket(store, { balances }) {
const { commit } = store;
const assetsIds = Object.keys(balances);
Expand Down Expand Up @@ -74,55 +50,30 @@ const actions = {

const getters = {
getBaseAssetId: state => state.baseAssetId,
getAssetMultiplier: state => {
getPrices: state => state.prices,
getPriceById: state => {
return (assetId) => {
if (!state.history[assetId]) {
return {
first: 0,
last: 0
};
}
return {
first: 1 / state.history[assetId].first,
last: 1 / state.history[assetId].last
};
if (assetId === state.baseId) return 1;
return state.prices[assetId] || 0;
};
},
getMarketHistory: state => state.history,
isFetching: state => state.pending,
isError: state => state.error,
isSubscribed: state => state.subscribed
};

const initialState = {
history: {},
days: 7,
pending: false,
error: false,
baseAssetId: null,
subscribed: false,
prices: {}
prices: {},
baseId: '1.3.0'
};

const mutations = {
[types.FETCH_MARKET_HISTORY_REQUEST](state, { baseId, days }) {
state.fetching = true;
state.baseAssetId = baseId;
state.days = days;
},
[types.FETCH_MARKET_HISTORY_COMPLETE](state, { prices }) {
state.fetching = false;
Object.keys(prices).forEach(assetId => {
Vue.set(state.history, assetId, prices[assetId]);
});
},
[types.FETCH_MARKET_HISTORY_ERROR](state) {
state.fetching = false;
state.error = true;
},
[types.UPDATE_MARKET_PRICE](state, { assetId, price }) {
if (!state.history[assetId]) Vue.set(state.history, assetId, {});
Vue.set(state.history[assetId], 'last', price);
Vue.set(state.prices, assetId, price);
},
[types.SUB_TO_MARKET_COMPLETE](state) {
state.subscribed = true;
Expand Down
4 changes: 4 additions & 0 deletions src/mutations.js
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,10 @@ export const FETCH_PORTFOLIO_ASSET_COMPLETE = 'FETCH_PORTFOLIO_ASSET_COMPLETE';
export const RESET_PORTFOLIO_STATE = 'RESET_PORTFOLIO_STATE';
export const UPDATE_PORTFOLIO = 'UPDATE_PORTFOLIO';

export const FETCH_PRICES_HISTORY_REQUEST = 'FETCH_PRICES_HISTORY_REQUEST';
export const FETCH_PRICES_HISTORY_COMPLETE = 'FETCH_PRICES_HISTORY_COMPLETE';
export const FETCH_PRICES_HISTORY_ERROR = 'FETCH_PRICES_HISTORY_ERROR';

export const FETCH_MARKET_HISTORY_REQUEST = 'FETCH_MARKET_HISTORY_REQUEST';
export const FETCH_MARKET_HISTORY_COMPLETE = 'FETCH_MARKET_HISTORY_COMPLETE';
export const FETCH_MARKET_HISTORY_ERROR = 'FETCH_MARKET_HISTORY_ERROR';
Expand Down
3 changes: 2 additions & 1 deletion src/services/api/assets.js
Original file line number Diff line number Diff line change
Expand Up @@ -32,8 +32,9 @@ const fetchPriceHistory = async (base, quote, days) => {
'get_market_history',
[base.id, quote.id, bucketSize, startDateISO, endDateISO]
);
if (quote.id === '1.3.2418') console.log(history);
// const prices = utils.formatPrices(utils.getPrices(history), base, quote);
const prices = utils.getPrices(history);
const prices = utils.getPrices(history, quote.id, days);
return prices;
} catch (error) {
console.log(error);
Expand Down
78 changes: 2 additions & 76 deletions src/utils/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ export const getPrices = (history) => {
};

/**
* Returns formatted prices for array calculated taking precision щf assets into account
* Returns formatted prices for array calculated taking precision of assets into account
* @param {Object} prices - object with asset's history prices
* @param {number} prices.first - first price of asset history
* @param {number} prices.last - last price of asset history (current)
Expand All @@ -39,6 +39,7 @@ export const getPrices = (history) => {
*/
export const formatPrices = (prices, base, quote) => {
const precisionDiff = base.precision - quote.precision;
console.log(quote.id + ' : ' + prices);

if (precisionDiff > 0) {
prices.first /= (precisionDiff * 10);
Expand All @@ -54,52 +55,6 @@ export const formatPrices = (prices, base, quote) => {
return prices;
};

/**
* Returns amount of change by percent, calculated by prices history and exchange multiplier
* @param {Object} object.prices - object with asset's history prices
* @param {number} object.prices.first - first price of asset history
* @param {number} object.prices.last - last price of asset history (current)
* @param {Object} object.multiplier - object with base -> fiat exchange rates
* @param {number} object.multiplier.first - multiplier for first history price
* @param {number} object.multiplier.last - multiplier for last history price (current)
*/
export const calcPercentChange = (prices, multiplier) => {
// temporary fix, remove after new portfolio with separate market and history modules implemented
if (prices.first === 0) return 0;

return ((((prices.last * multiplier.last) /
(prices.first * multiplier.first)) * 100) - 100);
};


/**
* Returns object with balance in base currency, balance in fiat currency
and change by percent
* @param {Object} object - object containing data for calculation
* @param {number} object.balance - balance of asset
* @param {Object} object.assetPrices - object with asset's history prices
* @param {number} object.assetPrices.first - first price of asset history
* @param {number} object.assetPrices.last - last price of asset history (current)
* @param {Object} object.fiatMultiplier - object with base -> fiat exchange rates
* @param {number} object.fiatMultiplier.first - multiplier for first history price
* @param {number} object.fiatMultiplier.last - multiplier for last history price (current)
* @param {Boolean} object.isBase - the asset for calculation is base asset
* @param {Boolean} object.isFiat - the asset for calculation is fiat asset
*/
export const calcPortfolioData = ({
balance, assetPrices, fiatMultiplier,
isBase, isFiat
}) => {
let multiplier = fiatMultiplier;
let prices = assetPrices;
if (isFiat) multiplier = { first: 1, last: 1 };
if (isBase) prices = { first: 1, last: 1 };
const balanceBase = balance * prices.last;
const balanceFiat = balanceBase * multiplier.last;
let change = calcPercentChange(prices, multiplier);
if (prices.last === prices.first && !isBase) change = 0;
return { balanceBase, balanceFiat, change };
};

export const encryptMemo = (memo, fromKey, toPubkey) => {
const nonce = TransactionHelper.unique_nonce_uint64();
Expand Down Expand Up @@ -258,32 +213,3 @@ export const getValuesToUpdate = (balances, baseBalances, update) => {
});
return result;
};

export const calcPortfolioItem = ({
asset,
prices,
baseAsset,
fiatMultiplier,
balance }) => {
const multiplier = fiatMultiplier;

const baseValue = parseInt((balance * prices.last).toFixed(0), 10);

const baseValuePrecised = baseValue / (10 ** baseAsset.precision);

const fiatValue = parseInt((baseValue * fiatMultiplier.last).toFixed(0), 10);

let change = calcPercentChange(prices, multiplier);

if (prices.fist === prices.last && asset.id !== baseAsset.id) change = 0;

return {
name: asset.symbol,
balance,
baseValue,
baseValuePrecised,
basePrecision: baseAsset.precision,
fiatValue,
change
};
};

0 comments on commit 5695492

Please sign in to comment.