diff --git a/.eslintignore b/.eslintignore new file mode 100644 index 0000000000..b6f5271476 --- /dev/null +++ b/.eslintignore @@ -0,0 +1,3 @@ +**/build/* +**/coverage/* +**/node_modules/* diff --git a/.eslintrc.js b/.eslintrc.js new file mode 100644 index 0000000000..af345b9b5d --- /dev/null +++ b/.eslintrc.js @@ -0,0 +1,10 @@ +const base = require('@polkadot/dev-react/config/eslint'); + +// add override for any (a metric ton of them, initial conversion) +module.exports = { + ...base, + rules: { + ...base.rules, + '@typescript-eslint/no-explicit-any': 'off' + } +}; diff --git a/jest.config.js b/jest.config.js index e196d87fd5..643163e06d 100644 --- a/jest.config.js +++ b/jest.config.js @@ -1,3 +1,4 @@ +/* eslint-disable @typescript-eslint/no-var-requires */ const config = require('@polkadot/dev-react/config/jest'); const findPackages = require('./scripts/findPackages'); diff --git a/package.json b/package.json index de4171caca..9fc1c5318f 100644 --- a/package.json +++ b/package.json @@ -24,8 +24,9 @@ "analyze": "yarn run build && cd packages/apps && yarn run source-map-explorer build/main.*.js", "build": "NODE_ENV=production polkadot-dev-build-ts", "check": "yarn lint", - "lint": "tslint --project . && tsc --noEmit --pretty", "clean": "polkadot-dev-clean-build", + "lint": "tslint --project . && tsc --noEmit --pretty", + "lint:new": "eslint --ext .js,.jsx,.ts,.tsx . && tsc --noEmit --pretty", "postinstall": "polkadot-dev-yarn-only", "test": "echo \"skipping tests\"", "vanitygen": "node packages/app-accounts/scripts/vanitygen.js", diff --git a/packages/app-123code/src/AccountSelector.tsx b/packages/app-123code/src/AccountSelector.tsx index 81ab06583d..64de963fc0 100644 --- a/packages/app-123code/src/AccountSelector.tsx +++ b/packages/app-123code/src/AccountSelector.tsx @@ -7,19 +7,19 @@ import styled from 'styled-components'; import { Bubble, InputAddress } from '@polkadot/ui-app'; import { AccountIndex, Balance, Nonce } from '@polkadot/ui-reactive'; -type Props = { - className?: string, - onChange: (accountId?: string) => void -}; +interface Props { + className?: string; + onChange: (accountId?: string) => void; +} -type State = { - accountId?: string -}; +interface State { + accountId?: string; +} class AccountSelector extends React.PureComponent { - state: State = {}; + public state: State = {}; - render () { + public render (): React.ReactNode { const { className } = this.props; const { accountId } = this.state; @@ -49,7 +49,7 @@ class AccountSelector extends React.PureComponent { private onChange = (accountId?: string): void => { const { onChange } = this.props; - this.setState({ accountId }, () => + this.setState({ accountId }, (): void => onChange(accountId) ); } diff --git a/packages/app-123code/src/Summary.tsx b/packages/app-123code/src/Summary.tsx index bdb10625b0..7ddc0cc614 100644 --- a/packages/app-123code/src/Summary.tsx +++ b/packages/app-123code/src/Summary.tsx @@ -7,12 +7,12 @@ import { BareProps } from '@polkadot/ui-app/types'; import React from 'react'; import styled from 'styled-components'; -type Props = BareProps & { - children: React.ReactNode -}; +interface Props extends BareProps { + children: React.ReactNode; +} class Summary extends React.PureComponent { - render () { + public render (): React.ReactNode { const { children, className, style } = this.props; return ( diff --git a/packages/app-123code/src/SummaryBar.tsx b/packages/app-123code/src/SummaryBar.tsx index e82244fe55..15294a412e 100644 --- a/packages/app-123code/src/SummaryBar.tsx +++ b/packages/app-123code/src/SummaryBar.tsx @@ -1,3 +1,4 @@ +/* eslint-disable @typescript-eslint/camelcase */ // Copyright 2017-2019 @polkadot/app-123code authors & contributors // This software may be modified and distributed under the terms // of the Apache-2.0 license. See the LICENSE file for details. @@ -15,38 +16,40 @@ import { formatBalance, formatNumber } from '@polkadot/util'; import translate from './translate'; type Props = ApiProps & BareProps & I18nProps & { - balances_totalIssuance?: BN, - chain_bestNumber?: BN, - chain_bestNumberLag?: BN, - chain_getRuntimeVersion?: RuntimeVersion, - session_validators?: Array, - staking_intentions?: Array, - system_chain?: string, - system_name?: string, - system_version?: string -}; -type State = { - nextUp: Array + balances_totalIssuance?: BN; + chain_bestNumber?: BN; + chain_bestNumberLag?: BN; + chain_getRuntimeVersion?: RuntimeVersion; + session_validators?: AccountId[]; + staking_intentions?: AccountId[]; + system_chain?: string; + system_name?: string; + system_version?: string; }; +interface State { + nextUp: AccountId[]; +} class SummaryBar extends React.PureComponent { - state: State = { + public state: State = { nextUp: [] }; - static getDerivedStateFromProps ({ staking_intentions, session_validators }: Props): State | null { + public static getDerivedStateFromProps ({ staking_intentions, session_validators }: Props): State | null { if (!staking_intentions || !session_validators) { return null; } return { - nextUp: staking_intentions.filter((accountId) => - !session_validators.find((validatorId) => validatorId.eq(accountId)) + nextUp: staking_intentions.filter((accountId): boolean => + !session_validators.find((validatorId): boolean => + validatorId.eq(accountId) + ) ) }; } - render () { + public render (): React.ReactNode { const { balances_totalIssuance, chain_bestNumber, chain_bestNumberLag, chain_getRuntimeVersion, session_validators = [], system_chain, system_name, system_version } = this.props; const { nextUp } = this.state; @@ -68,12 +71,12 @@ class SummaryBar extends React.PureComponent { {formatNumber(chain_bestNumber)} ({formatNumber(chain_bestNumberLag)} lag) { - session_validators.map((accountId, index) => ( + session_validators.map((accountId, index): React.ReactNode => ( )) } { - nextUp.map((accountId, index) => ( + nextUp.map((accountId, index): React.ReactNode => ( )) } diff --git a/packages/app-123code/src/Transfer.tsx b/packages/app-123code/src/Transfer.tsx index c618e1c776..9d5a8071a5 100644 --- a/packages/app-123code/src/Transfer.tsx +++ b/packages/app-123code/src/Transfer.tsx @@ -8,18 +8,18 @@ import { Button, InputAddress, InputBalance, TxButton, TxComponent } from '@polk import Summary from './Summary'; -type Props = { - accountId?: string -}; -type State = { +interface Props { + accountId?: string; +} +interface State { amount?: BN; recipientId?: string; -}; +} export default class Transfer extends TxComponent { - state: State = {}; + public state: State = {}; - render () { + public render (): React.ReactNode { const { accountId } = this.props; const { amount, recipientId } = this.state; diff --git a/packages/app-123code/src/index.tsx b/packages/app-123code/src/index.tsx index 7e56354c77..15798477e4 100644 --- a/packages/app-123code/src/index.tsx +++ b/packages/app-123code/src/index.tsx @@ -20,14 +20,14 @@ import translate from './translate'; // define out internal types type Props = AppProps & I18nProps; -type State = { - accountId?: string -}; +interface State { + accountId?: string; +} class App extends React.PureComponent { - state: State = {}; + public state: State = {}; - render () { + public render (): React.ReactNode { const { accountId } = this.state; return ( diff --git a/packages/app-accounts/scripts/vanitygen.js b/packages/app-accounts/scripts/vanitygen.js index 208cb4176c..72f1998ae4 100755 --- a/packages/app-accounts/scripts/vanitygen.js +++ b/packages/app-accounts/scripts/vanitygen.js @@ -1,4 +1,5 @@ #!/usr/bin/env node +/* eslint-disable @typescript-eslint/no-var-requires */ // Copyright 2017-2019 @polkadot/app-accounts authors & contributors // This software may be modified and distributed under the terms // of the Apache-2.0 license. See the LICENSE file for details. diff --git a/packages/app-accounts/src/Account.tsx b/packages/app-accounts/src/Account.tsx index 2096b93b45..ff5d55ba67 100644 --- a/packages/app-accounts/src/Account.tsx +++ b/packages/app-accounts/src/Account.tsx @@ -15,22 +15,22 @@ import Transfer from './modals/Transfer'; import translate from './translate'; -type Props = I18nProps & { - address: string -}; +interface Props extends I18nProps { + address: string; +} -type State = { - isBackupOpen: boolean, - isEditable: boolean, - isForgetOpen: boolean, - isPasswordOpen: boolean, - isTransferOpen: boolean -}; +interface State { + isBackupOpen: boolean; + isEditable: boolean; + isForgetOpen: boolean; + isPasswordOpen: boolean; + isTransferOpen: boolean; +} class Account extends React.PureComponent { - state: State; + public state: State; - constructor (props: Props) { + public constructor (props: Props) { super(props); const account = keyring.getAccount(props.address); @@ -46,7 +46,7 @@ class Account extends React.PureComponent { }; } - render () { + public render (): React.ReactNode { const { address } = this.props; const { isEditable } = this.state; @@ -72,7 +72,7 @@ class Account extends React.PureComponent { ); } - private renderModals () { + private renderModals (): React.ReactNode { const { address } = this.props; const { isBackupOpen, isForgetOpen, isPasswordOpen, isTransferOpen } = this.state; @@ -165,10 +165,10 @@ class Account extends React.PureComponent { return; } - const status = { + const status: Partial = { account: address, action: 'forget' - } as ActionStatus; + }; try { keyring.forgetAccount(address); @@ -180,7 +180,7 @@ class Account extends React.PureComponent { } } - private renderButtons () { + private renderButtons (): React.ReactNode { const { t } = this.props; const { isEditable } = this.state; diff --git a/packages/app-accounts/src/Overview.tsx b/packages/app-accounts/src/Overview.tsx index b895193e51..eaca80e037 100644 --- a/packages/app-accounts/src/Overview.tsx +++ b/packages/app-accounts/src/Overview.tsx @@ -17,19 +17,19 @@ import Account from './Account'; import translate from './translate'; type Props = ComponentProps & I18nProps & { - accounts?: SubjectInfo[] + accounts?: SubjectInfo[]; }; -type State = { - isCreateOpen: boolean, - isImportOpen: boolean -}; +interface State { + isCreateOpen: boolean; + isImportOpen: boolean; +} class Overview extends React.PureComponent { - constructor (props: Props) { + public constructor (props: Props) { super(props); - const { state : { isCreateOpen = false } = {} } = this.props.location; + const { state: { isCreateOpen = false } = {} } = this.props.location; this.state = { isCreateOpen, @@ -37,7 +37,7 @@ class Overview extends React.PureComponent { }; } - render () { + public render (): React.ReactNode { const { accounts, t } = this.props; const { isCreateOpen, isImportOpen } = this.state; const emptyScreen = !isCreateOpen && !isImportOpen && (!accounts || Object.keys(accounts).length === 0); @@ -64,7 +64,7 @@ class Overview extends React.PureComponent { > {this.renderCreate()} {this.renderImport()} - {accounts && Object.keys(accounts).map((address) => ( + {accounts && Object.keys(accounts).map((address): React.ReactNode => ( { ); } - private renderCreate () { + private renderCreate (): React.ReactNode { const { isCreateOpen } = this.state; const { onStatusChange } = this.props; @@ -90,7 +90,7 @@ class Overview extends React.PureComponent { ); } - private renderImport () { + private renderImport (): React.ReactNode { const { isImportOpen } = this.state; const { onStatusChange } = this.props; @@ -107,15 +107,15 @@ class Overview extends React.PureComponent { } private toggleCreate = (): void => { - this.setState(({ isCreateOpen }) => ({ + this.setState(({ isCreateOpen }): State => ({ isCreateOpen: !isCreateOpen - })); + }) as unknown as State); } private toggleImport = (): void => { - this.setState(({ isImportOpen }) => ({ + this.setState(({ isImportOpen }): State => ({ isImportOpen: !isImportOpen - })); + }) as unknown as State); } } diff --git a/packages/app-accounts/src/Vanity/Match.tsx b/packages/app-accounts/src/Vanity/Match.tsx index 20fcf8e64f..a878acaa2c 100644 --- a/packages/app-accounts/src/Vanity/Match.tsx +++ b/packages/app-accounts/src/Vanity/Match.tsx @@ -9,29 +9,29 @@ import styled from 'styled-components'; import { Button, IdentityIcon } from '@polkadot/ui-app'; import { u8aToHex } from '@polkadot/util'; -type Props = BareProps & { +interface Props extends BareProps { address: string; count: number; offset: number; - onCreateToggle: (seed: string) => void, - onRemove: (address: string) => void, + onCreateToggle: (seed: string) => void; + onRemove: (address: string) => void; seed: Uint8Array; -}; +} -type State = { - hexSeed: string -}; +interface State { + hexSeed: string; +} class Match extends React.PureComponent { - state: State = {} as State; + public state: State = { hexSeed: '' }; - static getDerivedStateFromProps ({ seed }: Props): State { + public static getDerivedStateFromProps ({ seed }: Props): State { return { hexSeed: u8aToHex(seed) }; } - render () { + public render (): React.ReactNode { const { address, className, count, offset } = this.props; const { hexSeed } = this.state; diff --git a/packages/app-accounts/src/Vanity/index.tsx b/packages/app-accounts/src/Vanity/index.tsx index f974719824..74113d5506 100644 --- a/packages/app-accounts/src/Vanity/index.tsx +++ b/packages/app-accounts/src/Vanity/index.tsx @@ -4,7 +4,7 @@ import { I18nProps } from '@polkadot/ui-app/types'; import { KeypairType } from '@polkadot/util-crypto/types'; -import { Generator$Matches, Generator$Result } from '../vanitygen/types'; +import { GeneratorMatches, GeneratorMatch, GeneratorResult } from '../vanitygen/types'; import { ComponentProps } from '../types'; import React from 'react'; @@ -29,7 +29,7 @@ interface State { keyCount: 0; keyTime: 0; match: string; - matches: Generator$Matches; + matches: GeneratorMatches; startAt: number; type: KeypairType; withCase: boolean; @@ -43,7 +43,8 @@ const BOOL_OPTIONS = [ ]; class VanityApp extends TxComponent { - private results: Generator$Result[] = []; + private results: GeneratorResult[] = []; + public state: State = { createSeed: null, elapsed: 0, @@ -61,7 +62,7 @@ class VanityApp extends TxComponent { private _isActive: boolean = false; - componentWillUnmount () { + public componentWillUnmount (): void { this._isActive = false; } @@ -87,7 +88,7 @@ class VanityApp extends TxComponent { ); } - private renderButtons () { + private renderButtons (): React.ReactNode { const { t } = this.props; const { isMatchValid, isRunning } = this.state; @@ -108,12 +109,12 @@ class VanityApp extends TxComponent { ); } - private renderMatches () { + private renderMatches (): React.ReactNode { const { matches } = this.state; return (
- {matches.map((match) => ( + {matches.map((match): React.ReactNode => ( { ); } - private renderOptions () { + private renderOptions (): React.ReactNode { const { t } = this.props; const { isMatchValid, isRunning, match, type, withCase } = this.state; @@ -167,7 +168,7 @@ class VanityApp extends TxComponent { ); } - private renderStats () { + private renderStats (): React.ReactNode { const { t } = this.props; const { elapsed, keyCount } = this.state; @@ -204,7 +205,7 @@ class VanityApp extends TxComponent { let newKeyCount = keyCount; let newKeyTime = keyTime; const newMatches = results - .reduce((result, { elapsed, found }) => { + .reduce((result, { elapsed, found }): GeneratorMatch[] => { newKeyCount += found.length; newKeyTime += elapsed; @@ -231,7 +232,7 @@ class VanityApp extends TxComponent { return; } - setTimeout(() => { + setTimeout((): void => { if (this._isActive) { if (this.results.length === 25) { this.checkMatches(); @@ -254,7 +255,7 @@ class VanityApp extends TxComponent { }, 0); } - private onCreateToggle = (createSeed: string) => { + private onCreateToggle = (createSeed: string): void => { this.setState({ createSeed }); } @@ -273,13 +274,13 @@ class VanityApp extends TxComponent { } private onChangeType = (type: KeypairType): void => { - this.setState({ type } as State); + this.setState({ type }); } private onRemove = (address: string): void => { this.setState( ({ matches }: State) => ({ - matches: matches.filter((item) => + matches: matches.filter((item): boolean => item.address !== address ) }) @@ -302,7 +303,7 @@ class VanityApp extends TxComponent { ); } - private closeCreate = () => { + private closeCreate = (): void => { this.setState({ createSeed: null }); } } diff --git a/packages/app-accounts/src/bipWorker.ts b/packages/app-accounts/src/bipWorker.ts index 82e31b6ef2..a4bf5c1ac0 100644 --- a/packages/app-accounts/src/bipWorker.ts +++ b/packages/app-accounts/src/bipWorker.ts @@ -4,13 +4,13 @@ import { cryptoWaitReady, mnemonicGenerate, mnemonicToMiniSecret, naclKeypairFromSeed, schnorrkelKeypairFromSeed } from '@polkadot/util-crypto'; -const ctx: Worker = self as any; +const ctx: Worker = self as unknown as Worker; -cryptoWaitReady().catch(() => { +cryptoWaitReady().catch((): void => { // ignore }); -ctx.onmessage = async ({ data: { pairType } }) => { +ctx.onmessage = async ({ data: { pairType } }): Promise => { await cryptoWaitReady(); const seed = mnemonicGenerate(); diff --git a/packages/app-accounts/src/index.tsx b/packages/app-accounts/src/index.tsx index cde9d3465d..754a95a739 100644 --- a/packages/app-accounts/src/index.tsx +++ b/packages/app-accounts/src/index.tsx @@ -19,18 +19,18 @@ import translate from './translate'; import Vanity from './Vanity'; type Props = AppProps & I18nProps & { - allAccounts?: SubjectInfo + allAccounts?: SubjectInfo; }; -type State = { - hidden: Array, - tabs: Array -}; +interface State { + hidden: string[]; + tabs: TabItem[]; +} class AccountsApp extends React.PureComponent { - state: State; + public state: State; - constructor (props: Props) { + public constructor (props: Props) { super(props); const { allAccounts = {}, t } = props; @@ -39,7 +39,7 @@ class AccountsApp extends React.PureComponent { : AccountsApp.hideTabsState(); this.state = { - ...baseState, + ...(baseState as State), tabs: [ { isRoot: true, @@ -54,14 +54,13 @@ class AccountsApp extends React.PureComponent { }; } - static showTabsState () { - + private static showTabsState (): Partial { return { - hidden: [] + hidden: [] as string[] }; } - static hideTabsState () { + private static hideTabsState (): Partial { // Hide vanity as well - since the route order and matching changes, the // /create/:seed route become problematic, so don't allow that option return { @@ -69,21 +68,21 @@ class AccountsApp extends React.PureComponent { }; } - static getDerivedStateFromProps ({ allAccounts = {} }: Props, { hidden }: State) { + public static getDerivedStateFromProps ({ allAccounts = {} }: Props, { hidden }: State): State | null { const hasAddresses = Object.keys(allAccounts).length !== 0; if (hidden.length === 0) { return hasAddresses ? null - : AccountsApp.hideTabsState(); + : AccountsApp.hideTabsState() as State; } return hasAddresses - ? AccountsApp.showTabsState() + ? AccountsApp.showTabsState() as State : null; } - render () { + public render (): React.ReactNode { const { basePath } = this.props; const { hidden, tabs } = this.state; @@ -105,8 +104,8 @@ class AccountsApp extends React.PureComponent { ); } - private renderComponent (Component: React.ComponentType) { - return ({ match }: LocationProps) => { + private renderComponent (Component: React.ComponentType): (props: LocationProps) => React.ReactNode { + return ({ match }: LocationProps): React.ReactNode => { const { basePath, location, onStatusChange } = this.props; return ( diff --git a/packages/app-accounts/src/modals/Backup.tsx b/packages/app-accounts/src/modals/Backup.tsx index c003729479..5bd9102647 100644 --- a/packages/app-accounts/src/modals/Backup.tsx +++ b/packages/app-accounts/src/modals/Backup.tsx @@ -12,23 +12,23 @@ import keyring from '@polkadot/ui-keyring'; import translate from '../translate'; -type Props = I18nProps & { - onClose: () => void, - address: string -}; +interface Props extends I18nProps { + onClose: () => void; + address: string; +} -type State = { - isPassValid: boolean, - password: string -}; +interface State { + isPassValid: boolean; + password: string; +} class Backup extends TxComponent { - state: State = { + public state: State = { isPassValid: false, password: '' }; - render () { + public render (): React.ReactNode { const { t } = this.props; return ( @@ -44,7 +44,7 @@ class Backup extends TxComponent { ); } - private renderButtons () { + private renderButtons (): React.ReactNode { const { onClose, t } = this.props; const { isPassValid } = this.state; @@ -69,7 +69,7 @@ class Backup extends TxComponent { ); } - private renderContent () { + private renderContent (): React.ReactNode { const { address, t } = this.props; const { isPassValid, password } = this.state; @@ -105,9 +105,9 @@ class Backup extends TxComponent { return; } - const status = { + const status: Partial = { action: 'backup' - } as ActionStatus; + }; try { const addressKeyring = address && keyring.getPair(address); @@ -131,7 +131,7 @@ class Backup extends TxComponent { onClose(); } - private onChangePass = (password: string) => { + private onChangePass = (password: string): void => { this.setState({ isPassValid: keyring.isPassValid(password), password diff --git a/packages/app-accounts/src/modals/ChangePass.tsx b/packages/app-accounts/src/modals/ChangePass.tsx index a73ef86dfa..704f3b14ab 100644 --- a/packages/app-accounts/src/modals/ChangePass.tsx +++ b/packages/app-accounts/src/modals/ChangePass.tsx @@ -11,27 +11,27 @@ import keyring from '@polkadot/ui-keyring'; import translate from '../translate'; -type Props = I18nProps & { - address: string, - onClose: () => void -}; +interface Props extends I18nProps { + address: string; + onClose: () => void; +} -type State = { - isNewValid: boolean, - isOldValid: boolean, - newPass: string, - oldPass: string -}; +interface State { + isNewValid: boolean; + isOldValid: boolean; + newPass: string; + oldPass: string; +} class ChangePass extends TxComponent { - state: State = { + public state: State = { isNewValid: false, isOldValid: false, newPass: '', oldPass: '' }; - render () { + public render (): React.ReactNode { const { t } = this.props; return ( @@ -47,7 +47,7 @@ class ChangePass extends TxComponent { ); } - private renderButtons () { + private renderButtons (): React.ReactNode { const { onClose, t } = this.props; const { isNewValid, isOldValid } = this.state; @@ -72,7 +72,7 @@ class ChangePass extends TxComponent { ); } - private renderContent () { + private renderContent (): React.ReactNode { const { address, t } = this.props; const { isNewValid, isOldValid, newPass, oldPass } = this.state; @@ -111,9 +111,9 @@ class ChangePass extends TxComponent { private doChange = (): void => { const { address, onClose, t } = this.props; const { newPass, oldPass } = this.state; - const status = { + const status: Partial = { action: 'changePassword' - } as ActionStatus; + }; try { const account = address && keyring.getPair(address); @@ -158,14 +158,14 @@ class ChangePass extends TxComponent { onClose(); } - private onChangeNew = (newPass: string) => { + private onChangeNew = (newPass: string): void => { this.setState({ isNewValid: this.validatePass(newPass), newPass }); } - private onChangeOld = (oldPass: string) => { + private onChangeOld = (oldPass: string): void => { this.setState({ isOldValid: this.validatePass(oldPass), oldPass @@ -173,7 +173,6 @@ class ChangePass extends TxComponent { } private validatePass (password: string): boolean { - return keyring.isPassValid(password); } } diff --git a/packages/app-accounts/src/modals/Create.tsx b/packages/app-accounts/src/modals/Create.tsx index 0732d8bdf2..0228bf3652 100644 --- a/packages/app-accounts/src/modals/Create.tsx +++ b/packages/app-accounts/src/modals/Create.tsx @@ -23,34 +23,34 @@ import { keyExtractPath, mnemonicGenerate, mnemonicValidate, randomAsU8a } from import translate from '../translate'; type Props = ModalProps & ApiProps & I18nProps & { - seed?: string, - type?: KeypairType + seed?: string; + type?: KeypairType; }; type SeedType = 'bip' | 'raw' | 'dev'; -type SeedOption = { - text: string, - value: SeedType -}; +interface SeedOption { + text: string; + value: SeedType; +} -type State = { - address: string, - deriveError: string | null, - derivePath: string, - isNameValid: boolean, - isSeedValid: boolean, - isPassValid: boolean, - isValid: boolean, - name: string, - pairType: KeypairType, - password: string, - seed: string, - seedOptions: Array, - seedType: SeedType, - showWarning: boolean, - tags: Array -}; +interface State { + address: string; + deriveError: string | null; + derivePath: string; + isNameValid: boolean; + isSeedValid: boolean; + isPassValid: boolean; + isValid: boolean; + name: string; + pairType: KeypairType; + password: string; + seed: string; + seedOptions: SeedOption[]; + seedType: SeedType; + showWarning: boolean; + tags: string[]; +} const DEFAULT_TYPE = 'sr25519'; @@ -60,7 +60,7 @@ function deriveValidate (derivePath: string, pairType: KeypairType): string | nu // we don't allow soft for ed25519 if (pairType === 'ed25519') { - const firstSoft = path.find(({ isSoft }) => isSoft); + const firstSoft = path.find(({ isSoft }): boolean => isSoft); if (firstSoft) { return 'Soft derivation paths are not allowed on ed25519'; @@ -88,13 +88,13 @@ function addressFromSeed (phrase: string, derivePath: string, pairType: KeypairT } class Create extends React.PureComponent { - state: State = { seedType: 'bip' } as State; + public state: State; - constructor (props: Props) { + public constructor (props: Props) { super(props); const { isDevelopment, seed, t, type } = this.props; - const seedOptions: Array = [ + const seedOptions: SeedOption[] = [ { value: 'bip', text: t('Mnemonic') }, { value: 'raw', text: t('Raw seed') } ]; @@ -104,12 +104,12 @@ class Create extends React.PureComponent { } this.state = { - ...this.emptyState(seed || null, '', type || DEFAULT_TYPE), + ...(this.emptyState(seed || null, '', type || DEFAULT_TYPE) as State), seedOptions }; } - render () { + public render (): React.ReactNode { const { className, t } = this.props; return ( @@ -126,7 +126,7 @@ class Create extends React.PureComponent { ); } - private renderButtons () { + private renderButtons (): React.ReactNode { const { t } = this.props; const { isValid } = this.state; @@ -149,11 +149,11 @@ class Create extends React.PureComponent { ); } - private renderInput () { + private renderInput (): React.ReactNode { const { t } = this.props; const { address, deriveError, derivePath, isNameValid, isPassValid, isSeedValid, name, pairType, password, seed, seedOptions, seedType } = this.state; const isDevSeed = seedType === 'dev'; - const seedLabel = (() => { + const seedLabel = ((): string => { switch (seedType) { case 'bip': return t('mnemonic seed'); @@ -239,7 +239,7 @@ class Create extends React.PureComponent { ); } - private renderModal () { + private renderModal (): React.ReactNode { const { t } = this.props; const { address, name, showWarning } = this.state; @@ -280,8 +280,8 @@ class Create extends React.PureComponent { ); } - private generateSeed (_seed: string | null, derivePath: string, seedType: SeedType, pairType: KeypairType): State { - const seed = (() => { + private generateSeed (_seed: string | null, derivePath: string, seedType: SeedType, pairType: KeypairType): Partial { + const seed = ((): string => { switch (seedType) { case 'bip': return mnemonicGenerate(); @@ -298,13 +298,13 @@ class Create extends React.PureComponent { deriveError: null, derivePath, seed - } as State; + }; } - private emptyState (seed: string | null, derivePath: string, pairType: KeypairType): State { + private emptyState (seed: string | null, derivePath: string, pairType: KeypairType): Partial { const seedType = seed ? 'raw' - : this.state.seedType; + : this.state ? this.state.seedType : 'bip'; return { ...this.generateSeed(seed, derivePath, seedType, pairType), @@ -321,7 +321,7 @@ class Create extends React.PureComponent { }; } - private nextState (newState: State): void { + private nextState (newState: Partial): void { this.setState( (prevState: State): State => { const { derivePath = prevState.derivePath, name = prevState.name, pairType = prevState.pairType, password = prevState.password, seed = prevState.seed, seedOptions = prevState.seedOptions, seedType = prevState.seedType, showWarning = prevState.showWarning, tags = prevState.tags } = newState; @@ -363,37 +363,37 @@ class Create extends React.PureComponent { } private onChangeDerive = (derivePath: string): void => { - this.nextState({ derivePath } as State); + this.nextState({ derivePath }); } private onChangeName = (name: string): void => { - this.nextState({ name } as State); + this.nextState({ name }); } private onChangePairType = (pairType: KeypairType): void => { - this.nextState({ pairType } as State); + this.nextState({ pairType }); } private onChangePass = (password: string): void => { - this.nextState({ password } as State); + this.nextState({ password }); } private onChangeSeed = (seed: string): void => { - this.nextState({ seed } as State); + this.nextState({ seed }); } private onShowWarning = (): void => { - this.nextState({ showWarning: true } as State); + this.nextState({ showWarning: true }); } private onHideWarning = (): void => { - this.nextState({ showWarning: false } as State); + this.nextState({ showWarning: false }); } private onCommit = (): void => { const { onClose, onStatusChange, t } = this.props; const { derivePath, isValid, name, pairType, password, seed, tags } = this.state; - const status = { action: 'create' } as ActionStatus; + const status: Partial = { action: 'create' }; if (!isValid) { return; @@ -418,7 +418,7 @@ class Create extends React.PureComponent { this.onHideWarning(); - onStatusChange(status); + onStatusChange(status as ActionStatus); onClose(); } @@ -433,8 +433,8 @@ class Create extends React.PureComponent { return; } - this.setState(({ derivePath, pairType }: State) => ({ - ...this.generateSeed(null, derivePath, seedType, pairType), + this.setState(({ derivePath, pairType }: State): State => ({ + ...(this.generateSeed(null, derivePath, seedType, pairType) as State), seedType })); } diff --git a/packages/app-accounts/src/modals/Import.tsx b/packages/app-accounts/src/modals/Import.tsx index 3bf7df75c2..c3892ebf83 100644 --- a/packages/app-accounts/src/modals/Import.tsx +++ b/packages/app-accounts/src/modals/Import.tsx @@ -17,16 +17,16 @@ import translate from '../translate'; type Props = ModalProps & I18nProps; -type State = { - address: string | null, - isFileValid: boolean, - isPassValid: boolean, - json: KeyringPair$Json | null, - password: string -}; +interface State { + address: string | null; + isFileValid: boolean; + isPassValid: boolean; + json: KeyringPair$Json | null; + password: string; +} class Import extends TxComponent { - state: State = { + public state: State = { address: null, isFileValid: false, isPassValid: false, @@ -34,7 +34,7 @@ class Import extends TxComponent { password: '' }; - render () { + public render (): React.ReactNode { const { onClose, t } = this.props; const { isFileValid, isPassValid } = this.state; @@ -65,7 +65,7 @@ class Import extends TxComponent { ); } - private renderInput () { + private renderInput (): React.ReactNode { const { t } = this.props; const { address, isFileValid, isPassValid, json, password } = this.state; const acceptedFormats = ['application/json', 'text/plain'].join(', '); @@ -141,7 +141,7 @@ class Import extends TxComponent { return; } - const status = { action: 'restore' } as ActionStatus; + const status: Partial = { action: 'restore' }; try { const pair = keyring.restoreAccount(json, password); @@ -160,7 +160,7 @@ class Import extends TxComponent { console.error(error); } - onStatusChange(status); + onStatusChange(status as ActionStatus); if (status.status !== 'error') { onClose(); diff --git a/packages/app-accounts/src/modals/Transfer.tsx b/packages/app-accounts/src/modals/Transfer.tsx index 8017508f82..fdfd0a4536 100644 --- a/packages/app-accounts/src/modals/Transfer.tsx +++ b/packages/app-accounts/src/modals/Transfer.tsx @@ -1,3 +1,4 @@ +/* eslint-disable @typescript-eslint/camelcase */ // Copyright 2017-2019 @polkadot/app-accounts authors & contributors // This software may be modified and distributed under the terms // of the Apache-2.0 license. See the LICENSE file for details. @@ -20,29 +21,29 @@ import { ZERO_FEES } from '@polkadot/ui-signer/Checks/constants'; import translate from '../translate'; type Props = ApiProps & I18nProps & { - balances_fees?: DerivedFees, - className?: string, - onClose: () => void, - recipientId?: string, - senderId?: string, - system_accountNonce?: BN + balances_fees?: DerivedFees; + className?: string; + onClose: () => void; + recipientId?: string; + senderId?: string; + system_accountNonce?: BN; }; -type State = { - amount: BN, - extrinsic: SubmittableExtrinsic | null, - hasAvailable: boolean, - maxBalance?: BN, - recipientId?: string | null, - senderId?: string | null -}; +interface State { + amount: BN; + extrinsic: SubmittableExtrinsic | null; + hasAvailable: boolean; + maxBalance?: BN; + recipientId?: string | null; + senderId?: string | null; +} const ZERO = new BN(0); class Transfer extends React.PureComponent { - state: State; + public state: State; - constructor (props: Props) { + public constructor (props: Props) { super(props); this.state = { @@ -55,7 +56,7 @@ class Transfer extends React.PureComponent { }; } - componentDidUpdate (prevProps: Props, prevState: State) { + public componentDidUpdate (prevProps: Props, prevState: State): void { const { balances_fees } = this.props; const { extrinsic, recipientId, senderId } = this.state; const hasLengthChanged = ((extrinsic && extrinsic.encodedLength) || 0) !== ((prevState.extrinsic && prevState.extrinsic.encodedLength) || 0); @@ -68,7 +69,7 @@ class Transfer extends React.PureComponent { } } - render () { + public render (): React.ReactNode { const { t } = this.props; return ( @@ -103,7 +104,7 @@ class Transfer extends React.PureComponent { }); } - private renderButtons () { + private renderButtons (): React.ReactNode { const { onClose, t } = this.props; const { extrinsic, hasAvailable, senderId } = this.state; @@ -130,7 +131,7 @@ class Transfer extends React.PureComponent { ); } - private renderContent () { + private renderContent (): React.ReactNode { const { className, recipientId: propRecipientId, senderId: propSenderId, t } = this.props; const { extrinsic, hasAvailable, maxBalance, recipientId, senderId } = this.state; const available = {t('available ')}; @@ -175,23 +176,23 @@ class Transfer extends React.PureComponent { ); } - private onChangeAmount = (amount: BN = new BN(0)) => { + private onChangeAmount = (amount: BN = new BN(0)): void => { this.nextState({ amount }); } - private onChangeFrom = (senderId: string) => { + private onChangeFrom = (senderId: string): void => { this.nextState({ senderId }); } - private onChangeTo = (recipientId: string) => { + private onChangeTo = (recipientId: string): void => { this.nextState({ recipientId }); } - private onChangeFees = (hasAvailable: boolean) => { + private onChangeFees = (hasAvailable: boolean): void => { this.setState({ hasAvailable }); } - private setMaxBalance = async () => { + private setMaxBalance = async (): Promise => { const { api, balances_fees = ZERO_FEES } = this.props; const { senderId, recipientId } = this.state; @@ -200,10 +201,6 @@ class Transfer extends React.PureComponent { } const { transferFee, transactionBaseFee, transactionByteFee, creationFee } = balances_fees; - - // FIXME The any casts here are irritating, but they are basically caused by the derive - // not really returning an actual `class implements Codec` - // (if casting to DerivedBalance it would be `as any as DerivedBalance`) const accountNonce = await api.query.system.accountNonce(senderId); const senderBalance = (await api.derive.balances.all(senderId)).availableBalance; const recipientBalance = (await api.derive.balances.all(recipientId)).availableBalance; diff --git a/packages/app-accounts/src/types.ts b/packages/app-accounts/src/types.ts index b462736567..753cb11d8d 100644 --- a/packages/app-accounts/src/types.ts +++ b/packages/app-accounts/src/types.ts @@ -7,24 +7,22 @@ import { ActionStatus } from '@polkadot/ui-app/Status/types'; import { WithTranslation } from 'react-i18next'; -export type LocationProps = { +export interface LocationProps { match: { - params: { [index: string]: any } - } -}; + params: Record; + }; +} -export type BareProps = { - className?: string, - style?: { - [index: string]: any - } -}; +export interface BareProps { + className?: string; + style?: Record; +} export type I18nProps = BareProps & WithTranslation; export type ComponentProps = AppProps & LocationProps; -export type ModalProps = { - onClose: () => void, - onStatusChange: (status: ActionStatus) => void -}; +export interface ModalProps { + onClose: () => void; + onStatusChange: (status: ActionStatus) => void; +} diff --git a/packages/app-accounts/src/vanitygen/calculate.ts b/packages/app-accounts/src/vanitygen/calculate.ts index e7fe1faeef..1c5f424d07 100644 --- a/packages/app-accounts/src/vanitygen/calculate.ts +++ b/packages/app-accounts/src/vanitygen/calculate.ts @@ -2,11 +2,11 @@ // This software may be modified and distributed under the terms // of the Apache-2.0 license. See the LICENSE file for details. -import { Generator$Calculation, Generator$Options } from './types'; +import { GeneratorCalculation, GeneratorOptions } from './types'; -function calculateAtOne (atOffset: number, test: string[], address: string): Generator$Calculation { +function calculateAtOne (atOffset: number, test: string[], address: string): GeneratorCalculation { return { - count: test.reduce((count, c, index) => { + count: test.reduce((count, c, index): number => { if (index === count) { count += (c === '?' || c === address.charAt(index + atOffset)) ? 1 : 0; } @@ -17,7 +17,7 @@ function calculateAtOne (atOffset: number, test: string[], address: string): Gen }; } -function calculateAt (atOffset: number, test: string[][], address: string): Generator$Calculation { +function calculateAt (atOffset: number, test: string[][], address: string): GeneratorCalculation { let bestCount = 0; let bestOffset = 1; @@ -36,7 +36,7 @@ function calculateAt (atOffset: number, test: string[][], address: string): Gene }; } -export default function calculate (test: string[][], _address: string, { atOffset = -1, withCase = false }: Generator$Options): Generator$Calculation { +export default function calculate (test: string[][], _address: string, { atOffset = -1, withCase = false }: GeneratorOptions): GeneratorCalculation { const address = withCase ? _address : _address.toLowerCase(); diff --git a/packages/app-accounts/src/vanitygen/cli.ts b/packages/app-accounts/src/vanitygen/cli.ts index a58782e812..87f7d6da16 100644 --- a/packages/app-accounts/src/vanitygen/cli.ts +++ b/packages/app-accounts/src/vanitygen/cli.ts @@ -4,7 +4,7 @@ // of the Apache-2.0 license. See the LICENSE file for details. import { KeypairType } from '@polkadot/util-crypto/types'; -import { Generator$Options } from './types'; +import { GeneratorOptions } from './types'; import yargs from 'yargs'; import chalk from 'chalk'; @@ -38,7 +38,7 @@ const { match, mnemonic, type } = yargs const INDICATORS = ['|', '/', '-', '\\']; const NUMBER_REGEX = new RegExp('(\\d+?)(?=(\\d{3})+(?!\\d)|$)', 'g'); -const options: Generator$Options = { +const options: GeneratorOptions = { match: `${match}`, runs: 50, type: type as KeypairType, @@ -51,7 +51,7 @@ let best: Best = { count: -1, offset: 65536 }; -let total: number = 0; +let total = 0; let indicator = -1; const tests = match.split(','); @@ -83,9 +83,9 @@ function showBest (): void { } cryptoWaitReady() - .then(() => { + .then((): void => { while (true) { - const nextBest = generator(options).found.reduce((best, match) => { + const nextBest = generator(options).found.reduce((best, match): Best => { if ((match.count > best.count) || ((match.count === best.count) && (match.offset <= best.offset))) { return match; } diff --git a/packages/app-accounts/src/vanitygen/generate.ts b/packages/app-accounts/src/vanitygen/generate.ts index 9199aa7ede..617552aa45 100644 --- a/packages/app-accounts/src/vanitygen/generate.ts +++ b/packages/app-accounts/src/vanitygen/generate.ts @@ -2,13 +2,13 @@ // This software may be modified and distributed under the terms // of the Apache-2.0 license. See the LICENSE file for details. -import { Generator$Match, Generator$Options } from './types'; +import { GeneratorMatch, GeneratorOptions } from './types'; import { encodeAddress, mnemonicGenerate, naclKeypairFromSeed, randomAsU8a, schnorrkelKeypairFromSeed, mnemonicToMiniSecret } from '@polkadot/util-crypto'; import calculate from './calculate'; -export default function generator (test: string[][], options: Generator$Options): Generator$Match { +export default function generator (test: string[][], options: GeneratorOptions): GeneratorMatch { const mnemonic = options.withHex ? undefined : mnemonicGenerate(12); diff --git a/packages/app-accounts/src/vanitygen/index.ts b/packages/app-accounts/src/vanitygen/index.ts index ce6cf30c5e..7621c210e3 100644 --- a/packages/app-accounts/src/vanitygen/index.ts +++ b/packages/app-accounts/src/vanitygen/index.ts @@ -2,15 +2,15 @@ // This software may be modified and distributed under the terms // of the Apache-2.0 license. See the LICENSE file for details. -import { Generator$Matches, Generator$Result, Generator$Options } from './types'; +import { GeneratorMatches, GeneratorResult, GeneratorOptions } from './types'; import generate from './generate'; -export default function generator (options: Generator$Options): Generator$Result { +export default function generator (options: GeneratorOptions): GeneratorResult { const { match, runs = 10, withCase = false } = options; const test = (withCase ? match : match.toLowerCase()).split(',').map((c) => c.split('')); const startAt = Date.now(); - const found: Generator$Matches = []; + const found: GeneratorMatches = []; while (found.length !== runs) { found.push(generate(test, options)); diff --git a/packages/app-accounts/src/vanitygen/sort.ts b/packages/app-accounts/src/vanitygen/sort.ts index 9530365443..ca44f72813 100644 --- a/packages/app-accounts/src/vanitygen/sort.ts +++ b/packages/app-accounts/src/vanitygen/sort.ts @@ -2,7 +2,7 @@ // This software may be modified and distributed under the terms // of the Apache-2.0 license. See the LICENSE file for details. -import { Generator$Match } from './types'; +import { GeneratorMatch } from './types'; function numberSort (a: number, b: number): number { if (a > b) { @@ -14,7 +14,7 @@ function numberSort (a: number, b: number): number { return 0; } -export default function sort (a: Generator$Match, b: Generator$Match): number { +export default function sort (a: GeneratorMatch, b: GeneratorMatch): number { const countResult = numberSort(a.count, b.count); if (countResult !== 0) { diff --git a/packages/app-accounts/src/vanitygen/types.d.ts b/packages/app-accounts/src/vanitygen/types.d.ts index 2fd02722e3..5e2f5bd215 100644 --- a/packages/app-accounts/src/vanitygen/types.d.ts +++ b/packages/app-accounts/src/vanitygen/types.d.ts @@ -4,20 +4,20 @@ import { KeypairType } from '@polkadot/util-crypto/types'; -export interface Generator$Calculation { +export interface GeneratorCalculation { count: number; offset: number; } -export interface Generator$Match extends Generator$Calculation { +export interface GeneratorMatch extends GeneratorCalculation { address: string; mnemonic?: string; seed: Uint8Array; } -export type Generator$Matches = Generator$Match[]; +export type GeneratorMatches = GeneratorMatch[]; -export interface Generator$Options { +export interface GeneratorOptions { atOffset?: number; match: string; runs: number; @@ -26,7 +26,7 @@ export interface Generator$Options { withHex?: boolean; } -export interface Generator$Result { +export interface GeneratorResult { elapsed: number; - found: Generator$Matches; + found: GeneratorMatches; } diff --git a/packages/app-accounts/src/worker-loader.d.ts b/packages/app-accounts/src/worker-loader.d.ts deleted file mode 100644 index cd9ad52616..0000000000 --- a/packages/app-accounts/src/worker-loader.d.ts +++ /dev/null @@ -1,8 +0,0 @@ -declare module 'worker-loader!*' { - class WebpackWorker extends Worker { - constructor(); - } - - // @ts-ignore valid according to integration instructions: https://github.com/webpack-contrib/worker-loader#integrating-with-typescript - export = WebpackWorker; -} diff --git a/packages/app-address-book/src/Address.tsx b/packages/app-address-book/src/Address.tsx index de32770bc8..537c838821 100644 --- a/packages/app-address-book/src/Address.tsx +++ b/packages/app-address-book/src/Address.tsx @@ -14,21 +14,21 @@ import Transfer from '@polkadot/app-accounts/modals/Transfer'; import translate from './translate'; -type Props = I18nProps & { - address: string -}; +interface Props extends I18nProps { + address: string; +} -type State = { - current?: KeyringAddress, - isEditable: boolean, - isForgetOpen: boolean, - isTransferOpen: boolean -}; +interface State { + current?: KeyringAddress; + isEditable: boolean; + isForgetOpen: boolean; + isTransferOpen: boolean; +} class Address extends React.PureComponent { - state: State; + public state: State; - constructor (props: Props) { + public constructor (props: Props) { super(props); const { address } = this.props; @@ -41,7 +41,7 @@ class Address extends React.PureComponent { }; } - render () { + public render (): React.ReactNode { const { address } = this.props; const { isEditable } = this.state; @@ -65,7 +65,7 @@ class Address extends React.PureComponent { ); } - private renderModals () { + private renderModals (): React.ReactNode { const { address } = this.props; const { isForgetOpen, isTransferOpen, current } = this.state; @@ -101,15 +101,15 @@ class Address extends React.PureComponent { } private toggleForget = (): void => { - this.setState(({ isForgetOpen }) => ({ + this.setState(({ isForgetOpen }): State => ({ isForgetOpen: !isForgetOpen - })); + }) as unknown as State); } private toggleTransfer = (): void => { - this.setState(({ isTransferOpen }) => ({ + this.setState(({ isTransferOpen }): State => ({ isTransferOpen: !isTransferOpen - })); + }) as unknown as State); } private onForget = (): void => { @@ -119,10 +119,10 @@ class Address extends React.PureComponent { return; } - const status = { + const status: Partial = { account: address, action: 'forget' - } as ActionStatus; + }; try { keyring.forgetAddress(address); @@ -134,7 +134,7 @@ class Address extends React.PureComponent { } } - private renderButtons () { + private renderButtons (): React.ReactNode { const { t } = this.props; const { isEditable } = this.state; diff --git a/packages/app-address-book/src/Overview.tsx b/packages/app-address-book/src/Overview.tsx index 7037d9907f..6d94811514 100644 --- a/packages/app-address-book/src/Overview.tsx +++ b/packages/app-address-book/src/Overview.tsx @@ -16,19 +16,19 @@ import Address from './Address'; import translate from './translate'; type Props = ComponentProps & I18nProps & { - addresses?: SubjectInfo[] + addresses?: SubjectInfo[]; }; -type State = { - isCreateOpen: boolean -}; +interface State { + isCreateOpen: boolean; +} class Overview extends React.PureComponent { - state: State = { + public state: State = { isCreateOpen: false }; - render () { + public render (): React.ReactNode { const { addresses, onStatusChange, t } = this.props; const { isCreateOpen } = this.state; const emptyScreen = !isCreateOpen && (!addresses || Object.keys(addresses).length === 0); @@ -53,7 +53,7 @@ class Overview extends React.PureComponent { onStatusChange={onStatusChange} /> )} - {addresses && Object.keys(addresses).map((address) => ( + {addresses && Object.keys(addresses).map((address): React.ReactNode => (
{ } private toggleCreate = (): void => { - this.setState(({ isCreateOpen }) => ({ + this.setState(({ isCreateOpen }): State => ({ isCreateOpen: !isCreateOpen })); } diff --git a/packages/app-address-book/src/index.tsx b/packages/app-address-book/src/index.tsx index e8b4e61daf..726888bde0 100644 --- a/packages/app-address-book/src/index.tsx +++ b/packages/app-address-book/src/index.tsx @@ -18,19 +18,19 @@ import Overview from './Overview'; import translate from './translate'; type Props = AppProps & I18nProps & { - allAddresses?: SubjectInfo + allAddresses?: SubjectInfo; }; -type State = { - hidden: Array, - items: Array, - isCreateOpen: boolean -}; +interface State { + hidden: string[]; + items: TabItem[]; + isCreateOpen: boolean; +} class AddressBookApp extends React.PureComponent { - state: State; + public state: State; - constructor (props: Props) { + public constructor (props: Props) { super(props); const { allAddresses = {}, t } = props; @@ -39,7 +39,7 @@ class AddressBookApp extends React.PureComponent { : AddressBookApp.hideEditState(); this.state = { - ...baseState, + ...(baseState as State), isCreateOpen: false, items: [ { @@ -51,33 +51,33 @@ class AddressBookApp extends React.PureComponent { }; } - static showEditState () { + private static showEditState (): Partial { return { hidden: [] }; } - static hideEditState () { + private static hideEditState (): Partial { return { hidden: ['edit'] }; } - static getDerivedStateFromProps ({ allAddresses = {} }: Props, { hidden }: State) { + public static getDerivedStateFromProps ({ allAddresses = {} }: Props, { hidden }: State): State | null { const hasAddresses = Object.keys(allAddresses).length !== 0; if (hidden.length === 0) { return hasAddresses ? null - : AddressBookApp.hideEditState(); + : AddressBookApp.hideEditState() as State; } return hasAddresses - ? AddressBookApp.showEditState() + ? AddressBookApp.showEditState() as State : null; } - render () { + public render (): React.ReactNode { const { basePath } = this.props; const { hidden, items } = this.state; @@ -98,8 +98,8 @@ class AddressBookApp extends React.PureComponent { ); } - private renderComponent (Component: React.ComponentType) { - return () => { + private renderComponent (Component: React.ComponentType): () => React.ReactNode { + return (): React.ReactNode => { const { basePath, location, onStatusChange } = this.props; return ( diff --git a/packages/app-address-book/src/modals/Create.tsx b/packages/app-address-book/src/modals/Create.tsx index 631fa9f2ad..2719864f02 100644 --- a/packages/app-address-book/src/modals/Create.tsx +++ b/packages/app-address-book/src/modals/Create.tsx @@ -16,26 +16,26 @@ import translate from '../translate'; type Props = ModalProps & I18nProps; -type State = { - address: string, - isAddressExisting: boolean, - isAddressValid: boolean, - isNameValid: boolean, - isValid: boolean, - name: string, - tags: Array -}; +interface State { + address: string; + isAddressExisting: boolean; + isAddressValid: boolean; + isNameValid: boolean; + isValid: boolean; + name: string; + tags: string[]; +} class Create extends React.PureComponent { - state: State; + public state: State; - constructor (props: Props) { + public constructor (props: Props) { super(props); this.state = this.emptyState(); } - render () { + public render (): React.ReactNode { const { t } = this.props; return ( @@ -50,7 +50,7 @@ class Create extends React.PureComponent { ); } - private renderButtons () { + private renderButtons (): React.ReactNode { const { t } = this.props; const { isValid } = this.state; @@ -74,7 +74,7 @@ class Create extends React.PureComponent { ); } - private renderContent () { + private renderContent (): React.ReactNode { const { t } = this.props; const { address, isAddressValid, isNameValid, name } = this.state; @@ -120,7 +120,7 @@ class Create extends React.PureComponent { }; } - private nextState (newState: State, allowEdit: boolean = false): void { + private nextState (newState: Partial, allowEdit: boolean = false): void { this.setState( (prevState: State): State => { let { address = prevState.address, name = prevState.name, tags = prevState.tags } = newState; @@ -166,17 +166,17 @@ class Create extends React.PureComponent { } private onChangeAddress = (address: string): void => { - this.nextState({ address } as State); + this.nextState({ address }); } private onChangeName = (name: string): void => { - this.nextState({ name } as State, true); + this.nextState({ name }, true); } private onCommit = (): void => { const { onClose, onStatusChange, t } = this.props; const { address, isAddressExisting, isValid, name, tags } = this.state; - const status = { action: 'create' } as ActionStatus; + const status: Partial = { action: 'create' }; if (!isValid) { return; @@ -197,7 +197,7 @@ class Create extends React.PureComponent { status.message = error.message; } - onStatusChange(status); + onStatusChange(status as ActionStatus); onClose(); } diff --git a/packages/app-address-book/src/types.ts b/packages/app-address-book/src/types.ts index 0e5a64d39f..00289a5761 100644 --- a/packages/app-address-book/src/types.ts +++ b/packages/app-address-book/src/types.ts @@ -7,7 +7,7 @@ import { ActionStatus } from '@polkadot/ui-app/Status/types'; export type ComponentProps = AppProps; -export type ModalProps = { - onClose: () => void, - onStatusChange: (status: ActionStatus) => void -}; +export interface ModalProps { + onClose: () => void; + onStatusChange: (status: ActionStatus) => void; +} diff --git a/packages/app-collective/src/Overview/Candidate.tsx b/packages/app-collective/src/Overview/Candidate.tsx index f742fe1793..ef15ed9a12 100644 --- a/packages/app-collective/src/Overview/Candidate.tsx +++ b/packages/app-collective/src/Overview/Candidate.tsx @@ -5,12 +5,12 @@ import React from 'react'; import { AddressCard } from '@polkadot/ui-app'; -type Props = { - address: string -}; +interface Props { + address: string; +} export default class Candidate extends React.PureComponent { - render () { + public render (): React.ReactNode { const { address } = this.props; return ( diff --git a/packages/app-collective/src/Overview/Member.tsx b/packages/app-collective/src/Overview/Member.tsx index 92cd2f5603..74cca2fbd2 100644 --- a/packages/app-collective/src/Overview/Member.tsx +++ b/packages/app-collective/src/Overview/Member.tsx @@ -11,13 +11,13 @@ import { formatNumber } from '@polkadot/util'; import translate from '../translate'; -type Props = I18nProps & { - address: string, - block: BN -}; +interface Props extends I18nProps { + address: string; + block: BN; +} class Member extends React.PureComponent { - render () { + public render (): React.ReactNode { const { address, block, t } = this.props; return ( diff --git a/packages/app-collective/src/Overview/Members.tsx b/packages/app-collective/src/Overview/Members.tsx index 7903c7882e..e5909612ca 100644 --- a/packages/app-collective/src/Overview/Members.tsx +++ b/packages/app-collective/src/Overview/Members.tsx @@ -1,3 +1,4 @@ +/* eslint-disable @typescript-eslint/camelcase */ // Copyright 2017-2019 @polkadot/app-democracy authors & contributors // This software may be modified and distributed under the terms // of the Apache-2.0 license. See the LICENSE file for details. @@ -13,13 +14,13 @@ import translate from '../translate'; import Candidate from './Candidate'; import Member from './Member'; -type Props = I18nProps & { - elections_members?: Array<[string, BlockNumber]> - elections_candidates?: Array -}; +interface Props extends I18nProps { + elections_members?: [string, BlockNumber][]; + elections_candidates?: string[]; +} class Members extends React.PureComponent { - render () { + public render (): React.ReactNode { const { elections_members = [], elections_candidates = [], t } = this.props; return ( @@ -28,7 +29,7 @@ class Members extends React.PureComponent { emptyText={t('No members found')} headerText={t('members')} > - {elections_members.map(([address, block]) => ( + {elections_members.map(([address, block]): React.ReactNode => ( { emptyText={t('No members found')} headerText={t('candidates')} > - {elections_candidates.map((address) => ( + {elections_candidates.map((address): React.ReactNode => ( { export default translate( withCalls( ['query.elections.members', { - transform: (active: Array<[AccountId, BlockNumber]>) => - active.map(([accountId, blockNumber]) => [accountId.toString(), blockNumber]) + transform: (active: [AccountId, BlockNumber][]): [string, BlockNumber][] => + active.map(([accountId, blockNumber]): [string, BlockNumber] => + [accountId.toString(), blockNumber] + ) }], ['query.elections.candidates', { - transform: (candidates: Array) => - candidates.map((accountId) => accountId.toString()) + transform: (candidates: AccountId[]): string[] => + candidates.map((accountId): string => accountId.toString()) }] )(Members) ); diff --git a/packages/app-collective/src/Overview/Summary.tsx b/packages/app-collective/src/Overview/Summary.tsx index 2a75668bd9..1880da7be9 100644 --- a/packages/app-collective/src/Overview/Summary.tsx +++ b/packages/app-collective/src/Overview/Summary.tsx @@ -1,3 +1,4 @@ +/* eslint-disable @typescript-eslint/camelcase */ // Copyright 2017-2019 @polkadot/app-democracy authors & contributors // This software may be modified and distributed under the terms // of the Apache-2.0 license. See the LICENSE file for details. @@ -13,16 +14,16 @@ import { formatNumber } from '@polkadot/util'; import translate from '../translate'; -type Props = I18nProps & { - elections_members?: Array<[AccountId, BlockNumber]> - elections_candidateCount?: BN, - elections_desiredSeats?: BN, - elections_termDuration?: BN, - elections_voteCount?: BN -}; +interface Props extends I18nProps { + elections_members?: [AccountId, BlockNumber][]; + elections_candidateCount?: BN; + elections_desiredSeats?: BN; + elections_termDuration?: BN; + elections_voteCount?: BN; +} class Summary extends React.PureComponent { - render () { + public render (): React.ReactNode { const { elections_members = [], elections_candidateCount = new BN(0), elections_desiredSeats = new BN(1), elections_termDuration = new BN(0), elections_voteCount = new BN(0), t } = this.props; return ( @@ -43,8 +44,8 @@ class Summary extends React.PureComponent {
- {formatNumber(elections_termDuration)} - + {formatNumber(elections_termDuration)} +
); diff --git a/packages/app-collective/src/Overview/index.tsx b/packages/app-collective/src/Overview/index.tsx index 82f9ab2b3d..c601e25d3d 100644 --- a/packages/app-collective/src/Overview/index.tsx +++ b/packages/app-collective/src/Overview/index.tsx @@ -7,10 +7,10 @@ import React from 'react'; import Members from './Members'; import Summary from './Summary'; -type Props = {}; +interface Props {} export default class Overview extends React.PureComponent { - render () { + public render (): React.ReactNode { return ( <> diff --git a/packages/app-collective/src/Proposals/Proposal.tsx b/packages/app-collective/src/Proposals/Proposal.tsx index f23d1f112c..85b6551e69 100644 --- a/packages/app-collective/src/Proposals/Proposal.tsx +++ b/packages/app-collective/src/Proposals/Proposal.tsx @@ -13,27 +13,27 @@ import { withCalls, withMulti } from '@polkadot/ui-api'; import translate from '../translate'; -type Props = I18nProps & { - chain_bestNumber?: BN, - hash: string, - proposal: ProposalType | null, - votes: Votes | null -}; +interface Props extends I18nProps { + chain_bestNumber?: BN; + hash: string; + proposal: ProposalType | null; + votes: Votes | null; +} -type State = { - votedTotal: number, - votedNay: number, - votedAye: number -}; +interface State { + votedTotal: number; + votedNay: number; + votedAye: number; +} class Proposal extends React.PureComponent { - state: State = { + public state: State = { votedTotal: 0, votedAye: 0, votedNay: 0 }; - static getDerivedStateFromProps ({ votes }: Props): State | null { + public static getDerivedStateFromProps ({ votes }: Props): State | null { if (!votes) { return null; } @@ -49,7 +49,7 @@ class Proposal extends React.PureComponent { return newState; } - render () { + public render (): React.ReactNode { const { className, hash, proposal, votes } = this.props; if (!proposal || !votes) { @@ -78,7 +78,7 @@ class Proposal extends React.PureComponent { ); } - private renderInfo () { + private renderInfo (): React.ReactNode { const { votes, t } = this.props; if (!votes) { @@ -100,7 +100,7 @@ class Proposal extends React.PureComponent { } )} - {ayes.map((address, index) => ( + {ayes.map((address, index): React.ReactNode => ( { } )} - {nays.map((address, index) => ( + {nays.map((address, index): React.ReactNode => ( ) => value.unwrapOr(null) + transform: (value: Option): ProposalType | null => + value.unwrapOr(null) } ], [ @@ -164,7 +165,8 @@ export default withMulti( { paramName: 'hash', propName: 'votes', - transform: (value: Option) => value.unwrapOr(null) + transform: (value: Option): Votes | null => + value.unwrapOr(null) } ] ) diff --git a/packages/app-collective/src/Proposals/Propose.tsx b/packages/app-collective/src/Proposals/Propose.tsx index 0697f24816..9beeba587b 100644 --- a/packages/app-collective/src/Proposals/Propose.tsx +++ b/packages/app-collective/src/Proposals/Propose.tsx @@ -15,16 +15,16 @@ import { withApi, withCalls, withMulti } from '@polkadot/ui-api'; import translate from '../translate'; type Props = TxModalProps & ApiProps & { - memberCount: number + memberCount: number; }; -type State = TxModalState & { - method: Method | null, - threshold: BN | null -}; +interface State extends TxModalState { + method: Method | null; + threshold: BN | null; +} class Propose extends TxModal { - constructor (props: Props) { + public constructor (props: Props) { super(props); this.defaultState = { @@ -137,7 +137,7 @@ export default withMulti( 'query.elections.members', { propName: 'memberCount', - transform: (value: Array) => value.length + transform: (value: any[]) => value.length } ] ) diff --git a/packages/app-collective/src/Proposals/index.tsx b/packages/app-collective/src/Proposals/index.tsx index 8a475797a3..976575cd07 100644 --- a/packages/app-collective/src/Proposals/index.tsx +++ b/packages/app-collective/src/Proposals/index.tsx @@ -1,3 +1,4 @@ +/* eslint-disable @typescript-eslint/camelcase */ // Copyright 2017-2019 @polkadot/app-democracy authors & contributors // This software may be modified and distributed under the terms // of the Apache-2.0 license. See the LICENSE file for details. @@ -13,12 +14,12 @@ import Proposal from './Proposal'; import Propose from './Propose'; import translate from '../translate'; -type Props = I18nProps & { - collective_proposals?: Array -}; +interface Props extends I18nProps { + collective_proposals?: Hash[]; +} class Proposals extends React.PureComponent { - render () { + public render (): React.ReactNode { const { t } = this.props; return ( @@ -34,10 +35,10 @@ class Proposals extends React.PureComponent { ); } - private renderProposals () { + private renderProposals (): React.ReactNode { const { collective_proposals = [] } = this.props; - return collective_proposals.map((hash) => ( + return collective_proposals.map((hash: Hash): React.ReactNode => ( -}; +interface State { + tabs: TabItem[]; +} class App extends React.PureComponent { - constructor (props: Props) { + public constructor (props: Props) { super(props); const { t } = props; @@ -40,7 +40,7 @@ class App extends React.PureComponent { }; } - render () { + public render (): React.ReactNode { const { basePath } = this.props; const { tabs } = this.state; diff --git a/packages/app-contracts/src/ABI.tsx b/packages/app-contracts/src/ABI.tsx index 981cb2e8d0..c036bea517 100644 --- a/packages/app-contracts/src/ABI.tsx +++ b/packages/app-contracts/src/ABI.tsx @@ -12,36 +12,36 @@ import { u8aToString } from '@polkadot/util'; import translate from './translate'; -type Props = I18nProps & { - className?: string, - contractAbi?: Abi | null, - help?: React.ReactNode, - isError?: boolean, - isDisabled?: boolean, - isRequired?: boolean, - label?: React.ReactNode, - onChange: (json: string | null, contractAbi: Abi | null) => void, - onRemove?: () => void, - onRemoved?: () => void, - onSelect?: () => void -}; +interface Props extends I18nProps { + className?: string; + contractAbi?: Abi | null; + help?: React.ReactNode; + isError?: boolean; + isDisabled?: boolean; + isRequired?: boolean; + label?: React.ReactNode; + onChange: (json: string | null, contractAbi: Abi | null) => void; + onRemove?: () => void; + onRemoved?: () => void; + onSelect?: () => void; +} -type State = { - contractAbi: Abi | null, - isAbiValid: boolean, - isEmpty: boolean, - isError: boolean -}; +interface State { + contractAbi: Abi | null; + isAbiValid: boolean; + isEmpty: boolean; + isError: boolean; +} class ABI extends React.PureComponent { - state: State = { + public state: State = { contractAbi: null, isAbiValid: false, isEmpty: true, isError: false }; - constructor (props: Props) { + public constructor (props: Props) { super(props); const { contractAbi, isError, isRequired } = this.props; @@ -55,7 +55,7 @@ class ABI extends React.PureComponent { }; } - componentWillReceiveProps ({ contractAbi, isError, isRequired }: Props) { + public componentWillReceiveProps ({ contractAbi, isError, isRequired }: Props): void { if (contractAbi) { this.setState({ contractAbi, @@ -71,7 +71,7 @@ class ABI extends React.PureComponent { } } - render () { + public render (): React.ReactNode { const { className } = this.props; const { contractAbi, isAbiValid } = this.state; @@ -86,7 +86,7 @@ class ABI extends React.PureComponent { ); } - private renderInputFile () { + private renderInputFile (): React.ReactNode { const { className, help, isDisabled, isRequired, label, t } = this.props; const { isAbiValid, isEmpty, isError } = this.state; @@ -108,7 +108,7 @@ class ABI extends React.PureComponent { ); } - private renderMessages () { + private renderMessages (): React.ReactNode { const { help, isDisabled, label, onRemove } = this.props; const { contractAbi } = this.state; @@ -140,7 +140,7 @@ class ABI extends React.PureComponent { isAbiValid: true, isEmpty: false, isError: false - }, () => onChange(json, contractAbi)); + }, (): void => onChange(json, contractAbi)); } catch (error) { console.error(error); @@ -148,7 +148,7 @@ class ABI extends React.PureComponent { isAbiValid: false, isEmpty: false, isError: true - }, () => onChange(null, null)); + }, (): void => onChange(null, null)); } } @@ -161,7 +161,7 @@ class ABI extends React.PureComponent { isAbiValid: false, isEmpty: true }, - () => { + (): void => { onChange(null, null); onRemoved && onRemoved(); } diff --git a/packages/app-contracts/src/Codes/Add.tsx b/packages/app-contracts/src/Codes/Add.tsx index a9d7b6161d..77df592d11 100644 --- a/packages/app-contracts/src/Codes/Add.tsx +++ b/packages/app-contracts/src/Codes/Add.tsx @@ -13,14 +13,14 @@ import translate from '../translate'; type Props = ContractModalProps; -type State = ContractModalState & { - codeHash: string, - isBusy: boolean, - isCodeValid: boolean -}; +interface State extends ContractModalState { + codeHash: string; + isBusy: boolean; + isCodeValid: boolean; +} class Add extends ContractModal { - constructor (props: Props) { + public constructor (props: Props) { super(props); this.defaultState = { ...this.defaultState, @@ -32,7 +32,7 @@ class Add extends ContractModal { this.headerText = props.t('Add an existing code hash'); } - renderContent = () => { + protected renderContent = (): React.ReactNode => { const { t } = this.props; const { codeHash, isBusy, isCodeValid } = this.state; @@ -58,7 +58,7 @@ class Add extends ContractModal { ); } - renderButtons = () => { + protected renderButtons = (): React.ReactNode => { const { t } = this.props; const { isBusy, isCodeValid, isNameValid } = this.state; const isValid = !isBusy && isCodeValid && isNameValid; @@ -92,22 +92,20 @@ class Add extends ContractModal { return; } - this.setState( - { isBusy: true }, - () => { - store.saveCode(new Hash(codeHash), { abi, name, tags }) - .then(() => { - this.setState( - { isBusy: false }, - () => this.onClose() - ); - }) - .catch((error) => { - console.error('Unable to save code', error); - this.setState({ isBusy: false }); - }); - } - ); + this.setState({ isBusy: true }, (): void => { + store + .saveCode(new Hash(codeHash), { abi, name, tags }) + .then((): void => { + this.setState( + { isBusy: false }, + (): void => this.onClose() + ); + }) + .catch((error): void => { + console.error('Unable to save code', error); + this.setState({ isBusy: false }); + }); + }); // this.redirect(); } diff --git a/packages/app-contracts/src/Codes/Code.tsx b/packages/app-contracts/src/Codes/Code.tsx index 13562dbf60..8597075aa4 100644 --- a/packages/app-contracts/src/Codes/Code.tsx +++ b/packages/app-contracts/src/Codes/Code.tsx @@ -19,15 +19,15 @@ import contracts from '../store'; import translate from '../translate'; type Props = I18nProps & RouteComponentProps & { - basePath: string, - code: CodeStored, - showDeploy: (codeHash?: string) => () => void + basePath: string; + code: CodeStored; + showDeploy: (codeHash?: string) => () => void; }; -type State = { - isForgetOpen: boolean, - isRemoveABIOpen: boolean -}; +interface State { + isForgetOpen: boolean; + isRemoveABIOpen: boolean; +} const CodeCard = styled(Card)` && { @@ -36,12 +36,12 @@ const CodeCard = styled(Card)` `; class Contract extends React.PureComponent { - state: State = { + public state: State = { isForgetOpen: false, isRemoveABIOpen: false }; - render () { + public render (): React.ReactNode { const { code, code: { contractAbi } } = this.props; return ( @@ -63,7 +63,7 @@ class Contract extends React.PureComponent { ); } - private renderButtons () { + private renderButtons (): React.ReactNode { const { code: { json: { codeHash } }, showDeploy, t } = this.props; return ( @@ -87,7 +87,7 @@ class Contract extends React.PureComponent { ); } - private renderModals () { + private renderModals (): React.ReactNode { const { code } = this.props; const { isForgetOpen, isRemoveABIOpen } = this.state; @@ -115,7 +115,7 @@ class Contract extends React.PureComponent { code={code} key='modal-remove-abi' onClose={this.toggleRemoveABI} - onRemove={() => this.onChangeABI(null)} + onRemove={this.onChangeABI} /> ); } @@ -155,7 +155,7 @@ class Contract extends React.PureComponent { } } - private onChangeABI = async (abi: string | null) => { + private onChangeABI = async (abi: string | null = null): Promise => { const { code: { json: { codeHash } } } = this.props; await contracts.saveCode( diff --git a/packages/app-contracts/src/Codes/Upload.tsx b/packages/app-contracts/src/Codes/Upload.tsx index 0546ab1c03..89650eb0bc 100644 --- a/packages/app-contracts/src/Codes/Upload.tsx +++ b/packages/app-contracts/src/Codes/Upload.tsx @@ -18,14 +18,14 @@ import translate from '../translate'; type Props = ContractModalProps & ApiProps; -type State = ContractModalState & { - gasLimit: BN, - isWasmValid: boolean, - wasm?: Uint8Array | null -}; +interface State extends ContractModalState { + gasLimit: BN; + isWasmValid: boolean; + wasm?: Uint8Array | null; +} class Upload extends ContractModal { - constructor (props: Props) { + public constructor (props: Props) { super(props); this.defaultState = { @@ -37,7 +37,7 @@ class Upload extends ContractModal { this.headerText = props.t('Upload WASM'); } - renderContent = () => { + protected renderContent = (): React.ReactNode => { const { t } = this.props; const { isBusy, isWasmValid, wasm } = this.state; @@ -63,7 +63,7 @@ class Upload extends ContractModal { ); } - renderButtons = () => { + protected renderButtons = (): React.ReactNode => { const { api, t } = this.props; const { accountId, gasLimit, isBusy, isNameValid, isWasmValid, wasm } = this.state; const isValid = !isBusy && accountId && isNameValid && isWasmValid && !gasLimit.isZero() && !!accountId; @@ -96,8 +96,8 @@ class Upload extends ContractModal { private onSuccess = (result: SubmittableResult): void => { const { api } = this.props; - this.setState(({ abi, name, tags }) => { + this.setState(({ abi, name, tags }): State | null => { const section = api.tx.contracts ? 'contracts' : 'contract'; const record = result.findRecord(section, 'CodeStored'); @@ -105,16 +105,17 @@ class Upload extends ContractModal { const codeHash = record.event.data[0]; if (!codeHash || !name) { - return; + return null; } store.saveCode(codeHash as Hash, { abi, name, tags }) - .then(() => this.onClose()) - .catch((error: any) => { + .then((): void => this.onClose()) + .catch((error: any): void => { console.error('Unable to save code', error); }); } - return { isBusy: false } as State; + + return { isBusy: false } as unknown as State; }); } } diff --git a/packages/app-contracts/src/Codes/ValidateCode.tsx b/packages/app-contracts/src/Codes/ValidateCode.tsx index 2a0f99e63c..1524f54c09 100644 --- a/packages/app-contracts/src/Codes/ValidateCode.tsx +++ b/packages/app-contracts/src/Codes/ValidateCode.tsx @@ -1,3 +1,4 @@ +/* eslint-disable @typescript-eslint/camelcase */ // Copyright 2017-2019 @polkadot/app-contracts authors & contributors // This software may be modified and distributed under the terms // of the Apache-2.0 license. See the LICENSE file for details. @@ -14,25 +15,25 @@ import { isHex } from '@polkadot/util'; import translate from '../translate'; type Props = ApiProps & I18nProps & { - codeHash?: string | null, - contract_codeStorage?: Option, - onChange: (isValid: boolean) => void + codeHash?: string | null; + contract_codeStorage?: Option; + onChange: (isValid: boolean) => void; }; -type State = { - isStored: boolean, - isValidHex: boolean, - isValid: boolean -}; +interface State { + isStored: boolean; + isValidHex: boolean; + isValid: boolean; +} class ValidateCode extends React.PureComponent { - state: State = { + public state: State = { isStored: false, isValidHex: false, isValid: false }; - static getDerivedStateFromProps ({ codeHash, contract_codeStorage, onChange }: Props): State { + public static getDerivedStateFromProps ({ codeHash, contract_codeStorage, onChange }: Props): State { const isValidHex = !!codeHash && isHex(codeHash) && codeHash.length === 66; const isStored = !!contract_codeStorage && contract_codeStorage.isSome; const isValid = isValidHex && isStored; @@ -47,7 +48,7 @@ class ValidateCode extends React.PureComponent { }; } - render () { + public render (): React.ReactNode { const { t } = this.props; const { isValid, isValidHex } = this.state; diff --git a/packages/app-contracts/src/Codes/index.tsx b/packages/app-contracts/src/Codes/index.tsx index 93690bd764..cd6ba782f3 100644 --- a/packages/app-contracts/src/Codes/index.tsx +++ b/packages/app-contracts/src/Codes/index.tsx @@ -17,18 +17,18 @@ import Add from './Add'; type Props = ComponentProps & I18nProps; -type State = { - isAddOpen: boolean, - isUploadOpen: boolean -}; +interface State { + isAddOpen: boolean; + isUploadOpen: boolean; +} class Codes extends React.PureComponent { - state = { + public state: State = { isAddOpen: false, isUploadOpen: false - } as State; + }; - render () { + public render (): React.ReactNode { const { basePath, showDeploy, t } = this.props; const { isAddOpen, isUploadOpen } = this.state; @@ -53,7 +53,7 @@ class Codes extends React.PureComponent { } > - {contracts.getAllCode().map((code) => { + {contracts.getAllCode().map((code): React.ReactNode => { return ( { ); } - private showUpload = () => { + private showUpload = (): void => { this.setState({ isUploadOpen: true }); } - private hideUpload = () => { + private hideUpload = (): void => { this.setState({ isUploadOpen: false }); } - private showAdd = () => { + private showAdd = (): void => { this.setState({ isAddOpen: true }); } - private hideAdd = () => { + private hideAdd = (): void => { this.setState({ isAddOpen: false }); } } diff --git a/packages/app-contracts/src/Contracts/Add.tsx b/packages/app-contracts/src/Contracts/Add.tsx index 2ae6f8d84a..9207f51315 100644 --- a/packages/app-contracts/src/Contracts/Add.tsx +++ b/packages/app-contracts/src/Contracts/Add.tsx @@ -18,13 +18,13 @@ import translate from '../translate'; type Props = ContractModalProps & ApiProps & I18nProps; -type State = ContractModalState & { - address?: string | null, - isAddressValid: boolean -}; +interface State extends ContractModalState { + address?: string | null; + isAddressValid: boolean; +} class Add extends ContractModal { - constructor (props: Props) { + public constructor (props: Props) { super(props); this.defaultState = { ...this.defaultState, @@ -37,9 +37,9 @@ class Add extends ContractModal { this.headerText = props.t('Add an existing contract'); } - isContract = true; + public isContract = true; - renderContent = () => { + protected renderContent = (): React.ReactNode => { const { t } = this.props; const { address, isAddressValid, isBusy, name } = this.state; @@ -69,7 +69,7 @@ class Add extends ContractModal { ); } - renderButtons = () => { + protected renderButtons = (): React.ReactNode => { const { t } = this.props; const { isAddressValid, isAbiValid, isNameValid } = this.state; const isValid = isNameValid && isAddressValid && isAbiValid; @@ -96,9 +96,9 @@ class Add extends ContractModal { this.setState({ isAddressValid }); } - private onAdd = async () => { + private onAdd = async (): Promise => { const { api } = this.props; - const status = { action: 'create' } as ActionStatus; + const status: Partial = { action: 'create' }; const { address, abi, name, tags } = this.state; if (!address || !abi || !name) { @@ -120,10 +120,11 @@ class Add extends ContractModal { status.account = address; status.status = address ? 'success' : 'error'; status.message = 'contract added'; - this.onClose(); + this.onClose(); } catch (error) { console.error(error); + status.status = 'error'; status.message = error.message; } diff --git a/packages/app-contracts/src/Contracts/Call.tsx b/packages/app-contracts/src/Contracts/Call.tsx index 2fd751214e..61125c43f5 100644 --- a/packages/app-contracts/src/Contracts/Call.tsx +++ b/packages/app-contracts/src/Contracts/Call.tsx @@ -17,26 +17,26 @@ import translate from '../translate'; import Params from '../Params'; type Props = BareProps & I18nProps & ApiProps & { - address: string | null, - isOpen: boolean, - method: string | null - onClose: () => void + address: string | null; + isOpen: boolean; + method: string | null; + onClose: () => void; }; -type State = { - accountId: string | null, - address: string | null, - contractAbi?: Abi | null, - endowment: BN, - gasLimit: BN, - isAddressValid: boolean, - isBusy: boolean, - method: string | null, - params: Array -}; +interface State { + accountId: string | null; + address: string | null; + contractAbi?: Abi | null; + endowment: BN; + gasLimit: BN; + isAddressValid: boolean; + isBusy: boolean; + method: string | null; + params: any[]; +} class Call extends TxComponent { - defaultState: State = { + public defaultState: State = { address: null, accountId: null, endowment: new BN(0), @@ -47,24 +47,25 @@ class Call extends TxComponent { params: [] }; - state: State = this.defaultState; + public state: State = this.defaultState; - static getDerivedStateFromProps ({ address: propsAddress, method: propsMethod, isOpen }: Props, { address, method }: State) { + public static getDerivedStateFromProps ({ address: propsAddress, method: propsMethod, isOpen }: Props, { address, method }: State): State | null { if (!isOpen) { return { address: null, method: null, contractAbi: null, - isValidAddress: false - }; + isAddressValid: false + } as unknown as State; } + return { ...( !address ? { address: propsAddress, contractAbi: propsAddress ? getContractAbi(propsAddress) : null, - isValidAddress: !!propsAddress + isAddressValid: !!propsAddress } : {} ), @@ -73,10 +74,10 @@ class Call extends TxComponent { ? { method: propsMethod } : {} ) - }; + } as unknown as State; } - render () { + public render (): React.ReactNode { const { isOpen, t } = this.props; return ( @@ -99,11 +100,11 @@ class Call extends TxComponent { ); } - renderContent = () => { + public renderContent (): React.ReactNode { const { t } = this.props; const { gasLimit } = this.state; - const [ address, contractAbi, method ] = this.getCallProps(); + const [address, contractAbi, method] = this.getCallProps(); const isEndowValid = true; const isGasValid = !gasLimit.isZero(); @@ -177,7 +178,7 @@ class Call extends TxComponent { ); } - private renderButtons = () => { + private renderButtons (): React.ReactNode { const { api, t } = this.props; const { accountId, gasLimit, isAddressValid } = this.state; const isEndowValid = true; // !endowment.isZero(); @@ -218,12 +219,12 @@ class Call extends TxComponent { } else { address = this.state.address; contractAbi = this.state.contractAbi || getContractAbi(address); - method = contractAbi && this.state.method && contractAbi.messages[this.state.method] ? - this.state.method : - ( - contractAbi ? - Object.keys(contractAbi.messages)[0] : - null + method = contractAbi && this.state.method && contractAbi.messages[this.state.method] + ? this.state.method + : ( + contractAbi + ? Object.keys(contractAbi.messages)[0] + : null ); } @@ -234,12 +235,12 @@ class Call extends TxComponent { ]; } - private constructCall = (): Array => { + private constructCall = (): any[] => { const { endowment, gasLimit, params } = this.state; - const [ address, contractAbi, method ] = this.getCallProps(); + const [address, contractAbi, method] = this.getCallProps(); if (!contractAbi || !method) { return []; @@ -270,29 +271,30 @@ class Call extends TxComponent { this.setState({ method, params: [] }); } - private onChangeParams = (params: Array): void => { + private onChangeParams = (params: any[]): void => { this.setState({ params }); } private toggleBusy = (): void => { - this.setState(({ isBusy }) => ({ + this.setState(({ isBusy }): State => ({ isBusy: !isBusy - })); + }) as unknown as State); } - private reset = () => { - this.setState((state: State) => { + private reset = (): void => { + this.setState((state: State): State => { if (!state.isBusy) { return { ...state, ...this.defaultState }; } - return {} as State; + + return {} as unknown as State; }); } - private onClose = () => { + private onClose = (): void => { const { onClose } = this.props; this.reset(); diff --git a/packages/app-contracts/src/Contracts/Contract.tsx b/packages/app-contracts/src/Contracts/Contract.tsx index bf282306bd..07f67df201 100644 --- a/packages/app-contracts/src/Contracts/Contract.tsx +++ b/packages/app-contracts/src/Contracts/Contract.tsx @@ -16,21 +16,21 @@ import { withMulti } from '@polkadot/ui-api'; import translate from '../translate'; type Props = I18nProps & RouteComponentProps & { - basePath: string, - address: string, - onCall: (callAddress?: string, callMethod?: string) => void + basePath: string; + address: string; + onCall: (callAddress?: string, callMethod?: string) => void; }; -type State = { - isBackupOpen: boolean, - isForgetOpen: boolean, - isPasswordOpen: boolean -}; +interface State { + isBackupOpen: boolean; + isForgetOpen: boolean; + isPasswordOpen: boolean; +} class Contract extends React.PureComponent { - state: State; + public state: State; - constructor (props: Props) { + public constructor (props: Props) { super(props); this.state = { isBackupOpen: false, @@ -39,7 +39,7 @@ class Contract extends React.PureComponent { }; } - render () { + public render (): React.ReactNode { const { address, onCall } = this.props; const contractAbi = getContractAbi(address); @@ -72,7 +72,7 @@ class Contract extends React.PureComponent { ); } - private renderModals () { + private renderModals (): React.ReactNode { const { address } = this.props; const { isForgetOpen } = this.state; @@ -112,10 +112,10 @@ class Contract extends React.PureComponent { return; } - const status = { + const status: Partial = { account: address, action: 'forget' - } as ActionStatus; + }; try { keyring.forgetContract(address); @@ -128,7 +128,7 @@ class Contract extends React.PureComponent { this.toggleForget(); } - private renderButtons () { + private renderButtons (): React.ReactNode { const { address, onCall, t } = this.props; return ( @@ -144,7 +144,7 @@ class Contract extends React.PureComponent { isPrimary label={t('execute')} labelIcon='play' - onClick={() => onCall(address)} + onClick={(): void => onCall(address)} size='small' tooltip={t('Call a method on this contract')} /> diff --git a/packages/app-contracts/src/Contracts/ValidateAddr.tsx b/packages/app-contracts/src/Contracts/ValidateAddr.tsx index 6c2fadad28..6785dcc3ba 100644 --- a/packages/app-contracts/src/Contracts/ValidateAddr.tsx +++ b/packages/app-contracts/src/Contracts/ValidateAddr.tsx @@ -1,3 +1,4 @@ +/* eslint-disable @typescript-eslint/camelcase */ // Copyright 2017-2019 @polkadot/app-contracts authors & contributors // This software may be modified and distributed under the terms // of the Apache-2.0 license. See the LICENSE file for details. @@ -14,25 +15,25 @@ import keyring from '@polkadot/ui-keyring'; import translate from '../translate'; type Props = ApiProps & I18nProps & { - address?: string | null, - contract_contractInfoOf?: Option, - onChange: (isValid: boolean) => void + address?: string | null; + contract_contractInfoOf?: Option; + onChange: (isValid: boolean) => void; }; -type State = { - isStored: boolean, - isValidAddr: boolean, - isValid: boolean -}; +interface State { + isStored: boolean; + isValidAddr: boolean; + isValid: boolean; +} class ValidateAddr extends React.PureComponent { - state: State = { + public state: State = { isStored: false, isValidAddr: false, isValid: false }; - static getDerivedStateFromProps ({ address, contract_contractInfoOf, onChange }: Props): State { + public static getDerivedStateFromProps ({ address, contract_contractInfoOf, onChange }: Props): State { let isValidAddr = false; try { @@ -59,7 +60,7 @@ class ValidateAddr extends React.PureComponent { }; } - render () { + public render (): React.ReactNode { const { t } = this.props; const { isValid, isValidAddr } = this.state; diff --git a/packages/app-contracts/src/Contracts/index.tsx b/packages/app-contracts/src/Contracts/index.tsx index c80a4446f5..0ff155efc2 100644 --- a/packages/app-contracts/src/Contracts/index.tsx +++ b/packages/app-contracts/src/Contracts/index.tsx @@ -18,22 +18,22 @@ import Call from './Call'; type Props = ComponentProps & I18nProps & RouteComponentProps; -type State = { - isAddOpen: boolean, - isCallOpen: boolean, - callAddress: string | null, - callMethod: string | null -}; +interface State { + isAddOpen: boolean; + isCallOpen: boolean; + callAddress: string | null; + callMethod: string | null; +} class Contracts extends React.PureComponent { - state: State = { + public state: State = { callAddress: null, callMethod: null, isAddOpen: false, isCallOpen: false }; - render () { + public render (): React.ReactNode { const { accounts, basePath, contracts, hasCode, showDeploy, t } = this.props; const { callAddress, callMethod, isAddOpen, isCallOpen } = this.state; @@ -62,7 +62,7 @@ class Contracts extends React.PureComponent { } > - {accounts && contracts && Object.keys(contracts).map((address) => { + {accounts && contracts && Object.keys(contracts).map((address): React.ReactNode => { return ( { ); } - private showAdd = () => { + private showAdd = (): void => { this.setState({ isAddOpen: true }); } - private hideAdd = () => { + private hideAdd = (): void => { this.setState({ isAddOpen: false }); } - private showCall = (callAddress?: string, callMethod?: string) => { + private showCall = (callAddress?: string, callMethod?: string): void => { this.setState({ isCallOpen: true, callAddress: callAddress || null, @@ -108,7 +108,7 @@ class Contracts extends React.PureComponent { }); } - private hideCall = () => { + private hideCall = (): void => { this.setState({ isCallOpen: false, callAddress: null, diff --git a/packages/app-contracts/src/Deploy.tsx b/packages/app-contracts/src/Deploy.tsx index 1621576686..bb9afea0cb 100644 --- a/packages/app-contracts/src/Deploy.tsx +++ b/packages/app-contracts/src/Deploy.tsx @@ -22,25 +22,26 @@ import Params from './Params'; import store from './store'; import translate from './translate'; -type ConstructOptions = Array<{key: string, text: string, value: string}>; +type ConstructOptions = { key: string; text: string; value: string }[]; type Props = ContractModalProps & ApiProps & I18nProps & RouteComponentProps & { - codeHash?: string + codeHash?: string; }; -type State = ContractModalState & { - codeHash?: string, - constructOptions: ConstructOptions, - endowment: BN, - isHashValid: boolean, - params: Array -}; +interface State extends ContractModalState { + codeHash?: string; + constructOptions: ConstructOptions; + endowment: BN; + isHashValid: boolean; + params: any[]; +} class Deploy extends ContractModal { - headerText = 'Deploy a new contract'; - isContract = true; + protected headerText = 'Deploy a new contract'; - constructor (props: Props) { + public isContract = true; + + public constructor (props: Props) { super(props); this.defaultState = { @@ -54,7 +55,7 @@ class Deploy extends ContractModal { this.state = this.defaultState; } - componentWillReceiveProps (nextProps: Props, nextState: State) { + public componentWillReceiveProps (nextProps: Props, nextState: State): void { super.componentWillReceiveProps(nextProps, nextState); if (nextProps.codeHash && nextProps.codeHash !== this.props.codeHash) { @@ -64,7 +65,7 @@ class Deploy extends ContractModal { } } - renderContent = () => { + protected renderContent = (): React.ReactNode => { const { t } = this.props; const { codeHash, constructOptions, contractAbi, endowment, isAbiSupplied, isBusy, isHashValid } = this.state; @@ -137,7 +138,7 @@ class Deploy extends ContractModal { ); } - renderButtons = () => { + protected renderButtons = (): React.ReactNode => { const { api, t } = this.props; const { accountId, endowment, gasLimit, isAbiValid, isHashValid, isNameValid } = this.state; const isEndowValid = !endowment.isZero(); @@ -163,9 +164,9 @@ class Deploy extends ContractModal { ); } - private getContractAbiState = (abi: string | null | undefined, contractAbi: Abi | null = null): State => { + private getContractAbiState = (abi: string | null | undefined, contractAbi: Abi | null = null): Partial => { if (contractAbi) { - const args = contractAbi.deploy.args.map(({ name, type }) => name + ': ' + type); + const args = contractAbi.deploy.args.map(({ name, type }): string => `${name}: ${type}`); const text = `deploy(${args.join(', ')})`; return { @@ -182,7 +183,7 @@ class Deploy extends ContractModal { type: getTypeDef(type, name) })) ) - } as State; + }; } else { return { constructOptions: [] as ConstructOptions, @@ -190,8 +191,8 @@ class Deploy extends ContractModal { contractAbi: null, isAbiSupplied: false, isAbiValid: false, - params: [] as Array - } as State; + params: [] as unknown[] + }; } } @@ -209,14 +210,14 @@ class Deploy extends ContractModal { isHashValid: true, isNameValid: true, ...this.getContractAbiState(json.abi, contractAbi) - } as State; + } as unknown as State; } } - return {} as State; + return {} as unknown as State; } - private constructCall = (): Array => { + private constructCall = (): any[] => { const { codeHash, contractAbi, endowment, gasLimit, params } = this.state; if (!contractAbi) { @@ -228,7 +229,7 @@ class Deploy extends ContractModal { protected onAddAbi = (abi: string | null | undefined, contractAbi?: Abi | null): void => { this.setState({ - ...this.getContractAbiState(abi, contractAbi) + ...(this.getContractAbiState(abi, contractAbi) as State) }); } @@ -242,20 +243,20 @@ class Deploy extends ContractModal { this.setState({ endowment: endowment || new BN(0) }); } - private onChangeParams = (params: Array): void => { + private onChangeParams = (params: any[]): void => { this.setState({ params }); } - private onSuccess = async (result: SubmittableResult) => { + private onSuccess = async (result: SubmittableResult): Promise => { const { api, history } = this.props; const section = api.tx.contracts ? 'contracts' : 'contract'; const record = result.findRecord(section, 'Instantiated'); if (record) { - const address = record.event.data[1] as any as AccountId; + const address = record.event.data[1] as unknown as AccountId; - this.setState(({ abi, name, tags }) => { + this.setState(({ abi, name, tags }): State | unknown => { if (!abi || !name) { return; } @@ -273,10 +274,9 @@ class Deploy extends ContractModal { this.onClose(); - return { isBusy: false } as State; + return { isBusy: false } as unknown as State; }); } - } } diff --git a/packages/app-contracts/src/Modal.tsx b/packages/app-contracts/src/Modal.tsx index eb698a1370..b4285601a6 100644 --- a/packages/app-contracts/src/Modal.tsx +++ b/packages/app-contracts/src/Modal.tsx @@ -11,25 +11,25 @@ import { Button, Input, InputAddress, InputNumber, Modal, TxComponent } from '@p import ABI from './ABI'; -export type ContractModalProps = I18nProps & { - basePath: string, - isNew?: boolean, - isOpen: boolean, - onClose?: () => void -}; +export interface ContractModalProps extends I18nProps { + basePath: string; + isNew?: boolean; + isOpen: boolean; + onClose?: () => void; +} -export type ContractModalState = { - abi?: string | null, - accountId?: string | null, - contractAbi?: Abi | null, - gasLimit: BN, - isAbiSupplied: boolean, - isAbiValid: boolean, - isBusy: boolean, - isNameValid: boolean, - name?: string | null, - tags: Array -}; +export interface ContractModalState { + abi?: string | null; + accountId?: string | null; + contractAbi?: Abi | null; + gasLimit: BN; + isAbiSupplied: boolean; + isAbiValid: boolean; + isBusy: boolean; + isNameValid: boolean; + name?: string | null; + tags: string[]; +} class ContractModal

extends TxComponent { protected defaultState: S = { @@ -40,20 +40,20 @@ class ContractModal

isBusy: false, isNameValid: false, name: null, - tags: [] as Array + tags: [] as string[] } as S; - state: S = this.defaultState; + public state: S = this.defaultState; - isContract?: boolean; + protected isContract?: boolean; - componentWillReceiveProps ({ isOpen }: P, _: S) { + public componentWillReceiveProps ({ isOpen }: P, _: S): void { if (isOpen && !this.props.isOpen && !this.state.isBusy) { this.reset(); } } - render () { + public render (): React.ReactNode { const { isOpen, t } = this.props; return ( @@ -77,24 +77,26 @@ class ContractModal

} protected headerText: string = ''; + protected renderContent: () => React.ReactNode | null = () => null; + protected renderButtons: () => React.ReactNode | null = () => null; - protected renderInputAbi () { + protected renderInputAbi (): React.ReactNode { const { t } = this.props; const { isBusy } = this.state; return ( ); } - protected renderInputAccount () { + protected renderInputAccount (): React.ReactNode { const { t } = this.props; const { accountId, isBusy } = this.state; @@ -121,7 +123,7 @@ class ContractModal

); } - protected renderInputName () { + protected renderInputName (): React.ReactNode { const { isNew, t } = this.props; const { isBusy, isNameValid, name } = this.state; @@ -129,16 +131,16 @@ class ContractModal

); } - protected renderInputGas () { + protected renderInputGas (): React.ReactNode { const { t } = this.props; const { gasLimit, isBusy } = this.state; const isGasValid = !gasLimit.isZero(); @@ -166,7 +168,7 @@ class ContractModal

); } - protected renderCancelButton () { + protected renderCancelButton (): React.ReactNode { const { t } = this.props; return ( @@ -181,21 +183,22 @@ class ContractModal

); } - protected reset = () => { + protected reset = (): void => { this.setState( this.defaultState ); } - protected toggleBusy = (isBusy?: boolean) => () => { - this.setState((state: S) => { - return { - isBusy: isBusy === undefined ? !state.isBusy : isBusy - }; - }); - } + protected toggleBusy = (isBusy?: boolean): () => void => + (): void => { + this.setState((state: S): S => { + return { + isBusy: isBusy === undefined ? !state.isBusy : isBusy + } as unknown as S; + }); + } - protected onClose = () => { + protected onClose = (): void => { const { onClose } = this.props; onClose && onClose(); diff --git a/packages/app-contracts/src/Params.tsx b/packages/app-contracts/src/Params.tsx index b298b96443..230691b58c 100644 --- a/packages/app-contracts/src/Params.tsx +++ b/packages/app-contracts/src/Params.tsx @@ -16,27 +16,32 @@ interface Props { onEnter?: () => void; } +interface ParamDef { + name: string; + type: TypeDef; +} + interface State { - params: { name: string; type: TypeDef }[]; + params: ParamDef[]; } export default class Params extends React.PureComponent { - state: State = { params: [] }; + public state: State = { params: [] }; - static getDerivedStateFromProps ({ params }: Props): State | null { + public static getDerivedStateFromProps ({ params }: Props): State | null { if (!params) { return { params: [] }; } return { - params: params.map(({ name, type }) => ({ + params: params.map(({ name, type }): ParamDef => ({ name, type: getTypeDef(type, name) })) - } as State; + } as unknown as State; } - render () { + public render (): React.ReactNode { const { isDisabled, onEnter } = this.props; const { params } = this.state; @@ -57,6 +62,6 @@ export default class Params extends React.PureComponent { private onChange = (values: RawParams): void => { const { onChange } = this.props; - onChange(values.map(({ value }) => value)); + onChange(values.map(({ value }): any => value)); } } diff --git a/packages/app-contracts/src/RemoveABI.tsx b/packages/app-contracts/src/RemoveABI.tsx index 6027fab4f1..f499d01fd8 100644 --- a/packages/app-contracts/src/RemoveABI.tsx +++ b/packages/app-contracts/src/RemoveABI.tsx @@ -10,14 +10,14 @@ import { Button, CodeRow, Modal } from '@polkadot/ui-app'; import translate from './translate'; -type Props = I18nProps & { - code: CodeStored, - onClose: () => void, - onRemove: () => void -}; +interface Props extends I18nProps { + code: CodeStored; + onClose: () => void; + onRemove: () => void; +} class RemoveABI extends React.PureComponent { - render () { + public render (): React.ReactNode { const { onClose, t } = this.props; return ( { ); } - private content = () => { + private content = (): React.ReactNode => { const { t } = this.props; return ( @@ -48,7 +48,7 @@ class RemoveABI extends React.PureComponent { ); } - private renderButtons () { + private renderButtons (): React.ReactNode { const { onClose, t } = this.props; return ( @@ -70,7 +70,7 @@ class RemoveABI extends React.PureComponent { ); } - private renderContent () { + private renderContent (): React.ReactNode { const { code } = this.props; return ( @@ -83,7 +83,7 @@ class RemoveABI extends React.PureComponent { ); } - private onRemove = () => { + private onRemove = (): void => { const { onClose, onRemove } = this.props; onClose && onClose(); diff --git a/packages/app-contracts/src/index.tsx b/packages/app-contracts/src/index.tsx index 82b3afae04..f2fc0a1d5a 100644 --- a/packages/app-contracts/src/index.tsx +++ b/packages/app-contracts/src/index.tsx @@ -21,48 +21,48 @@ import Codes from './Codes'; import Deploy from './Deploy'; type Props = AppProps & I18nProps & RouteComponentProps & { - accounts: SubjectInfo[], - contracts: SubjectInfo[] + accounts: SubjectInfo[]; + contracts: SubjectInfo[]; }; -type State = { - codeHash?: string, - hasContracts: boolean, - isDeployOpen: boolean, - updated: number -}; +interface State { + codeHash?: string; + hasContracts: boolean; + isDeployOpen: boolean; + updated: number; +} class App extends React.PureComponent { - state: State = { + public state: State = { hasContracts: false, isDeployOpen: false, updated: 0 }; - constructor (props: Props) { + public constructor (props: Props) { super(props); store.on('new-code', this.triggerUpdate); store.on('removed-code', this.triggerUpdate); // since we have a dep on the async API, we load here - store.loadAll().catch(() => { + store.loadAll().catch((): void => { // noop, handled internally }); } - static getDerivedStateFromProps ({ contracts }: Props): State { + public static getDerivedStateFromProps ({ contracts }: Props): State { const hasContracts = !!contracts && Object.keys(contracts).length >= 1; return { hasContracts - } as State; + } as unknown as State; } - render () { + public render (): React.ReactNode { const { basePath, t } = this.props; const { codeHash, isDeployOpen } = this.state; - const hidden: Array = []; + const hidden: string[] = []; return (

@@ -81,7 +81,7 @@ class App extends React.PureComponent { name: 'contracts', text: 'Contracts' } - ].map(tab => ({ ...tab, text: t(tab.text) })) + ].map((tab) => ({ ...tab, text: t(tab.text) })) } /> @@ -99,8 +99,8 @@ class App extends React.PureComponent { ); } - private renderComponent (Component: React.ComponentType) { - return ({ match }: LocationProps) => { + private renderComponent (Component: React.ComponentType): (p: LocationProps) => React.ReactNode { + return ({ match }: LocationProps): React.ReactNode => { const { accounts, basePath, contracts, location, onStatusChange } = this.props; if (!contracts) { @@ -122,14 +122,15 @@ class App extends React.PureComponent { }; } - private showDeploy = (codeHash?: string) => () => { - this.setState({ - codeHash: codeHash || undefined, - isDeployOpen: true - }); - } + private showDeploy = (codeHash?: string): () => void => + (): void => { + this.setState({ + codeHash: codeHash || undefined, + isDeployOpen: true + }); + } - private hideDeploy = () => { + private hideDeploy = (): void => { this.setState({ isDeployOpen: false }); } @@ -137,6 +138,7 @@ class App extends React.PureComponent { this.setState({ updated: Date.now() }); } } + export default withMulti( App, translate, diff --git a/packages/app-contracts/src/store.ts b/packages/app-contracts/src/store.ts index 60eec950bd..b723de4623 100644 --- a/packages/app-contracts/src/store.ts +++ b/packages/app-contracts/src/store.ts @@ -17,19 +17,19 @@ const codeRegex = new RegExp(`^${KEY_CODE}`, ''); class Store extends EventEmitter { private allCode: { [index: string]: CodeStored } = {}; - get hasCode (): boolean { + public get hasCode (): boolean { return Object.keys(this.allCode).length !== 0; } - getAllCode (): Array { + public getAllCode (): CodeStored[] { return Object.values(this.allCode); } - getCode (codeHash: string): CodeStored { + public getCode (codeHash: string): CodeStored { return this.allCode[codeHash]; } - async saveCode (codeHash: string | Hash, partial: Partial) { + public async saveCode (codeHash: string | Hash, partial: Partial): Promise { const hex = (typeof codeHash === 'string' ? new Hash(codeHash) : codeHash).toHex(); const existing = this.getCode(hex); @@ -39,26 +39,26 @@ class Store extends EventEmitter { ...partial, codeHash: hex, genesisHash: api.genesisHash.toHex() - } as CodeJson; + }; store.set(`${KEY_CODE}${json.codeHash}`, json); - this.addCode(json); + this.addCode(json as CodeJson); } - forgetCode (codeHash: string) { + public forgetCode (codeHash: string): void { store.remove(`${KEY_CODE}${codeHash}`); this.removeCode(codeHash); } - async loadAll () { + public async loadAll (): Promise { try { await api.isReady; const genesisHash = api.genesisHash.toHex(); - store.each((json: CodeJson, key: string) => { + store.each((json: CodeJson, key: string): void => { if (json && json.genesisHash !== genesisHash) { return; } @@ -72,7 +72,7 @@ class Store extends EventEmitter { } } - private addCode (json: CodeJson) { + private addCode (json: CodeJson): void { try { this.allCode[json.codeHash] = { json, @@ -87,7 +87,7 @@ class Store extends EventEmitter { } } - private removeCode (codeHash: string) { + private removeCode (codeHash: string): void { try { delete this.allCode[codeHash]; this.emit('removed-code'); diff --git a/packages/app-contracts/src/types.ts b/packages/app-contracts/src/types.ts index 7301700d76..e22bb629a8 100644 --- a/packages/app-contracts/src/types.ts +++ b/packages/app-contracts/src/types.ts @@ -6,32 +6,35 @@ import { Abi } from '@polkadot/api-contract'; import { AppProps } from '@polkadot/ui-app/types'; import { SubjectInfo } from '@polkadot/ui-keyring/observable/types'; -export type LocationProps = { +export interface LocationProps { match: { - params: { [index: string]: any } - } -}; + params: Record; + }; +} export type ComponentProps = AppProps & LocationProps & { - accounts: SubjectInfo[], - contracts: SubjectInfo[], - hasCode: boolean, - showDeploy: (codeHash?: string) => () => void + accounts: SubjectInfo[]; + contracts: SubjectInfo[]; + hasCode: boolean; + showDeploy: (codeHash?: string) => () => void; }; -export type CodeJson = { - abi?: string | null, - codeHash: string - name: string, - genesisHash: string, - tags: Array -}; +export interface CodeJson { + abi?: string | null; + codeHash: string; + name: string; + genesisHash: string; + tags: string[]; +} -export type CodeStored = { json: CodeJson , contractAbi?: Abi }; +export interface CodeStored { + json: CodeJson; + contractAbi?: Abi; +} -export type ContractJsonOld = { - genesisHash: string, - abi: string, - address: string, - name: string -}; +export interface ContractJsonOld { + genesisHash: string; + abi: string; + address: string; + name: string; +} diff --git a/packages/app-dashboard/src/Entry.tsx b/packages/app-dashboard/src/Entry.tsx index 2362897b9c..706a2b2505 100644 --- a/packages/app-dashboard/src/Entry.tsx +++ b/packages/app-dashboard/src/Entry.tsx @@ -12,12 +12,12 @@ import { Icon } from '@polkadot/ui-app'; import translate from './translate'; -type Props = I18nProps & { - route: Route -}; +interface Props extends I18nProps { + route: Route; +} class Entry extends React.PureComponent { - render () { + public render (): React.ReactNode { const { className, route: { i18n, icon, name }, t } = this.props; return ( diff --git a/packages/app-dashboard/src/Spacer.tsx b/packages/app-dashboard/src/Spacer.tsx index a5bee94fbe..257b13a0e4 100644 --- a/packages/app-dashboard/src/Spacer.tsx +++ b/packages/app-dashboard/src/Spacer.tsx @@ -4,10 +4,10 @@ import React from 'react'; -type Props = {}; +interface Props {} export default class Spacer extends React.PureComponent { - render () { + public render (): React.ReactNode { return (
); diff --git a/packages/app-dashboard/src/index.tsx b/packages/app-dashboard/src/index.tsx index 2d4595adbe..cd1399bc60 100644 --- a/packages/app-dashboard/src/index.tsx +++ b/packages/app-dashboard/src/index.tsx @@ -12,25 +12,25 @@ import routing from '@polkadot/apps-routing'; import Entry from './Entry'; import Spacer from './Spacer'; -type Props = AppProps & { +interface Props extends AppProps { className?: string; -}; +} -type State = { - routes: Array -}; +interface State { + routes: Route[]; +} class App extends React.PureComponent { // FIXME Atm we are not applying all the logic around should this be hidden or not, i.e. // is the api available, are there accounts, etc. (That logic should also be extracted so // it can be used in a proper way here) - state: State = { - routes: routing.routes.filter((route) => - route && !route.display.isHidden && route.name !== 'dashboard' - ) as Array + public state: State = { + routes: routing.routes.filter((route): boolean => + !!route && !route.display.isHidden && route.name !== 'dashboard' + ) as Route[] }; - render () { + public render (): React.ReactNode { const { className } = this.props; const { routes } = this.state; diff --git a/packages/app-democracy/src/Overview/Proposal.tsx b/packages/app-democracy/src/Overview/Proposal.tsx index e08bff76d6..3a565ba10c 100644 --- a/packages/app-democracy/src/Overview/Proposal.tsx +++ b/packages/app-democracy/src/Overview/Proposal.tsx @@ -14,14 +14,14 @@ import { formatBalance } from '@polkadot/util'; import translate from '../translate'; import Seconding from './Seconding'; -type Props = I18nProps & { - democracy_depositOf?: [Balance, Vector] | null, - idNumber: BN, - value: Proposal -}; +interface Props extends I18nProps { + democracy_depositOf?: [Balance, Vector] | null; + idNumber: BN; + value: Proposal; +} class ProposalDisplay extends React.PureComponent { - render () { + public render (): React.ReactNode { const { className, democracy_depositOf, idNumber, value } = this.props; const depositors = democracy_depositOf ? democracy_depositOf[1] diff --git a/packages/app-democracy/src/Overview/Proposals.tsx b/packages/app-democracy/src/Overview/Proposals.tsx index 3e5737d9df..995e6fda10 100644 --- a/packages/app-democracy/src/Overview/Proposals.tsx +++ b/packages/app-democracy/src/Overview/Proposals.tsx @@ -13,20 +13,20 @@ import { Column } from '@polkadot/ui-app'; import ProposalDisplay from './Proposal'; import translate from '../translate'; -type Props = I18nProps & { - democracy_publicProps?: Array<[BN, Proposal]> -}; +interface Props extends I18nProps { + democracy_publicProps?: [BN, Proposal][]; +} -type State = { - isProposeOpen: boolean -}; +interface State { + isProposeOpen: boolean; +} class Proposals extends React.PureComponent { - state: State = { + public state: State = { isProposeOpen: false }; - render () { + public render (): React.ReactNode { const { t } = this.props; return ( diff --git a/packages/app-democracy/src/Overview/Referendum.tsx b/packages/app-democracy/src/Overview/Referendum.tsx index 7ccdc3c475..0feb8f22df 100644 --- a/packages/app-democracy/src/Overview/Referendum.tsx +++ b/packages/app-democracy/src/Overview/Referendum.tsx @@ -25,25 +25,25 @@ const COLORS_NAY = settings.uiTheme === 'substrate' ? ['#d44', '#e44'] : ['#d75ea1', '#e189ba']; -type Props = I18nProps & { - idNumber: BN, - chain_bestNumber?: BN, - democracy_referendumVotesFor?: Array, - democracy_publicDelay?: BN, - value: ReferendumInfoExtended -}; +interface Props extends I18nProps { + idNumber: BN; + chain_bestNumber?: BN; + democracy_referendumVotesFor?: DerivedReferendumVote[]; + democracy_publicDelay?: BN; + value: ReferendumInfoExtended; +} -type State = { - voteCount: number, - voteCountAye: number, - voteCountNay: number, - votedAye: BN, - votedNay: BN, - votedTotal: BN -}; +interface State { + voteCount: number; + voteCountAye: number; + voteCountNay: number; + votedAye: BN; + votedNay: BN; + votedTotal: BN; +} class Referendum extends React.PureComponent { - state: State = { + public state: State = { voteCount: 0, voteCountAye: 0, voteCountNay: 0, @@ -86,7 +86,7 @@ class Referendum extends React.PureComponent { return newState; } - render () { + public render (): React.ReactNode { const { chain_bestNumber, className, value } = this.props; if (!chain_bestNumber || value.end.sub(chain_bestNumber).lten(0)) { diff --git a/packages/app-democracy/src/Overview/Referendums.tsx b/packages/app-democracy/src/Overview/Referendums.tsx index a42fdaae67..57e5c039bb 100644 --- a/packages/app-democracy/src/Overview/Referendums.tsx +++ b/packages/app-democracy/src/Overview/Referendums.tsx @@ -13,12 +13,12 @@ import { Column } from '@polkadot/ui-app'; import Referendum from './Referendum'; import translate from '../translate'; -type Props = I18nProps & { - democracy_referendums?: Array> -}; +interface Props extends I18nProps { + democracy_referendums?: Option[]; +} class Referendums extends React.PureComponent { - render () { + public render (): React.ReactNode { const { t } = this.props; return ( diff --git a/packages/app-democracy/src/Overview/Seconding.tsx b/packages/app-democracy/src/Overview/Seconding.tsx index c1756f443a..e02739de52 100644 --- a/packages/app-democracy/src/Overview/Seconding.tsx +++ b/packages/app-democracy/src/Overview/Seconding.tsx @@ -14,23 +14,23 @@ import { withMulti, withObservable } from '@polkadot/ui-api'; import translate from '../translate'; -type Props = I18nProps & { - allAccounts?: SubjectInfo, - depositors: Array, - proposalId: BN | number -}; +interface Props extends I18nProps { + allAccounts?: SubjectInfo; + depositors: AccountId[]; + proposalId: BN | number; +} -type State = { - accountId?: string, - isSecondingOpen: boolean -}; +interface State { + accountId?: string; + isSecondingOpen: boolean; +} class Seconding extends React.PureComponent { - state: State = { + public state: State = { isSecondingOpen: false }; - render () { + public render (): React.ReactNode { const { allAccounts, t } = this.props; const hasAccounts = allAccounts && Object.keys(allAccounts).length !== 0; @@ -101,12 +101,12 @@ class Seconding extends React.PureComponent { ); } - private onChangeAccount = (accountId?: string) => { + private onChangeAccount = (accountId?: string): void => { this.setState({ accountId }); } private toggleSeconding = (): void => { - this.setState(({ isSecondingOpen }) => ({ + this.setState(({ isSecondingOpen }): State => ({ isSecondingOpen: !isSecondingOpen })); } diff --git a/packages/app-democracy/src/Overview/Summary.tsx b/packages/app-democracy/src/Overview/Summary.tsx index bebe65013b..8c1c76e970 100644 --- a/packages/app-democracy/src/Overview/Summary.tsx +++ b/packages/app-democracy/src/Overview/Summary.tsx @@ -12,17 +12,17 @@ import { formatNumber } from '@polkadot/util'; import translate from '../translate'; -type Props = I18nProps & { - chain_bestNumber?: BN, - democracy_launchPeriod?: BN, - democracy_nextTally?: BN, - democracy_publicDelay?: BN, - democracy_publicPropCount?: BN, - democracy_referendumCount?: BN -}; +interface Props extends I18nProps { + chain_bestNumber?: BN; + democracy_launchPeriod?: BN; + democracy_nextTally?: BN; + democracy_publicDelay?: BN; + democracy_publicPropCount?: BN; + democracy_referendumCount?: BN; +} class Summary extends React.PureComponent { - render () { + public render (): React.ReactNode { const { chain_bestNumber = new BN(0), democracy_launchPeriod = new BN(1), democracy_nextTally = new BN(0), democracy_publicPropCount, democracy_referendumCount = new BN(0), t } = this.props; return ( diff --git a/packages/app-democracy/src/Overview/Voting.tsx b/packages/app-democracy/src/Overview/Voting.tsx index ff82fd146a..77877593a1 100644 --- a/packages/app-democracy/src/Overview/Voting.tsx +++ b/packages/app-democracy/src/Overview/Voting.tsx @@ -13,22 +13,22 @@ import { withMulti, withObservable } from '@polkadot/ui-api'; import translate from '../translate'; -type Props = I18nProps & { - allAccounts?: SubjectInfo, - referendumId: BN | number -}; +interface Props extends I18nProps { + allAccounts?: SubjectInfo; + referendumId: BN | number; +} -type State = { - accountId?: string, - isVotingOpen: boolean, - voteOptions: Array<{ text: React.ReactNode, value: boolean }>, - voteValue: boolean -}; +interface State { + accountId?: string; + isVotingOpen: boolean; + voteOptions: { text: React.ReactNode, value: boolean }[]; + voteValue: boolean; +} class Voting extends React.PureComponent { - state: State; + public state: State; - constructor (props: Props) { + public constructor (props: Props) { super(props); const { t } = props; @@ -43,7 +43,7 @@ class Voting extends React.PureComponent { }; } - render () { + public render (): React.ReactNode { const { allAccounts, t } = this.props; const hasAccounts = allAccounts && Object.keys(allAccounts).length !== 0; @@ -119,18 +119,18 @@ class Voting extends React.PureComponent { ); } - private onChangeAccount = (accountId?: string) => { + private onChangeAccount = (accountId?: string): void => { this.setState({ accountId }); } - private onChangeVote = (voteValue: boolean) => { + private onChangeVote = (voteValue: boolean): void => { this.setState({ voteValue }); } private toggleVoting = (): void => { - this.setState(({ isVotingOpen }) => ({ + this.setState(({ isVotingOpen }): State => ({ isVotingOpen: !isVotingOpen - })); + }) as unknown as State); } } diff --git a/packages/app-democracy/src/Overview/index.tsx b/packages/app-democracy/src/Overview/index.tsx index fa660510ec..d5def2d6d0 100644 --- a/packages/app-democracy/src/Overview/index.tsx +++ b/packages/app-democracy/src/Overview/index.tsx @@ -14,7 +14,7 @@ import Summary from './Summary'; type Props = AppProps & BareProps & I18nProps; export default class Overview extends React.PureComponent { - render () { + public render (): React.ReactNode { return ( <> diff --git a/packages/app-democracy/src/Propose.tsx b/packages/app-democracy/src/Propose.tsx index c7e0bbc2e3..18ee32fcbf 100644 --- a/packages/app-democracy/src/Propose.tsx +++ b/packages/app-democracy/src/Propose.tsx @@ -17,24 +17,24 @@ import { withApi, withMulti } from '@polkadot/ui-api'; import translate from './translate'; type Props = I18nProps & ApiProps & RouteComponentProps & { - basePath: string + basePath: string; }; -type State = { - accountId?: string, - method: Method | null, - value: BN, - isValid: boolean -}; +interface State { + accountId?: string; + method: Method | null; + value: BN; + isValid: boolean; +} class Propose extends TxComponent { - state: State = { + public state: State = { method: null, value: new BN(0), isValid: false }; - render () { + public render (): React.ReactNode { const { apiDefaultTxSudo, t } = this.props; const { isValid, accountId, method, value } = this.state; const hasValue = !!value && value.gtn(0); diff --git a/packages/app-democracy/src/index.tsx b/packages/app-democracy/src/index.tsx index 766d6e309a..aa785bfec6 100644 --- a/packages/app-democracy/src/index.tsx +++ b/packages/app-democracy/src/index.tsx @@ -17,12 +17,12 @@ import translate from './translate'; type Props = AppProps & BareProps & I18nProps; -type State = { - tabs: Array -}; +interface State { + tabs: TabItem[]; +} class App extends React.PureComponent { - constructor (props: Props) { + public constructor (props: Props) { super(props); const { t } = props; @@ -42,7 +42,7 @@ class App extends React.PureComponent { }; } - render () { + public render (): React.ReactNode { const { basePath } = this.props; const { tabs } = this.state; const hidden = uiSettings.uiMode === 'full' diff --git a/packages/app-explorer/src/BestHash.tsx b/packages/app-explorer/src/BestHash.tsx index 33cb1805f7..9d2bd87d40 100644 --- a/packages/app-explorer/src/BestHash.tsx +++ b/packages/app-explorer/src/BestHash.tsx @@ -9,12 +9,12 @@ import { Header } from '@polkadot/types'; import { withCalls } from '@polkadot/ui-api'; type Props = BareProps & CallProps & { - label?: string, - chain_subscribeNewHead?: Header + label?: string; + chain_subscribeNewHead?: Header; }; class BestHash extends React.PureComponent { - render () { + public render (): React.ReactNode { const { className, label = '', style, chain_subscribeNewHead } = this.props; return ( diff --git a/packages/app-explorer/src/BlockHeader/index.tsx b/packages/app-explorer/src/BlockHeader/index.tsx index bd63b7a796..1d2ad171ab 100644 --- a/packages/app-explorer/src/BlockHeader/index.tsx +++ b/packages/app-explorer/src/BlockHeader/index.tsx @@ -12,15 +12,15 @@ import { HeaderExtended } from '@polkadot/api-derive'; import { AddressMini, LinkPolkascan } from '@polkadot/ui-app'; import { formatNumber } from '@polkadot/util'; -type Props = BareProps & { - isSummary?: boolean, - value?: HeaderExtended, - withExplorer?: boolean, - withLink?: boolean -}; +interface Props extends BareProps { + isSummary?: boolean; + value?: HeaderExtended; + withExplorer?: boolean; + withLink?: boolean; +} export default class BlockHeader extends React.PureComponent { - render () { + public render (): React.ReactNode { const { isSummary, value, withExplorer, withLink } = this.props; if (!value) { diff --git a/packages/app-explorer/src/BlockHeaders.tsx b/packages/app-explorer/src/BlockHeaders.tsx index ecf30e84c7..2addb9894b 100644 --- a/packages/app-explorer/src/BlockHeaders.tsx +++ b/packages/app-explorer/src/BlockHeaders.tsx @@ -12,38 +12,38 @@ import BlockHeader from './BlockHeader'; export const MAX_ITEMS = 15; -let blockHeaders: Array = []; +let blockHeaders: HeaderExtended[] = []; -const transform = (header: HeaderExtended): Array => { +const transform = (header: HeaderExtended): HeaderExtended[] => { if (!header) { return blockHeaders; } blockHeaders = blockHeaders - .filter((old, index) => + .filter((old, index): boolean => index < MAX_ITEMS && old.blockNumber.lt(header.blockNumber) ) - .reduce((next, header) => { + .reduce((next, header): HeaderExtended[] => { next.push(header); return next; }, [header]) - .sort((a, b) => + .sort((a, b): number => b.blockNumber.cmp(a.blockNumber) ); return blockHeaders; }; -type Props = CallProps & { - headers?: Array -}; +interface Props extends CallProps { + headers?: HeaderExtended[]; +} class BlockHeaders extends React.PureComponent { - render () { + public render (): React.ReactNode { const { headers = [] } = this.props; - return headers.map((header, index) => ( + return headers.map((header, index): React.ReactNode => ( , - chain_getBlock?: SignedBlock, - chain_getHeader?: HeaderExtended, - value: string + system_events?: EventRecord[]; + chain_getBlock?: SignedBlock; + chain_getHeader?: HeaderExtended; + value: string; }; class BlockByHash extends React.PureComponent { - render () { + public render (): React.ReactNode { const { system_events, chain_getBlock, chain_getHeader } = this.props; if (!chain_getBlock || chain_getBlock.isEmpty || !chain_getHeader || chain_getHeader.isEmpty) { diff --git a/packages/app-explorer/src/BlockInfo/ByNumber.tsx b/packages/app-explorer/src/BlockInfo/ByNumber.tsx index 97c3a93bdf..9c386de9f0 100644 --- a/packages/app-explorer/src/BlockInfo/ByNumber.tsx +++ b/packages/app-explorer/src/BlockInfo/ByNumber.tsx @@ -10,13 +10,13 @@ import { withCalls } from '@polkadot/ui-api'; import BlockByHash from './ByHash'; -type Props = ApiProps & { - chain_getBlockHash?: Hash, - value: string -}; +interface Props extends ApiProps { + chain_getBlockHash?: Hash; + value: string; +} class BlockByNumber extends React.PureComponent { - render () { + public render (): React.ReactNode { const { chain_getBlockHash } = this.props; if (!chain_getBlockHash) { diff --git a/packages/app-explorer/src/BlockInfo/Events.tsx b/packages/app-explorer/src/BlockInfo/Events.tsx index 6be6f02cfd..e30328acc7 100644 --- a/packages/app-explorer/src/BlockInfo/Events.tsx +++ b/packages/app-explorer/src/BlockInfo/Events.tsx @@ -11,12 +11,12 @@ import { Column } from '@polkadot/ui-app'; import EventsDisplay from '../Events'; import translate from '../translate'; -type Props = I18nProps & { - value?: Array -}; +interface Props extends I18nProps { + value?: EventRecord[]; +} class Events extends React.PureComponent { - render () { + public render (): React.ReactNode { const { t, value } = this.props; if (!value || !value.length) { diff --git a/packages/app-explorer/src/BlockInfo/Extrinsics.tsx b/packages/app-explorer/src/BlockInfo/Extrinsics.tsx index 419cfe50f5..503c7b7402 100644 --- a/packages/app-explorer/src/BlockInfo/Extrinsics.tsx +++ b/packages/app-explorer/src/BlockInfo/Extrinsics.tsx @@ -12,14 +12,14 @@ import { BlockNumber, Extrinsic, Method } from '@polkadot/types'; import translate from '../translate'; -type Props = I18nProps & { - blockNumber?: BlockNumber, - label?: React.ReactNode, - value?: Array | null -}; +interface Props extends I18nProps { + blockNumber?: BlockNumber; + label?: React.ReactNode; + value?: Extrinsic[] | null; +} class Extrinsics extends React.PureComponent { - render () { + public render (): React.ReactNode { const { className, label, t } = this.props; return ( diff --git a/packages/app-explorer/src/BlockInfo/Logs.tsx b/packages/app-explorer/src/BlockInfo/Logs.tsx index 68e983af11..2855aa20de 100644 --- a/packages/app-explorer/src/BlockInfo/Logs.tsx +++ b/packages/app-explorer/src/BlockInfo/Logs.tsx @@ -11,12 +11,12 @@ import Params from '@polkadot/ui-params'; import translate from '../translate'; -type Props = I18nProps & { - value?: Array -}; +interface Props extends I18nProps { + value?: DigestItem[]; +} class Logs extends React.PureComponent { - render () { + public render (): React.ReactNode { const { t, value } = this.props; if (!value || !value.length) { diff --git a/packages/app-explorer/src/BlockInfo/index.tsx b/packages/app-explorer/src/BlockInfo/index.tsx index 4cd1bae009..40db4acb29 100644 --- a/packages/app-explorer/src/BlockInfo/index.tsx +++ b/packages/app-explorer/src/BlockInfo/index.tsx @@ -13,25 +13,25 @@ import Query from '../Query'; import BlockByHash from './ByHash'; import BlockByNumber from './ByNumber'; -type Props = BareProps & { - chain_bestNumber?: BlockNumber, +interface Props extends BareProps { + chain_bestNumber?: BlockNumber; match: { params: { - value: string - } - } -}; + value: string; + }; + }; +} -type State = { - value?: string -}; +interface State { + value?: string; +} class Entry extends React.Component { - state: State = { + public state: State = { value: undefined }; - static getDerivedStateFromProps ({ chain_bestNumber, match: { params } }: Props): State { + public static getDerivedStateFromProps ({ chain_bestNumber, match: { params } }: Props): State { let { value } = params; if ((!value || !value.length) && chain_bestNumber) { value = chain_bestNumber.toString(); @@ -47,7 +47,7 @@ class Entry extends React.Component { !this.state.value; } - render () { + public render (): React.ReactNode { const { value } = this.state; if (!value) { diff --git a/packages/app-explorer/src/Events.tsx b/packages/app-explorer/src/Events.tsx index 0944687020..4224d5025a 100644 --- a/packages/app-explorer/src/Events.tsx +++ b/packages/app-explorer/src/Events.tsx @@ -11,15 +11,15 @@ import { formatNumber } from '@polkadot/util'; import translate from './translate'; -type Props = I18nProps & { - emptyLabel?: React.ReactNode, - events: Array, - eventClassName?: string, - withoutIndex?: boolean -}; +interface Props extends I18nProps { + emptyLabel?: React.ReactNode; + events: KeyedEvent[]; + eventClassName?: string; + withoutIndex?: boolean; +} class Events extends React.PureComponent { - render () { + public render (): React.ReactNode { const { emptyLabel, events, t } = this.props; if (!events || events.length === 0) { @@ -29,7 +29,7 @@ class Events extends React.PureComponent { return events.map(this.renderEvent); } - private renderEvent = ({ key, record: { event, phase } }: KeyedEvent) => { + private renderEvent = ({ key, record: { event, phase } }: KeyedEvent): React.ReactNode => { const { eventClassName, withoutIndex } = this.props; const extIndex = !withoutIndex && phase.type === 'ApplyExtrinsic' ? phase.asApplyExtrinsic diff --git a/packages/app-explorer/src/Main.tsx b/packages/app-explorer/src/Main.tsx index 59b29ee00b..537e7212d1 100644 --- a/packages/app-explorer/src/Main.tsx +++ b/packages/app-explorer/src/Main.tsx @@ -14,12 +14,12 @@ import Query from './Query'; import Summary from './Summary'; import translate from './translate'; -type Props = I18nProps & { - events: Array -}; +interface Props extends I18nProps { + events: KeyedEvent[]; +} class Main extends React.PureComponent { - render () { + public render (): React.ReactNode { const { events, t } = this.props; return ( diff --git a/packages/app-explorer/src/NodeInfo/Peers.tsx b/packages/app-explorer/src/NodeInfo/Peers.tsx index 52a3d23b16..a6b546a374 100644 --- a/packages/app-explorer/src/NodeInfo/Peers.tsx +++ b/packages/app-explorer/src/NodeInfo/Peers.tsx @@ -10,12 +10,12 @@ import { formatNumber } from '@polkadot/util'; import translate from './translate'; -type Props = I18nProps & { - peers?: Array | null -}; +interface Props extends I18nProps { + peers?: PeerInfo[] | null; +} class Peers extends React.PureComponent { - render () { + public render (): React.ReactNode { const { t } = this.props; return ( @@ -26,7 +26,7 @@ class Peers extends React.PureComponent { ); } - private renderPeers () { + private renderPeers (): React.ReactNode { const { peers, t } = this.props; if (!peers || !peers.length) { @@ -50,9 +50,7 @@ class Peers extends React.PureComponent { {peers - .sort((a, b) => - b.bestNumber.cmp(a.bestNumber) - ) + .sort((a, b): number => b.bestNumber.cmp(a.bestNumber)) .map(this.renderPeer) } @@ -61,7 +59,7 @@ class Peers extends React.PureComponent { ); } - private renderPeer = (peer: PeerInfo) => { + private renderPeer = (peer: PeerInfo): React.ReactNode => { const peerId = peer.peerId.toString(); return ( diff --git a/packages/app-explorer/src/NodeInfo/Summary.tsx b/packages/app-explorer/src/NodeInfo/Summary.tsx index da7f9cfc8a..aba196544e 100644 --- a/packages/app-explorer/src/NodeInfo/Summary.tsx +++ b/packages/app-explorer/src/NodeInfo/Summary.tsx @@ -13,17 +13,17 @@ import { BestNumber, Elapsed } from '@polkadot/ui-reactive'; import translate from './translate'; -type Props = I18nProps & { +interface Props extends I18nProps { nextRefresh: number; info: Info; -}; +} -type State = { - peerBest?: BN -}; +interface State { + peerBest?: BN; +} class Summary extends React.PureComponent { - state: State = {}; + public state: State = {}; static getDerivedStateFromProps ({ info = {} }: Props): State | null { if (!info.peers) { @@ -39,7 +39,7 @@ class Summary extends React.PureComponent { }; } - render () { + public render (): React.ReactNode { const { info = {}, nextRefresh, t } = this.props; const { peerBest } = this.state; diff --git a/packages/app-explorer/src/NodeInfo/index.tsx b/packages/app-explorer/src/NodeInfo/index.tsx index dbcb6ce24e..b1e8c832d2 100644 --- a/packages/app-explorer/src/NodeInfo/index.tsx +++ b/packages/app-explorer/src/NodeInfo/index.tsx @@ -21,15 +21,15 @@ const POLL_TIMEOUT = 9900; type Props = ApiProps & AppProps & I18nProps; -type State = { - info?: Info, - nextRefresh: number, +interface State { + info?: Info; + nextRefresh: number; timerId?: number; -}; +} class App extends React.PureComponent { private isActive: boolean = true; - state: State = { + public state: State = { nextRefresh: Date.now() }; @@ -49,7 +49,7 @@ class App extends React.PureComponent { } } - render () { + public render (): React.ReactNode { const { t } = this.props; const { info = {}, nextRefresh } = this.state; diff --git a/packages/app-explorer/src/NodeInfo/types.ts b/packages/app-explorer/src/NodeInfo/types.ts index 4a0970de8e..306e394d57 100644 --- a/packages/app-explorer/src/NodeInfo/types.ts +++ b/packages/app-explorer/src/NodeInfo/types.ts @@ -4,9 +4,9 @@ import { BlockNumber, Health, PeerInfo, PendingExtrinsics } from '@polkadot/types'; -export type Info = { - blockNumber?: BlockNumber, - health?: Health | null, - peers?: Array | null, - extrinsics?: PendingExtrinsics | null -}; +export interface Info { + blockNumber?: BlockNumber; + health?: Health | null; + peers?: PeerInfo[] | null; + extrinsics?: PendingExtrinsics | null; +} diff --git a/packages/app-explorer/src/Query.tsx b/packages/app-explorer/src/Query.tsx index 1b16de96a9..76a47ca664 100644 --- a/packages/app-explorer/src/Query.tsx +++ b/packages/app-explorer/src/Query.tsx @@ -11,18 +11,18 @@ import { isHex } from '@polkadot/util'; import translate from './translate'; -type Props = I18nProps & { - value?: string -}; +interface Props extends I18nProps { + value?: string; +} -type State = { - value: string - isNumber: boolean, - isValid: boolean -}; +interface State { + value: string; + isNumber: boolean; + isValid: boolean; +} class Query extends TxComponent { - constructor (props: Props) { + public constructor (props: Props) { super(props); const { value } = this.props; @@ -30,7 +30,7 @@ class Query extends TxComponent { this.state = this.stateFromValue(value || ''); } - render () { + public render (): React.ReactNode { const { className, t } = this.props; const { value, isValid } = this.state; diff --git a/packages/app-explorer/src/Summary.tsx b/packages/app-explorer/src/Summary.tsx index 9d326baa2b..b0f3dd1494 100644 --- a/packages/app-explorer/src/Summary.tsx +++ b/packages/app-explorer/src/Summary.tsx @@ -11,10 +11,10 @@ import { BestFinalized, BestNumber, TimeNow, TimePeriod, TotalIssuance } from '@ import SummarySession from './SummarySession'; import translate from './translate'; -type Props = I18nProps & {}; +interface Props extends I18nProps {} class Summary extends React.PureComponent { - render () { + public render (): React.ReactNode { const { t } = this.props; return ( diff --git a/packages/app-explorer/src/SummarySession.tsx b/packages/app-explorer/src/SummarySession.tsx index 4dc3b87d93..8aba1f01fe 100644 --- a/packages/app-explorer/src/SummarySession.tsx +++ b/packages/app-explorer/src/SummarySession.tsx @@ -12,14 +12,14 @@ import { withCalls } from '@polkadot/ui-api'; import translate from './translate'; import { formatNumber } from '@polkadot/util'; -type Props = I18nProps & { - session_info?: DerivedSessionInfo, - withEra?: boolean, - withSession?: boolean -}; +interface Props extends I18nProps { + session_info?: DerivedSessionInfo; + withEra?: boolean; + withSession?: boolean; +} class SummarySession extends React.PureComponent { - render () { + public render (): React.ReactNode { return ( <> {this.renderSession()} diff --git a/packages/app-explorer/src/index.tsx b/packages/app-explorer/src/index.tsx index ec956f258d..706103fef8 100644 --- a/packages/app-explorer/src/index.tsx +++ b/packages/app-explorer/src/index.tsx @@ -24,17 +24,17 @@ import NodeInfo from './NodeInfo'; import translate from './translate'; type Props = AppProps & BareProps & I18nProps & { - system_events?: Array + system_events?: EventRecord[]; }; -type State = { - items: Array, +interface State { + items: TabItem[]; prevEventHash: string; - recentEvents: Array; -}; + recentEvents: KeyedEvent[]; +} class ExplorerApp extends React.Component { - constructor (props: Props) { + public constructor (props: Props) { super(props); const { t } = this.props; @@ -83,7 +83,7 @@ class ExplorerApp extends React.Component { }; } - render () { + public render (): React.ReactNode { const { basePath, className } = this.props; const { items } = this.state; const hidden = uiSettings.uiMode === 'full' diff --git a/packages/app-explorer/src/types.ts b/packages/app-explorer/src/types.ts index aee3b06800..9b2e627b4e 100644 --- a/packages/app-explorer/src/types.ts +++ b/packages/app-explorer/src/types.ts @@ -4,7 +4,7 @@ import { EventRecord } from '@polkadot/types'; -export type KeyedEvent = { - key: string, - record: EventRecord -}; +export interface KeyedEvent { + key: string; + record: EventRecord; +} diff --git a/packages/app-extrinsics/src/Balance.tsx b/packages/app-extrinsics/src/Balance.tsx index 1445b3c327..7957360140 100644 --- a/packages/app-extrinsics/src/Balance.tsx +++ b/packages/app-extrinsics/src/Balance.tsx @@ -10,12 +10,12 @@ import { withCalls, withMulti } from '@polkadot/ui-api'; import { InputBalance } from '@polkadot/ui-app'; type Props = BareProps & CallProps & { - balances_all?: DerivedBalances, - label?: React.ReactNode + balances_all?: DerivedBalances; + label?: React.ReactNode; }; class BalanceDisplay extends React.PureComponent { - render () { + public render (): React.ReactNode { const { className, label, style, balances_all } = this.props; return ( diff --git a/packages/app-extrinsics/src/Selection.tsx b/packages/app-extrinsics/src/Selection.tsx index 16d64e030d..436fb1a8a8 100644 --- a/packages/app-extrinsics/src/Selection.tsx +++ b/packages/app-extrinsics/src/Selection.tsx @@ -4,7 +4,7 @@ import BN from 'bn.js'; import { I18nProps } from '@polkadot/ui-app/types'; -import { QueueTx$ExtrinsicAdd } from '@polkadot/ui-app/Status/types'; +import { QueueTxExtrinsicAdd } from '@polkadot/ui-app/Status/types'; import { ApiProps } from '@polkadot/ui-api/types'; import { SubmittableExtrinsic } from '@polkadot/api/promise/types'; @@ -18,24 +18,24 @@ import Balance from './Balance'; import translate from './translate'; type Props = ApiProps & I18nProps & { - queueExtrinsic: QueueTx$ExtrinsicAdd + queueExtrinsic: QueueTxExtrinsicAdd; }; -type State = { - isValid: boolean, - isValidUnsigned: boolean, - method: Method | null, - accountNonce: BN, - accountId: string -}; +interface State { + isValid: boolean; + isValidUnsigned: boolean; + method: Method | null; + accountNonce: BN; + accountId: string; +} class Selection extends TxComponent { - state: State = { + public state: State = { isValid: false, isValidUnsigned: false } as State; - render () { + public render (): React.ReactNode { const { apiDefaultTxSudo, t } = this.props; const { isValid, isValidUnsigned, accountId } = this.state; const extrinsic = this.getExtrinsic() || apiDefaultTxSudo; diff --git a/packages/app-extrinsics/src/index.tsx b/packages/app-extrinsics/src/index.tsx index fd5a64b185..9a2bcc27cc 100644 --- a/packages/app-extrinsics/src/index.tsx +++ b/packages/app-extrinsics/src/index.tsx @@ -13,7 +13,7 @@ import translate from './translate'; type Props = AppProps & I18nProps; class ExtrinsicsApp extends React.PureComponent { - render () { + public render (): React.ReactNode { const { basePath, t } = this.props; return ( diff --git a/packages/app-js/src/ActionButtons.tsx b/packages/app-js/src/ActionButtons.tsx index 4d385dc34e..c8afb644b6 100644 --- a/packages/app-js/src/ActionButtons.tsx +++ b/packages/app-js/src/ActionButtons.tsx @@ -11,30 +11,30 @@ import { Button, Input } from '@polkadot/ui-app'; import translate from './translate'; type Props = BareProps & I18nProps & { - isCustomExample: boolean, - isRunning: boolean, - generateLink: () => void, - removeSnippet: () => void, - runJs: () => void, - saveSnippet: (snippetName: string) => void, - snippetName?: string, - stopJs: () => void + isCustomExample: boolean; + isRunning: boolean; + generateLink: () => void; + removeSnippet: () => void; + runJs: () => void; + saveSnippet: (snippetName: string) => void; + snippetName?: string; + stopJs: () => void; }; -type State = { - isOpen: boolean, - shareText: string, - snippetName: string -}; +interface State { + isOpen: boolean; + shareText: string; + snippetName: string; +} class ActionButtons extends React.PureComponent { - state: State = { + public state: State = { isOpen: false, shareText: this.props.t('Generate link to share code example'), snippetName: '' }; - render () { + public render (): React.ReactNode { const { props: { isCustomExample, isRunning, removeSnippet, runJs, stopJs, t }, state: { isOpen, shareText, snippetName } diff --git a/packages/app-js/src/Output.tsx b/packages/app-js/src/Output.tsx index 05273ea5e7..a2214efed0 100644 --- a/packages/app-js/src/Output.tsx +++ b/packages/app-js/src/Output.tsx @@ -8,10 +8,10 @@ import { Log } from './types'; import React from 'react'; import { isError, isNull, isUndefined } from '@polkadot/util'; -type Props = BareProps & { - children?: React.ReactNode, - logs: Array -}; +interface Props extends BareProps { + children?: React.ReactNode; + logs: Log[]; +} const format = (value: any): string => { if (isError(value)) { @@ -21,9 +21,9 @@ const format = (value: any): string => { } else if (isNull(value)) { return 'null'; } else if (Array.isArray(value)) { - return `[${value.map((value) => format(value)).join(', ')}]`; + return `[${value.map((value): string => format(value)).join(', ')}]`; } else if (value instanceof Map) { - return `{${[...value.entries()].map(([key, value]) => key + ': ' + format(value)).join(', ')}}`; + return `{${[...value.entries()].map(([key, value]): string => key + ': ' + format(value)).join(', ')}}`; } return value.toString(); @@ -31,12 +31,12 @@ const format = (value: any): string => { const renderEntry = ({ args, type }: Log, index: number): React.ReactNode => (
- {args.map((arg) => format(arg)).join(' ')} + {args.map((arg): string => format(arg)).join(' ')}
); export default class Output extends React.PureComponent { - render () { + public render (): React.ReactNode { const { children, logs } = this.props; return ( diff --git a/packages/app-js/src/Playground.tsx b/packages/app-js/src/Playground.tsx index cc0cec447c..676a5c1cc3 100644 --- a/packages/app-js/src/Playground.tsx +++ b/packages/app-js/src/Playground.tsx @@ -28,49 +28,50 @@ import { STORE_EXAMPLES, STORE_SELECTED, CUSTOM_LABEL } from './constants'; import Output from './Output'; import ActionButtons from './ActionButtons'; -type Injected = { - api: ApiPromise, +interface Injected { + api: ApiPromise; console: { - error: (...args: Array) => void, - log: (...args: Array) => void - }, - global: null, - hashing: typeof hashing, - keyring: KeyringInstance | null, - types: typeof types, - util: typeof util, - window: null -}; + error: (...args: any[]) => void; + log: (...args: any[]) => void; + }; + global: null; + hashing: typeof hashing; + keyring: KeyringInstance | null; + types: typeof types; + util: typeof util; + window: null; +} type Props = ApiProps & AppProps & I18nProps & { match: { params: { - base64?: string - } - }, + base64?: string; + }; + }; // FIXME wait for proper eslint integration in tslint, then hopefully remove this - history: any + history: any; }; -type State = { - animated: boolean, - customExamples: Array, - isCustomExample: boolean, - isRunning: boolean, - logs: Array, - options: Array, - sharedExample?: Snippet, - selected: Snippet -}; +interface State { + animated: boolean; + customExamples: Snippet[]; + isCustomExample: boolean; + isRunning: boolean; + logs: Log[]; + options: Snippet[]; + sharedExample?: Snippet; + selected: Snippet; +} class Playground extends React.PureComponent { - injected: Injected | null = null; - snippets: Array = JSON.parse(JSON.stringify(snippets)); + private injected: Injected | null = null; - constructor (props: Props) { + private snippets: Snippet[] = JSON.parse(JSON.stringify(snippets)); + + public constructor (props: Props) { super(props); - this.snippets.forEach((snippet) => { + this.snippets.forEach((snippet): void => { snippet.code = `${makeWrapper(this.props.isDevelopment)}${snippet.code}`; }); @@ -100,7 +101,7 @@ class Playground extends React.PureComponent { }; const customExamples = localData.examples ? JSON.parse(localData.examples) : []; - const options: Array = sharedExample + const options: Snippet[] = sharedExample ? [sharedExample, ...customExamples, ...this.snippets] : [...customExamples, ...this.snippets]; @@ -115,7 +116,7 @@ class Playground extends React.PureComponent { }) as State); } - render () { + public render (): React.ReactNode { const { t } = this.props; const { animated, isCustomExample, isRunning, logs, options, selected } = this.state; const snippetName = selected.type === 'custom' ? selected.text : undefined; @@ -286,7 +287,7 @@ class Playground extends React.PureComponent { } private hookConsole = (type: LogType) => { - return (...args: Array): void => { + return (...args: any[]): void => { this.setState(({ logs }: State) => { logs.push({ args, type }); diff --git a/packages/app-js/src/index.tsx b/packages/app-js/src/index.tsx index e4db4508f0..9a157e0094 100644 --- a/packages/app-js/src/index.tsx +++ b/packages/app-js/src/index.tsx @@ -13,7 +13,7 @@ import Playground from './Playground'; type Props = AppProps & BareProps; export default class AppJs extends React.PureComponent { - render () { + public render (): React.ReactNode { const { basePath } = this.props; return ( diff --git a/packages/app-js/src/snippets/index.ts b/packages/app-js/src/snippets/index.ts index d9860308fd..d62c1766a8 100644 --- a/packages/app-js/src/snippets/index.ts +++ b/packages/app-js/src/snippets/index.ts @@ -21,7 +21,7 @@ import { import { extrinsicMakeTransfer } from './extrinsics-examples'; -const snippets: Array = [ +const snippets: Snippet[] = [ rpcNetworkAuthoring, rpcNewHead, rpcQueryState, diff --git a/packages/app-js/src/types.ts b/packages/app-js/src/types.ts index 65cde809ff..246370d7a3 100644 --- a/packages/app-js/src/types.ts +++ b/packages/app-js/src/types.ts @@ -7,15 +7,15 @@ import { LabelProps } from 'semantic-ui-react/dist/commonjs/elements/Label'; export type LogType = 'error' | 'log'; -export type Log = { - args: Array, - type: LogType -}; +export interface Log { + args: any[]; + type: LogType; +} -export type Snippet = { +export interface Snippet { text: string; value: string; code: string; - label?: SemanticShorthandItem, - type?: 'custom' | 'shared' -}; + label?: SemanticShorthandItem; + type?: 'custom' | 'shared'; +} diff --git a/packages/app-parachains/src/Overview/Chain.tsx b/packages/app-parachains/src/Overview/Chain.tsx index fd5cc60298..6973ab943c 100644 --- a/packages/app-parachains/src/Overview/Chain.tsx +++ b/packages/app-parachains/src/Overview/Chain.tsx @@ -4,10 +4,8 @@ import React from 'react'; -type Props = {}; - -export default class Chain extends React.PureComponent { - render () { +export default class Chain extends React.PureComponent<{}> { + public render (): React.ReactNode { return null; } } diff --git a/packages/app-parachains/src/Overview/Parachain.tsx b/packages/app-parachains/src/Overview/Parachain.tsx index 9bf3f4f827..fd30bcd87f 100644 --- a/packages/app-parachains/src/Overview/Parachain.tsx +++ b/packages/app-parachains/src/Overview/Parachain.tsx @@ -15,15 +15,15 @@ import { formatNumber } from '@polkadot/util'; import translate from '../translate'; -type Props = I18nProps & { - className?: string, - paraId: BN, - parachains_heads?: string | null, - parachains_relayDispatchQueueSize?: [BN, BN] -}; +interface Props extends I18nProps { + className?: string; + paraId: BN; + parachains_heads?: string | null; + parachains_relayDispatchQueueSize?: [BN, BN]; +} class Parachain extends React.PureComponent { - render () { + public render (): React.ReactNode { const { className, paraId, parachains_heads, parachains_relayDispatchQueueSize, t } = this.props; return ( diff --git a/packages/app-parachains/src/Overview/Parachains.tsx b/packages/app-parachains/src/Overview/Parachains.tsx index bfb648a02c..cc93a65946 100644 --- a/packages/app-parachains/src/Overview/Parachains.tsx +++ b/packages/app-parachains/src/Overview/Parachains.tsx @@ -12,12 +12,12 @@ import { withCalls } from '@polkadot/ui-api'; import translate from '../translate'; import Parachain from './Parachain'; -type Props = I18nProps & { - parachains_parachains?: Array -}; +interface Props extends I18nProps { + parachains_parachains?: BN[]; +} class Parachains extends React.PureComponent { - render () { + public render (): React.ReactNode { const { parachains_parachains = [], t } = this.props; return ( diff --git a/packages/app-parachains/src/Overview/Summary.tsx b/packages/app-parachains/src/Overview/Summary.tsx index fcd931b3c6..09d22a547b 100644 --- a/packages/app-parachains/src/Overview/Summary.tsx +++ b/packages/app-parachains/src/Overview/Summary.tsx @@ -12,13 +12,13 @@ import { formatNumber } from '@polkadot/util'; import translate from '../translate'; -type Props = I18nProps & { - parachains_nextFreeId?: BN, - parachains_parachains?: Array -}; +interface Props extends I18nProps { + parachains_nextFreeId?: BN; + parachains_parachains?: BN[]; +} class Summary extends React.PureComponent { - render () { + public render (): React.ReactNode { const { parachains_nextFreeId, parachains_parachains = [], t } = this.props; return ( diff --git a/packages/app-parachains/src/Overview/index.tsx b/packages/app-parachains/src/Overview/index.tsx index 56b7f15b2e..f1d4c63cd9 100644 --- a/packages/app-parachains/src/Overview/index.tsx +++ b/packages/app-parachains/src/Overview/index.tsx @@ -8,10 +8,8 @@ import { Columar } from '@polkadot/ui-app'; import Parachains from './Parachains'; import Summary from './Summary'; -type Props = {}; - -export default class Overview extends React.PureComponent { - render () { +export default class Overview extends React.PureComponent<{}> { + public render (): React.ReactNode { return ( <> diff --git a/packages/app-parachains/src/index.tsx b/packages/app-parachains/src/index.tsx index 71b38c08f2..ec6ba96f5b 100644 --- a/packages/app-parachains/src/index.tsx +++ b/packages/app-parachains/src/index.tsx @@ -14,12 +14,12 @@ import translate from './translate'; type Props = AppProps & BareProps & I18nProps; -type State = { - tabs: Array -}; +interface State { + tabs: TabItem[]; +} class App extends React.PureComponent { - constructor (props: Props) { + public constructor (props: Props) { super(props); const { t } = props; @@ -35,7 +35,7 @@ class App extends React.PureComponent { }; } - render () { + public render (): React.ReactNode { const { basePath } = this.props; const { tabs } = this.state; diff --git a/packages/app-settings/src/Developer.tsx b/packages/app-settings/src/Developer.tsx index 5fcfaa44a3..1426b00a35 100644 --- a/packages/app-settings/src/Developer.tsx +++ b/packages/app-settings/src/Developer.tsx @@ -15,21 +15,21 @@ import { isJsonObject, stringToU8a, u8aToString } from '@polkadot/util'; import translate from './translate'; type Props = AppProps & I18nProps & { - onStatusChange: (status: ActionStatus) => void + onStatusChange: (status: ActionStatus) => void; }; -type State = { - code: string, - isJsonValid: boolean, - isTypesValid: boolean, - types: { [index: string]: any } | {}, - typesPlaceholder?: string -}; +interface State { + code: string; + isJsonValid: boolean; + isTypesValid: boolean; + types: Record | {}; + typesPlaceholder?: string; +} class Developer extends React.PureComponent { private defaultCode: string = `{\n\n}`; - constructor (props: Props) { + public constructor (props: Props) { super(props); const types = store.get('types') || {}; @@ -46,7 +46,7 @@ class Developer extends React.PureComponent { }; } - render () { + public render (): React.ReactNode { const { className, t } = this.props; const { code, isJsonValid, isTypesValid, types, typesPlaceholder } = this.state; const typesHasNoEntries = Object.keys(types).length === 0; diff --git a/packages/app-settings/src/General.tsx b/packages/app-settings/src/General.tsx index 1affc202fb..2930b91f17 100644 --- a/packages/app-settings/src/General.tsx +++ b/packages/app-settings/src/General.tsx @@ -14,21 +14,21 @@ import uiSettings from '@polkadot/ui-settings'; import translate from './translate'; type Props = AppProps & I18nProps & { - onStatusChange: (status: ActionStatus) => void + onStatusChange: (status: ActionStatus) => void; }; -type State = { - isCustomNode: boolean, - isUrlValid: boolean, - settings: SettingsStruct -}; +interface State { + isCustomNode: boolean; + isUrlValid: boolean; + settings: SettingsStruct; +} class General extends React.PureComponent { - constructor (props: Props) { + public constructor (props: Props) { super(props); const settings = uiSettings.get(); - const isCustomNode = uiSettings.availableNodes.reduce((isCustomNode, { value }) => { + const isCustomNode = uiSettings.availableNodes.reduce((isCustomNode, { value }): boolean => { return isCustomNode && value !== settings.apiUrl; }, true); @@ -39,7 +39,7 @@ class General extends React.PureComponent { }; } - render () { + public render (): React.ReactNode { const { className, t } = this.props; const { isUrlValid, settings: { i18nLang, uiMode, uiTheme } } = this.state; @@ -88,7 +88,7 @@ class General extends React.PureComponent { ); } - private renderEndpoint = () => { + private renderEndpoint = (): React.ReactNode => { const { t } = this.props; const { isCustomNode, isUrlValid, settings: { apiUrl } } = this.state; @@ -174,6 +174,7 @@ class General extends React.PureComponent { (apiUrl.startsWith('ws://') || apiUrl.startsWith('wss://')) ); } + private saveAndReload = (): void => { const { settings } = this.state; diff --git a/packages/app-settings/src/index.tsx b/packages/app-settings/src/index.tsx index 5aacc2c614..e24ec5427d 100644 --- a/packages/app-settings/src/index.tsx +++ b/packages/app-settings/src/index.tsx @@ -17,12 +17,12 @@ import General from './General'; type Props = AppProps & I18nProps; -type State = { - tabs: Array -}; +interface State { + tabs: TabItem[]; +} class App extends React.PureComponent { - constructor (props: Props) { + public constructor (props: Props) { super(props); const { t } = props; @@ -42,7 +42,7 @@ class App extends React.PureComponent { }; } - render () { + public render (): React.ReactNode { const { basePath } = this.props; const { tabs } = this.state; const hidden = uiSettings.uiMode === 'full' diff --git a/packages/app-staking/src/Actions/Account/BondExtra.tsx b/packages/app-staking/src/Actions/Account/BondExtra.tsx index 32ed0fbd29..249ed089e7 100644 --- a/packages/app-staking/src/Actions/Account/BondExtra.tsx +++ b/packages/app-staking/src/Actions/Account/BondExtra.tsx @@ -17,22 +17,22 @@ import { ZERO_BALANCE, ZERO_FEES } from '@polkadot/ui-signer/Checks/constants'; import translate from '../../translate'; type Props = I18nProps & ApiProps & CalculateBalanceProps & { - controllerId: string, - isOpen: boolean, - onClose: () => void, - stashId: string + controllerId: string; + isOpen: boolean; + onClose: () => void; + stashId: string; }; -type State = { - extrinsic: SubmittableExtrinsic | null, - maxAdditional?: BN, - maxBalance?: BN -}; +interface State { + extrinsic: SubmittableExtrinsic | null; + maxAdditional?: BN; + maxBalance?: BN; +} const ZERO = new BN(0); class BondExtra extends TxComponent { - state: State = { + public state: State = { extrinsic: null }; @@ -49,7 +49,7 @@ class BondExtra extends TxComponent { } } - render () { + public render (): React.ReactNode { const { balances_all = ZERO_BALANCE, isOpen, onClose, stashId, t } = this.props; const { extrinsic, maxAdditional, maxBalance = balances_all.availableBalance } = this.state; const canSubmit = !!maxAdditional && maxAdditional.gtn(0) && maxAdditional.lte(maxBalance); diff --git a/packages/app-staking/src/Actions/Account/InputValidationController.tsx b/packages/app-staking/src/Actions/Account/InputValidationController.tsx index 8f0d131649..4d258a7d06 100644 --- a/packages/app-staking/src/Actions/Account/InputValidationController.tsx +++ b/packages/app-staking/src/Actions/Account/InputValidationController.tsx @@ -11,21 +11,21 @@ import { withCalls } from '@polkadot/ui-api'; import translate from '../../translate'; -type Props = I18nProps & { - accountId: string | null, - bondedId?: string | null, - controllerId: string | null, - defaultController?: string, - onError: (error: string | null) => void, - stashId?: string | null -}; +interface Props extends I18nProps { + accountId: string | null; + bondedId?: string | null; + controllerId: string | null; + defaultController?: string; + onError: (error: string | null) => void; + stashId?: string | null; +} -type State = { - error: string | null -}; +interface State { + error: string | null; +} class ValidateController extends React.PureComponent { - state: State = { + public state: State = { error: null }; @@ -55,7 +55,7 @@ class ValidateController extends React.PureComponent { }; } - render () { + public render (): React.ReactNode { const { accountId } = this.props; const { error } = this.state; diff --git a/packages/app-staking/src/Actions/Account/InputValidationSession.tsx b/packages/app-staking/src/Actions/Account/InputValidationSession.tsx index 1b3f4a8077..b269e1a574 100644 --- a/packages/app-staking/src/Actions/Account/InputValidationSession.tsx +++ b/packages/app-staking/src/Actions/Account/InputValidationSession.tsx @@ -10,19 +10,19 @@ import keyring from '@polkadot/ui-keyring'; import translate from '../../translate'; -type Props = I18nProps & { - controllerId: string, - onError: (error: string | null) => void, - sessionId: string, - stashId: string -}; +interface Props extends I18nProps { + controllerId: string; + onError: (error: string | null) => void; + sessionId: string; + stashId: string; +} -type State = { - error: string | null -}; +interface State { + error: string | null; +} class ValidateSession extends React.PureComponent { - state: State = { + public state: State = { error: null }; @@ -53,7 +53,7 @@ class ValidateSession extends React.PureComponent { return { error }; } - render () { + public render (): React.ReactNode { const { error } = this.state; if (!error) { diff --git a/packages/app-staking/src/Actions/Account/InputValidationUnstakeThreshold.tsx b/packages/app-staking/src/Actions/Account/InputValidationUnstakeThreshold.tsx index a8f544cc69..8e4ad7155e 100644 --- a/packages/app-staking/src/Actions/Account/InputValidationUnstakeThreshold.tsx +++ b/packages/app-staking/src/Actions/Account/InputValidationUnstakeThreshold.tsx @@ -10,17 +10,17 @@ import { Icon } from '@polkadot/ui-app'; import translate from '../../translate'; -type Props = I18nProps & { - unstakeThreshold: BN | undefined, - onError: (error: string | null) => void -}; +interface Props extends I18nProps { + unstakeThreshold: BN | undefined; + onError: (error: string | null) => void; +} -type State = { - error: string | null -}; +interface State { + error: string | null; +} class InputValidationUnstakeThreshold extends React.PureComponent { - state: State = { + public state: State = { error: null }; @@ -46,7 +46,7 @@ class InputValidationUnstakeThreshold extends React.PureComponent return { error }; } - render () { + public render (): React.ReactNode { const { error } = this.state; if (!error) { diff --git a/packages/app-staking/src/Actions/Account/Nominate.tsx b/packages/app-staking/src/Actions/Account/Nominate.tsx index ec3407d82d..210b3e5cec 100644 --- a/packages/app-staking/src/Actions/Account/Nominate.tsx +++ b/packages/app-staking/src/Actions/Account/Nominate.tsx @@ -10,25 +10,25 @@ import { Button, InputAddress, Modal, TxButton } from '@polkadot/ui-app'; import translate from '../../translate'; -type Props = I18nProps & { - controllerId: string, - isOpen: boolean, - nominees?: Array, - onClose: () => void, - stashId: string, - stashOptions: Array -}; +interface Props extends I18nProps { + controllerId: string; + isOpen: boolean; + nominees?: string[]; + onClose: () => void; + stashId: string; + stashOptions: KeyringSectionOption[]; +} -type State = { - nominees: Array | undefined -}; +interface State { + nominees: string[] | undefined; +} class Nominate extends React.PureComponent { - state: State = { + public state: State = { nominees: this.props.nominees }; - render () { + public render (): React.ReactNode { const { isOpen } = this.props; if (!isOpen) { @@ -111,7 +111,7 @@ class Nominate extends React.PureComponent { ); } - private onChangeNominees = (nominees: Array) => { + private onChangeNominees = (nominees: string[]) => { this.setState({ nominees }); } } diff --git a/packages/app-staking/src/Actions/Account/SetControllerAccount.tsx b/packages/app-staking/src/Actions/Account/SetControllerAccount.tsx index e9a9b00d42..5df7b33314 100644 --- a/packages/app-staking/src/Actions/Account/SetControllerAccount.tsx +++ b/packages/app-staking/src/Actions/Account/SetControllerAccount.tsx @@ -11,20 +11,20 @@ import { withMulti } from '@polkadot/ui-api'; import translate from '../../translate'; import InputValidationController from '../Account/InputValidationController'; -type Props = I18nProps & { - defaultControllerId: string, - isValidating?: boolean, - onClose: () => void, - stashId: string -}; +interface Props extends I18nProps { + defaultControllerId: string; + isValidating?: boolean; + onClose: () => void; + stashId: string; +} -type State = { - controllerError: string | null, - controllerId: string | null -}; +interface State { + controllerError: string | null; + controllerId: string | null; +} class SetControllerAccount extends TxComponent { - constructor (props: Props) { + public constructor (props: Props) { super(props); this.state = { @@ -33,7 +33,7 @@ class SetControllerAccount extends TxComponent { }; } - render () { + public render (): React.ReactNode { const { defaultControllerId, onClose, stashId, t } = this.props; const { controllerError, controllerId } = this.state; const canSubmit = !controllerError && !!controllerId && (defaultControllerId !== controllerId); diff --git a/packages/app-staking/src/Actions/Account/SetRewardDestination.tsx b/packages/app-staking/src/Actions/Account/SetRewardDestination.tsx index 23db35fb72..e8b79b3781 100644 --- a/packages/app-staking/src/Actions/Account/SetRewardDestination.tsx +++ b/packages/app-staking/src/Actions/Account/SetRewardDestination.tsx @@ -11,18 +11,18 @@ import { withMulti } from '@polkadot/ui-api'; import translate from '../../translate'; import { rewardDestinationOptions } from '../constants'; -type Props = I18nProps & { - defaultDestination?: number, - controllerId: string, - onClose: () => void -}; +interface Props extends I18nProps { + defaultDestination?: number; + controllerId: string; + onClose: () => void; +} -type State = { - destination: number -}; +interface State { + destination: number; +} class SetRewardDestination extends TxComponent { - constructor (props: Props) { + public constructor (props: Props) { super(props); this.state = { @@ -30,7 +30,7 @@ class SetRewardDestination extends TxComponent { }; } - render () { + public render (): React.ReactNode { const { controllerId, onClose, t } = this.props; const { destination } = this.state; const canSubmit = !!controllerId; diff --git a/packages/app-staking/src/Actions/Account/SetSessionAccount.tsx b/packages/app-staking/src/Actions/Account/SetSessionAccount.tsx index 5cebb7582e..3e6a0b47c1 100644 --- a/packages/app-staking/src/Actions/Account/SetSessionAccount.tsx +++ b/packages/app-staking/src/Actions/Account/SetSessionAccount.tsx @@ -13,22 +13,22 @@ import ValidateSession from './InputValidationSession'; import translate from '../../translate'; type Props = I18nProps & ApiProps & { - controllerId: string, - isOpen: boolean, - onClose: () => void, - sessionId?: string | null, - stashId: string + controllerId: string; + isOpen: boolean; + onClose: () => void; + sessionId?: string | null; + stashId: string; }; -type State = { - sessionError: string | null, - sessionId: string -}; +interface State { + sessionError: string | null; + sessionId: string; +} class SetSessionKey extends React.PureComponent { - state: State; + public state: State; - constructor (props: Props) { + public constructor (props: Props) { super(props); this.state = { @@ -37,7 +37,7 @@ class SetSessionKey extends React.PureComponent { }; } - render () { + public render (): React.ReactNode { const { api, controllerId, isOpen, onClose, t } = this.props; const { sessionError, sessionId } = this.state; const isV2 = !!api.tx.session.setKeys; diff --git a/packages/app-staking/src/Actions/Account/Unbond.tsx b/packages/app-staking/src/Actions/Account/Unbond.tsx index e354682730..2d696d9ecf 100644 --- a/packages/app-staking/src/Actions/Account/Unbond.tsx +++ b/packages/app-staking/src/Actions/Account/Unbond.tsx @@ -15,17 +15,17 @@ import { withCalls, withApi, withMulti } from '@polkadot/ui-api'; import translate from '../../translate'; type Props = I18nProps & ApiProps & { - controllerId?: AccountId | null, - isOpen: boolean, - onClose: () => void, - stashId: string, - staking_ledger?: Option + controllerId?: AccountId | null; + isOpen: boolean; + onClose: () => void; + stashId: string; + staking_ledger?: Option; }; -type State = { - maxBalance?: BN - maxUnbond?: BN -}; +interface State { + maxBalance?: BN; + maxUnbond?: BN; +} const BalanceWrapper = styled.div` & > div { @@ -38,7 +38,7 @@ const BalanceWrapper = styled.div` `; class Unbond extends TxComponent { - state: State = {}; + public state: State = {}; componentDidUpdate (prevProps: Props) { const { staking_ledger } = this.props; @@ -48,7 +48,7 @@ class Unbond extends TxComponent { } } - render () { + public render (): React.ReactNode { const { controllerId, isOpen, onClose, t } = this.props; const { maxUnbond } = this.state; const canSubmit = !!maxUnbond && maxUnbond.gtn(0); diff --git a/packages/app-staking/src/Actions/Account/Validate.tsx b/packages/app-staking/src/Actions/Account/Validate.tsx index 7587137ac5..999ffb7088 100644 --- a/packages/app-staking/src/Actions/Account/Validate.tsx +++ b/packages/app-staking/src/Actions/Account/Validate.tsx @@ -12,22 +12,22 @@ import { Button, InputAddress, InputBalance, InputNumber, Modal, TxButton, TxCom import InputValidationUnstakeThreshold from './InputValidationUnstakeThreshold'; import translate from '../../translate'; -type Props = I18nProps & { - controllerId: string, - isOpen: boolean, - onClose: () => void, - stashId: string, - validatorPrefs?: ValidatorPrefs -}; +interface Props extends I18nProps { + controllerId: string; + isOpen: boolean; + onClose: () => void; + stashId: string; + validatorPrefs?: ValidatorPrefs; +} -type State = { - unstakeThreshold?: BN, - unstakeThresholdError: string | null, - validatorPayment?: BN -}; +interface State { + unstakeThreshold?: BN; + unstakeThresholdError: string | null; + validatorPayment?: BN; +} class Validate extends TxComponent { - state: State = { + public state: State = { unstakeThreshold: new BN(3), unstakeThresholdError: null, validatorPayment: new BN(0) @@ -57,7 +57,7 @@ class Validate extends TxComponent { }; } - render () { + public render (): React.ReactNode { const { isOpen } = this.props; if (!isOpen) { diff --git a/packages/app-staking/src/Actions/Account/index.tsx b/packages/app-staking/src/Actions/Account/index.tsx index a174c94216..25b6a0cc6c 100644 --- a/packages/app-staking/src/Actions/Account/index.tsx +++ b/packages/app-staking/src/Actions/Account/index.tsx @@ -1,3 +1,4 @@ +/* eslint-disable @typescript-eslint/camelcase */ // Copyright 2017-2019 @polkadot/app-staking authors & contributors // This software may be modified and distributed under the terms // of the Apache-2.0 license. See the LICENSE file for details. @@ -25,35 +26,35 @@ import Unbond from './Unbond'; import Validate from './Validate'; type Props = ApiProps & I18nProps & { - accountId: string, - className?: string, - recentlyOffline: RecentlyOfflineMap, - balances_all?: DerivedBalances, - staking_info?: DerivedStaking, - stashOptions: KeyringSectionOption[] + accountId: string; + className?: string; + recentlyOffline: RecentlyOfflineMap; + balances_all?: DerivedBalances; + staking_info?: DerivedStaking; + stashOptions: KeyringSectionOption[]; }; -type State = { - controllerId: string | null, - destination: number, - isActiveStash: boolean, - isBondExtraOpen: boolean, - isNominateOpen: boolean, - isSetControllerAccountOpen: boolean, - isSetRewardDestinationOpen: boolean, - isSetSessionAccountOpen: boolean, - isSettingPopupOpen: boolean, - isStashNominating: boolean, - isStashValidating: boolean, - isUnbondOpen: boolean, - isValidateOpen: boolean, - nominees?: string[], - sessionId: string | null, - stakers?: Exposure, - stakingLedger?: StakingLedger, - stashId: string | null, - validatorPrefs?: ValidatorPrefs -}; +interface State { + controllerId: string | null; + destination: number; + isActiveStash: boolean; + isBondExtraOpen: boolean; + isNominateOpen: boolean; + isSetControllerAccountOpen: boolean; + isSetRewardDestinationOpen: boolean; + isSetSessionAccountOpen: boolean; + isSettingPopupOpen: boolean; + isStashNominating: boolean; + isStashValidating: boolean; + isUnbondOpen: boolean; + isValidateOpen: boolean; + nominees?: string[]; + sessionId: string | null; + stakers?: Exposure; + stakingLedger?: StakingLedger; + stashId: string | null; + validatorPrefs?: ValidatorPrefs; +} function toIdString (id?: AccountId | null): string | null { return id @@ -62,7 +63,7 @@ function toIdString (id?: AccountId | null): string | null { } class Account extends React.PureComponent { - state: State = { + public state: State = { controllerId: null, destination: 0, isActiveStash: false, @@ -80,8 +81,7 @@ class Account extends React.PureComponent { stashId: null }; - static getDerivedStateFromProps ({ accountId, staking_info }: Props): State | null { - + public static getDerivedStateFromProps ({ accountId, staking_info }: Props): State | null { if (!staking_info) { return null; } @@ -102,10 +102,10 @@ class Account extends React.PureComponent { stakingLedger, stashId: toIdString(stashId), validatorPrefs - } as any as State; + } as unknown as State; } - render () { + public render (): React.ReactNode { const { className, t } = this.props; const { isActiveStash, stashId } = this.state; @@ -157,7 +157,7 @@ class Account extends React.PureComponent { ); } - private renderBondExtra () { + private renderBondExtra (): React.ReactNode { const { controllerId, isBondExtraOpen, stashId } = this.state; return ( @@ -170,7 +170,7 @@ class Account extends React.PureComponent { ); } - private renderUnbond () { + private renderUnbond (): React.ReactNode { const { controllerId, isUnbondOpen, stashId } = this.state; return ( @@ -183,7 +183,7 @@ class Account extends React.PureComponent { ); } - private renderInfos () { + private renderInfos (): React.ReactNode { const { stashId } = this.state; return ( @@ -202,7 +202,7 @@ class Account extends React.PureComponent { ); } - private renderNominee () { + private renderNominee (): React.ReactNode { const { t } = this.props; const { nominees } = this.state; @@ -213,7 +213,7 @@ class Account extends React.PureComponent { return (
- {nominees.map((nomineeId, index) => ( + {nominees.map((nomineeId, index): React.ReactNode => ( { ); } - private renderOffline (address: AccountId | string) { + private renderOffline (address: AccountId | string): React.ReactNode { const { recentlyOffline } = this.props; return ( @@ -238,7 +238,7 @@ class Account extends React.PureComponent { ); } - private renderControllerAccount () { + private renderControllerAccount (): React.ReactNode { const { t } = this.props; const { controllerId } = this.state; @@ -266,7 +266,7 @@ class Account extends React.PureComponent { ); } - private renderSessionAccount () { + private renderSessionAccount (): React.ReactNode { const { t } = this.props; const { sessionId } = this.state; @@ -292,7 +292,7 @@ class Account extends React.PureComponent { ); } - private renderNominate () { + private renderNominate (): React.ReactNode { const { stashOptions } = this.props; const { controllerId, isNominateOpen, nominees, stashId } = this.state; @@ -312,7 +312,7 @@ class Account extends React.PureComponent { ); } - private renderValidate () { + private renderValidate (): React.ReactNode { const { controllerId, isValidateOpen, stashId, validatorPrefs } = this.state; if (!stashId || !controllerId) { @@ -330,7 +330,7 @@ class Account extends React.PureComponent { ); } - private renderButtons () { + private renderButtons (): React.ReactNode { const { t } = this.props; const { controllerId, isSettingPopupOpen, isStashNominating, isStashValidating, sessionId } = this.state; const buttons = []; @@ -409,7 +409,7 @@ class Account extends React.PureComponent { ); } - private renderPopupMenu () { + private renderPopupMenu (): React.ReactNode { const { balances_all, t } = this.props; const { isStashNominating, isStashValidating, sessionId } = this.state; @@ -456,7 +456,7 @@ class Account extends React.PureComponent { ); } - private renderSetValidatorPrefs () { + private renderSetValidatorPrefs (): React.ReactNode { const { controllerId, isValidateOpen, stashId, validatorPrefs } = this.state; if (!controllerId || !validatorPrefs || !stashId) { @@ -474,7 +474,7 @@ class Account extends React.PureComponent { ); } - private renderSetControllerAccount () { + private renderSetControllerAccount (): React.ReactNode { const { controllerId, isSetControllerAccountOpen, isStashValidating, stashId } = this.state; if (!isSetControllerAccountOpen || !stashId) { @@ -491,7 +491,7 @@ class Account extends React.PureComponent { ); } - private renderSetRewardDestination () { + private renderSetRewardDestination (): React.ReactNode { const { controllerId, destination, isSetRewardDestinationOpen } = this.state; if (!isSetRewardDestinationOpen || !controllerId) { @@ -507,7 +507,7 @@ class Account extends React.PureComponent { ); } - private renderSetSessionAccount () { + private renderSetSessionAccount (): React.ReactNode { const { controllerId, isSetSessionAccountOpen, stashId, sessionId } = this.state; if (!controllerId || !stashId) { @@ -525,52 +525,52 @@ class Account extends React.PureComponent { ); } - private toggleBondExtra = () => { - this.setState(({ isBondExtraOpen }) => ({ + private toggleBondExtra = (): void => { + this.setState(({ isBondExtraOpen }): State => ({ isBondExtraOpen: !isBondExtraOpen - })); + }) as unknown as State); } - private toggleNominate = () => { - this.setState(({ isNominateOpen }) => ({ + private toggleNominate = (): void => { + this.setState(({ isNominateOpen }): State => ({ isNominateOpen: !isNominateOpen - })); + }) as unknown as State); } - private toggleSetControllerAccount = () => { - this.setState(({ isSetControllerAccountOpen }) => ({ + private toggleSetControllerAccount = (): void => { + this.setState(({ isSetControllerAccountOpen }): State => ({ isSetControllerAccountOpen: !isSetControllerAccountOpen - })); + }) as unknown as State); } - private toggleSetRewardDestination = () => { - this.setState(({ isSetRewardDestinationOpen }) => ({ + private toggleSetRewardDestination = (): void => { + this.setState(({ isSetRewardDestinationOpen }): State => ({ isSetRewardDestinationOpen: !isSetRewardDestinationOpen - })); + }) as unknown as State); } - private toggleSetSessionAccount = () => { - this.setState(({ isSetSessionAccountOpen }) => ({ + private toggleSetSessionAccount = (): void => { + this.setState(({ isSetSessionAccountOpen }): State => ({ isSetSessionAccountOpen: !isSetSessionAccountOpen - })); + }) as unknown as State); } - private toggleSettingPopup = () => { - this.setState(({ isSettingPopupOpen }) => ({ + private toggleSettingPopup = (): void => { + this.setState(({ isSettingPopupOpen }): State => ({ isSettingPopupOpen: !isSettingPopupOpen - })); + }) as unknown as State); } - private toggleUnbond = () => { - this.setState(({ isUnbondOpen }) => ({ + private toggleUnbond = (): void => { + this.setState(({ isUnbondOpen }): State => ({ isUnbondOpen: !isUnbondOpen - })); + }) as unknown as State); } - private toggleValidate = () => { - this.setState(({ isValidateOpen }) => ({ + private toggleValidate = (): void => { + this.setState(({ isValidateOpen }): State => ({ isValidateOpen: !isValidateOpen - })); + }) as unknown as State); } } diff --git a/packages/app-staking/src/Actions/Accounts.tsx b/packages/app-staking/src/Actions/Accounts.tsx index 1820647ecd..6adef828d2 100644 --- a/packages/app-staking/src/Actions/Accounts.tsx +++ b/packages/app-staking/src/Actions/Accounts.tsx @@ -19,19 +19,19 @@ import StartStaking from './NewStake'; import translate from '../translate'; type Props = I18nProps & ComponentProps & ApiProps & { - myControllers?: string[] + myControllers?: string[]; }; -type State = { - isNewStakeOpen: boolean -}; +interface State { + isNewStakeOpen: boolean; +} -class Accounts extends React.PureComponent { - state: State = { +class Accounts extends React.PureComponent { + public state: State = { isNewStakeOpen: false }; - render () { + public render (): React.ReactNode { const { className, recentlyOffline, t } = this.props; const { isNewStakeOpen } = this.state; const stashOptions = this.getStashOptions(); @@ -49,7 +49,7 @@ class Accounts extends React.PureComponent { {t('New stake')} - } + } onClick={this.toggleNewStake} /> } @@ -58,7 +58,7 @@ class Accounts extends React.PureComponent { isEmpty={isEmpty} > {this.renderNewStake()} - {myStashes && myStashes.map((address, index) => ( + {myStashes && myStashes.map((address, index): React.ReactNode => ( address && { ); } - private getMyStashes () { + private getMyStashes (): string[] | null { const { myControllers, allAccounts } = this.props; const result: string[] = []; @@ -79,7 +79,7 @@ class Accounts extends React.PureComponent { return null; } - myControllers.forEach((value,index) => { + myControllers.forEach((value, index): void => { if (value.toString() !== '') { allAccounts && result.push(Object.keys(allAccounts)[index]); } @@ -91,12 +91,12 @@ class Accounts extends React.PureComponent { private getStashOptions (): KeyringSectionOption[] { const { allStashes } = this.props; - return allStashes.map((stashId) => + return allStashes.map((stashId): KeyringSectionOption => createOption(stashId, getAddressName(stashId, 'account')) ); } - private renderNewStake () { + private renderNewStake (): React.ReactNode { const { isNewStakeOpen } = this.state; if (!isNewStakeOpen) { @@ -111,7 +111,7 @@ class Accounts extends React.PureComponent { } private toggleNewStake = (): void => { - this.setState(({ isNewStakeOpen }) => ({ + this.setState(({ isNewStakeOpen }): State => ({ isNewStakeOpen: !isNewStakeOpen })); } @@ -127,7 +127,7 @@ export default withMulti( withCalls( ['query.staking.bonded', { isMulti: true, - paramPick: ({ allAccounts }: Props) => { + paramPick: ({ allAccounts }: Props): undefined | string[] => { return allAccounts && Object.keys(allAccounts); }, propName: 'myControllers' diff --git a/packages/app-staking/src/Actions/NewStake.tsx b/packages/app-staking/src/Actions/NewStake.tsx index 8856137a87..1eccd1de8a 100644 --- a/packages/app-staking/src/Actions/NewStake.tsx +++ b/packages/app-staking/src/Actions/NewStake.tsx @@ -17,22 +17,22 @@ import { rewardDestinationOptions } from './constants'; import InputValidationController from './Account/InputValidationController'; type Props = I18nProps & ApiProps & CalculateBalanceProps & { - onClose: () => void + onClose: () => void; }; -type State = { - bondValue?: BN, - controllerError: string | null, - controllerId: string | null, - destination: number, - extrinsic: SubmittableExtrinsic | null, - stashId: string | null -}; +interface State { + bondValue?: BN; + controllerError: string | null; + controllerId: string | null; + destination: number; + extrinsic: SubmittableExtrinsic | null; + stashId: string | null; +} class NewStake extends TxComponent { - state: State; + public state: State; - constructor (props: Props) { + public constructor (props: Props) { super(props); this.state = { @@ -44,7 +44,7 @@ class NewStake extends TxComponent { }; } - render () { + public render (): React.ReactNode { const { onClose, t } = this.props; const { bondValue, controllerError, controllerId, extrinsic, stashId } = this.state; const hasValue = !!bondValue && bondValue.gtn(0); diff --git a/packages/app-staking/src/Overview/Address.tsx b/packages/app-staking/src/Overview/Address.tsx index 8770c81d70..3df5811db6 100644 --- a/packages/app-staking/src/Overview/Address.tsx +++ b/packages/app-staking/src/Overview/Address.tsx @@ -1,3 +1,4 @@ +/* eslint-disable @typescript-eslint/camelcase */ // Copyright 2017-2019 @polkadot/app-staking authors & contributors // This software may be modified and distributed under the terms // of the Apache-2.0 license. See the LICENSE file for details. @@ -16,32 +17,32 @@ import { formatBalance } from '@polkadot/util'; import translate from '../translate'; -type Props = I18nProps & { - address: string, // controller (v1) or stash (v2) - balances: DerivedBalancesMap, - className?: string, - defaultName: string, - lastAuthor: string, - lastBlock: string, - recentlyOffline: RecentlyOfflineMap, - filter: ValidatorFilter, - staking_info?: DerivedStaking -}; +interface Props extends I18nProps { + address: string; + balances: DerivedBalancesMap; + className?: string; + defaultName: string; + lastAuthor: string; + lastBlock: string; + recentlyOffline: RecentlyOfflineMap; + filter: ValidatorFilter; + staking_info?: DerivedStaking; +} -type State = { - controllerId: string | null, - stashActive: string | null, - stashTotal: string | null, - sessionId: string | null, - stakers?: Exposure, - stashId: string | null, +interface State { + controllerId: string | null; + stashActive: string | null; + stashTotal: string | null; + sessionId: string | null; + stakers?: Exposure; + stashId: string | null; badgeExpanded: boolean; -}; +} class Address extends React.PureComponent { - state: State; + public state: State; - constructor (props: Props) { + public constructor (props: Props) { super(props); this.state = { @@ -54,7 +55,7 @@ class Address extends React.PureComponent { }; } - static getDerivedStateFromProps ({ staking_info }: Props, prevState: State): State | null { + public static getDerivedStateFromProps ({ staking_info }: Props, prevState: State): State | null { if (!staking_info) { return null; } @@ -72,21 +73,21 @@ class Address extends React.PureComponent { stashTotal: stakingLedger ? formatBalance(stakingLedger.total) : prevState.stashTotal - } as State; + } as unknown as State; } - render () { + public render (): React.ReactNode { const { className, defaultName, filter } = this.props; const { controllerId, stakers, stashId } = this.state; const bonded = stakers && !stakers.own.isZero() ? [stakers.own, stakers.total.sub(stakers.own)] : true; - if ((filter === 'hasNominators' && !this.hasNominators()) - || (filter === 'noNominators' && this.hasNominators()) - || (filter === 'hasWarnings' && !this.hasWarnings()) - || (filter === 'noWarnings' && this.hasWarnings()) - || (filter === 'iNominated' && !this.iNominated())) { + if ((filter === 'hasNominators' && !this.hasNominators()) || + (filter === 'noNominators' && this.hasNominators()) || + (filter === 'hasWarnings' && !this.hasWarnings()) || + (filter === 'noWarnings' && this.hasWarnings()) || + (filter === 'iNominated' && !this.iNominated())) { return null; } @@ -105,7 +106,7 @@ class Address extends React.PureComponent { ); } - private renderKeys () { + private renderKeys (): React.ReactNode { const { address, lastAuthor, lastBlock, t } = this.props; const { controllerId, sessionId, stashId } = this.state; const isSame = controllerId === sessionId; @@ -143,7 +144,7 @@ class Address extends React.PureComponent { ); } - private getNominators () { + private getNominators (): [AccountId, Balance][] { const { stakers } = this.state; return stakers @@ -151,22 +152,22 @@ class Address extends React.PureComponent { : []; } - private iNominated () { + private iNominated (): boolean { const nominators = this.getNominators(); - const myAddresses = keyring.getAccounts().map(({ address }) => address); + const myAddresses = keyring.getAccounts().map(({ address }): string => address); - return nominators.some(([who]) => + return nominators.some(([who]): boolean => myAddresses.includes(who.toString()) ); } - private hasNominators () { + private hasNominators (): boolean { const nominators = this.getNominators(); return !!nominators.length; } - private hasWarnings () { + private hasWarnings (): boolean { const { recentlyOffline } = this.props; const { stashId } = this.state; @@ -177,7 +178,7 @@ class Address extends React.PureComponent { return true; } - private renderNominators () { + private renderNominators (): React.ReactNode { const { t } = this.props; const nominators = this.getNominators(); @@ -194,7 +195,7 @@ class Address extends React.PureComponent { } })}
- {nominators.map(([who, bonded]) => + {nominators.map(([who, bonded]): React.ReactNode => { ); } - private renderOffline () { + private renderOffline (): React.ReactNode { const { recentlyOffline } = this.props; const { stashId } = this.state; diff --git a/packages/app-staking/src/Overview/CurrentList.tsx b/packages/app-staking/src/Overview/CurrentList.tsx index 35aa0fe745..ed744ad534 100644 --- a/packages/app-staking/src/Overview/CurrentList.tsx +++ b/packages/app-staking/src/Overview/CurrentList.tsx @@ -12,24 +12,24 @@ import { Columar, Column, Dropdown, FilterOverlay } from '@polkadot/ui-app'; import translate from '../translate'; import Address from './Address'; -type Props = I18nProps & { - balances?: DerivedBalancesMap, - currentValidatorsControllersV1OrStashesV2: string[], - lastAuthor?: string, - lastBlock: string, - next: string[], - recentlyOffline: RecentlyOfflineMap -}; +interface Props extends I18nProps { + balances?: DerivedBalancesMap; + currentValidatorsControllersV1OrStashesV2: string[]; + lastAuthor?: string; + lastBlock: string; + next: string[]; + recentlyOffline: RecentlyOfflineMap; +} -type State = { - filter: ValidatorFilter, - filterOptions: { text: React.ReactNode, value: ValidatorFilter }[] -}; +interface State { + filter: ValidatorFilter; + filterOptions: { text: React.ReactNode; value: ValidatorFilter }[]; +} class CurrentList extends React.PureComponent { - state: State; + public state: State; - constructor (props: Props) { + public constructor (props: Props) { super(props); const { t } = props; @@ -47,7 +47,7 @@ class CurrentList extends React.PureComponent { }; } - render () { + public render (): React.ReactNode { const { currentValidatorsControllersV1OrStashesV2, next, t } = this.props; const { filter, filterOptions } = this.state; return ( @@ -78,11 +78,11 @@ class CurrentList extends React.PureComponent { ); } - private renderColumn (addresses: string[], defaultName: string) { + private renderColumn (addresses: string[], defaultName: string): React.ReactNode { const { balances, lastAuthor, lastBlock, recentlyOffline } = this.props; const { filter } = this.state; - return addresses.map((address) => ( + return addresses.map((address): React.ReactNode => (
{ - render () { + public render (): React.ReactNode { const { className, allControllers, lastAuthor, lastBlock, style, t, staking_validatorCount, currentValidatorsControllersV1OrStashesV2 } = this.props; const waiting = allControllers.length > currentValidatorsControllersV1OrStashesV2.length ? (allControllers.length - currentValidatorsControllersV1OrStashesV2.length) diff --git a/packages/app-staking/src/Overview/index.tsx b/packages/app-staking/src/Overview/index.tsx index 7020b46f0a..d6175b6718 100644 --- a/packages/app-staking/src/Overview/index.tsx +++ b/packages/app-staking/src/Overview/index.tsx @@ -1,3 +1,4 @@ +/* eslint-disable @typescript-eslint/camelcase */ // Copyright 2017-2019 @polkadot/app-staking authors & contributors // This software may be modified and distributed under the terms // of the Apache-2.0 license. See the LICENSE file for details. @@ -16,27 +17,27 @@ import { withApi } from '@polkadot/ui-api'; import { ApiProps } from '@polkadot/ui-api/types'; type Props = ApiProps & BareProps & ComponentProps & { - chain_subscribeNewHead?: HeaderExtended + chain_subscribeNewHead?: HeaderExtended; }; class Overview extends React.PureComponent { - render () { + public render (): React.ReactNode { const { chain_subscribeNewHead, allControllers, allStashes, recentlyOffline, currentValidatorsControllersV1OrStashesV2, isSubstrateV2 } = this.props; let nextSorted: string[]; if (isSubstrateV2) { // this is a V2 node currentValidatorsControllersV1OrStashesV2 is a list of stashes - nextSorted = allStashes.filter((address) => + nextSorted = allStashes.filter((address): boolean => !currentValidatorsControllersV1OrStashesV2.includes(address) ); } else { // this is a V1 node currentValidatorsControllersV1OrStashesV2 is a list of controllers - nextSorted = allControllers.filter((address) => + nextSorted = allControllers.filter((address): boolean => !currentValidatorsControllersV1OrStashesV2.includes(address) ); } - let lastBlock: string = '—'; + let lastBlock = '—'; let lastAuthor: string | undefined; if (chain_subscribeNewHead) { diff --git a/packages/app-staking/src/index.tsx b/packages/app-staking/src/index.tsx index 4c57366318..3c0335fefc 100644 --- a/packages/app-staking/src/index.tsx +++ b/packages/app-staking/src/index.tsx @@ -1,3 +1,4 @@ +/* eslint-disable @typescript-eslint/camelcase */ // Copyright 2017-2019 @polkadot/app-staking authors & contributors // This software may be modified and distributed under the terms // of the Apache-2.0 license. See the LICENSE file for details. @@ -23,24 +24,24 @@ import Overview from './Overview'; import translate from './translate'; type Props = AppProps & ApiProps & I18nProps & { - allAccounts?: SubjectInfo, - allStashesAndControllers?: [AccountId[], Option[]], - currentValidatorsControllersV1OrStashesV2?: AccountId[], - staking_recentlyOffline?: RecentlyOffline + allAccounts?: SubjectInfo; + allStashesAndControllers?: [AccountId[], Option[]]; + currentValidatorsControllersV1OrStashesV2?: AccountId[]; + staking_recentlyOffline?: RecentlyOffline; }; -type State = { - allControllers: string[], - allStashes: string[], - currentValidatorsControllersV1OrStashesV2: string[], - recentlyOffline: RecentlyOfflineMap, - tabs: TabItem[] -}; +interface State { + allControllers: string[]; + allStashes: string[]; + currentValidatorsControllersV1OrStashesV2: string[]; + recentlyOffline: RecentlyOfflineMap; + tabs: TabItem[]; +} class App extends React.PureComponent { - state: State; + public state: State; - constructor (props: Props) { + public constructor (props: Props) { super(props); const { t } = props; @@ -64,17 +65,17 @@ class App extends React.PureComponent { }; } - static getDerivedStateFromProps ({ allStashesAndControllers = [[], []], currentValidatorsControllersV1OrStashesV2 = [], staking_recentlyOffline = [] }: Props): State { + public static getDerivedStateFromProps ({ allStashesAndControllers = [[], []], currentValidatorsControllersV1OrStashesV2 = [], staking_recentlyOffline = [] }: Props): State { return { - allControllers: allStashesAndControllers[1].filter((optId) => optId.isSome).map((accountId) => + allControllers: allStashesAndControllers[1].filter((optId): boolean => optId.isSome).map((accountId): string => accountId.unwrap().toString() ), - allStashes: allStashesAndControllers[0].map((accountId) => accountId.toString()), - currentValidatorsControllersV1OrStashesV2: currentValidatorsControllersV1OrStashesV2.map((authorityId) => + allStashes: allStashesAndControllers[0].map((accountId): string => accountId.toString()), + currentValidatorsControllersV1OrStashesV2: currentValidatorsControllersV1OrStashesV2.map((authorityId): string => authorityId.toString() ), recentlyOffline: staking_recentlyOffline.reduce( - (result, [accountId, blockNumber, count]) => { + (result, [accountId, blockNumber, count]): RecentlyOfflineMap => { const account = accountId.toString(); if (!result[account]) { @@ -87,11 +88,11 @@ class App extends React.PureComponent { }); return result; - }, {} as RecentlyOfflineMap) - } as State; + }, {} as unknown as RecentlyOfflineMap) + } as unknown as State; } - render () { + public render (): React.ReactNode { const { allAccounts, basePath } = this.props; const { tabs } = this.state; const hidden = !allAccounts || Object.keys(allAccounts).length === 0 @@ -116,7 +117,7 @@ class App extends React.PureComponent { ); } - private renderComponent (Component: React.ComponentType) { + private renderComponent (Component: React.ComponentType): () => React.ReactNode { return (): React.ReactNode => { const { allControllers, recentlyOffline, allStashes, currentValidatorsControllersV1OrStashesV2 } = this.state; const { allAccounts } = this.props; diff --git a/packages/app-staking/src/types.ts b/packages/app-staking/src/types.ts index 1e37de7c32..9a43998d97 100644 --- a/packages/app-staking/src/types.ts +++ b/packages/app-staking/src/types.ts @@ -7,30 +7,25 @@ import BN from 'bn.js'; import { DerivedFees, DerivedBalances } from '@polkadot/api-derive/types'; import { SubjectInfo } from '@polkadot/ui-keyring/observable/types'; -export type Nominators = { - // stash account and who is being nominated - [index: string]: string[] -}; +export type Nominators = Record; -export type ComponentProps = { - allAccounts?: SubjectInfo, - allControllers: string[], - allStashes: string[], - currentValidatorsControllersV1OrStashesV2: string[], - recentlyOffline: RecentlyOfflineMap -}; +export interface ComponentProps { + allAccounts?: SubjectInfo; + allControllers: string[]; + allStashes: string[]; + currentValidatorsControllersV1OrStashesV2: string[]; + recentlyOffline: RecentlyOfflineMap; +} -export type CalculateBalanceProps = { - balances_fees?: DerivedFees, - balances_all?: DerivedBalances, - system_accountNonce?: BN -}; +export interface CalculateBalanceProps { + balances_fees?: DerivedFees; + balances_all?: DerivedBalances; + system_accountNonce?: BN; +} export type RecentlyOffline = [AccountId, BlockNumber, BN][]; -export type RecentlyOfflineMap = { - [s: string]: OfflineStatus[] -}; +export type RecentlyOfflineMap = Record; export interface OfflineStatus { blockNumber: BlockNumber; diff --git a/packages/app-storage/src/Queries.tsx b/packages/app-storage/src/Queries.tsx index 19c5e8fa35..d438e8fc6a 100644 --- a/packages/app-storage/src/Queries.tsx +++ b/packages/app-storage/src/Queries.tsx @@ -9,13 +9,13 @@ import React from 'react'; import Query from './Query'; -type Props = BareProps & { - onRemove: (id: number) => void, - value?: Array -}; +interface Props extends BareProps { + onRemove: (id: number) => void; + value?: QueryTypes[]; +} export default class Queries extends React.PureComponent { - render () { + public render (): React.ReactNode { const { onRemove, value } = this.props; if (!value || !value.length) { @@ -24,7 +24,7 @@ export default class Queries extends React.PureComponent { return (
- {value.map((query) => + {value.map((query): React.ReactNode => void, - value: QueryTypes -}; +interface Props extends I18nProps { + onRemove: (id: number) => void; + value: QueryTypes; +} -type ComponentProps = {}; +interface State { + inputs: React.ReactNode[]; + Component: React.ComponentType<{}>; + spread: Record; +} -type State = { - inputs: Array, - Component: React.ComponentType, - spread: { [index: number]: boolean } -}; +interface CacheInstance { + Component: React.ComponentType; + render: RenderFn; + refresh: (swallowErrors: boolean, contentShorten: boolean) => React.ComponentType; +} -type CacheInstance = { - Component: React.ComponentType, - render: RenderFn, - refresh: (swallowErrors: boolean, contentShorten: boolean) => React.ComponentType -}; - -const cache: Array = []; +const cache: CacheInstance[] = []; class Query extends React.PureComponent { - state: State = { spread: {} } as State; + public state: State = { spread: {} } as State; static getCachedComponent (query: QueryTypes): CacheInstance { const { id, key, params = [] } = query as StorageModuleQuery; if (!cache[id]) { - const values: Array = params.map(({ value }) => value); + const values: any[] = params.map(({ value }) => value); const type = key.creator.meta ? key.creator.meta.type.toString() : 'Data'; @@ -87,7 +85,7 @@ class Query extends React.PureComponent { static getDerivedStateFromProps ({ value }: Props) { const Component = Query.getCachedComponent(value).Component; - const inputs: Array = isU8a(value.key) + const inputs: React.ReactNode[] = isU8a(value.key) ? [] // FIXME We need to render the actual key params // const { key, params } = value; @@ -104,7 +102,7 @@ class Query extends React.PureComponent { } as State; } - render () { + public render (): React.ReactNode { const { className, value } = this.props; const { Component } = this.state; const { key } = value; diff --git a/packages/app-storage/src/Selection/Modules.tsx b/packages/app-storage/src/Selection/Modules.tsx index 374959e46a..bb1f8a273f 100644 --- a/packages/app-storage/src/Selection/Modules.tsx +++ b/packages/app-storage/src/Selection/Modules.tsx @@ -19,18 +19,18 @@ import translate from '../translate'; type Props = ComponentProps & ApiProps & I18nProps; -type State = { - isValid: boolean, - key: StorageEntryPromise, - values: RawParams, - params: Array<{ type: TypeDef }> -}; +interface State { + isValid: boolean; + key: StorageEntryPromise; + values: RawParams; + params: { type: TypeDef }[]; +} class Modules extends TxComponent { private defaultValue: any; public state: State; - constructor (props: Props) { + public constructor (props: Props) { super(props); const { api } = this.props; @@ -44,7 +44,7 @@ class Modules extends TxComponent { }; } - public render () { + public render (): React.ReactNode { const { t } = this.props; const { isValid, key: { creator: { method, section, meta } }, params } = this.state; diff --git a/packages/app-storage/src/Selection/Raw.tsx b/packages/app-storage/src/Selection/Raw.tsx index 81ccab538e..ed2795a6e1 100644 --- a/packages/app-storage/src/Selection/Raw.tsx +++ b/packages/app-storage/src/Selection/Raw.tsx @@ -14,18 +14,18 @@ import { Compact } from '@polkadot/types'; type Props = ComponentProps & I18nProps; -type State = { - isValid: boolean, - key: Uint8Array -}; +interface State { + isValid: boolean; + key: Uint8Array; +} class Raw extends TxComponent { - state: State = { + public state: State = { isValid: false, key: new Uint8Array([]) }; - render () { + public render (): React.ReactNode { const { t } = this.props; const { isValid } = this.state; diff --git a/packages/app-storage/src/Selection/index.tsx b/packages/app-storage/src/Selection/index.tsx index 597f5caa4a..b8fb0d2069 100644 --- a/packages/app-storage/src/Selection/index.tsx +++ b/packages/app-storage/src/Selection/index.tsx @@ -14,19 +14,19 @@ import Modules from './Modules'; import Raw from './Raw'; import translate from '../translate'; -type Props = I18nProps & { - basePath: string, - onAdd: (query: QueryTypes) => void -}; +interface Props extends I18nProps { + basePath: string; + onAdd: (query: QueryTypes) => void; +} -type State = { - items: Array -}; +interface State { + items: TabItem[]; +} let id = -1; class Selection extends React.PureComponent { - constructor (props: Props) { + public constructor (props: Props) { super(props); const { t } = this.props; @@ -46,7 +46,7 @@ class Selection extends React.PureComponent { }; } - render () { + public render (): React.ReactNode { const { basePath } = this.props; const { items } = this.state; diff --git a/packages/app-storage/src/index.tsx b/packages/app-storage/src/index.tsx index 9404ebca93..9f23c380ef 100644 --- a/packages/app-storage/src/index.tsx +++ b/packages/app-storage/src/index.tsx @@ -15,16 +15,16 @@ import translate from './translate'; type Props = AppProps & I18nProps; -type State = { - queue: Array -}; +interface State { + queue: QueryTypes[]; +} class StorageApp extends React.PureComponent { - state: State = { + public state: State = { queue: [] }; - render () { + public render (): React.ReactNode { const { basePath } = this.props; const { queue } = this.state; @@ -53,7 +53,7 @@ class StorageApp extends React.PureComponent { private onRemove = (id: number): void => { this.setState( (prevState: State): State => ({ - queue: prevState.queue.filter((item) => item.id !== id) + queue: prevState.queue.filter((item): boolean => item.id !== id) }) ); } diff --git a/packages/app-storage/src/types.ts b/packages/app-storage/src/types.ts index 1f19e9b74b..83d1013cb3 100644 --- a/packages/app-storage/src/types.ts +++ b/packages/app-storage/src/types.ts @@ -5,20 +5,20 @@ import { StorageEntryPromise } from '@polkadot/api/types'; import { RawParams } from '@polkadot/ui-params/types'; -type IdQuery = { - id: number -}; +interface IdQuery { + id: number; +} -export type PartialModuleQuery = { - key: StorageEntryPromise, - params: RawParams -}; +export interface PartialModuleQuery { + key: StorageEntryPromise; + params: RawParams; +} export type StorageModuleQuery = PartialModuleQuery & IdQuery; -export type PartialRawQuery = { - key: Uint8Array -}; +export interface PartialRawQuery { + key: Uint8Array; +} export type StorageRawQuery = PartialRawQuery & IdQuery; @@ -26,6 +26,6 @@ export type QueryTypes = StorageModuleQuery | StorageRawQuery; export type ParitalQueryTypes = PartialModuleQuery | PartialRawQuery; -export type ComponentProps = { - onAdd: (query: ParitalQueryTypes) => void -}; +export interface ComponentProps { + onAdd: (query: ParitalQueryTypes) => void; +} diff --git a/packages/app-sudo/src/SetKey.tsx b/packages/app-sudo/src/SetKey.tsx index b41247fb5f..187dbaf3c2 100644 --- a/packages/app-sudo/src/SetKey.tsx +++ b/packages/app-sudo/src/SetKey.tsx @@ -13,9 +13,9 @@ import translate from './translate'; type Props = I18nProps & ComponentProps; -type State = { - selected?: string -}; +interface State { + selected?: string; +} const SudoInputAddress = styled(InputAddress)` margin: -0.25rem 0.5rem -0.25rem 0; @@ -26,9 +26,9 @@ const SudoLabelled = styled(Labelled)` `; class SetKey extends React.PureComponent { - state: State = {}; + public state: State = {}; - constructor (props: Props) { + public constructor (props: Props) { super(props); this.state = { @@ -42,7 +42,7 @@ class SetKey extends React.PureComponent { } } - render () { + public render (): React.ReactNode { const { className, isMine, sudoKey, t } = this.props; const { selected } = this.state; diff --git a/packages/app-sudo/src/Sudo.tsx b/packages/app-sudo/src/Sudo.tsx index 2b17ebba79..29b815218c 100644 --- a/packages/app-sudo/src/Sudo.tsx +++ b/packages/app-sudo/src/Sudo.tsx @@ -17,18 +17,18 @@ type Props = I18nProps & ApiProps & ComponentProps & { onChange: (accountId?: string) => void }; -type State = { - method: Method | null, - isValid: boolean -}; +interface State { + method: Method | null; + isValid: boolean; +} class Propose extends TxComponent { - state: State = { + public state: State = { method: null, isValid: false }; - render () { + public render (): React.ReactNode { const { apiDefaultTxSudo, isMine, sudoKey, t } = this.props; const { method, isValid } = this.state; diff --git a/packages/app-sudo/src/index.tsx b/packages/app-sudo/src/index.tsx index d0d09dcc4b..67835d05b8 100644 --- a/packages/app-sudo/src/index.tsx +++ b/packages/app-sudo/src/index.tsx @@ -1,3 +1,4 @@ +/* eslint-disable @typescript-eslint/camelcase */ // Copyright 2017-2019 @polkadot/app-123code authors & contributors // This software may be modified and distributed under the terms // of the Apache-2.0 license. See the LICENSE file for details. @@ -19,26 +20,26 @@ import Sudo from './Sudo'; import translate from './translate'; type Props = AppProps & ApiProps & I18nProps & { - allAccounts: SubjectInfo, - sudo_key?: string + allAccounts: SubjectInfo; + sudo_key?: string; }; -type State = { - isMine: boolean -}; +interface State { + isMine: boolean; +} class App extends React.PureComponent { - state: State = { + public state: State = { isMine: false }; - static getDerivedStateFromProps ({ allAccounts = {}, sudo_key }: Props): State | null { + public static getDerivedStateFromProps ({ allAccounts = {}, sudo_key }: Props): State | null { return { - isMine: !!sudo_key && !!Object.keys(allAccounts).find((key) => key === sudo_key.toString()) + isMine: !!sudo_key && !!Object.keys(allAccounts).find((key): boolean => key === sudo_key.toString()) }; } - render () { + public render (): React.ReactNode { const { basePath, t } = this.props; const { isMine } = this.state; diff --git a/packages/app-sudo/src/types.ts b/packages/app-sudo/src/types.ts index 0424b22dc7..78e0f326d6 100644 --- a/packages/app-sudo/src/types.ts +++ b/packages/app-sudo/src/types.ts @@ -4,8 +4,8 @@ import { SubjectInfo } from '@polkadot/ui-keyring/observable/types'; -export type ComponentProps = { - allAccounts: SubjectInfo, - isMine: boolean, - sudoKey?: string -}; +export interface ComponentProps { + allAccounts: SubjectInfo; + isMine: boolean; + sudoKey?: string; +} diff --git a/packages/app-toolbox/src/Hash.tsx b/packages/app-toolbox/src/Hash.tsx index cd8244fd1a..a8a9d2bd54 100644 --- a/packages/app-toolbox/src/Hash.tsx +++ b/packages/app-toolbox/src/Hash.tsx @@ -11,20 +11,20 @@ import { blake2AsHex } from '@polkadot/util-crypto'; import translate from './translate'; -type State = { - data: string, - hash: string, - isHexData: boolean -}; +interface State { + data: string; + hash: string; + isHexData: boolean; +} class Hash extends React.PureComponent { - state: State = { + public state: State = { data: '', hash: blake2AsHex(stringToU8a(''), 256), isHexData: false }; - render () { + public render (): React.ReactNode { return (
{this.renderInput()} diff --git a/packages/app-toolbox/src/Rpc/Account.tsx b/packages/app-toolbox/src/Rpc/Account.tsx index 40d1063de5..665c716ad1 100644 --- a/packages/app-toolbox/src/Rpc/Account.tsx +++ b/packages/app-toolbox/src/Rpc/Account.tsx @@ -12,21 +12,21 @@ import { Nonce } from '@polkadot/ui-reactive'; import translate from './translate'; -type Props = I18nProps & { - defaultValue?: string | null, - isError?: boolean, - onChange: (accountId: string | undefined | null, accountNonce: BN) => void -}; +interface Props extends I18nProps { + defaultValue?: string | null; + isError?: boolean; + onChange: (accountId: string | undefined | null, accountNonce: BN) => void; +} -type State = { - accountNonce: BN, - accountId?: string | null -}; +interface State { + accountNonce: BN; + accountId?: string | null; +} class Account extends React.PureComponent { - state: State; + public state: State; - constructor (props: Props) { + public constructor (props: Props) { super(props); this.state = { @@ -35,7 +35,7 @@ class Account extends React.PureComponent { }; } - render () { + public render (): React.ReactNode { const { className, defaultValue, isError, t } = this.props; return ( diff --git a/packages/app-toolbox/src/Rpc/Results.tsx b/packages/app-toolbox/src/Rpc/Results.tsx index 2cc5cbf957..1001d50715 100644 --- a/packages/app-toolbox/src/Rpc/Results.tsx +++ b/packages/app-toolbox/src/Rpc/Results.tsx @@ -9,16 +9,16 @@ import React from 'react'; import { Output } from '@polkadot/ui-app'; import { isUndefined } from '@polkadot/util'; -type Props = BareProps & { - queue: Array -}; +interface Props extends BareProps { + queue: QueueTx[]; +} export default class Results extends React.PureComponent { - render () { + public render (): React.ReactNode { const { queue = [] } = this.props; const filtered = queue - .filter(({ error, result }) => + .filter(({ error, result }): boolean => !isUndefined(error) || !isUndefined(result) ) .reverse(); diff --git a/packages/app-toolbox/src/Rpc/Selection.tsx b/packages/app-toolbox/src/Rpc/Selection.tsx index bca145abc2..9aa122f837 100644 --- a/packages/app-toolbox/src/Rpc/Selection.tsx +++ b/packages/app-toolbox/src/Rpc/Selection.tsx @@ -5,7 +5,7 @@ import { RpcMethod } from '@polkadot/jsonrpc/types'; import { RawParam } from '@polkadot/ui-params/types'; import { I18nProps } from '@polkadot/ui-app/types'; -import { QueueTx$RpcAdd } from '@polkadot/ui-app/Status/types'; +import { QueueTxRpcAdd } from '@polkadot/ui-app/Status/types'; import React from 'react'; import rpc from '@polkadot/jsonrpc'; @@ -15,28 +15,28 @@ import Params from '@polkadot/ui-params'; import translate from './translate'; -type Props = I18nProps & { - queueRpc: QueueTx$RpcAdd -}; +interface Props extends I18nProps { + queueRpc: QueueTxRpcAdd; +} -type State = { - isValid: boolean, - accountId?: string | null, - rpc: RpcMethod, - values: Array -}; +interface State { + isValid: boolean; + accountId?: string | null; + rpc: RpcMethod; + values: RawParam[]; +} const defaultMethod = rpc.author.methods.submitExtrinsic; class Selection extends TxComponent { - state: State = { + public state: State = { isValid: false, accountId: null, rpc: defaultMethod, values: [] }; - render () { + public render (): React.ReactNode { const { t } = this.props; const { isValid, rpc } = this.state; const params = rpc.params.map(({ name, type }) => ({ @@ -75,7 +75,7 @@ class Selection extends TxComponent { this.setState( (prevState: State): State => { const { rpc = prevState.rpc, accountId = prevState.accountId, values = prevState.values } = newState; - const isValid = values.reduce((isValid, value) => { + const isValid = values.reduce((isValid, value): boolean => { return isValid && value.isValid === true; }, rpc.params.length === values.length); return { @@ -91,11 +91,11 @@ class Selection extends TxComponent { private onChangeMethod = (rpc: RpcMethod): void => { this.nextState({ rpc, - values: [] as Array + values: [] as RawParam[] } as State); } - private onChangeValues = (values: Array): void => { + private onChangeValues = (values: RawParam[]): void => { this.nextState({ values } as State); } diff --git a/packages/app-toolbox/src/Rpc/index.tsx b/packages/app-toolbox/src/Rpc/index.tsx index 4de9bc1754..e23601da02 100644 --- a/packages/app-toolbox/src/Rpc/index.tsx +++ b/packages/app-toolbox/src/Rpc/index.tsx @@ -14,10 +14,10 @@ import Selection from './Selection'; type Props = BareProps; export default class RpcApp extends React.PureComponent { - render () { + public render (): React.ReactNode { return ( - {({ txqueue, queueRpc }: QueueProps) => ( + {({ txqueue, queueRpc }: QueueProps): React.ReactNode => ( <> diff --git a/packages/app-toolbox/src/Sign.tsx b/packages/app-toolbox/src/Sign.tsx index 8a083809dd..9250964baa 100644 --- a/packages/app-toolbox/src/Sign.tsx +++ b/packages/app-toolbox/src/Sign.tsx @@ -15,23 +15,23 @@ import { hexToU8a, isHex, stringToU8a, u8aToHex } from '@polkadot/util'; import translate from './translate'; import Unlock from './Unlock'; -type Props = I18nProps & { - className?: string -}; +interface Props extends I18nProps { + className?: string; +} -type State = { - currentPair: KeyringPair | null, - data: string, - isHexData: boolean, - isLocked: boolean, - isUnlockVisible: boolean, - signature: string -}; +interface State { + currentPair: KeyringPair | null; + data: string; + isHexData: boolean; + isLocked: boolean; + isUnlockVisible: boolean; + signature: string; +} class Sign extends React.PureComponent { - state: State; + public state: State; - constructor (props: Props) { + public constructor (props: Props) { super(props); const pairs = keyring.getPairs(); @@ -49,7 +49,7 @@ class Sign extends React.PureComponent { }; } - render () { + public render (): React.ReactNode { const { className } = this.props; const { isLocked } = this.state; diff --git a/packages/app-toolbox/src/Unlock.tsx b/packages/app-toolbox/src/Unlock.tsx index d42e32dfaa..851f6ef942 100644 --- a/packages/app-toolbox/src/Unlock.tsx +++ b/packages/app-toolbox/src/Unlock.tsx @@ -10,19 +10,19 @@ import { AddressRow, Button, Modal, Password, TxComponent } from '@polkadot/ui-a import translate from './translate'; -type Props = I18nProps & { - onClose: () => void, - pair: KeyringPair | null -}; +interface Props extends I18nProps { + onClose: () => void; + pair: KeyringPair | null; +} -type State = { - address: string, - password: string, - unlockError: string | null -}; +interface State { + address: string; + password: string; + unlockError: string | null; +} class Unlock extends TxComponent { - state: State = { + public state: State = { address: '', password: '', unlockError: null @@ -34,7 +34,7 @@ class Unlock extends TxComponent { } as State; } - render () { + public render (): React.ReactNode { const { pair, t } = this.props; if (!pair) { diff --git a/packages/app-toolbox/src/Verify.tsx b/packages/app-toolbox/src/Verify.tsx index 08f991de33..eebeba9a20 100644 --- a/packages/app-toolbox/src/Verify.tsx +++ b/packages/app-toolbox/src/Verify.tsx @@ -16,28 +16,28 @@ import translate from './translate'; type CryptoTypes = KeypairType | 'unknown'; -type CryptoOption = { - text: string, - value: string -}; +interface CryptoOption { + text: string; + value: string; +} -type State = { - currentPublicKey: Uint8Array | null, - cryptoOptions: Array, - cryptoType: CryptoTypes, - defaultPublicKey?: Uint8Array, - data: string, - isHexData: boolean, - isValidAddress: boolean, - isValidSignature: boolean, - isValid: boolean, - signature: string -}; +interface State { + currentPublicKey: Uint8Array | null; + cryptoOptions: CryptoOption[]; + cryptoType: CryptoTypes; + defaultPublicKey?: Uint8Array; + data: string; + isHexData: boolean; + isValidAddress: boolean; + isValidSignature: boolean; + isValid: boolean; + signature: string; +} class Verify extends React.PureComponent { - state: State; + public state: State; - constructor (props: Props) { + public constructor (props: Props) { super(props); const { t } = this.props; @@ -61,7 +61,7 @@ class Verify extends React.PureComponent { }; } - render () { + public render (): React.ReactNode { const { t } = this.props; const { cryptoOptions, cryptoType, data, isHexData } = this.state; diff --git a/packages/app-toolbox/src/index.tsx b/packages/app-toolbox/src/index.tsx index 2e82fcc742..15fd40a734 100644 --- a/packages/app-toolbox/src/index.tsx +++ b/packages/app-toolbox/src/index.tsx @@ -18,15 +18,15 @@ import Verify from './Verify'; import translate from './translate'; type Props = AppProps & I18nProps & { - allAccounts?: SubjectInfo + allAccounts?: SubjectInfo; }; -type State = { - tabs: Array -}; +interface State { + tabs: TabItem[]; +} class ToolboxApp extends React.PureComponent { - constructor (props: Props) { + public constructor (props: Props) { super(props); const { t } = this.props; @@ -53,7 +53,7 @@ class ToolboxApp extends React.PureComponent { ] }; } - render () { + public render (): React.ReactNode { const { allAccounts, basePath } = this.props; const { tabs } = this.state; const hasAccounts = allAccounts && Object.keys(allAccounts).length !== 0; diff --git a/packages/app-transfer/src/index.tsx b/packages/app-transfer/src/index.tsx index 6364898872..cd2853f8a9 100644 --- a/packages/app-transfer/src/index.tsx +++ b/packages/app-transfer/src/index.tsx @@ -9,7 +9,7 @@ import React from 'react'; type Props = AppProps; export default class App extends React.PureComponent { - render () { + public render (): React.ReactNode { return 'Deprecated, now operates via modal'; } } diff --git a/packages/app-treasury/src/Overview/Approve.tsx b/packages/app-treasury/src/Overview/Approve.tsx index 69115ce30b..a5c0f42631 100644 --- a/packages/app-treasury/src/Overview/Approve.tsx +++ b/packages/app-treasury/src/Overview/Approve.tsx @@ -14,18 +14,18 @@ import TxModal, { TxModalProps, TxModalState } from '@polkadot/ui-app/TxModal'; import translate from '../translate'; type Props = I18nProps & ApiProps & TxModalProps & { - isApproved?: boolean, - proposalInfo?: React.ReactNode, - proposalId: string, - threshold: number + isApproved?: boolean; + proposalInfo?: React.ReactNode; + proposalId: string; + threshold: number; }; -type State = TxModalState & { - isApproving: boolean -}; +interface State extends TxModalState { + isApproving: boolean; +} class Approve extends TxModal { - state: State = { + public state: State = { ...this.defaultState, isApproving: false }; @@ -88,7 +88,7 @@ class Approve extends TxModal { ); } - private onChangeApproving = (isApproving: boolean) => { + private onChangeApproving = (isApproving: boolean): void => { this.setState({ isApproving }); } } @@ -102,7 +102,8 @@ export default withMulti( 'query.elections.members', { propName: 'threshold', - transform: (value: Array<[AccountId, BlockNumber]>) => 1 + (value.length / 2) + transform: (value: [AccountId, BlockNumber][]): number => + 1 + (value.length / 2) } ] ) diff --git a/packages/app-treasury/src/Overview/Proposal.tsx b/packages/app-treasury/src/Overview/Proposal.tsx index b41541d722..c73c2d0c5f 100644 --- a/packages/app-treasury/src/Overview/Proposal.tsx +++ b/packages/app-treasury/src/Overview/Proposal.tsx @@ -20,21 +20,21 @@ const Approved = styled.h3` margin: 0; `; -type Props = I18nProps & { - allAccounts?: SubjectInfo, - isApproved: boolean, - proposal?: TreasuryProposalType | null, - proposalId: string, - onPopulate: () => void, - onRespond: () => void -}; +interface Props extends I18nProps { + allAccounts?: SubjectInfo; + isApproved: boolean; + proposal?: TreasuryProposalType | null; + proposalId: string; + onPopulate: () => void; + onRespond: () => void; +} -type State = { - isApproveOpen: boolean -}; +interface State { + isApproveOpen: boolean; +} class ProposalDisplay extends React.PureComponent { - constructor (props: Props) { + public constructor (props: Props) { super(props); const { proposal, onPopulate } = props; @@ -51,11 +51,11 @@ class ProposalDisplay extends React.PureComponent { } } - state: State = { + public state: State = { isApproveOpen: false }; - render () { + public render (): React.ReactNode { const { proposal, proposalId } = this.props; if (!proposal) { diff --git a/packages/app-treasury/src/Overview/Proposals.tsx b/packages/app-treasury/src/Overview/Proposals.tsx index cc08a5ce3e..7be3c56aaa 100644 --- a/packages/app-treasury/src/Overview/Proposals.tsx +++ b/packages/app-treasury/src/Overview/Proposals.tsx @@ -16,26 +16,26 @@ import Proposal from './Proposal'; import translate from '../translate'; type Props = I18nProps & RouteComponentProps & { - isApprovals?: boolean, - treasury_approvals?: Array, - treasury_proposalCount?: BN + isApprovals?: boolean; + treasury_approvals?: BN[]; + treasury_proposalCount?: BN; }; -type State = { - isEmpty: boolean, - isProposeOpen: boolean, - proposalIndices: Array -}; +interface State { + isEmpty: boolean; + isProposeOpen: boolean; + proposalIndices: BN[]; +} class ProposalsBase extends React.PureComponent { - state: State = { + public state: State = { isEmpty: true, isProposeOpen: false, - proposalIndices: [] as Array + proposalIndices: [] as BN[] }; - static getDerivedStateFromProps ({ isApprovals = false, treasury_approvals = [] as Array, treasury_proposalCount = new BN(0) }: Props) { - let proposalIndices: Array = []; + static getDerivedStateFromProps ({ isApprovals = false, treasury_approvals = [] as BN[], treasury_proposalCount = new BN(0) }: Props) { + let proposalIndices: BN[] = []; if (isApprovals) { proposalIndices = treasury_approvals; @@ -49,7 +49,7 @@ class ProposalsBase extends React.PureComponent { return { proposalIndices }; } - render () { + public render (): React.ReactNode { const { isApprovals, t } = this.props; const { isEmpty } = this.state; @@ -104,7 +104,8 @@ const Proposals = withMulti( [ 'query.treasury.approvals', { - transform: (value: Array) => value.map((proposalId) => new BN(proposalId)) + transform: (value: ProposalIndex[]): BN[] => + value.map((proposalId): BN => new BN(proposalId)) } ], 'query.treasury.proposalCount' diff --git a/packages/app-treasury/src/Overview/Propose.tsx b/packages/app-treasury/src/Overview/Propose.tsx index 268a0cb02a..f59cd99d46 100644 --- a/packages/app-treasury/src/Overview/Propose.tsx +++ b/packages/app-treasury/src/Overview/Propose.tsx @@ -12,13 +12,13 @@ import translate from '../translate'; type Props = TxModalProps; -type State = TxModalState & { - beneficiary?: string, - value: BN -}; +interface State extends TxModalState { + beneficiary?: string; + value: BN; +} class Propose extends TxModal { - state: State = { + public state: State = { ...this.defaultState, value: new BN(0) }; diff --git a/packages/app-treasury/src/Overview/Summary.tsx b/packages/app-treasury/src/Overview/Summary.tsx index 38edcfc578..b84f349128 100644 --- a/packages/app-treasury/src/Overview/Summary.tsx +++ b/packages/app-treasury/src/Overview/Summary.tsx @@ -12,15 +12,15 @@ import { formatBalance, formatNumber } from '@polkadot/util'; import translate from '../translate'; -type Props = I18nProps & { - treasury_proposalCount?: BN, - treasury_approvals?: Array, - treasury_pot?: BN -}; +interface Props extends I18nProps { + treasury_proposalCount?: BN; + treasury_approvals?: BN[]; + treasury_pot?: BN; +} class Summary extends React.PureComponent { - render () { - const { treasury_proposalCount = new BN(0), treasury_approvals = [] as Array, treasury_pot = new BN(0), t } = this.props; + public render (): React.ReactNode { + const { treasury_proposalCount = new BN(0), treasury_approvals = [] as BN[], treasury_pot = new BN(0), t } = this.props; const value = treasury_pot ? treasury_pot.toString() : null; diff --git a/packages/app-treasury/src/Overview/index.tsx b/packages/app-treasury/src/Overview/index.tsx index 26e43918c4..839fff6d08 100644 --- a/packages/app-treasury/src/Overview/index.tsx +++ b/packages/app-treasury/src/Overview/index.tsx @@ -13,16 +13,16 @@ import Propose from './Propose'; type Props = AppProps & BareProps & I18nProps; -type State = { - isProposeOpen: boolean -}; +interface State { + isProposeOpen: boolean; +} export default class Overview extends React.PureComponent { - state: State = { + public state: State = { isProposeOpen: false }; - render () { + public render (): React.ReactNode { return ( <> diff --git a/packages/app-treasury/src/Settings.tsx b/packages/app-treasury/src/Settings.tsx index 6f02cdce3b..09d831c29e 100644 --- a/packages/app-treasury/src/Settings.tsx +++ b/packages/app-treasury/src/Settings.tsx @@ -16,25 +16,25 @@ import { withCalls, withMulti } from '@polkadot/ui-api'; import translate from './translate'; type Props = I18nProps & ApiProps & RouteComponentProps & { - basePath: string, - proposalBond: Permill, - proposalBondMinimum: BalanceOf, - spendPeriod: BlockNumber, - burn: Permill, - pot: BalanceOf + basePath: string; + proposalBond: Permill; + proposalBondMinimum: BalanceOf; + spendPeriod: BlockNumber; + burn: Permill; + pot: BalanceOf; }; -type State = { - accountId?: string, - proposalBond?: BN, - proposalBondMinimum?: BN, - spendPeriod?: BN, - burn?: BN, - pot?: BN -}; +interface State { + accountId?: string; + proposalBond?: BN; + proposalBondMinimum?: BN; + spendPeriod?: BN; + burn?: BN; + pot?: BN; +} class Settings extends TxComponent { - state: State = {}; + public state: State = {}; static getDerivedStateFromProps ({ proposalBond, proposalBondMinimum, spendPeriod, burn, pot }: Props, state: State) { const newState: State = {}; @@ -62,7 +62,7 @@ class Settings extends TxComponent { return newState; } - render () { + public render (): React.ReactNode { const { t } = this.props; const { accountId, proposalBond, proposalBondMinimum, spendPeriod, burn, pot } = this.state; diff --git a/packages/app-treasury/src/index.tsx b/packages/app-treasury/src/index.tsx index 658e41b78a..c255aa9f66 100644 --- a/packages/app-treasury/src/index.tsx +++ b/packages/app-treasury/src/index.tsx @@ -17,12 +17,12 @@ import translate from './translate'; type Props = AppProps & BareProps & I18nProps; -type State = { - tabs: Array -}; +interface State { + tabs: TabItem[]; +} class App extends React.PureComponent { - constructor (props: Props) { + public constructor (props: Props) { super(props); const { t } = props; @@ -42,7 +42,7 @@ class App extends React.PureComponent { }; } - render () { + public render (): React.ReactNode { const { basePath } = this.props; const { tabs } = this.state; diff --git a/packages/apps-routing/src/types.ts b/packages/apps-routing/src/types.ts index 73f847c6d5..17e859f2a7 100644 --- a/packages/apps-routing/src/types.ts +++ b/packages/apps-routing/src/types.ts @@ -7,26 +7,26 @@ import { AppProps, BareProps } from '@polkadot/ui-app/types'; export type RouteProps = AppProps & BareProps; -export type Route = { - Component: React.ComponentType, - Modal?: React.ComponentType, +export interface Route { + Component: React.ComponentType; + Modal?: React.ComponentType; display: { - isHidden?: boolean, - isModal?: boolean, - needsAccounts?: boolean, - needsApi?: Array>, - needsSudo?: boolean - }, + isHidden?: boolean; + isModal?: boolean; + needsAccounts?: boolean; + needsApi?: (string | string[])[]; + needsSudo?: boolean; + }; i18n: { - defaultValue: string - }, - icon: SemanticICONS, - name: string -}; + defaultValue: string; + }; + icon: SemanticICONS; + name: string; +} -export type Routes = Array; +export type Routes = (Route | null)[]; -export type Routing = { - default: string, - routes: Routes -}; +export interface Routing { + default: string; + routes: Routes; +} diff --git a/packages/apps/src/Apps.tsx b/packages/apps/src/Apps.tsx index 3f97d3a556..7f2ba26b5e 100644 --- a/packages/apps/src/Apps.tsx +++ b/packages/apps/src/Apps.tsx @@ -21,19 +21,19 @@ import { SideBarTransition, SIDEBAR_TRANSITION_DURATION, SIDEBAR_MENU_THRESHOLD import Content from './Content'; import SideBar from './SideBar'; -type Props = BareProps & {}; +type Props = BareProps; -type State = { - isCollapsed: boolean, - isMenu: boolean, - menuOpen: boolean, - transition: SideBarTransition -}; +interface State { + isCollapsed: boolean; + isMenu: boolean; + menuOpen: boolean; + transition: SideBarTransition; +} class Apps extends React.Component { - state: State; + public state: State; - constructor (props: Props) { + public constructor (props: Props) { super(props); const state = store.get('sidebar') || {}; @@ -57,7 +57,7 @@ class Apps extends React.Component { this.handleMenuTransition(); } - render () { + public render (): React.ReactNode { const { className } = this.props; const { isCollapsed, isMenu, menuOpen } = this.state; diff --git a/packages/apps/src/Content/NotFound.tsx b/packages/apps/src/Content/NotFound.tsx index 5451f40c58..d1d27e1149 100644 --- a/packages/apps/src/Content/NotFound.tsx +++ b/packages/apps/src/Content/NotFound.tsx @@ -11,7 +11,7 @@ type Props = {}; const defaultTo = `/${routing.default}`; export default class NotFound extends React.PureComponent { - render () { + public render (): React.ReactNode { return ( ); diff --git a/packages/apps/src/Content/Status.tsx b/packages/apps/src/Content/Status.tsx index fe355639e8..4e0709d92a 100644 --- a/packages/apps/src/Content/Status.tsx +++ b/packages/apps/src/Content/Status.tsx @@ -1,3 +1,4 @@ +/* eslint-disable @typescript-eslint/camelcase */ // Copyright 2017-2019 @polkadot/apps authors & contributors // This software may be modified and distributed under the terms // of the Apache-2.0 license. See the LICENSE file for details. @@ -16,18 +17,18 @@ import { xxhashAsHex } from '@polkadot/util-crypto'; import translate from '../translate'; -type Props = I18nProps & { - optionsAll?: KeyringOptions, - queueAction: QueueAction$Add, - stqueue: Array, - system_events?: Array, - txqueue: Array -}; +interface Props extends I18nProps { + optionsAll?: KeyringOptions; + queueAction: QueueAction$Add; + stqueue: QueueStatus[]; + system_events?: EventRecord[]; + txqueue: QueueTx[]; +} let prevEventHash: string; class Status extends React.PureComponent { - componentDidUpdate ({ optionsAll = { account: [] as any } as KeyringOptions, queueAction, system_events, t }: Props) { + public componentDidUpdate ({ optionsAll = { account: [] as any[] } as KeyringOptions, queueAction, system_events, t }: Props): void { const eventHash = xxhashAsHex(stringToU8a(JSON.stringify(system_events || []))); if (eventHash === prevEventHash) { @@ -36,9 +37,9 @@ class Status extends React.PureComponent { prevEventHash = eventHash; - const addresses = optionsAll.account.map((account) => account.value); + const addresses = optionsAll.account.map((account): string | null => account.value); - (system_events || []).forEach(({ event: { data, method, section } }) => { + (system_events || []).forEach(({ event: { data, method, section } }): void => { if (section === 'balances' && method === 'Transfer') { const account = data[1].toString(); @@ -66,7 +67,7 @@ class Status extends React.PureComponent { }); } - render () { + public render (): React.ReactNode { const { stqueue, txqueue } = this.props; return ( diff --git a/packages/apps/src/Content/index.tsx b/packages/apps/src/Content/index.tsx index 57e14d2476..28a3587db5 100644 --- a/packages/apps/src/Content/index.tsx +++ b/packages/apps/src/Content/index.tsx @@ -51,7 +51,7 @@ const unknown = { }; class Content extends React.Component { - render () { + public render (): React.ReactNode { const { isApiConnected, isApiReady, location, t } = this.props; const app = location.pathname.slice(1) || ''; const { Component, display: { needsApi }, name } = routing.routes.find((route) => diff --git a/packages/apps/src/SideBar/Item.tsx b/packages/apps/src/SideBar/Item.tsx index fbabd0826a..71cdc22759 100644 --- a/packages/apps/src/SideBar/Item.tsx +++ b/packages/apps/src/SideBar/Item.tsx @@ -17,15 +17,15 @@ import { isFunction } from '@polkadot/util'; import translate from '../translate'; type Props = I18nProps & ApiProps & { - isCollapsed: boolean, - onClick: () => void, - allAccounts?: SubjectInfo, - route: Route, - sudo_key: string + isCollapsed: boolean; + onClick: () => void; + allAccounts?: SubjectInfo; + route: Route; + sudo_key: string; }; class Item extends React.PureComponent { - render () { + public render (): React.ReactNode { const { route: { Modal, i18n, icon, name }, t, isCollapsed, onClick } = this.props; if (!this.isVisible()) { @@ -61,18 +61,18 @@ class Item extends React.PureComponent { ) : ( - - {body} - - ) + + {body} + + ) } ); @@ -89,7 +89,7 @@ class Item extends React.PureComponent { } } - private isVisible () { + private isVisible (): boolean { const { allAccounts = {}, isApiConnected, isApiReady, route: { display: { isHidden, needsAccounts, needsApi, needsSudo }, name }, sudo_key: sudoKey } = this.props; const hasAccounts = Object.keys(allAccounts).length !== 0; const hasSudo = !!Object.keys(allAccounts).find(address => address === sudoKey); @@ -109,9 +109,9 @@ class Item extends React.PureComponent { } } - const notFound = needsApi.filter((endpoint: string | Array) => { + const notFound = needsApi.filter((endpoint: string | string[]): boolean => { const hasApi = Array.isArray(endpoint) - ? endpoint.reduce((hasApi, endpoint) => hasApi || this.hasApi(endpoint), false) + ? endpoint.reduce((hasApi, endpoint): boolean => hasApi || this.hasApi(endpoint), false) : this.hasApi(endpoint); return !hasApi; @@ -130,7 +130,10 @@ export default withMulti( translate, withApi, withCalls( - ['query.sudo.key', { transform: key => key.toString() }] + ['query.sudo.key', { + transform: (key): string => + key.toString() + }] ), withObservable(accountObservable.subject, { propName: 'allAccounts' }) ); diff --git a/packages/apps/src/SideBar/NodeInfo.tsx b/packages/apps/src/SideBar/NodeInfo.tsx index 1e98fdaff7..d535908248 100644 --- a/packages/apps/src/SideBar/NodeInfo.tsx +++ b/packages/apps/src/SideBar/NodeInfo.tsx @@ -39,7 +39,7 @@ const Wrapper = styled.div` const pkgJson = require('../../package.json'); class NodeInfo extends React.PureComponent { - render () { + public render (): React.ReactNode { const { api } = this.props; const uiInfo = `apps v${pkgJson.version}`; diff --git a/packages/apps/src/SideBar/index.tsx b/packages/apps/src/SideBar/index.tsx index 7e2635a22a..425ffab096 100644 --- a/packages/apps/src/SideBar/index.tsx +++ b/packages/apps/src/SideBar/index.tsx @@ -21,19 +21,17 @@ import Item from './Item'; import NodeInfo from './NodeInfo'; import getLogo from './logos'; -type Props = I18nProps & { - collapse: () => void, - handleResize: () => void, - isCollapsed: boolean, - menuOpen: boolean, - toggleMenu: () => void -}; +interface Props extends I18nProps { + collapse: () => void; + handleResize: () => void; + isCollapsed: boolean; + menuOpen: boolean; + toggleMenu: () => void; +} -type State = { - modals: { - [index: string]: boolean - } -}; +interface State { + modals: Record; +} const Toggle = styled.img` background: ${logoBackground}; @@ -62,24 +60,24 @@ const Toggle = styled.img` `; class SideBar extends React.PureComponent { - state: State; + public state: State; - constructor (props: Props) { + public constructor (props: Props) { super(props); // setup modals for each of the actual modal routes this.state = { - modals: routing.routes.reduce((result, route) => { + modals: routing.routes.reduce((result, route): Record => { if (route && route.Modal) { result[route.name] = false; } return result; - }, {} as { [index: string]: boolean }) + }, {} as unknown as Record) }; } - render () { + public render (): React.ReactNode { const { handleResize, isCollapsed, toggleMenu, menuOpen } = this.props; const logo = getLogo(true); @@ -126,7 +124,7 @@ class SideBar extends React.PureComponent { ); } - private renderCollapse () { + private renderCollapse (): React.ReactNode { const { isCollapsed } = this.props; return ( @@ -144,7 +142,7 @@ class SideBar extends React.PureComponent { ); } - private renderLogo () { + private renderLogo (): React.ReactNode { const { isCollapsed } = this.props; const logo = getLogo(isCollapsed); @@ -157,11 +155,11 @@ class SideBar extends React.PureComponent { ); } - private renderModals () { + private renderModals (): React.ReactNode { const { modals } = this.state; - const filtered = routing.routes.filter((route) => route && route.Modal) as Array; + const filtered = routing.routes.filter((route): any => route && route.Modal) as Route[]; - return filtered.map(({ name, Modal }) => ( + return filtered.map(({ name, Modal }): React.ReactNode => ( Modal && modals[name] ? ( { )); } - private renderRoutes () { + private renderRoutes (): React.ReactNode { const { handleResize, isCollapsed } = this.props; - return routing.routes.map((route, index) => ( + return routing.routes.map((route, index): React.ReactNode => ( route ? ( { )); } - private renderGithub () { + private renderGithub (): React.ReactNode { return ( GitHub @@ -213,12 +212,13 @@ class SideBar extends React.PureComponent { ); } - private renderWiki () { + private renderWiki (): React.ReactNode { return ( Wiki @@ -227,9 +227,9 @@ class SideBar extends React.PureComponent { ); } - private closeModal = (name: string) => { - return () => { - this.setState(({ modals }) => ({ + private closeModal = (name: string): () => void => { + return (): void => { + this.setState(({ modals }): State => ({ modals: { ...modals, [name]: false @@ -238,9 +238,9 @@ class SideBar extends React.PureComponent { }; } - private openModal = (name: string) => { - return () => { - this.setState(({ modals }) => ({ + private openModal = (name: string): () => void => { + return (): void => { + this.setState(({ modals }): State => ({ modals: { ...modals, [name]: true diff --git a/packages/apps/src/TopBar.tsx b/packages/apps/src/TopBar.tsx index ff78bd5056..b289f5fbf3 100644 --- a/packages/apps/src/TopBar.tsx +++ b/packages/apps/src/TopBar.tsx @@ -13,7 +13,7 @@ type Props = { }; class TopBar extends React.PureComponent { - render () { + public render (): React.ReactNode { const { className } = this.props; return ( diff --git a/packages/apps/src/overlays/Accounts.tsx b/packages/apps/src/overlays/Accounts.tsx index 8b51db99e9..d844764346 100644 --- a/packages/apps/src/overlays/Accounts.tsx +++ b/packages/apps/src/overlays/Accounts.tsx @@ -17,16 +17,16 @@ import translate from '../translate'; import BaseOverlay from './Base'; type Props = I18nProps & ApiProps & { - allAccounts?: SubjectInfo + allAccounts?: SubjectInfo; }; -type State = { - hasAccounts: boolean, - isHidden: boolean -}; +interface State { + hasAccounts: boolean; + isHidden: boolean; +} class Accounts extends React.PureComponent { - state: State = { + public state: State = { hasAccounts: false, isHidden: false }; @@ -47,7 +47,7 @@ class Accounts extends React.PureComponent { } as State; } - render () { + public render (): React.ReactNode { const { isApiReady, className, t } = this.props; const { hasAccounts, isHidden } = this.state; diff --git a/packages/apps/src/overlays/Base.tsx b/packages/apps/src/overlays/Base.tsx index df4abac3a3..bc61ca5aa7 100644 --- a/packages/apps/src/overlays/Base.tsx +++ b/packages/apps/src/overlays/Base.tsx @@ -6,22 +6,22 @@ import React from 'react'; import styled from 'styled-components'; import { Icon } from '@polkadot/ui-app'; -type Props = { - children: React.ReactNode, - className?: string, - icon: string -}; +interface Props { + children: React.ReactNode; + className?: string; + icon: string; +} -type State = { - isHidden: boolean -}; +interface State { + isHidden: boolean; +} class BaseOverlay extends React.PureComponent { - state: State = { + public state: State = { isHidden: false }; - render () { + public render (): React.ReactNode { const { children, className, icon } = this.props; const { isHidden } = this.state; @@ -50,7 +50,7 @@ class BaseOverlay extends React.PureComponent { ); } - private onClose = () => { + private onClose = (): void => { this.setState({ isHidden: true }); } } diff --git a/packages/apps/src/overlays/Connecting.tsx b/packages/apps/src/overlays/Connecting.tsx index ac43113e60..6f1671bb2f 100644 --- a/packages/apps/src/overlays/Connecting.tsx +++ b/packages/apps/src/overlays/Connecting.tsx @@ -18,7 +18,7 @@ type Props = I18nProps & ApiProps; const isFirefox = typeof InstallTrigger !== 'undefined'; class Connecting extends React.PureComponent { - render () { + public render (): React.ReactNode { return this.renderExtension() || this.renderConnecting(); } diff --git a/packages/ui-api/src/Api.tsx b/packages/ui-api/src/Api.tsx index 3a69723929..fa3bdc09d9 100644 --- a/packages/ui-api/src/Api.tsx +++ b/packages/ui-api/src/Api.tsx @@ -3,7 +3,7 @@ // of the Apache-2.0 license. See the LICENSE file for details. import { ProviderInterface } from '@polkadot/rpc-provider/types'; -import { QueueTx$ExtrinsicAdd, QueueTx$MessageSetStatus } from '@polkadot/ui-app/Status/types'; +import { QueueTxExtrinsicAdd, QueueTxMessageSetStatus } from '@polkadot/ui-app/Status/types'; import { ApiProps } from './types'; import React from 'react'; @@ -21,25 +21,25 @@ import ApiContext from './ApiContext'; let api: ApiPromise; -type Props = { - children: React.ReactNode, - queueExtrinsic: QueueTx$ExtrinsicAdd, - queueSetTxStatus: QueueTx$MessageSetStatus, - url?: string -}; +interface Props { + children: React.ReactNode; + queueExtrinsic: QueueTxExtrinsicAdd; + queueSetTxStatus: QueueTxMessageSetStatus; + url?: string; +} -type State = ApiProps & { - chain?: string | null -}; +interface State extends ApiProps { + chain?: string | null; +} export { api }; const injectedPromise = web3Enable('polkadot-js/apps'); export default class Api extends React.PureComponent { - state: State = {} as State; + public state: State = {} as unknown as State; - constructor (props: Props) { + public constructor (props: Props) { super(props); const { queueExtrinsic, queueSetTxStatus, url } = props; @@ -49,7 +49,7 @@ export default class Api extends React.PureComponent { const setApi = (provider: ProviderInterface): void => { api = new ApiPromise({ provider, signer }); - this.setState({ api }, () => { + this.setState({ api }, (): void => { this.subscribeEvents(); }); }; @@ -65,29 +65,29 @@ export default class Api extends React.PureComponent { isSubstrateV2: true, isWaitingInjected: isWeb3Injected, setApiUrl - } as State; + } as unknown as State; } - componentDidMount () { + public componentDidMount (): void { this.subscribeEvents(); injectedPromise - .then(() => this.setState({ isWaitingInjected: false })) + .then((): void => this.setState({ isWaitingInjected: false })) .catch(console.error); } - private subscribeEvents () { + private subscribeEvents (): void { const { api } = this.state; - api.on('connected', () => { + api.on('connected', (): void => { this.setState({ isApiConnected: true }); }); - api.on('disconnected', () => { + api.on('disconnected', (): void => { this.setState({ isApiConnected: false }); }); - api.on('ready', async () => { + api.on('ready', async (): Promise => { try { await this.loadOnReady(api); } catch (error) { @@ -96,7 +96,7 @@ export default class Api extends React.PureComponent { }); } - private async loadOnReady (api: ApiPromise) { + private async loadOnReady (api: ApiPromise): Promise { const [properties = new ChainProperties(), value] = await Promise.all([ api.rpc.system.properties(), api.rpc.system.chain() @@ -151,7 +151,7 @@ export default class Api extends React.PureComponent { }); } - render () { + public render (): React.ReactNode { const { api, apiDefaultTx, apiDefaultTxSudo, chain, isApiConnected, isApiReady, isDevelopment, isSubstrateV2, isWaitingInjected, setApiUrl } = this.state; return ( diff --git a/packages/ui-api/src/types.ts b/packages/ui-api/src/types.ts index 688c5b07bf..a392f482cc 100644 --- a/packages/ui-api/src/types.ts +++ b/packages/ui-api/src/types.ts @@ -10,44 +10,47 @@ import ApiPromise from '@polkadot/api/promise'; export type OmitProps = Pick>; export type SubtractProps = OmitProps; -export type BareProps = { - className?: string, - style?: { [index: string]: any } -}; +export interface BareProps { + className?: string; + style?: Record; +} -export type ApiProps = { - api: ApiPromise, - apiDefaultTx: SubmittableExtrinsicFunction, - apiDefaultTxSudo: SubmittableExtrinsicFunction, - currentChain: string, - isApiConnected: boolean, - isApiReady: boolean, - isDevelopment: boolean, - isSubstrateV2: boolean, - isWaitingInjected: boolean, - setApiUrl: (url?: string) => void -}; +export interface ApiProps { + api: ApiPromise; + apiDefaultTx: SubmittableExtrinsicFunction; + apiDefaultTxSudo: SubmittableExtrinsicFunction; + currentChain: string; + isApiConnected: boolean; + isApiReady: boolean; + isDevelopment: boolean; + isSubstrateV2: boolean; + isWaitingInjected: boolean; + setApiUrl: (url?: string) => void; +} -export type OnChangeCb$Obs = { next: (value?: any) => any }; -export type OnChangeCb$Fn = (value?: any) => any; -export type OnChangeCb = OnChangeCb$Obs | OnChangeCb$Fn; +export interface OnChangeCbObs { + next: (value?: any) => any; +} -export type ChangeProps = { - callOnResult?: OnChangeCb -}; +export type OnChangeCbFn = (value?: any) => any; +export type OnChangeCb = OnChangeCbObs | OnChangeCbFn; -export type CallState = { +export interface ChangeProps { + callOnResult?: OnChangeCb; +} + +export interface CallState { callResult?: any; callUpdated?: boolean; callUpdatedAt?: number; -}; +} export type CallProps = ApiProps & CallState; export type BaseProps = BareProps & CallProps & ChangeProps & { - children?: React.ReactNode, - label?: string, - render?: (value?: T) => React.ReactNode + children?: React.ReactNode; + label?: string; + render?: (value?: T) => React.ReactNode; }; export type Formatter = (value?: any) => string; diff --git a/packages/ui-api/src/util/triggerChange.ts b/packages/ui-api/src/util/triggerChange.ts index 9bcc73f4a3..4022d176a3 100644 --- a/packages/ui-api/src/util/triggerChange.ts +++ b/packages/ui-api/src/util/triggerChange.ts @@ -6,7 +6,7 @@ import { OnChangeCb } from '../types'; import { isFunction, isObservable } from '@polkadot/util'; -export default function triggerChange (value?: any, ...callOnResult: Array): void { +export default function triggerChange (value?: any, ...callOnResult: (OnChangeCb | undefined)[]): void { if (!callOnResult || !callOnResult.length) { return; } diff --git a/packages/ui-api/src/with/api.tsx b/packages/ui-api/src/with/api.tsx index 771aebe468..535ac7b218 100644 --- a/packages/ui-api/src/with/api.tsx +++ b/packages/ui-api/src/with/api.tsx @@ -14,7 +14,7 @@ export default function withApi

(Inner: React.ComponentType return class WithApi extends React.PureComponent> { component: any = React.createRef(); - render () { + public render (): React.ReactNode { return ( {(apiProps?: ApiProps) => { diff --git a/packages/ui-api/src/with/call.tsx b/packages/ui-api/src/with/call.tsx index 901c5f909e..976b9fdd5b 100644 --- a/packages/ui-api/src/with/call.tsx +++ b/packages/ui-api/src/with/call.tsx @@ -13,33 +13,37 @@ import echoTransform from '../transform/echo'; import withApi from './api'; interface Method { - (...params: Array): Promise; - at: (hash: Uint8Array | string, ...params: Array) => Promise; - multi: (params: Array, cb: (value?: any) => void) => Promise; + (...params: any[]): Promise; + at: (hash: Uint8Array | string, ...params: any[]) => Promise; + multi: (params: any[], cb: (value?: any) => void) => Promise; } -type ApiMethodInfo = [Method, Array, boolean]; +type ApiMethodInfo = [Method, any[], boolean]; type State = CallState; -const NOOP = () => { +const NOOP = (): void => { // ignore }; export default function withCall

(endpoint: string, { at, atProp, callOnResult, isMulti = false, params = [], paramName, paramPick, paramValid = false, propName, transform = echoTransform }: Options = {}): (Inner: React.ComponentType) => React.ComponentType { return (Inner: React.ComponentType): React.ComponentType> => { class WithPromise extends React.Component { - state: State = { + public state: State = { callResult: void 0, callUpdated: false, callUpdatedAt: 0 }; + private destroy?: () => void; + private isActive: boolean = false; + private propName: string; + private timerId: number = -1; - constructor (props: P) { + public constructor (props: P) { super(props); const [, section, method] = endpoint.split('.'); @@ -47,7 +51,7 @@ export default function withCall

(endpoint: string, { at, at this.propName = `${section}_${method}`; } - componentDidUpdate (prevProps: any) { + public componentDidUpdate (prevProps: any): void { const oldParams = this.getParams(prevProps); const newParams = this.getParams(this.props); @@ -59,9 +63,9 @@ export default function withCall

(endpoint: string, { at, at } } - componentDidMount () { + public componentDidMount (): void { this.isActive = true; - this.timerId = window.setInterval(() => { + this.timerId = window.setInterval((): void => { const elapsed = Date.now() - (this.state.callUpdatedAt || 0); const callUpdated = elapsed <= 1500; @@ -76,7 +80,7 @@ export default function withCall

(endpoint: string, { at, at .catch(NOOP); } - componentWillUnmount () { + public componentWillUnmount (): void { this.isActive = false; this.unsubscribe() @@ -88,13 +92,13 @@ export default function withCall

(endpoint: string, { at, at } } - private nextState (state: Partial) { + private nextState (state: Partial): void { if (this.isActive) { this.setState(state as State); } } - private getParams (props: any): [boolean, Array] { + private getParams (props: any): [boolean, any[]] { const paramValue = paramPick ? paramPick(props) : paramName @@ -122,7 +126,7 @@ export default function withCall

(endpoint: string, { at, at return [true, values]; } - private getApiMethod (newParams: Array): ApiMethodInfo { + private getApiMethod (newParams: any[]): ApiMethodInfo { const { api } = this.props; if (endpoint === 'subscribe') { @@ -160,7 +164,7 @@ export default function withCall

(endpoint: string, { at, at ]; } - private async subscribe ([isValid, newParams]: [boolean, Array]) { + private async subscribe ([isValid, newParams]: [boolean, any[]]): Promise { if (!isValid) { return; } @@ -183,7 +187,7 @@ export default function withCall

(endpoint: string, { at, at } const [apiMethod, params, isSubscription] = info; - const updateCb = (value?: any) => + const updateCb = (value?: any): void => this.triggerUpdate(this.props, value); await this.unsubscribe(); @@ -205,7 +209,7 @@ export default function withCall

(endpoint: string, { at, at } } - private async unsubscribe () { + private async unsubscribe (): Promise { if (this.destroy) { this.destroy(); this.destroy = undefined; @@ -232,7 +236,7 @@ export default function withCall

(endpoint: string, { at, at } } - render () { + public render (): React.ReactNode { const { callUpdated, callUpdatedAt, callResult } = this.state; const _props = { ...this.props, diff --git a/packages/ui-api/src/with/callDiv.tsx b/packages/ui-api/src/with/callDiv.tsx index 17f42d37d8..862e7eae5b 100644 --- a/packages/ui-api/src/with/callDiv.tsx +++ b/packages/ui-api/src/with/callDiv.tsx @@ -16,7 +16,7 @@ type Props = BaseProps & { export default function withCallDiv (endpoint: string, options: Options = {}) { return (render: (value?: T) => React.ReactNode, defaultProps: DefaultProps = {}): React.ComponentType => { class Inner extends React.PureComponent> { - render () { + public render (): React.ReactNode { const { callResult, callUpdated, children, className = defaultProps.className, label = '', style } = this.props; return ( diff --git a/packages/ui-api/src/with/calls.ts b/packages/ui-api/src/with/calls.ts index e1cad8757e..d325d69226 100644 --- a/packages/ui-api/src/with/calls.ts +++ b/packages/ui-api/src/with/calls.ts @@ -10,13 +10,13 @@ import withCall from './call'; type Call = string | [string, Options]; -export default function withCalls

(...calls: Array): (Component: React.ComponentType

) => React.ComponentType> { +export default function withCalls

(...calls: Call[]): (Component: React.ComponentType

) => React.ComponentType> { return (Component: React.ComponentType

): React.ComponentType => { // NOTE: Order is reversed so it makes sense in the props, i.e. component // after something can use the value of the preceding version return calls .reverse() - .reduce((Component, call) => { + .reduce((Component, call): React.ComponentType => { return Array.isArray(call) ? withCall(...call)(Component as any) : withCall(call)(Component as any); diff --git a/packages/ui-api/src/with/multi.ts b/packages/ui-api/src/with/multi.ts index 9497f6371c..fa6364729f 100644 --- a/packages/ui-api/src/with/multi.ts +++ b/packages/ui-api/src/with/multi.ts @@ -6,12 +6,12 @@ import React from 'react'; type HOC = (Component: React.ComponentType) => React.ComponentType; -export default function withMulti (Component: React.ComponentType, ...hocs: Array): React.ComponentType { +export default function withMulti (Component: React.ComponentType, ...hocs: HOC[]): React.ComponentType { // NOTE: Order is reversed so it makes sense in the props, i.e. component // after something can use the value of the preceding version return hocs .reverse() - .reduce((Component, hoc) => { + .reduce((Component, hoc): React.ComponentType => { return hoc(Component); }, Component); } diff --git a/packages/ui-api/src/with/observable.tsx b/packages/ui-api/src/with/observable.tsx index b94571880e..0189203c31 100644 --- a/packages/ui-api/src/with/observable.tsx +++ b/packages/ui-api/src/with/observable.tsx @@ -14,16 +14,16 @@ import { catchError, map } from 'rxjs/operators'; import echoTransform from '../transform/echo'; import { intervalObservable, isEqual, triggerChange } from '../util'; -type State = CallState & { - subscriptions: Array; // FIXME subscriptions -}; +interface State extends CallState { + subscriptions: any[]; // FIXME subscriptions +} // FIXME proper types for attributes export default function withObservable (observable: Observable

, { callOnResult, propName = 'value', transform = echoTransform }: Options = {}): HOC { return (Inner: React.ComponentType, defaultProps: DefaultProps = {}, render?: RenderFn): React.ComponentType => { return class WithObservable extends React.Component { - state: State = { + public state: State = { callResult: void 0, callUpdated: false, callUpdatedAt: 0, @@ -72,7 +72,7 @@ export default function withObservable (observable: Observable

, { callO } } - render () { + public render (): React.ReactNode { const { children } = this.props; const { callUpdated, callUpdatedAt, callResult } = this.state; const _props = { diff --git a/packages/ui-api/src/with/types.ts b/packages/ui-api/src/with/types.ts index c58a363018..dacf6e946d 100644 --- a/packages/ui-api/src/with/types.ts +++ b/packages/ui-api/src/with/types.ts @@ -18,7 +18,7 @@ export type Options = { atProp?: string, callOnResult?: OnChangeCb, isMulti?: boolean, - params?: Array, + params?: any[], paramName?: string, paramPick?: (props: any) => any, paramValid?: boolean, diff --git a/packages/ui-app/src/ActionItem.tsx b/packages/ui-app/src/ActionItem.tsx index f1a0a43cff..1d1b50668f 100644 --- a/packages/ui-app/src/ActionItem.tsx +++ b/packages/ui-app/src/ActionItem.tsx @@ -29,7 +29,7 @@ export const styles = ` `; class ActionItem extends React.PureComponent { - render () { + public render (): React.ReactNode { const { className, children, accessory } = this.props; return ( diff --git a/packages/ui-app/src/AddressCard.tsx b/packages/ui-app/src/AddressCard.tsx index b7c06b3194..caab8290c2 100644 --- a/packages/ui-app/src/AddressCard.tsx +++ b/packages/ui-app/src/AddressCard.tsx @@ -19,7 +19,7 @@ type Props = AddressProps & { }; class AddressCard extends React.PureComponent { - render () { + public render (): React.ReactNode { const { className, value, withExplorer } = this.props; return ( diff --git a/packages/ui-app/src/AddressInfo.tsx b/packages/ui-app/src/AddressInfo.tsx index c67f9c665a..8f6f511bd7 100644 --- a/packages/ui-app/src/AddressInfo.tsx +++ b/packages/ui-app/src/AddressInfo.tsx @@ -19,7 +19,7 @@ import translate from './translate'; // true to display, or (for bonded) provided values [own, ...all extras] export type BalanceActiveType = { available?: boolean, - bonded?: boolean | Array, + bonded?: boolean | BN[], free?: boolean, redeemable?: boolean, unlocking?: boolean @@ -47,7 +47,7 @@ type Props = BareProps & I18nProps & { }; class AddressInfo extends React.PureComponent { - render () { + public render (): React.ReactNode { const { children, className } = this.props; return ( @@ -117,7 +117,7 @@ class AddressInfo extends React.PureComponent { } // either true (filtered above already) or [own, ...all extras bonded funds from nominators] - private renderBonded (bonded: true | Array) { + private renderBonded (bonded: true | BN[]) { const { staking_info, t } = this.props; let value = undefined; diff --git a/packages/ui-app/src/AddressMini.tsx b/packages/ui-app/src/AddressMini.tsx index ddeee85817..7fef2512a7 100644 --- a/packages/ui-app/src/AddressMini.tsx +++ b/packages/ui-app/src/AddressMini.tsx @@ -16,8 +16,8 @@ import BondedDisplay from './Bonded'; import IdentityIcon from './IdentityIcon'; type Props = BareProps & { - balance?: BN | Array, - bonded?: BN | Array, + balance?: BN | BN[], + bonded?: BN | BN[], children?: React.ReactNode, iconInfo?: React.ReactNode, isPadded?: boolean, @@ -30,7 +30,7 @@ type Props = BareProps & { }; class AddressMini extends React.PureComponent { - render () { + public render (): React.ReactNode { const { children, className, iconInfo, isPadded = true, style, value } = this.props; if (!value) { diff --git a/packages/ui-app/src/AddressRow.tsx b/packages/ui-app/src/AddressRow.tsx index 3de48b9d26..442eaccdee 100644 --- a/packages/ui-app/src/AddressRow.tsx +++ b/packages/ui-app/src/AddressRow.tsx @@ -20,14 +20,14 @@ import Row, { RowProps, RowState, styles } from './Row'; import translate from './translate'; export type Props = I18nProps & RowProps & { - bonded?: BN | Array, - isContract?: boolean, - isValid?: boolean, - label?: string, - value: AccountId | AccountIndex | Address | string | null, - withAddressOrName?: boolean, - withBalance?: boolean | BalanceActiveType, - withIndex?: boolean + bonded?: BN | BN[]; + isContract?: boolean; + isValid?: boolean; + label?: string; + value: AccountId | AccountIndex | Address | string | null; + withAddressOrName?: boolean; + withBalance?: boolean | BalanceActiveType; + withIndex?: boolean; }; type State = RowState; @@ -36,9 +36,9 @@ const DEFAULT_ADDR = '5'.padEnd(16, 'x'); const ICON_SIZE = 48; class AddressRow extends Row { - state: State; + public state: State; - constructor (props: Props) { + public constructor (props: Props) { super(props); this.state = this.createState(); @@ -70,7 +70,7 @@ class AddressRow extends Row { : null; } - render () { + public render (): React.ReactNode { const { accounts_idAndIndex = [], className, isContract, isInline, style } = this.props; const [accountId, accountIndex] = accounts_idAndIndex; const isValid = this.props.isValid || accountId || accountIndex; diff --git a/packages/ui-app/src/Available.tsx b/packages/ui-app/src/Available.tsx index 39679b46ea..55d9bb44b4 100644 --- a/packages/ui-app/src/Available.tsx +++ b/packages/ui-app/src/Available.tsx @@ -16,7 +16,7 @@ export type Props = BareProps & { }; export default class AvailableDisplay extends React.PureComponent { - render () { + public render (): React.ReactNode { const { params, className, label, style } = this.props; if (!params) { diff --git a/packages/ui-app/src/Balance.tsx b/packages/ui-app/src/Balance.tsx index 37d28ddc00..fac909d9c3 100644 --- a/packages/ui-app/src/Balance.tsx +++ b/packages/ui-app/src/Balance.tsx @@ -13,14 +13,14 @@ import { Balance } from '@polkadot/ui-reactive'; import { classes } from './util'; export type Props = BareProps & { - balance?: BN | Array, + balance?: BN | BN[], label?: React.ReactNode, params?: AccountId | AccountIndex | Address | string | Uint8Array | null, withLabel?: boolean }; export default class BalanceDisplay extends React.PureComponent { - render () { + public render (): React.ReactNode { const { balance, className, label, params, style } = this.props; if (!params) { diff --git a/packages/ui-app/src/Bonded.tsx b/packages/ui-app/src/Bonded.tsx index f47e0139e5..63cb45a4cc 100644 --- a/packages/ui-app/src/Bonded.tsx +++ b/packages/ui-app/src/Bonded.tsx @@ -13,14 +13,14 @@ import { Bonded } from '@polkadot/ui-reactive'; import { classes } from './util'; export type Props = BareProps & { - bonded?: BN | Array, + bonded?: BN | BN[], label?: React.ReactNode, params?: AccountId | AccountIndex | Address | string | Uint8Array | null, withLabel?: boolean }; export default class BondedDisplay extends React.PureComponent { - render () { + public render (): React.ReactNode { const { bonded, params, className, label, style } = this.props; if (!params) { diff --git a/packages/ui-app/src/Bubble.tsx b/packages/ui-app/src/Bubble.tsx index 903cd5dd59..a1e7688292 100644 --- a/packages/ui-app/src/Bubble.tsx +++ b/packages/ui-app/src/Bubble.tsx @@ -21,7 +21,7 @@ type Props = BareProps & { }; class Bubble extends React.PureComponent { - render () { + public render (): React.ReactNode { const { color, children, className, icon, label } = this.props; return ( diff --git a/packages/ui-app/src/Button/Button.tsx b/packages/ui-app/src/Button/Button.tsx index 942f6d0d0e..6b2edb96d0 100644 --- a/packages/ui-app/src/Button/Button.tsx +++ b/packages/ui-app/src/Button/Button.tsx @@ -16,7 +16,7 @@ let idCounter = 0; export default class Button extends React.PureComponent { private id: string = `button-${++idCounter}`; - render () { + public render (): React.ReactNode { const { children, className, floated, icon, isBasic = false, isCircular = false, isDisabled = false, isLoading = false, isNegative = false, isPositive = false, isPrimary = false, label, labelIcon, labelPosition, onClick, size, style, tabIndex, tooltip } = this.props; const props = { @@ -68,12 +68,4 @@ export default class Button extends React.PureComponent { ); } - - click = () => { - const { onClick } = this.props; - - if (onClick) { - onClick(); - } - } } diff --git a/packages/ui-app/src/Button/Divider.tsx b/packages/ui-app/src/Button/Divider.tsx index 3283cb5cad..fb9ed5fff7 100644 --- a/packages/ui-app/src/Button/Divider.tsx +++ b/packages/ui-app/src/Button/Divider.tsx @@ -9,7 +9,7 @@ import React from 'react'; import { classes } from '../util'; export default class ButtonDivider extends React.Component { - render () { + public render (): React.ReactNode { const { className, style } = this.props; return ( diff --git a/packages/ui-app/src/Button/Group.tsx b/packages/ui-app/src/Button/Group.tsx index 335f3d2bb7..fd9490bd31 100644 --- a/packages/ui-app/src/Button/Group.tsx +++ b/packages/ui-app/src/Button/Group.tsx @@ -12,7 +12,7 @@ import { classes } from '../util'; import Divider from './Divider'; class ButtonGroup extends React.PureComponent { - render () { + public render (): React.ReactNode { const { children, className, isBasic = false, isCentered = false, style } = this.props; return ( @@ -46,4 +46,4 @@ export default styled(ButtonGroup)` margin-bottom: 0.5rem; text-align: center; } -` as any as GroupType; +` as unknown as GroupType; diff --git a/packages/ui-app/src/Button/Or.tsx b/packages/ui-app/src/Button/Or.tsx index d21e15f3fb..2523d6ddcd 100644 --- a/packages/ui-app/src/Button/Or.tsx +++ b/packages/ui-app/src/Button/Or.tsx @@ -10,12 +10,12 @@ import { isUndefined } from '@polkadot/util'; import translate from '../translate'; -type Props = I18nProps & { - text?: string -}; +interface Props extends I18nProps { + text?: string; +} class ButtonOr extends React.PureComponent { - render () { + public render (): React.ReactNode { const { className, style, t, text } = this.props; return ( diff --git a/packages/ui-app/src/Button/index.tsx b/packages/ui-app/src/Button/index.tsx index 2f13fef454..cec4a348dd 100644 --- a/packages/ui-app/src/Button/index.tsx +++ b/packages/ui-app/src/Button/index.tsx @@ -11,7 +11,7 @@ import Divider from './Divider'; import Group from './Group'; import Or from './Or'; -const Button = IButton as any as ButtonType; +const Button = IButton as unknown as ButtonType; Button.Divider = Divider; Button.Group = Group; diff --git a/packages/ui-app/src/Button/types.ts b/packages/ui-app/src/Button/types.ts index a378514dab..30aa620453 100644 --- a/packages/ui-app/src/Button/types.ts +++ b/packages/ui-app/src/Button/types.ts @@ -6,41 +6,41 @@ import { BareProps } from '../types'; export type Button$Sizes = 'mini' | 'tiny' | 'small' | 'medium' | 'large' | 'big' | 'huge' | 'massive'; -export type ButtonProps = BareProps & { - children?: React.ReactNode, - floated?: 'left' | 'right', - icon?: string, - isBasic?: boolean, - isCircular?: boolean, - isDisabled?: boolean, - isLoading?: boolean, - isNegative?: boolean, - isPositive?: boolean, - isPrimary?: boolean, - label?: React.ReactNode, - labelIcon?: string, - labelPosition?: 'left' | 'right', - onClick?: () => void | Promise, - ref?: any, - size?: Button$Sizes, - tabIndex?: number, - tooltip?: React.ReactNode -}; +export interface ButtonProps extends BareProps { + children?: React.ReactNode; + floated?: 'left' | 'right'; + icon?: string; + isBasic?: boolean; + isCircular?: boolean; + isDisabled?: boolean; + isLoading?: boolean; + isNegative?: boolean; + isPositive?: boolean; + isPrimary?: boolean; + label?: React.ReactNode; + labelIcon?: string; + labelPosition?: 'left' | 'right'; + onClick?: () => void | Promise; + ref?: any; + size?: Button$Sizes; + tabIndex?: number; + tooltip?: React.ReactNode; +} export type DividerProps = BareProps; -export type GroupProps = BareProps & { - children?: React.ReactNode, - isBasic?: boolean, - isCentered?: boolean -}; +export interface GroupProps extends BareProps { + children?: React.ReactNode; + isBasic?: boolean; + isCentered?: boolean; +} export type GroupType = React.ComponentType & { - Divider: React.ComponentType + Divider: React.ComponentType; }; export type ButtonType = React.ComponentType & { - Divider: React.ComponentType, - Group: GroupType, - Or: React.ComponentType + Divider: React.ComponentType; + Group: GroupType; + Or: React.ComponentType; }; diff --git a/packages/ui-app/src/Call.tsx b/packages/ui-app/src/Call.tsx index d0d6f42762..731a92e504 100644 --- a/packages/ui-app/src/Call.tsx +++ b/packages/ui-app/src/Call.tsx @@ -31,7 +31,7 @@ const Wrapper = styled.div` `; class Call extends React.PureComponent { - render () { + public render (): React.ReactNode { const { children, className, style, mortality, value, withHash, t } = this.props; const params = Method.filterOrigin(value.meta).map(({ name, type }) => ({ name: name.toString(), diff --git a/packages/ui-app/src/Card.tsx b/packages/ui-app/src/Card.tsx index f72efb9760..0e0dd6b189 100644 --- a/packages/ui-app/src/Card.tsx +++ b/packages/ui-app/src/Card.tsx @@ -11,7 +11,7 @@ type Props = { }; class Card extends React.PureComponent { - render () { + public render (): React.ReactNode { const { children, className } = this.props; return ( diff --git a/packages/ui-app/src/CardGrid.tsx b/packages/ui-app/src/CardGrid.tsx index 2cd00b082b..ca79104c8c 100644 --- a/packages/ui-app/src/CardGrid.tsx +++ b/packages/ui-app/src/CardGrid.tsx @@ -15,7 +15,7 @@ type State = CollectionState; class CardGrid extends Collection { static getDerivedStateFromProps ({ children, headerText }: Props) { - if (!children || (children as Array).length <= 0) { + if (!children || (children as any[]).length <= 0) { return { isEmpty: true, showHeader: !!headerText }; } return { isEmpty: false, showHeader: true }; diff --git a/packages/ui-app/src/CardSummary.tsx b/packages/ui-app/src/CardSummary.tsx index 48f12dd2b0..4a7d11084c 100644 --- a/packages/ui-app/src/CardSummary.tsx +++ b/packages/ui-app/src/CardSummary.tsx @@ -29,7 +29,7 @@ type Props = BareProps & { }; class CardSummary extends React.PureComponent { - render () { + public render (): React.ReactNode { const { children, className, help, label, progress } = this.props; const value = progress && progress.value; const total = progress && progress.total; diff --git a/packages/ui-app/src/Chart/Base.tsx b/packages/ui-app/src/Chart/Base.tsx index 00e07b4ce8..44b0b6dafa 100644 --- a/packages/ui-app/src/Chart/Base.tsx +++ b/packages/ui-app/src/Chart/Base.tsx @@ -9,9 +9,9 @@ import styled from 'styled-components'; import { classes } from '../util'; -type Props = BareProps & { - children: React.ReactNode -}; +interface Props extends BareProps { + children: React.ReactNode; +} const Wrapper = styled.div` position: relative; @@ -22,7 +22,7 @@ const Wrapper = styled.div` `; export default class BaseChart extends React.PureComponent { - render () { + public render (): React.ReactNode { const { children, className, style } = this.props; return ( diff --git a/packages/ui-app/src/Chart/Doughnut.tsx b/packages/ui-app/src/Chart/Doughnut.tsx index 1ebdb01910..4bf0999149 100644 --- a/packages/ui-app/src/Chart/Doughnut.tsx +++ b/packages/ui-app/src/Chart/Doughnut.tsx @@ -11,46 +11,45 @@ import { bnToBn } from '@polkadot/util'; import Base from './Base'; -type Value = { - colors: Array, - label: string, - value: number | BN -}; +interface Value { + colors: string[]; + label: string; + value: number | BN; +} -type Props = BareProps & { - size?: number, - values: Array -}; +interface Props extends BareProps { + size?: number; + values: Value[]; +} -type Options = { - colorNormal: Array, - colorHover: Array, - data: Array, - labels: Array -}; +interface Options { + colorNormal: string[]; + colorHover: string[]; + data: number[]; + labels: string[]; +} export default class ChartDoughnut extends React.PureComponent { - render () { + public render (): React.ReactNode { const { className, size = 100, style, values } = this.props; + const options: Options = { + colorNormal: [], + colorHover: [], + data: [], + labels: [] + }; // FIXME Classic case of kicking the can down the road, i.e. don't expend energy // when stuff are not used. This was replaced by the HorizBar as the only Chart // in actual use (by Referendum). However the below is not optimal, and gets re- // calculated on each render. If this component is put back in use, look at // getDerivedStateFromProps in HorizBar (the logic is the same for chartData) - const options = values.reduce((options, { colors: [normalColor = '#00f', hoverColor], label, value }) => { + values.forEach(({ colors: [normalColor = '#00f', hoverColor], label, value }): void => { options.colorNormal.push(normalColor); options.colorHover.push(hoverColor || normalColor); options.data.push(bnToBn(value).toNumber()); options.labels.push(label); - - return options; - }, { - colorNormal: [], - colorHover: [], - data: [], - labels: [] - } as Options); + }); return ( , - label: string, - value: number | BN -}; +interface Value { + colors: string[]; + label: string; + value: number | BN; +} -type Props = BareProps & { - aspectRatio?: number, - values: Array -}; +interface Props extends BareProps { + aspectRatio?: number; + values: Value[]; +} -type State = { - chartData?: ChartJs.ChartData, - chartOptions?: ChartJs.ChartOptions, - valuesStr?: string -}; +interface State { + chartData?: ChartJs.ChartData; + chartOptions?: ChartJs.ChartOptions; + valuesStr?: string; +} const alphaColor = (hexColor: string): string => ChartJs.helpers.color(hexColor).alpha(0.65).rgbString(); export default class ChartHorizBar extends React.PureComponent { - state: State = {}; + public state: State = {}; - static getDerivedStateFromProps ({ aspectRatio = 4, values }: Props, prevState: State) { + public static getDerivedStateFromProps ({ aspectRatio = 4, values }: Props, prevState: State): State | null { const valuesStr = JSON.stringify(values); if (valuesStr === prevState.valuesStr) { @@ -50,11 +50,11 @@ export default class ChartHorizBar extends React.PureComponent { return data; }, { - labels: [] as Array, + labels: [] as string[], datasets: [{ - data: [] as Array, - backgroundColor: [] as Array, - hoverBackgroundColor: [] as Array + data: [] as number[], + backgroundColor: [] as string[], + hoverBackgroundColor: [] as string[] }] }); @@ -80,7 +80,7 @@ export default class ChartHorizBar extends React.PureComponent { }; } - render () { + public render (): React.ReactNode { const { className, style } = this.props; const { chartData, chartOptions } = this.state; diff --git a/packages/ui-app/src/CodeRow.tsx b/packages/ui-app/src/CodeRow.tsx index 2330597395..a3ec27ebea 100644 --- a/packages/ui-app/src/CodeRow.tsx +++ b/packages/ui-app/src/CodeRow.tsx @@ -20,13 +20,13 @@ import Row, { RowProps, RowState, styles } from './Row'; import translate from './translate'; type Props = I18nProps & RowProps & { - code: CodeStored, - withMessages?: boolean + code: CodeStored; + withMessages?: boolean; }; -type State = RowState & { - codeHash: string -}; +interface State extends RowState { + codeHash: string; +} const DEFAULT_HASH = '0x'; const DEFAULT_NAME = ''; @@ -48,9 +48,9 @@ const CodeIcon = styled.div` const DEFAULT_ADDR = '5'.padEnd(16, 'x'); class CodeRow extends Row { - state: State; + public state: State; - constructor (props: Props) { + public constructor (props: Props) { super(props); this.state = this.createState(); @@ -89,7 +89,7 @@ class CodeRow extends Row { : null; } - render () { + public render (): React.ReactNode { const { className, isInline, style } = this.props; return ( diff --git a/packages/ui-app/src/Collection.tsx b/packages/ui-app/src/Collection.tsx index 4b5086fe9d..09930ad886 100644 --- a/packages/ui-app/src/Collection.tsx +++ b/packages/ui-app/src/Collection.tsx @@ -39,7 +39,7 @@ export const collectionStyles = ` `; export default class Collection

extends React.PureComponent { - constructor (props: P) { + public constructor (props: P) { super(props); this.state = { @@ -57,7 +57,7 @@ export default class Collection

{ - render () { + public render (): React.ReactNode { const { children, className } = this.props; return ( diff --git a/packages/ui-app/src/Column.tsx b/packages/ui-app/src/Column.tsx index 1a860b20d6..b0d25ef8e3 100644 --- a/packages/ui-app/src/Column.tsx +++ b/packages/ui-app/src/Column.tsx @@ -14,7 +14,7 @@ type Props = CollectionProps; type State = CollectionState; class Column extends Collection { - render () { + public render (): React.ReactNode { const { className } = this.props; const { isEmpty } = this.state; diff --git a/packages/ui-app/src/CopyButton.tsx b/packages/ui-app/src/CopyButton.tsx index b1da51eae3..916497b418 100644 --- a/packages/ui-app/src/CopyButton.tsx +++ b/packages/ui-app/src/CopyButton.tsx @@ -25,7 +25,7 @@ type InnerProps = Props & I18nProps & { }; class CopyButtonInner extends React.PureComponent { - render () { + public render (): React.ReactNode { const { children, className, icon = 'copy', value } = this.props; return ( @@ -67,7 +67,7 @@ class CopyButtonInner extends React.PureComponent { const CopyButtonI18n = translate(CopyButtonInner); class CopyButton extends React.PureComponent { - render () { + public render (): React.ReactNode { return ( {({ queueAction }) => ( diff --git a/packages/ui-app/src/CryptoType.tsx b/packages/ui-app/src/CryptoType.tsx index bc4d092bee..2fd0153891 100644 --- a/packages/ui-app/src/CryptoType.tsx +++ b/packages/ui-app/src/CryptoType.tsx @@ -16,7 +16,7 @@ type Props = BareProps & { }; export default class CryptoType extends React.PureComponent { - render () { + public render (): React.ReactNode { const { accountId, className, label = '' } = this.props; let type = 'unknown'; diff --git a/packages/ui-app/src/Dropdown.tsx b/packages/ui-app/src/Dropdown.tsx index 9bd1b94793..f0d8ecde2d 100644 --- a/packages/ui-app/src/Dropdown.tsx +++ b/packages/ui-app/src/Dropdown.tsx @@ -12,43 +12,43 @@ import { isUndefined } from '@polkadot/util'; import { classes } from './util'; import Labelled from './Labelled'; -type Props

extends React.PureComponent { - state: S = { + public state: S = { isEditingName: false, isEditingTags: false - } as S; + } as unknown as S; static defaultProps = { defaultName: '' }; - protected onChangeName = (name: string) => { + protected onChangeName = (name: string): void => { this.setState({ name }); } - protected onChangeTags = (tags: string[]) => { + protected onChangeTags = (tags: string[]): void => { this.setState({ tags }); } @@ -354,16 +354,16 @@ class Row

extends React.PureComponent void; - protected toggleNameEditor = () => { - this.setState(({ isEditingName }) => ({ + protected toggleNameEditor = (): void => { + this.setState(({ isEditingName }): S => ({ isEditingName: !isEditingName - })); + }) as unknown as S); } - protected toggleTagsEditor = () => { - this.setState(({ isEditingTags }) => ({ + protected toggleTagsEditor = (): void => { + this.setState(({ isEditingTags }): S => ({ isEditingTags: !isEditingTags - })); + }) as unknown as S); } } diff --git a/packages/ui-app/src/Static.tsx b/packages/ui-app/src/Static.tsx index 6325c5cc84..ac70afa8e7 100644 --- a/packages/ui-app/src/Static.tsx +++ b/packages/ui-app/src/Static.tsx @@ -21,7 +21,7 @@ type Props = BareProps & { }; export default class Static extends React.PureComponent { - render () { + public render (): React.ReactNode { const { className, children, defaultValue, help, isHidden, label, style, value, withLabel } = this.props; return ( diff --git a/packages/ui-app/src/Status/Context.ts b/packages/ui-app/src/Status/Context.ts index 5fd906b90a..443dab2622 100644 --- a/packages/ui-app/src/Status/Context.ts +++ b/packages/ui-app/src/Status/Context.ts @@ -7,8 +7,8 @@ import { QueueProps, QueueStatus, QueueTx } from './types'; import React from 'react'; const defaultState = { - stqueue: [] as Array, - txqueue: [] as Array + stqueue: [] as QueueStatus[], + txqueue: [] as QueueTx[] } as QueueProps; const Context: React.Context = React.createContext(defaultState); diff --git a/packages/ui-app/src/Status/Queue.tsx b/packages/ui-app/src/Status/Queue.tsx index 3b3cd11940..128791365f 100644 --- a/packages/ui-app/src/Status/Queue.tsx +++ b/packages/ui-app/src/Status/Queue.tsx @@ -4,7 +4,7 @@ import { RpcMethod } from '@polkadot/jsonrpc/types'; import { BareProps } from '../types'; -import { ActionStatus, PartialQueueTx$Extrinsic, PartialQueueTx$Rpc, QueueProps, QueueStatus, QueueTx, QueueTx$Extrinsic, QueueTx$Rpc, QueueTx$Status } from './types'; +import { ActionStatus, PartialQueueTxExtrinsic, PartialQueueTxRpc, QueueProps, QueueStatus, QueueTx, QueueTxExtrinsic, QueueTxRpc, QueueTxStatus } from './types'; import React from 'react'; import jsonrpc from '@polkadot/jsonrpc'; @@ -12,22 +12,22 @@ import jsonrpc from '@polkadot/jsonrpc'; import { QueueProvider } from './Context'; import { SubmittableResult } from '@polkadot/api/SubmittableExtrinsic'; -export type Props = BareProps & { - children: React.ReactNode -}; +export interface Props extends BareProps { + children: React.ReactNode; +} type State = QueueProps; const defaultState = { - stqueue: [] as Array, - txqueue: [] as Array + stqueue: [] as QueueStatus[], + txqueue: [] as QueueTx[] } as QueueProps; let nextId = 0; const REMOVE_TIMEOUT = 7500; const SUBMIT_RPC = jsonrpc.author.methods.submitAndWatchExtrinsic; -const STATUS_COMPLETE: Array = [ +const STATUS_COMPLETE: QueueTxStatus[] = [ // status from subscription 'finalized', 'usurped', 'dropped', 'invalid', // normal completion @@ -35,9 +35,9 @@ const STATUS_COMPLETE: Array = [ ]; export default class Queue extends React.Component { - state: State = defaultState; + public state: State = defaultState; - constructor (props: Props) { + public constructor (props: Props) { super(props); this.state = { @@ -50,7 +50,7 @@ export default class Queue extends React.Component { }; } - render () { + public render (): React.ReactNode { return ( {this.props.children} @@ -102,7 +102,7 @@ export default class Queue extends React.Component { }; } - queueSetTxStatus = (id: number, status: QueueTx$Status, result?: SubmittableResult, error?: Error): void => { + queueSetTxStatus = (id: number, status: QueueTxStatus, result?: SubmittableResult, error?: Error): void => { this.setState( (prevState: State): State => ({ txqueue: prevState.txqueue.map((item) => @@ -151,9 +151,9 @@ export default class Queue extends React.Component { }); } - private queueAdd = (value: QueueTx$Extrinsic | QueueTx$Rpc | QueueTx): number => { + private queueAdd = (value: QueueTxExtrinsic | QueueTxRpc | QueueTx): number => { const id = ++nextId; - const rpc: RpcMethod = (value as QueueTx$Rpc).rpc || SUBMIT_RPC; + const rpc: RpcMethod = (value as QueueTxRpc).rpc || SUBMIT_RPC; const removeItem = this.clearStatus(id); this.setState( @@ -171,7 +171,7 @@ export default class Queue extends React.Component { return id; } - queueExtrinsic = ({ accountId, extrinsic, signerCb, signerOptions, txFailedCb, txSuccessCb, txStartCb, txUpdateCb, isUnsigned }: PartialQueueTx$Extrinsic): number => { + queueExtrinsic = ({ accountId, extrinsic, signerCb, signerOptions, txFailedCb, txSuccessCb, txStartCb, txUpdateCb, isUnsigned }: PartialQueueTxExtrinsic): number => { return this.queueAdd({ accountId, extrinsic, @@ -185,7 +185,7 @@ export default class Queue extends React.Component { }); } - queueRpc = ({ accountId, rpc, values }: PartialQueueTx$Rpc): number => { + queueRpc = ({ accountId, rpc, values }: PartialQueueTxRpc): number => { return this.queueAdd({ accountId, rpc, diff --git a/packages/ui-app/src/Status/index.tsx b/packages/ui-app/src/Status/index.tsx index 1777e17d5b..c675e26b07 100644 --- a/packages/ui-app/src/Status/index.tsx +++ b/packages/ui-app/src/Status/index.tsx @@ -3,7 +3,7 @@ // of the Apache-2.0 license. See the LICENSE file for details. import { I18nProps } from '../types'; -import { QueueStatus, QueueTx, QueueTx$Status } from './types'; +import { QueueStatus, QueueTx, QueueTxStatus } from './types'; import React from 'react'; import styled from 'styled-components'; @@ -14,10 +14,10 @@ import Icon from '../Icon'; import { classes } from '../util'; import translate from '../translate'; -type Props = I18nProps & { - stqueue?: Array, - txqueue?: Array -}; +interface Props extends I18nProps { + stqueue?: QueueStatus[]; + txqueue?: QueueTx[]; +} const Wrapper = styled.div` display: inline-block; @@ -90,10 +90,10 @@ const Wrapper = styled.div` `; class Status extends React.PureComponent { - render () { + public render (): React.ReactNode { const { stqueue = [], txqueue = [] } = this.props; - const allst: Array = stqueue.filter(({ isCompleted }) => !isCompleted); - const alltx: Array = txqueue.filter(({ status }) => + const allst: QueueStatus[] = stqueue.filter(({ isCompleted }) => !isCompleted); + const alltx: QueueTx[] = txqueue.filter(({ status }) => !['completed', 'incomplete'].includes(status) ); @@ -198,7 +198,7 @@ class Status extends React.PureComponent { } } - private signerIconName = (status: QueueTx$Status) => { + private signerIconName = (status: QueueTxStatus) => { switch (status) { case 'cancelled': return 'ban'; diff --git a/packages/ui-app/src/Status/types.ts b/packages/ui-app/src/Status/types.ts index 3a1d560502..af4684ad23 100644 --- a/packages/ui-app/src/Status/types.ts +++ b/packages/ui-app/src/Status/types.ts @@ -10,18 +10,18 @@ import { SignatureOptions } from '@polkadot/types/types'; export type Actions = 'create' | 'edit' | 'restore' | 'forget' | 'backup' | 'changePassword' | 'transfer'; -export type ActionStatus = { - account?: AccountId | Address | string, - action: Actions | string, - message?: string, - status: 'error' | 'event' | 'queued' | 'received' | 'success' -}; +export interface ActionStatus { + account?: AccountId | Address | string; + action: Actions | string; + message?: string; + status: 'error' | 'event' | 'queued' | 'received' | 'success'; +} -export type AccountInfo = { - accountId?: string | null -}; +export interface AccountInfo { + accountId?: string | null; +} -export type QueueTx$Status = 'future' | 'ready' | 'finalized' | 'usurped' | 'dropped' | 'invalid' | 'broadcast' | 'cancelled' | 'completed' | 'error' | 'incomplete' | 'queued' | 'sending' | 'sent' | 'blocked'; +export type QueueTxStatus = 'future' | 'ready' | 'finalized' | 'usurped' | 'dropped' | 'invalid' | 'broadcast' | 'cancelled' | 'completed' | 'error' | 'incomplete' | 'queued' | 'sending' | 'sent' | 'blocked'; export type SignerCallback = (id: number, isSigned: boolean) => void; @@ -29,78 +29,78 @@ export type TxCallback = (status: SubmittableResult) => void; export type TxFailedCallback = (status: SubmittableResult | null) => void; -export type QueueTx = AccountInfo & { - error?: Error, - extrinsic?: SubmittableExtrinsic, - id: number, - isUnsigned?: boolean, - result?: any, - removeItem: () => void, - rpc: RpcMethod, - signerCb?: SignerCallback, - signerOptions?: SignatureOptions, - txFailedCb?: TxFailedCallback, - txSuccessCb?: TxCallback, - txStartCb?: () => void, - txUpdateCb?: TxCallback, - values?: Array, - status: QueueTx$Status -}; +export interface QueueTx extends AccountInfo { + error?: Error; + extrinsic?: SubmittableExtrinsic; + id: number; + isUnsigned?: boolean; + result?: any; + removeItem: () => void; + rpc: RpcMethod; + signerCb?: SignerCallback; + signerOptions?: SignatureOptions; + txFailedCb?: TxFailedCallback; + txSuccessCb?: TxCallback; + txStartCb?: () => void; + txUpdateCb?: TxCallback; + values?: any[]; + status: QueueTxStatus; +} -export type QueueStatus = ActionStatus & { - id: number, - isCompleted: boolean, - removeItem: () => void -}; +export interface QueueStatus extends ActionStatus { + id: number; + isCompleted: boolean; + removeItem: () => void; +} -export type QueueTx$Result = { - error?: Error, - result?: any, - status: QueueTx$Status -}; +export interface QueueTxResult { + error?: Error; + result?: any; + status: QueueTxStatus; +} -export type QueueTx$Extrinsic = AccountInfo & { - extrinsic: SubmittableExtrinsic -}; +export interface QueueTxExtrinsic extends AccountInfo { + extrinsic: SubmittableExtrinsic; +} -export type QueueTx$Rpc = AccountInfo & { - rpc: RpcMethod, - values: Array -}; +export interface QueueTxRpc extends AccountInfo { + rpc: RpcMethod; + values: any[]; +} -export type PartialAccountInfo = { - accountId?: string | null -}; +export interface PartialAccountInfo { + accountId?: string | null; +} -export type PartialQueueTx$Extrinsic = PartialAccountInfo & { - extrinsic: SubmittableExtrinsic, - signerCb?: SignerCallback, - signerOptions?: SignatureOptions, - txFailedCb?: TxFailedCallback, - txSuccessCb?: TxCallback, - txStartCb?: () => void, - txUpdateCb?: TxCallback, - isUnsigned?: boolean -}; +export interface PartialQueueTxExtrinsic extends PartialAccountInfo { + extrinsic: SubmittableExtrinsic; + signerCb?: SignerCallback; + signerOptions?: SignatureOptions; + txFailedCb?: TxFailedCallback; + txSuccessCb?: TxCallback; + txStartCb?: () => void; + txUpdateCb?: TxCallback; + isUnsigned?: boolean; +} -export type PartialQueueTx$Rpc = PartialAccountInfo & { - rpc: RpcMethod, - values: Array -}; +export interface PartialQueueTxRpc extends PartialAccountInfo { + rpc: RpcMethod; + values: any[]; +} -export type QueueTx$RpcAdd = (value: PartialQueueTx$Rpc) => number; +export type QueueTxRpcAdd = (value: PartialQueueTxRpc) => number; -export type QueueTx$ExtrinsicAdd = (value: PartialQueueTx$Extrinsic) => number; +export type QueueTxExtrinsicAdd = (value: PartialQueueTxExtrinsic) => number; -export type QueueTx$MessageSetStatus = (id: number, status: QueueTx$Status, result?: any, error?: Error) => void; +export type QueueTxMessageSetStatus = (id: number, status: QueueTxStatus, result?: any, error?: Error) => void; export type QueueAction$Add = (status: ActionStatus) => number; -export type QueueProps = { - stqueue: Array, - txqueue: Array, - queueAction: QueueAction$Add, - queueExtrinsic: QueueTx$ExtrinsicAdd, - queueRpc: QueueTx$RpcAdd, - queueSetTxStatus: QueueTx$MessageSetStatus -}; +export interface QueueProps { + stqueue: QueueStatus[]; + txqueue: QueueTx[]; + queueAction: QueueAction$Add; + queueExtrinsic: QueueTxExtrinsicAdd; + queueRpc: QueueTxRpcAdd; + queueSetTxStatus: QueueTxMessageSetStatus; +} diff --git a/packages/ui-app/src/SummaryBox.tsx b/packages/ui-app/src/SummaryBox.tsx index 055948917c..e41d09b0b1 100644 --- a/packages/ui-app/src/SummaryBox.tsx +++ b/packages/ui-app/src/SummaryBox.tsx @@ -13,7 +13,7 @@ type Props = BareProps & { }; class SummaryBox extends React.PureComponent { - render () { + public render (): React.ReactNode { const { children, className } = this.props; return ( diff --git a/packages/ui-app/src/Tabs.tsx b/packages/ui-app/src/Tabs.tsx index 5c43ccde95..7e6e8ec5b4 100644 --- a/packages/ui-app/src/Tabs.tsx +++ b/packages/ui-app/src/Tabs.tsx @@ -34,13 +34,13 @@ export type TabItem = { type Props = BareProps & { basePath: string, - hidden?: Array, - items: Array, + hidden?: string[], + items: TabItem[], isSequence?: boolean }; export default class Tabs extends React.PureComponent { - render () { + public render (): React.ReactNode { const { className, hidden = [], items, style } = this.props; return (

{ - render () { + public render (): React.ReactNode { const { className, defaultValue, label } = this.props; return ( diff --git a/packages/ui-app/src/Tooltip.tsx b/packages/ui-app/src/Tooltip.tsx index 95efae50f9..e74c0d9beb 100644 --- a/packages/ui-app/src/Tooltip.tsx +++ b/packages/ui-app/src/Tooltip.tsx @@ -24,7 +24,7 @@ type Props = BareProps & { export default class Tooltip extends React.PureComponent { private tooltipContainer: HTMLElement; - constructor (props: Props) { + public constructor (props: Props) { super(props); this.tooltipContainer = document.createElement('div'); @@ -42,7 +42,7 @@ export default class Tooltip extends React.PureComponent { } } - render () { + public render (): React.ReactNode { const { className, effect = 'solid', offset, place = 'bottom', text, trigger } = this.props; return ReactDOM.createPortal( diff --git a/packages/ui-app/src/TreasuryProposal.tsx b/packages/ui-app/src/TreasuryProposal.tsx index b67a5d8220..0e8622bfda 100644 --- a/packages/ui-app/src/TreasuryProposal.tsx +++ b/packages/ui-app/src/TreasuryProposal.tsx @@ -29,9 +29,9 @@ type State = { }; class TreasuryProposal extends React.PureComponent { - state: State = {}; + public state: State = {}; - constructor (props: Props) { + public constructor (props: Props) { super(props); if (!props.proposal) { @@ -50,7 +50,7 @@ class TreasuryProposal extends React.PureComponent { this.fetchProposal(); } - render () { + public render (): React.ReactNode { const { className, asInset, insetProps, onClick, t } = this.props; const { proposal } = this.state; diff --git a/packages/ui-app/src/TxButton.tsx b/packages/ui-app/src/TxButton.tsx index e686014d7f..e618a4ff37 100644 --- a/packages/ui-app/src/TxButton.tsx +++ b/packages/ui-app/src/TxButton.tsx @@ -7,7 +7,7 @@ import { ApiProps } from '@polkadot/ui-api/types'; import { assert, isFunction, isUndefined } from '@polkadot/util'; import { Index } from '@polkadot/types'; import { IExtrinsic } from '@polkadot/types/types'; -import { QueueTx, QueueTx$ExtrinsicAdd, TxCallback, TxFailedCallback } from './Status/types'; +import { QueueTx, QueueTxExtrinsicAdd, TxCallback, TxFailedCallback } from './Status/types'; import React from 'react'; import { SubmittableResult } from '@polkadot/api'; @@ -17,50 +17,50 @@ import Button from './Button'; import { Button$Sizes } from './Button/types'; import { QueueConsumer } from './Status/Context'; -type ConstructFn = () => Array; +type ConstructFn = () => any[]; -type InjectedProps = { - queueExtrinsic: QueueTx$ExtrinsicAdd; - txqueue: Array; -}; +interface InjectedProps { + queueExtrinsic: QueueTxExtrinsicAdd; + txqueue: QueueTx[]; +} -type Props = ApiProps & { - accountId?: string, - accountNonce?: Index, - className?: string, - extrinsic?: IExtrinsic | SubmittableExtrinsic, - icon?: string, - iconSize?: Button$Sizes, - isBasic?: boolean, - isDisabled?: boolean, - isNegative?: boolean, - isPrimary?: boolean, - isUnsigned?: boolean, - label: React.ReactNode, - onClick?: () => any, - onFailed?: TxFailedCallback, - onStart?: () => void, - onSuccess?: TxCallback, - onUpdate?: TxCallback, - params?: Array | ConstructFn, - tooltip?: string, - tx?: string, - withSpinner?: boolean -}; +interface Props extends ApiProps { + accountId?: string; + accountNonce?: Index; + className?: string; + extrinsic?: IExtrinsic | SubmittableExtrinsic; + icon?: string; + iconSize?: Button$Sizes; + isBasic?: boolean; + isDisabled?: boolean; + isNegative?: boolean; + isPrimary?: boolean; + isUnsigned?: boolean; + label: React.ReactNode; + onClick?: () => any; + onFailed?: TxFailedCallback; + onStart?: () => void; + onSuccess?: TxCallback; + onUpdate?: TxCallback; + params?: any[] | ConstructFn; + tooltip?: string; + tx?: string; + withSpinner?: boolean; +} type InnerProps = Props & InjectedProps; -type State = { - extrinsic: SubmittableExtrinsic, - isSending: boolean -}; +interface State { + extrinsic: SubmittableExtrinsic; + isSending: boolean; +} class TxButtonInner extends React.PureComponent { state = { isSending: false } as State; - render () { + public render (): React.ReactNode { const { accountId, className, icon, iconSize , isBasic, isDisabled, isNegative, isPrimary, isUnsigned, label, tooltip } = this.props; const { isSending } = this.state; const needsAccount = isUnsigned @@ -141,7 +141,7 @@ class TxButtonInner extends React.PureComponent { class TxButton extends React.PureComponent { button: any = React.createRef(); - render () { + public render (): React.ReactNode { return ( {({ queueExtrinsic, txqueue }) => ( diff --git a/packages/ui-app/src/TxComponent.tsx b/packages/ui-app/src/TxComponent.tsx index c95c984c7c..ac9a4a3184 100644 --- a/packages/ui-app/src/TxComponent.tsx +++ b/packages/ui-app/src/TxComponent.tsx @@ -7,7 +7,7 @@ import React from 'react'; export default class TxComponent extends React.PureComponent { button: any; - constructor (props: P) { + public constructor (props: P) { super(props); this.button = React.createRef(); } diff --git a/packages/ui-app/src/TxModal.tsx b/packages/ui-app/src/TxModal.tsx index 7f46235a19..14cb43c2c9 100644 --- a/packages/ui-app/src/TxModal.tsx +++ b/packages/ui-app/src/TxModal.tsx @@ -29,7 +29,7 @@ class TxModal

extends TxComponen state: S = this.defaultState; - render () { + public render (): React.ReactNode { const { isOpen } = this.state; return ( @@ -102,7 +102,7 @@ class TxModal

extends TxComponen } protected txMethod: () => string = () => ''; - protected txParams: () => Array = () => []; + protected txParams: () => any[] = () => []; protected renderContent: () => React.ReactNode | null = () => null; protected renderPreContent: () => React.ReactNode | null = () => null; diff --git a/packages/ui-app/src/Voting.tsx b/packages/ui-app/src/Voting.tsx index ce15d87fb7..edf5d170ed 100644 --- a/packages/ui-app/src/Voting.tsx +++ b/packages/ui-app/src/Voting.tsx @@ -19,21 +19,21 @@ import TxModal, { TxModalProps, TxModalState } from './TxModal'; import { isTreasuryProposalVote } from './util'; type Props = I18nProps & TxModalProps & { - allAccounts?: SubjectInfo, - hash?: string, - idNumber: BN | number, - isCollective: boolean, - proposal?: Proposal | null, - preContent?: React.ReactNode + allAccounts?: SubjectInfo; + hash?: string; + idNumber: BN | number; + isCollective: boolean; + proposal?: Proposal | null; + preContent?: React.ReactNode; }; -type State = TxModalState & { - voteOptions: Array<{ text: React.ReactNode, value: boolean }>, - voteValue: boolean -}; +interface State extends TxModalState { + voteOptions: { text: React.ReactNode; value: boolean }[]; + voteValue: boolean; +} class Voting extends TxModal { - state: State; + public state: State; headerText = () => { const { isCollective, t } = this.props; @@ -59,7 +59,7 @@ class Voting extends TxModal { : [idNumber, voteValue]; } - constructor (props: Props) { + public constructor (props: Props) { super(props); const { t } = props; diff --git a/packages/ui-app/src/media.ts b/packages/ui-app/src/media.ts index 99390e3ec8..5fb0229258 100644 --- a/packages/ui-app/src/media.ts +++ b/packages/ui-app/src/media.ts @@ -12,10 +12,10 @@ type MediaCss = { const media = Object .keys(ScreenSizes) - .reduce((acc, label: any) => { + .reduce((acc, label: any): MediaCss => { const size: number = ScreenSizes[label] as any; - acc[label] = (values: TemplateStringsArray) => + acc[label] = (values: TemplateStringsArray): unknown => css` @media (min-width: ${size / 16}em) { ${values} @@ -23,6 +23,6 @@ const media = Object `; return acc; - }, {} as MediaCss); + }, {} as unknown as MediaCss); export default media; diff --git a/packages/ui-app/src/util/classes.ts b/packages/ui-app/src/util/classes.ts index 7d78646924..b29ebff01f 100644 --- a/packages/ui-app/src/util/classes.ts +++ b/packages/ui-app/src/util/classes.ts @@ -2,7 +2,7 @@ // This software may be modified and distributed under the terms // of the Apache-2.0 license. See the LICENSE file for details. -export default function classes (...classNames: Array): string { +export default function classes (...classNames: any[]): string { return classNames .filter((className) => className) .join(' '); diff --git a/packages/ui-app/src/util/getAddressTags.ts b/packages/ui-app/src/util/getAddressTags.ts index 0bf52efbf6..a9b7dcbd61 100644 --- a/packages/ui-app/src/util/getAddressTags.ts +++ b/packages/ui-app/src/util/getAddressTags.ts @@ -6,6 +6,6 @@ import { KeyringItemType } from '@polkadot/ui-keyring/types'; import getAddressMeta from './getAddressMeta'; -export default function getAddressTags (address: string, type: KeyringItemType | null = null): Array { +export default function getAddressTags (address: string, type: KeyringItemType | null = null): string[] { return getAddressMeta(address, type).tags || []; } diff --git a/packages/ui-app/src/util/types.ts b/packages/ui-app/src/util/types.ts index 36bb179f04..7dbcb4fa71 100644 --- a/packages/ui-app/src/util/types.ts +++ b/packages/ui-app/src/util/types.ts @@ -2,11 +2,11 @@ // This software may be modified and distributed under the terms // of the Apache-2.0 license. See the LICENSE file for details. -export type DropdownOption = { - className?: string, - key?: string, - text: React.ReactNode, - value: string -}; +export interface DropdownOption { + className?: string; + key?: string; + text: React.ReactNode; + value: string; +} -export type DropdownOptions = Array; +export type DropdownOptions = DropdownOption[]; diff --git a/packages/ui-params/src/Param/Account.tsx b/packages/ui-params/src/Param/Account.tsx index 8a1b0f73d5..002e622626 100644 --- a/packages/ui-params/src/Param/Account.tsx +++ b/packages/ui-params/src/Param/Account.tsx @@ -11,7 +11,7 @@ import keyring from '@polkadot/ui-keyring'; import Bare from './Bare'; export default class Account extends React.PureComponent { - render () { + public render (): React.ReactNode { const { className, defaultValue: { value }, isDisabled, isError, label, style, withLabel } = this.props; const defaultValue = value && value.toString(); diff --git a/packages/ui-params/src/Param/Amount.tsx b/packages/ui-params/src/Param/Amount.tsx index 4a5605f692..7b19643620 100644 --- a/packages/ui-params/src/Param/Amount.tsx +++ b/packages/ui-params/src/Param/Amount.tsx @@ -13,7 +13,7 @@ import { bnToBn, formatNumber } from '@polkadot/util'; import Bare from './Bare'; export default class Amount extends React.PureComponent { - render () { + public render (): React.ReactNode { const { className, defaultValue: { value }, isDisabled, isError, label, onEnter, style, withLabel } = this.props; const defaultValue = isDisabled ? ( diff --git a/packages/ui-params/src/Param/Balance.tsx b/packages/ui-params/src/Param/Balance.tsx index f97a7ebfe5..ebdd54c0c2 100644 --- a/packages/ui-params/src/Param/Balance.tsx +++ b/packages/ui-params/src/Param/Balance.tsx @@ -13,7 +13,7 @@ import Bare from './Bare'; type Props = BareProps; class Balance extends React.PureComponent { - render () { + public render (): React.ReactNode { const { className, defaultValue: { value }, isDisabled, isError, label, onEnter, style, withLabel } = this.props; const defaultValue = new BN((value as BN || '0').toString()).toString(10); diff --git a/packages/ui-params/src/Param/Bare.tsx b/packages/ui-params/src/Param/Bare.tsx index 4e5dde7ef2..8c044755a1 100644 --- a/packages/ui-params/src/Param/Bare.tsx +++ b/packages/ui-params/src/Param/Bare.tsx @@ -12,7 +12,7 @@ type Props = BareProps & { }; export default class Bare extends React.PureComponent { - render () { + public render (): React.ReactNode { const { children, className, style } = this.props; return ( diff --git a/packages/ui-params/src/Param/Base.tsx b/packages/ui-params/src/Param/Base.tsx index 4c81990477..58e5fede58 100644 --- a/packages/ui-params/src/Param/Base.tsx +++ b/packages/ui-params/src/Param/Base.tsx @@ -19,7 +19,7 @@ type Props = BareProps & { }; export default class Base extends React.PureComponent { - render () { + public render (): React.ReactNode { const { children, className, isDisabled, label, size = 'medium', style, withLabel } = this.props; return ( diff --git a/packages/ui-params/src/Param/BaseBytes.tsx b/packages/ui-params/src/Param/BaseBytes.tsx index c3ca1de2f7..452e884895 100644 --- a/packages/ui-params/src/Param/BaseBytes.tsx +++ b/packages/ui-params/src/Param/BaseBytes.tsx @@ -23,7 +23,7 @@ const defaultValidate = (): boolean => true; export default class BaseBytes extends React.PureComponent { - render () { + public render (): React.ReactNode { const { children, className, defaultValue: { value }, isDisabled, isError, label, onEnter, size = 'full', style, withLabel } = this.props; const defaultValue = value ? ( diff --git a/packages/ui-params/src/Param/Bool.tsx b/packages/ui-params/src/Param/Bool.tsx index 5bb6a04086..1862225b64 100644 --- a/packages/ui-params/src/Param/Bool.tsx +++ b/packages/ui-params/src/Param/Bool.tsx @@ -15,7 +15,7 @@ const options = [ ]; export default class BoolParam extends React.PureComponent { - render () { + public render (): React.ReactNode { const { className, defaultValue: { value }, isDisabled, isError, label, style, withLabel } = this.props; const defaultValue = value instanceof Boolean ? value.valueOf() diff --git a/packages/ui-params/src/Param/Bytes.tsx b/packages/ui-params/src/Param/Bytes.tsx index be73b7e529..62617141ea 100644 --- a/packages/ui-params/src/Param/Bytes.tsx +++ b/packages/ui-params/src/Param/Bytes.tsx @@ -16,11 +16,11 @@ type State = { }; export default class Bytes extends React.PureComponent { - state: State = { + public state: State = { isFileDrop: false }; - render () { + public render (): React.ReactNode { const { isDisabled } = this.props; const { isFileDrop } = this.state; diff --git a/packages/ui-params/src/Param/Code.tsx b/packages/ui-params/src/Param/Code.tsx index 28f65e0a64..e16cb1341f 100644 --- a/packages/ui-params/src/Param/Code.tsx +++ b/packages/ui-params/src/Param/Code.tsx @@ -10,7 +10,7 @@ import Bytes from './Bytes'; import BytesFile from './File'; export default class Code extends React.PureComponent { - render () { + public render (): React.ReactNode { const { className, defaultValue, isDisabled, isError, label, style, withLabel } = this.props; if (isDisabled) { diff --git a/packages/ui-params/src/Param/Enum.tsx b/packages/ui-params/src/Param/Enum.tsx index 05867dfee0..d0f7a8e1b5 100644 --- a/packages/ui-params/src/Param/Enum.tsx +++ b/packages/ui-params/src/Param/Enum.tsx @@ -12,30 +12,35 @@ import Params from '../'; import Bare from './Bare'; import Static from './Static'; +interface Option { + text?: string; + value?: string; +} + type Props = BaseProps; -type State = { - def: TypeDef | null, - options: Array<{ text: string, value: string }>, - sub: Array, - type: string | null -}; +interface State { + def: TypeDef | null; + options: Option[]; + sub: TypeDef[]; + type: string | null; +} export default class EnumParam extends React.PureComponent { - state: State = { + public state: State = { def: null, options: [], sub: [], type: null }; - static getDerivedStateFromProps ({ type: { type } }: Props, prevState: State) { + public static getDerivedStateFromProps ({ type: { type } }: Props, prevState: State): State | null { if (prevState.type === type) { return null; } - const sub = getTypeDef(createType(type).toRawType()).sub as Array; - const options = sub.map(({ name }) => ({ + const sub = getTypeDef(createType(type).toRawType()).sub as TypeDef[]; + const options = sub.map(({ name }): Option => ({ text: name, value: name })); @@ -46,10 +51,10 @@ export default class EnumParam extends React.PureComponent { options, sub, type - } as State; + }; } - render () { + public render (): React.ReactNode { const { className, defaultValue, isDisabled, isError, label, style, withLabel } = this.props; if (isDisabled) { @@ -90,14 +95,12 @@ export default class EnumParam extends React.PureComponent { } private onChange = (value: string): void => { - const { sub } = this.state; - - this.setState({ - def: sub.find(({ name }) => name === value) || null - }); + this.setState(({ sub }): State => ({ + def: sub.find(({ name }): boolean => name === value) || null + }) as unknown as State); } - private onChangeParam = ([{ isValid, value }]: Array): void => { + private onChangeParam = ([{ isValid, value }]: RawParam[]): void => { const { onChange } = this.props; const { def } = this.state; diff --git a/packages/ui-params/src/Param/File.tsx b/packages/ui-params/src/Param/File.tsx index eb5a042d79..abbf50716c 100644 --- a/packages/ui-params/src/Param/File.tsx +++ b/packages/ui-params/src/Param/File.tsx @@ -20,7 +20,7 @@ type Props = BareProps & { }; export default class File extends React.PureComponent { - render () { + public render (): React.ReactNode { const { className, isDisabled, isError = false, label, onChange, placeholder, style, withLabel } = this.props; return ( diff --git a/packages/ui-params/src/Param/Hash.tsx b/packages/ui-params/src/Param/Hash.tsx index 3049d9aab0..fe1e01aa62 100644 --- a/packages/ui-params/src/Param/Hash.tsx +++ b/packages/ui-params/src/Param/Hash.tsx @@ -9,7 +9,7 @@ import React from 'react'; import BaseBytes from './BaseBytes'; export default class Hash extends React.PureComponent { - render () { + public render (): React.ReactNode { const { className, defaultValue, isDisabled, isError, label, name, onChange, onEnter, style, type, withLabel } = this.props; return ( diff --git a/packages/ui-params/src/Param/KeyValue.tsx b/packages/ui-params/src/Param/KeyValue.tsx index 7613427723..04f7567e1c 100644 --- a/packages/ui-params/src/Param/KeyValue.tsx +++ b/packages/ui-params/src/Param/KeyValue.tsx @@ -22,7 +22,7 @@ type State = { }; export default class KeyValue extends React.PureComponent { - state: State = { + public state: State = { key: { isValid: false, u8a: new Uint8Array([]) @@ -33,7 +33,7 @@ export default class KeyValue extends React.PureComponent { } }; - render () { + public render (): React.ReactNode { const { className, isDisabled, label, onEnter, style, withLabel } = this.props; const { key, value } = this.state; diff --git a/packages/ui-params/src/Param/KeyValueArray.tsx b/packages/ui-params/src/Param/KeyValueArray.tsx index 7572703d4b..a7afdd698a 100644 --- a/packages/ui-params/src/Param/KeyValueArray.tsx +++ b/packages/ui-params/src/Param/KeyValueArray.tsx @@ -17,17 +17,17 @@ import KeyValue from './KeyValue'; type Props = BaseProps & WithTranslation; -type State = { +interface State { placeholder?: string; -}; +} -type Parsed = { - isValid: boolean, - value: Array<{ - key: Uint8Array, - value: Uint8Array - }> -}; +interface Parsed { + isValid: boolean; + value: { + key: Uint8Array; + value: Uint8Array; + }[]; +} const BYTES_TYPE = { type: 'Bytes', @@ -37,7 +37,7 @@ const BYTES_TYPE = { class KeyValueArray extends React.PureComponent { private placeholderEmpty: string; - constructor (props: Props) { + public constructor (props: Props) { super(props); this.placeholderEmpty = props.t('click to select or drag and drop JSON key/value (hex-encoded) file'); @@ -46,7 +46,7 @@ class KeyValueArray extends React.PureComponent { }; } - render () { + public render (): React.ReactNode { const { className, isDisabled, isError, label, style, withLabel } = this.props; const { placeholder } = this.state; diff --git a/packages/ui-params/src/Param/Moment.tsx b/packages/ui-params/src/Param/Moment.tsx index 6d86cba574..ab9d576962 100644 --- a/packages/ui-params/src/Param/Moment.tsx +++ b/packages/ui-params/src/Param/Moment.tsx @@ -2,7 +2,7 @@ // This software may be modified and distributed under the terms // of the Apache-2.0 license. See the LICENSE file for details. -import { Props, RawParam$OnChange$Value } from '../types'; +import { Props, RawParamOnChangeValue } from '../types'; import React from 'react'; import { Static } from '@polkadot/ui-app'; @@ -10,7 +10,7 @@ import { Static } from '@polkadot/ui-app'; import Amount from './Amount'; export default class Code extends React.PureComponent { - render () { + public render (): React.ReactNode { const { className, defaultValue, isDisabled, isError, label, onEnter, style, type, withLabel } = this.props; if (isDisabled) { @@ -53,7 +53,7 @@ export default class Code extends React.PureComponent { } // TODO: Validate that we have actual proper WASM code - private onChange = (value: RawParam$OnChange$Value): void => { + private onChange = (value: RawParamOnChangeValue): void => { const { onChange } = this.props; onChange && onChange(value); diff --git a/packages/ui-params/src/Param/Null.tsx b/packages/ui-params/src/Param/Null.tsx index cffc214e31..b869b3c391 100644 --- a/packages/ui-params/src/Param/Null.tsx +++ b/packages/ui-params/src/Param/Null.tsx @@ -16,7 +16,7 @@ export default class Null extends React.PureComponent { }); } - render () { + public render (): React.ReactNode { return null; } } diff --git a/packages/ui-params/src/Param/Proposal.tsx b/packages/ui-params/src/Param/Proposal.tsx index e6aa2a170a..c67b5d6ff8 100644 --- a/packages/ui-params/src/Param/Proposal.tsx +++ b/packages/ui-params/src/Param/Proposal.tsx @@ -13,7 +13,7 @@ import Bare from './Bare'; import Unknown from './Unknown'; export default class Proposal extends React.PureComponent { - render () { + public render (): React.ReactNode { const { className, defaultValue: { value }, isDisabled, label, style, withLabel } = this.props; if (!isDisabled) { diff --git a/packages/ui-params/src/Param/Static.tsx b/packages/ui-params/src/Param/Static.tsx index 15c18c3949..07d6703d8a 100644 --- a/packages/ui-params/src/Param/Static.tsx +++ b/packages/ui-params/src/Param/Static.tsx @@ -17,7 +17,7 @@ type Props = BareProps & WithTranslation & { }; class StaticParam extends React.PureComponent { - render () { + public render (): React.ReactNode { const { className, defaultValue, label, style, t } = this.props; const value = defaultValue && defaultValue.value && defaultValue.value.toString(); diff --git a/packages/ui-params/src/Param/Struct.tsx b/packages/ui-params/src/Param/Struct.tsx index e459fbafb9..bf73c1159d 100644 --- a/packages/ui-params/src/Param/Struct.tsx +++ b/packages/ui-params/src/Param/Struct.tsx @@ -14,12 +14,12 @@ import Static from './Static'; type Props = BaseProps; type State = { - defs: Array, + defs: TypeDef[], type: string | null }; export default class StructParam extends React.PureComponent { - state: State = { + public state: State = { defs: [], type: null }; @@ -29,7 +29,7 @@ export default class StructParam extends React.PureComponent { return null; } - const defs = getTypeDef(createType(type).toRawType()).sub as Array; + const defs = getTypeDef(createType(type).toRawType()).sub as TypeDef[]; return { defs, @@ -37,7 +37,7 @@ export default class StructParam extends React.PureComponent { } as State; } - render () { + public render (): React.ReactNode { const { className, isDisabled, label, style, withLabel } = this.props; if (isDisabled) { @@ -66,19 +66,19 @@ export default class StructParam extends React.PureComponent { ); } - private onChangeParams = (values: Array) => { + private onChangeParams = (values: RawParam[]): void => { const { onChange } = this.props; if (onChange) { const { defs } = this.state; onChange({ - isValid: values.reduce((result, { isValid }) => result && isValid, true as boolean), + isValid: values.reduce((result, { isValid }): boolean => result && isValid, true as boolean), value: defs.reduce((value, { name }, index) => { value[name as string] = values[index].value; return value; - }, {} as { [index: string]: any }) + }, {} as Record) }); } } diff --git a/packages/ui-params/src/Param/Text.tsx b/packages/ui-params/src/Param/Text.tsx index f87deff946..24e3060ac8 100644 --- a/packages/ui-params/src/Param/Text.tsx +++ b/packages/ui-params/src/Param/Text.tsx @@ -10,7 +10,7 @@ import { Input } from '@polkadot/ui-app'; import Bare from './Bare'; export default class Text extends React.PureComponent { - render () { + public render (): React.ReactNode { const { className, defaultValue: { value }, isDisabled, isError, label, onEnter, style, withLabel } = this.props; const defaultValue = (value || '').toString(); diff --git a/packages/ui-params/src/Param/Tuple.tsx b/packages/ui-params/src/Param/Tuple.tsx index 77e37d2169..2ee9590e00 100644 --- a/packages/ui-params/src/Param/Tuple.tsx +++ b/packages/ui-params/src/Param/Tuple.tsx @@ -11,23 +11,23 @@ import { isUndefined } from '@polkadot/util'; import Bare from './Bare'; import findComponent from './findComponent'; -type State = { - Components: Array>, - sub: Array, - subTypes: Array, - type?: string, - values: Array -}; +interface State { + Components: React.ComponentType[]; + sub: string[]; + subTypes: TypeDef[]; + type?: string; + values: RawParam[]; +} export default class Tuple extends React.PureComponent { - state: State = { + public state: State = { Components: [], sub: [], subTypes: [], values: [] }; - static getDerivedStateFromProps ({ defaultValue: { value }, type: { sub, type } }: Props, prevState: State): Partial | null { + public static getDerivedStateFromProps ({ defaultValue: { value }, type: { sub, type } }: Props, prevState: State): Partial | null { if (type === prevState.type) { return null; } @@ -35,7 +35,7 @@ export default class Tuple extends React.PureComponent { const subTypes = sub && Array.isArray(sub) ? sub : []; - const values = (value as Array).map((value) => + const values = (value as any[]).map((value) => isUndefined(value) || isUndefined(value.isValid) ? { isValid: !isUndefined(value), @@ -53,7 +53,7 @@ export default class Tuple extends React.PureComponent { }; } - render () { + public render (): React.ReactNode { const { className, isDisabled, onEnter, style, withLabel } = this.props; const { Components, sub, subTypes, values } = this.state; diff --git a/packages/ui-params/src/Param/Unknown.tsx b/packages/ui-params/src/Param/Unknown.tsx index a3add02d01..3d48ad4837 100644 --- a/packages/ui-params/src/Param/Unknown.tsx +++ b/packages/ui-params/src/Param/Unknown.tsx @@ -15,7 +15,7 @@ type Props = BareProps & { }; export default class Unknown extends React.PureComponent { - render () { + public render (): React.ReactNode { const { className, defaultValue, isDisabled, isError, label, name, onChange, onEnter, style, type } = this.props; if (isDisabled) { diff --git a/packages/ui-params/src/Param/Vector.tsx b/packages/ui-params/src/Param/Vector.tsx index 7921d1df0b..cce7340654 100644 --- a/packages/ui-params/src/Param/Vector.tsx +++ b/packages/ui-params/src/Param/Vector.tsx @@ -17,32 +17,32 @@ import findComponent from './findComponent'; type Props = BareProps & WithTranslation; -type State = { - Component: React.ComponentType | null, - type?: string, - values: Array -}; +interface State { + Component: React.ComponentType | null; + type?: string; + values: RawParam[]; +} class Vector extends React.PureComponent { - state: State = { + public state: State = { Component: null, values: [] }; - static getDerivedStateFromProps ({ defaultValue: { value = [] }, isDisabled, type: { sub, type } }: Props, prevState: State): Partial | null { + public static getDerivedStateFromProps ({ defaultValue: { value = [] }, isDisabled, type: { sub, type } }: Props, prevState: State): Partial | null { if (type === prevState.type) { return null; } - const values: Array = isDisabled || prevState.values.length === 0 - ? value.map((value: any) => - isUndefined(value) || isUndefined(value.isValid) - ? { - isValid: !isUndefined(value), - value - } - : value - ) + const values: RawParam[] = isDisabled || prevState.values.length === 0 + ? value.map((value: any): RawParam => ( + isUndefined(value) || isUndefined(value.isValid) + ? { + isValid: !isUndefined(value), + value + } + : value + )) : prevState.values; return { @@ -52,7 +52,7 @@ class Vector extends React.PureComponent { }; } - render () { + public render (): React.ReactNode { const { className, isDisabled, onEnter, style, type, withLabel } = this.props; const { Component, values } = this.state; const subType = type.sub as TypeDef; @@ -66,7 +66,7 @@ class Vector extends React.PureComponent { className={className} style={style} > - {values.map((value, index) => ( + {values.map((value, index): React.ReactNode => ( { ); } - private renderButtons () { + private renderButtons (): React.ReactNode { const { isDisabled, t } = this.props; const { values } = this.state; @@ -108,22 +108,23 @@ class Vector extends React.PureComponent { ); } - private onChange = (index: number) => { + private onChange = (index: number): (value: RawParam) => void => { return (value: RawParam): void => { this.setState( - ({ values }: State) => ({ - values: values.map((svalue, sindex) => + ({ values }: State): State => ({ + values: values.map((svalue, sindex): RawParam => (sindex === index) ? value : svalue - )}), - () => { + ) + } as unknown as State), + (): void => { const { values } = this.state; const { onChange } = this.props; onChange && onChange({ - isValid: values.reduce((result: boolean, { isValid }) => result && isValid, true), - value: values.map(({ value }) => value) + isValid: values.reduce((result: boolean, { isValid }): boolean => result && isValid, true), + value: values.map(({ value }): any => value) }); } ); @@ -131,7 +132,7 @@ class Vector extends React.PureComponent { } private rowAdd = (): void => { - this.setState(({ values }: State, { type: { sub } }: Props) => { + this.setState(({ values }: State, { type: { sub } }: Props): State => { const value = getInitValue(sub as TypeDef); return { @@ -139,14 +140,14 @@ class Vector extends React.PureComponent { isValid: !isUndefined(value), value }) - }; + } as unknown as State; }); } private rowRemove = (): void => { - this.setState(({ values }: State) => ({ + this.setState(({ values }: State): State => ({ values: values.slice(0, values.length - 1) - })); + } as unknown as State)); } } diff --git a/packages/ui-params/src/Param/Vote.tsx b/packages/ui-params/src/Param/Vote.tsx index b49ca57308..69c5851bda 100644 --- a/packages/ui-params/src/Param/Vote.tsx +++ b/packages/ui-params/src/Param/Vote.tsx @@ -16,7 +16,7 @@ const options = [ ]; export default class Vote extends React.PureComponent { - render () { + public render (): React.ReactNode { const { className, defaultValue: { value }, isDisabled, isError, label, style, withLabel } = this.props; const defaultValue = value instanceof BN ? value.toNumber() diff --git a/packages/ui-params/src/Param/VoteThreshold.tsx b/packages/ui-params/src/Param/VoteThreshold.tsx index 8c01dabb19..02673933e2 100644 --- a/packages/ui-params/src/Param/VoteThreshold.tsx +++ b/packages/ui-params/src/Param/VoteThreshold.tsx @@ -26,7 +26,7 @@ export const textMap = options.reduce((textMap, { text, value }) => { }, {} as TextMap); export default class VoteThresholdParam extends React.PureComponent { - render () { + public render (): React.ReactNode { const { className, defaultValue: { value }, isDisabled, isError, label, style, withLabel } = this.props; const defaultValue = value instanceof VoteThreshold ? value.toNumber() diff --git a/packages/ui-params/src/Param/findComponent.ts b/packages/ui-params/src/Param/findComponent.ts index 5c93da9cf6..f98e8ac829 100644 --- a/packages/ui-params/src/Param/findComponent.ts +++ b/packages/ui-params/src/Param/findComponent.ts @@ -28,10 +28,10 @@ import Vector from './Vector'; import Vote from './Vote'; import VoteThreshold from './VoteThreshold'; -type TypeToComponent = { - c: React.ComponentType, - t: Array -}; +interface TypeToComponent { + c: React.ComponentType; + t: string[]; +} const components: ComponentMap = ([ { c: Account, t: ['AccountId', 'AccountIdOf', 'Address', 'SessionKey'] }, @@ -54,16 +54,16 @@ const components: ComponentMap = ([ { c: Vote, t: ['Vote'] }, { c: VoteThreshold, t: ['VoteThreshold'] }, { c: Unknown, t: ['Unknown'] } -] as Array).reduce((components, { c, t }) => { - t.forEach((type) => { +] as TypeToComponent[]).reduce((components, { c, t }): ComponentMap => { + t.forEach((type): void => { components[type] = c; }); return components; -}, {} as ComponentMap); +}, {} as unknown as ComponentMap); export default function findComponent (def: TypeDef, overrides: ComponentMap = {}): React.ComponentType { - const type = (({ info, sub, type }: TypeDef) => { + const type = (({ info, sub, type }: TypeDef): string => { switch (info) { case TypeDefInfo.Compact: case TypeDefInfo.Option: @@ -88,7 +88,7 @@ export default function findComponent (def: TypeDef, overrides: ComponentMap = { } })(def); - let Component = overrides[type] || components[type]; + const Component = overrides[type] || components[type]; if (!Component) { try { diff --git a/packages/ui-params/src/Param/index.tsx b/packages/ui-params/src/Param/index.tsx index 45b309b291..0fcee7a768 100644 --- a/packages/ui-params/src/Param/index.tsx +++ b/packages/ui-params/src/Param/index.tsx @@ -13,28 +13,28 @@ import { isUndefined } from '@polkadot/util'; import findComponent from './findComponent'; type Props = I18nProps & BaseProps & { - isDisabled?: boolean, - overrides?: ComponentMap + isDisabled?: boolean; + overrides?: ComponentMap; }; -type State = { - Component: React.ComponentType | null -}; +interface State { + Component: React.ComponentType | null; +} class ParamComponent extends React.PureComponent { - state: State = { + public state: State = { Component: null }; - static getDerivedStateFromProps ({ overrides, type }: Props): State { + public static getDerivedStateFromProps ({ overrides, type }: Props): State { return { Component: !type ? null : findComponent(type, overrides) - } as State; + }; } - render () { + public render (): React.ReactNode { const { Component } = this.state; if (Component === null) { diff --git a/packages/ui-params/src/index.tsx b/packages/ui-params/src/index.tsx index 9a4d014dd9..a594b19676 100644 --- a/packages/ui-params/src/index.tsx +++ b/packages/ui-params/src/index.tsx @@ -4,7 +4,7 @@ import { TypeDef } from '@polkadot/types'; import { I18nProps } from '@polkadot/ui-app/types'; -import { ComponentMap, RawParams, RawParam$OnChange, RawParam$OnChange$Value } from './types'; +import { ComponentMap, RawParam, RawParams, RawParamOnChange, RawParamOnChangeValue } from './types'; import './Params.css'; @@ -15,39 +15,42 @@ import translate from '@polkadot/ui-app/translate'; import Param from './Param'; import createValues from './values'; -type Param = { - name?: string, - type: TypeDef -}; +interface Param { + name?: string; + type: TypeDef; +} -type Props = I18nProps & { - isDisabled?: boolean, - onChange?: (value: RawParams) => void, - onEnter?: () => void, - overrides?: ComponentMap, - params: Array, - values?: RawParams -}; +interface Props extends I18nProps { + isDisabled?: boolean; + onChange?: (value: RawParams) => void; + onEnter?: () => void; + overrides?: ComponentMap; + params: Param[]; + values?: RawParams; +} -type State = { - handlers: Array, - onChangeParam: (at: number, next: RawParam$OnChange$Value) => void, - params: Array, - values: RawParams -}; +interface State { + handlers: RawParamOnChange[]; + onChangeParam: (at: number, next: RawParamOnChangeValue) => void; + params: Param[]; + values: RawParams; +} class Params extends React.PureComponent { - state: State; + public state: State; - constructor (props: Props) { + public constructor (props: Props) { super(props); - this.state = ({ - onChangeParam: this.onChangeParam - } as State); + this.state = { + handlers: [], + onChangeParam: this.onChangeParam, + params: [], + values: [] + }; } - static getDerivedStateFromProps (props: Props, { params, onChangeParam }: State): State | null { + public static getDerivedStateFromProps (props: Props, { params, onChangeParam }: State): State | null { const isSame = JSON.stringify(params) === JSON.stringify(props.params); if (props.isDisabled || isSame) { @@ -56,26 +59,27 @@ class Params extends React.PureComponent { const values = createValues(props.params); const handlers = values.map( - (_, index): RawParam$OnChange => - (value: RawParam$OnChange$Value): void => + (_, index): RawParamOnChange => + (value: RawParamOnChangeValue): void => onChangeParam(index, value) ); return { handlers, + onChangeParam, params: props.params, values - } as State; + }; } // Fire the intial onChange (we did update) when the component is loaded - componentDidMount () { - this.componentDidUpdate({} as Props, {} as State); + public componentDidMount (): void { + this.componentDidUpdate({} as unknown as Props, {} as unknown as State); } - // This is needed in the case where the item changes, i.e. the values get - // initialised and we need to alert the parent that we have new values - componentDidUpdate (_: Props, prevState: State) { + // This is needed in the case where the item changes, i.e. the values get + // initialised and we need to alert the parent that we have new values + public componentDidUpdate (_: Props, prevState: State): void { const { onChange, isDisabled } = this.props; const { values } = this.state; @@ -84,7 +88,7 @@ class Params extends React.PureComponent { } } - render () { + public render (): React.ReactNode { const { className, isDisabled, onEnter, overrides, params, style } = this.props; const { handlers = [], values = this.props.values } = this.state; @@ -98,7 +102,7 @@ class Params extends React.PureComponent { style={style} >

- {params.map(({ name, type }, index) => ( + {params.map(({ name, type }, index): React.ReactNode => ( { ); } - private onChangeParam = (at: number, newValue: RawParam$OnChange$Value): void => { + private onChangeParam = (at: number, newValue: RawParamOnChangeValue): void => { const { isDisabled } = this.props; if (isDisabled) { @@ -126,7 +130,7 @@ class Params extends React.PureComponent { this.setState( (prevState: State): State => ({ - values: prevState.values.map((prev, index) => + values: prevState.values.map((prev, index): RawParam => index !== at ? prev : { @@ -134,7 +138,7 @@ class Params extends React.PureComponent { value } ) - } as State), + } as unknown as State), this.triggerUpdate ); } diff --git a/packages/ui-params/src/initValue.ts b/packages/ui-params/src/initValue.ts index d53bdca222..0d2e4c79b8 100644 --- a/packages/ui-params/src/initValue.ts +++ b/packages/ui-params/src/initValue.ts @@ -2,25 +2,25 @@ // This software may be modified and distributed under the terms // of the Apache-2.0 license. See the LICENSE file for details. -import { RawParam$Value } from './types'; +import { RawParamValue } from './types'; import BN from 'bn.js'; import { Bytes, Hash, TypeDef, TypeDefInfo, U8a, createType, getTypeDef } from '@polkadot/types'; -export default function getInitValue (def: TypeDef): RawParam$Value | Array { +export default function getInitValue (def: TypeDef): RawParamValue | RawParamValue[] { if (def.info === TypeDefInfo.Vector) { return [getInitValue(def.sub as TypeDef)]; } else if (def.info === TypeDefInfo.Tuple) { return Array.isArray(def.sub) - ? def.sub.map((def) => getInitValue(def)) + ? def.sub.map((def): any => getInitValue(def)) : []; } else if (def.info === TypeDefInfo.Struct) { return Array.isArray(def.sub) - ? def.sub.reduce((result, def) => { + ? def.sub.reduce((result, def): Record => { result[def.name as string] = getInitValue(def); return result; - }, {} as { [index: string]: RawParam$Value | Array }) + }, {} as unknown as Record) : {}; } else if (def.info === TypeDefInfo.Enum) { return Array.isArray(def.sub) @@ -77,7 +77,6 @@ export default function getInitValue (def: TypeDef): RawParam$Value | Array>; +export type RawParamValueArray = (RawParamValue | RawParamValue[])[]; -export type RawParam$Values = RawParam$Value | RawParam$ValueArray; +export type RawParamValues = RawParamValue | RawParamValueArray; -export type RawParam = { - isValid: boolean, - value: RawParam$Values -}; +export interface RawParam { + isValid: boolean; + value: RawParamValues; +} -export type RawParam$OnChange$Value = { isValid: boolean, value: RawParam$Values }; -export type RawParam$OnChange = (value: RawParam$OnChange$Value) => void; -export type RawParam$OnEnter = () => void; +export interface RawParamOnChangeValue { + isValid: boolean; + value: RawParamValues; +} +export type RawParamOnChange = (value: RawParamOnChangeValue) => void; +export type RawParamOnEnter = () => void; -export type RawParams = Array; +export type RawParams = RawParam[]; -export type BaseProps = BareProps & { - defaultValue: RawParam, - name?: string, - onChange?: RawParam$OnChange, - onEnter?: RawParam$OnEnter, - type: TypeDef -}; +export interface BaseProps extends BareProps { + defaultValue: RawParam; + name?: string; + onChange?: RawParamOnChange; + onEnter?: RawParamOnEnter; + type: TypeDef; +} -export type Props = BaseProps & { - isDisabled?: boolean, - isError?: boolean, - isReadOnly?: boolean, - label?: React.ReactNode, - withLabel?: boolean -}; +export interface Props extends BaseProps { + isDisabled?: boolean; + isError?: boolean; + isReadOnly?: boolean; + label?: React.ReactNode; + withLabel?: boolean; +} export type Size = 'full' | 'large' | 'medium' | 'small'; -export type ComponentMap = { - [index: string]: React.ComponentType -}; +export type ComponentMap = Record>; diff --git a/packages/ui-params/src/valueToText.tsx b/packages/ui-params/src/valueToText.tsx index 0d65909ec7..b158669599 100644 --- a/packages/ui-params/src/valueToText.tsx +++ b/packages/ui-params/src/valueToText.tsx @@ -9,14 +9,12 @@ import { classes } from '@polkadot/ui-app/util'; import { isNull, isUndefined, u8aToHex } from '@polkadot/util'; import { Option, U8a } from '@polkadot/types'; -const unknown = div({}, ''); +interface DivProps { + className?: string; + key?: any; +} -type DivProps = { - className?: string, - key?: any -}; - -function div ({ key, className }: DivProps, ...values: Array): React.ReactNode { +function div ({ key, className }: DivProps, ...values: React.ReactNode[]): React.ReactNode { return (
): ); } +const unknown = div({}, ''); + +// eslint-disable-next-line @typescript-eslint/no-unused-vars function valueToText (type: string, value: any, swallowError: boolean = true, contentShorten: boolean = true): React.ReactNode { // dont' even ask, nested ?: ... really? return isNull(value) || isUndefined(value) diff --git a/packages/ui-params/src/values.ts b/packages/ui-params/src/values.ts index ef2db3a2c3..57e9e7f082 100644 --- a/packages/ui-params/src/values.ts +++ b/packages/ui-params/src/values.ts @@ -9,7 +9,7 @@ import { isUndefined } from '@polkadot/util'; import getInitValue from './initValue'; -export default function values (params: Array<{ type: TypeDef }>): Array { +export default function values (params: { type: TypeDef }[]): RawParam[] { return params.map(({ type }): RawParam => { const value = getInitValue(type); diff --git a/packages/ui-reactive/src/AccountIndex.tsx b/packages/ui-reactive/src/AccountIndex.tsx index 21358ac3ee..cfef33424f 100644 --- a/packages/ui-reactive/src/AccountIndex.tsx +++ b/packages/ui-reactive/src/AccountIndex.tsx @@ -1,3 +1,4 @@ +/* eslint-disable @typescript-eslint/camelcase */ // Copyright 2017-2019 @polkadot/ui-reactive authors & contributors // This software may be modified and distributed under the terms // of the Apache-2.0 license. See the LICENSE file for details. @@ -9,14 +10,14 @@ import { AccountId, AccountIndex } from '@polkadot/types'; import { withCalls } from '@polkadot/ui-api'; type Props = BareProps & CallProps & { - children?: React.ReactNode, - label?: React.ReactNode, - params?: string, - accounts_idAndIndex?: [AccountId?, AccountIndex?] + children?: React.ReactNode; + label?: React.ReactNode; + params?: string; + accounts_idAndIndex?: [AccountId?, AccountIndex?]; }; export class AccountIndexDisplay extends React.PureComponent { - render () { + public render (): React.ReactNode { const { children, className, label = '', style, accounts_idAndIndex = [] } = this.props; const [, accountIndex] = accounts_idAndIndex; @@ -29,7 +30,7 @@ export class AccountIndexDisplay extends React.PureComponent { accountIndex ? accountIndex.toString() : '-' - }{children} + }{children}
); } diff --git a/packages/ui-reactive/src/Available.tsx b/packages/ui-reactive/src/Available.tsx index 17dc945b84..85d11b0e2f 100644 --- a/packages/ui-reactive/src/Available.tsx +++ b/packages/ui-reactive/src/Available.tsx @@ -1,3 +1,4 @@ +/* eslint-disable @typescript-eslint/camelcase */ // Copyright 2017-2019 @polkadot/ui-reactive authors & contributors // This software may be modified and distributed under the terms // of the Apache-2.0 license. See the LICENSE file for details. @@ -11,22 +12,22 @@ import { formatBalance } from '@polkadot/util'; import { withCalls } from '@polkadot/ui-api'; type Props = BareProps & CallProps & { - balances_all?: DerivedBalances, - children?: React.ReactNode, - label?: React.ReactNode, - params?: AccountId | AccountIndex | Address | string | Uint8Array | null + balances_all?: DerivedBalances; + children?: React.ReactNode; + label?: React.ReactNode; + params?: AccountId | AccountIndex | Address | string | Uint8Array | null; }; export class AvailableDisplay extends React.PureComponent { - render () { + public render (): React.ReactNode { const { balances_all, children, className, label = '' } = this.props; return (
{label}{ - balances_all ? - formatBalance(balances_all.availableBalance) : - '0' + balances_all + ? formatBalance(balances_all.availableBalance) + : '0' }{children}
); diff --git a/packages/ui-reactive/src/Balance.tsx b/packages/ui-reactive/src/Balance.tsx index f85c79c760..3186d85a7e 100644 --- a/packages/ui-reactive/src/Balance.tsx +++ b/packages/ui-reactive/src/Balance.tsx @@ -1,3 +1,4 @@ +/* eslint-disable @typescript-eslint/camelcase */ // Copyright 2017-2019 @polkadot/ui-reactive authors & contributors // This software may be modified and distributed under the terms // of the Apache-2.0 license. See the LICENSE file for details. @@ -12,14 +13,14 @@ import { withCalls } from '@polkadot/ui-api'; import { formatBalance } from '@polkadot/util'; type Props = BareProps & CallProps & { - children?: React.ReactNode, - label?: React.ReactNode, - params?: AccountId | AccountIndex | Address | string | Uint8Array | null, - balances_all?: DerivedBalances + children?: React.ReactNode; + label?: React.ReactNode; + params?: AccountId | AccountIndex | Address | string | Uint8Array | null; + balances_all?: DerivedBalances; }; export class BalanceDisplay extends React.PureComponent { - render () { + public render (): React.ReactNode { const { children, className, label = '', balances_all } = this.props; return ( @@ -28,7 +29,7 @@ export class BalanceDisplay extends React.PureComponent { balances_all ? formatBalance(balances_all.freeBalance) : '0' - }{children} + }{children}
); } diff --git a/packages/ui-reactive/src/BestFinalized.tsx b/packages/ui-reactive/src/BestFinalized.tsx index d860337525..1c3f1863d5 100644 --- a/packages/ui-reactive/src/BestFinalized.tsx +++ b/packages/ui-reactive/src/BestFinalized.tsx @@ -1,3 +1,4 @@ +/* eslint-disable @typescript-eslint/camelcase */ // Copyright 2017-2019 @polkadot/ui-reactive authors & contributors // This software may be modified and distributed under the terms // of the Apache-2.0 license. See the LICENSE file for details. @@ -10,13 +11,13 @@ import { withCalls } from '@polkadot/ui-api'; import { formatNumber } from '@polkadot/util'; type Props = BareProps & CallProps & { - children?: React.ReactNode, - label?: React.ReactNode, - chain_bestNumberFinalized?: BlockNumber + children?: React.ReactNode; + label?: React.ReactNode; + chain_bestNumberFinalized?: BlockNumber; }; export class BestFinalized extends React.PureComponent { - render () { + public render (): React.ReactNode { const { children, className, label = '', style, chain_bestNumberFinalized } = this.props; return ( @@ -28,7 +29,7 @@ export class BestFinalized extends React.PureComponent { chain_bestNumberFinalized ? formatNumber(chain_bestNumberFinalized) : '-' - }{children} + }{children}
); } diff --git a/packages/ui-reactive/src/BestNumber.tsx b/packages/ui-reactive/src/BestNumber.tsx index 6be68e3ae5..f30ee65f29 100644 --- a/packages/ui-reactive/src/BestNumber.tsx +++ b/packages/ui-reactive/src/BestNumber.tsx @@ -1,3 +1,4 @@ +/* eslint-disable @typescript-eslint/camelcase */ // Copyright 2017-2019 @polkadot/ui-reactive authors & contributors // This software may be modified and distributed under the terms // of the Apache-2.0 license. See the LICENSE file for details. @@ -10,13 +11,13 @@ import { withCalls } from '@polkadot/ui-api'; import { formatNumber } from '@polkadot/util'; type Props = BareProps & CallProps & { - children?: React.ReactNode, - label?: React.ReactNode, - chain_bestNumber?: BlockNumber + children?: React.ReactNode; + label?: React.ReactNode; + chain_bestNumber?: BlockNumber; }; export class BestNumber extends React.PureComponent { - render () { + public render (): React.ReactNode { const { children, className, label = '', style, chain_bestNumber } = this.props; return ( diff --git a/packages/ui-reactive/src/Bonded.tsx b/packages/ui-reactive/src/Bonded.tsx index 5535f39cbc..650a3a4317 100644 --- a/packages/ui-reactive/src/Bonded.tsx +++ b/packages/ui-reactive/src/Bonded.tsx @@ -1,3 +1,4 @@ +/* eslint-disable @typescript-eslint/camelcase */ // Copyright 2017-2019 @polkadot/ui-reactive authors & contributors // This software may be modified and distributed under the terms // of the Apache-2.0 license. See the LICENSE file for details. @@ -11,14 +12,14 @@ import { withCalls } from '@polkadot/ui-api'; import { formatBalance } from '@polkadot/util'; type Props = BareProps & CallProps & { - children?: React.ReactNode, - params?: AccountId | AccountIndex | Address | string | Uint8Array | null, - label?: React.ReactNode, - staking_ledger?: StakingLedger | null + children?: React.ReactNode; + params?: AccountId | AccountIndex | Address | string | Uint8Array | null; + label?: React.ReactNode; + staking_ledger?: StakingLedger | null; }; export class BondedDisplay extends React.PureComponent { - render () { + public render (): React.ReactNode { const { children, className, label = '', staking_ledger } = this.props; return ( @@ -37,12 +38,12 @@ export default withCalls( ['query.staking.bonded', { paramName: 'params', propName: 'controllerId', - transform: (value) => + transform: (value): AccountId | null => value.unwrapOr(null) }], ['query.staking.ledger', { paramName: 'controllerId', - transform: (value) => + transform: (value): StakingLedger | null => value.unwrapOr(null) }] )(BondedDisplay); diff --git a/packages/ui-reactive/src/Chain.tsx b/packages/ui-reactive/src/Chain.tsx index da95c60834..1f23da5525 100644 --- a/packages/ui-reactive/src/Chain.tsx +++ b/packages/ui-reactive/src/Chain.tsx @@ -1,3 +1,4 @@ +/* eslint-disable @typescript-eslint/camelcase */ // Copyright 2017-2019 @polkadot/ui-reactive authors & contributors // This software may be modified and distributed under the terms // of the Apache-2.0 license. See the LICENSE file for details. @@ -9,13 +10,13 @@ import { Text } from '@polkadot/types'; import { withCalls } from '@polkadot/ui-api'; type Props = BareProps & CallProps & { - children?: React.ReactNode, - label?: React.ReactNode, - system_chain?: Text + children?: React.ReactNode; + label?: React.ReactNode; + system_chain?: Text; }; export class Chain extends React.PureComponent { - render () { + public render (): React.ReactNode { const { children, className, label = '', style, system_chain = 'unknown' } = this.props; return ( diff --git a/packages/ui-reactive/src/Elapsed.tsx b/packages/ui-reactive/src/Elapsed.tsx index 1f37eb25dc..65bff12d90 100644 --- a/packages/ui-reactive/src/Elapsed.tsx +++ b/packages/ui-reactive/src/Elapsed.tsx @@ -7,18 +7,20 @@ import { BareProps } from '@polkadot/ui-api/types'; import React from 'react'; import { Moment } from '@polkadot/types'; -type Props = BareProps & { - value?: Moment | Date | number -}; +type Ticker = (now: Date) => void; -type State = { - now?: Date -}; +interface Props extends BareProps { + value?: Moment | Date | number; +} + +interface State { + now?: Date; +} const TICK_TIMEOUT = 100; -const tickers = new Map void>(); +const tickers = new Map(); -function tick () { +function tick (): void { const now = new Date(); for (const ticker of tickers.values()) { @@ -33,7 +35,7 @@ tick(); export default class Elapsed extends React.PureComponent { public state: State = {}; - public componentWillMount () { + public componentWillMount (): void { tickers.set(this, (now: Date): void => { this.setState({ now @@ -41,11 +43,11 @@ export default class Elapsed extends React.PureComponent { }); } - public componentWillUnmount () { + public componentWillUnmount (): void { tickers.delete(this); } - public render () { + public render (): React.ReactNode { const { className, style, value } = this.props; const { now } = this.state; diff --git a/packages/ui-reactive/src/NodeName.tsx b/packages/ui-reactive/src/NodeName.tsx index 35fc15af37..812654c1ac 100644 --- a/packages/ui-reactive/src/NodeName.tsx +++ b/packages/ui-reactive/src/NodeName.tsx @@ -1,3 +1,4 @@ +/* eslint-disable @typescript-eslint/camelcase */ // Copyright 2017-2019 @polkadot/ui-reactive authors & contributors // This software may be modified and distributed under the terms // of the Apache-2.0 license. See the LICENSE file for details. @@ -9,13 +10,13 @@ import { Text } from '@polkadot/types'; import { withCalls } from '@polkadot/ui-api'; type Props = BareProps & CallProps & { - children?: React.ReactNode, - label?: React.ReactNode, - system_name?: Text + children?: React.ReactNode; + label?: React.ReactNode; + system_name?: Text; }; export class NodeName extends React.PureComponent { - render () { + public render (): React.ReactNode { const { children, className, label = '', style, system_name = 'unknown' } = this.props; return ( diff --git a/packages/ui-reactive/src/NodeVersion.tsx b/packages/ui-reactive/src/NodeVersion.tsx index 223494b338..6a77138e46 100644 --- a/packages/ui-reactive/src/NodeVersion.tsx +++ b/packages/ui-reactive/src/NodeVersion.tsx @@ -1,3 +1,4 @@ +/* eslint-disable @typescript-eslint/camelcase */ // Copyright 2017-2019 @polkadot/ui-reactive authors & contributors // This software may be modified and distributed under the terms // of the Apache-2.0 license. See the LICENSE file for details. @@ -9,13 +10,13 @@ import { Text } from '@polkadot/types'; import { withCalls } from '@polkadot/ui-api'; type Props = BareProps & CallProps & { - children?: React.ReactNode, - label?: React.ReactNode, - system_version?: Text + children?: React.ReactNode; + label?: React.ReactNode; + system_version?: Text; }; export class NodeVersion extends React.PureComponent { - render () { + public render (): React.ReactNode { const { children, className, label = '', style, system_version = '-' } = this.props; return ( diff --git a/packages/ui-reactive/src/Nonce.tsx b/packages/ui-reactive/src/Nonce.tsx index 7f3aeeb2a6..6ab5a7961c 100644 --- a/packages/ui-reactive/src/Nonce.tsx +++ b/packages/ui-reactive/src/Nonce.tsx @@ -11,15 +11,15 @@ import { formatNumber } from '@polkadot/util'; import { withCalls } from '@polkadot/ui-api'; type Props = BareProps & CallProps & { - accountNonce?: BN, - callOnResult?: (accountNonce: BN) => void, - children?: React.ReactNode, - label?: React.ReactNode, - params?: string + accountNonce?: BN; + callOnResult?: (accountNonce: BN) => void; + children?: React.ReactNode; + label?: React.ReactNode; + params?: string; }; export class Nonce extends React.PureComponent { - render () { + public render (): React.ReactNode { const { accountNonce, children, className, label = '' } = this.props; return ( @@ -38,7 +38,7 @@ export default withCalls( ['derive.balances.all', { paramName: 'params', propName: 'accountNonce', - transform: ({ accountNonce }: DerivedBalances) => + transform: ({ accountNonce }: DerivedBalances): BN => accountNonce }] )(Nonce); diff --git a/packages/ui-reactive/src/TimeNow.tsx b/packages/ui-reactive/src/TimeNow.tsx index 0dee28bf49..934017bef4 100644 --- a/packages/ui-reactive/src/TimeNow.tsx +++ b/packages/ui-reactive/src/TimeNow.tsx @@ -1,3 +1,4 @@ +/* eslint-disable @typescript-eslint/camelcase */ // Copyright 2017-2019 @polkadot/ui-reactive authors & contributors // This software may be modified and distributed under the terms // of the Apache-2.0 license. See the LICENSE file for details. @@ -11,13 +12,13 @@ import { withCalls } from '@polkadot/ui-api'; import Elapsed from './Elapsed'; type Props = BareProps & CallProps & { - children?: React.ReactNode, - label?: React.ReactNode, - timestamp_now?: Moment + children?: React.ReactNode; + label?: React.ReactNode; + timestamp_now?: Moment; }; export class TimeNow extends React.PureComponent { - render () { + public render (): React.ReactNode { const { children, className, label = '', style, timestamp_now } = this.props; return ( diff --git a/packages/ui-reactive/src/TimePeriod.tsx b/packages/ui-reactive/src/TimePeriod.tsx index e1d1455309..935e64ca41 100644 --- a/packages/ui-reactive/src/TimePeriod.tsx +++ b/packages/ui-reactive/src/TimePeriod.tsx @@ -1,3 +1,4 @@ +/* eslint-disable @typescript-eslint/camelcase */ // Copyright 2017-2019 @polkadot/ui-reactive authors & contributors // This software may be modified and distributed under the terms // of the Apache-2.0 license. See the LICENSE file for details. @@ -10,14 +11,14 @@ import { withCalls } from '@polkadot/ui-api'; import { formatNumber } from '@polkadot/util'; type Props = BareProps & CallProps & { - children?: React.ReactNode, - label?: React.ReactNode, - timestamp_blockPeriod?: Moment | Option, // support for previous - timestamp_minimumPeriod?: Moment // support for new version + children?: React.ReactNode; + label?: React.ReactNode; + timestamp_blockPeriod?: Moment | Option; // support for previous + timestamp_minimumPeriod?: Moment; // support for new version }; export class TimePeriod extends React.PureComponent { - render () { + public render (): React.ReactNode { const { children, className, label = '', style, timestamp_blockPeriod, timestamp_minimumPeriod } = this.props; const period = timestamp_minimumPeriod || ( timestamp_blockPeriod diff --git a/packages/ui-reactive/src/TotalIssuance.tsx b/packages/ui-reactive/src/TotalIssuance.tsx index f29b6452d2..5b6dd07f18 100644 --- a/packages/ui-reactive/src/TotalIssuance.tsx +++ b/packages/ui-reactive/src/TotalIssuance.tsx @@ -1,3 +1,4 @@ +/* eslint-disable @typescript-eslint/camelcase */ // Copyright 2017-2019 @polkadot/ui-reactive authors & contributors // This software may be modified and distributed under the terms // of the Apache-2.0 license. See the LICENSE file for details. @@ -10,13 +11,13 @@ import { withCalls } from '@polkadot/ui-api'; import { formatBalance } from '@polkadot/util'; type Props = BareProps & CallProps & { - children?: React.ReactNode, - label?: React.ReactNode, - balances_totalIssuance?: Balance + children?: React.ReactNode; + label?: React.ReactNode; + balances_totalIssuance?: Balance; }; export class TotalIssuance extends React.PureComponent { - render () { + public render (): React.ReactNode { const { children, className, label = '', style, balances_totalIssuance } = this.props; const value = balances_totalIssuance ? balances_totalIssuance.toString() @@ -31,7 +32,7 @@ export class TotalIssuance extends React.PureComponent { value ? `${formatBalance(value, false)}${formatBalance.calcSi(value).value}` : '-' - }{children} + }{children}
); } diff --git a/packages/ui-signer/src/ApiSigner.ts b/packages/ui-signer/src/ApiSigner.ts index a45a916afb..7c36a95658 100644 --- a/packages/ui-signer/src/ApiSigner.ts +++ b/packages/ui-signer/src/ApiSigner.ts @@ -5,22 +5,23 @@ import { Signer } from '@polkadot/api/types'; import { SubmittableResult } from '@polkadot/api'; import { SubmittableExtrinsic } from '@polkadot/api/promise/types'; -import { QueueTx$ExtrinsicAdd, QueueTx$MessageSetStatus } from '@polkadot/ui-app/Status/types'; +import { QueueTxExtrinsicAdd, QueueTxMessageSetStatus, QueueTxStatus } from '@polkadot/ui-app/Status/types'; import { SignatureOptions } from '@polkadot/types/types'; import { Hash } from '@polkadot/types'; export default class ApiSigner implements Signer { - private _queueExtrinsic: QueueTx$ExtrinsicAdd; - private _queueSetTxStatus: QueueTx$MessageSetStatus; + private _queueExtrinsic: QueueTxExtrinsicAdd; - constructor (queueExtrinsic: QueueTx$ExtrinsicAdd, queueSetTxStatus: QueueTx$MessageSetStatus) { + private _queueSetTxStatus: QueueTxMessageSetStatus; + + public constructor (queueExtrinsic: QueueTxExtrinsicAdd, queueSetTxStatus: QueueTxMessageSetStatus) { this._queueExtrinsic = queueExtrinsic; this._queueSetTxStatus = queueSetTxStatus; } - async sign (extrinsic: SubmittableExtrinsic, accountId: string, signerOptions: SignatureOptions): Promise { - return new Promise((resolve, reject) => { + public async sign (extrinsic: SubmittableExtrinsic, accountId: string, signerOptions: SignatureOptions): Promise { + return new Promise((resolve, reject): void => { this._queueExtrinsic({ accountId, extrinsic, @@ -29,18 +30,18 @@ export default class ApiSigner implements Signer { if (isSigned) { resolve(id); } else { - reject(); + reject(new Error()); } } }); }); } - update (id: number, result: Hash | SubmittableResult): void { + public update (id: number, result: Hash | SubmittableResult): void { if (result instanceof Hash) { this._queueSetTxStatus(id, 'sent', result.toHex()); } else { - this._queueSetTxStatus(id, result.status.type.toLowerCase() as any, status); + this._queueSetTxStatus(id, result.status.type.toLowerCase() as QueueTxStatus, status); } } } diff --git a/packages/ui-signer/src/Checks/ContractCall.tsx b/packages/ui-signer/src/Checks/ContractCall.tsx index 623699823c..f8ebb4640c 100644 --- a/packages/ui-signer/src/Checks/ContractCall.tsx +++ b/packages/ui-signer/src/Checks/ContractCall.tsx @@ -9,25 +9,26 @@ import BN from 'bn.js'; import React from 'react'; import { Compact } from '@polkadot/types'; -type Props = { - endowment: BN | Compact, - fees: DerivedContractFees, - onChange: (fees: ExtraFees) => void -}; +interface Props { + endowment: BN | Compact; + fees: DerivedContractFees; + onChange: (fees: ExtraFees) => void; +} -type State = ExtraFees & {}; +type State = ExtraFees; export default class ContractCall extends React.PureComponent { - state: State = { + public state: State = { extraFees: new BN(0), extraAmount: new BN(0), extraWarn: false }; - static getDerivedStateFromProps ({ endowment, fees, onChange }: Props, state: State) { - let extraFees = new BN(fees.callBaseFee); - - const extraAmount = endowment instanceof Compact ? endowment.toBn() : new BN(endowment || 0); + public static getDerivedStateFromProps ({ endowment, fees, onChange }: Props, state: State): State { + const extraFees = new BN(fees.callBaseFee); + const extraAmount = endowment instanceof Compact + ? endowment.toBn() + : new BN(endowment || 0); const update = { extraAmount, @@ -42,7 +43,7 @@ export default class ContractCall extends React.PureComponent { return update; } - render () { + public render (): React.ReactNode { return null; } } diff --git a/packages/ui-signer/src/Checks/ContractDeploy.tsx b/packages/ui-signer/src/Checks/ContractDeploy.tsx index 5fe29324bb..5f05b6adc0 100644 --- a/packages/ui-signer/src/Checks/ContractDeploy.tsx +++ b/packages/ui-signer/src/Checks/ContractDeploy.tsx @@ -9,26 +9,26 @@ import BN from 'bn.js'; import React from 'react'; import { Compact } from '@polkadot/types'; -type Props = { - endowment: BN | Compact, - fees: DerivedContractFees, - onChange: (fees: ExtraFees) => void -}; +interface Props { + endowment: BN | Compact; + fees: DerivedContractFees; + onChange: (fees: ExtraFees) => void; +} -type State = ExtraFees & {}; +type State = ExtraFees; export default class ContractDeploy extends React.PureComponent { - state: State = { + public state: State = { extraFees: new BN(0), extraAmount: new BN(0), extraWarn: false }; - static getDerivedStateFromProps ({ endowment, fees, onChange }: Props, state: State) { - let extraFees = new BN(fees.createBaseFee) - .add(fees.contractFee); - - const extraAmount = endowment instanceof Compact ? endowment.toBn() : new BN(endowment || 0); + public static getDerivedStateFromProps ({ endowment, fees, onChange }: Props, state: State): State { + const extraFees = new BN(fees.createBaseFee).add(fees.contractFee); + const extraAmount = endowment instanceof Compact + ? endowment.toBn() + : new BN(endowment || 0); const update = { extraAmount, @@ -43,7 +43,7 @@ export default class ContractDeploy extends React.PureComponent { return update; } - render () { + public render (): React.ReactNode { return null; } } diff --git a/packages/ui-signer/src/Checks/Proposal.tsx b/packages/ui-signer/src/Checks/Proposal.tsx index 8b4daa5b97..05a391b7f9 100644 --- a/packages/ui-signer/src/Checks/Proposal.tsx +++ b/packages/ui-signer/src/Checks/Proposal.tsx @@ -1,3 +1,4 @@ +/* eslint-disable @typescript-eslint/camelcase */ // Copyright 2017-2019 @polkadot/ui-signer authors & contributors // This software may be modified and distributed under the terms // of the Apache-2.0 license. See the LICENSE file for details. @@ -15,25 +16,26 @@ import { formatBalance } from '@polkadot/util'; import translate from '../translate'; -type Props = I18nProps & { - deposit: BN | Compact, - fees: DerivedFees, - democracy_minimumDeposit?: BN - onChange: (fees: ExtraFees) => void -}; -type State = ExtraFees & { - isBelowMinimum: boolean -}; +interface Props extends I18nProps { + deposit: BN | Compact; + fees: DerivedFees; + democracy_minimumDeposit?: BN; + onChange: (fees: ExtraFees) => void; +} + +interface State extends ExtraFees { + isBelowMinimum: boolean; +} export class Proposal extends React.PureComponent { - state: State = { + public state: State = { extraFees: new BN(0), extraAmount: new BN(0), extraWarn: false, isBelowMinimum: false }; - static getDerivedStateFromProps ({ deposit, democracy_minimumDeposit = new BN(0), onChange }: Props): State { + public static getDerivedStateFromProps ({ deposit, democracy_minimumDeposit = new BN(0), onChange }: Props): State { const extraAmount = deposit instanceof Compact ? deposit.toBn() : deposit; @@ -53,7 +55,7 @@ export class Proposal extends React.PureComponent { }; } - render () { + public render (): React.ReactNode { const { democracy_minimumDeposit = new BN(0), t } = this.props; const { extraAmount, isBelowMinimum } = this.state; diff --git a/packages/ui-signer/src/Checks/Transfer.tsx b/packages/ui-signer/src/Checks/Transfer.tsx index 361e191fcc..28bc97a4ec 100644 --- a/packages/ui-signer/src/Checks/Transfer.tsx +++ b/packages/ui-signer/src/Checks/Transfer.tsx @@ -1,3 +1,4 @@ +/* eslint-disable @typescript-eslint/camelcase */ // Copyright 2017-2019 @polkadot/ui-signer authors & contributors // This software may be modified and distributed under the terms // of the Apache-2.0 license. See the LICENSE file for details. @@ -16,21 +17,21 @@ import { formatBalance } from '@polkadot/util'; import translate from '../translate'; import { ZERO_BALANCE } from './constants'; -type Props = I18nProps & { - amount: BN | Compact, - fees: DerivedFees, - balances_all?: DerivedBalances, - recipientId: string, - onChange: (fees: ExtraFees) => void -}; +interface Props extends I18nProps { + amount: BN | Compact; + fees: DerivedFees; + balances_all?: DerivedBalances; + recipientId: string; + onChange: (fees: ExtraFees) => void; +} -type State = ExtraFees & { - isCreation: boolean, - isNoEffect: boolean -}; +interface State extends ExtraFees { + isCreation: boolean; + isNoEffect: boolean; +} export class Transfer extends React.PureComponent { - state: State = { + public state: State = { extraFees: new BN(0), extraAmount: new BN(0), extraWarn: false, @@ -38,7 +39,7 @@ export class Transfer extends React.PureComponent { isNoEffect: false }; - static getDerivedStateFromProps ({ amount, balances_all = ZERO_BALANCE, fees, onChange }: Props): State { + public static getDerivedStateFromProps ({ amount, balances_all = ZERO_BALANCE, fees, onChange }: Props): State { let extraFees = new BN(fees.transferFee); if (balances_all.votingBalance.isZero()) { @@ -64,7 +65,7 @@ export class Transfer extends React.PureComponent { }; } - render () { + public render (): React.ReactNode { const { fees, t } = this.props; const { isCreation, isNoEffect } = this.state; @@ -72,7 +73,8 @@ export class Transfer extends React.PureComponent { <> { isNoEffect - ?
+ ? ( +
{t('The final recipient balance is less or equal to {{existentialDeposit}} (the existential amount) and will not be reflected', { @@ -82,6 +84,7 @@ export class Transfer extends React.PureComponent { } )}
+ ) : undefined } { diff --git a/packages/ui-signer/src/Checks/constants.ts b/packages/ui-signer/src/Checks/constants.ts index f5b5b91d0a..f1a089a489 100644 --- a/packages/ui-signer/src/Checks/constants.ts +++ b/packages/ui-signer/src/Checks/constants.ts @@ -5,27 +5,30 @@ import { DerivedFees, DerivedBalances, DerivedContractFees } from '@polkadot/api-derive/types'; import BN from 'bn.js'; +import { AccountId, Nonce } from '@polkadot/types'; -export const ZERO_BALANCE = { +const ZERO_BALANCE: DerivedBalances = { + accountId: new AccountId(), + accountNonce: new Nonce(0), availableBalance: new BN(0), lockedBalance: new BN(0), freeBalance: new BN(0), reservedBalance: new BN(0), vestedBalance: new BN(0), votingBalance: new BN(0) -} as DerivedBalances; +}; -export const ZERO_FEES_BALANCES = { +const ZERO_FEES_BALANCES: DerivedFees = { transactionBaseFee: new BN(0), transactionByteFee: new BN(0), creationFee: new BN(0), existentialDeposit: new BN(0), transferFee: new BN(0) -} as DerivedFees; +}; -export const ZERO_FEES = ZERO_FEES_BALANCES; +const ZERO_FEES = ZERO_FEES_BALANCES; -export const ZERO_FEES_CONTRACT = { +const ZERO_FEES_CONTRACT: DerivedContractFees = { callBaseFee: new BN(0), contractFee: new BN(0), createBaseFee: new BN(0), @@ -36,7 +39,16 @@ export const ZERO_FEES_CONTRACT = { transactionByteFee: new BN(0), transferFee: new BN(0), tombstoneDeposit: new BN(0) -} as DerivedContractFees; +}; -export const MAX_SIZE_MB = 10; -export const MAX_SIZE_BYTES = MAX_SIZE_MB * 1024 * 1024; +const MAX_SIZE_MB = 10; +const MAX_SIZE_BYTES = MAX_SIZE_MB * 1024 * 1024; + +export { + ZERO_BALANCE, + ZERO_FEES, + ZERO_FEES_BALANCES, + ZERO_FEES_CONTRACT, + MAX_SIZE_BYTES, + MAX_SIZE_MB +}; diff --git a/packages/ui-signer/src/Checks/index.tsx b/packages/ui-signer/src/Checks/index.tsx index 3a933687e5..95c0bebe18 100644 --- a/packages/ui-signer/src/Checks/index.tsx +++ b/packages/ui-signer/src/Checks/index.tsx @@ -1,3 +1,4 @@ +/* eslint-disable @typescript-eslint/camelcase */ // Copyright 2017-2019 @polkadot/ui-signer authors & contributors // This software may be modified and distributed under the terms // of the Apache-2.0 license. See the LICENSE file for details. @@ -21,28 +22,28 @@ import Proposal from './Proposal'; import Transfer from './Transfer'; import { MAX_SIZE_BYTES, MAX_SIZE_MB, ZERO_BALANCE, ZERO_FEES_BALANCES, ZERO_FEES_CONTRACT } from './constants'; -type State = ExtraFees & { - allFees: BN, - allTotal: BN, - allWarn: boolean, - extMethod?: string, - extSection?: string, - hasAvailable: boolean, - isRemovable: boolean, - isReserved: boolean, - overLimit: boolean -}; +interface State extends ExtraFees { + allFees: BN; + allTotal: BN; + allWarn: boolean; + extMethod?: string; + extSection?: string; + hasAvailable: boolean; + isRemovable: boolean; + isReserved: boolean; + overLimit: boolean; +} -type Props = I18nProps & { - balances_fees?: DerivedFees, - balances_all?: DerivedBalances, - contract_fees?: DerivedContractFees, - accountId?: string | null, - extrinsic?: IExtrinsic | null, - isSendable: boolean, - onChange?: (hasAvailable: boolean) => void, - system_accountNonce?: BN -}; +interface Props extends I18nProps { + balances_fees?: DerivedFees; + balances_all?: DerivedBalances; + contract_fees?: DerivedContractFees; + accountId?: string | null; + extrinsic?: IExtrinsic | null; + isSendable: boolean; + onChange?: (hasAvailable: boolean) => void; + system_accountNonce?: BN; +} const LENGTH_PUBLICKEY = 32 + 1; // publicKey + prefix const LENGTH_SIGNATURE = 64; @@ -56,7 +57,7 @@ export const calcSignatureLength = (extrinsic?: IExtrinsic | null, accountNonce? }; export class FeeDisplay extends React.PureComponent { - state: State = { + public state: State = { allFees: new BN(0), allTotal: new BN(0), allWarn: false, @@ -69,7 +70,7 @@ export class FeeDisplay extends React.PureComponent { overLimit: false }; - static getDerivedStateFromProps ({ accountId, balances_all = ZERO_BALANCE, extrinsic, balances_fees = ZERO_FEES_BALANCES, system_accountNonce = new BN(0) }: Props, prevState: State): State | null { + public static getDerivedStateFromProps ({ accountId, balances_all = ZERO_BALANCE, extrinsic, balances_fees = ZERO_FEES_BALANCES, system_accountNonce = new BN(0) }: Props, prevState: State): State | null { if (!accountId || !extrinsic) { return null; } @@ -116,14 +117,14 @@ export class FeeDisplay extends React.PureComponent { }; } - componentDidUpdate () { + public componentDidUpdate (): void { const { onChange } = this.props; const { hasAvailable } = this.state; onChange && onChange(hasAvailable); } - render () { + public render (): React.ReactNode { const { accountId, balances_fees, className, isSendable, t } = this.props; const { allFees, allTotal, allWarn, hasAvailable, isRemovable, isReserved, overLimit } = this.state; @@ -157,12 +158,13 @@ export class FeeDisplay extends React.PureComponent { } { overLimit - ?
{t(`This transaction will be rejected by the node as it is greater than the maximum size of ${MAX_SIZE_MB}MB`)}>
+ ?
{t(`This transaction will be rejected by the node as it is greater than the maximum size of ${MAX_SIZE_MB}MB`)}
: undefined } { isRemovable && hasAvailable - ?
+ ? ( +
{t('Submitting this transaction will drop the account balance to below the existential amount ({{existentialDeposit}}), which can result in the account being removed from the chain state and its associated funds burned.', { @@ -172,6 +174,7 @@ export class FeeDisplay extends React.PureComponent { } )}
+ ) : undefined } {this.renderTransfer()} @@ -198,7 +201,7 @@ export class FeeDisplay extends React.PureComponent { ); } - private renderProposal () { + private renderProposal (): React.ReactNode { const { extrinsic, balances_fees } = this.props; const { extMethod, extSection } = this.state; @@ -217,7 +220,7 @@ export class FeeDisplay extends React.PureComponent { ); } - private renderTransfer () { + private renderTransfer (): React.ReactNode { const { extrinsic, balances_fees } = this.props; const { extMethod, extSection } = this.state; @@ -237,7 +240,7 @@ export class FeeDisplay extends React.PureComponent { ); } - private renderCall () { + private renderCall (): React.ReactNode { const { extrinsic, contract_fees = ZERO_FEES_CONTRACT } = this.props; const { extMethod, extSection } = this.state; @@ -249,14 +252,14 @@ export class FeeDisplay extends React.PureComponent { return ( ); } - private renderDeploy () { + private renderDeploy (): React.ReactNode { const { extrinsic, contract_fees = ZERO_FEES_CONTRACT } = this.props; const { extMethod, extSection } = this.state; @@ -268,14 +271,14 @@ export class FeeDisplay extends React.PureComponent { return ( ); } - private onExtraUpdate = (extra: ExtraFees) => { + private onExtraUpdate = (extra: ExtraFees): void => { this.setState({ ...extra }); } } diff --git a/packages/ui-signer/src/Checks/types.ts b/packages/ui-signer/src/Checks/types.ts index fe858bdb05..44b9841bb7 100644 --- a/packages/ui-signer/src/Checks/types.ts +++ b/packages/ui-signer/src/Checks/types.ts @@ -4,8 +4,8 @@ import BN from 'bn.js'; -export type ExtraFees = { - extraAmount: BN, - extraFees: BN, - extraWarn: boolean -}; +export interface ExtraFees { + extraAmount: BN; + extraFees: BN; + extraWarn: boolean; +} diff --git a/packages/ui-signer/src/Modal.tsx b/packages/ui-signer/src/Modal.tsx index 43334e8591..e498b92a2c 100644 --- a/packages/ui-signer/src/Modal.tsx +++ b/packages/ui-signer/src/Modal.tsx @@ -9,7 +9,7 @@ import { I18nProps, BareProps } from '@polkadot/ui-app/types'; import { RpcMethod } from '@polkadot/jsonrpc/types'; import { KeyringPair } from '@polkadot/keyring/types'; import { SubjectInfo } from '@polkadot/ui-keyring/observable/types'; -import { QueueTx, QueueTx$MessageSetStatus, QueueTx$Result, QueueTx$Status } from '@polkadot/ui-app/Status/types'; +import { QueueTx, QueueTxMessageSetStatus, QueueTxResult, QueueTxStatus } from '@polkadot/ui-app/Status/types'; import React from 'react'; import { web3FromSource } from '@polkadot/extension-dapp'; @@ -24,33 +24,31 @@ import Transaction from './Transaction'; import translate from './translate'; import Unlock from './Unlock'; -type BaseProps = BareProps & { - queue: Array, - queueSetTxStatus: QueueTx$MessageSetStatus -}; +interface BaseProps extends BareProps { + queue: QueueTx[]; + queueSetTxStatus: QueueTxMessageSetStatus; +} type Props = I18nProps & ApiProps & BaseProps & { - allAccounts?: SubjectInfo + allAccounts?: SubjectInfo; }; -type State = { - currentItem?: QueueTx, - isSendable: boolean, - password: string, - unlockError?: string | null -}; +interface State { + currentItem?: QueueTx; + isSendable: boolean; + password: string; + unlockError?: string | null; +} class Signer extends React.PureComponent { - state: State = { + public state: State = { isSendable: false, password: '', unlockError: null }; - static getDerivedStateFromProps ({ allAccounts, queue }: Props, { currentItem, password, unlockError }: State): State { - const nextItem = queue.find(({ status }) => - status === 'queued' - ); + public static getDerivedStateFromProps ({ allAccounts, queue }: Props, { currentItem, password, unlockError }: State): State { + const nextItem = queue.find(({ status }): boolean => status === 'queued'); const isSame = !!nextItem && !!currentItem && @@ -81,7 +79,7 @@ class Signer extends React.PureComponent { }; } - async componentDidUpdate () { + public async componentDidUpdate (): Promise { const { currentItem } = this.state; if (currentItem && currentItem.status === 'queued' && !currentItem.extrinsic) { @@ -89,7 +87,7 @@ class Signer extends React.PureComponent { } } - render () { + public render (): React.ReactNode { const { currentItem } = this.state; if (!currentItem) { @@ -108,7 +106,7 @@ class Signer extends React.PureComponent { ); } - private renderButtons () { + private renderButtons (): React.ReactNode { const { t } = this.props; const { currentItem, isSendable } = this.state; @@ -143,7 +141,7 @@ class Signer extends React.PureComponent { ); } - private renderContent () { + private renderContent (): React.ReactNode { const { currentItem, isSendable } = this.state; if (!currentItem) { @@ -160,7 +158,7 @@ class Signer extends React.PureComponent { ); } - private renderUnlock () { + private renderUnlock (): React.ReactNode { const { currentItem, isSendable, password, unlockError } = this.state; if (!isSendable || !currentItem || currentItem.isUnsigned) { @@ -296,7 +294,7 @@ class Signer extends React.PureComponent { return this.makeExtrinsicCall(submittable, queueTx, submittable.signAndSend, keyring.getPair(accountId as string)); } - private async submitRpc ({ method, section }: RpcMethod, values: Array): Promise { + private async submitRpc ({ method, section }: RpcMethod, values: any[]): Promise { const { api } = this.props; try { @@ -318,7 +316,7 @@ class Signer extends React.PureComponent { } } - private async makeExtrinsicCall (extrinsic: SubmittableExtrinsic, { id, txFailedCb, txSuccessCb, txStartCb, txUpdateCb }: QueueTx, extrinsicCall: (...params: Array) => any, pair?: KeyringPair): Promise { + private async makeExtrinsicCall (extrinsic: SubmittableExtrinsic, { id, txFailedCb, txSuccessCb, txStartCb, txUpdateCb }: QueueTx, extrinsicCall: (...params: any[]) => any, pair?: KeyringPair): Promise { const { api, queueSetTxStatus } = this.props; console.log('makeExtrinsicCall: extrinsic ::', extrinsic.toHex()); @@ -346,12 +344,12 @@ class Signer extends React.PureComponent { } try { - const unsubscribe = await extrinsicCall.apply(extrinsic, [...params, async (result: SubmittableResult) => { + const unsubscribe = await extrinsicCall.apply(extrinsic, [...params, async (result: SubmittableResult): Promise => { if (!result || !result.status) { return; } - const status = result.status.type.toLowerCase() as QueueTx$Status; + const status = result.status.type.toLowerCase() as QueueTxStatus; console.log('makeExtrinsicCall: updated status ::', JSON.stringify(result)); queueSetTxStatus(id, status, result); @@ -364,8 +362,8 @@ class Signer extends React.PureComponent { unsubscribe(); result.events - .filter(({ event: { section } }) => section === 'system') - .forEach(({ event: { method } }) => { + .filter(({ event: { section } }): boolean => section === 'system') + .forEach(({ event: { method } }): void => { if (isFunction(txFailedCb) && method === 'ExtrinsicFailed') { txFailedCb(result); } else if (isFunction(txSuccessCb) && method === 'ExtrinsicSuccess') { diff --git a/packages/ui-signer/src/PasswordCheck.tsx b/packages/ui-signer/src/PasswordCheck.tsx index 07d0c77967..25292279b6 100644 --- a/packages/ui-signer/src/PasswordCheck.tsx +++ b/packages/ui-signer/src/PasswordCheck.tsx @@ -10,17 +10,17 @@ import { withMulti } from '@polkadot/ui-api'; import translate from './translate'; -type Props = I18nProps & { - className?: string, - unlockError?: string | null -}; +interface Props extends I18nProps { + className?: string; + unlockError?: string | null; +} -function PasswordCheck (props: Props) { +function PasswordCheck (props: Props): React.ReactElement | null { const { className, unlockError, t } = props; return unlockError - ?
{t('wrong password')}
- : null; + ?
{t('wrong password')}
+ : null; } export default withMulti( diff --git a/packages/ui-signer/src/Transaction.tsx b/packages/ui-signer/src/Transaction.tsx index d3e2a1a4cb..e307381476 100644 --- a/packages/ui-signer/src/Transaction.tsx +++ b/packages/ui-signer/src/Transaction.tsx @@ -12,14 +12,14 @@ import { Call, InputAddress, Modal } from '@polkadot/ui-app'; import Checks from './Checks'; import translate from './translate'; -type Props = I18nProps & { - children?: React.ReactNode, - isSendable: boolean, - value: QueueTx -}; +interface Props extends I18nProps { + children?: React.ReactNode; + isSendable: boolean; + value: QueueTx; +} class Transaction extends React.PureComponent { - render () { + public render (): React.ReactNode { const { children, value: { extrinsic } } = this.props; if (!extrinsic) { @@ -48,7 +48,7 @@ class Transaction extends React.PureComponent { ); } - private renderAccount () { + private renderAccount (): React.ReactNode { const { t, value: { accountId, isUnsigned } } = this.props; if (isUnsigned || !accountId) { @@ -67,7 +67,7 @@ class Transaction extends React.PureComponent { ); } - private renderChecks () { + private renderChecks (): React.ReactNode { const { isSendable, value: { accountId, extrinsic, isUnsigned } } = this.props; if (isUnsigned) { diff --git a/packages/ui-signer/src/Unlock.tsx b/packages/ui-signer/src/Unlock.tsx index 8fffd78df9..fd35aeb9cb 100644 --- a/packages/ui-signer/src/Unlock.tsx +++ b/packages/ui-signer/src/Unlock.tsx @@ -11,29 +11,30 @@ import keyring from '@polkadot/ui-keyring'; import translate from './translate'; -type Props = I18nProps & { - autoFocus?: boolean, - error?: string, - onChange: (password: string) => void, - onEnter?: () => void, - password: string, - tabIndex?: number, - value?: string | null -}; +interface Props extends I18nProps { + autoFocus?: boolean; + error?: string; + onChange: (password: string) => void; + onEnter?: () => void; + password: string; + tabIndex?: number; + value?: string | null; +} -type State = { - isError: boolean, - isInjected: boolean, - isLocked: boolean, - pair: KeyringPair -}; +interface State { + isError: boolean; + isInjected?: boolean; + isLocked: boolean; + pair?: KeyringPair; +} class Unlock extends React.PureComponent { - state: State = { + public state: State = { + isError: false, isLocked: false - } as State; + }; - static getDerivedStateFromProps ({ error, value }: Props): State | null { + public static getDerivedStateFromProps ({ error, value }: Props): State | null { const pair = keyring.getPair(value as string); if (!pair) { @@ -50,7 +51,7 @@ class Unlock extends React.PureComponent { }; } - render () { + public render (): React.ReactNode { const { autoFocus, onChange, onEnter, password, t, tabIndex } = this.props; const { isError, isInjected, isLocked } = this.state; diff --git a/packages/ui-signer/src/index.tsx b/packages/ui-signer/src/index.tsx index c9e9eb4218..8f96ce29dc 100644 --- a/packages/ui-signer/src/index.tsx +++ b/packages/ui-signer/src/index.tsx @@ -12,19 +12,19 @@ import { QueueConsumer } from '@polkadot/ui-app/Status/Context'; import Modal from './Modal'; -type Props = BareProps & { - children: React.ReactNode -}; +interface Props extends BareProps { + children: React.ReactNode; +} export default class Signer extends React.PureComponent { - render () { + public render (): React.ReactNode { const { children, className, style } = this.props; return ( <> {children} - {({ txqueue, queueSetTxStatus }: QueueProps) => ( + {({ txqueue, queueSetTxStatus }: QueueProps): React.ReactNode => (