diff --git a/packages/apps-config/src/api/index.ts b/packages/apps-config/src/api/index.ts index f878496a29..7f45f3d81b 100644 --- a/packages/apps-config/src/api/index.ts +++ b/packages/apps-config/src/api/index.ts @@ -4,6 +4,7 @@ import typesChain from './chain'; import typesSpec from './spec'; import typesBundle from './bundle'; +import typesRpc from './rpc'; export function getChainTypes (specName: string, chainName: string): Record> { return { @@ -15,5 +16,6 @@ export function getChainTypes (specName: string, chainName: string): Record> { + function generateDescription (description:string, returnType:string, params:DefinitionRpcParam[] = []):DefinitionRpc { + return { + description, + params, + type: returnType + }; + } + + const numberParam: DefinitionRpcParam = { isOptional: true, name: 'number', type: 'BlockNumber' }; + const hashParam: DefinitionRpcParam = { name: 'hash', type: 'H256' }; + const reqParam: DefinitionRpcParam = { name: 'request', type: 'CallRequest' }; + const blockParam: DefinitionRpcParam = { name: 'block', type: 'BlockNumber' }; + const addressParam: DefinitionRpcParam = { name: 'address', type: 'H160' }; + const indexParam: DefinitionRpcParam = { name: 'index', type: 'U256' }; + + return { + eth: { + accounts: generateDescription('Returns accounts list.', 'Vec'), + blockNumber: generateDescription('Returns balance of the given account.', 'U256'), + call: generateDescription('Call contract, returning the output data.', 'Bytes', [reqParam, numberParam]), + chainId: generateDescription('Returns the chain ID used for transaction signing at the current best block. None is returned if not available.', 'U64'), + coinbase: generateDescription('Returns block author.', 'H160'), + estimateGas: generateDescription('Estimate gas needed for execution of given contract.', 'U256', [reqParam, numberParam]), + gasPrice: generateDescription('Returns current gas_price.', 'U256'), + getBalance: generateDescription('Returns balance of the given account.', 'U256', [addressParam, numberParam]), + getBlockByHash: generateDescription('Returns block with given hash.', 'RichBlock', [hashParam, { isOptional: true, name: 'full', type: 'bool' }]), + getBlockByNumber: generateDescription('Returns block with given number.', 'RichBlock', [blockParam, { isOptional: true, name: 'full', type: 'bool' }]), + getBlockTransactionCountByHash: generateDescription('Returns the number of transactions in a block with given hash.', 'U256', [hashParam]), + getBlockTransactionCountByNumber: generateDescription('Returns the number of transactions in a block with given block number.', 'U256', [blockParam]), + getCode: generateDescription('Returns the code at given address at given time (block number).', 'Bytes', [addressParam, numberParam]), + getLogs: generateDescription('Returns logs matching given filter object.', 'Vec', [{ name: 'filter', type: 'Filter' }]), + getStorageAt: generateDescription('Returns content of the storage at given address.', 'H256', [addressParam, indexParam, numberParam]), + getTransactionByBlockHashAndIndex: generateDescription('Returns transaction at given block hash and index.', 'Transaction', [hashParam, indexParam]), + getTransactionByBlockNumberAndIndex: generateDescription('Returns transaction by given block number and index.', 'Transaction', [numberParam, indexParam]), + getTransactionByHash: generateDescription('Get transaction by its hash.', 'Transaction', [hashParam]), + getTransactionCount: generateDescription('Returns the number of transactions sent from given address at given time (block number).', 'U256', [hashParam, numberParam]), + getTransactionReceipt: generateDescription('Returns transaction receipt by transaction hash.', 'Receipt', [hashParam]), + getUncleByBlockHashAndIndex: generateDescription('Returns an uncles at given block and index.', 'RichBlock', [hashParam, indexParam]), + getUncleByBlockNumberAndIndex: generateDescription('Returns an uncles at given block and index.', 'RichBlock', [numberParam, indexParam]), + getUncleCountByBlockHash: generateDescription('Returns the number of uncles in a block with given hash.', 'U256', [hashParam]), + getUncleCountByBlockNumber: generateDescription('Returns the number of uncles in a block with given block number.', 'U256', [numberParam]), + getWork: generateDescription('Returns the hash of the current block, the seedHash, and the boundary condition to be met.', 'Work'), + hashrate: generateDescription('Returns the number of hashes per second that the node is mining with.', 'U256'), + mining: generateDescription('Returns true if client is actively mining new blocks.', 'bool'), + protocolVersion: generateDescription('Returns protocol version encoded as a string (quotes are necessary).', 'u64'), + sendRawTransaction: generateDescription('Sends signed transaction, returning its hash.', 'BoxFuture', [{ name: 'bytes', type: 'Bytes' }]), + submitHashrate: generateDescription('Used for submitting mining hashrate.', 'bool', [indexParam, hashParam]), + submitWork: generateDescription('Used for submitting a proof-of-work solution.', 'bool', [{ name: '_', type: 'H64' }, { name: '_', type: 'H256' }, { name: '_', type: 'H256' }]), + subscribe: generateDescription('Subscribe to Eth subscription.', '', [{ name: '_metadata', type: 'Self::Metadata' }, { name: 'subscriber', type: 'Subscriber' }, { name: 'kind', type: 'Kind' }, { isOptional: true, name: 'params', type: 'Params' }]), + syncing: generateDescription('Returns an object with data about the sync status or false. (wtf?)', 'SyncStatus'), + unsubscribe: generateDescription('nsubscribe from existing Eth subscription.', '', [{ name: '_metadata', type: 'Self::Metadata' }, { name: 'subscription_id', type: 'Self::SubscriptionId' }]) + }, + net: { + listening: generateDescription('Returns true if client is actively listening for network connections. Otherwise false.', 'bool'), + peerCount: generateDescription('Returns number of peers connected to node.', 'String'), + version: generateDescription('Returns protocol version.', 'String') + } + }; +} diff --git a/packages/apps-config/src/api/spec/index.ts b/packages/apps-config/src/api/spec/index.ts index ccd72f7e6d..67b50226f0 100644 --- a/packages/apps-config/src/api/spec/index.ts +++ b/packages/apps-config/src/api/spec/index.ts @@ -17,6 +17,7 @@ import equilibrium from './equilibrium'; import hanonycash from './hanonycash'; import kilt from './kilt'; import kulupu from './kulupu'; +import moonbeam from './moonbeam'; import nodeTemplate from './node-template'; import nodle from './nodle'; import plasm from './plasm'; @@ -46,6 +47,9 @@ export default { hanonycash, kulupu, 'mashnet-node': kilt, + 'moonbase-alphanet': moonbeam, + 'moonbeam-standalone': moonbeam, + 'node-moonbeam': moonbeam, 'node-template': nodeTemplate, 'nodle-chain': nodle, plasm, diff --git a/packages/apps-config/src/api/spec/moonbeam.ts b/packages/apps-config/src/api/spec/moonbeam.ts new file mode 100644 index 0000000000..a9886a7b9b --- /dev/null +++ b/packages/apps-config/src/api/spec/moonbeam.ts @@ -0,0 +1,77 @@ +// Copyright 2017-2020 @polkadot/apps-config authors & contributors +// SPDX-License-Identifier: Apache-2.0 + +// structs need to be in order +/* eslint-disable sort-keys */ + +export default { + AccountId: 'EthereumAccountId', + Address: 'AccountId', + Balance: 'u128', + RefCount: 'u8', + LookupSource: 'AccountId', + Account: { + nonce: 'U256', + balance: 'u128' + }, + TransactionCondition: { + _enum: { + block: 'u64', + time: 'u64' + } + }, + Transaction: { + action: 'String', + block_hash: 'Option', + block_number: 'Option', + chain_id: 'Option', + condition: 'Option', + creates: 'Option', + from: 'H160', + gas: 'U256', + gas_price: 'U256', + gas_limit: 'u64', + hash: 'H256', + input: 'Bytes', + nonce: 'U256', + public_key: 'Option', + r: 'U256', + raw: 'Bytes', + s: 'U256', + signature: 'Signature', + standard_v: 'U256', + to: 'Option', + transaction_index: 'Option', + v: 'U256', + value: 'U256' + }, + Signature: { + v: 'u64', + r: 'H256', + s: 'H256' + }, + TransactionStatus: { + transaction_hash: 'H256', + transaction_index: 'u32', + from: 'H160', + to: 'Option', + contract_address: 'Option', + logs: 'Vec', + logs_bloom: 'Bloom' + }, + Receipt: { + transaction_hash: 'Option', + transaction_index: 'Option', + block_hash: 'Option', + from: 'Option', + to: 'Option', + block_number: 'Option', + cumulative_gas_used: 'U256', + gas_used: 'Option', + contract_address: 'Option', + logs: 'Vec', + state_root: 'Option', + logs_bloom: 'H2048', + status_code: 'Option' + } +}; diff --git a/packages/apps-config/src/settings/ethereumNetworks.ts b/packages/apps-config/src/settings/ethereumNetworks.ts new file mode 100644 index 0000000000..de5dfca82a --- /dev/null +++ b/packages/apps-config/src/settings/ethereumNetworks.ts @@ -0,0 +1,4 @@ +// Copyright 2017-2020 @polkadot/apps-config authors & contributors +// SPDX-License-Identifier: Apache-2.0 + +export const ethereumNetworks = ['node-moonbeam', 'moonbase-alphanet', 'moonbeam-standalone']; diff --git a/packages/apps-config/src/settings/index.ts b/packages/apps-config/src/settings/index.ts index ba10fc3846..5bcdb2d076 100644 --- a/packages/apps-config/src/settings/index.ts +++ b/packages/apps-config/src/settings/index.ts @@ -5,10 +5,12 @@ import createEndpoints from './endpoints'; import createLanguages from './languages'; import createSs58 from './ss58'; import { CUSTOM_ENDPOINT_KEY } from './constants'; +import { ethereumNetworks } from './ethereumNetworks'; export { createEndpoints, createLanguages, createSs58, - CUSTOM_ENDPOINT_KEY + CUSTOM_ENDPOINT_KEY, + ethereumNetworks }; diff --git a/packages/apps-config/src/ui/colors.ts b/packages/apps-config/src/ui/colors.ts index 8bdecf370e..c82f39f1bb 100644 --- a/packages/apps-config/src/ui/colors.ts +++ b/packages/apps-config/src/ui/colors.ts @@ -31,6 +31,7 @@ const nodeCanvas = '#c77cff'; const nodeCentrifuge = '#fcc367'; const nodeEdgeware = '#0a95df'; const nodeEquilibrium = '#1792ff'; +const nodeMoonbeam = '#53cbc9'; const nodeNodle = '#1ab394'; const nodeKilt = '#eb5b2a'; const nodeStafi = '#00F3AB'; @@ -75,6 +76,7 @@ const nodeColors: Record = [ ['edgeware node', nodeEdgeware], ['Equilibrium node', nodeEquilibrium], ['kilt node', nodeKilt], + ['moonbase alpha', nodeMoonbeam], ['nodle chain node', nodeNodle], ['Stafi node', nodeStafi], ['subsocial node', nodeSubsocial] diff --git a/packages/page-accounts/src/Vanity/index.tsx b/packages/page-accounts/src/Vanity/index.tsx index 2e502f704f..625068349e 100644 --- a/packages/page-accounts/src/Vanity/index.tsx +++ b/packages/page-accounts/src/Vanity/index.tsx @@ -8,7 +8,7 @@ import { GeneratorMatches, GeneratorMatch, GeneratorResult } from '@polkadot/van import React, { useCallback, useEffect, useMemo, useRef, useState } from 'react'; import styled from 'styled-components'; import { Button, Dropdown, Input, Table } from '@polkadot/react-components'; -import { useIsMountedRef } from '@polkadot/react-hooks'; +import { useApi, useIsMountedRef } from '@polkadot/react-hooks'; import uiSettings from '@polkadot/ui-settings'; import generator from '@polkadot/vanitygen/generator'; import matchRegex from '@polkadot/vanitygen/regex'; @@ -45,6 +45,7 @@ const BOOL_OPTIONS = [ function VanityApp ({ className = '', onStatusChange }: Props): React.ReactElement { const { t } = useTranslation(); + const { isEthereum } = useApi(); const results = useRef([]); const runningRef = useRef(false); const mountedRef = useIsMountedRef(); @@ -211,7 +212,7 @@ function VanityApp ({ className = '', onStatusChange }: Props): React.ReactEleme help={t('Determines what cryptography will be used to create this account. Note that to validate on Polkadot, the session account must use "ed25519".')} label={t('keypair crypto type')} onChange={setType} - options={uiSettings.availableCryptos} + options={isEthereum ? uiSettings.availableCryptosEth : uiSettings.availableCryptos} /> diff --git a/packages/page-accounts/src/modals/Create.tsx b/packages/page-accounts/src/modals/Create.tsx index 06e2ad7a72..515b1ce113 100644 --- a/packages/page-accounts/src/modals/Create.tsx +++ b/packages/page-accounts/src/modals/Create.tsx @@ -182,8 +182,8 @@ function createAccount (suri: string, pairType: KeypairType, { genesisHash, name function Create ({ className = '', onClose, onStatusChange, seed: propsSeed, type: propsType }: Props): React.ReactElement { const { t } = useTranslation(); - const { api, isDevelopment } = useApi(); - const [{ address, derivePath, deriveValidation, isSeedValid, pairType, seed, seedType }, setAddress] = useState(generateSeed(propsSeed, '', propsSeed ? 'raw' : 'bip', propsType)); + const { api, isDevelopment, isEthereum } = useApi(); + const [{ address, derivePath, deriveValidation, isSeedValid, pairType, seed, seedType }, setAddress] = useState(generateSeed(propsSeed, '', propsSeed ? 'raw' : 'bip', isEthereum ? 'ethereum' : propsType)); const [isMnemonicSaved, setIsMnemonicSaved] = useState(false); const [step, setStep] = useState(1); const [isBusy, setIsBusy] = useState(false); @@ -339,7 +339,7 @@ function Create ({ className = '', onClose, onStatusChange, seed: propsSeed, typ help={t('Determines what cryptography will be used to create this account. Note that to validate on Polkadot, the session account must use "ed25519".')} label={t('keypair crypto type')} onChange={_onChangePairType} - options={uiSettings.availableCryptos} + options={isEthereum ? uiSettings.availableCryptosEth : uiSettings.availableCryptos} tabIndex={-1} /> diff --git a/packages/page-addresses/src/modals/Create.tsx b/packages/page-addresses/src/modals/Create.tsx index a602d65929..f145b16f28 100644 --- a/packages/page-addresses/src/modals/Create.tsx +++ b/packages/page-addresses/src/modals/Create.tsx @@ -9,6 +9,8 @@ import React, { useCallback, useState } from 'react'; import { AddressRow, Button, Input, InputAddress, Modal } from '@polkadot/react-components'; import { useApi, useCall } from '@polkadot/react-hooks'; import keyring from '@polkadot/ui-keyring'; +import { hexToU8a } from '@polkadot/util'; +import { ethereumEncode } from '@polkadot/util-crypto'; import { useTranslation } from '../translate'; @@ -27,7 +29,7 @@ interface NameState { function Create ({ onClose, onStatusChange }: Props): React.ReactElement { const { t } = useTranslation(); - const { api } = useApi(); + const { api, isEthereum } = useApi(); const [{ isNameValid, name }, setName] = useState({ isNameValid: false, name: '' }); const [{ address, addressInput, isAddressExisting, isAddressValid }, setAddress] = useState({ address: '', addressInput: '', isAddressExisting: false, isAddressValid: false, isPublicKey: false }); const info = useCall(!!address && isAddressValid && api.derive.accounts.info, [address]); @@ -41,11 +43,17 @@ function Create ({ onClose, onStatusChange }: Props): React.ReactElement let isPublicKey = false; try { - const publicKey = keyring.decodeAddress(addressInput); + if (isEthereum) { + const rawAddress = hexToU8a(addressInput); - address = keyring.encodeAddress(publicKey); - isAddressValid = keyring.isAvailable(address); - isPublicKey = publicKey.length === 32; + address = ethereumEncode(rawAddress); + isPublicKey = rawAddress.length === 20; + } else { + const publicKey = keyring.decodeAddress(addressInput); + + address = keyring.encodeAddress(publicKey); + isPublicKey = publicKey.length === 32; + } if (!isAddressValid) { const old = keyring.getAddress(address); @@ -65,7 +73,7 @@ function Create ({ onClose, onStatusChange }: Props): React.ReactElement setAddress({ address: isAddressValid ? address : '', addressInput, isAddressExisting, isAddressValid, isPublicKey }); }, - [name] + [isEthereum, name] ); const _onChangeName = useCallback( diff --git a/packages/react-api/src/Api.tsx b/packages/react-api/src/Api.tsx index 468bd65b91..2d5a6dac22 100644 --- a/packages/react-api/src/Api.tsx +++ b/packages/react-api/src/Api.tsx @@ -10,7 +10,7 @@ import React, { useContext, useEffect, useMemo, useState } from 'react'; import store from 'store'; import ApiPromise from '@polkadot/api/promise'; import { setDeriveCache, deriveMapCache } from '@polkadot/api-derive/util'; -import { typesChain, typesSpec, typesBundle } from '@polkadot/apps-config/api'; +import { typesChain, typesSpec, typesBundle, typesRpc } from '@polkadot/apps-config/api'; import { POLKADOT_DENOM_BLOCK, POLKADOT_GENESIS } from '@polkadot/apps-config/api/constants'; import { web3Accounts, web3Enable } from '@polkadot/extension-dapp'; import { WsProvider } from '@polkadot/rpc-provider'; @@ -26,6 +26,7 @@ import addressDefaults from '@polkadot/util-crypto/address/defaults'; import ApiContext from './ApiContext'; import registry from './typeRegistry'; +import { ethereumNetworks } from '@polkadot/apps-config/settings'; interface Props { children: React.ReactNode; @@ -121,7 +122,6 @@ async function retrieve (api: ApiPromise, injectedPromise: Promise, store: KeyringStore | undefined, types: Record>): Promise { registry.register(types); - const { injectedAccounts, properties, systemChain, systemChainType, systemName, systemVersion } = await retrieve(api, injectedPromise); const ss58Format = uiSettings.prefix === -1 ? properties.ss58Format.unwrapOr(DEFAULT_SS58).toNumber() @@ -129,6 +129,7 @@ async function loadOnReady (api: ApiPromise, injectedPromise: Promise | null const signer = new ApiSigner(queuePayload, queueSetTxStatus); const types = getDevTypes(); - api = new ApiPromise({ provider, registry, signer, types, typesBundle, typesChain, typesSpec }); + api = new ApiPromise({ provider, registry, rpc: typesRpc, signer, types, typesBundle, typesChain, typesSpec }); api.on('connected', () => setIsApiConnected(true)); api.on('disconnected', () => setIsApiConnected(false)); diff --git a/packages/react-api/src/types.ts b/packages/react-api/src/types.ts index 75e50b004f..217a0410b8 100644 --- a/packages/react-api/src/types.ts +++ b/packages/react-api/src/types.ts @@ -20,6 +20,7 @@ export interface ApiState { hasInjectedAccounts: boolean; isApiReady: boolean; isDevelopment: boolean; + isEthereum: boolean; isSubstrateV2: boolean; systemChain: string; systemName: string; diff --git a/packages/react-components/src/IdentityIcon/index.tsx b/packages/react-components/src/IdentityIcon/index.tsx index aa7e8cf87f..76ecc53323 100644 --- a/packages/react-components/src/IdentityIcon/index.tsx +++ b/packages/react-components/src/IdentityIcon/index.tsx @@ -27,7 +27,7 @@ export function getIdentityTheme (systemName: string): 'substrate' { } function IdentityIcon ({ className = '', prefix, size = 24, theme, value }: Props): React.ReactElement { - const { systemName } = useApi(); + const { isEthereum, systemName } = useApi(); const { t } = useTranslation(); const { queueAction } = useContext(StatusContext); const thisTheme = theme || getIdentityTheme(systemName); @@ -52,7 +52,7 @@ function IdentityIcon ({ className = '', prefix, size = 24, theme, value }: Prop onCopy={_onCopy} prefix={prefix} size={size} - theme={thisTheme as 'substrate'} + theme={isEthereum ? 'ethereum' : thisTheme as 'substrate'} value={value} /> ); diff --git a/packages/react-components/src/util/toAddress.ts b/packages/react-components/src/util/toAddress.ts index d4652980b7..1a708ebdd6 100644 --- a/packages/react-components/src/util/toAddress.ts +++ b/packages/react-components/src/util/toAddress.ts @@ -3,6 +3,7 @@ import keyring from '@polkadot/ui-keyring'; import { hexToU8a, isHex, assert } from '@polkadot/util'; +import { ethereumEncode } from '@polkadot/util-crypto'; export default function toAddress (value?: string | Uint8Array | null, allowIndices = false): string | undefined { if (value) { @@ -11,9 +12,13 @@ export default function toAddress (value?: string | Uint8Array | null, allowIndi ? hexToU8a(value) : keyring.decodeAddress(value); - assert(allowIndices || u8a.length === 32, 'AccountIndex values not allowed'); + assert(allowIndices || u8a.length === 32 || u8a.length === 20, 'AccountIndex values not allowed'); - return keyring.encodeAddress(u8a); + if (u8a.length === 20) { + return ethereumEncode(u8a); + } else { + return keyring.encodeAddress(u8a); + } } catch (error) { // noop, undefined return indicates invalid/transient } diff --git a/packages/react-params/src/Param/Hash160.tsx b/packages/react-params/src/Param/Hash160.tsx new file mode 100644 index 0000000000..4d48143ef7 --- /dev/null +++ b/packages/react-params/src/Param/Hash160.tsx @@ -0,0 +1,29 @@ +// Copyright 2017-2020 @polkadot/react-params authors & contributors +// SPDX-License-Identifier: Apache-2.0 + +import { Props } from '../types'; + +import React from 'react'; + +import BaseBytes from './BaseBytes'; + +function Hash160 ({ className = '', defaultValue, isDisabled, isError, label, name, onChange, onEnter, onEscape, type, withLabel }: Props): React.ReactElement { + return ( + + ); +} + +export default React.memo(Hash160); diff --git a/packages/react-params/src/Param/findComponent.ts b/packages/react-params/src/Param/findComponent.ts index e5a88e2091..6b916320d7 100644 --- a/packages/react-params/src/Param/findComponent.ts +++ b/packages/react-params/src/Param/findComponent.ts @@ -18,6 +18,7 @@ import Code from './Code'; import DispatchError from './DispatchError'; import Enum from './Enum'; import Hash256 from './Hash256'; +import Hash160 from './Hash160'; import Hash512 from './Hash512'; import KeyValue from './KeyValue'; import KeyValueArray from './KeyValueArray'; @@ -54,6 +55,7 @@ const componentDef: TypeToComponent[] = [ { c: Raw, t: ['Raw', 'Keys'] }, { c: Enum, t: ['Enum'] }, { c: Hash256, t: ['BlockHash', 'CodeHash', 'Hash', 'H256', 'SeedOf'] }, + { c: Hash160, t: ['H160'] }, { c: Hash512, t: ['H512', 'Signature'] }, { c: KeyValue, t: ['KeyValue'] }, { c: KeyValueArray, t: ['Vec'] }, diff --git a/packages/react-params/src/initValue.ts b/packages/react-params/src/initValue.ts index 4cb6d04240..f598e1e9bb 100644 --- a/packages/react-params/src/initValue.ts +++ b/packages/react-params/src/initValue.ts @@ -88,6 +88,9 @@ export default function getInitValue (def: TypeDef): unknown { case 'H512': return createType(registry, 'H512'); + case 'H160': + return registry.createType('H160'); + case 'Raw': case 'Keys': return ''; @@ -100,6 +103,7 @@ export default function getInitValue (def: TypeDef): unknown { case 'Digest': case 'Header': case 'KeyValue': + case 'LookupSource': case 'MisbehaviorReport': case 'Proposal': case 'Signature':