Skip to content
This repository has been archived by the owner on Jun 28, 2021. It is now read-only.

chore: add typings to snxjs #485

Merged
merged 1 commit into from
Aug 5, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 4 additions & 4 deletions src/ducks/wallet/walletDetails.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import { LOCAL_STORAGE_KEYS } from 'constants/storage';

import { setSigner } from 'utils/snxJSConnector';
import { getAddress } from 'utils/formatters';
import { defaultNetwork } from 'utils/networkUtils';
import { defaultNetwork, NetworkId } from 'utils/networkUtils';
import { RootState } from 'ducks/types';

export type WalletDetailsSliceState = {
Expand All @@ -15,7 +15,7 @@ export type WalletDetailsSliceState = {
walletPaginatorIndex: number;
availableWallets: string[];
derivationPath: string | null;
networkId: number;
networkId: NetworkId;
networkName: string;
};

Expand Down Expand Up @@ -57,7 +57,7 @@ export const walletDetailsSlice = createSlice({
updateNetworkSettings: (
state,
action: PayloadAction<{
networkId: number;
networkId: NetworkId;
networkName: string;
}>
) => {
Expand All @@ -71,7 +71,7 @@ export const walletDetailsSlice = createSlice({
action: PayloadAction<{
signerOptions: {
type: string;
networkId: number;
networkId: NetworkId;
derivationPath: string;
networkName: string;
};
Expand Down
5 changes: 3 additions & 2 deletions src/pages/Synths/Overview/SynthInfo/SynthInfo.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -22,9 +22,10 @@ import { subtitleLargeCSS } from 'components/Typography/General';
import { getNetworkId } from 'ducks/wallet/walletDetails';
import { getEtherscanTokenLink } from 'utils/explorers';
import { getDecimalPlaces } from 'utils/formatters';
import { NetworkId } from 'utils/networkUtils';

type StateProps = {
networkId: number;
networkId: NetworkId;
};

type Props = {
Expand All @@ -47,8 +48,8 @@ export const SynthInfo: FC<SynthInfoProps> = ({ synth, networkId }) => {
const assetDesc = synth.desc.replace(/^Inverse /, '');
const assetSymbol = synth.desc !== synth.asset ? ` (${synth.asset})` : '';

// @ts-ignore
const { snxJS } = snxJSConnector;
// @ts-ignore
const contractAddress = snxJS[synth.name].contract.address;
evgenyboxer marked this conversation as resolved.
Show resolved Hide resolved

const synthSign = USD_SIGN;
Expand Down
5 changes: 3 additions & 2 deletions src/pages/Trade/components/OrderBookCard/TradeHistory.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import { connect } from 'react-redux';
import styled from 'styled-components';
import { useTranslation } from 'react-i18next';
import Tooltip from '@material-ui/core/Tooltip';
import { CellProps } from 'react-table';
evgenyboxer marked this conversation as resolved.
Show resolved Hide resolved

import { getNetworkId } from 'ducks/wallet/walletDetails';

Expand All @@ -26,10 +27,10 @@ import {
formatCurrency,
formatCurrencyWithSign,
} from 'utils/formatters';
import { CellProps } from 'react-table';
import { NetworkId } from 'utils/networkUtils';

type StateProps = {
networkId: number;
networkId: NetworkId;
};

type Props = {
Expand Down
1 change: 0 additions & 1 deletion src/typings/missing-types.d.ts
Original file line number Diff line number Diff line change
@@ -1,2 +1 @@
declare module 'synthetix-js';
evgenyboxer marked this conversation as resolved.
Show resolved Hide resolved
declare module 'synthetix-data';
78 changes: 78 additions & 0 deletions src/typings/synthetix-js.d.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,78 @@
declare module 'synthetix-js' {
import { JsonRpcSigner, Web3Provider } from 'ethers/providers';
import { ethers } from 'ethers';
import { BigNumberish } from 'ethers/utils';

export interface ContractSettings {
networkId: 1 | 3 | 4 | 42;
signer?: JsonRpcSignerWithNextAddress;
}

export type JsonRpcSignerWithNextAddress = JsonRpcSigner & {
getNextAddresses: () => Promise<string[]>;
};
export type Synths = {
name: string;
asset: string;
category: string;
sign: string;
desc: string;
aggregator?: string;
subclass?: string;
exchange?: string;
index?: { symbol: string; name: string; units: number }[];
inverted?: { entryPoint: number; upperLimit: number; lowerLimit: number };
}[];

export type Signers = {
Metamask: JsonRpcSignerWithNextAddress;
Ledger: JsonRpcSignerWithNextAddress;
Coinbase: JsonRpcSignerWithNextAddress;
WalletConnect: JsonRpcSignerWithNextAddress;
Portis: JsonRpcSignerWithNextAddress;
};

export class SynthetixJs {
constructor(contractSettings: ContractSettings);

contractSettings: {
synths: Synths;
signer: JsonRpcSignerWithNextAddress;
provider: Web3Provider;
};
utils: typeof ethers.utils;
ethers: { utils: typeof ethers.utils };
static signers: Signers;
binaryOptionsUtils: any;
Exchanger: {
feeRateForExchange: (
quoteCurrencyKey: string,
baseCurrencyKey: string
) => Promise<BigNumberish>;
maxSecsLeftInWaitingPeriod: (address: string, currencyKey: string) => Promise<BigNumberish>;
};
SystemStatus: {
synthSuspension: (
currencyKey: string
) => Promise<{
suspended: boolean;
}>;
};
Synthetix: {
contract: any;
exchange: (
quoteCurrencyKey: string,
amount: string,
baseCurrencyKey: string,
gasProps?: {
gasPrice: number;
gasLimit: number;
}
) => Promise<ethers.ContractTransaction>;
};
sUSD: {
contract: any;
approve: any;
};
evgenyboxer marked this conversation as resolved.
Show resolved Hide resolved
}
}
21 changes: 21 additions & 0 deletions src/typings/window.d.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
import { NetworkId } from 'utils/networkUtils';

declare global {
interface Window {
web3?: {
eth?: {
net: {
getId: () => NetworkId;
};
};
version: {
getNetwork(cb: (err: Error | undefined, networkId: string) => void): void;
network: NetworkId;
};
};
ethereum?: {
on: (event: string, cb: () => void) => void;
networkVersion: NetworkId;
};
}
}
64 changes: 43 additions & 21 deletions src/utils/networkUtils.js → src/utils/networkUtils.ts
Original file line number Diff line number Diff line change
@@ -1,16 +1,14 @@
import throttle from 'lodash/throttle';

export type NetworkId = 1 | 3 | 4 | 42;
Copy link
Contributor Author

Choose a reason for hiding this comment

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

now its easier to match for networkId, its not just a "number", rather it must be this ^

Choose a reason for hiding this comment

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

you could also make it an enum

Choose a reason for hiding this comment

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

where the name points to the number

Choose a reason for hiding this comment

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

maybe supported networks is just an enum?

Copy link
Contributor Author

Choose a reason for hiding this comment

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

let's grab it from snxjs when its there... agree, can be an enum.


export const GWEI_UNIT = 1000000000;

export const SUPPORTED_NETWORKS = {
export const SUPPORTED_NETWORKS: Record<NetworkId, string> = {
1: 'MAINNET',
3: 'ROPSTEN',
4: 'RINKEBY',
42: 'KOVAN',
MAINNET: 1,
ROPSTEN: 3,
RINKEBY: 4,
KOVAN: 42,
};

export const DEFAULT_GAS_LIMIT = {
Expand All @@ -25,7 +23,7 @@ export const DEFAULT_GAS_LIMIT = {

export const INFURA_PROJECT_ID = process.env.REACT_APP_INFURA_PROJECT_ID;

export const INFURA_JSON_RPC_URLS = {
export const INFURA_JSON_RPC_URLS: Record<NetworkId, string> = {
1: `https://mainnet.infura.io/v3/${INFURA_PROJECT_ID}`,
3: `https://ropsten.infura.io/v3/${INFURA_PROJECT_ID}`,
4: `https://rinkeby.infura.io/v3/${INFURA_PROJECT_ID}`,
Expand All @@ -34,7 +32,15 @@ export const INFURA_JSON_RPC_URLS = {

export const PORTIS_APP_ID = '26e198be-a8bb-4240-ad78-ae88579085bc';

export const SUPPORTED_WALLETS_MAP = {
export type WalletType =
| 'METAMASK'
| 'TREZOR'
| 'LEDGER'
| 'COINBASE'
| 'WALLET_CONNECT'
| 'PORTIS';

export const SUPPORTED_WALLETS_MAP: Record<WalletType, string> = {
METAMASK: 'Metamask',
TREZOR: 'Trezor',
LEDGER: 'Ledger',
Expand All @@ -44,24 +50,32 @@ export const SUPPORTED_WALLETS_MAP = {
};
export const SUPPORTED_WALLETS = Object.values(SUPPORTED_WALLETS_MAP);

export const hasWeb3 = () => {
return window.web3;
};
export const hasWeb3 = () => !!window.web3;

export const defaultNetwork = { name: 'MAINNET', networkId: 1 };
export const defaultNetwork: { name: string; networkId: NetworkId } = {
name: 'MAINNET',

Choose a reason for hiding this comment

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

should prob have an enum for the names here

Copy link
Contributor Author

Choose a reason for hiding this comment

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

yeah all of that stuff should be in the snxjs lib

networkId: 1,
};

export async function getEthereumNetwork() {
if (!window.web3) return defaultNetwork;
let networkId = 1;
if (!hasWeb3()) {
return defaultNetwork;
}

let networkId: NetworkId = 1;

try {
if (window.web3?.eth?.net) {
networkId = await window.web3.eth.net.getId();
return { name: SUPPORTED_NETWORKS[networkId], networkId: Number(networkId) };

return { name: SUPPORTED_NETWORKS[networkId], networkId: Number(networkId) as NetworkId };
} else if (window.web3?.version?.network) {
networkId = Number(window.web3.version.network);
networkId = Number(window.web3.version.network) as NetworkId;

return { name: SUPPORTED_NETWORKS[networkId], networkId };
} else if (window.ethereum?.networkVersion) {
networkId = Number(window.ethereum?.networkVersion);
networkId = Number(window.ethereum?.networkVersion) as NetworkId;

return { name: SUPPORTED_NETWORKS[networkId], networkId };
}
return defaultNetwork;
Expand All @@ -71,12 +85,20 @@ export async function getEthereumNetwork() {
}
}

export const getTransactionPrice = (gasPrice, gasLimit, ethPrice) => {
export const getTransactionPrice = (
gasPrice: number | null,
gasLimit: number | null,
ethPrice: number | null
) => {
if (!gasPrice || !gasLimit || !ethPrice) return 0;

Choose a reason for hiding this comment

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

should prob say gasPrice == null || gasLimit == null || ethPrice == null since it is either going to be null or a number. What if gasPrice is 0 though?

Copy link
Contributor Author

Choose a reason for hiding this comment

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

I actually didn't want to touch the actual logic since it worked, just added the types here. Falsy values should be fine here! 0,null,etc...all good - and if one of them is falsy, it should return 0. Because, the formula is

(gasPrice * ethPrice * gasLimit) / GWEI_UNIT


return (gasPrice * ethPrice * gasLimit) / GWEI_UNIT;
};

const getPriceLimit = (networkInfo, gasPriceLimit) => {
const getPriceLimit = (
networkInfo: { fast: number; average: number; safeLow: number },
gasPriceLimit: number
) => {
const fast = networkInfo.fast / 10;
const average = networkInfo.average / 10;
const slow = networkInfo.safeLow / 10;
Expand Down Expand Up @@ -113,16 +135,16 @@ export const getGasInfo = async () => {
}
};

export function onMetamaskAccountChange(cb) {
export function onMetamaskAccountChange(cb: () => void) {
if (!window.ethereum) return;
const listener = throttle(cb, 1000);
window.ethereum.on('accountsChanged', listener);
}

export function onMetamaskNetworkChange(cb) {
export function onMetamaskNetworkChange(cb: () => void) {
if (!window.ethereum) return;
const listener = throttle(cb, 1000);
window.ethereum.on('networkChanged', listener);
}

export const isMainNet = (networkId) => networkId === SUPPORTED_NETWORKS.MAINNET;
export const isMainNet = (networkId: NetworkId) => networkId === 1;
Copy link

@dvd-schwrtz dvd-schwrtz Aug 5, 2020

Choose a reason for hiding this comment

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

would be good to have Networks as an enum to make equality checks easier

Copy link
Contributor Author

Choose a reason for hiding this comment

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

happy to replace this when we switch to the new library (which has the networks, etc)

Loading