Skip to content
This repository has been archived by the owner on Oct 11, 2024. It is now read-only.

Commit

Permalink
Upgrade typescript, refactorings
Browse files Browse the repository at this point in the history
  • Loading branch information
DennisSimon committed Jul 11, 2022
1 parent 649fe18 commit d33da4d
Show file tree
Hide file tree
Showing 21 changed files with 102 additions and 60 deletions.
6 changes: 4 additions & 2 deletions ts/blockchain.ts
Original file line number Diff line number Diff line change
Expand Up @@ -579,7 +579,8 @@ export class Blockchain {
if (injectedProviderIfExists.enable !== undefined) {
try {
await injectedProviderIfExists.enable();
} catch (err) {
} catch (e) {
const err = utils.maybeWrapInError(e);
errorReporter.report(err);
}
}
Expand Down Expand Up @@ -917,7 +918,8 @@ export class Blockchain {
try {
const contractInstance = address === undefined ? await c.deployed() : await c.at(address);
return contractInstance;
} catch (err) {
} catch (e) {
const err = utils.maybeWrapInError(e);
const errMsg = `${err}`;
logUtils.log(`Notice: Error encountered: ${err} ${err.stack}`);
if (_.includes(errMsg, 'not been deployed to detected network')) {
Expand Down
3 changes: 2 additions & 1 deletion ts/components/eth_weth_conversion_button.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -106,7 +106,8 @@ export class EthWethConversionButton extends React.Component<
await this.props.refetchEthTokenStateAsync();
}
this.props.onConversionSuccessful();
} catch (err) {
} catch (e) {
const err = utils.maybeWrapInError(e);
const errMsg = `${err}`;
if (_.includes(errMsg, BlockchainCallErrs.UserHasNoAssociatedAddresses)) {
this.props.dispatcher.updateShouldBlockchainErrDialogBeOpen(true);
Expand Down
3 changes: 2 additions & 1 deletion ts/components/inputs/allowance_state_toggle.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -139,7 +139,8 @@ export class AllowanceStateToggle extends React.Component<AllowanceStateTogglePr
await this.props.blockchain.setProxyAllowanceAsync(this.props.token, newAllowanceAmountInBaseUnits);
analytics.track('Set Allowances Success', logData);
await this.props.refetchTokenStateAsync();
} catch (err) {
} catch (e) {
const err = utils.maybeWrapInError(e);
analytics.track('Set Allowance Failure', logData);
this.setState({
allowanceState: AllowanceStateToggle._getAllowanceState(this.state.prevTokenState),
Expand Down
4 changes: 3 additions & 1 deletion ts/components/newsletter_form.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import * as React from 'react';
import styled from 'styled-components';
import { fadeIn } from 'ts/style/keyframes';
import { errorReporter } from 'ts/utils/error_reporter';
import { utils } from 'ts/utils/utils';

interface IFormProps {
color?: string;
Expand Down Expand Up @@ -46,7 +47,8 @@ export const NewsletterForm: React.FC<IFormProps> = ({ color }) => {
method: 'POST',
});
} catch (e) {
errorReporter.report(e);
const err = utils.maybeWrapInError(e);
errorReporter.report(err);
}
};

Expand Down
6 changes: 4 additions & 2 deletions ts/components/relayer_index/relayer_index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import { RelayerGridTile, RelayerGridTileStyle } from 'ts/components/relayer_ind
import { Retry } from 'ts/components/ui/retry';
import { ScreenWidths, WebsiteBackendRelayerInfo } from 'ts/types';
import { backendClient } from 'ts/utils/backend_client';
import { utils } from 'ts/utils/utils';

export enum RelayerIndexCellStyle {
Expanded = 0,
Expand Down Expand Up @@ -104,10 +105,11 @@ export class RelayerIndex extends React.Component<RelayerIndexProps, RelayerInde
relayerInfos,
});
}
} catch (error) {
} catch (e) {
const err = utils.maybeWrapInError(e);
if (!this._isUnmounted) {
this.setState({
error,
error: err,
});
}
}
Expand Down
3 changes: 2 additions & 1 deletion ts/components/send_button.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -75,7 +75,8 @@ export class SendButton extends React.Component<SendButtonProps, SendButtonState
await this.props.blockchain.transferAsync(token, recipient, value);
await this.props.refetchTokenStateAsync(token.address);
}
} catch (err) {
} catch (e) {
const err = utils.maybeWrapInError(e);
const errMsg = `${err}`;
if (_.includes(errMsg, BlockchainCallErrs.UserHasNoAssociatedAddresses)) {
this.props.dispatcher.updateShouldBlockchainErrDialogBeOpen(true);
Expand Down
2 changes: 1 addition & 1 deletion ts/components/staking/add_pool_dialog.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ import styled from 'styled-components';
import { Button } from 'ts/components/button';
import { Icon } from 'ts/components/icon';
import { Input } from 'ts/components/modals/input';
import { Thumbnail } from 'ts/components/staking/thumbnail.tsx';
import { Thumbnail } from 'ts/components/staking/thumbnail';
import { Heading, Paragraph } from 'ts/components/text';

import { useSearch } from 'ts/hooks/use_search';
Expand Down
2 changes: 1 addition & 1 deletion ts/components/staking/change_pool_dialog.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ import styled from 'styled-components';
import { Button } from 'ts/components/button';
import { Icon } from 'ts/components/icon';
import { Input } from 'ts/components/modals/input';
import { Thumbnail } from 'ts/components/staking/thumbnail.tsx';
import { Thumbnail } from 'ts/components/staking/thumbnail';
import { Heading, Paragraph } from 'ts/components/text';

import { useSearch } from 'ts/hooks/use_search';
Expand Down
3 changes: 2 additions & 1 deletion ts/components/token_balances.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -475,7 +475,8 @@ export class TokenBalances extends React.Component<TokenBalancesProps, TokenBala
const amount = Web3Wrapper.toUnitAmount(constants.MINT_AMOUNT, token.decimals);
this.props.dispatcher.showFlashMessage(`Successfully minted ${amount.toString(10)} ${token.symbol}`);
return true;
} catch (err) {
} catch (e) {
const err = utils.maybeWrapInError(e);
const errMsg = `${err}`;
if (_.includes(errMsg, BlockchainCallErrs.UserHasNoAssociatedAddresses)) {
this.props.dispatcher.updateShouldBlockchainErrDialogBeOpen(true);
Expand Down
3 changes: 2 additions & 1 deletion ts/components/wallet/wrap_ether_item.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -201,7 +201,8 @@ export class WrapEtherItem extends React.Component<WrapEtherItemProps, WrapEther
}
await this.props.refetchEthTokenStateAsync();
this.props.onConversionSuccessful();
} catch (err) {
} catch (e) {
const err = utils.maybeWrapInError(e);
const errMsg = `${err}`;
if (_.includes(errMsg, BlockchainCallErrs.UserHasNoAssociatedAddresses)) {
this.props.dispatcher.updateShouldBlockchainErrDialogBeOpen(true);
Expand Down
3 changes: 2 additions & 1 deletion ts/pages/account/activity.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -183,7 +183,8 @@ export const AccountActivity: React.FC<ActivityProps> = () => {
try {
exportDataToCSVAndDownloadForUser(csvHeaders, delegatorHistory, 'staking_activity');
} catch (e) {
errorReporter.report(e);
const err = utils.maybeWrapInError(e);
errorReporter.report(err);
alert('Error exporting CSV.');
}
}}
Expand Down
60 changes: 30 additions & 30 deletions ts/pages/docs/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -49,51 +49,49 @@ export const DocsPage: React.FC<IDocsPageProps> = (props) => {
const { page, type, version } = props.match.params;
const { hash } = props.location;
// For api explorer / core-concepts the url does not include the page, i.e. it's only 'docs/core-concepts'
const key = page ? page : type;
// @ts-ignore
const pageMeta = meta[type] && meta[type][key];

if (!pageMeta) {
return <PageNotFound />;
}

const [state, setState] = React.useState<IDocsPageState>({
Component: '',
contents: [],
wasNotFound: false,
});
const key = page ? page : type;
// @ts-ignore
const pageMeta = meta[type] && meta[type][key];

const { Component, contents, wasNotFound } = state;

const { description, keywords, path, subtitle, title, versions } = pageMeta;

const isLoading = !Component;

// If the route path includes a version, replace the initial version on path
const filePath = versions && version ? path.replace(versions[0], version) : path;

React.useEffect(() => {
const loadPageAsync = async (_filePath: string) => {
try {
const component = await import(/* webpackChunkName: "mdx/[request]" */ `mdx/${_filePath}`);

setState({
...state,
Component: component.default,
contents: component.tableOfContents(),
});

if (hash) {
await waitForImages(); // images will push down content when loading, so we wait...
scrollToHash(hash); // ...and then scroll to hash when ready not to push the content down
}
} catch (error) {
setState({ ...state, wasNotFound: true });
}
};
void loadPageAsync(filePath);
}, [filePath]);

const loadPageAsync = async (_filePath: string) => {
try {
const component = await import(/* webpackChunkName: "mdx/[request]" */ `mdx/${_filePath}`);

setState({
...state,
Component: component.default,
contents: component.tableOfContents(),
});
}, [filePath, hash, state]);

if (hash) {
await waitForImages(); // images will push down content when loading, so we wait...
scrollToHash(hash); // ...and then scroll to hash when ready not to push the content down
}
} catch (error) {
setState({ ...state, wasNotFound: true });
}
};
if (!pageMeta) {
return <PageNotFound />;
}
// If the route path includes a version, replace the initial version on path

if (wasNotFound) {
return <PageNotFound />;
Expand Down Expand Up @@ -158,8 +156,10 @@ const waitForImages = async () => {
_.map(images, (img: HTMLImageElement) => {
if (!img.complete) {
// tslint:disable-next-line:no-inferred-empty-object-type
return new Promise((resolve) => {
img.addEventListener('load', () => resolve());
return new Promise<void>((resolve) => {
img.addEventListener('load', () => {
resolve();
});
});
}
return false;
Expand Down
12 changes: 8 additions & 4 deletions ts/pages/governance/vote_form.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ import { backendClient } from 'ts/utils/backend_client';
import { configs, GOVERNOR_CONTRACT_ADDRESS } from 'ts/utils/configs';
import { constants } from 'ts/utils/constants';
import { environments } from 'ts/utils/environments';
import { utils } from 'ts/utils/utils';

export enum VoteValue {
Yes = 'Yes',
Expand Down Expand Up @@ -252,7 +253,8 @@ class VoteFormComponent extends React.Component<Props> {
const errorMessage = responseBody.reason !== undefined ? responseBody.reason : 'Unknown Error';
this._handleError(errorMessage);
}
} catch (err) {
} catch (e) {
const err = utils.maybeWrapInError(e);
this._handleError(err.message);
}
};
Expand Down Expand Up @@ -307,8 +309,9 @@ class VoteFormComponent extends React.Component<Props> {
if (onTransactionSuccess) {
onTransactionSuccess();
}
} catch (error) {
this._handleError(error.message);
} catch (e) {
const err = utils.maybeWrapInError(e);
this._handleError(err.message);
}
};
private _handleError(errorMessage: string): void {
Expand All @@ -328,7 +331,8 @@ class VoteFormComponent extends React.Component<Props> {

try {
signatureHex = await this._eip712SignatureAsync(selectedAddress, typedData, web3Wrapper);
} catch (err) {
} catch (e) {
const err = utils.maybeWrapInError(e);
// HACK: We are unable to handle specific errors thrown since provider is not an object
// under our control. It could be Metamask Web3, Ethers, or any general RPC provider.
// We check for a user denying the signature request in a way that supports Metamask and
Expand Down
5 changes: 4 additions & 1 deletion ts/pages/staking/home.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ import { errorReporter } from 'ts/utils/error_reporter';
import { stakingUtils } from 'ts/utils/staking_utils';

import { AccountReady, Epoch, PoolsListSortingParameter, PoolWithStats, ScreenWidths, WebsitePaths } from 'ts/types';
import { utils } from 'ts/utils/utils';

const sortFnMapping: { [key: string]: (a: PoolWithStats, b: PoolWithStats) => number } = {
[PoolsListSortingParameter.Staked]: stakingUtils.sortByStakedDesc,
Expand Down Expand Up @@ -146,7 +147,9 @@ export const StakingIndex: React.FC<StakingIndexProps> = () => {
try {
const epochsResponse = await apiClient.getStakingEpochsAsync();
setNextEpochStats(epochsResponse.nextEpoch);
} catch (err) {
} catch (e) {
const err = utils.maybeWrapInError(e);

logUtils.warn(err);
setNextEpochStats(undefined);
errorReporter.report(err);
Expand Down
6 changes: 4 additions & 2 deletions ts/pages/staking/wizard/newsletter.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -16,8 +16,9 @@ import { State } from 'ts/redux/reducer';
import { AccountReady, WebsitePaths } from 'ts/types';

import { backendClient } from 'ts/utils/backend_client';
import { configs } from 'ts/utils/configs.ts';
import { configs } from 'ts/utils/configs';
import { errorReporter } from 'ts/utils/error_reporter';
import { utils } from 'ts/utils/utils';

const StyledHeading = styled(Heading)`
text-align: center;
Expand Down Expand Up @@ -136,7 +137,8 @@ export const Newsletter = () => {
list: configs.STAKING_UPDATES_NEWSLETTER_ID,
});
setHasSubmitted(true);
} catch (err) {
} catch (e) {
const err = utils.maybeWrapInError(e);
logUtils.warn(`Unable to register email to newsletter`, email, err);
errorReporter.report(err);
}
Expand Down
10 changes: 7 additions & 3 deletions ts/pages/staking/wizard/wizard.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,7 @@ import {
import { constants } from 'ts/utils/constants';
import { errorReporter } from 'ts/utils/error_reporter';
import { stakingUtils } from 'ts/utils/staking_utils';
import { utils } from 'ts/utils/utils';

export interface StakingWizardProps {
providerState: ProviderState;
Expand Down Expand Up @@ -104,7 +105,8 @@ export const StakingWizard: React.FC<StakingWizardProps> = (props) => {
setAllStakingPools(poolsResponse.stakingPools);
const activePools = (poolsResponse.stakingPools || []).filter(stakingUtils.isPoolActive);
setStakingPools(activePools);
} catch (err) {
} catch (e) {
const err = utils.maybeWrapInError(e);
logUtils.warn(err);
setAllStakingPools([]);
setStakingPools([]);
Expand All @@ -122,7 +124,8 @@ export const StakingWizard: React.FC<StakingWizardProps> = (props) => {
const epochsResponse = await apiClient.getStakingEpochsAsync();
setCurrentEpochStats(epochsResponse.currentEpoch);
setNextEpochStats(epochsResponse.nextEpoch);
} catch (err) {
} catch (e) {
const err = utils.maybeWrapInError(e);
logUtils.warn(err);
setCurrentEpochStats(undefined);
setNextEpochStats(undefined);
Expand All @@ -138,7 +141,8 @@ export const StakingWizard: React.FC<StakingWizardProps> = (props) => {
try {
const stats = await apiClient.getStakingStatsAsync();
setAllTimeStats(stats.allTime);
} catch (err) {
} catch (e) {
const err = utils.maybeWrapInError(e);
logUtils.warn(err);
setAllTimeStats(undefined);
errorReporter.report(err);
Expand Down
4 changes: 3 additions & 1 deletion ts/redux/async_dispatcher.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import * as _ from 'lodash';
import { Dispatcher } from 'ts/redux/dispatcher';
import { AccountState, Network, ProviderState } from 'ts/types';
import { errorReporter } from 'ts/utils/error_reporter';
import { utils } from 'ts/utils/utils';

// NOTE: Copied from Instant
export const asyncDispatcher = {
Expand Down Expand Up @@ -68,7 +69,8 @@ export const asyncDispatcher = {
dispatcher.updateAccountEthBalance({ address, ethBalanceInWei });
dispatcher.updateAccountZrxBalance(zrxBalance);
dispatcher.updateAccountZrxAllowance(zrxAllowance);
} catch (err) {
} catch (e) {
const err = utils.maybeWrapInError(e);
logUtils.warn(err);
errorReporter.report(err);
return;
Expand Down
10 changes: 5 additions & 5 deletions ts/style/dimensions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,10 +23,10 @@ function getDimensionObject(node: HTMLElement): DimensionObject {
return {
width: rect.width,
height: rect.height,
top: 'x' in rect ? rect.x : (rect as DOMRect).top,
left: 'y' in rect ? rect.y : (rect as DOMRect).left,
x: 'x' in rect ? rect.x : (rect as DOMRect).left,
y: 'y' in rect ? rect.y : (rect as DOMRect).top,
top: 'x' in rect ? rect.x : rect.top,
left: 'y' in rect ? rect.y : rect.left,
x: 'x' in rect ? rect.x : rect.left,
y: 'y' in rect ? rect.y : rect.top,
right: rect.right,
bottom: rect.bottom,
};
Expand Down Expand Up @@ -57,7 +57,7 @@ export function useDimensions({ isLiveMeasure = true }: UseDimensionsArgs = {}):
return undefined;
}
return undefined;
}, [node]);
}, [isLiveMeasure, node]);

return [ref, dimensions, node];
}
6 changes: 6 additions & 0 deletions ts/utils/csv_export_utils.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,9 @@
declare global {
interface Navigator {
msSaveBlob?: (blob: any, defaultName?: string) => boolean;
}
}

function convertToCSV(headers: string[], objArray: Array<{ [key: string]: any }>): string {
let str = `${headers.join('\t')}\r\n`;

Expand Down
Loading

1 comment on commit d33da4d

@vercel
Copy link

@vercel vercel bot commented on d33da4d Jul 11, 2022

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please sign in to comment.