Support ethereum addresses for Moonbeam (#3961)

* support ethereum addresses

* corrections

* add standalone url and ethereum identicons

* add moonbeam config

* added changes from the old pr

* add new config

* added dummy rpc method declarations for eth methods

* wip fix address add modal

* support ethereum addresses

* corrections

* add standalone url and ethereum identicons

* add moonbeam config

* added changes from the old pr

* add new config

* added dummy rpc method declarations for eth methods

* wip fix address add modal

* wip repair app with new keyring

* use isDevelopement false for ethereum

* lint

* more formatng

* eth addresses by default for account creation

* added many more types to support moonbeam

* added color

* add h160 to types and components

* add rpc methods to app-config

* lint

* polish

* Update packages/react-params/src/initValue.ts

Co-authored-by: Jaco Greeff <jacogr@gmail.com>

* Apply suggestions from code review

Co-authored-by: Jaco Greeff <jacogr@gmail.com>

* moved ethereum networks to config

* added real rpc method typings

Co-authored-by: Jaco Greeff <jacogr@gmail.com>
This commit is contained in:
Antoine Estienne 2020-11-10 18:12:11 +01:00 committed by GitHub
parent 6d74c3ba54
commit 31904bf106
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
18 changed files with 240 additions and 22 deletions

View File

@ -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<string, string | Record<string, unknown>> {
return {
@ -15,5 +16,6 @@ export function getChainTypes (specName: string, chainName: string): Record<stri
export {
typesChain,
typesSpec,
typesBundle
typesBundle,
typesRpc
};

View File

@ -0,0 +1,10 @@
// Copyright 2017-2020 @polkadot/apps-config authors & contributors
// SPDX-License-Identifier: Apache-2.0
import moonbeam from './moonbeam';
// Add your rpc method definitions here
export default {
// Moonbeam rpc types (Frontier)
...moonbeam()
};

View File

@ -0,0 +1,65 @@
// Copyright 2017-2020 @polkadot/apps-config authors & contributors
// SPDX-License-Identifier: Apache-2.0
import { DefinitionRpc, DefinitionRpcParam } from '@polkadot/types/types';
export default function (): Record<string, Record<string, DefinitionRpc>> {
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<H160>'),
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<Log>', [{ 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<H256>', [{ 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<PubSubResult>' }, { 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')
}
};
}

View File

@ -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,

View File

@ -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<H256>',
block_number: 'Option<U256>',
chain_id: 'Option<u64>',
condition: 'Option<TransactionCondition>',
creates: 'Option<H160>',
from: 'H160',
gas: 'U256',
gas_price: 'U256',
gas_limit: 'u64',
hash: 'H256',
input: 'Bytes',
nonce: 'U256',
public_key: 'Option<H512>',
r: 'U256',
raw: 'Bytes',
s: 'U256',
signature: 'Signature',
standard_v: 'U256',
to: 'Option<H160>',
transaction_index: 'Option<U256>',
v: 'U256',
value: 'U256'
},
Signature: {
v: 'u64',
r: 'H256',
s: 'H256'
},
TransactionStatus: {
transaction_hash: 'H256',
transaction_index: 'u32',
from: 'H160',
to: 'Option<H160>',
contract_address: 'Option<H160>',
logs: 'Vec<Log>',
logs_bloom: 'Bloom'
},
Receipt: {
transaction_hash: 'Option<H256>',
transaction_index: 'Option<U256>',
block_hash: 'Option<H256>',
from: 'Option<H160>',
to: 'Option<H160>',
block_number: 'Option<U256>',
cumulative_gas_used: 'U256',
gas_used: 'Option<U256>',
contract_address: 'Option<H160>',
logs: 'Vec<Log>',
state_root: 'Option<H256>',
logs_bloom: 'H2048',
status_code: 'Option<U64>'
}
};

View File

@ -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'];

View File

@ -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
};

View File

@ -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<string, any> = [
['edgeware node', nodeEdgeware],
['Equilibrium node', nodeEquilibrium],
['kilt node', nodeKilt],
['moonbase alpha', nodeMoonbeam],
['nodle chain node', nodeNodle],
['Stafi node', nodeStafi],
['subsocial node', nodeSubsocial]

View File

@ -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<Props> {
const { t } = useTranslation();
const { isEthereum } = useApi();
const results = useRef<GeneratorResult[]>([]);
const runningRef = useRef(false);
const mountedRef = useIsMountedRef();
@ -211,7 +212,7 @@ function VanityApp ({ className = '', onStatusChange }: Props): React.ReactEleme
help={t<string>('Determines what cryptography will be used to create this account. Note that to validate on Polkadot, the session account must use "ed25519".')}
label={t<string>('keypair crypto type')}
onChange={setType}
options={uiSettings.availableCryptos}
options={isEthereum ? uiSettings.availableCryptosEth : uiSettings.availableCryptos}
/>
</div>
<Button.Group>

View File

@ -182,8 +182,8 @@ function createAccount (suri: string, pairType: KeypairType, { genesisHash, name
function Create ({ className = '', onClose, onStatusChange, seed: propsSeed, type: propsType }: Props): React.ReactElement<Props> {
const { t } = useTranslation();
const { api, isDevelopment } = useApi();
const [{ address, derivePath, deriveValidation, isSeedValid, pairType, seed, seedType }, setAddress] = useState<AddressState>(generateSeed(propsSeed, '', propsSeed ? 'raw' : 'bip', propsType));
const { api, isDevelopment, isEthereum } = useApi();
const [{ address, derivePath, deriveValidation, isSeedValid, pairType, seed, seedType }, setAddress] = useState<AddressState>(generateSeed(propsSeed, '', propsSeed ? 'raw' : 'bip', isEthereum ? 'ethereum' : propsType));
const [isMnemonicSaved, setIsMnemonicSaved] = useState<boolean>(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<string>('Determines what cryptography will be used to create this account. Note that to validate on Polkadot, the session account must use "ed25519".')}
label={t<string>('keypair crypto type')}
onChange={_onChangePairType}
options={uiSettings.availableCryptos}
options={isEthereum ? uiSettings.availableCryptosEth : uiSettings.availableCryptos}
tabIndex={-1}
/>
</Modal.Column>

View File

@ -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<Props> {
const { t } = useTranslation();
const { api } = useApi();
const { api, isEthereum } = useApi();
const [{ isNameValid, name }, setName] = useState<NameState>({ isNameValid: false, name: '' });
const [{ address, addressInput, isAddressExisting, isAddressValid }, setAddress] = useState<AddrState>({ address: '', addressInput: '', isAddressExisting: false, isAddressValid: false, isPublicKey: false });
const info = useCall<DeriveAccountInfo>(!!address && isAddressValid && api.derive.accounts.info, [address]);
@ -41,11 +43,17 @@ function Create ({ onClose, onStatusChange }: Props): React.ReactElement<Props>
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<Props>
setAddress({ address: isAddressValid ? address : '', addressInput, isAddressExisting, isAddressValid, isPublicKey });
},
[name]
[isEthereum, name]
);
const _onChangeName = useCallback(

View File

@ -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<InjectedExten
async function loadOnReady (api: ApiPromise, injectedPromise: Promise<InjectedExtension[]>, store: KeyringStore | undefined, types: Record<string, Record<string, string>>): Promise<ApiState> {
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<InjectedEx
const tokenSymbol = properties.tokenSymbol.unwrapOr(undefined)?.toString();
const tokenDecimals = properties.tokenDecimals.unwrapOr(DEFAULT_DECIMALS).toNumber();
const isDevelopment = systemChainType.isDevelopment || systemChainType.isLocal || isTestChain(systemChain);
const isEthereum: boolean = ethereumNetworks.includes(api.runtimeVersion.specName.toString());
console.log(`chain: ${systemChain} (${systemChainType.toString()}), ${JSON.stringify(properties)}`);
@ -151,7 +152,7 @@ async function loadOnReady (api: ApiPromise, injectedPromise: Promise<InjectedEx
isDevelopment,
ss58Format,
store,
type: 'ed25519'
type: isEthereum ? 'ethereum' : 'ed25519'
}, injectedAccounts);
const defaultSection = Object.keys(api.tx)[0];
@ -167,7 +168,8 @@ async function loadOnReady (api: ApiPromise, injectedPromise: Promise<InjectedEx
apiDefaultTxSudo,
hasInjectedAccounts: injectedAccounts.length !== 0,
isApiReady: true,
isDevelopment,
isDevelopment: isEthereum ? false : isDevelopment,
isEthereum,
isSubstrateV2,
systemChain,
systemName,
@ -192,7 +194,7 @@ function Api ({ children, store, url }: Props): React.ReactElement<Props> | 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));

View File

@ -20,6 +20,7 @@ export interface ApiState {
hasInjectedAccounts: boolean;
isApiReady: boolean;
isDevelopment: boolean;
isEthereum: boolean;
isSubstrateV2: boolean;
systemChain: string;
systemName: string;

View File

@ -27,7 +27,7 @@ export function getIdentityTheme (systemName: string): 'substrate' {
}
function IdentityIcon ({ className = '', prefix, size = 24, theme, value }: Props): React.ReactElement<Props> {
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}
/>
);

View File

@ -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
}

View File

@ -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<Props> {
return (
<BaseBytes
className={className}
defaultValue={defaultValue}
isDisabled={isDisabled}
isError={isError}
label={label}
length={20}
name={name}
onChange={onChange}
onEnter={onEnter}
onEscape={onEscape}
type={type}
withLabel={withLabel}
/>
);
}
export default React.memo(Hash160);

View File

@ -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<KeyValue>'] },

View File

@ -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':