Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

refactor: store typescript readability improvements #1852

Open
wants to merge 10 commits into
base: production
Choose a base branch
from
49 changes: 0 additions & 49 deletions src/store/demeris-api/action-types.ts
Original file line number Diff line number Diff line change
@@ -1,53 +1,4 @@
export enum ActionTypes {
// Wrapper/Grouping actions
GET_ALL_BALANCES = 'GET_ALL_BALANCES',
GET_ALL_STAKING_BALANCES = 'GET_ALL_STAKING_BALANCES',
GET_ALL_UNBONDING_DELEGATIONS = 'GET_ALL_UNBONDING_DELEGATIONS',

// Emeris Endpoints
GET_BALANCES = 'GET_BALANCES',
GET_POOL_BALANCES = 'GET_POOL_BALANCES',
GET_STAKING_BALANCES = 'GET_STAKING_BALANCES',
GET_UNBONDING_DELEGATIONS = 'GET_UNBONDING_DELEGATIONS',
GET_NUMBERS_CHAIN = 'GET_NUMBERS_CHAIN',
GET_VERIFIED_DENOMS = 'GET_VERIFIED_DENOMS',
GET_CHAIN = 'GET_CHAIN',
GET_CHAIN_APR = 'GET_CHAIN_APR',
GET_CHAIN_STATUS = 'GET_CHAIN_STATUS',
GET_CHAINS = 'GET_CHAINS',
GET_CHAINS_AND_CHAIN_STATUS = 'GET_CHAINS_AND_CHAIN_STATUS',
GET_PRICES = 'GET_PRICES',
GET_TX_STATUS = 'GET_TX_STATUS',
GET_TX_DEST_HASH = 'GET_TX_DEST_HASH',
GET_END_BLOCK_EVENTS = 'GET_END_BLOCK_EVENTS',
GET_VALIDATORS = 'GET_VALIDATORS',
GET_INFLATION = 'GET_INFLATION',
GET_STAKING_REWARDS = 'GET_STAKING_REWARDS',
GET_UNSTAKING_PARAM = 'GET_UNSTAKING_PARAM',
GET_VERIFY_TRACE = 'GET_VERIFY_TRACE',
GET_TOKEN_PRICES = 'GET_TOKEN_PRICES',
TRACE_TX_RESPONSE = 'TRACE_TX_RESPONSE',
GET_TX_FROM_RPC = 'GET_TX_FROM_RPC',
GET_NEW_BLOCK = 'GET_NEW_BLOCK',

// Coingecko Endpoints
GET_COINGECKO_ID_BY_NAMES = 'GET_COINGECKO_ID_BY_NAMES',

// Airdrop Endpoints
GET_GIT_AIRDROPS_LIST = 'GET_GIT_AIRDROPS_LIST',
GET_AIRDROPS = 'GET_AIRDROPS',
RESET_AIRDROPS = 'RESET_AIRDROPS',
VALIDATE_POOLS = 'VALIDATE_POOLS',
RESET_TOKEN_PRICES = 'RESET_TOKEN_PRICES',
SIGN_OUT = 'SIGN_OUT',

// Internal module actions
INIT = 'INIT',
RESET_STATE = 'RESET_STATE',
UNSUBSCRIBE = 'UNSUBSCRIBE',
STORE_UPDATE = 'STORE_UPDATE',
}
export enum GlobalActionTypes {
// Wrapper/Grouping actions
GET_ALL_BALANCES = 'demerisAPI/GET_ALL_BALANCES',
GET_ALL_STAKING_BALANCES = 'demerisAPI/GET_ALL_STAKING_BALANCES',
Expand Down
139 changes: 42 additions & 97 deletions src/store/demeris-api/actions.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,9 @@
import { EncodeObject, Registry } from '@cosmjs/proto-signing';
import { EmerisAPI, EmerisBase } from '@emeris/types';
import { EmerisAPI } from '@emeris/types';
import axios, { AxiosResponse } from 'axios';
import { ActionTree } from 'vuex';

import { GlobalGetterTypes, RootState } from '@/store';
import { Pool } from '@/types/actions';
import { UserData } from '@/types/user';
import { ActionParams, SimpleSubscribable, Subscribable } from '@/types/util';
import { validPools } from '@/utils/actionHandler';
import { getOwnAddress, hashObject } from '@/utils/basic';
Expand All @@ -16,12 +14,12 @@ import { RootStoreTyped } from '../';
import { featureRunning } from './../../utils/FeatureManager';
import { APIStore } from '.';
import { ActionTypes } from './action-types';
import { AirdropActions, AirdropActionsInterface } from './actions/airdrops';
import { BalanceActions, BalanceActionsInterface } from './actions/balances';
import { ChainActions, ChainActionsInterface } from './actions/chain';
import { PriceActions, PriceActionsInterface } from './actions/prices';
import { StakingActions, StakingActionsInterface } from './actions/staking';
import { TransactionActions, TransactionActionsInterface } from './actions/transactions';
import { AirdropActions } from './actions/airdrops';
import { BalanceActions } from './actions/balances';
import { ChainActions } from './actions/chain';
import { PriceActions } from './actions/prices';
import { StakingActions } from './actions/staking';
import { TransactionActions } from './actions/transactions';
import { MutationTypes } from './mutation-types';
import { APIState } from './state';

Expand All @@ -43,107 +41,48 @@ export type DemerisConfig = {
hub_chain?: string;
gas_limit?: number;
};
export type DemerisTxParams = {
tx: string;
chain_name: string;
address: string;
};
export type DemerisTxResultParams = {
height: number;
stepType: string;
};
export type GasFee = {
amount: Array<EmerisBase.Amount>;
gas: string;
};

export type DemerisSignParams = {
msgs: Array<EncodeObject>;
chain_name: string;
fee: GasFee;
registry: Registry;
memo?: string;
};
export type DemerisSessionParams = {
data: UserData;
};
export type TicketResponse = {
ticket: string;
};
export type DemerisGetValidatorsParam = {
chain_name: string;
};
export type DemerisGetInflationParam = {
chain_name: string;
};
export type DemerisGetRewardsParam = {
chain_name: string;
};
export type DemerisGetUnstakingParam = {
chain_name: string;
};
type Namespaced<T, N extends string> = {
[P in keyof T & string as `${N}/${P}`]: T[P];
};

export type Subscription<K extends keyof Actions> = {
action: K;
payload?: Omit<Parameters<Actions[K]>[1], 'subscribe'>;
export type Subscription = {
action: any;
payload?: any;
};
export type Subscriptions = Subscription<keyof Actions>;

export interface Actions
extends ChainActionsInterface,
AirdropActionsInterface,
BalanceActionsInterface,
StakingActionsInterface,
PriceActionsInterface,
TransactionActionsInterface {
//Pools Action types
[ActionTypes.VALIDATE_POOLS](context: APIActionContext, pools: Pool[]): Promise<Pool[]>;

//Uncategorized Action types
[ActionTypes.GET_VERIFIED_DENOMS](
context: APIActionContext,
payload: SimpleSubscribable,
): Promise<EmerisAPI.VerifiedDenoms>;
[ActionTypes.GET_VERIFY_TRACE](
context: APIActionContext,
payload: Subscribable<ActionParams<EmerisAPI.VerifyTraceReq>>,
): Promise<EmerisAPI.VerifyTrace>;
[ActionTypes.GET_END_BLOCK_EVENTS](context: APIActionContext, { height }: DemerisTxResultParams): Promise<unknown>;
[ActionTypes.INIT](context: APIActionContext, config: DemerisConfig): void;
[ActionTypes.RESET_STATE](context: APIActionContext): void;
[ActionTypes.SIGN_OUT](context: APIActionContext, keyHashes: string[]): void;
[ActionTypes.UNSUBSCRIBE](context: APIActionContext, subscription: Subscriptions): void;
[ActionTypes.STORE_UPDATE](context: APIActionContext): void;
}

export type GlobalActions = Namespaced<Actions, 'demerisAPI'>;
export type Subscriptions = Subscription;

export const actions: ActionTree<APIState, RootState> & Actions = {
export const actions: ActionTree<APIState, RootState> = {
...ChainActions,
...AirdropActions,
...BalanceActions,
...StakingActions,
...PriceActions,
...TransactionActions,

async [ActionTypes.VALIDATE_POOLS]({ commit, getters }, pools) {
async [ActionTypes.VALIDATE_POOLS]({ commit, getters }: APIActionContext, pools: Pool[]): Promise<Pool[]> {
try {
const vp = await validPools(pools);
commit(MutationTypes.SET_VALID_POOLS, vp);
} catch (e) {
console.error(e);
throw new EmerisError('Demeris:ValidatePools', 'Could not perform pool validation.');
}
return getters['getAllValidPools'];
return getters[GlobalGetterTypes.API.getAllValidPools];
},
async [ActionTypes.GET_VERIFIED_DENOMS]({ commit, getters, rootGetters }, { subscribe = false }) {
async [ActionTypes.GET_VERIFIED_DENOMS](
{ commit, getters, rootGetters }: APIActionContext,
{ subscribe = false }: SimpleSubscribable,
): Promise<EmerisAPI.VerifiedDenoms> {
axios.defaults.headers.get['X-Correlation-Id'] = rootGetters[GlobalGetterTypes.USER.getCorrelationId];
try {
const response: AxiosResponse<EmerisAPI.VerifiedDenomsResponse> = await axios.get(
getters['getEndpoint'] + '/verified_denoms',
getters[GlobalGetterTypes.API.getEndpoint] + '/verified_denoms',
);
commit(MutationTypes.SET_VERIFIED_DENOMS, { value: response.data.verified_denoms });
if (subscribe) {
Expand All @@ -152,17 +91,20 @@ export const actions: ActionTree<APIState, RootState> & Actions = {
} catch (e) {
throw new EmerisError('Demeris:GetVerifiedDenoms', 'Could not perform API query.');
}
return getters['getVerifiedDenoms'];
return getters[GlobalGetterTypes.API.getVerifiedDenoms];
},

// Chain-specific endpoint actions

async [ActionTypes.GET_VERIFY_TRACE]({ commit, getters, state, rootGetters }, { subscribe = false, params }) {
async [ActionTypes.GET_VERIFY_TRACE](
{ commit, getters, state, rootGetters }: APIActionContext,
{ subscribe = false, params }: Subscribable<ActionParams<EmerisAPI.VerifyTraceReq>>,
): Promise<EmerisAPI.VerifyTrace> {
axios.defaults.headers.get['X-Correlation-Id'] = rootGetters[GlobalGetterTypes.USER.getCorrelationId];
const reqHash = hashObject({ action: ActionTypes.GET_VERIFY_TRACE, payload: { params } });
if (state._InProgess.get(reqHash)) {
await state._InProgess.get(reqHash);
return getters['getVerifyTrace'](params);
return getters[GlobalGetterTypes.API.getVerifyTrace](params);
} else {
let resolver;
const promise: Promise<void> = new Promise((resolve, _) => {
Expand All @@ -171,7 +113,7 @@ export const actions: ActionTree<APIState, RootState> & Actions = {
commit(MutationTypes.SET_IN_PROGRESS, { hash: reqHash, promise });
try {
const response: AxiosResponse<EmerisAPI.VerifyTraceResponse> = await axios.get(
getters['getEndpoint'] + '/chain/' + params.chain_name + '/denom/verify_trace/' + params.hash,
`${getters[GlobalGetterTypes.API.getEndpoint]}/chain/${params.chain_name}/denom/verify_trace/${params.hash}`,
);
if (response?.data?.verify_trace?.trace) {
commit(MutationTypes.SET_VERIFY_TRACE, { params, value: response.data.verify_trace });
Expand All @@ -197,14 +139,14 @@ export const actions: ActionTree<APIState, RootState> & Actions = {
}
resolver();
commit(MutationTypes.DELETE_IN_PROGRESS, reqHash);
return getters['getVerifyTrace'](params);
return getters[GlobalGetterTypes.API.getVerifyTrace](params);
}
},
async [ActionTypes.GET_NEW_BLOCK]({ getters }, { chain_name }) {
async [ActionTypes.GET_NEW_BLOCK]({ getters }: APIActionContext, { chain_name }) {
return new Promise(async (resolve, reject) => {
const timeout = 30000;

const wsUrl = `${getters['getWebSocketEndpoint']}/chain/${chain_name}/rpc/websocket`;
const wsUrl = `${getters[GlobalGetterTypes.API.getWebSocketEndpoint]}/chain/${chain_name}/rpc/websocket`;
const wss = new TendermintWS({ server: wsUrl, timeout: 5000, autoReconnect: false });

await wss.connect().catch(reject);
Expand All @@ -223,23 +165,26 @@ export const actions: ActionTree<APIState, RootState> & Actions = {
});
},

async [ActionTypes.GET_END_BLOCK_EVENTS]({ getters, rootGetters }, { height, stepType }: DemerisTxResultParams) {
async [ActionTypes.GET_END_BLOCK_EVENTS](
{ getters, rootGetters }: APIActionContext,
{ height, stepType }: DemerisTxResultParams,
): Promise<unknown> {
axios.defaults.headers.get['X-Correlation-Id'] = rootGetters[GlobalGetterTypes.USER.getCorrelationId];
function sleep(ms) {
return new Promise((resolve) => setTimeout(resolve, ms));
}

try {
await sleep(800); // Apparently it takes some time for end block events to be available on the rpc endpoint after the tx is delivered and our tx ticket updates so this is why this was added originally.
const response = await axios.get(`${getters['getEndpoint']}/block_results?height=${height}`);
const response = await axios.get(`${getters[GlobalGetterTypes.API.getEndpoint]}/block_results?height=${height}`);
const successData = {};

if (response.data.result?.end_block_events) {
let isMine = false;

const checks = getEndBlockChecks({
type: stepType,
requesterAddress: await getOwnAddress({ chain_name: getters['getDexChain'] }),
requesterAddress: await getOwnAddress({ chain_name: getters[GlobalGetterTypes.API.getDexChain] }),
});

response.data.result?.end_block_events?.forEach((item) => {
Expand Down Expand Up @@ -282,7 +227,7 @@ export const actions: ActionTree<APIState, RootState> & Actions = {
// Internal module actions

[ActionTypes.INIT](
{ commit, dispatch },
{ commit, dispatch }: APIActionContext,
{
endpoint,
gitEndpoint,
Expand All @@ -291,8 +236,8 @@ export const actions: ActionTree<APIState, RootState> & Actions = {
hub_chain = 'cosmos-hub',
refreshTime = 5000,
gas_limit = 500000,
},
) {
}: DemerisConfig,
): void {
console.log('Vuex nodule: demeris initialized!');
commit(MutationTypes.INIT, { wsEndpoint, endpoint, gitEndpoint, rawGitEndpoint, hub_chain, gas_limit });
if (!featureRunning('DEBUG')) {
Expand All @@ -301,18 +246,18 @@ export const actions: ActionTree<APIState, RootState> & Actions = {
}, refreshTime);
}
},
[ActionTypes.RESET_STATE]({ commit }) {
[ActionTypes.RESET_STATE]({ commit }: APIActionContext): void {
commit(MutationTypes.RESET_STATE);
},
async [ActionTypes.SIGN_OUT]({ commit, state }, keyHashes) {
async [ActionTypes.SIGN_OUT]({ commit, state }: APIActionContext, keyHashes: string[]): Promise<void> {
commit(MutationTypes.CLEAR_SUBSCRIPTIONS);
// Although on the CLEAR_SUBSCRIPTIONS mutation we remove any subscriptions from the previously signed in account
// there is a chance some requests were already in progress and may return after we clear them so we await completion
// before deleting state data on SIGN_OUT mutation
await Promise.all(state._InProgess.values());
commit(MutationTypes.SIGN_OUT, keyHashes);
},
[ActionTypes.STORE_UPDATE]({ state, dispatch }) {
[ActionTypes.STORE_UPDATE]({ state, dispatch }: APIActionContext): void {
state._Subscriptions.forEach(async (subscription_json) => {
const subscription = JSON.parse(subscription_json);
try {
Expand All @@ -322,7 +267,7 @@ export const actions: ActionTree<APIState, RootState> & Actions = {
}
});
},
[ActionTypes.UNSUBSCRIBE]({ commit }, subscription) {
[ActionTypes.UNSUBSCRIBE]({ commit }: APIActionContext, subscription: Subscription): void {
commit(MutationTypes.UNSUBSCRIBE, subscription);
},
};
Loading