Add metacoin example project

This commit is contained in:
Leonid Logvinov 2018-03-28 11:05:36 +02:00
parent bc49dde4d5
commit 4d9029bb0e
No known key found for this signature in database
GPG Key ID: 0DD294BFDE8C95D4
82 changed files with 1209 additions and 732 deletions

2
.gitignore vendored
View File

@ -85,3 +85,5 @@ packages/deployer/solc_bin/
# Monorepo scripts
packages/*/scripts/
packages/metacoin/src/contract_wrappers

View File

@ -8,6 +8,7 @@ CHANGELOG
## v0.34.0 - _April 2, 2018_
* Fix the bug causing `zeroEx.exchange.fillOrdersUpToAsync` validation to fail if there were some extra orders passed (#470)
* Removed `ZeroExError.TransactionMiningTimeout` and moved it to '@0xproject/web3_wrapper' `Web3WrapperErrors.TransactionMiningTimeout` (#485)
* Remove automatic instantiation of `zeroEx.orderStateWatcher` (#488)
* Add `zeroEx.createOrderStateWatcher` to allow creating arbitrary number of OrderStateWatchers (#488)
* Added `stateLayer` setting to `OrderStateWatcherConfig` so OrderStateWatcher can be set to monitor different blockchain state layers (#488)

View File

@ -90,7 +90,6 @@
"truffle-hdwallet-provider": "^0.0.3",
"tslint": "5.8.0",
"typedoc": "0xProject/typedoc",
"types-bn": "^0.0.1",
"typescript": "2.7.1",
"web3-provider-engine": "^13.0.1",
"webpack": "^3.1.0"

View File

@ -58,7 +58,6 @@ export class ZeroEx {
*/
public proxy: TokenTransferProxyWrapper;
private _web3Wrapper: Web3Wrapper;
private _abiDecoder: AbiDecoder;
/**
* Verifies that the elliptic curve signature `signature` was generated
* by signing `data` with the private key corresponding to the `signerAddress` address.
@ -167,21 +166,22 @@ export class ZeroEx {
]);
const artifactJSONs = _.values(artifacts);
const abiArrays = _.map(artifactJSONs, artifact => artifact.abi);
this._abiDecoder = new AbiDecoder(abiArrays);
const defaults = {
gasPrice: config.gasPrice,
};
this._web3Wrapper = new Web3Wrapper(provider, defaults);
_.forEach(abiArrays, abi => {
this._web3Wrapper.abiDecoder.addABI(abi);
});
this.proxy = new TokenTransferProxyWrapper(
this._web3Wrapper,
config.networkId,
config.tokenTransferProxyContractAddress,
);
this.token = new TokenWrapper(this._web3Wrapper, config.networkId, this._abiDecoder, this.proxy);
this.token = new TokenWrapper(this._web3Wrapper, config.networkId, this.proxy);
this.exchange = new ExchangeWrapper(
this._web3Wrapper,
config.networkId,
this._abiDecoder,
this.token,
config.exchangeContractAddress,
config.zrxContractAddress,
@ -191,7 +191,7 @@ export class ZeroEx {
config.networkId,
config.tokenRegistryContractAddress,
);
this.etherToken = new EtherTokenWrapper(this._web3Wrapper, config.networkId, this._abiDecoder, this.token);
this.etherToken = new EtherTokenWrapper(this._web3Wrapper, config.networkId, this.token);
}
/**
* Sets a new web3 provider for 0x.js. Updating the provider will stop all
@ -285,44 +285,12 @@ export class ZeroEx {
pollingIntervalMs = 1000,
timeoutMs?: number,
): Promise<TransactionReceiptWithDecodedLogs> {
let timeoutExceeded = false;
if (timeoutMs) {
setTimeout(() => (timeoutExceeded = true), timeoutMs);
}
const txReceiptPromise = new Promise(
(resolve: (receipt: TransactionReceiptWithDecodedLogs) => void, reject) => {
const intervalId = intervalUtils.setAsyncExcludingInterval(
async () => {
if (timeoutExceeded) {
intervalUtils.clearAsyncExcludingInterval(intervalId);
return reject(ZeroExError.TransactionMiningTimeout);
}
const transactionReceipt = await this._web3Wrapper.getTransactionReceiptAsync(txHash);
if (!_.isNull(transactionReceipt)) {
intervalUtils.clearAsyncExcludingInterval(intervalId);
const logsWithDecodedArgs = _.map(
transactionReceipt.logs,
this._abiDecoder.tryToDecodeLogOrNoop.bind(this._abiDecoder),
);
const transactionReceiptWithDecodedLogArgs: TransactionReceiptWithDecodedLogs = {
...transactionReceipt,
logs: logsWithDecodedArgs,
};
resolve(transactionReceiptWithDecodedLogArgs);
}
},
pollingIntervalMs,
(err: Error) => {
intervalUtils.clearAsyncExcludingInterval(intervalId);
reject(err);
},
);
},
const transactionReceiptWithDecodedLogs = await this._web3Wrapper.awaitTransactionMinedAsync(
txHash,
pollingIntervalMs,
timeoutMs,
);
const txReceipt = await txReceiptPromise;
return txReceipt;
return transactionReceiptWithDecodedLogs;
}
/**
* Instantiates and returns a new OrderStateWatcher instance.

View File

@ -32,7 +32,6 @@ const CONTRACT_NAME_TO_NOT_FOUND_ERROR: {
export class ContractWrapper {
protected _web3Wrapper: Web3Wrapper;
protected _networkId: number;
private _abiDecoder?: AbiDecoder;
private _blockAndLogStreamerIfExists?: BlockAndLogStreamer;
private _blockAndLogStreamIntervalIfExists?: NodeJS.Timer;
private _filters: { [filterToken: string]: FilterObject };
@ -41,10 +40,9 @@ export class ContractWrapper {
};
private _onLogAddedSubscriptionToken: string | undefined;
private _onLogRemovedSubscriptionToken: string | undefined;
constructor(web3Wrapper: Web3Wrapper, networkId: number, abiDecoder?: AbiDecoder) {
constructor(web3Wrapper: Web3Wrapper, networkId: number) {
this._web3Wrapper = web3Wrapper;
this._networkId = networkId;
this._abiDecoder = abiDecoder;
this._filters = {};
this._filterCallbacks = {};
this._blockAndLogStreamerIfExists = undefined;
@ -102,10 +100,10 @@ export class ContractWrapper {
protected _tryToDecodeLogOrNoop<ArgsType extends ContractEventArgs>(
log: LogEntry,
): LogWithDecodedArgs<ArgsType> | RawLog {
if (_.isUndefined(this._abiDecoder)) {
if (_.isUndefined(this._web3Wrapper.abiDecoder)) {
throw new Error(InternalZeroExError.NoAbiDecoder);
}
const logWithDecodedArgs = this._abiDecoder.tryToDecodeLogOrNoop(log);
const logWithDecodedArgs = this._web3Wrapper.abiDecoder.tryToDecodeLogOrNoop(log);
return logWithDecodedArgs;
}
protected async _getContractAbiAndAddressFromArtifactsAsync(

View File

@ -21,8 +21,8 @@ export class EtherTokenWrapper extends ContractWrapper {
[address: string]: EtherTokenContract;
} = {};
private _tokenWrapper: TokenWrapper;
constructor(web3Wrapper: Web3Wrapper, networkId: number, abiDecoder: AbiDecoder, tokenWrapper: TokenWrapper) {
super(web3Wrapper, networkId, abiDecoder);
constructor(web3Wrapper: Web3Wrapper, networkId: number, tokenWrapper: TokenWrapper) {
super(web3Wrapper, networkId);
this._tokenWrapper = tokenWrapper;
}
/**

View File

@ -87,12 +87,11 @@ export class ExchangeWrapper extends ContractWrapper {
constructor(
web3Wrapper: Web3Wrapper,
networkId: number,
abiDecoder: AbiDecoder,
tokenWrapper: TokenWrapper,
contractAddressIfExists?: string,
zrxContractAddressIfExists?: string,
) {
super(web3Wrapper, networkId, abiDecoder);
super(web3Wrapper, networkId);
this._tokenWrapper = tokenWrapper;
this._orderValidationUtils = new OrderValidationUtils(this);
this._contractAddressIfExists = contractAddressIfExists;

View File

@ -22,13 +22,8 @@ export class TokenWrapper extends ContractWrapper {
public UNLIMITED_ALLOWANCE_IN_BASE_UNITS = constants.UNLIMITED_ALLOWANCE_IN_BASE_UNITS;
private _tokenContractsByAddress: { [address: string]: TokenContract };
private _tokenTransferProxyWrapper: TokenTransferProxyWrapper;
constructor(
web3Wrapper: Web3Wrapper,
networkId: number,
abiDecoder: AbiDecoder,
tokenTransferProxyWrapper: TokenTransferProxyWrapper,
) {
super(web3Wrapper, networkId, abiDecoder);
constructor(web3Wrapper: Web3Wrapper, networkId: number, tokenTransferProxyWrapper: TokenTransferProxyWrapper) {
super(web3Wrapper, networkId);
this._tokenContractsByAddress = {};
this._tokenTransferProxyWrapper = tokenTransferProxyWrapper;
}

View File

@ -1,50 +1,14 @@
declare module 'web3_beta';
declare module 'chai-bignumber';
declare module 'dirty-chai';
declare module 'request-promise-native';
declare module 'web3-provider-engine';
declare module 'web3-provider-engine/subproviders/rpc';
declare module 'publish-release';
// semver-sort declarations
declare module 'semver-sort' {
const desc: (versions: string[]) => string[];
}
// HACK: In order to merge the bignumber declaration added by chai-bignumber to the chai Assertion
// interface we must use `namespace` as the Chai definitelyTyped definition does. Since we otherwise
// disallow `namespace`, we disable tslint for the following.
/* tslint:disable */
declare namespace Chai {
interface Assertion {
bignumber: Assertion;
// HACK: In order to comply with chai-as-promised we make eventually a `PromisedAssertion` not an `Assertion`
eventually: PromisedAssertion;
}
}
/* tslint:enable */
declare module '*.json' {
const json: any;
/* tslint:disable */
export default json;
/* tslint:enable */
}
declare module 'ethereumjs-abi' {
const soliditySHA3: (argTypes: string[], args: any[]) => Buffer;
}
// truffle-hdwallet-provider declarations
declare module 'truffle-hdwallet-provider' {
import { JSONRPCRequestPayload, JSONRPCResponsePayload } from '@0xproject/types';
import * as Web3 from 'web3';
class HDWalletProvider implements Web3.Provider {
constructor(mnemonic: string, rpcUrl: string);
public sendAsync(
payload: JSONRPCRequestPayload,
callback: (err: Error, result: JSONRPCResponsePayload) => void,
): void;
}
export = HDWalletProvider;
}

View File

@ -1,23 +0,0 @@
import { BigNumber } from '@0xproject/utils';
// HACK: This module overrides the Chai namespace so that we can use BigNumber types inside.
// Source: https://github.com/Microsoft/TypeScript/issues/7352#issuecomment-191547232
declare global {
// HACK: In order to merge the bignumber declaration added by chai-bignumber to the chai Assertion
// interface we must use `namespace` as the Chai definitelyTyped definition does. Since we otherwise
// disallow `namespace`, we disable tslint for the following.
/* tslint:disable */
namespace Chai {
interface NumberComparer {
(value: number | BigNumber, message?: string): Assertion;
}
interface NumericComparison {
greaterThan: NumberComparer;
}
}
/* tslint:enable */
interface DecodedLogArg {
name: string;
value: string | BigNumber;
}
}

View File

@ -69,7 +69,6 @@ export class OrderStateWatcher {
private _callbackIfExists?: OnOrderStateChangeCallback;
private _eventWatcher: EventWatcher;
private _web3Wrapper: Web3Wrapper;
private _abiDecoder: AbiDecoder;
private _expirationWatcher: ExpirationWatcher;
private _orderStateUtils: OrderStateUtils;
private _orderFilledCancelledLazyStore: OrderFilledCancelledLazyStore;
@ -78,12 +77,10 @@ export class OrderStateWatcher {
private _cleanupJobIntervalIdIfExists?: NodeJS.Timer;
constructor(
web3Wrapper: Web3Wrapper,
abiDecoder: AbiDecoder,
token: TokenWrapper,
exchange: ExchangeWrapper,
config?: OrderStateWatcherConfig,
) {
this._abiDecoder = abiDecoder;
this._web3Wrapper = web3Wrapper;
const pollingIntervalIfExistsMs = _.isUndefined(config) ? undefined : config.eventPollingIntervalMs;
const stateLayer =
@ -230,7 +227,7 @@ export class OrderStateWatcher {
return;
}
const log = logIfExists as LogEvent; // At this moment we are sure that no error occured and log is defined.
const maybeDecodedLog = this._abiDecoder.tryToDecodeLogOrNoop<ContractEventArgs>(log);
const maybeDecodedLog = this._web3Wrapper.abiDecoder.tryToDecodeLogOrNoop<ContractEventArgs>(log);
const isLogDecoded = !_.isUndefined(((maybeDecodedLog as any) as LogWithDecodedArgs<ContractEventArgs>).event);
if (!isLogDecoded) {
return; // noop

View File

@ -38,7 +38,6 @@ export enum ZeroExError {
NoNetworkId = 'NO_NETWORK_ID',
SubscriptionNotFound = 'SUBSCRIPTION_NOT_FOUND',
SubscriptionAlreadyPresent = 'SUBSCRIPTION_ALREADY_PRESENT',
TransactionMiningTimeout = 'TRANSACTION_MINING_TIMEOUT',
}
export enum InternalZeroExError {

View File

@ -1,13 +1,7 @@
{
"extends": "../../tsconfig",
"compilerOptions": {
"outDir": "lib",
"noImplicitThis": false
"outDir": "lib"
},
"include": [
"./src/**/*",
"./test/**/*",
"../../node_modules/types-bn/index.d.ts",
"../../node_modules/types-ethereumjs-util/index.d.ts"
]
"include": ["./src/**/*", "./test/**/*"]
}

View File

@ -1,5 +1,3 @@
declare module 'dirty-chai';
declare module '*.json' {
const json: any;
/* tslint:disable */

View File

@ -9,6 +9,12 @@ CHANGELOG
* Dependencies updated
## v0.1.0 - _TBD, 2018_
* Add tests for traversing ABI tree (#485)
* Fix ABI tuples traversing (#485)
* Fix ABI arrays traversing (#485)
## v0.0.2 - _March 4, 2018_
* Initial release

View File

View File

@ -2,13 +2,18 @@
"name": "@0xproject/base-contract",
"version": "0.0.6",
"description": "0x Base TS contract",
"main": "lib/index.js",
"types": "lib/index.d.ts",
"main": "lib/src/index.js",
"types": "lib/src/index.d.ts",
"scripts": {
"build:watch": "tsc -w",
"build": "tsc && copyfiles -u 2 './lib/monorepo_scripts/**/*' ./scripts",
"clean": "shx rm -rf lib scripts",
"lint": "tslint --project . 'src/**/*.ts'"
"test": "run-s clean build run_mocha",
"test:circleci": "yarn test:coverage",
"run_mocha": "mocha lib/test/**/*_test.js --bail --exit",
"test:coverage": "nyc npm run test --all && yarn coverage:report:lcov",
"coverage:report:lcov": "nyc report --reporter=text-lcov > coverage/lcov.info",
"lint": "tslint --project ."
},
"license": "Apache-2.0",
"repository": {
@ -26,10 +31,13 @@
"copyfiles": "^1.2.0",
"npm-run-all": "^4.1.2",
"shx": "^0.2.2",
"chai": "^4.0.1",
"mocha": "^4.0.1",
"tslint": "5.8.0",
"typescript": "2.7.1"
},
"dependencies": {
"@0xproject/utils": "^0.4.3",
"@0xproject/types": "^0.4.2",
"@0xproject/typescript-typings": "^0.0.2",
"@0xproject/web3-wrapper": "^0.4.0",

View File

@ -1,40 +1,31 @@
import { ContractAbi, DataItem, TxData, TxDataPayable } from '@0xproject/types';
import { BigNumber } from '@0xproject/utils';
import { Web3Wrapper } from '@0xproject/web3-wrapper';
import * as ethersContracts from 'ethers-contracts';
import * as _ from 'lodash';
import { formatABIDataItem } from './utils';
export class BaseContract {
protected _ethersInterface: ethersContracts.Interface;
protected _web3Wrapper: Web3Wrapper;
public abi: ContractAbi;
public address: string;
protected static _transformABIData(
protected static _formatABIDataItemList(
abis: DataItem[],
values: any[],
transformation: (type: string, value: any) => any,
formatter: (type: string, value: any) => any,
): any {
return _.map(values, (value: any, i: number) =>
BaseContract._transformTypedData(abis[i].type, value, transformation),
);
return _.map(values, (value: any, i: number) => formatABIDataItem(abis[i], value, formatter));
}
protected static _lowercaseAddress(type: string, value: string): string {
return type === 'address' ? value.toLowerCase() : value;
}
protected static _bigNumberToString(type: string, value: string): string {
return _.isObject(value) && (value as any).isBigNumber ? value.toString() : value;
protected static _bigNumberToString(type: string, value: any): any {
return _.isObject(value) && value.isBigNumber ? value.toString() : value;
}
private static _transformTypedData(
type: string,
values: any,
transformation: (type: string, value: any) => any,
): any {
const trailingArrayRegex = /\[\d*\]$/;
if (type.match(trailingArrayRegex)) {
const arrayItemType = type.replace(trailingArrayRegex, '');
return _.map(values, value => this._transformTypedData(arrayItemType, value, transformation));
} else {
return transformation(type, values);
}
protected static _bnToBigNumber(type: string, value: any): any {
return _.isObject(value) && value._bn ? new BigNumber(value.toString()) : value;
}
protected async _applyDefaultsToTxDataAsync<T extends Partial<TxData | TxDataPayable>>(
txData: T,

View File

@ -0,0 +1,25 @@
import { DataItem } from '@0xproject/types';
import * as _ from 'lodash';
// tslint:disable-next-line:completed-docs
export function formatABIDataItem(abi: DataItem, value: any, formatter: (type: string, value: any) => any): any {
const trailingArrayRegex = /\[\d*\]$/;
if (abi.type.match(trailingArrayRegex)) {
const arrayItemType = abi.type.replace(trailingArrayRegex, '');
return _.map(value, val => {
const arrayItemAbi = {
...abi,
type: arrayItemType,
};
return formatABIDataItem(arrayItemAbi, val, formatter);
});
} else if (abi.type === 'tuple') {
const formattedTuple: { [componentName: string]: DataItem } = {};
_.forEach(abi.components, componentABI => {
formattedTuple[componentABI.name] = formatABIDataItem(componentABI, value[componentABI.name], formatter);
});
return formattedTuple;
} else {
return formatter(abi.type, value);
}
}

View File

@ -0,0 +1,108 @@
import { BigNumber } from '@0xproject/utils';
import * as chai from 'chai';
import 'mocha';
import { formatABIDataItem } from '../src/utils';
const { expect } = chai;
describe('Utils tests', () => {
describe('#formatABIDataItem', () => {
it('correctly handles arrays', () => {
const calls: Array<{ type: string; value: any }> = [];
const abi = {
name: 'values',
type: 'uint256[]',
};
const val = [1, 2, 3];
const formatted = formatABIDataItem(abi, val, (type: string, value: any) => {
calls.push({ type, value });
return value; // no-op
});
expect(formatted).to.be.deep.equal(val);
expect(calls).to.be.deep.equal([
{ type: 'uint256', value: 1 },
{ type: 'uint256', value: 2 },
{ type: 'uint256', value: 3 },
]);
});
it('correctly handles tuples', () => {
const calls: Array<{ type: string; value: any }> = [];
const abi = {
components: [
{
name: 'to',
type: 'address',
},
{
name: 'amount',
type: 'uint256',
},
],
name: 'data',
type: 'tuple',
};
const ZERO_ADDRESS = '0x0000000000000000000000000000000000000000';
const val = { to: ZERO_ADDRESS, amount: new BigNumber(1) };
const formatted = formatABIDataItem(abi, val, (type: string, value: any) => {
calls.push({ type, value });
return value; // no-op
});
expect(formatted).to.be.deep.equal(val);
expect(calls).to.be.deep.equal([
{
type: 'address',
value: val.to,
},
{
type: 'uint256',
value: val.amount,
},
]);
});
it('correctly handles nested arrays of tuples', () => {
const calls: Array<{ type: string; value: any }> = [];
const abi = {
components: [
{
name: 'to',
type: 'address',
},
{
name: 'amount',
type: 'uint256',
},
],
name: 'data',
type: 'tuple[2][]',
};
const ZERO_ADDRESS = '0x0000000000000000000000000000000000000000';
const val = [
[{ to: ZERO_ADDRESS, amount: new BigNumber(1) }, { to: ZERO_ADDRESS, amount: new BigNumber(2) }],
];
const formatted = formatABIDataItem(abi, val, (type: string, value: any) => {
calls.push({ type, value });
return value; // no-op
});
expect(formatted).to.be.deep.equal(val);
expect(calls).to.be.deep.equal([
{
type: 'address',
value: val[0][0].to,
},
{
type: 'uint256',
value: val[0][0].amount,
},
{
type: 'address',
value: val[0][1].to,
},
{
type: 'uint256',
value: val[0][1].amount,
},
]);
});
});
});

View File

@ -3,5 +3,5 @@
"compilerOptions": {
"outDir": "lib"
},
"include": ["./src/**/*"]
"include": ["src/**/*", "test/**/*"]
}

View File

@ -1,5 +1,4 @@
declare module 'async-child-process';
declare module 'dirty-chai';
declare module '*.json' {
const value: any;

View File

@ -10,7 +10,6 @@ import { BigNumber, classUtils, promisify } from '@0xproject/utils';
import { Web3Wrapper } from '@0xproject/web3-wrapper';
import * as ethersContracts from 'ethers-contracts';
import * as _ from 'lodash';
import * as Web3 from 'web3';
{{#if events}}
export type {{contractName}}ContractEventArgs =

View File

@ -4,9 +4,9 @@ async callAsync(
callData: Partial<CallData> = {},
defaultBlock?: BlockParam,
): Promise<{{> return_type outputs=outputs}}> {
const self = this as {{contractName}}Contract;
const self = this as any as {{contractName}}Contract;
const inputAbi = (_.find(self.abi, {name: '{{this.name}}'}) as MethodAbi).inputs;
[{{> params inputs=inputs}}] = BaseContract._transformABIData(inputAbi, [{{> params inputs=inputs}}], BaseContract._bigNumberToString.bind(self));
[{{> params inputs=inputs}}] = BaseContract._formatABIDataItemList(inputAbi, [{{> params inputs=inputs}}], BaseContract._bigNumberToString.bind(self));
const encodedData = self._ethersInterface.functions.{{this.name}}(
{{> params inputs=inputs}}
).data;
@ -19,7 +19,8 @@ async callAsync(
const outputAbi = (_.find(self.abi, {name: '{{this.name}}'}) as MethodAbi).outputs;
const outputParamsTypes = _.map(outputAbi, 'type');
let resultArray = ethersContracts.Interface.decodeParams(outputParamsTypes, rawCallResult) as any;
resultArray = BaseContract._transformABIData(outputAbi, resultArray, BaseContract._lowercaseAddress.bind(this));
resultArray = BaseContract._formatABIDataItemList(outputAbi, resultArray, BaseContract._lowercaseAddress.bind(this));
resultArray = BaseContract._formatABIDataItemList(outputAbi, resultArray, BaseContract._bnToBigNumber.bind(this));
return resultArray{{#singleReturnValue}}[0]{{/singleReturnValue}};
},
{{/hasReturnValue}}

View File

@ -8,9 +8,9 @@ public {{this.name}} = {
txData: Partial<TxData> = {},
{{/this.payable}}
): Promise<string> {
const self = this as {{contractName}}Contract;
const self = this as any as {{contractName}}Contract;
const inputAbi = (_.find(self.abi, {name: '{{this.name}}'}) as MethodAbi).inputs;
[{{> params inputs=inputs}}] = BaseContract._transformABIData(inputAbi, [{{> params inputs=inputs}}], BaseContract._bigNumberToString.bind(self));
[{{> params inputs=inputs}}] = BaseContract._formatABIDataItemList(inputAbi, [{{> params inputs=inputs}}], BaseContract._bigNumberToString.bind(self));
const encodedData = self._ethersInterface.functions.{{this.name}}(
{{> params inputs=inputs}}
).data
@ -31,9 +31,9 @@ public {{this.name}} = {
{{> typed_params inputs=inputs}}
txData: Partial<TxData> = {},
): Promise<number> {
const self = this as {{contractName}}Contract;
const self = this as any as {{contractName}}Contract;
const inputAbi = (_.find(self.abi, {name: '{{this.name}}'}) as MethodAbi).inputs;
[{{> params inputs=inputs}}] = BaseContract._transformABIData(inputAbi, [{{> params inputs=inputs}}], BaseContract._bigNumberToString.bind(this));
[{{> params inputs=inputs}}] = BaseContract._formatABIDataItemList(inputAbi, [{{> params inputs=inputs}}], BaseContract._bigNumberToString.bind(this));
const encodedData = self._ethersInterface.functions.{{this.name}}(
{{> params inputs=inputs}}
).data
@ -49,9 +49,9 @@ public {{this.name}} = {
getABIEncodedTransactionData(
{{> typed_params inputs=inputs}}
): string {
const self = this as {{contractName}}Contract;
const self = this as any as {{contractName}}Contract;
const inputAbi = (_.find(self.abi, {name: '{{this.name}}'}) as MethodAbi).inputs;
[{{> params inputs=inputs}}] = BaseContract._transformABIData(inputAbi, [{{> params inputs=inputs}}], BaseContract._bigNumberToString.bind(self));
[{{> params inputs=inputs}}] = BaseContract._formatABIDataItemList(inputAbi, [{{> params inputs=inputs}}], BaseContract._bigNumberToString.bind(self));
const abiEncodedTransactionData = self._ethersInterface.functions.{{this.name}}(
{{> params inputs=inputs}}
).data

View File

@ -1,35 +1,6 @@
declare module 'chai-bignumber';
declare module 'dirty-chai';
// HACK: In order to merge the bignumber declaration added by chai-bignumber to the chai Assertion
// interface we must use `namespace` as the Chai definitelyTyped definition does. Since we otherwise
// disallow `namespace`, we disable tslint for the following.
/* tslint:disable */
declare namespace Chai {
interface Assertion {
bignumber: Assertion;
}
}
/* tslint:enable */
declare module '*.json' {
const json: any;
/* tslint:disable */
export default json;
/* tslint:enable */
}
declare module 'solc' {
export function compile(sources: any, optimizerEnabled: number, findImports: (importPath: string) => any): any;
export function setupMethods(solcBin: any): any;
}
declare module 'web3-eth-abi' {
export function encodeParameters(typesArray: string[], parameters: any[]): string;
}
declare module 'ethereumjs-abi' {
const soliditySHA3: (argTypes: string[], args: any[]) => Buffer;
const soliditySHA256: (argTypes: string[], args: any[]) => Buffer;
const methodID: (name: string, types: string[]) => Buffer;
}

View File

@ -1,19 +0,0 @@
import { BigNumber } from '@0xproject/utils';
// HACK: This module overrides the Chai namespace so that we can use BigNumber types inside.
// Source: https://github.com/Microsoft/TypeScript/issues/7352#issuecomment-191547232
declare global {
// HACK: In order to merge the bignumber declaration added by chai-bignumber to the chai Assertion
// interface we must use `namespace` as the Chai definitelyTyped definition does. Since we otherwise
// disallow `namespace`, we disable tslint for the following.
/* tslint:disable */
namespace Chai {
interface NumberComparer {
(value: number | BigNumber, message?: string): Assertion;
}
interface NumericComparison {
greaterThan: NumberComparer;
}
}
/* tslint:enable */
}

View File

@ -59,8 +59,6 @@
"shx": "^0.2.2",
"solc": "^0.4.18",
"tslint": "5.8.0",
"types-bn": "^0.0.1",
"types-ethereumjs-util": "0xProject/types-ethereumjs-util",
"typescript": "2.7.1",
"yargs": "^10.0.3"
},

View File

@ -4,17 +4,8 @@
"outDir": "lib",
"baseUrl": ".",
"declaration": false,
"noImplicitThis": false,
"allowJs": true
},
"include": [
"../../node_modules/types-ethereumjs-util/index.d.ts",
"../../node_modules/types-bn/index.d.ts",
"./globals.d.ts",
"./src/**/*",
"./util/**/*",
"./test/**/*",
"./migrations/**/*"
],
"include": ["./globals.d.ts", "./src/**/*", "./util/**/*", "./test/**/*", "./migrations/**/*"],
"exclude": ["./deploy/solc/solc_bin"]
}

View File

@ -1,4 +1,13 @@
[
{
"version": "0.3.5",
"changes": [
{
"note": "Don't try to write contract artifact if the error occured",
"pr": 485
}
]
},
{
"version": "0.3.4",
"changes": [
@ -7,7 +16,8 @@
"pr": 491
}
],
"timestamp": 1522658513
"timestamp": 1522658513,
"isPublished": true
},
{
"version": "0.3.1",

View File

View File

@ -179,10 +179,15 @@ export class Compiler {
);
if (!_.isUndefined(compiled.errors)) {
const isError = (errorOrWarning: string) => !errorOrWarning.includes('Warning');
const errors = _.filter(compiled.errors, isError);
_.forEach(compiled.errors, errMsg => {
const normalizedErrMsg = getNormalizedErrMsg(errMsg);
this._solcErrors.add(normalizedErrMsg);
});
if (!_.isEmpty(errors)) {
return;
}
}
const contractName = path.basename(fileName, constants.SOLIDITY_FILE_EXTENSION);
const contractIdentifier = `${fileName}:${contractName}`;

View File

@ -1,49 +1,3 @@
declare module 'dirty-chai';
// tslint:disable:completed-docs
declare module 'solc' {
export interface ContractCompilationResult {
srcmap: string;
srcmapRuntime: string;
bytecode: string;
runtimeBytecode: string;
interface: string;
}
export interface CompilationResult {
errors: string[];
contracts: {
[contractIdentifier: string]: ContractCompilationResult;
};
sources: {
[sourceName: string]: {
AST: any;
};
};
sourceList: string[];
}
export interface ImportContents {
contents: string;
}
export interface InputSources {
sources: {
[fileName: string]: string;
};
}
export interface SolcInstance {
compile(
sources: InputSources,
optimizerEnabled: number,
findImports: (importPath: string) => ImportContents,
): CompilationResult;
}
export function loadRemoteVersion(versionName: string, cb: (err: Error | null, res?: SolcInstance) => void): void;
export function setupMethods(solcBin: any): SolcInstance;
}
declare module 'web3-eth-abi' {
export function encodeParameters(typesArray: string[], parameters: any[]): string;
}
declare module '*.json' {
const json: any;
/* tslint:disable */

View File

@ -4,10 +4,5 @@
"outDir": "lib",
"strictFunctionTypes": false
},
"include": [
"./src/**/*",
"./test/**/*",
"../../node_modules/types-bn/index.d.ts",
"../../node_modules/types-ethereumjs-util/index.d.ts"
]
"include": ["./src/**/*", "./test/**/*"]
}

View File

@ -36,8 +36,6 @@
"nyc": "^11.0.1",
"shx": "^0.2.2",
"tslint": "5.8.0",
"types-bn": "^0.0.1",
"types-ethereumjs-util": "0xProject/types-ethereumjs-util",
"typescript": "2.7.1"
},
"dependencies": {

View File

@ -1,4 +1,3 @@
declare module 'web3-provider-engine';
declare module 'web3-provider-engine/subproviders/rpc';
declare module '*.json' {

View File

@ -3,10 +3,5 @@
"compilerOptions": {
"outDir": "lib"
},
"include": [
"./src/**/*",
"./test/**/*",
"../../node_modules/types-bn/index.d.ts",
"../../node_modules/types-ethereumjs-util/index.d.ts"
]
"include": ["./src/**/*", "./test/**/*"]
}

View File

@ -1,5 +1,3 @@
declare module 'dirty-chai';
declare module '*.json' {
const json: any;
/* tslint:disable */

View File

@ -0,0 +1,98 @@
{
"contract_name": "Metacoin",
"networks": {
"50": {
"solc_version": "0.4.21",
"keccak256": "0x2c3aa2e9dbef58abf57cecc148464d0852a83d7f30bbd2066f2a13b8bd3b1dd0",
"source_tree_hash": "0x2c3aa2e9dbef58abf57cecc148464d0852a83d7f30bbd2066f2a13b8bd3b1dd0",
"optimizer_enabled": false,
"abi": [
{
"constant": true,
"inputs": [
{
"name": "",
"type": "address"
}
],
"name": "balances",
"outputs": [
{
"name": "",
"type": "uint256"
}
],
"payable": false,
"stateMutability": "view",
"type": "function"
},
{
"constant": false,
"inputs": [
{
"components": [
{
"name": "to",
"type": "address"
},
{
"name": "amount",
"type": "uint256"
}
],
"name": "transferData",
"type": "tuple"
}
],
"name": "transfer",
"outputs": [
{
"name": "success",
"type": "bool"
}
],
"payable": false,
"stateMutability": "nonpayable",
"type": "function"
},
{
"inputs": [],
"payable": false,
"stateMutability": "nonpayable",
"type": "constructor"
},
{
"anonymous": false,
"inputs": [
{
"indexed": true,
"name": "_from",
"type": "address"
},
{
"indexed": true,
"name": "_to",
"type": "address"
},
{
"indexed": false,
"name": "_value",
"type": "uint256"
}
],
"name": "Transfer",
"type": "event"
}
],
"bytecode":
"0x6060604052341561000f57600080fd5b6127106000803373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002081905550610406806100636000396000f30060606040526004361061004c576000357c0100000000000000000000000000000000000000000000000000000000900463ffffffff16806327e235e3146100515780632bd14bb914610087575b600080fd5b341561005c57600080fd5b610071600461006c9036906102b9565b6100bd565b60405161007e9190610344565b60405180910390f35b341561009257600080fd5b6100a760046100a29036906102e2565b6100d5565b6040516100b49190610329565b60405180910390f35b60006020528060005260406000206000915090505481565b600081602001516000803373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002054101561012a5760009050610240565b81602001516000803373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020600082825403925050819055508160200151600080846000015173ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002060008282540192505081905550816000015173ffffffffffffffffffffffffffffffffffffffff163373ffffffffffffffffffffffffffffffffffffffff167fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef84602001516040516102339190610344565b60405180910390a3600190505b919050565b600061025182356103a2565b905092915050565b60006040828403121561026b57600080fd5b610275604061035f565b9050600061028584828501610245565b6000830152506020610299848285016102a5565b60208301525092915050565b60006102b182356103c2565b905092915050565b6000602082840312156102cb57600080fd5b60006102d984828501610245565b91505092915050565b6000604082840312156102f457600080fd5b600061030284828501610259565b91505092915050565b6103148161038c565b82525050565b61032381610398565b82525050565b600060208201905061033e600083018461030b565b92915050565b6000602082019050610359600083018461031a565b92915050565b6000604051905081810181811067ffffffffffffffff8211171561038257600080fd5b8060405250919050565b60008115159050919050565b6000819050919050565b600073ffffffffffffffffffffffffffffffffffffffff82169050919050565b60008190509190505600a265627a7a72305820d15828219194e8ddaa624e10f9c8823c05268d79753b4c60ef401fb4fe5f09dc6c6578706572696d656e74616cf50037",
"runtime_bytecode":
"0x60606040526004361061004c576000357c0100000000000000000000000000000000000000000000000000000000900463ffffffff16806327e235e3146100515780632bd14bb914610087575b600080fd5b341561005c57600080fd5b610071600461006c9036906102b9565b6100bd565b60405161007e9190610344565b60405180910390f35b341561009257600080fd5b6100a760046100a29036906102e2565b6100d5565b6040516100b49190610329565b60405180910390f35b60006020528060005260406000206000915090505481565b600081602001516000803373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002054101561012a5760009050610240565b81602001516000803373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020600082825403925050819055508160200151600080846000015173ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002060008282540192505081905550816000015173ffffffffffffffffffffffffffffffffffffffff163373ffffffffffffffffffffffffffffffffffffffff167fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef84602001516040516102339190610344565b60405180910390a3600190505b919050565b600061025182356103a2565b905092915050565b60006040828403121561026b57600080fd5b610275604061035f565b9050600061028584828501610245565b6000830152506020610299848285016102a5565b60208301525092915050565b60006102b182356103c2565b905092915050565b6000602082840312156102cb57600080fd5b60006102d984828501610245565b91505092915050565b6000604082840312156102f457600080fd5b600061030284828501610259565b91505092915050565b6103148161038c565b82525050565b61032381610398565b82525050565b600060208201905061033e600083018461030b565b92915050565b6000602082019050610359600083018461031a565b92915050565b6000604051905081810181811067ffffffffffffffff8211171561038257600080fd5b8060405250919050565b60008115159050919050565b6000819050919050565b600073ffffffffffffffffffffffffffffffffffffffff82169050919050565b60008190509190505600a265627a7a72305820d15828219194e8ddaa624e10f9c8823c05268d79753b4c60ef401fb4fe5f09dc6c6578706572696d656e74616cf50037",
"updated_at": 1522318279735,
"source_map": "60:662:0:-;;;290:72;;;;;;;;350:5;327:8;:20;336:10;327:20;;;;;;;;;;;;;;;:28;;;;60:662;;;;;;",
"source_map_runtime":
"60:662:0:-;;;;;;;;;;;;;;;;;;;;;;;;;;;;;84:41;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;368:352;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;84:41;;;;;;;;;;;;;;;;;:::o;368:352::-;429:12;480;:19;;;457:8;:20;466:10;457:20;;;;;;;;;;;;;;;;:42;453:60;;;508:5;501:12;;;;453:60;547:12;:19;;;523:8;:20;532:10;523:20;;;;;;;;;;;;;;;;:43;;;;;;;;;;;605:12;:19;;;576:8;:25;585:12;:15;;;576:25;;;;;;;;;;;;;;;;:48;;;;;;;;;;;655:12;:15;;;634:58;;643:10;634:58;;;672:12;:19;;;634:58;;;;;;;;;;;;;;;709:4;702:11;;368:352;;;;:::o;5:118:-1:-;;72:46;110:6;97:20;72:46;;;63:55;;57:66;;;;;165:469;;282:4;270:9;265:3;261:19;257:30;254:2;;;300:1;297;290:12;254:2;318:20;333:4;318:20;;;309:29;;386:1;417:49;462:3;453:6;442:9;438:22;417:49;;;411:3;404:5;400:15;393:74;348:130;530:2;563:49;608:3;599:6;588:9;584:22;563:49;;;556:4;549:5;545:16;538:75;488:136;248:386;;;;;641:118;;708:46;746:6;733:20;708:46;;;699:55;;693:66;;;;;766:241;;870:2;858:9;849:7;845:23;841:32;838:2;;;886:1;883;876:12;838:2;921:1;938:53;983:7;974:6;963:9;959:22;938:53;;;928:63;;900:97;832:175;;;;;1014:297;;1146:2;1134:9;1125:7;1121:23;1117:32;1114:2;;;1162:1;1159;1152:12;1114:2;1197:1;1214:81;1287:7;1278:6;1267:9;1263:22;1214:81;;;1204:91;;1176:125;1108:203;;;;;1318:101;1385:28;1407:5;1385:28;;;1380:3;1373:41;1367:52;;;1426:110;1499:31;1524:5;1499:31;;;1494:3;1487:44;1481:55;;;1543:181;;1645:2;1634:9;1630:18;1622:26;;1659:55;1711:1;1700:9;1696:17;1687:6;1659:55;;;1616:108;;;;;1731:193;;1839:2;1828:9;1824:18;1816:26;;1853:61;1911:1;1900:9;1896:17;1887:6;1853:61;;;1810:114;;;;;1931:256;;1993:2;1987:9;1977:19;;2031:4;2023:6;2019:17;2130:6;2118:10;2115:22;2094:18;2082:10;2079:34;2076:62;2073:2;;;2151:1;2148;2141:12;2073:2;2171:10;2167:2;2160:22;1971:216;;;;;2194:92;;2274:5;2267:13;2260:21;2249:32;;2243:43;;;;2293:79;;2362:5;2351:16;;2345:27;;;;2379:128;;2459:42;2452:5;2448:54;2437:65;;2431:76;;;;2514:79;;2583:5;2572:16;;2566:27;;;",
"sources": ["Metacoin.sol"]
}
}
}

View File

@ -0,0 +1,25 @@
pragma solidity ^0.4.21;
pragma experimental ABIEncoderV2;
contract Metacoin {
mapping (address => uint) public balances;
event Transfer(address indexed _from, address indexed _to, uint256 _value);
struct TransferData {
address to;
uint256 amount;
}
function Metacoin() public {
balances[msg.sender] = 10000;
}
function transfer(TransferData transferData) public returns (bool success) {
if (balances[msg.sender] < transferData.amount) return false;
balances[msg.sender] -= transferData.amount;
balances[transferData.to] += transferData.amount;
Transfer(msg.sender, transferData.to, transferData.amount);
return true;
}
}

View File

View File

@ -0,0 +1,60 @@
{
"name": "@0xproject/metacoin",
"version": "0.0.1",
"private": true,
"description": "Example solidity project using 0x dev tools",
"scripts": {
"build:watch": "tsc -w",
"lint": "tslint --project .",
"clean": "shx rm -rf lib",
"prebuild": "run-s clean generate_contract_wrappers",
"build": "tsc",
"test": "run-s build run_mocha",
"test:coverage": "SOLIDITY_COVERAGE=true run-s build run_mocha coverage:report:text coverage:report:lcov",
"run_mocha": "mocha 'lib/test/**/*.js'",
"generate_contract_wrappers": "node ../abi-gen/lib/index.js --abis 'artifacts/Metacoin.json' --template ../contract_templates/contract.handlebars --partials '../contract_templates/partials/**/*.handlebars' --output src/contract_wrappers --backend ethers && prettier --write 'src/contract_wrappers/**.ts'",
"coverage:report:text": "istanbul report text",
"coverage:report:html": "istanbul report html && open coverage/index.html",
"coverage:report:lcov": "istanbul report lcov",
"test:circleci": "yarn test:coverage",
"compile": "node ../deployer/lib/src/cli.js compile --contracts Metacoin --contracts-dir contracts --artifacts-dir artifacts"
},
"repository": {
"type": "git",
"url": "https://github.com/0xProject/0x-monorepo.git"
},
"author": "",
"license": "Apache-2.0",
"bugs": {
"url": "https://github.com/0xProject/0x-monorepo/issues"
},
"homepage": "https://github.com/0xProject/0x-monorepo/packages/metacoin/README.md",
"dependencies": {
"@0xproject/abi-gen": "^0.2.7",
"@0xproject/base-contract": "^0.0.5",
"@0xproject/deployer": "^0.3.3",
"@0xproject/types": "^0.4.1",
"@0xproject/tslint-config": "^0.4.12",
"@0xproject/sol-cov": "^0.0.4",
"@0xproject/subproviders": "^0.8.2",
"@0xproject/web3-wrapper": "^0.3.1",
"@0xproject/utils": "^0.4.3",
"ethers-contracts": "^2.2.1",
"lodash": "^4.17.4",
"web3-provider-engine": "^13.0.1"
},
"devDependencies": {
"@0xproject/dev-utils": "^0.3.2",
"npm-run-all": "^4.1.2",
"dirty-chai": "^2.0.1",
"shx": "^0.2.2",
"tslint": "5.8.0",
"chai": "^4.0.1",
"chai-as-promised": "^7.1.0",
"chai-bignumber": "^2.0.1",
"typescript": "2.7.1"
},
"publishConfig": {
"access": "private"
}
}

View File

@ -0,0 +1,10 @@
import { env, EnvVars } from '@0xproject/dev-utils';
import { coverage } from './utils/coverage';
after('generate coverage report', async () => {
if (env.parseBoolean(EnvVars.SolidityCoverage)) {
const coverageSubprovider = coverage.getCoverageSubproviderSingleton();
await coverageSubprovider.writeCoverageAsync();
}
});

View File

@ -0,0 +1,62 @@
import { BlockchainLifecycle, devConstants } from '@0xproject/dev-utils';
import { LogWithDecodedArgs } from '@0xproject/types';
import { BigNumber } from '@0xproject/utils';
import { Web3Wrapper } from '@0xproject/web3-wrapper';
import * as chai from 'chai';
import { MetacoinContract, TransferContractEventArgs } from '../src/contract_wrappers/metacoin';
import { chaiSetup } from './utils/chai_setup';
import { deployer } from './utils/deployer';
import { web3Wrapper } from './utils/web3_wrapper';
chaiSetup.configure();
const { expect } = chai;
const blockchainLifecycle = new BlockchainLifecycle(web3Wrapper);
describe('Metacoin', () => {
let metacoin: MetacoinContract;
const ownerAddress = devConstants.TESTRPC_FIRST_ADDRESS;
const INITIAL_BALANCE = new BigNumber(10000);
before(async () => {
const metacoinInstance = await deployer.deployAsync('Metacoin');
web3Wrapper.abiDecoder.addABI(metacoinInstance.abi);
metacoin = new MetacoinContract(web3Wrapper, metacoinInstance.abi, metacoinInstance.address);
});
beforeEach(async () => {
await blockchainLifecycle.startAsync();
});
afterEach(async () => {
await blockchainLifecycle.revertAsync();
});
describe('#constructor', () => {
it(`should initialy give ${INITIAL_BALANCE} tokens to the creator`, async () => {
const balance = await metacoin.balances.callAsync(ownerAddress);
expect(balance).to.be.bignumber.equal(INITIAL_BALANCE);
});
});
describe('#transfer', () => {
it(`should successfully transfer tokens`, async () => {
const ZERO_ADDRESS = '0x0000000000000000000000000000000000000000';
const amount = INITIAL_BALANCE.div(2);
const oldBalance = await metacoin.balances.callAsync(ZERO_ADDRESS);
expect(oldBalance).to.be.bignumber.equal(0);
const txHash = await metacoin.transfer.sendTransactionAsync(
{
to: ZERO_ADDRESS,
amount,
},
{ from: devConstants.TESTRPC_FIRST_ADDRESS },
);
const txReceipt = await web3Wrapper.awaitTransactionMinedAsync(txHash);
const transferLogs = txReceipt.logs[0] as LogWithDecodedArgs<TransferContractEventArgs>;
expect(transferLogs.args).to.be.deep.equal({
_to: ZERO_ADDRESS,
_from: devConstants.TESTRPC_FIRST_ADDRESS,
_value: amount,
});
const newBalance = await metacoin.balances.callAsync(ZERO_ADDRESS);
expect(newBalance).to.be.bignumber.equal(amount);
});
});
});

View File

@ -0,0 +1,13 @@
import * as chai from 'chai';
import chaiAsPromised = require('chai-as-promised');
import ChaiBigNumber = require('chai-bignumber');
import * as dirtyChai from 'dirty-chai';
export const chaiSetup = {
configure() {
chai.config.includeStack = true;
chai.use(ChaiBigNumber());
chai.use(dirtyChai);
chai.use(chaiAsPromised);
},
};

View File

@ -0,0 +1,22 @@
import { CoverageSubprovider } from '@0xproject/sol-cov';
import * as _ from 'lodash';
import { devConstants } from '@0xproject/dev-utils';
let coverageSubprovider: CoverageSubprovider;
export const coverage = {
getCoverageSubproviderSingleton(): CoverageSubprovider {
if (_.isUndefined(coverageSubprovider)) {
coverageSubprovider = coverage._getCoverageSubprovider();
}
return coverageSubprovider;
},
_getCoverageSubprovider(): CoverageSubprovider {
const artifactsPath = 'artifacts';
const contractsPath = 'contracts';
const networkId = 50;
const defaultFromAddress = devConstants.TESTRPC_FIRST_ADDRESS;
return new CoverageSubprovider(artifactsPath, contractsPath, networkId, defaultFromAddress);
},
};

View File

@ -0,0 +1,16 @@
import { Deployer } from '@0xproject/deployer';
import { devConstants } from '@0xproject/dev-utils';
import * as path from 'path';
import { web3Wrapper } from './web3_wrapper';
const deployerOpts = {
web3Provider: web3Wrapper.getProvider(),
artifactsDir: path.resolve('artifacts'),
networkId: 50,
defaults: {
from: devConstants.TESTRPC_FIRST_ADDRESS,
},
};
export const deployer = new Deployer(deployerOpts);

View File

@ -0,0 +1,30 @@
import { env, EnvVars } from '@0xproject/dev-utils';
import { GanacheSubprovider } from '@0xproject/subproviders';
import { Web3Wrapper } from '@0xproject/web3-wrapper';
import * as fs from 'fs';
import * as _ from 'lodash';
import ProviderEngine = require('web3-provider-engine');
import { coverage } from './coverage';
export const web3Provider = new ProviderEngine();
const isCoverageEnabled = env.parseBoolean(EnvVars.SolidityCoverage);
if (isCoverageEnabled) {
web3Provider.addProvider(coverage.getCoverageSubproviderSingleton());
}
web3Provider.addProvider(
new GanacheSubprovider({
logger: {
log: (arg: any) => {
fs.appendFileSync('ganache.log', `${arg}\n`);
},
},
verbose: env.parseBoolean(EnvVars.SolidityCoverage),
port: 8545,
networkId: 50,
mnemonic: 'concert load couple harbor equip island argue ramp clarify fence smart topic',
}),
);
web3Provider.start();
export const web3Wrapper = new Web3Wrapper(web3Provider);

View File

@ -0,0 +1,7 @@
{
"extends": "../../tsconfig",
"compilerOptions": {
"outDir": "lib"
},
"include": ["src/**/*", "test/**/*"]
}

View File

@ -0,0 +1,3 @@
{
"extends": ["@0xproject/tslint-config"]
}

View File

@ -50,7 +50,7 @@
"lodash": "^4.17.4",
"semaphore-async-await": "^1.5.1",
"solidity-coverage": "^0.4.10",
"solidity-parser-antlr": "^0.2.7",
"solidity-parser-antlr": "^0.2.8",
"solidity-parser-sc": "^0.4.4"
},
"devDependencies": {

View File

@ -1,5 +1,3 @@
declare module 'dirty-chai';
// tslint:disable:completed-docs
declare module '*.json' {
const json: any;

View File

@ -3,10 +3,5 @@
"compilerOptions": {
"outDir": "lib"
},
"include": [
"./src/**/*",
"./test/**/*",
"../../node_modules/types-bn/index.d.ts",
"../../node_modules/types-ethereumjs-util/index.d.ts"
]
"include": ["./src/**/*", "./test/**/*"]
}

View File

@ -1,5 +1,3 @@
declare module 'dirty-chai';
declare module 'newman' {
export interface NewmanRunSummary {
run: NewmanRun;

View File

@ -69,8 +69,6 @@
"shx": "^0.2.2",
"tslint": "5.8.0",
"typedoc": "0xProject/typedoc",
"types-bn": "^0.0.1",
"types-ethereumjs-util": "0xProject/types-ethereumjs-util",
"typescript": "2.7.1",
"webpack": "^3.1.0"
},

View File

@ -1,4 +1,3 @@
declare module 'dirty-chai';
declare module 'es6-promisify';
// tslint:disable:max-classes-per-file
@ -7,19 +6,6 @@ declare module 'es6-promisify';
// tslint:disable:completed-docs
// Ethereumjs-tx declarations
declare module 'ethereumjs-tx' {
class EthereumTx {
public raw: Buffer[];
public r: Buffer;
public s: Buffer;
public v: Buffer;
public nonce: Buffer;
public serialize(): Buffer;
public getSenderAddress(): Buffer;
constructor(txParams: any);
}
export = EthereumTx;
}
// Ledgerco declarations
interface ECSignatureString {
@ -84,17 +70,6 @@ declare module 'web3-provider-engine/subproviders/rpc' {
}
export = RpcSubprovider;
}
declare module 'web3-provider-engine' {
class Web3ProviderEngine {
public on(event: string, handler: () => void): void;
public send(payload: any): void;
public sendAsync(payload: any, callback: (error: any, response: any) => void): void;
public addProvider(provider: any): void;
public start(): void;
public stop(): void;
}
export = Web3ProviderEngine;
}
declare module 'web3-provider-engine/util/rpc-cache-utils' {
class ProviderEngineRpcUtils {
public static blockTagForPayload(payload: any): string | null;

View File

@ -3,10 +3,5 @@
"compilerOptions": {
"outDir": "lib"
},
"include": [
"./src/**/*",
"./test/**/*",
"../../node_modules/types-bn/index.d.ts",
"../../node_modules/types-ethereumjs-util/index.d.ts"
]
"include": ["./src/**/*", "./test/**/*"]
}

View File

@ -39,8 +39,6 @@
"shx": "^0.2.2",
"source-map-loader": "^0.1.6",
"tslint": "5.8.0",
"types-bn": "^0.0.1",
"types-ethereumjs-util": "0xProject/types-ethereumjs-util",
"typescript": "2.7.1",
"webpack": "^3.1.0",
"webpack-node-externals": "^1.6.0"

View File

@ -9,31 +9,3 @@ declare module '*.json' {
export default json;
/* tslint:enable */
}
// Ethereumjs-tx declarations
declare module 'ethereumjs-tx' {
class EthereumTx {
public raw: Buffer[];
public r: Buffer;
public s: Buffer;
public v: Buffer;
public serialize(): Buffer;
public sign(buffer: Buffer): void;
constructor(txParams: any);
}
export = EthereumTx;
}
/* tslint:disable */
declare module 'web3-provider-engine' {
class Web3ProviderEngine {
public on(event: string, handler: () => void): void;
public send(payload: any): void;
public sendAsync(payload: any, callback: (error: any, response: any) => void): void;
public addProvider(provider: any): void;
public start(): void;
public stop(): void;
}
export = Web3ProviderEngine;
}
/* tslint:enable */

View File

@ -4,9 +4,5 @@
"outDir": "lib",
"strictPropertyInitialization": false
},
"include": [
"./src/ts/**/*",
"../../node_modules/types-bn/index.d.ts",
"../../node_modules/types-ethereumjs-util/index.d.ts"
]
"include": ["./src/ts/**/*"]
}

View File

@ -9,6 +9,10 @@ CHANGELOG
* Dependencies updated
## v0.5.0 - _TBD, 2018_
* Make `DataItem.components` optional (#485)
## v0.4.0 - _March 18, 2018_
* Remove `JSONRPCPayload` (#426)

View File

@ -45,7 +45,7 @@ export interface EventAbi {
export interface DataItem {
name: string;
type: string;
components: DataItem[];
components?: DataItem[];
}
export type OpCode = string;

View File

@ -4,5 +4,5 @@
"typeRoots": ["node_modules/@types"],
"outDir": "lib"
},
"include": ["./src/**/*"]
"include": ["src/**/*"]
}

View File

@ -0,0 +1,57 @@
declare module 'bn.js' {
import { Buffer } from 'buffer';
type Endianness = 'le' | 'be';
class BN {
constructor(num: number | string | number[] | Buffer, base?: number, endian?: Endianness);
public clone(): BN;
public toString(base?: number, length?: number): string;
public toNumber(): number;
public toJSON(): string;
public toArray(endian?: Endianness, length?: number): number[];
public toBuffer(endian?: Endianness, length?: number): Buffer;
public bitLength(): number;
public zeroBits(): number;
public byteLength(): number;
public isNeg(): boolean;
public isEven(): boolean;
public isOdd(): boolean;
public isZero(): boolean;
public cmp(b: any): number;
public lt(b: any): boolean;
public lte(b: any): boolean;
public gt(b: any): boolean;
public gte(b: any): boolean;
public eq(b: any): boolean;
public isBN(b: any): boolean;
public neg(): BN;
public abs(): BN;
public add(b: BN): BN;
public sub(b: BN): BN;
public mul(b: BN): BN;
public sqr(): BN;
public pow(b: BN): BN;
public div(b: BN): BN;
public mod(b: BN): BN;
public divRound(b: BN): BN;
public or(b: BN): BN;
public and(b: BN): BN;
public xor(b: BN): BN;
public setn(b: number): BN;
public shln(b: number): BN;
public shrn(b: number): BN;
public testn(b: number): boolean;
public maskn(b: number): BN;
public bincn(b: number): BN;
public notn(w: number): BN;
public gcd(b: BN): BN;
public egcd(b: BN): { a: BN; b: BN; gcd: BN };
public invm(b: BN): BN;
}
export = BN;
}

View File

@ -0,0 +1 @@
declare module 'chai-bignumber';

View File

@ -114,6 +114,9 @@ declare namespace Chai {
extensible: Assertion;
sealed: Assertion;
frozen: Assertion;
bignumber: Assertion;
// HACK: In order to comply with chai-as-promised we make eventually a `PromisedAssertion` not an `Assertion`
eventually: PromisedAssertion;
oneOf(list: any[], message?: string): Assertion;
}
@ -148,7 +151,7 @@ declare namespace Chai {
}
interface NumberComparer {
(value: number, message?: string): Assertion;
(value: number | object, message?: string): Assertion;
}
interface TypeComparison {

View File

@ -0,0 +1 @@
declare module 'dirty-chai';

View File

@ -0,0 +1,5 @@
declare module 'ethereumjs-abi' {
const soliditySHA3: (argTypes: string[], args: any[]) => Buffer;
const soliditySHA256: (argTypes: string[], args: any[]) => Buffer;
const methodID: (name: string, types: string[]) => Buffer;
}

View File

@ -0,0 +1,14 @@
declare module 'ethereumjs-tx' {
class EthereumTx {
public raw: Buffer[];
public r: Buffer;
public s: Buffer;
public v: Buffer;
public nonce: Buffer;
public serialize(): Buffer;
public sign(buffer: Buffer): void;
public getSenderAddress(): Buffer;
constructor(txParams: any);
}
export = EthereumTx;
}

View File

@ -0,0 +1,101 @@
declare module 'ethereumjs-util' {
import { Buffer } from 'buffer';
import BN = require('bn.js');
interface Signature {
v: number;
r: Buffer;
s: Buffer;
}
export const MAX_INTEGER: BN;
export const TWO_POW256: BN;
export const SHA3_NULL_S: string;
export const SHA3_NULL: Buffer;
export const SHA3_RLP_ARRAY_S: string;
export const SHA3_RLP_ARRAY: Buffer;
export const SHA3_RLP_S: string;
export const SHA3_RLP: Buffer;
export function zeros(bytes: number): Buffer;
export function setLength(msg: Buffer, length: number, right: boolean): Buffer;
export function setLength(msg: number[], length: number, right: boolean): number[];
export function setLengthLeft(msg: Buffer, length: number, right?: boolean): Buffer;
export function setLengthLeft(msg: number[], length: number, right?: boolean): number[];
export function setLengthRight(msg: Buffer, length: number): Buffer;
export function setLengthRight(msg: number[], length: number): number[];
export function unpad(a: Buffer): Buffer;
export function unpad(a: number[]): number[];
export function unpad(a: string): string;
export function toBuffer(v: any): Buffer;
export function bufferToInt(buf: Buffer): number;
export function bufferToHex(buf: Buffer): string;
export function fromSigned(num: Buffer): BN;
export function toUnsigned(num: BN): Buffer;
export function sha3(a: Buffer | string | number | number[], bits?: number): Buffer;
export function sha256(a: Buffer | string | number | number[]): Buffer;
export function ripemd160(a: Buffer | string | number | number[], padded?: boolean): Buffer;
export function rlphash(a: Buffer | string | number | number[]): Buffer;
export function isValidPrivate(privateKey: Buffer): boolean;
export function isValidPublic(publicKey: Buffer, sanitize?: boolean): boolean;
export function pubToAddress(publicKey: Buffer, sanitize?: boolean): Buffer;
export function publicToAddress(publicKey: Buffer, sanitize?: boolean): Buffer;
export function privateToPublic(privateKey: Buffer): Buffer;
export function importPublic(publicKey: Buffer): Buffer;
export function ecsign(message: Buffer, privateKey: Buffer): Signature;
export function hashPersonalMessage(message: Buffer | string): Buffer;
export function ecrecover(msgHash: Buffer, v: number, r: Buffer, s: Buffer): Buffer;
export function toRpcSig(v: number, r: Buffer, s: Buffer): string;
export function fromRpcSig(sig: string): Signature;
export function privateToAddress(privateKey: Buffer): Buffer;
export function isValidAddress(address: string): boolean;
export function toChecksumAddress(address: string): string;
export function isValidChecksumAddress(address: string): boolean;
export function generateAddress(from: Buffer | string, nonce: number | string | number[] | Buffer): Buffer;
export function isPrecompiled(address: Buffer | string): boolean;
export function addHexPrefix(str: string): string;
export function stripHexPrefix(str: string): string;
export function isValidSignature(v: number, r: Buffer | string, s: Buffer | string, homestead?: boolean): boolean;
export function baToJSON(ba: Buffer): string;
export function baToJSON(ba: any[]): string[];
}

View File

@ -0,0 +1,38 @@
declare module 'solc' {
export interface ContractCompilationResult {
srcmap: string;
srcmapRuntime: string;
bytecode: string;
runtimeBytecode: string;
interface: string;
}
export interface CompilationResult {
errors: string[];
contracts: {
[contractIdentifier: string]: ContractCompilationResult;
};
sources: {
[sourceName: string]: {
AST: any;
};
};
sourceList: string[];
}
export interface ImportContents {
contents: string;
}
export interface InputSources {
sources: {
[fileName: string]: string;
};
}
export interface SolcInstance {
compile(
sources: InputSources,
optimizerEnabled: number,
findImports: (importPath: string) => ImportContents,
): CompilationResult;
}
export function loadRemoteVersion(versionName: string, cb: (err: Error | null, res?: SolcInstance) => void): void;
export function setupMethods(solcBin: any): SolcInstance;
}

View File

@ -0,0 +1,12 @@
declare module 'truffle-hdwallet-provider' {
import { JSONRPCRequestPayload, JSONRPCResponsePayload } from '@0xproject/types';
import * as Web3 from 'web3';
class HDWalletProvider implements Web3.Provider {
constructor(mnemonic: string, rpcUrl: string);
public sendAsync(
payload: JSONRPCRequestPayload,
callback: (err: Error, result: JSONRPCResponsePayload) => void,
): void;
}
export = HDWalletProvider;
}

View File

@ -0,0 +1,3 @@
declare module 'web3-eth-abi' {
export function encodeParameters(typesArray: string[], parameters: any[]): string;
}

View File

@ -0,0 +1,11 @@
declare module 'web3-provider-engine' {
class Web3ProviderEngine {
public on(event: string, handler: () => void): void;
public send(payload: any): void;
public sendAsync(payload: any, callback: (error: any, response: any) => void): void;
public addProvider(provider: any): void;
public start(): void;
public stop(): void;
}
export = Web3ProviderEngine;
}

View File

@ -9,6 +9,10 @@ CHANGELOG
* Dependencies updated
## v0.5.0 - _TBD, 2018_
* Make `AbiDecoder.addABI` public (#485)
## v0.4.3 - _March 18, 2018_
* Add `@types/node` to dependencies since `intervalUtils` has the `NodeJS` type as part of its public interface.

View File

@ -27,7 +27,7 @@ export class AbiDecoder {
return `0x${formatted}`;
}
constructor(abiArrays: AbiDefinition[][]) {
_.forEach(abiArrays, this._addABI.bind(this));
_.forEach(abiArrays, this.addABI.bind(this));
}
// This method can only decode logs from the 0x & ERC20 smart contracts
public tryToDecodeLogOrNoop<ArgsType>(log: LogEntry): LogWithDecodedArgs<ArgsType> | RawLog {
@ -73,7 +73,7 @@ export class AbiDecoder {
};
}
}
private _addABI(abiArray: AbiDefinition[]): void {
public addABI(abiArray: AbiDefinition[]): void {
if (_.isUndefined(abiArray)) {
return;
}

View File

@ -8,6 +8,9 @@ CHANGELOG
## v0.4.0 - _April 2, 2018_
* Rename `signTransactionAsync` to `signMessageAsync` for clarity (#465)
* Add `web3Wrapper.awaitTransactionMinedAsync` (#485)
* Add a public field `abiDecoder: AbiDecoder` which allows you to add your ABIs that are later used to decode logs (#485)
* Export enum `Web3WrapperErrors` with a single value so far: `TransactionMiningTimeout` (#485)
## v0.3.0 - _March 18, 2018_

View File

@ -1,326 +1,2 @@
import {
BlockParam,
BlockWithoutTransactionData,
CallData,
ContractAbi,
FilterObject,
JSONRPCRequestPayload,
JSONRPCResponsePayload,
LogEntry,
RawLogEntry,
TransactionReceipt,
TxData,
} from '@0xproject/types';
import { BigNumber, promisify } from '@0xproject/utils';
import * as _ from 'lodash';
import * as Web3 from 'web3';
/**
* A wrapper around the Web3.js 0.x library that provides a consistent, clean promise-based interface.
*/
export class Web3Wrapper {
/**
* Flag to check if this instance is of type Web3Wrapper
*/
public isZeroExWeb3Wrapper = true;
private _web3: Web3;
private _defaults: Partial<TxData>;
private _jsonRpcRequestId: number;
/**
* Instantiates a new Web3Wrapper.
* @param provider The Web3 provider instance you would like the Web3Wrapper to use for interacting with
* the backing Ethereum node.
* @param defaults Override TxData defaults sent with RPC requests to the backing Ethereum node.
* @return An instance of the Web3Wrapper class.
*/
constructor(provider: Web3.Provider, defaults?: Partial<TxData>) {
if (_.isUndefined((provider as any).sendAsync)) {
// Web3@1.0 provider doesn't support synchronous http requests,
// so it only has an async `send` method, instead of a `send` and `sendAsync` in web3@0.x.x`
// We re-assign the send method so that Web3@1.0 providers work with @0xproject/web3-wrapper
(provider as any).sendAsync = (provider as any).send;
}
this._web3 = new Web3();
this._web3.setProvider(provider);
this._defaults = defaults || {};
this._jsonRpcRequestId = 0;
}
/**
* Get the contract defaults set to the Web3Wrapper instance
* @return TxData defaults (e.g gas, gasPrice, nonce, etc...)
*/
public getContractDefaults(): Partial<TxData> {
return this._defaults;
}
/**
* Retrieve the Web3 provider
* @return Web3 provider instance
*/
public getProvider(): Web3.Provider {
return this._web3.currentProvider;
}
/**
* Update the used Web3 provider
* @param provider The new Web3 provider to be set
*/
public setProvider(provider: Web3.Provider) {
this._web3.setProvider(provider);
}
/**
* Check if an address is a valid Ethereum address
* @param address Address to check
* @returns Whether the address is a valid Ethereum address
*/
public isAddress(address: string): boolean {
return this._web3.isAddress(address);
}
/**
* Check whether an address is available through the backing provider. This can be
* useful if you want to know whether a user can sign messages or transactions from
* a given Ethereum address.
* @param senderAddress Address to check availability for
* @returns Whether the address is available through the provider.
*/
public async isSenderAddressAvailableAsync(senderAddress: string): Promise<boolean> {
const addresses = await this.getAvailableAddressesAsync();
const normalizedAddress = senderAddress.toLowerCase();
return _.includes(addresses, normalizedAddress);
}
/**
* Fetch the backing Ethereum node's version string (e.g `MetaMask/v4.2.0`)
* @returns Ethereum node's version string
*/
public async getNodeVersionAsync(): Promise<string> {
const nodeVersion = await promisify<string>(this._web3.version.getNode)();
return nodeVersion;
}
/**
* Fetches the networkId of the backing Ethereum node
* @returns The network id
*/
public async getNetworkIdAsync(): Promise<number> {
const networkIdStr = await promisify<string>(this._web3.version.getNetwork)();
const networkId = _.parseInt(networkIdStr);
return networkId;
}
/**
* Retrieves the transaction receipt for a given transaction hash
* @param txHash Transaction hash
* @returns The transaction receipt, including it's status (0: failed, 1: succeeded or undefined: not found)
*/
public async getTransactionReceiptAsync(txHash: string): Promise<TransactionReceipt> {
const transactionReceipt = await promisify<TransactionReceipt>(this._web3.eth.getTransactionReceipt)(txHash);
if (!_.isNull(transactionReceipt)) {
transactionReceipt.status = this._normalizeTxReceiptStatus(transactionReceipt.status);
}
return transactionReceipt;
}
/**
* Convert an Ether amount from ETH to Wei
* @param ethAmount Amount of Ether to convert to wei
* @returns Amount in wei
*/
public toWei(ethAmount: BigNumber): BigNumber {
const balanceWei = this._web3.toWei(ethAmount, 'ether');
return balanceWei;
}
/**
* Retrieves an accounts Ether balance in wei
* @param owner Account whose balance you wish to check
* @returns Balance in wei
*/
public async getBalanceInWeiAsync(owner: string): Promise<BigNumber> {
let balanceInWei = await promisify<BigNumber>(this._web3.eth.getBalance)(owner);
// Rewrap in a new BigNumber
balanceInWei = new BigNumber(balanceInWei);
return balanceInWei;
}
/**
* Check if a contract exists at a given address
* @param address Address to which to check
* @returns Whether or not contract code was found at the supplied address
*/
public async doesContractExistAtAddressAsync(address: string): Promise<boolean> {
const code = await promisify<string>(this._web3.eth.getCode)(address);
// Regex matches 0x0, 0x00, 0x in order to accommodate poorly implemented clients
const codeIsEmpty = /^0x0{0,40}$/i.test(code);
return !codeIsEmpty;
}
/**
* Sign a message with a specific address's private key (`eth_sign`)
* @param address Address of signer
* @param message Message to sign
* @returns Signature string (might be VRS or RSV depending on the Signer)
*/
public async signMessageAsync(address: string, message: string): Promise<string> {
const signData = await promisify<string>(this._web3.eth.sign)(address, message);
return signData;
}
/**
* Fetches the latest block number
* @returns Block number
*/
public async getBlockNumberAsync(): Promise<number> {
const blockNumber = await promisify<number>(this._web3.eth.getBlockNumber)();
return blockNumber;
}
/**
* Fetch a specific Ethereum block
* @param blockParam The block you wish to fetch (blockHash, blockNumber or blockLiteral)
* @returns The requested block without transaction data
*/
public async getBlockAsync(blockParam: string | BlockParam): Promise<BlockWithoutTransactionData> {
const block = await promisify<BlockWithoutTransactionData>(this._web3.eth.getBlock)(blockParam);
return block;
}
/**
* Fetch a block's timestamp
* @param blockParam The block you wish to fetch (blockHash, blockNumber or blockLiteral)
* @returns The block's timestamp
*/
public async getBlockTimestampAsync(blockParam: string | BlockParam): Promise<number> {
const { timestamp } = await this.getBlockAsync(blockParam);
return timestamp;
}
/**
* Retrieve the user addresses available through the backing provider
* @returns Available user addresses
*/
public async getAvailableAddressesAsync(): Promise<string[]> {
const addresses = await promisify<string[]>(this._web3.eth.getAccounts)();
const normalizedAddresses = _.map(addresses, address => address.toLowerCase());
return normalizedAddresses;
}
/**
* Take a snapshot of the blockchain state on a TestRPC/Ganache local node
* @returns The snapshot id. This can be used to revert to this snapshot
*/
public async takeSnapshotAsync(): Promise<number> {
const snapshotId = Number(await this._sendRawPayloadAsync<string>({ method: 'evm_snapshot', params: [] }));
return snapshotId;
}
/**
* Revert the blockchain state to a previous snapshot state on TestRPC/Ganache local node
* @param snapshotId snapshot id to revert to
* @returns Whether the revert was successful
*/
public async revertSnapshotAsync(snapshotId: number): Promise<boolean> {
const didRevert = await this._sendRawPayloadAsync<boolean>({ method: 'evm_revert', params: [snapshotId] });
return didRevert;
}
/**
* Mine a block on a TestRPC/Ganache local node
*/
public async mineBlockAsync(): Promise<void> {
await this._sendRawPayloadAsync<string>({ method: 'evm_mine', params: [] });
}
/**
* Increase the next blocks timestamp on TestRPC/Ganache local node
* @param timeDelta Amount of time to add in seconds
*/
public async increaseTimeAsync(timeDelta: number): Promise<void> {
await this._sendRawPayloadAsync<string>({ method: 'evm_increaseTime', params: [timeDelta] });
}
/**
* Retrieve smart contract logs for a given filter
* @param filter Parameters by which to filter which logs to retrieve
* @returns The corresponding log entries
*/
public async getLogsAsync(filter: FilterObject): Promise<LogEntry[]> {
let fromBlock = filter.fromBlock;
if (_.isNumber(fromBlock)) {
fromBlock = this._web3.toHex(fromBlock);
}
let toBlock = filter.toBlock;
if (_.isNumber(toBlock)) {
toBlock = this._web3.toHex(toBlock);
}
const serializedFilter = {
...filter,
fromBlock,
toBlock,
};
const payload = {
jsonrpc: '2.0',
id: this._jsonRpcRequestId++,
method: 'eth_getLogs',
params: [serializedFilter],
};
const rawLogs = await this._sendRawPayloadAsync<RawLogEntry[]>(payload);
const formattedLogs = _.map(rawLogs, this._formatLog.bind(this));
return formattedLogs;
}
/**
* Get a Web3 contract factory instance for a given ABI
* @param abi Smart contract ABI
* @returns Web3 contract factory which can create Web3 Contract instances from the supplied ABI
*/
public getContractFromAbi(abi: ContractAbi): Web3.Contract<any> {
const web3Contract = this._web3.eth.contract(abi);
return web3Contract;
}
/**
* Calculate the estimated gas cost for a given transaction
* @param txData Transaction data
* @returns Estimated gas cost
*/
public async estimateGasAsync(txData: Partial<TxData>): Promise<number> {
const gas = await promisify<number>(this._web3.eth.estimateGas)(txData);
return gas;
}
/**
* Call a smart contract method at a given block height
* @param callData Call data
* @param defaultBlock Block height at which to make the call. Defaults to `latest`
* @returns The raw call result
*/
public async callAsync(callData: CallData, defaultBlock?: BlockParam): Promise<string> {
const rawCallResult = await promisify<string>(this._web3.eth.call)(callData, defaultBlock);
return rawCallResult;
}
/**
* Send a transaction
* @param txData Transaction data
* @returns Transaction hash
*/
public async sendTransactionAsync(txData: TxData): Promise<string> {
const txHash = await promisify<string>(this._web3.eth.sendTransaction)(txData);
return txHash;
}
private async _sendRawPayloadAsync<A>(payload: Partial<JSONRPCRequestPayload>): Promise<A> {
const sendAsync = this._web3.currentProvider.sendAsync.bind(this._web3.currentProvider);
const response = await promisify<JSONRPCResponsePayload>(sendAsync)(payload);
const result = response.result;
return result;
}
private _normalizeTxReceiptStatus(status: undefined | null | string | 0 | 1): null | 0 | 1 {
// Transaction status might have four values
// undefined - Testrpc and other old clients
// null - New clients on old transactions
// number - Parity
// hex - Geth
if (_.isString(status)) {
return this._web3.toDecimal(status) as 0 | 1;
} else if (_.isUndefined(status)) {
return null;
} else {
return status;
}
}
private _formatLog(rawLog: RawLogEntry): LogEntry {
const formattedLog = {
...rawLog,
logIndex: this._hexToDecimal(rawLog.logIndex),
blockNumber: this._hexToDecimal(rawLog.blockNumber),
transactionIndex: this._hexToDecimal(rawLog.transactionIndex),
};
return formattedLog;
}
private _hexToDecimal(hex: string | null): number | null {
if (_.isNull(hex)) {
return null;
}
const decimal = this._web3.toDecimal(hex);
return decimal;
}
}
export { Web3Wrapper } from './web3_wrapper';
export { Web3WrapperErrors } from './types';

View File

@ -0,0 +1,3 @@
export enum Web3WrapperErrors {
TransactionMiningTimeout = 'TRANSACTION_MINING_TIMEOUT',
}

View File

@ -0,0 +1,375 @@
import {
BlockParam,
BlockWithoutTransactionData,
CallData,
ContractAbi,
FilterObject,
JSONRPCRequestPayload,
JSONRPCResponsePayload,
LogEntry,
RawLogEntry,
TransactionReceipt,
TransactionReceiptWithDecodedLogs,
TxData,
} from '@0xproject/types';
import { AbiDecoder, BigNumber, intervalUtils, promisify } from '@0xproject/utils';
import * as _ from 'lodash';
import * as Web3 from 'web3';
import { Web3WrapperErrors } from './types';
/**
* A wrapper around the Web3.js 0.x library that provides a consistent, clean promise-based interface.
*/
export class Web3Wrapper {
/**
* Flag to check if this instance is of type Web3Wrapper
*/
public isZeroExWeb3Wrapper = true;
public abiDecoder: AbiDecoder;
private _web3: Web3;
private _defaults: Partial<TxData>;
private _jsonRpcRequestId: number;
/**
* Instantiates a new Web3Wrapper.
* @param provider The Web3 provider instance you would like the Web3Wrapper to use for interacting with
* the backing Ethereum node.
* @param defaults Override TxData defaults sent with RPC requests to the backing Ethereum node.
* @return An instance of the Web3Wrapper class.
*/
constructor(provider: Web3.Provider, defaults?: Partial<TxData>) {
if (_.isUndefined((provider as any).sendAsync)) {
// Web3@1.0 provider doesn't support synchronous http requests,
// so it only has an async `send` method, instead of a `send` and `sendAsync` in web3@0.x.x`
// We re-assign the send method so that Web3@1.0 providers work with @0xproject/web3-wrapper
(provider as any).sendAsync = (provider as any).send;
}
this.abiDecoder = new AbiDecoder([]);
this._web3 = new Web3();
this._web3.setProvider(provider);
this._defaults = defaults || {};
this._jsonRpcRequestId = 0;
}
/**
* Get the contract defaults set to the Web3Wrapper instance
* @return TxData defaults (e.g gas, gasPrice, nonce, etc...)
*/
public getContractDefaults(): Partial<TxData> {
return this._defaults;
}
/**
* Retrieve the Web3 provider
* @return Web3 provider instance
*/
public getProvider(): Web3.Provider {
return this._web3.currentProvider;
}
/**
* Update the used Web3 provider
* @param provider The new Web3 provider to be set
*/
public setProvider(provider: Web3.Provider) {
this._web3.setProvider(provider);
}
/**
* Check if an address is a valid Ethereum address
* @param address Address to check
* @returns Whether the address is a valid Ethereum address
*/
public isAddress(address: string): boolean {
return this._web3.isAddress(address);
}
/**
* Check whether an address is available through the backing provider. This can be
* useful if you want to know whether a user can sign messages or transactions from
* a given Ethereum address.
* @param senderAddress Address to check availability for
* @returns Whether the address is available through the provider.
*/
public async isSenderAddressAvailableAsync(senderAddress: string): Promise<boolean> {
const addresses = await this.getAvailableAddressesAsync();
const normalizedAddress = senderAddress.toLowerCase();
return _.includes(addresses, normalizedAddress);
}
/**
* Fetch the backing Ethereum node's version string (e.g `MetaMask/v4.2.0`)
* @returns Ethereum node's version string
*/
public async getNodeVersionAsync(): Promise<string> {
const nodeVersion = await promisify<string>(this._web3.version.getNode)();
return nodeVersion;
}
/**
* Fetches the networkId of the backing Ethereum node
* @returns The network id
*/
public async getNetworkIdAsync(): Promise<number> {
const networkIdStr = await promisify<string>(this._web3.version.getNetwork)();
const networkId = _.parseInt(networkIdStr);
return networkId;
}
/**
* Retrieves the transaction receipt for a given transaction hash
* @param txHash Transaction hash
* @returns The transaction receipt, including it's status (0: failed, 1: succeeded or undefined: not found)
*/
public async getTransactionReceiptAsync(txHash: string): Promise<TransactionReceipt> {
const transactionReceipt = await promisify<TransactionReceipt>(this._web3.eth.getTransactionReceipt)(txHash);
if (!_.isNull(transactionReceipt)) {
transactionReceipt.status = this._normalizeTxReceiptStatus(transactionReceipt.status);
}
return transactionReceipt;
}
/**
* Convert an Ether amount from ETH to Wei
* @param ethAmount Amount of Ether to convert to wei
* @returns Amount in wei
*/
public toWei(ethAmount: BigNumber): BigNumber {
const balanceWei = this._web3.toWei(ethAmount, 'ether');
return balanceWei;
}
/**
* Retrieves an accounts Ether balance in wei
* @param owner Account whose balance you wish to check
* @returns Balance in wei
*/
public async getBalanceInWeiAsync(owner: string): Promise<BigNumber> {
let balanceInWei = await promisify<BigNumber>(this._web3.eth.getBalance)(owner);
// Rewrap in a new BigNumber
balanceInWei = new BigNumber(balanceInWei);
return balanceInWei;
}
/**
* Check if a contract exists at a given address
* @param address Address to which to check
* @returns Whether or not contract code was found at the supplied address
*/
public async doesContractExistAtAddressAsync(address: string): Promise<boolean> {
const code = await promisify<string>(this._web3.eth.getCode)(address);
// Regex matches 0x0, 0x00, 0x in order to accommodate poorly implemented clients
const codeIsEmpty = /^0x0{0,40}$/i.test(code);
return !codeIsEmpty;
}
/**
* Sign a message with a specific address's private key (`eth_sign`)
* @param address Address of signer
* @param message Message to sign
* @returns Signature string (might be VRS or RSV depending on the Signer)
*/
public async signMessageAsync(address: string, message: string): Promise<string> {
const signData = await promisify<string>(this._web3.eth.sign)(address, message);
return signData;
}
/**
* Fetches the latest block number
* @returns Block number
*/
public async getBlockNumberAsync(): Promise<number> {
const blockNumber = await promisify<number>(this._web3.eth.getBlockNumber)();
return blockNumber;
}
/**
* Fetch a specific Ethereum block
* @param blockParam The block you wish to fetch (blockHash, blockNumber or blockLiteral)
* @returns The requested block without transaction data
*/
public async getBlockAsync(blockParam: string | BlockParam): Promise<BlockWithoutTransactionData> {
const block = await promisify<BlockWithoutTransactionData>(this._web3.eth.getBlock)(blockParam);
return block;
}
/**
* Fetch a block's timestamp
* @param blockParam The block you wish to fetch (blockHash, blockNumber or blockLiteral)
* @returns The block's timestamp
*/
public async getBlockTimestampAsync(blockParam: string | BlockParam): Promise<number> {
const { timestamp } = await this.getBlockAsync(blockParam);
return timestamp;
}
/**
* Retrieve the user addresses available through the backing provider
* @returns Available user addresses
*/
public async getAvailableAddressesAsync(): Promise<string[]> {
const addresses = await promisify<string[]>(this._web3.eth.getAccounts)();
const normalizedAddresses = _.map(addresses, address => address.toLowerCase());
return normalizedAddresses;
}
/**
* Take a snapshot of the blockchain state on a TestRPC/Ganache local node
* @returns The snapshot id. This can be used to revert to this snapshot
*/
public async takeSnapshotAsync(): Promise<number> {
const snapshotId = Number(await this._sendRawPayloadAsync<string>({ method: 'evm_snapshot', params: [] }));
return snapshotId;
}
/**
* Revert the blockchain state to a previous snapshot state on TestRPC/Ganache local node
* @param snapshotId snapshot id to revert to
* @returns Whether the revert was successful
*/
public async revertSnapshotAsync(snapshotId: number): Promise<boolean> {
const didRevert = await this._sendRawPayloadAsync<boolean>({ method: 'evm_revert', params: [snapshotId] });
return didRevert;
}
/**
* Mine a block on a TestRPC/Ganache local node
*/
public async mineBlockAsync(): Promise<void> {
await this._sendRawPayloadAsync<string>({ method: 'evm_mine', params: [] });
}
/**
* Increase the next blocks timestamp on TestRPC/Ganache local node
* @param timeDelta Amount of time to add in seconds
*/
public async increaseTimeAsync(timeDelta: number): Promise<void> {
await this._sendRawPayloadAsync<string>({ method: 'evm_increaseTime', params: [timeDelta] });
}
/**
* Retrieve smart contract logs for a given filter
* @param filter Parameters by which to filter which logs to retrieve
* @returns The corresponding log entries
*/
public async getLogsAsync(filter: FilterObject): Promise<LogEntry[]> {
let fromBlock = filter.fromBlock;
if (_.isNumber(fromBlock)) {
fromBlock = this._web3.toHex(fromBlock);
}
let toBlock = filter.toBlock;
if (_.isNumber(toBlock)) {
toBlock = this._web3.toHex(toBlock);
}
const serializedFilter = {
...filter,
fromBlock,
toBlock,
};
const payload = {
jsonrpc: '2.0',
id: this._jsonRpcRequestId++,
method: 'eth_getLogs',
params: [serializedFilter],
};
const rawLogs = await this._sendRawPayloadAsync<RawLogEntry[]>(payload);
const formattedLogs = _.map(rawLogs, this._formatLog.bind(this));
return formattedLogs;
}
/**
* Get a Web3 contract factory instance for a given ABI
* @param abi Smart contract ABI
* @returns Web3 contract factory which can create Web3 Contract instances from the supplied ABI
*/
public getContractFromAbi(abi: ContractAbi): Web3.Contract<any> {
const web3Contract = this._web3.eth.contract(abi);
return web3Contract;
}
/**
* Calculate the estimated gas cost for a given transaction
* @param txData Transaction data
* @returns Estimated gas cost
*/
public async estimateGasAsync(txData: Partial<TxData>): Promise<number> {
const gas = await promisify<number>(this._web3.eth.estimateGas)(txData);
return gas;
}
/**
* Call a smart contract method at a given block height
* @param callData Call data
* @param defaultBlock Block height at which to make the call. Defaults to `latest`
* @returns The raw call result
*/
public async callAsync(callData: CallData, defaultBlock?: BlockParam): Promise<string> {
const rawCallResult = await promisify<string>(this._web3.eth.call)(callData, defaultBlock);
return rawCallResult;
}
/**
* Send a transaction
* @param txData Transaction data
* @returns Transaction hash
*/
public async sendTransactionAsync(txData: TxData): Promise<string> {
const txHash = await promisify<string>(this._web3.eth.sendTransaction)(txData);
return txHash;
}
public async awaitTransactionMinedAsync(
txHash: string,
pollingIntervalMs = 1000,
timeoutMs?: number,
): Promise<TransactionReceiptWithDecodedLogs> {
let timeoutExceeded = false;
if (timeoutMs) {
setTimeout(() => (timeoutExceeded = true), timeoutMs);
}
const txReceiptPromise = new Promise(
(resolve: (receipt: TransactionReceiptWithDecodedLogs) => void, reject) => {
const intervalId = intervalUtils.setAsyncExcludingInterval(
async () => {
if (timeoutExceeded) {
intervalUtils.clearAsyncExcludingInterval(intervalId);
return reject(Web3WrapperErrors.TransactionMiningTimeout);
}
const transactionReceipt = await this.getTransactionReceiptAsync(txHash);
if (!_.isNull(transactionReceipt)) {
intervalUtils.clearAsyncExcludingInterval(intervalId);
const logsWithDecodedArgs = _.map(
transactionReceipt.logs,
this.abiDecoder.tryToDecodeLogOrNoop.bind(this.abiDecoder),
);
const transactionReceiptWithDecodedLogArgs: TransactionReceiptWithDecodedLogs = {
...transactionReceipt,
logs: logsWithDecodedArgs,
};
resolve(transactionReceiptWithDecodedLogArgs);
}
},
pollingIntervalMs,
(err: Error) => {
intervalUtils.clearAsyncExcludingInterval(intervalId);
reject(err);
},
);
},
);
const txReceipt = await txReceiptPromise;
return txReceipt;
}
private async _sendRawPayloadAsync<A>(payload: Partial<JSONRPCRequestPayload>): Promise<A> {
const sendAsync = this._web3.currentProvider.sendAsync.bind(this._web3.currentProvider);
const response = await promisify<JSONRPCResponsePayload>(sendAsync)(payload);
const result = response.result;
return result;
}
private _normalizeTxReceiptStatus(status: undefined | null | string | 0 | 1): null | 0 | 1 {
// Transaction status might have four values
// undefined - Testrpc and other old clients
// null - New clients on old transactions
// number - Parity
// hex - Geth
if (_.isString(status)) {
return this._web3.toDecimal(status) as 0 | 1;
} else if (_.isUndefined(status)) {
return null;
} else {
return status;
}
}
private _formatLog(rawLog: RawLogEntry): LogEntry {
const formattedLog = {
...rawLog,
logIndex: this._hexToDecimal(rawLog.logIndex),
blockNumber: this._hexToDecimal(rawLog.blockNumber),
transactionIndex: this._hexToDecimal(rawLog.transactionIndex),
};
return formattedLog;
}
private _hexToDecimal(hex: string | null): number | null {
if (_.isNull(hex)) {
return null;
}
const decimal = this._web3.toDecimal(hex);
return decimal;
}
}

View File

@ -1,7 +1,6 @@
declare module 'react-tooltip';
declare module 'react-router-hash-link';
declare module 'truffle-contract';
declare module 'ethereumjs-util';
declare module 'keccak';
declare module 'whatwg-fetch';
declare module 'react-html5video';
@ -9,7 +8,6 @@ declare module 'web3-provider-engine/subproviders/filters';
declare module 'thenby';
declare module 'react-recaptcha';
declare module 'react-document-title';
declare module 'ethereumjs-tx';
declare module 'react-ga';
declare module '*.json' {
@ -126,17 +124,6 @@ declare module 'web3-provider-engine/subproviders/rpc' {
}
export = RpcSubprovider;
}
declare module 'web3-provider-engine' {
class Web3ProviderEngine {
public on(event: string, handler: () => void): void;
public send(payload: any): void;
public sendAsync(payload: any, callback: (error: any, response: any) => void): void;
public addProvider(provider: any): void;
public start(): void;
public stop(): void;
}
export = Web3ProviderEngine;
}
declare interface Artifact {
abi: any;

View File

@ -1781,7 +1781,7 @@ bn.js@4.11.7:
version "4.11.7"
resolved "https://registry.yarnpkg.com/bn.js/-/bn.js-4.11.7.tgz#ddb048e50d9482790094c13eb3fcfc833ce7ab46"
bn.js@^4.0.0, bn.js@^4.1.0, bn.js@^4.1.1, bn.js@^4.10.0, bn.js@^4.11.0, bn.js@^4.11.3, bn.js@^4.11.6, bn.js@^4.11.7, bn.js@^4.11.8, bn.js@^4.4.0, bn.js@^4.8.0:
bn.js@^4.0.0, bn.js@^4.1.0, bn.js@^4.1.1, bn.js@^4.10.0, bn.js@^4.11.0, bn.js@^4.11.3, bn.js@^4.11.6, bn.js@^4.11.8, bn.js@^4.4.0, bn.js@^4.8.0:
version "4.11.8"
resolved "https://registry.yarnpkg.com/bn.js/-/bn.js-4.11.8.tgz#2cde09eb5ee341f484746bb0309b3253b1b1442f"
@ -2018,7 +2018,7 @@ buffer@^4.3.0:
ieee754 "^1.1.4"
isarray "^1.0.0"
buffer@^5.0.5, buffer@^5.0.6:
buffer@^5.0.5:
version "5.1.0"
resolved "https://registry.yarnpkg.com/buffer/-/buffer-5.1.0.tgz#c913e43678c7cb7c8bd16afbcddb6c5505e8f9fe"
dependencies:
@ -10563,7 +10563,7 @@ solidity-coverage@^0.4.10:
solidity-parser-sc "0.4.6"
web3 "^0.18.4"
solidity-parser-antlr@^0.2.7:
solidity-parser-antlr@^0.2.8:
version "0.2.8"
resolved "https://registry.yarnpkg.com/solidity-parser-antlr/-/solidity-parser-antlr-0.2.8.tgz#8eb8547a88dfeaf6cf4c7811e3824084214244d4"
@ -11686,21 +11686,6 @@ types-bn@^0.0.1:
dependencies:
bn.js "4.11.7"
"types-bn@https://github.com/machinomy/types-bn.git":
version "0.0.1"
resolved "https://github.com/machinomy/types-bn.git#08ede69e138640d332b0dae0dc2e2fffee5f7160"
dependencies:
bn.js "4.11.7"
types-ethereumjs-util@0xProject/types-ethereumjs-util:
version "0.0.7"
resolved "https://codeload.github.com/0xProject/types-ethereumjs-util/tar.gz/72722fc605bfa7f87ec4a959956b387320479ffc"
dependencies:
bn.js "^4.11.7"
buffer "^5.0.6"
rlp "^2.0.0"
types-bn "https://github.com/machinomy/types-bn.git"
typescript@2.4.1:
version "2.4.1"
resolved "https://registry.yarnpkg.com/typescript/-/typescript-2.4.1.tgz#c3ccb16ddaa0b2314de031e7e6fee89e5ba346bc"