Eslint formatting updates (#4234)

* Eslint updated (newline-after-var)

* Fix newline-after-var

* Eslint updated (one-var-declaration-per-line)

* Fix one-var-declaration-per-line

* Fix additional errors

* Lint after merge
This commit is contained in:
Jaco Greeff 2017-01-23 13:39:52 +01:00 committed by GitHub
parent cff64233b4
commit 66e540edf8
165 changed files with 346 additions and 21 deletions

View File

@ -13,6 +13,7 @@
"rules": { "rules": {
"curly": ["error", "all"], "curly": ["error", "all"],
"jsx-quotes": ["error", "prefer-single"], "jsx-quotes": ["error", "prefer-single"],
"newline-after-var": ["error", "always"],
"no-alert": "error", "no-alert": "error",
"no-debugger": "error", "no-debugger": "error",
"no-duplicate-imports": ["error", { "no-duplicate-imports": ["error", {
@ -20,6 +21,7 @@
}], }],
"object-curly-spacing": ["error", "always"], "object-curly-spacing": ["error", "always"],
"object-property-newline": 0, "object-property-newline": 0,
"one-var-declaration-per-line": ["error", "always"],
"padded-blocks": ["error", { "padded-blocks": ["error", {
"blocks": "never", "blocks": "never",
"classes": "never", "classes": "never",

View File

@ -49,6 +49,7 @@ export const hasReceivedCode = (email, address, isTestnet = false) => {
export const postToServer = (query, isTestnet = false) => { export const postToServer = (query, isTestnet = false) => {
const port = isTestnet ? 28443 : 18443; const port = isTestnet ? 28443 : 18443;
query = stringify(query); query = stringify(query);
return fetch(`https://email-verification.parity.io:${port}/?${query}`, { return fetch(`https://email-verification.parity.io:${port}/?${query}`, {

View File

@ -49,6 +49,7 @@ export const hasReceivedCode = (number, address, isTestnet = false) => {
export const postToServer = (query, isTestnet = false) => { export const postToServer = (query, isTestnet = false) => {
const port = isTestnet ? 8443 : 443; const port = isTestnet ? 8443 : 443;
query = stringify(query); query = stringify(query);
return fetch(`https://sms-verification.parity.io:${port}/?${query}`, { return fetch(`https://sms-verification.parity.io:${port}/?${query}`, {

View File

@ -37,6 +37,7 @@ export default class Decoder {
return params.map((param) => { return params.map((param) => {
const result = Decoder.decodeParam(param, slices, offset); const result = Decoder.decodeParam(param, slices, offset);
offset = result.newOffset; offset = result.newOffset;
return result.token; return result.token;
}); });
@ -121,6 +122,7 @@ export default class Decoder {
for (let idx = 0; idx < length; idx++) { for (let idx = 0; idx < length; idx++) {
const result = Decoder.decodeParam(param.subtype, slices, newOffset); const result = Decoder.decodeParam(param.subtype, slices, newOffset);
newOffset = result.newOffset; newOffset = result.newOffset;
tokens.push(result.token); tokens.push(result.token);
} }
@ -132,6 +134,7 @@ export default class Decoder {
for (let idx = 0; idx < param.length; idx++) { for (let idx = 0; idx < param.length; idx++) {
const result = Decoder.decodeParam(param.subtype, slices, newOffset); const result = Decoder.decodeParam(param.subtype, slices, newOffset);
newOffset = result.newOffset; newOffset = result.newOffset;
tokens.push(result.token); tokens.push(result.token);
} }

View File

@ -100,6 +100,7 @@ describe('abi/decoder/Decoder', () => {
it('throws an error on invalid param type', () => { it('throws an error on invalid param type', () => {
const pt = new ParamType('address'); const pt = new ParamType('address');
pt._type = 'noMatch'; pt._type = 'noMatch';
expect(() => Decoder.decodeParam(pt)).to.throw(/noMatch/); expect(() => Decoder.decodeParam(pt)).to.throw(/noMatch/);

View File

@ -93,6 +93,7 @@ describe('abi/encoder/Encoder', () => {
it('throws an Error on invalid tokens', () => { it('throws an Error on invalid tokens', () => {
const token = new Token('address'); const token = new Token('address');
token._type = 'noMatch'; token._type = 'noMatch';
expect(() => Encoder.encodeToken(token)).to.throw(/noMatch/); expect(() => Encoder.encodeToken(token)).to.throw(/noMatch/);

View File

@ -27,6 +27,7 @@ export default class Event {
this._anonymous = !!abi.anonymous; this._anonymous = !!abi.anonymous;
const { id, name, signature } = eventSignature(abi.name, this.inputParamTypes()); const { id, name, signature } = eventSignature(abi.name, this.inputParamTypes());
this._id = id; this._id = id;
this._name = name; this._name = name;
this._signature = signature; this._signature = signature;

View File

@ -20,6 +20,7 @@ describe('abi/spec/event/EventParam', () => {
describe('constructor', () => { describe('constructor', () => {
it('sets the properties', () => { it('sets the properties', () => {
const param = new EventParam('foo', 'uint', true); const param = new EventParam('foo', 'uint', true);
expect(param.name).to.equal('foo'); expect(param.name).to.equal('foo');
expect(param.kind.type).to.equal('uint'); expect(param.kind.type).to.equal('uint');
expect(param.indexed).to.be.true; expect(param.indexed).to.be.true;

View File

@ -28,6 +28,7 @@ export default class Func {
this._outputs = Param.toParams(abi.outputs || []); this._outputs = Param.toParams(abi.outputs || []);
const { id, name, signature } = methodSignature(abi.name, this.inputParamTypes()); const { id, name, signature } = methodSignature(abi.name, this.inputParamTypes());
this._id = id; this._id = id;
this._name = name; this._name = name;
this._signature = signature; this._signature = signature;

View File

@ -47,6 +47,7 @@ function stringToBytes (input) {
return input; return input;
} else if (input.substr(0, 2) === '0x') { } else if (input.substr(0, 2) === '0x') {
const matches = input.substr(2).toLowerCase().match(/.{1,2}/g) || []; const matches = input.substr(2).toLowerCase().match(/.{1,2}/g) || [];
return matches.map((value) => parseInt(value, 16)); return matches.map((value) => parseInt(value, 16));
} else { } else {
return input.split('').map((char) => char.charCodeAt(0)); return input.split('').map((char) => char.charCodeAt(0));

View File

@ -40,6 +40,7 @@ function parseName (name) {
} }
const trimmedName = strName.slice(0, idx); const trimmedName = strName.slice(0, idx);
return { return {
strName: trimmedName, strName: trimmedName,
name: trimmedName name: trimmedName

View File

@ -22,6 +22,7 @@ describe('abi/util/sliceAs', () => {
describe('asAddress', () => { describe('asAddress', () => {
it('correctly returns the last 0x40 characters', () => { it('correctly returns the last 0x40 characters', () => {
const address = '1111111111222222222233333333334444444444'; const address = '1111111111222222222233333333334444444444';
expect(asAddress(`000000000000000000000000${address}`)).to.equal(`0x${address}`); expect(asAddress(`000000000000000000000000${address}`)).to.equal(`0x${address}`);
}); });
}); });

View File

@ -258,6 +258,7 @@ export default class Contract {
if (!func.constant) { if (!func.constant) {
func.postTransaction = (options, values = []) => { func.postTransaction = (options, values = []) => {
const _options = this._encodeOptions(func, this._addOptionsTo(options), values); const _options = this._encodeOptions(func, this._addOptionsTo(options), values);
return this._api.parity return this._api.parity
.postTransaction(_options) .postTransaction(_options)
.catch((error) => { .catch((error) => {
@ -268,6 +269,7 @@ export default class Contract {
func.estimateGas = (options, values = []) => { func.estimateGas = (options, values = []) => {
const _options = this._encodeOptions(func, this._addOptionsTo(options), values); const _options = this._encodeOptions(func, this._addOptionsTo(options), values);
return this._api.eth return this._api.eth
.estimateGas(_options) .estimateGas(_options)
.catch((error) => { .catch((error) => {
@ -303,6 +305,7 @@ export default class Contract {
} }
const options = this._getFilterOptions(event, _options); const options = this._getFilterOptions(event, _options);
options.fromBlock = 0; options.fromBlock = 0;
options.toBlock = 'latest'; options.toBlock = 'latest';
@ -318,6 +321,7 @@ export default class Contract {
if (eventName && !event) { if (eventName && !event) {
const events = this._events.map((evt) => evt.name).join(', '); const events = this._events.map((evt) => evt.name).join(', ');
throw new Error(`${eventName} is not a valid eventName, subscribe using one of ${events} (or null to include all)`); throw new Error(`${eventName} is not a valid eventName, subscribe using one of ${events} (or null to include all)`);
} }
@ -344,12 +348,14 @@ export default class Contract {
_createEthFilter (event = null, _options) { _createEthFilter (event = null, _options) {
const options = this._getFilterOptions(event, _options); const options = this._getFilterOptions(event, _options);
return this._api.eth.newFilter(options); return this._api.eth.newFilter(options);
} }
subscribe (eventName = null, options = {}, callback, autoRemove) { subscribe (eventName = null, options = {}, callback, autoRemove) {
try { try {
const event = this._findEvent(eventName); const event = this._findEvent(eventName);
return this._subscribe(event, options, callback, autoRemove); return this._subscribe(event, options, callback, autoRemove);
} catch (e) { } catch (e) {
return Promise.reject(e); return Promise.reject(e);
@ -374,6 +380,7 @@ export default class Contract {
_subscribe (event = null, _options, callback, autoRemove = false) { _subscribe (event = null, _options, callback, autoRemove = false) {
const subscriptionId = nextSubscriptionId++; const subscriptionId = nextSubscriptionId++;
const { skipInitFetch } = _options; const { skipInitFetch } = _options;
delete _options['skipInitFetch']; delete _options['skipInitFetch'];
return this return this

View File

@ -143,6 +143,7 @@ describe('api/contract/Contract', () => {
type: 'event' type: 'event'
} }
]); ]);
contract.at('6789'); contract.at('6789');
expect(Object.keys(contract.instance)).to.deep.equal([ expect(Object.keys(contract.instance)).to.deep.equal([

View File

@ -105,6 +105,7 @@ describe('api/format/input', () => {
['address'].forEach((input) => { ['address'].forEach((input) => {
it(`formats ${input} address as address`, () => { it(`formats ${input} address as address`, () => {
const block = {}; const block = {};
block[input] = address; block[input] = address;
const formatted = inFilter(block)[input]; const formatted = inFilter(block)[input];
@ -116,6 +117,7 @@ describe('api/format/input', () => {
['fromBlock', 'toBlock'].forEach((input) => { ['fromBlock', 'toBlock'].forEach((input) => {
it(`formats ${input} number as blockNumber`, () => { it(`formats ${input} number as blockNumber`, () => {
const block = {}; const block = {};
block[input] = 0x123; block[input] = 0x123;
const formatted = inFilter(block)[input]; const formatted = inFilter(block)[input];
@ -186,6 +188,7 @@ describe('api/format/input', () => {
['data'].forEach((input) => { ['data'].forEach((input) => {
it(`converts ${input} to hex data`, () => { it(`converts ${input} to hex data`, () => {
const block = {}; const block = {};
block[input] = '1234'; block[input] = '1234';
const formatted = inData(block[input]); const formatted = inData(block[input]);
@ -196,6 +199,7 @@ describe('api/format/input', () => {
['from', 'to'].forEach((input) => { ['from', 'to'].forEach((input) => {
it(`formats ${input} address as address`, () => { it(`formats ${input} address as address`, () => {
const block = {}; const block = {};
block[input] = address; block[input] = address;
const formatted = inOptions(block)[input]; const formatted = inOptions(block)[input];
@ -207,6 +211,7 @@ describe('api/format/input', () => {
['gas', 'gasPrice', 'value', 'minBlock', 'nonce'].forEach((input) => { ['gas', 'gasPrice', 'value', 'minBlock', 'nonce'].forEach((input) => {
it(`formats ${input} number as hexnumber`, () => { it(`formats ${input} number as hexnumber`, () => {
const block = {}; const block = {};
block[input] = 0x123; block[input] = 0x123;
const formatted = inOptions(block)[input]; const formatted = inOptions(block)[input];
@ -250,11 +255,13 @@ describe('api/format/input', () => {
describe('inTraceType', () => { describe('inTraceType', () => {
it('returns array of types as is', () => { it('returns array of types as is', () => {
const types = ['vmTrace', 'trace', 'stateDiff']; const types = ['vmTrace', 'trace', 'stateDiff'];
expect(inTraceType(types)).to.deep.equal(types); expect(inTraceType(types)).to.deep.equal(types);
}); });
it('formats single string type into array', () => { it('formats single string type into array', () => {
const type = 'vmTrace'; const type = 'vmTrace';
expect(inTraceType(type)).to.deep.equal([type]); expect(inTraceType(type)).to.deep.equal([type]);
}); });
}); });

View File

@ -59,6 +59,7 @@ describe('api/format/output', () => {
['author', 'miner'].forEach((input) => { ['author', 'miner'].forEach((input) => {
it(`formats ${input} address as address`, () => { it(`formats ${input} address as address`, () => {
const block = {}; const block = {};
block[input] = address; block[input] = address;
const formatted = outBlock(block)[input]; const formatted = outBlock(block)[input];
@ -70,6 +71,7 @@ describe('api/format/output', () => {
['difficulty', 'gasLimit', 'gasUsed', 'number', 'nonce', 'totalDifficulty'].forEach((input) => { ['difficulty', 'gasLimit', 'gasUsed', 'number', 'nonce', 'totalDifficulty'].forEach((input) => {
it(`formats ${input} number as hexnumber`, () => { it(`formats ${input} number as hexnumber`, () => {
const block = {}; const block = {};
block[input] = 0x123; block[input] = 0x123;
const formatted = outBlock(block)[input]; const formatted = outBlock(block)[input];
@ -81,6 +83,7 @@ describe('api/format/output', () => {
['timestamp'].forEach((input) => { ['timestamp'].forEach((input) => {
it(`formats ${input} number as Date`, () => { it(`formats ${input} number as Date`, () => {
const block = {}; const block = {};
block[input] = 0x57513668; block[input] = 0x57513668;
const formatted = outBlock(block)[input]; const formatted = outBlock(block)[input];
@ -219,6 +222,7 @@ describe('api/format/output', () => {
['contractAddress'].forEach((input) => { ['contractAddress'].forEach((input) => {
it(`formats ${input} address as address`, () => { it(`formats ${input} address as address`, () => {
const block = {}; const block = {};
block[input] = address; block[input] = address;
const formatted = outReceipt(block)[input]; const formatted = outReceipt(block)[input];
@ -230,6 +234,7 @@ describe('api/format/output', () => {
['blockNumber', 'cumulativeGasUsed', 'cumulativeGasUsed', 'gasUsed', 'transactionIndex'].forEach((input) => { ['blockNumber', 'cumulativeGasUsed', 'cumulativeGasUsed', 'gasUsed', 'transactionIndex'].forEach((input) => {
it(`formats ${input} number as hexnumber`, () => { it(`formats ${input} number as hexnumber`, () => {
const block = {}; const block = {};
block[input] = 0x123; block[input] = 0x123;
const formatted = outReceipt(block)[input]; const formatted = outReceipt(block)[input];
@ -283,6 +288,7 @@ describe('api/format/output', () => {
['from', 'to'].forEach((input) => { ['from', 'to'].forEach((input) => {
it(`formats ${input} address as address`, () => { it(`formats ${input} address as address`, () => {
const block = {}; const block = {};
block[input] = address; block[input] = address;
const formatted = outTransaction(block)[input]; const formatted = outTransaction(block)[input];
@ -294,6 +300,7 @@ describe('api/format/output', () => {
['blockNumber', 'gasPrice', 'gas', 'minBlock', 'nonce', 'transactionIndex', 'value'].forEach((input) => { ['blockNumber', 'gasPrice', 'gas', 'minBlock', 'nonce', 'transactionIndex', 'value'].forEach((input) => {
it(`formats ${input} number as hexnumber`, () => { it(`formats ${input} number as hexnumber`, () => {
const block = {}; const block = {};
block[input] = 0x123; block[input] = 0x123;
const formatted = outTransaction(block)[input]; const formatted = outTransaction(block)[input];

View File

@ -34,6 +34,7 @@ function stubApi (blockNumber) {
eth: { eth: {
blockNumber: () => { blockNumber: () => {
const stub = sinon.stub().resolves(new BigNumber(blockNumber || START_BLOCK))(); const stub = sinon.stub().resolves(new BigNumber(blockNumber || START_BLOCK))();
_calls.blockNumber.push(stub); _calls.blockNumber.push(stub);
return stub; return stub;
} }

View File

@ -36,6 +36,7 @@ function stubApi (accounts, info) {
parity: { parity: {
allAccountsInfo: () => { allAccountsInfo: () => {
const stub = sinon.stub().resolves(info || TEST_INFO)(); const stub = sinon.stub().resolves(info || TEST_INFO)();
_calls.allAccountsInfo.push(stub); _calls.allAccountsInfo.push(stub);
return stub; return stub;
} }
@ -43,6 +44,7 @@ function stubApi (accounts, info) {
eth: { eth: {
accounts: () => { accounts: () => {
const stub = sinon.stub().resolves(accounts || TEST_LIST)(); const stub = sinon.stub().resolves(accounts || TEST_LIST)();
_calls.listAccounts.push(stub); _calls.listAccounts.push(stub);
return stub; return stub;
} }

View File

@ -44,6 +44,7 @@ export const ERROR_CODES = {
export default class TransportError extends ExtendableError { export default class TransportError extends ExtendableError {
constructor (method, code, message) { constructor (method, code, message) {
const m = `${method}: ${code}: ${message}`; const m = `${method}: ${code}: ${message}`;
super(m); super(m);
this.code = code; this.code = code;

View File

@ -75,6 +75,7 @@ export default class Http extends JsonRpcBase {
console.error(`${method}(${JSON.stringify(params)}): ${response.error.code}: ${response.error.message}`); console.error(`${method}(${JSON.stringify(params)}): ${response.error.code}: ${response.error.message}`);
const error = new TransportError(method, response.error.code, response.error.message); const error = new TransportError(method, response.error.code, response.error.message);
throw error; throw error;
} }

View File

@ -212,6 +212,7 @@ export default class Ws extends JsonRpcBase {
} }
const error = new TransportError(method, result.error.code, result.error.message); const error = new TransportError(method, result.error.code, result.error.message);
reject(error); reject(error);
delete this._messages[result.id]; delete this._messages[result.id];

View File

@ -48,11 +48,13 @@ export function asciiToHex (string) {
export function padRight (input, length) { export function padRight (input, length) {
const value = toHex(input).substr(2, length * 2); const value = toHex(input).substr(2, length * 2);
return '0x' + value + range(length * 2 - value.length).map(() => '0').join(''); return '0x' + value + range(length * 2 - value.length).map(() => '0').join('');
} }
export function padLeft (input, length) { export function padLeft (input, length) {
const value = toHex(input).substr(2, length * 2); const value = toHex(input).substr(2, length * 2);
return '0x' + range(length * 2 - value.length).map(() => '0').join('') + value; return '0x' + range(length * 2 - value.length).map(() => '0').join('') + value;
} }

View File

@ -24,6 +24,7 @@ export function sha3 (value, options) {
if (forceHex || (!options && isHex(value))) { if (forceHex || (!options && isHex(value))) {
const bytes = hexToBytes(value); const bytes = hexToBytes(value);
return sha3(bytes); return sha3(bytes);
} }

View File

@ -24,6 +24,7 @@ describe('api/util/sha3', () => {
it('constructs a correct sha3 encoded as hex', () => { it('constructs a correct sha3 encoded as hex', () => {
const key = '000000000000000000000000391694e7e0b0cce554cb130d723a9d27458f9298' + '0000000000000000000000000000000000000000000000000000000000000001'; const key = '000000000000000000000000391694e7e0b0cce554cb130d723a9d27458f9298' + '0000000000000000000000000000000000000000000000000000000000000001';
expect(sha3(key, { encoding: 'hex' })).to.equal('0x6661e9d6d8b923d5bbaab1b96e1dd51ff6ea2a93520fdc9eb75d059238b8c5e9'); expect(sha3(key, { encoding: 'hex' })).to.equal('0x6661e9d6d8b923d5bbaab1b96e1dd51ff6ea2a93520fdc9eb75d059238b8c5e9');
expect(sha3(`0x${key}`, { encoding: 'hex' })).to.equal('0x6661e9d6d8b923d5bbaab1b96e1dd51ff6ea2a93520fdc9eb75d059238b8c5e9'); expect(sha3(`0x${key}`, { encoding: 'hex' })).to.equal('0x6661e9d6d8b923d5bbaab1b96e1dd51ff6ea2a93520fdc9eb75d059238b8c5e9');
}); });

View File

@ -67,6 +67,7 @@ export default class BadgeReg {
return this.fetchMeta(id) return this.fetchMeta(id)
.then(({ title, icon }) => { .then(({ title, icon }) => {
const data = { address, id, name, title, icon }; const data = { address, id, name, title, icon };
this.certifiers[id] = data; this.certifiers[id] = data;
return data; return data;
}); });
@ -87,6 +88,7 @@ export default class BadgeReg {
return this.fetchMeta(id) return this.fetchMeta(id)
.then(({ title, icon }) => { .then(({ title, icon }) => {
const data = { address, id, name, title, icon }; const data = { address, id, name, title, icon };
this.certifiers[id] = data; this.certifiers[id] = data;
return data; return data;
}); });

View File

@ -76,6 +76,7 @@ export const awaitPuzzle = (api, contract, account) => {
from: block.toNumber(), from: block.toNumber(),
filter: (log) => log.params.who.value === account filter: (log) => log.params.who.value === account
}); });
subscription.once('error', reject); subscription.once('error', reject);
subscription.once('log', subscription.unsubscribe); subscription.once('log', subscription.unsubscribe);
subscription.once('log', resolve); subscription.once('log', resolve);

View File

@ -293,6 +293,7 @@ export default class Deployment extends Component {
this.setState({ deployState: 'Gas estimated, Posting transaction to the network' }); this.setState({ deployState: 'Gas estimated, Posting transaction to the network' });
const gasPassed = gas.mul(1.2); const gasPassed = gas.mul(1.2);
options.gas = gasPassed.toFixed(0); options.gas = gasPassed.toFixed(0);
console.log(`gas estimated at ${gas.toFormat(0)}, passing ${gasPassed.toFormat(0)}`); console.log(`gas estimated at ${gas.toFormat(0)}, passing ${gasPassed.toFormat(0)}`);

View File

@ -37,6 +37,7 @@ export default class Events extends Component {
loadAllTokens() loadAllTokens()
.then((tokens) => { .then((tokens) => {
const addresses = tokens.map((token) => token.address); const addresses = tokens.map((token) => token.address);
this.setState({ tokens }); this.setState({ tokens });
return subscribeEvents(addresses, this.eventCallback); return subscribeEvents(addresses, this.eventCallback);
}) })
@ -144,6 +145,7 @@ export default class Events extends Component {
.concat(pendingEvents) .concat(pendingEvents)
.filter((log) => !minedNew.find((event) => event.transactionHash === log.transactionHash)); .filter((log) => !minedNew.find((event) => event.transactionHash === log.transactionHash));
const events = [].concat(pendingNew).concat(minedNew); const events = [].concat(pendingNew).concat(minedNew);
this.setState({ loading: false, events, minedEvents: minedNew, pendingEvents: pendingNew }); this.setState({ loading: false, events, minedEvents: minedNew, pendingEvents: pendingNew });
} }
} }

View File

@ -275,6 +275,7 @@ export default class Send extends Component {
this.setState({ sendState: 'Gas estimated, Posting transaction to the network' }); this.setState({ sendState: 'Gas estimated, Posting transaction to the network' });
const gasPassed = gas.mul(1.2); const gasPassed = gas.mul(1.2);
options.gas = gasPassed.toFixed(0); options.gas = gasPassed.toFixed(0);
console.log(`gas estimated at ${gas.toFormat(0)}, passing ${gasPassed.toFormat(0)}`); console.log(`gas estimated at ${gas.toFormat(0)}, passing ${gasPassed.toFormat(0)}`);

View File

@ -105,6 +105,7 @@ export function attachInstances () {
]) ])
.then(([registryAddress, netChain]) => { .then(([registryAddress, netChain]) => {
const registry = api.newContract(abis.registry, registryAddress).instance; const registry = api.newContract(abis.registry, registryAddress).instance;
isTest = ['morden', 'ropsten', 'testnet'].includes(netChain); isTest = ['morden', 'ropsten', 'testnet'].includes(netChain);
console.log(`contract was found at registry=${registryAddress}`); console.log(`contract was found at registry=${registryAddress}`);
@ -180,6 +181,7 @@ export function loadOwnedTokens (addresses) {
.then((_tokens) => { .then((_tokens) => {
const tokens = _tokens.reduce((tokens, token) => { const tokens = _tokens.reduce((tokens, token) => {
const [address, owner, tokenreg] = token; const [address, owner, tokenreg] = token;
tokens[owner] = tokens[owner] || []; tokens[owner] = tokens[owner] || [];
tokens[owner].push({ address, owner, tokenreg }); tokens[owner].push({ address, owner, tokenreg });
return tokens; return tokens;
@ -212,6 +214,7 @@ export function loadAllTokens () {
.all( .all(
_tokens.map(([address, owner, tokenreg]) => { _tokens.map(([address, owner, tokenreg]) => {
const isGlobal = tokenreg === tokenregInstance.address; const isGlobal = tokenreg === tokenregInstance.address;
tokens.push({ address, owner, tokenreg, isGlobal }); tokens.push({ address, owner, tokenreg, isGlobal });
return registries[tokenreg].fromAddress.call({}, [address]); return registries[tokenreg].fromAddress.call({}, [address]);
}) })
@ -219,6 +222,7 @@ export function loadAllTokens () {
.then((coins) => { .then((coins) => {
return tokens.map((token, index) => { return tokens.map((token, index) => {
const [id, tla, base, name, owner] = coins[index]; const [id, tla, base, name, owner] = coins[index];
token.coin = { id, tla, base, name, owner }; token.coin = { id, tla, base, name, owner };
return token; return token;
}); });
@ -243,6 +247,7 @@ export function loadBalances (addresses) {
.then((_balances) => { .then((_balances) => {
return tokens.map((token, tindex) => { return tokens.map((token, tindex) => {
const balances = _balances[tindex]; const balances = _balances[tindex];
token.balances = addresses.map((address, aindex) => { token.balances = addresses.map((address, aindex) => {
return { address, balance: balances[aindex] }; return { address, balance: balances[aindex] };
}); });

View File

@ -100,6 +100,7 @@ export default class Dapp extends Component {
const hash = app[`${type}Hash`]; const hash = app[`${type}Hash`];
let overlayImage = null; let overlayImage = null;
if (withImage && hash) { if (withImage && hash) {
overlayImage = ( overlayImage = (
<img <img

View File

@ -42,6 +42,7 @@ export default class SelectDapp extends Component {
} }
let overlayImg = null; let overlayImg = null;
if (this.dappsStore.currentApp.imageHash) { if (this.dappsStore.currentApp.imageHash) {
overlayImg = ( overlayImg = (
<img src={ `/api/content/${this.dappsStore.currentApp.imageHash.substr(2)}` } /> <img src={ `/api/content/${this.dappsStore.currentApp.imageHash.substr(2)}` } />

View File

@ -145,6 +145,7 @@ export default class DappsStore {
@action setApps = (apps) => { @action setApps = (apps) => {
this.sortApps(apps.filter((app) => { this.sortApps(apps.filter((app) => {
const bnid = new BigNumber(app.id); const bnid = new BigNumber(app.id);
return bnid.gt(0); return bnid.gt(0);
})); }));
@ -194,6 +195,7 @@ export default class DappsStore {
.keys(accountsInfo) .keys(accountsInfo)
.map((address) => { .map((address) => {
const account = accountsInfo[address]; const account = accountsInfo[address];
account.address = address; account.address = address;
return account; return account;
}); });

View File

@ -78,6 +78,7 @@ export default class Application extends Component {
const { fromAddress, registerBusy, url, urlError, contentHash, contentHashError, contentHashOwner, commit, commitError, registerType, repo, repoError } = this.state; const { fromAddress, registerBusy, url, urlError, contentHash, contentHashError, contentHashOwner, commit, commitError, registerType, repo, repoError } = this.state;
let hashClass = null; let hashClass = null;
if (contentHashError) { if (contentHashError) {
hashClass = contentHashOwner !== fromAddress ? styles.hashError : styles.hashWarning; hashClass = contentHashOwner !== fromAddress ? styles.hashError : styles.hashWarning;
} else if (contentHash) { } else if (contentHash) {
@ -85,6 +86,7 @@ export default class Application extends Component {
} }
let valueInputs = null; let valueInputs = null;
if (registerType === 'content') { if (registerType === 'content') {
valueInputs = [ valueInputs = [
<div className={ styles.capture } key='repo'> <div className={ styles.capture } key='repo'>
@ -275,6 +277,7 @@ export default class Application extends Component {
// TODO: field validation // TODO: field validation
if (!urlError) { if (!urlError) {
const parts = url.split('/'); const parts = url.split('/');
hasContent = parts.length !== 0; hasContent = parts.length !== 0;
if (parts[2] === 'github.com' || parts[2] === 'raw.githubusercontent.com') { if (parts[2] === 'github.com' || parts[2] === 'raw.githubusercontent.com') {
@ -366,6 +369,7 @@ export default class Application extends Component {
registerContent (contentRepo, contentCommit) { registerContent (contentRepo, contentCommit) {
const { contentHash, fromAddress, instance } = this.state; const { contentHash, fromAddress, instance } = this.state;
contentCommit = contentCommit.substr(0, 2) === '0x' ? contentCommit : `0x${contentCommit}`; contentCommit = contentCommit.substr(0, 2) === '0x' ? contentCommit : `0x${contentCommit}`;
const eventId = nextEventId++; const eventId = nextEventId++;
@ -407,6 +411,7 @@ export default class Application extends Component {
}); });
const gasPassed = gas.mul(1.2); const gasPassed = gas.mul(1.2);
options.gas = gasPassed.toFixed(0); options.gas = gasPassed.toFixed(0);
console.log(`gas estimated at ${gas.toFormat(0)}, passing ${gasPassed.toFormat(0)}`); console.log(`gas estimated at ${gas.toFormat(0)}, passing ${gasPassed.toFormat(0)}`);
@ -456,6 +461,7 @@ export default class Application extends Component {
}); });
const gasPassed = gas.mul(1.2); const gasPassed = gas.mul(1.2);
options.gas = gasPassed.toFixed(0); options.gas = gasPassed.toFixed(0);
console.log(`gas estimated at ${gas.toFormat(0)}, passing ${gasPassed.toFormat(0)}`); console.log(`gas estimated at ${gas.toFormat(0)}, passing ${gasPassed.toFormat(0)}`);

View File

@ -66,6 +66,7 @@ export default class Application extends Component {
.filter(tx => tx.isLocal) .filter(tx => tx.isLocal)
.map(data => { .map(data => {
const tx = data.transaction; const tx = data.transaction;
local[tx.hash].transaction = tx; local[tx.hash].transaction = tx;
local[tx.hash].stats = data.stats; local[tx.hash].stats = data.stats;
}); });
@ -73,6 +74,7 @@ export default class Application extends Component {
// Convert local transactions to array // Convert local transactions to array
const localTransactions = Object.keys(local).map(hash => { const localTransactions = Object.keys(local).map(hash => {
const data = local[hash]; const data = local[hash];
data.txHash = hash; data.txHash = hash;
return data; return data;
}); });
@ -124,6 +126,7 @@ export default class Application extends Component {
renderQueueSummary () { renderQueueSummary () {
const { transactions } = this.state; const { transactions } = this.state;
if (!transactions.length) { if (!transactions.length) {
return null; return null;
} }
@ -146,6 +149,7 @@ export default class Application extends Component {
renderQueue () { renderQueue () {
const { blockNumber, transactions } = this.state; const { blockNumber, transactions } = this.state;
if (!transactions.length) { if (!transactions.length) {
return ( return (
<h3>The queue seems is empty.</h3> <h3>The queue seems is empty.</h3>
@ -177,6 +181,7 @@ export default class Application extends Component {
renderLocals () { renderLocals () {
const { localTransactions } = this.state; const { localTransactions } = this.state;
if (!localTransactions.length) { if (!localTransactions.length) {
return ( return (
<h3>You haven't sent any transactions yet.</h3> <h3>You haven't sent any transactions yet.</h3>

View File

@ -168,11 +168,13 @@ export class Transaction extends BaseTransaction {
renderTime (firstSeen) { renderTime (firstSeen) {
const { blockNumber } = this.props; const { blockNumber } = this.props;
if (!firstSeen) { if (!firstSeen) {
return 'never'; return 'never';
} }
const timeInMinutes = blockNumber.sub(firstSeen).mul(14).div(60).toFormat(1); const timeInMinutes = blockNumber.sub(firstSeen).mul(14).div(60).toFormat(1);
return `${timeInMinutes} minutes ago`; return `${timeInMinutes} minutes ago`;
} }
} }

View File

@ -56,6 +56,7 @@ export default connect(
// react -> redux connection // react -> redux connection
(dispatch) => { (dispatch) => {
const bound = bindActionCreators(actions, dispatch); const bound = bindActionCreators(actions, dispatch);
bound.addresses = bindActionCreators(actions.addresses, dispatch); bound.addresses = bindActionCreators(actions.addresses, dispatch);
bound.accounts = bindActionCreators(actions.accounts, dispatch); bound.accounts = bindActionCreators(actions.accounts, dispatch);
bound.lookup = bindActionCreators(actions.lookup, dispatch); bound.lookup = bindActionCreators(actions.lookup, dispatch);

View File

@ -59,6 +59,7 @@ export const subscribe = (name, from = 0, to = 'pending') =>
parameters: e.params, parameters: e.params,
timestamp: block.timestamp timestamp: block.timestamp
}; };
dispatch(event(name, data)); dispatch(event(name, data));
}) })
.catch((err) => { .catch((err) => {

View File

@ -72,6 +72,7 @@ const renderEvent = (classNames, verb) => (e) => {
const renderDataChanged = (e) => { const renderDataChanged = (e) => {
let classNames = styles.dataChanged; let classNames = styles.dataChanged;
if (e.state === 'pending') { if (e.state === 'pending') {
classNames += ' ' + styles.pending; classNames += ' ' + styles.pending;
} }
@ -113,6 +114,7 @@ const renderReverse = (e) => {
} }
const classes = [ styles.reverse ]; const classes = [ styles.reverse ];
if (e.state === 'pending') { if (e.state === 'pending') {
classes.push(styles.pending); classes.push(styles.pending);
} }

View File

@ -29,6 +29,7 @@ export const fail = (action) => ({ type: `${action} error` });
export const lookup = (name, key) => (dispatch, getState) => { export const lookup = (name, key) => (dispatch, getState) => {
const { contract } = getState(); const { contract } = getState();
if (!contract) { if (!contract) {
return; return;
} }

View File

@ -55,6 +55,7 @@ const renderQueue = (queue) => {
const grouped = queue.reduce((grouped, change) => { const grouped = queue.reduce((grouped, change) => {
const last = grouped[grouped.length - 1]; const last = grouped[grouped.length - 1];
if (last && last.action === change.action) { if (last && last.action === change.action) {
last.names.push(change.name); last.names.push(change.name);
} else { } else {

View File

@ -120,6 +120,7 @@ class Records extends Component {
onSaveClick = () => { onSaveClick = () => {
const { name, type, value } = this.state; const { name, type, value } = this.state;
this.props.update(name, type, value); this.props.update(name, type, value);
}; };

View File

@ -59,6 +59,7 @@ class Reverse extends Component {
); );
let addressInput = null; let addressInput = null;
if (action === 'propose') { if (action === 'propose') {
addressInput = ( addressInput = (
<TextField <TextField

View File

@ -50,6 +50,7 @@ export const fetchContract = () => (dispatch) =>
api.parity.registryAddress() api.parity.registryAddress()
.then((address) => { .then((address) => {
const contract = api.newContract(registryAbi, address); const contract = api.newContract(registryAbi, address);
dispatch(setContract(contract)); dispatch(setContract(contract));
dispatch(fetchFee()); dispatch(fetchFee());
dispatch(fetchOwner()); dispatch(fetchOwner());
@ -65,6 +66,7 @@ export const setFee = (fee) => ({ type: 'set fee', fee });
const fetchFee = () => (dispatch, getState) => { const fetchFee = () => (dispatch, getState) => {
const { contract } = getState(); const { contract } = getState();
if (!contract) { if (!contract) {
return; return;
} }
@ -83,6 +85,7 @@ export const setOwner = (owner) => ({ type: 'set owner', owner });
export const fetchOwner = () => (dispatch, getState) => { export const fetchOwner = () => (dispatch, getState) => {
const { contract } = getState(); const { contract } = getState();
if (!contract) { if (!contract) {
return; return;
} }

View File

@ -27,6 +27,7 @@ export default (state = initialState, action) => {
accounts[account.address] = account; accounts[account.address] = account;
return accounts; return accounts;
}, {}); }, {});
return { ...state, all: accounts }; return { ...state, all: accounts };
} }

View File

@ -29,6 +29,7 @@ export const fetch = () => (dispatch) => {
address, address,
isAccount: true isAccount: true
})); }));
dispatch(set(addresses)); dispatch(set(addresses));
}) })
.catch((error) => { .catch((error) => {

View File

@ -24,6 +24,7 @@ export default (state = initialState, action) => {
contacts[contact.address] = contact; contacts[contact.address] = contact;
return contacts; return contacts;
}, {}); }, {});
return contacts; return contacts;
} }

View File

@ -38,6 +38,7 @@ class Hash extends Component {
const { hash, isTestnet, linked } = this.props; const { hash, isTestnet, linked } = this.props;
let shortened = hash.toLowerCase().replace(leading0x, ''); let shortened = hash.toLowerCase().replace(leading0x, '');
shortened = shortened.length > (6 + 6) shortened = shortened.length > (6 + 6)
? shortened.substr(0, 6) + '...' + shortened.slice(-6) ? shortened.substr(0, 6) + '...' + shortened.slice(-6)
: shortened; : shortened;

View File

@ -33,6 +33,7 @@ class AccountSelectorItem extends Component {
const account = this.props.account; const account = this.props.account;
const props = Object.assign({}, this.props); const props = Object.assign({}, this.props);
delete props.account; delete props.account;
delete props.onSelectAccount; delete props.onSelectAccount;

View File

@ -33,6 +33,7 @@ class AccountSelectorContainer extends Component {
const mapStateToProps = (state) => { const mapStateToProps = (state) => {
const { accounts } = state; const { accounts } = state;
return { ...accounts }; return { ...accounts };
}; };

View File

@ -188,6 +188,7 @@ export default class RegisterAction extends Component {
onAccountChange = () => { onAccountChange = () => {
const { dialog } = this.refs; const { dialog } = this.refs;
dialog.forceUpdate(); dialog.forceUpdate();
} }

View File

@ -98,11 +98,11 @@ export default class InputText extends Component {
onChange = (event) => { onChange = (event) => {
const value = event.target.value; const value = event.target.value;
// So we can focus on the input after async validation // So we can focus on the input after async validation
event.persist(); event.persist();
const { validationType, contract } = this.props; const { validationType, contract } = this.props;
const validation = validate(value, validationType, contract); const validation = validate(value, validationType, contract);
if (validation instanceof Promise) { if (validation instanceof Promise) {

View File

@ -381,6 +381,7 @@ export default class Token extends Component {
onUnregister = () => { onUnregister = () => {
const index = this.props.index; const index = this.props.index;
this.props.handleUnregister(index); this.props.handleUnregister(index);
} }

View File

@ -77,6 +77,7 @@ export const loadTokens = () => (dispatch, getState) => {
.call() .call()
.then((count) => { .then((count) => {
const tokenCount = parseInt(count); const tokenCount = parseInt(count);
dispatch(setTokenCount(tokenCount)); dispatch(setTokenCount(tokenCount));
for (let i = 0; i < tokenCount; i++) { for (let i = 0; i < tokenCount; i++) {
@ -93,7 +94,6 @@ export const loadTokens = () => (dispatch, getState) => {
export const loadToken = (index) => (dispatch, getState) => { export const loadToken = (index) => (dispatch, getState) => {
const state = getState(); const state = getState();
const contractInstance = state.status.contract.instance; const contractInstance = state.status.contract.instance;
const userAccounts = state.accounts.list; const userAccounts = state.accounts.list;
const accountsInfo = state.accounts.accountsInfo; const accountsInfo = state.accounts.accountsInfo;
@ -104,11 +104,9 @@ export const loadToken = (index) => (dispatch, getState) => {
.call({}, [ parseInt(index) ]) .call({}, [ parseInt(index) ])
.then((result) => { .then((result) => {
const tokenOwner = result[4]; const tokenOwner = result[4];
const isTokenOwner = userAccounts const isTokenOwner = userAccounts
.filter(a => a.address === tokenOwner) .filter(a => a.address === tokenOwner)
.length > 0; .length > 0;
const data = { const data = {
index: parseInt(index), index: parseInt(index),
address: result[0], address: result[0],
@ -156,8 +154,8 @@ export const loadToken = (index) => (dispatch, getState) => {
export const queryTokenMeta = (index, query) => (dispatch, getState) => { export const queryTokenMeta = (index, query) => (dispatch, getState) => {
const state = getState(); const state = getState();
const contractInstance = state.status.contract.instance; const contractInstance = state.status.contract.instance;
const startDate = Date.now(); const startDate = Date.now();
dispatch(setTokenMetaLoading(index, true)); dispatch(setTokenMetaLoading(index, true));
contractInstance contractInstance
@ -184,7 +182,6 @@ export const addTokenMeta = (index, key, value) => (dispatch, getState) => {
const state = getState(); const state = getState();
const contractInstance = state.status.contract.instance; const contractInstance = state.status.contract.instance;
const token = state.tokens.tokens.find(t => t.index === index); const token = state.tokens.tokens.find(t => t.index === index);
const options = { from: token.owner }; const options = { from: token.owner };
const values = [ index, key, value ]; const values = [ index, key, value ];
@ -203,9 +200,7 @@ export const addTokenMeta = (index, key, value) => (dispatch, getState) => {
export const addGithubhintURL = (from, key, url) => (dispatch, getState) => { export const addGithubhintURL = (from, key, url) => (dispatch, getState) => {
const state = getState(); const state = getState();
const contractInstance = state.status.githubhint.instance; const contractInstance = state.status.githubhint.instance;
const options = { from }; const options = { from };
const values = [ key, url ]; const values = [ key, url ];
contractInstance contractInstance
@ -223,7 +218,6 @@ export const addGithubhintURL = (from, key, url) => (dispatch, getState) => {
export const unregisterToken = (index) => (dispatch, getState) => { export const unregisterToken = (index) => (dispatch, getState) => {
const { contract } = getState().status; const { contract } = getState().status;
const { instance, owner } = contract; const { instance, owner } = contract;
const values = [ index ]; const values = [ index ];
const options = { const options = {
from: owner from: owner

View File

@ -77,6 +77,7 @@ class FakeRpcServer {
} }
const fakeRpc = new FakeRpcServer(); const fakeRpc = new FakeRpcServer();
fakeRpc.start(); fakeRpc.start();
mockedResponses.rpc.forEach(method => fakeRpc.simpleRpc(method.name, method.response)); mockedResponses.rpc.forEach(method => fakeRpc.simpleRpc(method.name, method.response));

View File

@ -20,6 +20,7 @@ const isProd = process.env.NODE_ENV === 'production';
// Component utils for integration tests hooks. // Component utils for integration tests hooks.
const TEST_HOOK = 'data-test'; const TEST_HOOK = 'data-test';
Component.prototype._test = isProd ? noop : testHook; Component.prototype._test = isProd ? noop : testHook;
Component.prototype._testInherit = isProd ? noop : testHookInherit; Component.prototype._testInherit = isProd ? noop : testHookInherit;
@ -27,6 +28,7 @@ function noop (name) {}
function testHookInherit (name) { function testHookInherit (name) {
let hook = this.props[TEST_HOOK]; let hook = this.props[TEST_HOOK];
if (name) { if (name) {
hook += `-${name}`; hook += `-${name}`;
} }
@ -37,6 +39,7 @@ function testHookInherit (name) {
function testHook (name) { function testHook (name) {
let hook = this.constructor.name; let hook = this.constructor.name;
if (name) { if (name) {
hook += `-${name}`; hook += `-${name}`;
} }

View File

@ -49,6 +49,7 @@ injectTapEventPlugin();
if (process.env.NODE_ENV === 'development') { if (process.env.NODE_ENV === 'development') {
// Expose the React Performance Tools on the`window` object // Expose the React Performance Tools on the`window` object
const Perf = require('react-addons-perf'); const Perf = require('react-addons-perf');
window.Perf = Perf; window.Perf = Perf;
} }
@ -56,15 +57,18 @@ const AUTH_HASH = '#/auth?';
const parityUrl = process.env.PARITY_URL || window.location.host; const parityUrl = process.env.PARITY_URL || window.location.host;
let token = null; let token = null;
if (window.location.hash && window.location.hash.indexOf(AUTH_HASH) === 0) { if (window.location.hash && window.location.hash.indexOf(AUTH_HASH) === 0) {
token = qs.parse(window.location.hash.substr(AUTH_HASH.length)).token; token = qs.parse(window.location.hash.substr(AUTH_HASH.length)).token;
} }
const api = new SecureApi(`ws://${parityUrl}`, token); const api = new SecureApi(`ws://${parityUrl}`, token);
patchApi(api); patchApi(api);
ContractInstances.create(api); ContractInstances.create(api);
const store = initStore(api, hashHistory); const store = initStore(api, hashHistory);
store.dispatch({ type: 'initAll', api }); store.dispatch({ type: 'initAll', api });
store.dispatch(setApi(api)); store.dispatch(setApi(api));

View File

@ -28,6 +28,7 @@ export default class AccountDetailsGeth extends Component {
const formatted = addresses.map((address, idx) => { const formatted = addresses.map((address, idx) => {
const comma = !idx ? '' : ((idx === addresses.length - 1) ? ' & ' : ', '); const comma = !idx ? '' : ((idx === addresses.length - 1) ? ' & ' : ', ');
return `${comma}${address}`; return `${comma}${address}`;
}).join(''); }).join('');

View File

@ -91,6 +91,7 @@ export default class NewGeth extends Component {
const { available } = this.state; const { available } = this.state;
const account = available.find((_account) => _account.address === address); const account = available.find((_account) => _account.address === address);
account.checked = checked; account.checked = checked;
const selected = available.filter((_account) => _account.checked); const selected = available.filter((_account) => _account.checked);

View File

@ -112,6 +112,7 @@ export default class NewImport extends Component {
if (el.files.length) { if (el.files.length) {
const reader = new FileReader(); const reader = new FileReader();
reader.onload = (event) => { reader.onload = (event) => {
this.setState({ this.setState({
walletJson: event.target.result, walletJson: event.target.result,

View File

@ -15,13 +15,17 @@
// along with Parity. If not, see <http://www.gnu.org/licenses/>. // along with Parity. If not, see <http://www.gnu.org/licenses/>.
export const onPrint = (window, cb) => { export const onPrint = (window, cb) => {
let called = false; let query, queryFn; let called = false;
let query;
let queryFn;
const onPrint = () => { const onPrint = () => {
if (queryFn) { if (queryFn) {
query.removeListener(queryFn); query.removeListener(queryFn);
} }
window.removeEventListener('afterprint', onPrint, false); window.removeEventListener('afterprint', onPrint, false);
if (!called) { if (!called) {
called = true; called = true;
cb(); cb();
@ -34,14 +38,17 @@ export const onPrint = (window, cb) => {
onPrint(); onPrint();
} }
}; };
query = window.matchMedia('print'); query = window.matchMedia('print');
query.addListener(queryFn); query.addListener(queryFn);
} }
window.addEventListener('afterprint', onPrint, false); window.addEventListener('afterprint', onPrint, false);
}; };
export default (html) => { export default (html) => {
const iframe = document.createElement('iframe'); const iframe = document.createElement('iframe');
iframe.setAttribute('sandbox', 'allow-modals allow-same-origin allow-scripts'); iframe.setAttribute('sandbox', 'allow-modals allow-same-origin allow-scripts');
iframe.setAttribute('src', '/'); iframe.setAttribute('src', '/');
iframe.setAttribute('style', 'display: none'); iframe.setAttribute('style', 'display: none');

View File

@ -120,11 +120,13 @@ export default class CreateWalletStore {
@action onNext = () => { @action onNext = () => {
const stepIndex = this.stepsKeys.findIndex((k) => k === this.step) + 1; const stepIndex = this.stepsKeys.findIndex((k) => k === this.step) + 1;
this.step = this.stepsKeys[stepIndex]; this.step = this.stepsKeys[stepIndex];
} }
@action onChange = (_wallet) => { @action onChange = (_wallet) => {
const newWallet = Object.assign({}, this.wallet, _wallet); const newWallet = Object.assign({}, this.wallet, _wallet);
this.validateWallet(newWallet); this.validateWallet(newWallet);
} }

View File

@ -307,6 +307,7 @@ export default class DetailsStep extends Component {
inputs.forEach((input) => { inputs.forEach((input) => {
const param = parseAbiType(input.type); const param = parseAbiType(input.type);
params.push(param.default); params.push(param.default);
}); });

View File

@ -358,6 +358,7 @@ class DeployContract extends Component {
const body = txhash const body = txhash
? <TxHash hash={ txhash } /> ? <TxHash hash={ txhash } />
: null; : null;
return ( return (
<BusyStep <BusyStep
title={ title={

View File

@ -329,6 +329,7 @@ class ExecuteContract extends Component {
onFuncChange = (event, func) => { onFuncChange = (event, func) => {
const values = (func.abi.inputs || []).map((input) => { const values = (func.abi.inputs || []).map((input) => {
const parsedType = parseAbiType(input.type); const parsedType = parseAbiType(input.type);
return parsedType.default; return parsedType.default;
}); });

View File

@ -69,6 +69,7 @@ const STORE = {
function createApi (result = true) { function createApi (result = true) {
const sha3 = sinon.stub().resolves('0x0000000000000000000000000000000000000000'); const sha3 = sinon.stub().resolves('0x0000000000000000000000000000000000000000');
sha3.text = sha3; sha3.text = sha3;
return { return {
parity: { parity: {

View File

@ -148,6 +148,7 @@ class FirstRun extends Component {
onClick={ this.onCreate } onClick={ this.onCreate }
/> />
]; ];
if (hasAccounts) { if (hasAccounts) {
buttons.unshift( buttons.unshift(
<Button <Button

View File

@ -263,6 +263,7 @@ export default class LoadContract extends Component {
onConfirmRemoval = () => { onConfirmRemoval = () => {
const { deleteId } = this.state; const { deleteId } = this.state;
this.props.onDelete(deleteId); this.props.onDelete(deleteId);
this.setState({ this.setState({

View File

@ -102,6 +102,7 @@ export default class SaveContract extends Component {
onChangeName = (event, value) => { onChangeName = (event, value) => {
const { name, nameError } = validateName(value); const { name, nameError } = validateName(value);
this.setState({ name, nameError }); this.setState({ name, nameError });
} }
} }

View File

@ -32,6 +32,7 @@ export default class Value extends Component {
const { amount, symbol } = this.props; const { amount, symbol } = this.props;
let value = ''; let value = '';
if (amount) { if (amount) {
value = new BigNumber(amount).toFormat(3); value = new BigNumber(amount).toFormat(3);
} }

View File

@ -66,6 +66,7 @@ class TokenSelect extends Component {
const token = balance.token; const token = balance.token;
const isEth = index === 0; const isEth = index === 0;
let imagesrc = token.image; let imagesrc = token.image;
if (!imagesrc) { if (!imagesrc) {
imagesrc = imagesrc =
images[token.address] images[token.address]
@ -79,6 +80,7 @@ class TokenSelect extends Component {
} else { } else {
const format = balance.token.format || 1; const format = balance.token.format || 1;
const decimals = format === 1 ? 0 : Math.min(3, Math.floor(format / 10)); const decimals = format === 1 ? 0 : Math.min(3, Math.floor(format / 10));
value = new BigNumber(balance.value).div(format).toFormat(decimals); value = new BigNumber(balance.value).div(format).toFormat(decimals);
} }

View File

@ -115,6 +115,7 @@ export default class TransferStore {
this.api = api; this.api = api;
const { account, balance, gasLimit, senders, newError, sendersBalances } = props; const { account, balance, gasLimit, senders, newError, sendersBalances } = props;
this.account = account; this.account = account;
this.balance = balance; this.balance = balance;
this.isWallet = account && account.wallet; this.isWallet = account && account.wallet;
@ -588,6 +589,7 @@ export default class TransferStore {
send () { send () {
const { options, values } = this._getTransferParams(); const { options, values } = this._getTransferParams();
options.minBlock = new BigNumber(this.minBlock || 0).gt(0) ? this.minBlock : null; options.minBlock = new BigNumber(this.minBlock || 0).gt(0) ? this.minBlock : null;
log.debug('@send', 'transfer value', options.value && options.value.toFormat()); log.debug('@send', 'transfer value', options.value && options.value.toFormat());
@ -596,6 +598,7 @@ export default class TransferStore {
_estimateGas (forceToken = false) { _estimateGas (forceToken = false) {
const { options, values } = this._getTransferParams(true, forceToken); const { options, values } = this._getTransferParams(true, forceToken);
return this._getTransferMethod(true, forceToken).estimateGas(options, values); return this._getTransferMethod(true, forceToken).estimateGas(options, values);
} }
@ -681,6 +684,7 @@ export default class TransferStore {
_validatePositiveNumber (num) { _validatePositiveNumber (num) {
try { try {
const v = new BigNumber(num); const v = new BigNumber(num);
if (v.lt(0)) { if (v.lt(0)) {
return ERRORS.invalidAmount; return ERRORS.invalidAmount;
} }

View File

@ -309,6 +309,7 @@ function mapStateToProps (initState, initProps) {
return (state) => { return (state) => {
const { gasLimit } = state.nodeStatus; const { gasLimit } = state.nodeStatus;
const sendersBalances = senders ? pick(state.balances.balances, Object.keys(senders)) : null; const sendersBalances = senders ? pick(state.balances.balances, Object.keys(senders)) : null;
return { gasLimit, wallet, senders, sendersBalances }; return { gasLimit, wallet, senders, sendersBalances };
}; };
} }

View File

@ -233,6 +233,7 @@ export default class GatherData extends Component {
field.onChange(v); field.onChange(v);
}; };
const onSubmit = field.onChange; const onSubmit = field.onChange;
return ( return (
<Input <Input
key={ field.key } key={ field.key }

View File

@ -76,6 +76,7 @@ export default class EmailVerificationStore extends VerificationStore {
requestCode = () => { requestCode = () => {
const { email, account, isTestnet } = this; const { email, account, isTestnet } = this;
return postToServer({ email, address: account }, isTestnet); return postToServer({ email, address: account }, isTestnet);
} }
} }

View File

@ -73,6 +73,7 @@ export default class SMSVerificationStore extends VerificationStore {
requestCode = () => { requestCode = () => {
const { number, account, isTestnet } = this; const { number, account, isTestnet } = this;
return postToServer({ number, address: account }, isTestnet); return postToServer({ number, address: account }, isTestnet);
} }
} }

View File

@ -72,6 +72,7 @@ export default class VerificationStore {
@action load = () => { @action load = () => {
const { contract, account } = this; const { contract, account } = this;
this.step = LOADING; this.step = LOADING;
const isServerRunning = this.isServerRunning() const isServerRunning = this.isServerRunning()
@ -156,6 +157,7 @@ export default class VerificationStore {
const values = this.requestValues(); const values = this.requestValues();
let chain = Promise.resolve(); let chain = Promise.resolve();
if (!hasRequested) { if (!hasRequested) {
this.step = POSTING_REQUEST; this.step = POSTING_REQUEST;
chain = request.estimateGas(options, values) chain = request.estimateGas(options, values)

View File

@ -83,7 +83,9 @@ class Verification extends Component {
render () { render () {
const store = this.store; const store = this.store;
let phase = 0; let error = false; let isStepValid = true; let phase = 0;
let error = false;
let isStepValid = true;
if (store) { if (store) {
phase = Verification.phases[store.step]; phase = Verification.phases[store.step];
@ -117,6 +119,7 @@ class Verification extends Component {
onClick={ onClose } onClick={ onClose }
/> />
); );
if (error) { if (error) {
return (<div>{ cancel }</div>); return (<div>{ cancel }</div>);
} }
@ -137,10 +140,12 @@ class Verification extends Component {
} }
let action = () => {}; let action = () => {};
switch (phase) { switch (phase) {
case 0: case 0:
action = () => { action = () => {
const { method } = this.state; const { method } = this.state;
this.onSelectMethod(method); this.onSelectMethod(method);
}; };
break; break;
@ -179,13 +184,17 @@ class Verification extends Component {
renderStep (phase, error) { renderStep (phase, error) {
if (error) { if (error) {
return (<p>{ error }</p>); return (
<p>{ error }</p>
);
} }
const { method } = this.state; const { method } = this.state;
if (phase === 0) { if (phase === 0) {
const values = Object.values(methods); const values = Object.values(methods);
const value = values.findIndex((v) => v.value === method); const value = values.findIndex((v) => v.value === method);
return ( return (
<RadioButtons <RadioButtons
onChange={ this.selectMethod } onChange={ this.selectMethod }
@ -209,8 +218,8 @@ class Verification extends Component {
} }
const { setConsentGiven } = this.store; const { setConsentGiven } = this.store;
const fields = []; const fields = [];
if (method === 'sms') { if (method === 'sms') {
fields.push({ fields.push({
key: 'number', key: 'number',
@ -249,7 +258,9 @@ class Verification extends Component {
); );
case 3: case 3:
let receiver, hint; let receiver;
let hint;
if (method === 'sms') { if (method === 'sms') {
receiver = this.store.number; receiver = this.store.number;
hint = 'Enter the code you received via SMS.'; hint = 'Enter the code you received via SMS.';
@ -306,5 +317,5 @@ const mapStateToProps = (state) => ({
export default connect( export default connect(
mapStateToProps, mapStateToProps,
null // mapDispatchToProps null
)(Verification); )(Verification);

View File

@ -151,11 +151,13 @@ export default class WalletSettingsStore {
@action onNext = () => { @action onNext = () => {
const stepIndex = this.stepsKeys.findIndex((k) => k === this.step) + 1; const stepIndex = this.stepsKeys.findIndex((k) => k === this.step) + 1;
this.step = this.stepsKeys[stepIndex]; this.step = this.stepsKeys[stepIndex];
} }
@action onChange = (_wallet) => { @action onChange = (_wallet) => {
const newWallet = Object.assign({}, this.wallet, _wallet); const newWallet = Object.assign({}, this.wallet, _wallet);
this.validateWallet(newWallet); this.validateWallet(newWallet);
} }
@ -178,6 +180,7 @@ export default class WalletSettingsStore {
@action send = () => { @action send = () => {
const changes = this.changes; const changes = this.changes;
const walletInstance = this.walletInstance; const walletInstance = this.walletInstance;
this.step = 'SENDING'; this.step = 'SENDING';
this.onTransactionsState('postTransaction'); this.onTransactionsState('postTransaction');
@ -193,11 +196,13 @@ export default class WalletSettingsStore {
.pollMethod('parity_checkRequest', id) .pollMethod('parity_checkRequest', id)
.then((txhash) => { .then((txhash) => {
const index = this.requests.findIndex((r) => r.id === id); const index = this.requests.findIndex((r) => r.id === id);
this.requests[index].txhash = txhash; this.requests[index].txhash = txhash;
}) })
.catch((e) => { .catch((e) => {
if (e.code === ERROR_CODES.REQUEST_REJECTED) { if (e.code === ERROR_CODES.REQUEST_REJECTED) {
const index = this.requests.findIndex((r) => r.id === id); const index = this.requests.findIndex((r) => r.id === id);
this.requests[index].rejected = true; this.requests[index].rejected = true;
return false; return false;
} }

View File

@ -21,6 +21,7 @@ const initialState = {};
export default handleActions({ export default handleActions({
setApi (state, action) { setApi (state, action) {
const { api } = action; const { api } = action;
return api; return api;
} }
}, initialState); }, initialState);

View File

@ -73,6 +73,7 @@ export default class Balances {
static get (store = {}) { static get (store = {}) {
if (!instance && store) { if (!instance && store) {
const { api } = store.getState(); const { api } = store.getState();
return Balances.instantiate(store, api); return Balances.instantiate(store, api);
} }
@ -340,6 +341,7 @@ export default class Balances {
handleTokensLogs (logs) { handleTokensLogs (logs) {
const tokenIds = logs.map((log) => log.params.id.value.toNumber()); const tokenIds = logs.map((log) => log.params.id.value.toNumber());
this._store.dispatch(fetchTokens(tokenIds)); this._store.dispatch(fetchTokens(tokenIds));
} }
} }

View File

@ -91,6 +91,7 @@ function setBalances (_balances, skipNotifications = false) {
const redirectToAccount = () => { const redirectToAccount = () => {
const route = `/accounts/${account.address}`; const route = `/accounts/${account.address}`;
dispatch(push(route)); dispatch(push(route));
}; };
@ -168,6 +169,7 @@ export function loadTokens (options = {}) {
.call() .call()
.then((numTokens) => { .then((numTokens) => {
const tokenIds = range(numTokens.toNumber()); const tokenIds = range(numTokens.toNumber());
dispatch(fetchTokens(tokenIds, options)); dispatch(fetchTokens(tokenIds, options));
}) })
.catch((error) => { .catch((error) => {
@ -443,6 +445,7 @@ function fetchTokensBalance (address, _tokens, api) {
})); }));
const balance = { tokens }; const balance = { tokens };
return balance; return balance;
}) })
.catch((error) => { .catch((error) => {

View File

@ -26,6 +26,7 @@ const initialState = {
export default handleActions({ export default handleActions({
setBalances (state, action) { setBalances (state, action) {
const { balances } = action; const { balances } = action;
return Object.assign({}, state, { balances }); return Object.assign({}, state, { balances });
}, },
@ -57,6 +58,7 @@ export default handleActions({
} }
const tokens = [].concat(balances[address].tokens); const tokens = [].concat(balances[address].tokens);
tokens[tokenIndex].token = { tokens[tokenIndex].token = {
...tokens[tokenIndex].token, ...tokens[tokenIndex].token,
image image
@ -73,11 +75,13 @@ export default handleActions({
setTokenReg (state, action) { setTokenReg (state, action) {
const { tokenreg } = action; const { tokenreg } = action;
return Object.assign({}, state, { tokenreg }); return Object.assign({}, state, { tokenreg });
}, },
setTokensFilter (state, action) { setTokensFilter (state, action) {
const { tokensFilter } = action; const { tokensFilter } = action;
return Object.assign({}, state, { tokensFilter }); return Object.assign({}, state, { tokensFilter });
} }
}, initialState); }, initialState);

View File

@ -106,6 +106,7 @@ export default class CertificationsMiddleware {
logs = contract.parseEventLogs(logs); logs = contract.parseEventLogs(logs);
logs.forEach((log) => { logs.forEach((log) => {
const certifier = certifiers.find((c) => c.address === log.address); const certifier = certifiers.find((c) => c.address === log.address);
if (!certifier) { if (!certifier) {
throw new Error(`Could not find certifier at ${log.address}.`); throw new Error(`Could not find certifier at ${log.address}.`);
} }
@ -121,6 +122,7 @@ export default class CertificationsMiddleware {
function onBadgeRegLogs (logs) { function onBadgeRegLogs (logs) {
const ids = logs.map((log) => log.params.id.value.toNumber()); const ids = logs.map((log) => log.params.id.value.toNumber());
return fetchCertifiers(uniq(ids)); return fetchCertifiers(uniq(ids));
} }
@ -216,6 +218,7 @@ export default class CertificationsMiddleware {
break; break;
case 'setVisibleAccounts': case 'setVisibleAccounts':
const _addresses = action.addresses || []; const _addresses = action.addresses || [];
addresses = uniq(addresses.concat(_addresses)); addresses = uniq(addresses.concat(_addresses));
fetchConfirmedEvents(); fetchConfirmedEvents();
next(action); next(action);

View File

@ -28,6 +28,7 @@ export default (state = initialState, action) => {
const newCertifications = certifications.concat({ const newCertifications = certifications.concat({
id, name, icon, title id, name, icon, title
}); });
return { ...state, [address]: newCertifications }; return { ...state, [address]: newCertifications };
} }
@ -36,6 +37,7 @@ export default (state = initialState, action) => {
const certifications = state[address] || []; const certifications = state[address] || [];
const newCertifications = certifications.filter((c) => c.id !== id); const newCertifications = certifications.filter((c) => c.id !== id);
return { ...state, [address]: newCertifications }; return { ...state, [address]: newCertifications };
} }

View File

@ -26,6 +26,7 @@ let next;
let store; let store;
const api = createWsApi(); const api = createWsApi();
Contracts.create(api); Contracts.create(api);
function createMiddleware (collection = {}) { function createMiddleware (collection = {}) {

View File

@ -59,6 +59,7 @@ export function personalAccountsInfo (accountsInfo) {
.values(wallets) .values(wallets)
.map((wallet) => { .map((wallet) => {
const walletContract = new Contract(api, WalletAbi); const walletContract = new Contract(api, WalletAbi);
return WalletsUtils.fetchOwners(walletContract.at(wallet.address)); return WalletsUtils.fetchOwners(walletContract.at(wallet.address));
}); });

View File

@ -45,7 +45,10 @@ const write = debounce((getChain, getReverses, getLastBlock) => {
}, 20000); }, 20000);
export default (api) => (store) => { export default (api) => (store) => {
let contract, subscription, timeout, interval; let contract;
let subscription;
let timeout;
let interval;
let addressesToCheck = {}; let addressesToCheck = {};
@ -85,10 +88,11 @@ export default (api) => (store) => {
store.dispatch(startCachingReverses()); store.dispatch(startCachingReverses());
break; break;
case 'startCachingReverses': case 'startCachingReverses':
const { registry } = Contracts.get(); const { registry } = Contracts.get();
const cached = read(store.getState().nodeStatus.netChain); const cached = read(store.getState().nodeStatus.netChain);
if (cached) { if (cached) {
Object Object
.entries(cached.reverses) .entries(cached.reverses)

View File

@ -90,6 +90,7 @@ export default class SignerMiddleware {
}) })
.then((result) => { .then((result) => {
const seed = Buffer.from(result.data); const seed = Buffer.from(result.data);
return new Signer(seed); return new Signer(seed);
}) })
: Signer.fromJson(wallet, password); : Signer.fromJson(wallet, password);

View File

@ -93,6 +93,7 @@ export default handleActions({
state.pending.find(p => p.id === id) || { id }, state.pending.find(p => p.id === id) || { id },
{ status: 'rejected' } { status: 'rejected' }
); );
return { return {
...state, ...state,
pending: removeWithId(state.pending, id), pending: removeWithId(state.pending, id),

View File

@ -95,6 +95,7 @@ export default class Status {
}); });
const promise = BalancesProvider.stop(); const promise = BalancesProvider.stop();
promises.push(promise); promises.push(promise);
return Promise.all(promises) return Promise.all(promises)
@ -108,6 +109,7 @@ export default class Status {
updateApiStatus () { updateApiStatus () {
const apiStatus = this.getApiStatus(); const apiStatus = this.getApiStatus();
log.debug('status::updateApiStatus', apiStatus); log.debug('status::updateApiStatus', apiStatus);
if (!isEqual(apiStatus, this._apiStatus)) { if (!isEqual(apiStatus, this._apiStatus)) {

View File

@ -80,6 +80,7 @@ export default handleActions({
toggleStatusRefresh (state, action) { toggleStatusRefresh (state, action) {
const { refreshStatus } = action; const { refreshStatus } = action;
return Object.assign({}, state, { refreshStatus }); return Object.assign({}, state, { refreshStatus });
} }
}, initialState); }, initialState);

View File

@ -182,6 +182,7 @@ function fetchWalletsInfo (updates) {
Promise Promise
.all(_updates.map((update) => { .all(_updates.map((update) => {
const contract = new Contract(api, WALLET_ABI).at(update.address); const contract = new Contract(api, WALLET_ABI).at(update.address);
return fetchWalletInfo(contract, update, getState); return fetchWalletInfo(contract, update, getState);
})) }))
.then((updates) => { .then((updates) => {
@ -415,6 +416,7 @@ function fetchOperationConfirmations (contract, operation, owners = null) {
return promise return promise
.then((result) => { .then((result) => {
const owners = result.value; const owners = result.value;
return Promise return Promise
.all(owners.map((owner) => walletInstance.hasConfirmed.call({}, [ operation, owner ]))) .all(owners.map((owner) => walletInstance.hasConfirmed.call({}, [ operation, owner ])))
.then((data) => { .then((data) => {

View File

@ -27,6 +27,7 @@ function getWorker () {
.then(() => navigator.serviceWorker.ready) .then(() => navigator.serviceWorker.ready)
.then((registration) => { .then((registration) => {
const worker = registration.active; const worker = registration.active;
worker.controller = registration.active; worker.controller = registration.active;
return new PromiseWorker(worker); return new PromiseWorker(worker);

View File

@ -24,11 +24,13 @@ const initialState = {
export default handleActions({ export default handleActions({
setWorker (state, action) { setWorker (state, action) {
const { worker } = action; const { worker } = action;
return Object.assign({}, state, { worker: worker || null }); return Object.assign({}, state, { worker: worker || null });
}, },
setError (state, action) { setError (state, action) {
const { error } = action; const { error } = action;
return Object.assign({}, state, { error }); return Object.assign({}, state, { error });
} }
}, initialState); }, initialState);

View File

@ -113,6 +113,7 @@ export default class SecureApi extends Api {
if (connected) { if (connected) {
const token = this.secureToken; const token = this.secureToken;
log.debug('got connected ; saving token', token); log.debug('got connected ; saving token', token);
// Save the sucessful token // Save the sucessful token
@ -145,6 +146,7 @@ export default class SecureApi extends Api {
*/ */
isNodeUp () { isNodeUp () {
const url = this._url.replace(/wss?/, 'http'); const url = this._url.replace(/wss?/, 'http');
return fetch(url, { method: 'HEAD' }) return fetch(url, { method: 'HEAD' })
.then( .then(
(r) => r.status === 200, (r) => r.status === 200,
@ -159,6 +161,7 @@ export default class SecureApi extends Api {
*/ */
updateToken (_token) { updateToken (_token) {
const token = this._sanitiseToken(_token); const token = this._sanitiseToken(_token);
log.debug('updating token', token); log.debug('updating token', token);
// Update the tokens list: put the new one on first position // Update the tokens list: put the new one on first position
@ -298,6 +301,7 @@ export default class SecureApi extends Api {
} }
const nextToken = this._tokens[nextTokenIndex]; const nextToken = this._tokens[nextTokenIndex];
return nextToken; return nextToken;
} }

View File

@ -106,6 +106,7 @@ function handleMessage (message) {
function getSignerSeed (data) { function getSignerSeed (data) {
console.log('deriving seed from service-worker'); console.log('deriving seed from service-worker');
const { wallet, password } = data; const { wallet, password } = data;
return Signer.getSeed(wallet, password); return Signer.getSeed(wallet, password);
} }
@ -138,6 +139,7 @@ function getCompiler (build) {
const fetcher = (url) => { const fetcher = (url) => {
const request = new Request(url); const request = new Request(url);
return cachedFetcher(request); return cachedFetcher(request);
}; };

View File

@ -157,6 +157,7 @@ export default class AccountCard extends Component {
// @see https://developers.google.com/web/updates/2015/04/cut-and-copy-commands // @see https://developers.google.com/web/updates/2015/04/cut-and-copy-commands
try { try {
const range = document.createRange(); const range = document.createRange();
range.selectNode(element); range.selectNode(element);
window.getSelection().addRange(range); window.getSelection().addRange(range);
document.execCommand('copy'); document.execCommand('copy');
@ -183,11 +184,13 @@ export default class AccountCard extends Component {
onClick = () => { onClick = () => {
const { account, onClick } = this.props; const { account, onClick } = this.props;
onClick(account.address); onClick(account.address);
} }
onFocus = () => { onFocus = () => {
const { account, onFocus } = this.props; const { account, onFocus } = this.props;
onFocus(account.index); onFocus(account.index);
} }

View File

@ -50,6 +50,7 @@ class ActionbarExport extends Component {
const text = JSON.stringify(content, null, 4); const text = JSON.stringify(content, null, 4);
const blob = new Blob([ text ], { type: 'application/json' }); const blob = new Blob([ text ], { type: 'application/json' });
FileSaver.saveAs(blob, `${filename}.json`); FileSaver.saveAs(blob, `${filename}.json`);
} }
} }

View File

@ -39,12 +39,14 @@ export default class SortStore {
@action handleSortChange = (event, child) => { @action handleSortChange = (event, child) => {
const order = child.props.value; const order = child.props.value;
this.onChange(order); this.onChange(order);
this.saveOrder(order); this.saveOrder(order);
} }
@action restoreSavedOrder = () => { @action restoreSavedOrder = () => {
const order = this.getSavedOrder(); const order = this.getSavedOrder();
this.onChange(order); this.onChange(order);
} }

Some files were not shown because too many files have changed in this diff Show More