Merge branch 'master' into jg-typedinput-tests

This commit is contained in:
Jaco Greeff
2016-12-12 10:14:29 +01:00
39 changed files with 921 additions and 355 deletions

View File

@@ -1,6 +1,6 @@
{
"name": "parity.js",
"version": "0.2.116",
"version": "0.2.119",
"main": "release/index.js",
"jsnext:main": "src/index.js",
"author": "Parity Team <admin@parity.io>",

View File

@@ -48,7 +48,6 @@ class BaseTransaction extends Component {
<IdentityIcon
address={ transaction.from }
/>
0x{ transaction.nonce.toString(16) }
</div>
);
}

View File

@@ -34,7 +34,7 @@ describe('dapps/localtx/Transaction', () => {
it('renders without crashing', () => {
const transaction = {
hash: '0x1234567890',
nonce: 15,
nonce: new BigNumber(15),
gasPrice: new BigNumber(10),
gas: new BigNumber(10)
};

View File

@@ -14,31 +14,29 @@
// You should have received a copy of the GNU General Public License
// along with Parity. If not, see <http://www.gnu.org/licenses/>.
import React, { Component, PropTypes } from 'react';
import ContentAdd from 'material-ui/svg-icons/content/add';
import ContentClear from 'material-ui/svg-icons/content/clear';
import { observer } from 'mobx-react';
import React, { Component, PropTypes } from 'react';
import { FormattedMessage } from 'react-intl';
import { Button, Modal, Form, Input, InputAddress } from '~/ui';
import { ERRORS, validateAddress, validateName } from '~/util/validation';
import { Button, Form, Input, InputAddress, Modal } from '~/ui';
import Store from './store';
@observer
export default class AddAddress extends Component {
static contextTypes = {
api: PropTypes.object.isRequired
}
static propTypes = {
contacts: PropTypes.object.isRequired,
address: PropTypes.string,
onClose: PropTypes.func
contacts: PropTypes.object.isRequired,
onClose: PropTypes.func.isRequired
};
state = {
address: '',
addressError: ERRORS.invalidAddress,
name: '',
nameError: ERRORS.invalidName,
description: ''
};
store = new Store(this.context.api, this.props.contacts);
componentWillMount () {
if (this.props.address) {
@@ -49,109 +47,113 @@ export default class AddAddress extends Component {
render () {
return (
<Modal
visible
actions={ this.renderDialogActions() }
title='add saved address'>
title={
<FormattedMessage
id='addAddress.label'
defaultMessage='add saved address' />
}
visible>
{ this.renderFields() }
</Modal>
);
}
renderDialogActions () {
const { addressError, nameError } = this.state;
const hasError = !!(addressError || nameError);
const { hasError } = this.store;
return ([
<Button
icon={ <ContentClear /> }
label='Cancel'
onClick={ this.onClose } />,
label={
<FormattedMessage
id='addAddress.button.close'
defaultMessage='Cancel' />
}
onClick={ this.onClose }
ref='closeButton' />,
<Button
icon={ <ContentAdd /> }
label='Save Address'
disabled={ hasError }
onClick={ this.onAdd } />
icon={ <ContentAdd /> }
label={
<FormattedMessage
id='addAddress.button.add'
defaultMessage='Save Address' />
}
onClick={ this.onAdd }
ref='addButton' />
]);
}
renderFields () {
const { address, addressError, description, name, nameError } = this.state;
const { address, addressError, description, name, nameError } = this.store;
return (
<Form>
<InputAddress
label='network address'
hint='the network address for the entry'
error={ addressError }
value={ address }
disabled={ !!this.props.address }
allowCopy={ false }
onChange={ this.onEditAddress } />
disabled={ !!this.props.address }
error={ addressError }
hint={
<FormattedMessage
id='addAddress.input.address.hint'
defaultMessage='the network address for the entry' />
}
label={
<FormattedMessage
id='addAddress.input.address.label'
defaultMessage='network address' />
}
onChange={ this.onEditAddress }
ref='inputAddress'
value={ address } />
<Input
label='address name'
hint='a descriptive name for the entry'
error={ nameError }
value={ name }
onChange={ this.onEditName } />
hint={
<FormattedMessage
id='addAddress.input.name.hint'
defaultMessage='a descriptive name for the entry' />
}
label={
<FormattedMessage
id='addAddress.input.name.label'
defaultMessage='address name' />
}
onChange={ this.onEditName }
ref='inputName'
value={ name } />
<Input
multiLine
rows={ 1 }
label='(optional) address description'
hint='an expanded description for the entry'
value={ description }
onChange={ this.onEditDescription } />
hint={
<FormattedMessage
id='addAddress.input.description.hint'
defaultMessage='an expanded description for the entry' />
}
label={
<FormattedMessage
id='addAddress.input.description.label'
defaultMessage='(optional) address description' />
}
onChange={ this.onEditDescription }
ref='inputDescription'
value={ description } />
</Form>
);
}
onEditAddress = (event, _address) => {
const { contacts } = this.props;
let { address, addressError } = validateAddress(_address);
if (!addressError) {
const contact = contacts[address];
if (contact) {
addressError = ERRORS.duplicateAddress;
}
}
this.setState({
address,
addressError
});
onEditAddress = (event, address) => {
this.store.setAddress(address);
}
onEditDescription = (event, description) => {
this.setState({
description
});
this.store.setDescription(description);
}
onEditName = (event, _name) => {
const { name, nameError } = validateName(_name);
this.setState({
name,
nameError
});
onEditName = (event, name) => {
this.store.setName(name);
}
onAdd = () => {
const { api } = this.context;
const { address, name, description } = this.state;
Promise.all([
api.parity.setAccountName(address, name),
api.parity.setAccountMeta(address, {
description,
timestamp: Date.now(),
deleted: false
})
]).catch((error) => {
console.error('onAdd', error);
});
this.store.add();
this.props.onClose();
}

View File

@@ -0,0 +1,32 @@
// Copyright 2015, 2016 Parity Technologies (UK) Ltd.
// This file is part of Parity.
// Parity is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// Parity is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with Parity. If not, see <http://www.gnu.org/licenses/>.
import { shallow } from 'enzyme';
import React from 'react';
import AddAddress from './';
describe('modals/AddAddress', () => {
describe('rendering', () => {
it('renders defaults', () => {
expect(
shallow(
<AddAddress />
)
).to.be.ok;
});
});
});

View File

@@ -0,0 +1,87 @@
// Copyright 2015, 2016 Parity Technologies (UK) Ltd.
// This file is part of Parity.
// Parity is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// Parity is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with Parity. If not, see <http://www.gnu.org/licenses/>.
import { action, computed, transaction, observable } from 'mobx';
import { ERRORS, validateAddress, validateName } from '~/util/validation';
export default class Store {
@observable address = '';
@observable addressError = ERRORS.invalidAddress;
@observable createError = null;
@observable description = '';
@observable name = '';
@observable nameError = ERRORS.invalidName;
constructor (api, contacts) {
this._api = api;
this._contacts = contacts;
}
@computed get hasError () {
return !!(this.addressError || this.nameError);
}
@action setAddress = (_address) => {
let { address, addressError } = validateAddress(_address);
if (!addressError) {
const contact = this._contacts[address];
if (contact) {
addressError = ERRORS.duplicateAddress;
}
}
transaction(() => {
this.address = address;
this.addressError = addressError;
});
}
@action setCreateError = (error) => {
this.createError = error;
}
@action setDescription = (description) => {
this.description = description;
}
@action setName = (_name) => {
const { name, nameError } = validateName(_name);
transaction(() => {
this.name = name;
this.nameError = nameError;
});
}
add () {
return Promise
.all([
this._api.parity.setAccountName(this.address, this.name),
this._api.parity.setAccountMeta(this.address, {
description: this.description,
timestamp: Date.now(),
deleted: false
})
])
.catch((error) => {
console.warn('Store:add', error);
this.setCreateError(error);
});
}
}

View File

@@ -0,0 +1,128 @@
// Copyright 2015, 2016 Parity Technologies (UK) Ltd.
// This file is part of Parity.
// Parity is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// Parity is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with Parity. If not, see <http://www.gnu.org/licenses/>.
import sinon from 'sinon';
import Store from './store';
import { TEST_ADDR_A, TEST_ADDR_B, TEST_CONTACTS } from './store.test.js';
describe('modals/AddAddress/store', () => {
let store;
describe('@action', () => {
beforeEach(() => {
store = new Store(null, TEST_CONTACTS);
});
describe('setAddress', () => {
it('successfully sets non-existent addresses', () => {
store.setAddress(TEST_ADDR_B);
expect(store.addressError).to.be.null;
expect(store.address).to.equal(TEST_ADDR_B);
});
it('fails on invalid addresses', () => {
store.setAddress('0xinvalid');
expect(store.addressError).not.to.be.null;
});
it('fails when an address is already added', () => {
store.setAddress(TEST_ADDR_A);
expect(store.addressError).not.to.be.null;
});
});
describe('setName', () => {
it('sucessfully sets valid names', () => {
const name = 'Test Name';
store.setName(name);
expect(store.nameError).to.be.null;
expect(store.name).to.equal(name);
});
it('fails when name is invalid', () => {
store.setName(null);
expect(store.nameError).not.to.be.null;
});
});
});
describe('@computed', () => {
beforeEach(() => {
store = new Store(null, TEST_CONTACTS);
});
describe('hasError', () => {
beforeEach(() => {
store.setAddress(TEST_ADDR_B);
store.setName('Test Name');
});
it('returns false proper inputs', () => {
expect(store.hasError).to.be.false;
});
it('returns true with addressError', () => {
store.setAddress(TEST_ADDR_A);
expect(store.addressError).not.to.be.null;
expect(store.hasError).to.be.true;
});
it('returns true with nameError', () => {
store.setName(null);
expect(store.nameError).not.to.be.null;
expect(store.hasError).to.be.true;
});
});
});
describe('methods', () => {
let api;
beforeEach(() => {
api = {
parity: {
setAccountMeta: sinon.stub().resolves(true),
setAccountName: sinon.stub().resolves(true)
}
};
store = new Store(api, {});
});
describe('add', () => {
it('calls setAccountMeta', () => {
store.add();
expect(api.parity.setAccountMeta).to.have.been.called;
});
it('calls setAccountName', () => {
store.add();
expect(api.parity.setAccountName).to.have.been.called;
});
});
});
});

View File

@@ -0,0 +1,28 @@
// Copyright 2015, 2016 Parity Technologies (UK) Ltd.
// This file is part of Parity.
// Parity is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// Parity is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with Parity. If not, see <http://www.gnu.org/licenses/>.
const TEST_ADDR_A = '0x63Cf90D3f0410092FC0fca41846f596223979195';
const TEST_ADDR_B = '0x00A40dEfa9933e82244bE542Fa7F8748eCCdd457';
const TEST_CONTACTS = {
[TEST_ADDR_A]: { name: 'test', meta: {} }
};
export {
TEST_ADDR_A,
TEST_ADDR_B,
TEST_CONTACTS
};

View File

@@ -19,6 +19,8 @@ import { isEqual } from 'lodash';
import { fetchBalances } from './balancesActions';
import { attachWallets } from './walletActions';
import MethodDecodingStore from '~/ui/MethodDecoding/methodDecodingStore';
export function personalAccountsInfo (accountsInfo) {
const accounts = {};
const contacts = {};
@@ -41,6 +43,9 @@ export function personalAccountsInfo (accountsInfo) {
}
});
// Load user contracts for Method Decoding
MethodDecodingStore.loadContracts(contracts);
return (dispatch) => {
const data = {
accountsInfo,

View File

@@ -16,6 +16,7 @@
import React, { Component, PropTypes } from 'react';
import { MenuItem } from 'material-ui';
import { isEqual, pick } from 'lodash';
import AutoComplete from '../AutoComplete';
import IdentityIcon from '../../IdentityIcon';
@@ -31,19 +32,20 @@ export default class AddressSelect extends Component {
}
static propTypes = {
disabled: PropTypes.bool,
onChange: PropTypes.func.isRequired,
accounts: PropTypes.object,
allowInput: PropTypes.bool,
balances: PropTypes.object,
contacts: PropTypes.object,
contracts: PropTypes.object,
wallets: PropTypes.object,
label: PropTypes.string,
hint: PropTypes.string,
disabled: PropTypes.bool,
error: PropTypes.string,
value: PropTypes.string,
hint: PropTypes.string,
label: PropTypes.string,
tokens: PropTypes.object,
onChange: PropTypes.func.isRequired,
allowInput: PropTypes.bool,
balances: PropTypes.object
value: PropTypes.string,
wallets: PropTypes.object
}
state = {
@@ -53,6 +55,9 @@ export default class AddressSelect extends Component {
value: ''
}
// Cache autocomplete items
items = {}
entriesFromProps (props = this.props) {
const { accounts = {}, contacts = {}, contracts = {}, wallets = {} } = props;
@@ -76,6 +81,15 @@ export default class AddressSelect extends Component {
return { autocompleteEntries, entries };
}
shouldComponentUpdate (nextProps, nextState) {
const keys = [ 'error', 'value' ];
const prevValues = pick(this.props, keys);
const nextValues = pick(nextProps, keys);
return !isEqual(prevValues, nextValues);
}
componentWillMount () {
const { value } = this.props;
const { entries, autocompleteEntries } = this.entriesFromProps();
@@ -143,14 +157,21 @@ export default class AddressSelect extends Component {
renderItem = (entry) => {
const { address, name } = entry;
return {
text: name && name.toUpperCase() || address,
value: this.renderMenuItem(address),
address
};
const _balance = this.getBalance(address);
const balance = _balance ? _balance.toNumber() : _balance;
if (!this.items[address] || this.items[address].balance !== balance) {
this.items[address] = {
text: name && name.toUpperCase() || address,
value: this.renderMenuItem(address),
address, balance
};
}
return this.items[address];
}
renderBalance (address) {
getBalance (address) {
const { balances = {} } = this.props;
const balance = balances[address];
@@ -164,7 +185,12 @@ export default class AddressSelect extends Component {
return null;
}
const value = fromWei(ethToken.value);
return ethToken.value;
}
renderBalance (address) {
const balance = this.getBalance(address);
const value = fromWei(balance);
return (
<div className={ styles.balance }>

View File

@@ -0,0 +1,24 @@
/* Copyright 2015, 2016 Ethcore (UK) Ltd.
/* This file is part of Parity.
/*
/* Parity is free software: you can redistribute it and/or modify
/* it under the terms of the GNU General Public License as published by
/* the Free Software Foundation, either version 3 of the License, or
/* (at your option) any later version.
/*
/* Parity is distributed in the hope that it will be useful,
/* but WITHOUT ANY WARRANTY; without even the implied warranty of
/* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
/* GNU General Public License for more details.
/*
/* You should have received a copy of the GNU General Public License
/* along with Parity. If not, see <http://www.gnu.org/licenses/>.
*/
.item {
&:last-child {
&.divider {
display: none;
}
}
}

View File

@@ -21,13 +21,18 @@ import { PopoverAnimationVertical } from 'material-ui/Popover';
import { isEqual } from 'lodash';
import styles from './autocomplete.css';
// Hack to prevent "Unknown prop `disableFocusRipple` on <hr> tag" error
class Divider extends Component {
static muiName = MUIDivider.muiName;
render () {
return (
<div style={ { margin: '0.25em 0' } }>
<div
style={ { margin: '0.25em 0' } }
className={ [styles.item, styles.divider].join(' ') }
>
<MUIDivider style={ { height: 2 } } />
</div>
);
@@ -143,11 +148,16 @@ export default class AutoComplete extends Component {
if (renderItem && typeof renderItem === 'function') {
item = renderItem(entry);
// Add the item class to the entry
const classNames = [ styles.item ].concat(item.value.props.className);
item.value = React.cloneElement(item.value, { className: classNames.join(' ') });
} else {
item = {
text: entry,
value: (
<MenuItem
className={ styles.item }
primaryText={ entry }
/>
)
@@ -160,6 +170,7 @@ export default class AutoComplete extends Component {
}
item.divider = currentDivider;
item.entry = entry;
return item;
}).filter((item) => item !== undefined);
@@ -215,13 +226,8 @@ export default class AutoComplete extends Component {
return;
}
const { entries } = this.props;
const entriesArray = (entries instanceof Array)
? entries
: Object.values(entries);
const entry = entriesArray[idx];
const { dataSource } = this.state;
const { entry } = dataSource[idx];
this.handleOnChange(entry);
this.setState({ entry, open: false });

View File

@@ -18,6 +18,8 @@ import React, { Component, PropTypes } from 'react';
import { TextField } from 'material-ui';
import { noop } from 'lodash';
import { nodeOrStringProptype } from '~/util/proptypes';
import CopyToClipboard from '../../CopyToClipboard';
import styles from './input.css';
@@ -41,18 +43,21 @@ const NAME_ID = ' ';
export default class Input extends Component {
static propTypes = {
children: PropTypes.node,
className: PropTypes.string,
disabled: PropTypes.bool,
readOnly: PropTypes.bool,
allowCopy: PropTypes.oneOfType([
PropTypes.string,
PropTypes.bool
]),
floatCopy: PropTypes.bool,
children: PropTypes.node,
className: PropTypes.string,
disabled: PropTypes.bool,
error: PropTypes.string,
hint: PropTypes.string,
label: PropTypes.string,
readOnly: PropTypes.bool,
floatCopy: PropTypes.bool,
hint: nodeOrStringProptype(),
hideUnderline: PropTypes.bool,
label: nodeOrStringProptype(),
max: PropTypes.any,
min: PropTypes.any,
multiLine: PropTypes.bool,
onBlur: PropTypes.func,
onChange: PropTypes.func,
@@ -61,26 +66,26 @@ export default class Input extends Component {
rows: PropTypes.number,
type: PropTypes.string,
submitOnBlur: PropTypes.bool,
hideUnderline: PropTypes.bool,
style: PropTypes.object,
value: PropTypes.oneOfType([
PropTypes.number, PropTypes.string
]),
min: PropTypes.any,
max: PropTypes.any,
style: PropTypes.object
PropTypes.number,
PropTypes.string
])
};
static defaultProps = {
submitOnBlur: true,
readOnly: false,
allowCopy: false,
hideUnderline: false,
floatCopy: false,
readOnly: false,
submitOnBlur: true,
style: {}
}
state = {
value: typeof this.props.value === 'undefined' ? '' : this.props.value
value: typeof this.props.value === 'undefined'
? ''
: this.props.value
}
componentWillReceiveProps (newProps) {
@@ -114,38 +119,29 @@ export default class Input extends Component {
autoComplete='off'
className={ className }
errorText={ error }
floatingLabelFixed
floatingLabelText={ label }
fullWidth
hintText={ hint }
id={ NAME_ID }
inputStyle={ inputStyle }
fullWidth
max={ max }
min={ min }
multiLine={ multiLine }
name={ NAME_ID }
onBlur={ this.onBlur }
onChange={ this.onChange }
onKeyDown={ this.onKeyDown }
onPaste={ this.onPaste }
readOnly={ readOnly }
rows={ rows }
style={ textFieldStyle }
type={ type || 'text' }
underlineDisabledStyle={ UNDERLINE_DISABLED }
underlineStyle={ readOnly ? UNDERLINE_READONLY : UNDERLINE_NORMAL }
underlineFocusStyle={ readOnly ? { display: 'none' } : null }
underlineShow={ !hideUnderline }
value={ value }
>
value={ value }>
{ children }
</TextField>
</div>
@@ -159,11 +155,14 @@ export default class Input extends Component {
if (!allowCopy) {
return null;
}
const text = typeof allowCopy === 'string'
? allowCopy
: value;
const style = hideUnderline ? {} : { position: 'relative', top: '2px' };
const style = hideUnderline
? {}
: { position: 'relative', top: '2px' };
return (
<div className={ styles.copy } style={ style }>

View File

@@ -18,28 +18,30 @@ import React, { Component, PropTypes } from 'react';
import { connect } from 'react-redux';
import { bindActionCreators } from 'redux';
import Input from '../Input';
import IdentityIcon from '../../IdentityIcon';
import util from '~/api/util';
import { nodeOrStringProptype } from '~/util/proptypes';
import IdentityIcon from '../../IdentityIcon';
import Input from '../Input';
import styles from './inputAddress.css';
class InputAddress extends Component {
static propTypes = {
accountsInfo: PropTypes.object,
allowCopy: PropTypes.bool,
className: PropTypes.string,
disabled: PropTypes.bool,
error: PropTypes.string,
label: PropTypes.string,
hint: PropTypes.string,
value: PropTypes.string,
accountsInfo: PropTypes.object,
tokens: PropTypes.object,
text: PropTypes.bool,
hideUnderline: PropTypes.bool,
hint: nodeOrStringProptype(),
label: nodeOrStringProptype(),
onChange: PropTypes.func,
onSubmit: PropTypes.func,
hideUnderline: PropTypes.bool,
allowCopy: PropTypes.bool,
small: PropTypes.bool
small: PropTypes.bool,
text: PropTypes.bool,
tokens: PropTypes.object,
value: PropTypes.string
};
static defaultProps = {
@@ -49,8 +51,8 @@ class InputAddress extends Component {
};
render () {
const { className, disabled, error, label, hint, value, text } = this.props;
const { small, allowCopy, hideUnderline, onSubmit, accountsInfo, tokens } = this.props;
const { className, disabled, error, hint, label, text, value } = this.props;
const { accountsInfo, allowCopy, hideUnderline, onSubmit, small, tokens } = this.props;
const account = accountsInfo[value] || tokens[value];
@@ -68,17 +70,20 @@ class InputAddress extends Component {
return (
<div className={ containerClasses.join(' ') }>
<Input
allowCopy={ allowCopy && (disabled ? value : false) }
className={ classes.join(' ') }
disabled={ disabled }
label={ label }
hint={ hint }
error={ error }
value={ text && account ? account.name : value }
hideUnderline={ hideUnderline }
hint={ hint }
label={ label }
onChange={ this.handleInputChange }
onSubmit={ onSubmit }
allowCopy={ allowCopy && (disabled ? value : false) }
hideUnderline={ hideUnderline }
/>
value={
text && account
? account.name
: value
} />
{ icon }
</div>
);
@@ -128,8 +133,8 @@ class InputAddress extends Component {
}
function mapStateToProps (state) {
const { accountsInfo } = state.personal;
const { tokens } = state.balances;
const { accountsInfo } = state.personal;
return {
accountsInfo,

View File

@@ -17,16 +17,14 @@
import BigNumber from 'bignumber.js';
import React, { Component, PropTypes } from 'react';
import { connect } from 'react-redux';
import { bindActionCreators } from 'redux';
import CircularProgress from 'material-ui/CircularProgress';
import Contracts from '~/contracts';
import { Input, InputAddress } from '../Form';
import MethodDecodingStore from './methodDecodingStore';
import styles from './methodDecoding.css';
const ASCII_INPUT = /^[a-z0-9\s,?;.:/!()-_@'"#]+$/i;
const CONTRACT_CREATE = '0x60606040';
const TOKEN_METHODS = {
'0xa9059cbb': 'transfer(to,value)'
};
@@ -38,19 +36,17 @@ class MethodDecoding extends Component {
static propTypes = {
address: PropTypes.string.isRequired,
tokens: PropTypes.object,
token: PropTypes.object,
transaction: PropTypes.object,
historic: PropTypes.bool
}
state = {
contractAddress: null,
method: null,
methodName: null,
methodInputs: null,
methodParams: null,
methodSignature: null,
token: null,
isContract: false,
isDeploy: false,
isReceived: false,
@@ -59,14 +55,29 @@ class MethodDecoding extends Component {
inputType: 'auto'
}
componentWillMount () {
const lookupResult = this.lookup();
methodDecodingStore = MethodDecodingStore.get(this.context.api);
if (typeof lookupResult === 'object' && typeof lookupResult.then === 'function') {
lookupResult.then(() => this.setState({ isLoading: false }));
} else {
this.setState({ isLoading: false });
}
componentWillMount () {
const { address, transaction } = this.props;
this
.methodDecodingStore
.lookup(address, transaction)
.then((lookup) => {
const newState = {
methodName: lookup.name,
methodInputs: lookup.inputs,
methodParams: lookup.params,
methodSignature: lookup.signature,
isContract: lookup.contract,
isDeploy: lookup.deploy,
isLoading: false,
isReceived: lookup.received
};
this.setState(newState);
});
}
render () {
@@ -116,7 +127,8 @@ class MethodDecoding extends Component {
}
renderAction () {
const { methodName, methodInputs, methodSignature, token, isDeploy, isReceived, isContract } = this.state;
const { token } = this.props;
const { methodName, methodInputs, methodSignature, isDeploy, isReceived, isContract } = this.state;
if (isDeploy) {
return this.renderDeploy();
@@ -378,7 +390,7 @@ class MethodDecoding extends Component {
}
renderTokenValue (value) {
const { token } = this.state;
const { token } = this.props;
return (
<span className={ styles.tokenValue }>
@@ -436,96 +448,18 @@ class MethodDecoding extends Component {
});
}
lookup () {
const { transaction } = this.props;
if (!transaction) {
return;
}
const { api } = this.context;
const { address, tokens } = this.props;
const isReceived = transaction.to === address;
const contractAddress = isReceived ? transaction.from : transaction.to;
const input = transaction.input || transaction.data;
const token = (tokens || {})[contractAddress];
this.setState({ token, isReceived, contractAddress });
if (!input || input === '0x') {
return;
}
const { signature, paramdata } = api.util.decodeCallData(input);
this.setState({ methodSignature: signature, methodParams: paramdata });
if (!signature || signature === CONTRACT_CREATE || transaction.creates) {
this.setState({ isDeploy: true });
return;
}
if (contractAddress === '0x') {
return;
}
return api.eth
.getCode(contractAddress || transaction.creates)
.then((bytecode) => {
const isContract = bytecode && /^(0x)?([0]*[1-9a-f]+[0]*)+$/.test(bytecode);
this.setState({ isContract });
if (!isContract) {
return;
}
return Contracts.get()
.signatureReg
.lookup(signature)
.then((method) => {
let methodInputs = null;
let methodName = null;
if (method && method.length) {
const { methodParams } = this.state;
const abi = api.util.methodToAbi(method);
methodName = abi.name;
methodInputs = api.util
.decodeMethodInput(abi, methodParams)
.map((value, index) => {
const type = abi.inputs[index].type;
return { type, value };
});
}
this.setState({
method,
methodName,
methodInputs,
bytecode
});
});
})
.catch((error) => {
console.warn('lookup', error);
});
}
}
function mapStateToProps (state) {
const { tokens } = state.balances;
function mapStateToProps (initState, initProps) {
const { tokens } = initState.balances;
const { address } = initProps;
return { tokens };
const token = (tokens || {})[address];
return () => {
return { token };
};
}
function mapDispatchToProps (dispatch) {
return bindActionCreators({}, dispatch);
}
export default connect(
mapStateToProps,
mapDispatchToProps
mapStateToProps
)(MethodDecoding);

View File

@@ -0,0 +1,216 @@
// Copyright 2015, 2016 Ethcore (UK) Ltd.
// This file is part of Parity.
// Parity is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// Parity is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with Parity. If not, see <http://www.gnu.org/licenses/>.
import Contracts from '~/contracts';
import Abi from '~/abi';
import * as abis from '~/contracts/abi';
const CONTRACT_CREATE = '0x60606040';
let instance = null;
export default class MethodDecodingStore {
api = null;
_isContract = {};
_methods = {};
constructor (api, contracts = {}) {
this.api = api;
// Load the signatures from the local ABIs
Object.keys(abis).forEach((abiKey) => {
this.loadFromAbi(abis[abiKey]);
});
this.addContracts(contracts);
}
addContracts (contracts = {}) {
// Load the User defined contracts
Object.values(contracts).forEach((contract) => {
if (!contract || !contract.meta || !contract.meta.abi) {
return;
}
this.loadFromAbi(contract.meta.abi);
});
}
loadFromAbi (_abi) {
const abi = new Abi(_abi);
abi
.functions
.map((f) => ({ sign: f.signature, abi: f.abi }))
.forEach((mapping) => {
const sign = (/^0x/.test(mapping.sign) ? '' : '0x') + mapping.sign;
this._methods[sign] = mapping.abi;
});
}
static get (api, contracts = {}) {
if (!instance) {
instance = new MethodDecodingStore(api, contracts);
}
// Set API if not set yet
if (!instance.api) {
instance.api = api;
}
return instance;
}
static loadContracts (contracts = {}) {
if (!instance) {
// Just create the instance with null API
MethodDecodingStore.get(null, contracts);
} else {
instance.addContracts(contracts);
}
}
/**
* Looks up a transaction in the context of the given
* address
*
* @param {String} address The address contract
* @param {Object} transaction The transaction to lookup
* @return {Promise} The result of the lookup. Resolves with:
* {
* contract: Boolean,
* deploy: Boolean,
* inputs: Array,
* name: String,
* params: Array,
* received: Boolean,
* signature: String
* }
*/
lookup (address, transaction) {
const result = {};
if (!transaction) {
return Promise.resolve(result);
}
const isReceived = transaction.to === address;
const contractAddress = isReceived ? transaction.from : transaction.to;
const input = transaction.input || transaction.data;
result.received = isReceived;
// No input, should be a ETH transfer
if (!input || input === '0x') {
return Promise.resolve(result);
}
const { signature, paramdata } = this.api.util.decodeCallData(input);
result.signature = signature;
result.params = paramdata;
// Contract deployment
if (!signature || signature === CONTRACT_CREATE || transaction.creates) {
return Promise.resolve({ ...result, deploy: true });
}
return this
.isContract(contractAddress || transaction.creates)
.then((isContract) => {
result.contract = isContract;
if (!isContract) {
return result;
}
return this
.fetchMethodAbi(signature)
.then((abi) => {
let methodName = null;
let methodInputs = null;
if (abi) {
methodName = abi.name;
methodInputs = this.api.util
.decodeMethodInput(abi, paramdata)
.map((value, index) => {
const type = abi.inputs[index].type;
return { type, value };
});
}
return {
...result,
name: methodName,
inputs: methodInputs
};
});
})
.catch((error) => {
console.warn('lookup', error);
});
}
fetchMethodAbi (signature) {
if (this._methods[signature] !== undefined) {
return Promise.resolve(this._methods[signature]);
}
this._methods[signature] = Contracts.get()
.signatureReg
.lookup(signature)
.then((method) => {
let abi = null;
if (method && method.length) {
abi = this.api.util.methodToAbi(method);
}
this._methods[signature] = abi;
return this._methods[signature];
});
return Promise.resolve(this._methods[signature]);
}
/**
* Checks (and caches) if the given address is a
* Contract or not, from its fetched bytecode
*/
isContract (contractAddress) {
// If zero address, it isn't a contract
if (/^(0x)?0*$/.test(contractAddress)) {
return Promise.resolve(false);
}
if (this._isContract[contractAddress]) {
return Promise.resolve(this._isContract[contractAddress]);
}
this._isContract[contractAddress] = this.api.eth
.getCode(contractAddress)
.then((bytecode) => {
// Is a contract if the address contains *valid* bytecode
const _isContract = bytecode && /^(0x)?([0]*[1-9a-f]+[0]*)+$/.test(bytecode);
this._isContract[contractAddress] = _isContract;
return this._isContract[contractAddress];
});
return Promise.resolve(this._isContract[contractAddress]);
}
}

View File

@@ -42,11 +42,11 @@ class Modal extends Component {
className: PropTypes.string,
compact: PropTypes.bool,
current: PropTypes.number,
waiting: PropTypes.array,
settings: PropTypes.object.isRequired,
steps: PropTypes.array,
title: nodeOrStringProptype(),
visible: PropTypes.bool.isRequired,
settings: PropTypes.object.isRequired
waiting: PropTypes.array
}
render () {
@@ -55,23 +55,23 @@ class Modal extends Component {
const contentStyle = muiTheme.parity.getBackgroundStyle(null, settings.backgroundSeed);
const header = (
<Title
current={ current }
busy={ busy }
waiting={ waiting }
current={ current }
steps={ steps }
title={ title } />
title={ title }
waiting={ waiting } />
);
const classes = `${styles.dialog} ${className}`;
return (
<Dialog
className={ classes }
actions={ actions }
actionsContainerClassName={ styles.actions }
actionsContainerStyle={ ACTIONS_STYLE }
autoDetectWindowHeight={ false }
autoScrollBodyContent
actionsContainerClassName={ styles.actions }
bodyClassName={ styles.body }
className={ classes }
contentClassName={ styles.content }
contentStyle={ contentStyle }
modal
@@ -82,7 +82,12 @@ class Modal extends Component {
style={ DIALOG_STYLE }
title={ header }
titleStyle={ TITLE_STYLE }>
<Container light compact={ compact } style={ { transition: 'none' } }>
<Container
compact={ compact }
light
style={
{ transition: 'none' }
}>
{ children }
</Container>
</Dialog>

View File

@@ -19,7 +19,7 @@ import { connect } from 'react-redux';
import { bindActionCreators } from 'redux';
import etherscan from '~/3rdparty/etherscan';
import { Container, TxList } from '~/ui';
import { Container, TxList, Loading } from '~/ui';
import styles from './transactions.css';
@@ -60,19 +60,32 @@ class Transactions extends Component {
}
render () {
const { address } = this.props;
const { hashes } = this.state;
return (
<Container title='transactions'>
<TxList
address={ address }
hashes={ hashes } />
{ this.renderTransactionList() }
{ this.renderEtherscanFooter() }
</Container>
);
}
renderTransactionList () {
const { address } = this.props;
const { hashes, loading } = this.state;
if (loading) {
return (
<Loading />
);
}
return (
<TxList
address={ address }
hashes={ hashes }
/>
);
}
renderEtherscanFooter () {
const { traceMode } = this.props;

View File

@@ -32,6 +32,10 @@
flex: 1;
flex-direction: row;
// Fallback for browsers not supporting `calc`
min-height: 90vh;
min-height: calc(100vh - 8em);
> * {
margin: 0;

View File

@@ -15,11 +15,13 @@
// along with Parity. If not, see <http://www.gnu.org/licenses/>.
import 'isomorphic-fetch';
import 'mock-local-storage';
import es6Promise from 'es6-promise';
es6Promise.polyfill();
import 'mock-local-storage';
import injectTapEventPlugin from 'react-tap-event-plugin';
injectTapEventPlugin();
import chai from 'chai';
import chaiAsPromised from 'chai-as-promised';