Skip to content

Commit

Permalink
chore: rug portfolio websocket (#5371)
Browse files Browse the repository at this point in the history
* rug portfolio websocket

* cleanup

* rug it all

---------

Co-authored-by: skylarbarrera <skylar.barrera@gmail.com>
  • Loading branch information
dereknelson and skylarbarrera committed Feb 13, 2024
1 parent 17b1d70 commit 9208194
Show file tree
Hide file tree
Showing 5 changed files with 4 additions and 222 deletions.
1 change: 0 additions & 1 deletion src/hooks/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -72,7 +72,6 @@ export { default as useOpenENSNFTHandler } from './useOpenENSNFTHandler';
export { default as useOpenSmallBalances } from './useOpenSmallBalances';
export { default as useOpenFamilies } from './useOpenFamilies';
export { default as usePrevious } from './usePrevious';
export { default as usePortfolios } from './usePortfolios';
export { default as useRefreshAccountData } from './useRefreshAccountData';
export { default as useRequests } from './useRequests';
export { default as useResetAccountState } from './useResetAccountState';
Expand Down
46 changes: 0 additions & 46 deletions src/hooks/usePortfolios.ts

This file was deleted.

94 changes: 2 additions & 92 deletions src/redux/data.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { StaticJsonRpcProvider, TransactionResponse } from '@ethersproject/providers';
import { isEmpty, isNil, mapValues, partition } from 'lodash';
import { isEmpty, isNil, partition } from 'lodash';
import { Dispatch } from 'redux';
import { ThunkDispatch } from 'redux-thunk';
import { AppGetState, AppState } from './store';
Expand Down Expand Up @@ -39,9 +39,7 @@ import {
import { SwapType } from '@rainbow-me/swaps';
import { logger as loggr } from '@/logger';
import { queryClient } from '@/react-query';
import { RainbowAddressAssets } from '@/resources/assets/types';
import { nftsQueryKey } from '@/resources/nfts';
import { getProvider } from 'e2e/helpers';
import { nonceStore } from '@/state/nonces';

const BACKUP_SHEET_DELAY_MS = android ? 10000 : 3000;
Expand All @@ -54,7 +52,6 @@ const TXN_WATCHER_POLL_INTERVAL = 5000; // 5 seconds
// -- Constants --------------------------------------- //

const DATA_UPDATE_ETH_USD = 'data/DATA_UPDATE_ETH_USD';
const DATA_UPDATE_PORTFOLIOS = 'data/DATA_UPDATE_PORTFOLIOS';

const DATA_LOAD_TRANSACTIONS_REQUEST = 'data/DATA_LOAD_TRANSACTIONS_REQUEST';
const DATA_LOAD_TRANSACTIONS_SUCCESS = 'data/DATA_LOAD_TRANSACTIONS_SUCCESS';
Expand Down Expand Up @@ -85,13 +82,6 @@ export interface DataState {
*/
pendingTransactions: RainbowTransaction[];

/**
* Zerion portfolio information keyed by account address.
*/
portfolios: {
[accountAddress: string]: ZerionPortfolio;
};

/**
* Transactions for this account.
*/
Expand All @@ -102,22 +92,13 @@ export interface DataState {
* An action for the `data` reducer.
*/
type DataAction =
| DataUpdatePortfoliosAction
| DataUpdateEthUsdAction
| DataLoadTransactionsRequestAction
| DataLoadTransactionSuccessAction
| DataLoadTransactionsFailureAction
| DataUpdatePendingTransactionSuccessAction
| DataClearStateAction;

/**
* The action to update `portfolios`.
*/
interface DataUpdatePortfoliosAction {
type: typeof DATA_UPDATE_PORTFOLIOS;
payload: DataState['portfolios'];
}

/**
* The action to update `ethUSDPrice`.
*/
Expand Down Expand Up @@ -167,34 +148,6 @@ interface DataClearStateAction {

// Zerion types:

/**
* Data loaded from the Zerion API for a portfolio. See
* https://docs.zerion.io/websockets/models#portfolio for details.
*/
interface ZerionPortfolio {
arbitrum_assets_value: number;
aurora_assets_value: number;
avalanche_assets_value: number;
ethereum_assets_value: number;
fantom_assets_value: number;
loopring_assets_value: number;
nft_floor_price_value: number;
nft_last_price_value: number;
optimism_assets_value: number;
solana_assets_value: number;
xdai_assets_value: number;
assets_value: number;
deposited_value: number;
borrowed_value: number;
locked_value: number;
staked_value: number;
bsc_assets_value: number;
polygon_assets_value: number;
total_value: number;
absolute_change_24h: number;
relative_change_24h?: number;
}

/**
* A message from the Zerion API indicating that assets were received.
*/
Expand All @@ -209,16 +162,6 @@ export interface AddressAssetsReceivedMessage {
meta?: MessageMeta;
}

/**
* A message from the Zerion API indicating that portfolio data was received.
*/
export interface PortfolioReceivedMessage {
payload?: {
portfolio?: ZerionPortfolio;
};
meta?: MessageMeta;
}

/**
* A message from the Zerion API indicating that transaction data was received.
*/
Expand Down Expand Up @@ -268,12 +211,7 @@ export interface MessageMeta {
/**
* A message from the Zerion API.
*/
type DataMessage =
| AddressAssetsReceivedMessage
| PortfolioReceivedMessage
| TransactionsReceivedMessage
| AssetPricesReceivedMessage
| AssetPricesChangedMessage;
type DataMessage = AddressAssetsReceivedMessage | TransactionsReceivedMessage | AssetPricesReceivedMessage | AssetPricesChangedMessage;

// The success code used to determine if an incoming message is successful.
export const DISPERSION_SUCCESS_CODE = 'ok';
Expand Down Expand Up @@ -365,28 +303,6 @@ const checkForUpdatedNonce =
}
};

/**
* Handles an incoming portfolio data message from Zerion and updates state
* accordidngly.
*
* @param message The `PortfolioReceivedMessage`, or undefined.
*/
export const portfolioReceived =
(message: PortfolioReceivedMessage | undefined) => async (dispatch: Dispatch<DataUpdatePortfoliosAction>, getState: AppGetState) => {
if (message?.meta?.status !== DISPERSION_SUCCESS_CODE) return;
if (!message?.payload?.portfolio) return;

const { portfolios } = getState().data;

const newPortfolios = { ...portfolios };
newPortfolios[message.meta.address!] = message.payload.portfolio;

dispatch({
payload: newPortfolios,
type: DATA_UPDATE_PORTFOLIOS,
});
};

/**
* Handles a `TransactionsReceivedMessage` message from Zerion and updates
* state and account local storage accordingly.
Expand Down Expand Up @@ -846,17 +762,11 @@ const INITIAL_STATE: DataState = {
ethUSDPrice: null,
isLoadingTransactions: true,
pendingTransactions: [],
portfolios: {},
transactions: [],
};

export default (state: DataState = INITIAL_STATE, action: DataAction) => {
switch (action.type) {
case DATA_UPDATE_PORTFOLIOS:
return {
...state,
portfolios: action.payload,
};
case DATA_UPDATE_ETH_USD:
return {
...state,
Expand Down
58 changes: 2 additions & 56 deletions src/redux/explorer.ts
Original file line number Diff line number Diff line change
@@ -1,26 +1,13 @@
import { concat, isEmpty, isNil, keys, toLower } from 'lodash';
import { isNil, toLower } from 'lodash';
import { Dispatch } from 'redux';
import { ThunkDispatch } from 'redux-thunk';
import { io, Socket } from 'socket.io-client';
import { getExperimetalFlag, L2_TXS } from '@/config/experimental';
import { getRemoteConfig } from '@/model/remoteConfig';
import { assetChartsReceived, ChartsReceivedMessage, DEFAULT_CHART_TYPE } from './charts';
import {
assetPricesChanged,
AssetPricesChangedMessage,
assetPricesReceived,
AssetPricesReceivedMessage,
portfolioReceived,
PortfolioReceivedMessage,
transactionsReceived,
TransactionsReceivedMessage,
} from './data';
import { transactionsReceived, TransactionsReceivedMessage } from './data';
import { AppGetState, AppState } from './store';
import { getProviderForNetwork, isHardHat } from '@/handlers/web3';
import currencyTypes from '@/helpers/currencyTypes';
import { Network } from '@/helpers/networkTypes';
import { BNB_MAINNET_ADDRESS, ETH_ADDRESS, MATIC_MAINNET_ADDRESS, OP_ADDRESS, rainbowTokenList } from '@/references';
import { TokensListenedCache } from '@/utils';
import logger from '@/utils/logger';

// -- Constants --------------------------------------- //
Expand All @@ -30,9 +17,6 @@ const EXPLORER_CLEAR_STATE = 'explorer/EXPLORER_CLEAR_STATE';
const TRANSACTIONS_LIMIT = 250;

const messages = {
ADDRESS_PORTFOLIO: {
RECEIVED: 'received address portfolio',
},
ADDRESS_TRANSACTIONS: {
APPENDED: 'appended address transactions',
RECEIVED: 'received address transactions',
Expand Down Expand Up @@ -140,26 +124,6 @@ const addressSubscription = (
},
];

/**
* Configures a portfolio subscription.
*
* @param address The address to subscribe to.
* @param currency The currency to use.
* @param action The API action.
* @returns Arguments for an `emit` function call.
*/
const portfolioSubscription = (address: string, currency: string, action: SocketGetActionType = 'get'): SocketEmitArguments => [
action,
{
payload: {
address,
currency: toLower(currency),
portfolio_fields: 'all',
},
scope: ['portfolio'],
},
];

/**
* Configures a notifications subscription.
*
Expand Down Expand Up @@ -263,20 +227,6 @@ export const explorerInit =
});
};

/**
* Emits a portfolio request. The result is handled by a listener in
* `listenOnAddressMessages`.
*
* @param address The address.
* @param currency The currency to use.
*/
export const emitPortfolioRequest = (address: string, currency?: string) => (_: Dispatch, getState: AppGetState) => {
const nativeCurrency = currency || getState().settings.nativeCurrency;
const { addressSocket } = getState().explorer;

addressSocket?.emit(...portfolioSubscription(address, nativeCurrency));
};

/**
* Emits a layer-2 transaction history request for the current address. The
* result is handled by a listener in `listenOnAddressMessages`.
Expand All @@ -293,10 +243,6 @@ export const emitL2TransactionHistoryRequest = () => (_: Dispatch, getState: App
* @param socket The socket to add listeners to.
*/
const listenOnAddressMessages = (socket: Socket) => (dispatch: ThunkDispatch<AppState, unknown, never>) => {
socket.on(messages.ADDRESS_PORTFOLIO.RECEIVED, (message: PortfolioReceivedMessage) => {
dispatch(portfolioReceived(message));
});

socket.on(messages.ADDRESS_TRANSACTIONS.RECEIVED, (message: TransactionsReceivedMessage) => {
// logger.log('mainnet txns received', message?.payload?.transactions);

Expand Down
27 changes: 0 additions & 27 deletions src/screens/WalletScreen/index.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
import { InteractionManager, View } from 'react-native';
import React, { useCallback, useEffect, useState } from 'react';
import { isEmpty, keys } from 'lodash';
import { useDispatch, useSelector } from 'react-redux';
import { AssetList } from '../../components/asset-list';
import { Page } from '../../components/layout';
Expand All @@ -20,13 +19,10 @@ import {
useLoadAccountData,
useLoadAccountLateData,
useLoadGlobalLateData,
usePortfolios,
useResetAccountState,
useTrackENSProfile,
useUserAccounts,
useWalletSectionsData,
} from '@/hooks';
import { emitPortfolioRequest } from '@/redux/explorer';
import Routes from '@rainbow-me/routes';
import { position } from '@/styles';
import { Toast, ToastPositionContainer } from '@/components/toasts';
Expand All @@ -48,14 +44,11 @@ const WalletScreen: React.FC<any> = ({ navigation, route }) => {
const { setParams, getState: dangerouslyGetState, getParent: dangerouslyGetParent } = navigation;
const removeFirst = useRemoveFirst();
const [initialized, setInitialized] = useState(!!params?.initialized);
const [portfoliosFetched, setPortfoliosFetched] = useState(false);
const initializeWallet = useInitializeWallet();
const { trackENSProfile } = useTrackENSProfile();
const { network: currentNetwork, accountAddress, appIcon, nativeCurrency } = useAccountSettings();
const { userAccounts } = useUserAccounts();
usePositions({ address: accountAddress, currency: nativeCurrency });

const { portfolios, trackPortfolios } = usePortfolios();
const loadAccountLateData = useLoadAccountLateData();
const loadGlobalLateData = useLoadGlobalLateData();
const dispatch = useDispatch();
Expand Down Expand Up @@ -122,26 +115,6 @@ const WalletScreen: React.FC<any> = ({ navigation, route }) => {
}
}, [initializeWallet, initialized, params, setParams]);

useEffect(() => {
if (initialized && addressSocket && !portfoliosFetched) {
setPortfoliosFetched(true);
const fetchPortfolios = async () => {
for (let i = 0; i < userAccounts.length; i++) {
const account = userAccounts[i];
// Passing usd for consistency in tracking
dispatch(emitPortfolioRequest(account.address.toLowerCase(), 'usd'));
}
};
fetchPortfolios();
}
}, [addressSocket, dispatch, initialized, portfolios, portfoliosFetched, userAccounts]);

useEffect(() => {
if (!isEmpty(portfolios) && portfoliosFetched && keys(portfolios).length === userAccounts.length) {
trackPortfolios();
}
}, [portfolios, portfoliosFetched, trackPortfolios, userAccounts.length]);

useEffect(() => {
if (walletReady) {
loadAccountLateData();
Expand Down

0 comments on commit 9208194

Please sign in to comment.