Split 0x.js into contract-wrappers, order-watcher but keep 0x.js as a unifying library with the same interface

This commit is contained in:
Fabio Berger 2018-05-09 20:36:28 +02:00
parent 69a6166b6a
commit 209266dbed
168 changed files with 19678 additions and 1357 deletions

4
.gitignore vendored
View File

@ -77,12 +77,16 @@ bin/
packages/sol-cov/test/fixtures/artifacts packages/sol-cov/test/fixtures/artifacts
packages/metacoin/artifacts packages/metacoin/artifacts
packages/0x.js/test/artifacts packages/0x.js/test/artifacts
packages/order-watcher/test/artifacts
packages/contract-wrappers/test/artifacts
packages/migrations/src/artifacts packages/migrations/src/artifacts
# generated contract wrappers # generated contract wrappers
packages/0x.js/src/contract_wrappers/generated/ packages/0x.js/src/contract_wrappers/generated/
packages/contracts/src/contract_wrappers/generated/ packages/contracts/src/contract_wrappers/generated/
packages/metacoin/src/contract_wrappers packages/metacoin/src/contract_wrappers
packages/fill-scenarios/src/generated_contract_wrappers/
packages/order-watcher/src/generated_contract_wrappers/
# solc-bin in deployer # solc-bin in deployer
packages/deployer/solc_bin/ packages/deployer/solc_bin/

View File

@ -1,4 +1,14 @@
[ [
{
"version": "0.38.0",
"changes": [
{
"note": "Renamed createOrderStateWatcher to createOrderWatcherAsync since it is not async",
"note":
"Renamed ZeroExError to ContractWrappersErrors since they not live in the @0xproject/contract-wrappers subpackage"
}
]
},
{ {
"timestamp": 1525477860, "timestamp": 1525477860,
"version": "0.37.2", "version": "0.37.2",

View File

@ -65,15 +65,11 @@
"@0xproject/dev-utils": "^0.4.1", "@0xproject/dev-utils": "^0.4.1",
"@0xproject/migrations": "^0.0.5", "@0xproject/migrations": "^0.0.5",
"@0xproject/monorepo-scripts": "^0.1.19", "@0xproject/monorepo-scripts": "^0.1.19",
"@0xproject/subproviders": "^0.10.1",
"@0xproject/tslint-config": "^0.4.17", "@0xproject/tslint-config": "^0.4.17",
"@types/bintrees": "^1.0.2",
"@types/lodash": "4.14.104", "@types/lodash": "4.14.104",
"@types/mocha": "^2.2.42", "@types/mocha": "^2.2.42",
"@types/node": "^8.0.53", "@types/node": "^8.0.53",
"@types/request": "2.47.0",
"@types/sinon": "^2.2.2", "@types/sinon": "^2.2.2",
"@types/uuid": "^3.4.2",
"awesome-typescript-loader": "^3.1.3", "awesome-typescript-loader": "^3.1.3",
"chai": "^4.0.1", "chai": "^4.0.1",
"chai-as-promised": "^7.1.0", "chai-as-promised": "^7.1.0",
@ -86,35 +82,26 @@
"nyc": "^11.0.1", "nyc": "^11.0.1",
"opn-cli": "^3.1.0", "opn-cli": "^3.1.0",
"prettier": "^1.11.1", "prettier": "^1.11.1",
"request": "^2.81.0",
"shx": "^0.2.2", "shx": "^0.2.2",
"sinon": "^4.0.0", "sinon": "^4.0.0",
"source-map-support": "^0.5.0", "source-map-support": "^0.5.0",
"tslint": "5.8.0", "tslint": "5.8.0",
"typedoc": "0xProject/typedoc", "typedoc": "0xProject/typedoc",
"typescript": "2.7.1", "typescript": "2.7.1",
"web3-provider-engine": "^14.0.4",
"webpack": "^3.1.0" "webpack": "^3.1.0"
}, },
"dependencies": { "dependencies": {
"@0xproject/assert": "^0.2.9", "@0xproject/assert": "^0.2.9",
"@0xproject/base-contract": "^0.3.1", "@0xproject/base-contract": "^0.3.1",
"@0xproject/json-schemas": "^0.7.23", "@0xproject/contract-wrappers": "^0.0.1",
"@0xproject/order-watcher": "^0.0.1",
"@0xproject/order-utils": "^0.0.4", "@0xproject/order-utils": "^0.0.4",
"@0xproject/types": "^0.6.3", "@0xproject/types": "^0.6.3",
"@0xproject/typescript-typings": "^0.3.1", "@0xproject/typescript-typings": "^0.3.1",
"@0xproject/utils": "^0.6.1", "@0xproject/utils": "^0.6.1",
"@0xproject/web3-wrapper": "^0.6.3", "@0xproject/web3-wrapper": "^0.6.3",
"bintrees": "^1.0.2",
"bn.js": "^4.11.8",
"ethereumjs-abi": "^0.6.4",
"ethereumjs-blockstream": "^2.0.6",
"ethereumjs-util": "^5.1.1",
"ethers": "^3.0.15", "ethers": "^3.0.15",
"js-sha3": "^0.7.0", "lodash": "^4.17.4"
"lodash": "^4.17.4",
"uuid": "^3.1.0",
"web3": "^0.20.0"
}, },
"publishConfig": { "publishConfig": {
"access": "public" "access": "public"

View File

@ -1,4 +1,13 @@
import { schemas, SchemaValidator } from '@0xproject/json-schemas'; import { assert } from '@0xproject/assert';
import {
ContractWrappers,
EtherTokenWrapper,
ExchangeWrapper,
TokenRegistryWrapper,
TokenTransferProxyWrapper,
TokenWrapper,
ZeroExContractConfig,
} from '@0xproject/contract-wrappers';
import { import {
generatePseudoRandomSalt, generatePseudoRandomSalt,
getOrderHashHex, getOrderHashHex,
@ -6,27 +15,13 @@ import {
isValidSignature, isValidSignature,
signOrderHashAsync, signOrderHashAsync,
} from '@0xproject/order-utils'; } from '@0xproject/order-utils';
import { OrderWatcher, OrderWatcherConfig } from '@0xproject/order-watcher';
import { ECSignature, Order, Provider, SignedOrder, TransactionReceiptWithDecodedLogs } from '@0xproject/types'; import { ECSignature, Order, Provider, SignedOrder, TransactionReceiptWithDecodedLogs } from '@0xproject/types';
import { AbiDecoder, BigNumber, intervalUtils } from '@0xproject/utils'; import { BigNumber } from '@0xproject/utils';
import { Web3Wrapper } from '@0xproject/web3-wrapper'; import { Web3Wrapper } from '@0xproject/web3-wrapper';
import * as ethUtil from 'ethereumjs-util';
import * as _ from 'lodash'; import * as _ from 'lodash';
import { artifacts } from './artifacts';
import { EtherTokenWrapper } from './contract_wrappers/ether_token_wrapper';
import { ExchangeWrapper } from './contract_wrappers/exchange_wrapper';
import { TokenRegistryWrapper } from './contract_wrappers/token_registry_wrapper';
import { TokenTransferProxyWrapper } from './contract_wrappers/token_transfer_proxy_wrapper';
import { TokenWrapper } from './contract_wrappers/token_wrapper';
import { OrderStateWatcher } from './order_watcher/order_state_watcher';
import { zeroExConfigSchema } from './schemas/zero_ex_config_schema';
import { zeroExPrivateNetworkConfigSchema } from './schemas/zero_ex_private_network_config_schema';
import { zeroExPublicNetworkConfigSchema } from './schemas/zero_ex_public_network_config_schema';
import { OrderStateWatcherConfig, ZeroExConfig, ZeroExError } from './types';
import { assert } from './utils/assert';
import { constants } from './utils/constants'; import { constants } from './utils/constants';
import { decorators } from './utils/decorators';
import { utils } from './utils/utils';
/** /**
* The ZeroEx class is the single entry-point into the 0x.js library. It contains all of the library's functionality * The ZeroEx class is the single entry-point into the 0x.js library. It contains all of the library's functionality
@ -62,7 +57,7 @@ export class ZeroEx {
* tokenTransferProxy smart contract. * tokenTransferProxy smart contract.
*/ */
public proxy: TokenTransferProxyWrapper; public proxy: TokenTransferProxyWrapper;
private _web3Wrapper: Web3Wrapper; private _contractWrappers: ContractWrappers;
/** /**
* Generates a pseudo-random 256-bit salt. * Generates a pseudo-random 256-bit salt.
* The salt can be included in a 0x order, ensuring that the order generates a unique orderHash * The salt can be included in a 0x order, ensuring that the order generates a unique orderHash
@ -136,40 +131,15 @@ export class ZeroEx {
* @param config The configuration object. Look up the type for the description. * @param config The configuration object. Look up the type for the description.
* @return An instance of the 0x.js ZeroEx class. * @return An instance of the 0x.js ZeroEx class.
*/ */
constructor(provider: Provider, config: ZeroExConfig) { constructor(provider: Provider, config: ZeroExContractConfig) {
assert.isWeb3Provider('provider', provider); assert.isWeb3Provider('provider', provider);
assert.doesConformToSchema('config', config, zeroExConfigSchema, [ this._contractWrappers = new ContractWrappers(provider, config);
zeroExPrivateNetworkConfigSchema,
zeroExPublicNetworkConfigSchema, this.proxy = this._contractWrappers.proxy;
]); this.token = this._contractWrappers.token;
const artifactJSONs = _.values(artifacts); this.exchange = this._contractWrappers.exchange;
const abiArrays = _.map(artifactJSONs, artifact => artifact.abi); this.tokenRegistry = this._contractWrappers.tokenRegistry;
const defaults = { this.etherToken = this._contractWrappers.etherToken;
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.proxy);
this.exchange = new ExchangeWrapper(
this._web3Wrapper,
config.networkId,
this.token,
config.exchangeContractAddress,
config.zrxContractAddress,
);
this.tokenRegistry = new TokenRegistryWrapper(
this._web3Wrapper,
config.networkId,
config.tokenRegistryContractAddress,
);
this.etherToken = new EtherTokenWrapper(this._web3Wrapper, config.networkId, this.token);
} }
/** /**
* Sets a new web3 provider for 0x.js. Updating the provider will stop all * Sets a new web3 provider for 0x.js. Updating the provider will stop all
@ -178,31 +148,23 @@ export class ZeroEx {
* @param networkId The id of the network your provider is connected to * @param networkId The id of the network your provider is connected to
*/ */
public setProvider(provider: Provider, networkId: number): void { public setProvider(provider: Provider, networkId: number): void {
this._web3Wrapper.setProvider(provider); this._contractWrappers.setProvider(provider, networkId);
(this.exchange as any)._invalidateContractInstances();
(this.exchange as any)._setNetworkId(networkId);
(this.tokenRegistry as any)._invalidateContractInstance();
(this.tokenRegistry as any)._setNetworkId(networkId);
(this.token as any)._invalidateContractInstances();
(this.token as any)._setNetworkId(networkId);
(this.proxy as any)._invalidateContractInstance();
(this.proxy as any)._setNetworkId(networkId);
(this.etherToken as any)._invalidateContractInstance();
(this.etherToken as any)._setNetworkId(networkId);
} }
/** /**
* Get the provider instance currently used by 0x.js * Get the provider instance currently used by 0x.js
* @return Web3 provider instance * @return Web3 provider instance
*/ */
public getProvider(): Provider { public getProvider(): Provider {
return this._web3Wrapper.getProvider(); return this._contractWrappers.getProvider();
} }
/** /**
* Get user Ethereum addresses available through the supplied web3 provider available for sending transactions. * Get user Ethereum addresses available through the supplied web3 provider available for sending transactions.
* @return An array of available user Ethereum addresses. * @return An array of available user Ethereum addresses.
*/ */
public async getAvailableAddressesAsync(): Promise<string[]> { public async getAvailableAddressesAsync(): Promise<string[]> {
const availableAddresses = await this._web3Wrapper.getAvailableAddressesAsync(); // Hack: Get Web3Wrapper from ZeroExContract
const web3Wrapper = (this._contractWrappers as any)._web3Wrapper;
const availableAddresses = await web3Wrapper.getAvailableAddressesAsync();
return availableAddresses; return availableAddresses;
} }
/** /**
@ -223,7 +185,7 @@ export class ZeroEx {
shouldAddPersonalMessagePrefix: boolean, shouldAddPersonalMessagePrefix: boolean,
): Promise<ECSignature> { ): Promise<ECSignature> {
return signOrderHashAsync( return signOrderHashAsync(
this._web3Wrapper.getProvider(), this._contractWrappers.getProvider(),
orderHash, orderHash,
signerAddress, signerAddress,
shouldAddPersonalMessagePrefix, shouldAddPersonalMessagePrefix,
@ -241,7 +203,9 @@ export class ZeroEx {
pollingIntervalMs = 1000, pollingIntervalMs = 1000,
timeoutMs?: number, timeoutMs?: number,
): Promise<TransactionReceiptWithDecodedLogs> { ): Promise<TransactionReceiptWithDecodedLogs> {
const transactionReceiptWithDecodedLogs = await this._web3Wrapper.awaitTransactionMinedAsync( // Hack: Get Web3Wrapper from ZeroExContract
const web3Wrapper = (this._contractWrappers as any)._web3Wrapper;
const transactionReceiptWithDecodedLogs = await web3Wrapper.awaitTransactionMinedAsync(
txHash, txHash,
pollingIntervalMs, pollingIntervalMs,
timeoutMs, timeoutMs,
@ -249,22 +213,16 @@ export class ZeroEx {
return transactionReceiptWithDecodedLogs; return transactionReceiptWithDecodedLogs;
} }
/** /**
* Instantiates and returns a new OrderStateWatcher instance. * Instantiates and returns a new OrderWatcher instance.
* Defaults to watching the pending state. * Defaults to watching the pending state.
* @param config The configuration object. Look up the type for the description. * @param config The configuration object. Look up the type for the description.
* @return An instance of the 0x.js OrderStateWatcher class. * @return An instance of the 0x.js OrderWatcher class.
*/ */
public createOrderStateWatcher(config?: OrderStateWatcherConfig) { public async createOrderWatcherAsync(config?: OrderWatcherConfig) {
return new OrderStateWatcher(this._web3Wrapper, this.token, this.exchange, config); // Hack: Get Web3Wrapper from ZeroExContract
} const web3Wrapper = (this._contractWrappers as any)._web3Wrapper;
/* const networkId = web3Wrapper.getNetworkIdAsync();
* HACK: `TokenWrapper` needs a token transfer proxy address. `TokenTransferProxy` address is fetched from const provider = this._contractWrappers.getProvider();
* an `ExchangeWrapper`. `ExchangeWrapper` needs `TokenWrapper` to validate orders, creating a dependency cycle. return new OrderWatcher(provider, networkId, config);
* In order to break this - we create this function here and pass it as a parameter to the `TokenWrapper`
* and `ProxyWrapper`.
*/
private async _getTokenTransferProxyAddressAsync(): Promise<string> {
const tokenTransferProxyAddress = await (this.exchange as any)._getTokenTransferProxyAddressAsync();
return tokenTransferProxyAddress;
} }
} }

View File

@ -1,18 +0,0 @@
import * as DummyTokenArtifact from './compact_artifacts/DummyToken.json';
import * as EtherTokenArtifact from './compact_artifacts/EtherToken.json';
import * as ExchangeArtifact from './compact_artifacts/Exchange.json';
import * as TokenArtifact from './compact_artifacts/Token.json';
import * as TokenRegistryArtifact from './compact_artifacts/TokenRegistry.json';
import * as TokenTransferProxyArtifact from './compact_artifacts/TokenTransferProxy.json';
import * as ZRXArtifact from './compact_artifacts/ZRX.json';
import { Artifact } from './types';
export const artifacts = {
ZRXArtifact: (ZRXArtifact as any) as Artifact,
DummyTokenArtifact: (DummyTokenArtifact as any) as Artifact,
TokenArtifact: (TokenArtifact as any) as Artifact,
ExchangeArtifact: (ExchangeArtifact as any) as Artifact,
EtherTokenArtifact: (EtherTokenArtifact as any) as Artifact,
TokenRegistryArtifact: (TokenRegistryArtifact as any) as Artifact,
TokenTransferProxyArtifact: (TokenTransferProxyArtifact as any) as Artifact,
};

View File

@ -1,61 +1,51 @@
export { ZeroEx } from './0x'; export { ZeroEx } from './0x';
export {
ZeroExError,
EventCallback,
ExchangeContractErrs,
ContractEvent,
Token,
IndexedFilterValues,
BlockRange,
OrderCancellationRequest,
OrderFillRequest,
ContractEventArgs,
ZeroExConfig,
MethodOpts,
OrderTransactionOpts,
TransactionOpts,
LogEvent,
DecodedLogEvent,
EventWatcherCallback,
OnOrderStateChangeCallback,
OrderStateValid,
OrderStateInvalid,
OrderState,
} from './types';
export { export {
BlockParamLiteral, BlockParamLiteral,
FilterObject, FilterObject,
BlockParam, BlockParam,
ContractEventArg, ContractEventArg,
ExchangeContractErrs,
LogWithDecodedArgs, LogWithDecodedArgs,
Order, Order,
Provider, Provider,
SignedOrder, SignedOrder,
ECSignature, ECSignature,
OrderStateValid,
OrderStateInvalid,
OrderState,
Token,
TransactionReceipt, TransactionReceipt,
TransactionReceiptWithDecodedLogs, TransactionReceiptWithDecodedLogs,
} from '@0xproject/types'; } from '@0xproject/types';
export { export {
EventCallback,
ContractEvent,
IndexedFilterValues,
BlockRange,
OrderCancellationRequest,
OrderFillRequest,
ContractEventArgs,
MethodOpts,
OrderTransactionOpts,
TransactionOpts,
LogEvent,
DecodedLogEvent,
OnOrderStateChangeCallback,
ContractWrappersError,
EtherTokenContractEventArgs, EtherTokenContractEventArgs,
WithdrawalContractEventArgs, WithdrawalContractEventArgs,
DepositContractEventArgs, DepositContractEventArgs,
EtherTokenEvents, EtherTokenEvents,
} from './contract_wrappers/generated/ether_token';
export {
TransferContractEventArgs, TransferContractEventArgs,
ApprovalContractEventArgs, ApprovalContractEventArgs,
TokenContractEventArgs, TokenContractEventArgs,
TokenEvents, TokenEvents,
} from './contract_wrappers/generated/token';
export {
LogErrorContractEventArgs, LogErrorContractEventArgs,
LogCancelContractEventArgs, LogCancelContractEventArgs,
LogFillContractEventArgs, LogFillContractEventArgs,
ExchangeContractEventArgs, ExchangeContractEventArgs,
ExchangeEvents, ExchangeEvents,
} from './contract_wrappers/generated/exchange'; ZeroExContractConfig,
} from '@0xproject/contract-wrappers';

View File

@ -1,23 +1,16 @@
import { BigNumber } from '@0xproject/utils';
import { import {
BlockParam, BlockParam,
BlockParamLiteral, BlockParamLiteral,
ContractAbi, ContractAbi,
ContractEventArg, ContractEventArg,
ExchangeContractErrs,
FilterObject, FilterObject,
LogEntryEvent,
LogWithDecodedArgs, LogWithDecodedArgs,
Order, Order,
OrderState,
SignedOrder, SignedOrder,
} from '@0xproject/types'; } from '@0xproject/types';
import * as Web3 from 'web3';
import { EtherTokenContractEventArgs, EtherTokenEvents } from './contract_wrappers/generated/ether_token';
import { ExchangeContractEventArgs, ExchangeEvents } from './contract_wrappers/generated/exchange';
import { TokenContractEventArgs, TokenEvents } from './contract_wrappers/generated/token';
export enum ZeroExError { export enum ZeroExError {
ExchangeContractDoesNotExist = 'EXCHANGE_CONTRACT_DOES_NOT_EXIST', ExchangeContractDoesNotExist = 'EXCHANGE_CONTRACT_DOES_NOT_EXIST',
ZRXContractDoesNotExist = 'ZRX_CONTRACT_DOES_NOT_EXIST', ZRXContractDoesNotExist = 'ZRX_CONTRACT_DOES_NOT_EXIST',
@ -45,232 +38,4 @@ export enum InternalZeroExError {
WethNotInTokenRegistry = 'WETH_NOT_IN_TOKEN_REGISTRY', WethNotInTokenRegistry = 'WETH_NOT_IN_TOKEN_REGISTRY',
} }
export type OrderAddresses = [string, string, string, string, string];
export type OrderValues = [BigNumber, BigNumber, BigNumber, BigNumber, BigNumber, BigNumber];
export type LogEvent = LogEntryEvent;
export interface DecodedLogEvent<ArgsType> {
isRemoved: boolean;
log: LogWithDecodedArgs<ArgsType>;
}
export type EventCallback<ArgsType> = (err: null | Error, log?: DecodedLogEvent<ArgsType>) => void;
export type EventWatcherCallback = (err: null | Error, log?: LogEvent) => void;
export enum ExchangeContractErrCodes {
ERROR_FILL_EXPIRED, // Order has already expired
ERROR_FILL_NO_VALUE, // Order has already been fully filled or cancelled
ERROR_FILL_TRUNCATION, // Rounding error too large
ERROR_FILL_BALANCE_ALLOWANCE, // Insufficient balance or allowance for token transfer
ERROR_CANCEL_EXPIRED, // Order has already expired
ERROR_CANCEL_NO_VALUE, // Order has already been fully filled or cancelled
}
export enum ExchangeContractErrs {
OrderFillExpired = 'ORDER_FILL_EXPIRED',
OrderCancelExpired = 'ORDER_CANCEL_EXPIRED',
OrderCancelAmountZero = 'ORDER_CANCEL_AMOUNT_ZERO',
OrderAlreadyCancelledOrFilled = 'ORDER_ALREADY_CANCELLED_OR_FILLED',
OrderFillAmountZero = 'ORDER_FILL_AMOUNT_ZERO',
OrderRemainingFillAmountZero = 'ORDER_REMAINING_FILL_AMOUNT_ZERO',
OrderFillRoundingError = 'ORDER_FILL_ROUNDING_ERROR',
FillBalanceAllowanceError = 'FILL_BALANCE_ALLOWANCE_ERROR',
InsufficientTakerBalance = 'INSUFFICIENT_TAKER_BALANCE',
InsufficientTakerAllowance = 'INSUFFICIENT_TAKER_ALLOWANCE',
InsufficientMakerBalance = 'INSUFFICIENT_MAKER_BALANCE',
InsufficientMakerAllowance = 'INSUFFICIENT_MAKER_ALLOWANCE',
InsufficientTakerFeeBalance = 'INSUFFICIENT_TAKER_FEE_BALANCE',
InsufficientTakerFeeAllowance = 'INSUFFICIENT_TAKER_FEE_ALLOWANCE',
InsufficientMakerFeeBalance = 'INSUFFICIENT_MAKER_FEE_BALANCE',
InsufficientMakerFeeAllowance = 'INSUFFICIENT_MAKER_FEE_ALLOWANCE',
TransactionSenderIsNotFillOrderTaker = 'TRANSACTION_SENDER_IS_NOT_FILL_ORDER_TAKER',
MultipleMakersInSingleCancelBatchDisallowed = 'MULTIPLE_MAKERS_IN_SINGLE_CANCEL_BATCH_DISALLOWED',
InsufficientRemainingFillAmount = 'INSUFFICIENT_REMAINING_FILL_AMOUNT',
MultipleTakerTokensInFillUpToDisallowed = 'MULTIPLE_TAKER_TOKENS_IN_FILL_UP_TO_DISALLOWED',
BatchOrdersMustHaveSameExchangeAddress = 'BATCH_ORDERS_MUST_HAVE_SAME_EXCHANGE_ADDRESS',
BatchOrdersMustHaveAtLeastOneItem = 'BATCH_ORDERS_MUST_HAVE_AT_LEAST_ONE_ITEM',
}
export interface ContractEvent {
logIndex: number;
transactionIndex: number;
transactionHash: string;
blockHash: string;
blockNumber: number;
address: string;
type: string;
event: string;
args: ContractEventArgs;
}
export type ContractEventArgs = ExchangeContractEventArgs | TokenContractEventArgs | EtherTokenContractEventArgs;
// [address, name, symbol, decimals, ipfsHash, swarmHash]
export type TokenMetadata = [string, string, string, number, string, string];
export interface Token {
name: string;
address: string;
symbol: string;
decimals: number;
}
export interface TxOpts {
from: string;
gas?: number;
value?: BigNumber;
gasPrice?: BigNumber;
}
export interface TokenAddressBySymbol {
[symbol: string]: string;
}
export type ContractEvents = TokenEvents | ExchangeEvents | EtherTokenEvents;
export interface IndexedFilterValues {
[index: string]: ContractEventArg;
}
export interface BlockRange {
fromBlock: BlockParam;
toBlock: BlockParam;
}
export type DoneCallback = (err?: Error) => void;
export interface OrderCancellationRequest {
order: Order | SignedOrder;
takerTokenCancelAmount: BigNumber;
}
export interface OrderFillRequest {
signedOrder: SignedOrder;
takerTokenFillAmount: BigNumber;
}
export type AsyncMethod = (...args: any[]) => Promise<any>;
export type SyncMethod = (...args: any[]) => any;
/**
* orderExpirationCheckingIntervalMs: How often to check for expired orders. Default=50.
* eventPollingIntervalMs: How often to poll the Ethereum node for new events. Default=200.
* expirationMarginMs: Amount of time before order expiry that you'd like to be notified
* of an orders expiration. Default=0.
* cleanupJobIntervalMs: How often to run a cleanup job which revalidates all the orders. Default=1hr.
* stateLayer: Optional blockchain state layer OrderWatcher will monitor for new events. Default=latest.
*/
export interface OrderStateWatcherConfig {
orderExpirationCheckingIntervalMs?: number;
eventPollingIntervalMs?: number;
expirationMarginMs?: number;
cleanupJobIntervalMs?: number;
stateLayer: BlockParamLiteral;
}
/**
* networkId: The id of the underlying ethereum network your provider is connected to. (1-mainnet, 3-ropsten, 4-rinkeby, 42-kovan, 50-testrpc)
* gasPrice: Gas price to use with every transaction
* exchangeContractAddress: The address of an exchange contract to use
* zrxContractAddress: The address of the ZRX contract to use
* tokenRegistryContractAddress: The address of a token registry contract to use
* tokenTransferProxyContractAddress: The address of the token transfer proxy contract to use
* orderWatcherConfig: All the configs related to the orderWatcher
*/
export interface ZeroExConfig {
networkId: number;
gasPrice?: BigNumber;
exchangeContractAddress?: string;
zrxContractAddress?: string;
tokenRegistryContractAddress?: string;
tokenTransferProxyContractAddress?: string;
orderWatcherConfig?: OrderStateWatcherConfig;
}
export type ArtifactContractName = 'ZRX' | 'TokenTransferProxy' | 'TokenRegistry' | 'Token' | 'Exchange' | 'EtherToken';
export interface Artifact {
contract_name: ArtifactContractName;
abi: ContractAbi;
networks: {
[networkId: number]: {
address: string;
};
};
}
/**
* expectedFillTakerTokenAmount: If specified, the validation method will ensure that the
* supplied order maker has a sufficient allowance/balance to fill this amount of the order's
* takerTokenAmount. If not specified, the validation method ensures that the maker has a sufficient
* allowance/balance to fill the entire remaining order amount.
*/
export interface ValidateOrderFillableOpts {
expectedFillTakerTokenAmount?: BigNumber;
}
/**
* defaultBlock: The block up to which to query the blockchain state. Setting this to a historical block number
* let's the user query the blockchain's state at an arbitrary point in time. In order for this to work, the
* backing Ethereum node must keep the entire historical state of the chain (e.g setting `--pruning=archive`
* flag when running Parity).
*/
export interface MethodOpts {
defaultBlock?: BlockParam;
}
/**
* gasPrice: Gas price in Wei to use for a transaction
* gasLimit: The amount of gas to send with a transaction
*/
export interface TransactionOpts {
gasPrice?: BigNumber;
gasLimit?: number;
}
/**
* shouldValidate: Flag indicating whether the library should make attempts to validate a transaction before
* broadcasting it. For example, order has a valid signature, maker has sufficient funds, etc. Default=true.
*/
export interface OrderTransactionOpts extends TransactionOpts {
shouldValidate?: boolean;
}
export enum TradeSide {
Maker = 'maker',
Taker = 'taker',
}
export enum TransferType {
Trade = 'trade',
Fee = 'fee',
}
export interface OrderRelevantState {
makerBalance: BigNumber;
makerProxyAllowance: BigNumber;
makerFeeBalance: BigNumber;
makerFeeProxyAllowance: BigNumber;
filledTakerTokenAmount: BigNumber;
cancelledTakerTokenAmount: BigNumber;
remainingFillableMakerTokenAmount: BigNumber;
remainingFillableTakerTokenAmount: BigNumber;
}
export interface OrderStateValid {
isValid: true;
orderHash: string;
orderRelevantState: OrderRelevantState;
}
export interface OrderStateInvalid {
isValid: false;
orderHash: string;
error: ExchangeContractErrs;
}
export type OrderState = OrderStateValid | OrderStateInvalid;
export type OnOrderStateChangeCallback = (err: Error | null, orderState?: OrderState) => void;
// tslint:disable:max-file-line-count // tslint:disable:max-file-line-count

View File

@ -3,9 +3,4 @@ import { BigNumber } from '@0xproject/utils';
export const constants = { export const constants = {
NULL_ADDRESS: '0x0000000000000000000000000000000000000000', NULL_ADDRESS: '0x0000000000000000000000000000000000000000',
TESTRPC_NETWORK_ID: 50, TESTRPC_NETWORK_ID: 50,
INVALID_JUMP_PATTERN: 'invalid JUMP at',
OUT_OF_GAS_PATTERN: 'out of gas',
INVALID_TAKER_FORMAT: 'instance.taker is not of a type(s) string',
UNLIMITED_ALLOWANCE_IN_BASE_UNITS: new BigNumber(2).pow(256).minus(1),
DEFAULT_BLOCK_POLLING_INTERVAL: 1000,
}; };

View File

@ -41,8 +41,8 @@ describe('ZeroEx library', () => {
expect((zeroEx.exchange as any)._exchangeContractIfExists).to.be.undefined(); expect((zeroEx.exchange as any)._exchangeContractIfExists).to.be.undefined();
expect((zeroEx.tokenRegistry as any)._tokenRegistryContractIfExists).to.be.undefined(); expect((zeroEx.tokenRegistry as any)._tokenRegistryContractIfExists).to.be.undefined();
// Check that all nested web3 wrapper instances return the updated provider // Check that all nested zeroExContract/web3Wrapper instances return the updated provider
const nestedWeb3WrapperProvider = (zeroEx as any)._web3Wrapper.getProvider(); const nestedWeb3WrapperProvider = (zeroEx as any)._contractWrappers.getProvider();
expect(nestedWeb3WrapperProvider.zeroExTestId).to.be.a('number'); expect(nestedWeb3WrapperProvider.zeroExTestId).to.be.a('number');
const exchangeWeb3WrapperProvider = (zeroEx.exchange as any)._web3Wrapper.getProvider(); const exchangeWeb3WrapperProvider = (zeroEx.exchange as any)._web3Wrapper.getProvider();
expect(exchangeWeb3WrapperProvider.zeroExTestId).to.be.a('number'); expect(exchangeWeb3WrapperProvider.zeroExTestId).to.be.a('number');

View File

@ -1,66 +0,0 @@
import * as chai from 'chai';
import * as _ from 'lodash';
import { DoneCallback } from '../../src/types';
const expect = chai.expect;
export const reportNoErrorCallbackErrors = (done: DoneCallback, expectToBeCalledOnce = true) => {
return <T>(f?: (value: T) => void) => {
const wrapped = (value: T) => {
if (_.isUndefined(f)) {
done();
return;
}
try {
f(value);
if (expectToBeCalledOnce) {
done();
}
} catch (err) {
done(err);
}
};
return wrapped;
};
};
export const reportNodeCallbackErrors = (done: DoneCallback, expectToBeCalledOnce = true) => {
return <T>(f?: (value: T) => void) => {
const wrapped = (error: Error | null, value: T | undefined) => {
if (!_.isNull(error)) {
done(error);
} else {
if (_.isUndefined(f)) {
done();
return;
}
try {
f(value as T);
if (expectToBeCalledOnce) {
done();
}
} catch (err) {
done(err);
}
}
};
return wrapped;
};
};
export const assertNodeCallbackError = (done: DoneCallback, errMsg: string) => {
const wrapped = <T>(error: Error | null, value: T | undefined) => {
if (_.isNull(error)) {
done(new Error('Expected callback to receive an error'));
} else {
try {
expect(error.message).to.be.equal(errMsg);
done();
} catch (err) {
done(err);
}
}
};
return wrapped;
};

View File

@ -1,6 +1,7 @@
import { Token } from '@0xproject/types';
import * as _ from 'lodash'; import * as _ from 'lodash';
import { InternalZeroExError, Token } from '../../src/types'; import { InternalZeroExError } from '../../src/types';
const PROTOCOL_TOKEN_SYMBOL = 'ZRX'; const PROTOCOL_TOKEN_SYMBOL = 'ZRX';
const WETH_TOKEN_SYMBOL = 'WETH'; const WETH_TOKEN_SYMBOL = 'WETH';

View File

@ -0,0 +1,11 @@
.*
tsconfig.json
webpack.config.js
yarn-error.log
test/
/src/
/_bundles/
/contract_templates/
/generated_docs/
/scripts/
/lib/src/monorepo_scripts/

View File

@ -0,0 +1,10 @@
[
{
"version": "0.0.1",
"changes": [
{
"note": "Moved contractWrappers out of 0x.js"
}
]
}
]

View File

@ -0,0 +1,6 @@
<!--
This file is auto-generated using the monorepo-scripts package. Don't edit directly.
Edit the package's CHANGELOG.json file only.
-->
CHANGELOG

View File

@ -0,0 +1,91 @@
## @0xproject/contract-wrappers
Smart TS wrappers for 0x smart contracts. The wrappers have simplified interfaces, perform client-side validation on transactions and throw helpful error messages.
### Read the [Documentation](https://0xproject.com/docs/0x.js).
## Installation
**Install**
```bash
npm install @0xproject/contract-wrappers --save
```
**Import**
```javascript
import { ContractWrappers } from '@0xproject/contract-wrappers';
```
If your project is in [TypeScript](https://www.typescriptlang.org/), add the following to your `tsconfig.json`:
```json
"compilerOptions": {
"typeRoots": ["node_modules/@0xproject/typescript-typings/types", "node_modules/@types"],
}
```
## Contributing
We strongly recommend that the community help us make improvements and determine the future direction of the protocol. To report bugs within this package, please create an issue in this repository.
Please read our [contribution guidelines](../../CONTRIBUTING.md) before getting started.
### Install dependencies
If you don't have yarn workspaces enabled (Yarn < v1.0) - enable them:
```bash
yarn config set workspaces-experimental true
```
Then install dependencies
```bash
yarn install
```
### Build
If this is your **first** time building this package, you must first build **all** packages within the monorepo. This is because packages that depend on other packages located inside this monorepo are symlinked when run from **within** the monorepo. This allows you to make changes across multiple packages without first publishing dependent packages to NPM. To build all packages, run the following from the monorepo root directory:
```bash
yarn lerna:rebuild
```
Or continuously rebuild on change:
```bash
yarn dev
```
You can also build this specific package by running the following from within its directory:
```bash
yarn build
```
or continuously rebuild on change:
```bash
yarn build:watch
```
### Clean
```bash
yarn clean
```
### Lint
```bash
yarn lint
```
### Run Tests
```bash
yarn test
```

View File

@ -0,0 +1,95 @@
{
"name": "@0xproject/contract-wrappers",
"version": "0.0.1",
"description": "Smart TS wrappers for 0x smart contracts",
"keywords": [
"0xproject",
"ethereum",
"tokens",
"exchange"
],
"main": "lib/src/index.js",
"types": "lib/src/index.d.ts",
"scripts": {
"build:watch": "tsc -w",
"prebuild": "run-s clean generate_contract_wrappers",
"generate_contract_wrappers": "node ../abi-gen/lib/index.js --abis 'src/compact_artifacts/@(Exchange|Token|TokenTransferProxy|EtherToken|TokenRegistry|DummyToken).json' --template ../contract_templates/contract.handlebars --partials '../contract_templates/partials/**/*.handlebars' --output src/contract_wrappers/generated --backend ethers && prettier --write 'src/contract_wrappers/generated/**.ts'",
"lint": "tslint --project . 'src/**/*.ts' 'test/**/*.ts'",
"test:circleci": "run-s test:coverage",
"test": "run-s clean build run_mocha",
"test:coverage": "nyc npm run test --all && yarn coverage:report:lcov",
"coverage:report:lcov": "nyc report --reporter=text-lcov > coverage/lcov.info",
"update_artifacts": "for i in ${npm_package_config_contracts}; do copyfiles -u 4 ../migrations/src/artifacts/$i.json test/artifacts; done;",
"clean": "shx rm -rf _bundles lib test_temp scripts",
"build": "tsc && yarn update_artifacts && copyfiles -u 2 './src/compact_artifacts/**/*.json' ./lib/src/compact_artifacts && copyfiles -u 3 './lib/src/monorepo_scripts/**/*' ./scripts",
"run_mocha": "mocha lib/test/**/*_test.js lib/test/global_hooks.js --timeout 10000 --bail --exit",
"manual:postpublish": "yarn build; node ./scripts/postpublish.js"
},
"config": {
"compact_artifacts": "Exchange DummyToken ZRXToken Token EtherToken TokenTransferProxy TokenRegistry",
"contracts": "Exchange DummyToken ZRXToken Token WETH9 TokenTransferProxy MultiSigWallet MultiSigWalletWithTimeLock MultiSigWalletWithTimeLockExceptRemoveAuthorizedAddress MaliciousToken TokenRegistry Arbitrage EtherDelta AccountLevels",
"postpublish": {
"assets": [
"packages/contract-wrappers/_bundles/index.js",
"packages/contract-wrappers/_bundles/index.min.js"
]
}
},
"repository": {
"type": "git",
"url": "https://github.com/0xProject/0x-monorepo"
},
"license": "Apache-2.0",
"engines": {
"node": ">=6.0.0"
},
"devDependencies": {
"@0xproject/deployer": "^0.4.3",
"@0xproject/dev-utils": "^0.4.1",
"@0xproject/migrations": "^0.0.5",
"@0xproject/monorepo-scripts": "^0.1.19",
"@0xproject/subproviders": "^0.10.1",
"@0xproject/tslint-config": "^0.4.17",
"@types/lodash": "4.14.104",
"@types/mocha": "^2.2.42",
"@types/node": "^8.0.53",
"@types/sinon": "^2.2.2",
"awesome-typescript-loader": "^3.1.3",
"chai": "^4.0.1",
"chai-as-promised": "^7.1.0",
"chai-bignumber": "^2.0.1",
"copyfiles": "^1.2.0",
"dirty-chai": "^2.0.1",
"mocha": "^4.0.1",
"npm-run-all": "^4.1.2",
"nyc": "^11.0.1",
"opn-cli": "^3.1.0",
"prettier": "^1.11.1",
"shx": "^0.2.2",
"sinon": "^4.0.0",
"source-map-support": "^0.5.0",
"tslint": "5.8.0",
"typescript": "2.7.1",
"web3-provider-engine": "^14.0.4"
},
"dependencies": {
"@0xproject/assert": "^0.2.9",
"@0xproject/base-contract": "^0.3.1",
"@0xproject/fill-scenarios": "^0.0.1",
"@0xproject/json-schemas": "^0.7.23",
"@0xproject/order-utils": "^0.0.4",
"@0xproject/types": "^0.6.3",
"@0xproject/typescript-typings": "^0.3.1",
"@0xproject/utils": "^0.6.1",
"@0xproject/web3-wrapper": "^0.6.3",
"ethereumjs-blockstream": "^2.0.6",
"ethereumjs-util": "^5.1.1",
"ethers": "^3.0.15",
"js-sha3": "^0.7.0",
"lodash": "^4.17.4",
"uuid": "^3.1.0"
},
"publishConfig": {
"access": "public"
}
}

View File

@ -0,0 +1,18 @@
import { Artifact } from '@0xproject/types';
import * as DummyToken from './compact_artifacts/DummyToken.json';
import * as EtherToken from './compact_artifacts/EtherToken.json';
import * as Exchange from './compact_artifacts/Exchange.json';
import * as Token from './compact_artifacts/Token.json';
import * as TokenRegistry from './compact_artifacts/TokenRegistry.json';
import * as TokenTransferProxy from './compact_artifacts/TokenTransferProxy.json';
import * as ZRX from './compact_artifacts/ZRX.json';
export const artifacts = {
ZRX: (ZRX as any) as Artifact,
DummyToken: (DummyToken as any) as Artifact,
Token: (Token as any) as Artifact,
Exchange: (Exchange as any) as Artifact,
EtherToken: (EtherToken as any) as Artifact,
TokenRegistry: (TokenRegistry as any) as Artifact,
TokenTransferProxy: (TokenTransferProxy as any) as Artifact,
};

View File

@ -0,0 +1,22 @@
{
"contract_name": "DummyToken",
"abi": [
{
"constant": false,
"inputs": [
{
"name": "_target",
"type": "address"
},
{
"name": "_value",
"type": "uint256"
}
],
"name": "setBalance",
"outputs": [],
"payable": false,
"type": "function"
}
]
}

View File

@ -0,0 +1,287 @@
{
"contract_name": "EtherToken",
"abi": [
{
"constant": true,
"inputs": [],
"name": "name",
"outputs": [
{
"name": "",
"type": "string"
}
],
"payable": false,
"type": "function"
},
{
"constant": false,
"inputs": [
{
"name": "_spender",
"type": "address"
},
{
"name": "_value",
"type": "uint256"
}
],
"name": "approve",
"outputs": [
{
"name": "",
"type": "bool"
}
],
"payable": false,
"type": "function"
},
{
"constant": true,
"inputs": [],
"name": "totalSupply",
"outputs": [
{
"name": "",
"type": "uint256"
}
],
"payable": false,
"type": "function"
},
{
"constant": false,
"inputs": [
{
"name": "_from",
"type": "address"
},
{
"name": "_to",
"type": "address"
},
{
"name": "_value",
"type": "uint256"
}
],
"name": "transferFrom",
"outputs": [
{
"name": "",
"type": "bool"
}
],
"payable": false,
"type": "function"
},
{
"constant": false,
"inputs": [
{
"name": "amount",
"type": "uint256"
}
],
"name": "withdraw",
"outputs": [],
"payable": false,
"type": "function"
},
{
"constant": true,
"inputs": [],
"name": "decimals",
"outputs": [
{
"name": "",
"type": "uint8"
}
],
"payable": false,
"type": "function"
},
{
"constant": true,
"inputs": [
{
"name": "_owner",
"type": "address"
}
],
"name": "balanceOf",
"outputs": [
{
"name": "",
"type": "uint256"
}
],
"payable": false,
"type": "function"
},
{
"constant": true,
"inputs": [],
"name": "symbol",
"outputs": [
{
"name": "",
"type": "string"
}
],
"payable": false,
"type": "function"
},
{
"constant": false,
"inputs": [
{
"name": "_to",
"type": "address"
},
{
"name": "_value",
"type": "uint256"
}
],
"name": "transfer",
"outputs": [
{
"name": "",
"type": "bool"
}
],
"payable": false,
"type": "function"
},
{
"constant": false,
"inputs": [],
"name": "deposit",
"outputs": [],
"payable": true,
"type": "function"
},
{
"constant": true,
"inputs": [
{
"name": "_owner",
"type": "address"
},
{
"name": "_spender",
"type": "address"
}
],
"name": "allowance",
"outputs": [
{
"name": "",
"type": "uint256"
}
],
"payable": false,
"type": "function"
},
{
"payable": true,
"type": "fallback"
},
{
"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"
},
{
"anonymous": false,
"inputs": [
{
"indexed": true,
"name": "_owner",
"type": "address"
},
{
"indexed": true,
"name": "_spender",
"type": "address"
},
{
"indexed": false,
"name": "_value",
"type": "uint256"
}
],
"name": "Approval",
"type": "event"
},
{
"anonymous": false,
"inputs": [
{
"indexed": true,
"name": "_owner",
"type": "address"
},
{
"indexed": false,
"name": "_value",
"type": "uint256"
}
],
"name": "Deposit",
"type": "event"
},
{
"anonymous": false,
"inputs": [
{
"indexed": true,
"name": "_owner",
"type": "address"
},
{
"indexed": false,
"name": "_value",
"type": "uint256"
}
],
"name": "Withdrawal",
"type": "event"
}
],
"networks": {
"1": {
"address": "0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2"
},
"3": {
"address": "0xc00fd9820cd2898cc4c054b7bf142de637ad129a"
},
"4": {
"address": "0xc778417e063141139fce010982780140aa0cd5ab"
},
"42": {
"address": "0x653e49e301e508a13237c0ddc98ae7d4cd2667a1"
},
"50": {
"address": "0x871dd7c2b4b25e1aa18728e9d5f2af4c4e431f5c"
}
}
}

View File

@ -0,0 +1,610 @@
{
"contract_name": "Exchange",
"abi": [
{
"constant": true,
"inputs": [
{
"name": "numerator",
"type": "uint256"
},
{
"name": "denominator",
"type": "uint256"
},
{
"name": "target",
"type": "uint256"
}
],
"name": "isRoundingError",
"outputs": [
{
"name": "",
"type": "bool"
}
],
"payable": false,
"type": "function"
},
{
"constant": true,
"inputs": [
{
"name": "",
"type": "bytes32"
}
],
"name": "filled",
"outputs": [
{
"name": "",
"type": "uint256"
}
],
"payable": false,
"type": "function"
},
{
"constant": true,
"inputs": [
{
"name": "",
"type": "bytes32"
}
],
"name": "cancelled",
"outputs": [
{
"name": "",
"type": "uint256"
}
],
"payable": false,
"type": "function"
},
{
"constant": false,
"inputs": [
{
"name": "orderAddresses",
"type": "address[5][]"
},
{
"name": "orderValues",
"type": "uint256[6][]"
},
{
"name": "fillTakerTokenAmount",
"type": "uint256"
},
{
"name": "shouldThrowOnInsufficientBalanceOrAllowance",
"type": "bool"
},
{
"name": "v",
"type": "uint8[]"
},
{
"name": "r",
"type": "bytes32[]"
},
{
"name": "s",
"type": "bytes32[]"
}
],
"name": "fillOrdersUpTo",
"outputs": [
{
"name": "",
"type": "uint256"
}
],
"payable": false,
"type": "function"
},
{
"constant": false,
"inputs": [
{
"name": "orderAddresses",
"type": "address[5]"
},
{
"name": "orderValues",
"type": "uint256[6]"
},
{
"name": "cancelTakerTokenAmount",
"type": "uint256"
}
],
"name": "cancelOrder",
"outputs": [
{
"name": "",
"type": "uint256"
}
],
"payable": false,
"type": "function"
},
{
"constant": true,
"inputs": [],
"name": "ZRX_TOKEN_CONTRACT",
"outputs": [
{
"name": "",
"type": "address"
}
],
"payable": false,
"type": "function"
},
{
"constant": false,
"inputs": [
{
"name": "orderAddresses",
"type": "address[5][]"
},
{
"name": "orderValues",
"type": "uint256[6][]"
},
{
"name": "fillTakerTokenAmounts",
"type": "uint256[]"
},
{
"name": "v",
"type": "uint8[]"
},
{
"name": "r",
"type": "bytes32[]"
},
{
"name": "s",
"type": "bytes32[]"
}
],
"name": "batchFillOrKillOrders",
"outputs": [],
"payable": false,
"type": "function"
},
{
"constant": false,
"inputs": [
{
"name": "orderAddresses",
"type": "address[5]"
},
{
"name": "orderValues",
"type": "uint256[6]"
},
{
"name": "fillTakerTokenAmount",
"type": "uint256"
},
{
"name": "v",
"type": "uint8"
},
{
"name": "r",
"type": "bytes32"
},
{
"name": "s",
"type": "bytes32"
}
],
"name": "fillOrKillOrder",
"outputs": [],
"payable": false,
"type": "function"
},
{
"constant": true,
"inputs": [
{
"name": "orderHash",
"type": "bytes32"
}
],
"name": "getUnavailableTakerTokenAmount",
"outputs": [
{
"name": "",
"type": "uint256"
}
],
"payable": false,
"type": "function"
},
{
"constant": true,
"inputs": [
{
"name": "signer",
"type": "address"
},
{
"name": "hash",
"type": "bytes32"
},
{
"name": "v",
"type": "uint8"
},
{
"name": "r",
"type": "bytes32"
},
{
"name": "s",
"type": "bytes32"
}
],
"name": "isValidSignature",
"outputs": [
{
"name": "",
"type": "bool"
}
],
"payable": false,
"type": "function"
},
{
"constant": true,
"inputs": [
{
"name": "numerator",
"type": "uint256"
},
{
"name": "denominator",
"type": "uint256"
},
{
"name": "target",
"type": "uint256"
}
],
"name": "getPartialAmount",
"outputs": [
{
"name": "",
"type": "uint256"
}
],
"payable": false,
"type": "function"
},
{
"constant": true,
"inputs": [],
"name": "TOKEN_TRANSFER_PROXY_CONTRACT",
"outputs": [
{
"name": "",
"type": "address"
}
],
"payable": false,
"type": "function"
},
{
"constant": false,
"inputs": [
{
"name": "orderAddresses",
"type": "address[5][]"
},
{
"name": "orderValues",
"type": "uint256[6][]"
},
{
"name": "fillTakerTokenAmounts",
"type": "uint256[]"
},
{
"name": "shouldThrowOnInsufficientBalanceOrAllowance",
"type": "bool"
},
{
"name": "v",
"type": "uint8[]"
},
{
"name": "r",
"type": "bytes32[]"
},
{
"name": "s",
"type": "bytes32[]"
}
],
"name": "batchFillOrders",
"outputs": [],
"payable": false,
"type": "function"
},
{
"constant": false,
"inputs": [
{
"name": "orderAddresses",
"type": "address[5][]"
},
{
"name": "orderValues",
"type": "uint256[6][]"
},
{
"name": "cancelTakerTokenAmounts",
"type": "uint256[]"
}
],
"name": "batchCancelOrders",
"outputs": [],
"payable": false,
"type": "function"
},
{
"constant": false,
"inputs": [
{
"name": "orderAddresses",
"type": "address[5]"
},
{
"name": "orderValues",
"type": "uint256[6]"
},
{
"name": "fillTakerTokenAmount",
"type": "uint256"
},
{
"name": "shouldThrowOnInsufficientBalanceOrAllowance",
"type": "bool"
},
{
"name": "v",
"type": "uint8"
},
{
"name": "r",
"type": "bytes32"
},
{
"name": "s",
"type": "bytes32"
}
],
"name": "fillOrder",
"outputs": [
{
"name": "filledTakerTokenAmount",
"type": "uint256"
}
],
"payable": false,
"type": "function"
},
{
"constant": true,
"inputs": [
{
"name": "orderAddresses",
"type": "address[5]"
},
{
"name": "orderValues",
"type": "uint256[6]"
}
],
"name": "getOrderHash",
"outputs": [
{
"name": "",
"type": "bytes32"
}
],
"payable": false,
"type": "function"
},
{
"constant": true,
"inputs": [],
"name": "EXTERNAL_QUERY_GAS_LIMIT",
"outputs": [
{
"name": "",
"type": "uint16"
}
],
"payable": false,
"type": "function"
},
{
"constant": true,
"inputs": [],
"name": "VERSION",
"outputs": [
{
"name": "",
"type": "string"
}
],
"payable": false,
"type": "function"
},
{
"inputs": [
{
"name": "_zrxToken",
"type": "address"
},
{
"name": "_tokenTransferProxy",
"type": "address"
}
],
"payable": false,
"type": "constructor"
},
{
"anonymous": false,
"inputs": [
{
"indexed": true,
"name": "maker",
"type": "address"
},
{
"indexed": false,
"name": "taker",
"type": "address"
},
{
"indexed": true,
"name": "feeRecipient",
"type": "address"
},
{
"indexed": false,
"name": "makerToken",
"type": "address"
},
{
"indexed": false,
"name": "takerToken",
"type": "address"
},
{
"indexed": false,
"name": "filledMakerTokenAmount",
"type": "uint256"
},
{
"indexed": false,
"name": "filledTakerTokenAmount",
"type": "uint256"
},
{
"indexed": false,
"name": "paidMakerFee",
"type": "uint256"
},
{
"indexed": false,
"name": "paidTakerFee",
"type": "uint256"
},
{
"indexed": true,
"name": "tokens",
"type": "bytes32"
},
{
"indexed": false,
"name": "orderHash",
"type": "bytes32"
}
],
"name": "LogFill",
"type": "event"
},
{
"anonymous": false,
"inputs": [
{
"indexed": true,
"name": "maker",
"type": "address"
},
{
"indexed": true,
"name": "feeRecipient",
"type": "address"
},
{
"indexed": false,
"name": "makerToken",
"type": "address"
},
{
"indexed": false,
"name": "takerToken",
"type": "address"
},
{
"indexed": false,
"name": "cancelledMakerTokenAmount",
"type": "uint256"
},
{
"indexed": false,
"name": "cancelledTakerTokenAmount",
"type": "uint256"
},
{
"indexed": true,
"name": "tokens",
"type": "bytes32"
},
{
"indexed": false,
"name": "orderHash",
"type": "bytes32"
}
],
"name": "LogCancel",
"type": "event"
},
{
"anonymous": false,
"inputs": [
{
"indexed": true,
"name": "errorId",
"type": "uint8"
},
{
"indexed": true,
"name": "orderHash",
"type": "bytes32"
}
],
"name": "LogError",
"type": "event"
}
],
"networks": {
"1": {
"address": "0x12459c951127e0c374ff9105dda097662a027093"
},
"3": {
"address": "0x479cc461fecd078f766ecc58533d6f69580cf3ac"
},
"4": {
"address": "0x1d16ef40fac01cec8adac2ac49427b9384192c05"
},
"42": {
"address": "0x90fe2af704b34e0224bf2299c838e04d4dcf1364"
},
"50": {
"address": "0x48bacb9266a570d521063ef5dd96e61686dbe788"
}
}
}

View File

@ -0,0 +1,172 @@
{
"contract_name": "Token",
"abi": [
{
"constant": false,
"inputs": [
{
"name": "_spender",
"type": "address"
},
{
"name": "_value",
"type": "uint256"
}
],
"name": "approve",
"outputs": [
{
"name": "success",
"type": "bool"
}
],
"payable": false,
"type": "function"
},
{
"constant": true,
"inputs": [],
"name": "totalSupply",
"outputs": [
{
"name": "supply",
"type": "uint256"
}
],
"payable": false,
"type": "function"
},
{
"constant": false,
"inputs": [
{
"name": "_from",
"type": "address"
},
{
"name": "_to",
"type": "address"
},
{
"name": "_value",
"type": "uint256"
}
],
"name": "transferFrom",
"outputs": [
{
"name": "success",
"type": "bool"
}
],
"payable": false,
"type": "function"
},
{
"constant": true,
"inputs": [
{
"name": "_owner",
"type": "address"
}
],
"name": "balanceOf",
"outputs": [
{
"name": "balance",
"type": "uint256"
}
],
"payable": false,
"type": "function"
},
{
"constant": false,
"inputs": [
{
"name": "_to",
"type": "address"
},
{
"name": "_value",
"type": "uint256"
}
],
"name": "transfer",
"outputs": [
{
"name": "success",
"type": "bool"
}
],
"payable": false,
"type": "function"
},
{
"constant": true,
"inputs": [
{
"name": "_owner",
"type": "address"
},
{
"name": "_spender",
"type": "address"
}
],
"name": "allowance",
"outputs": [
{
"name": "remaining",
"type": "uint256"
}
],
"payable": false,
"type": "function"
},
{
"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"
},
{
"anonymous": false,
"inputs": [
{
"indexed": true,
"name": "_owner",
"type": "address"
},
{
"indexed": true,
"name": "_spender",
"type": "address"
},
{
"indexed": false,
"name": "_value",
"type": "uint256"
}
],
"name": "Approval",
"type": "event"
}
]
}

View File

@ -0,0 +1,547 @@
{
"contract_name": "TokenRegistry",
"abi": [
{
"constant": false,
"inputs": [
{
"name": "_token",
"type": "address"
},
{
"name": "_index",
"type": "uint256"
}
],
"name": "removeToken",
"outputs": [],
"payable": false,
"type": "function"
},
{
"constant": true,
"inputs": [
{
"name": "_name",
"type": "string"
}
],
"name": "getTokenAddressByName",
"outputs": [
{
"name": "",
"type": "address"
}
],
"payable": false,
"type": "function"
},
{
"constant": true,
"inputs": [
{
"name": "_symbol",
"type": "string"
}
],
"name": "getTokenAddressBySymbol",
"outputs": [
{
"name": "",
"type": "address"
}
],
"payable": false,
"type": "function"
},
{
"constant": false,
"inputs": [
{
"name": "_token",
"type": "address"
},
{
"name": "_swarmHash",
"type": "bytes"
}
],
"name": "setTokenSwarmHash",
"outputs": [],
"payable": false,
"type": "function"
},
{
"constant": true,
"inputs": [
{
"name": "_token",
"type": "address"
}
],
"name": "getTokenMetaData",
"outputs": [
{
"name": "",
"type": "address"
},
{
"name": "",
"type": "string"
},
{
"name": "",
"type": "string"
},
{
"name": "",
"type": "uint8"
},
{
"name": "",
"type": "bytes"
},
{
"name": "",
"type": "bytes"
}
],
"payable": false,
"type": "function"
},
{
"constant": true,
"inputs": [],
"name": "owner",
"outputs": [
{
"name": "",
"type": "address"
}
],
"payable": false,
"type": "function"
},
{
"constant": false,
"inputs": [
{
"name": "_token",
"type": "address"
},
{
"name": "_name",
"type": "string"
},
{
"name": "_symbol",
"type": "string"
},
{
"name": "_decimals",
"type": "uint8"
},
{
"name": "_ipfsHash",
"type": "bytes"
},
{
"name": "_swarmHash",
"type": "bytes"
}
],
"name": "addToken",
"outputs": [],
"payable": false,
"type": "function"
},
{
"constant": false,
"inputs": [
{
"name": "_token",
"type": "address"
},
{
"name": "_name",
"type": "string"
}
],
"name": "setTokenName",
"outputs": [],
"payable": false,
"type": "function"
},
{
"constant": true,
"inputs": [
{
"name": "",
"type": "address"
}
],
"name": "tokens",
"outputs": [
{
"name": "token",
"type": "address"
},
{
"name": "name",
"type": "string"
},
{
"name": "symbol",
"type": "string"
},
{
"name": "decimals",
"type": "uint8"
},
{
"name": "ipfsHash",
"type": "bytes"
},
{
"name": "swarmHash",
"type": "bytes"
}
],
"payable": false,
"type": "function"
},
{
"constant": true,
"inputs": [
{
"name": "",
"type": "uint256"
}
],
"name": "tokenAddresses",
"outputs": [
{
"name": "",
"type": "address"
}
],
"payable": false,
"type": "function"
},
{
"constant": true,
"inputs": [
{
"name": "_name",
"type": "string"
}
],
"name": "getTokenByName",
"outputs": [
{
"name": "",
"type": "address"
},
{
"name": "",
"type": "string"
},
{
"name": "",
"type": "string"
},
{
"name": "",
"type": "uint8"
},
{
"name": "",
"type": "bytes"
},
{
"name": "",
"type": "bytes"
}
],
"payable": false,
"type": "function"
},
{
"constant": true,
"inputs": [],
"name": "getTokenAddresses",
"outputs": [
{
"name": "",
"type": "address[]"
}
],
"payable": false,
"type": "function"
},
{
"constant": false,
"inputs": [
{
"name": "_token",
"type": "address"
},
{
"name": "_ipfsHash",
"type": "bytes"
}
],
"name": "setTokenIpfsHash",
"outputs": [],
"payable": false,
"type": "function"
},
{
"constant": true,
"inputs": [
{
"name": "_symbol",
"type": "string"
}
],
"name": "getTokenBySymbol",
"outputs": [
{
"name": "",
"type": "address"
},
{
"name": "",
"type": "string"
},
{
"name": "",
"type": "string"
},
{
"name": "",
"type": "uint8"
},
{
"name": "",
"type": "bytes"
},
{
"name": "",
"type": "bytes"
}
],
"payable": false,
"type": "function"
},
{
"constant": false,
"inputs": [
{
"name": "_token",
"type": "address"
},
{
"name": "_symbol",
"type": "string"
}
],
"name": "setTokenSymbol",
"outputs": [],
"payable": false,
"type": "function"
},
{
"constant": false,
"inputs": [
{
"name": "newOwner",
"type": "address"
}
],
"name": "transferOwnership",
"outputs": [],
"payable": false,
"type": "function"
},
{
"anonymous": false,
"inputs": [
{
"indexed": true,
"name": "token",
"type": "address"
},
{
"indexed": false,
"name": "name",
"type": "string"
},
{
"indexed": false,
"name": "symbol",
"type": "string"
},
{
"indexed": false,
"name": "decimals",
"type": "uint8"
},
{
"indexed": false,
"name": "ipfsHash",
"type": "bytes"
},
{
"indexed": false,
"name": "swarmHash",
"type": "bytes"
}
],
"name": "LogAddToken",
"type": "event"
},
{
"anonymous": false,
"inputs": [
{
"indexed": true,
"name": "token",
"type": "address"
},
{
"indexed": false,
"name": "name",
"type": "string"
},
{
"indexed": false,
"name": "symbol",
"type": "string"
},
{
"indexed": false,
"name": "decimals",
"type": "uint8"
},
{
"indexed": false,
"name": "ipfsHash",
"type": "bytes"
},
{
"indexed": false,
"name": "swarmHash",
"type": "bytes"
}
],
"name": "LogRemoveToken",
"type": "event"
},
{
"anonymous": false,
"inputs": [
{
"indexed": true,
"name": "token",
"type": "address"
},
{
"indexed": false,
"name": "oldName",
"type": "string"
},
{
"indexed": false,
"name": "newName",
"type": "string"
}
],
"name": "LogTokenNameChange",
"type": "event"
},
{
"anonymous": false,
"inputs": [
{
"indexed": true,
"name": "token",
"type": "address"
},
{
"indexed": false,
"name": "oldSymbol",
"type": "string"
},
{
"indexed": false,
"name": "newSymbol",
"type": "string"
}
],
"name": "LogTokenSymbolChange",
"type": "event"
},
{
"anonymous": false,
"inputs": [
{
"indexed": true,
"name": "token",
"type": "address"
},
{
"indexed": false,
"name": "oldIpfsHash",
"type": "bytes"
},
{
"indexed": false,
"name": "newIpfsHash",
"type": "bytes"
}
],
"name": "LogTokenIpfsHashChange",
"type": "event"
},
{
"anonymous": false,
"inputs": [
{
"indexed": true,
"name": "token",
"type": "address"
},
{
"indexed": false,
"name": "oldSwarmHash",
"type": "bytes"
},
{
"indexed": false,
"name": "newSwarmHash",
"type": "bytes"
}
],
"name": "LogTokenSwarmHashChange",
"type": "event"
}
],
"networks": {
"1": {
"address": "0x926a74c5c36adf004c87399e65f75628b0f98d2c"
},
"3": {
"address": "0x6b1a50f0bb5a7995444bd3877b22dc89c62843ed"
},
"4": {
"address": "0x4e9aad8184de8833365fea970cd9149372fdf1e6"
},
"42": {
"address": "0xf18e504561f4347bea557f3d4558f559dddbae7f"
},
"50": {
"address": "0x0b1ba0af832d7c05fd64161e0db78e85978e8082"
}
}
}

View File

@ -0,0 +1,187 @@
{
"contract_name": "TokenTransferProxy",
"abi": [
{
"constant": false,
"inputs": [
{
"name": "token",
"type": "address"
},
{
"name": "from",
"type": "address"
},
{
"name": "to",
"type": "address"
},
{
"name": "value",
"type": "uint256"
}
],
"name": "transferFrom",
"outputs": [
{
"name": "",
"type": "bool"
}
],
"payable": false,
"type": "function"
},
{
"constant": false,
"inputs": [
{
"name": "target",
"type": "address"
}
],
"name": "addAuthorizedAddress",
"outputs": [],
"payable": false,
"type": "function"
},
{
"constant": true,
"inputs": [
{
"name": "",
"type": "uint256"
}
],
"name": "authorities",
"outputs": [
{
"name": "",
"type": "address"
}
],
"payable": false,
"type": "function"
},
{
"constant": false,
"inputs": [
{
"name": "target",
"type": "address"
}
],
"name": "removeAuthorizedAddress",
"outputs": [],
"payable": false,
"type": "function"
},
{
"constant": true,
"inputs": [],
"name": "owner",
"outputs": [
{
"name": "",
"type": "address"
}
],
"payable": false,
"type": "function"
},
{
"constant": true,
"inputs": [
{
"name": "",
"type": "address"
}
],
"name": "authorized",
"outputs": [
{
"name": "",
"type": "bool"
}
],
"payable": false,
"type": "function"
},
{
"constant": true,
"inputs": [],
"name": "getAuthorizedAddresses",
"outputs": [
{
"name": "",
"type": "address[]"
}
],
"payable": false,
"type": "function"
},
{
"constant": false,
"inputs": [
{
"name": "newOwner",
"type": "address"
}
],
"name": "transferOwnership",
"outputs": [],
"payable": false,
"type": "function"
},
{
"anonymous": false,
"inputs": [
{
"indexed": true,
"name": "target",
"type": "address"
},
{
"indexed": true,
"name": "caller",
"type": "address"
}
],
"name": "LogAuthorizedAddressAdded",
"type": "event"
},
{
"anonymous": false,
"inputs": [
{
"indexed": true,
"name": "target",
"type": "address"
},
{
"indexed": true,
"name": "caller",
"type": "address"
}
],
"name": "LogAuthorizedAddressRemoved",
"type": "event"
}
],
"networks": {
"1": {
"address": "0x8da0d80f5007ef1e431dd2127178d224e32c2ef4"
},
"3": {
"address": "0x4e9aad8184de8833365fea970cd9149372fdf1e6"
},
"4": {
"address": "0xa8e9fa8f91e5ae138c74648c9c304f1c75003a8d"
},
"42": {
"address": "0x087eed4bc1ee3de49befbd66c662b434b15d49d4"
},
"50": {
"address": "0x1dc4c1cefef38a777b15aa20260a54e584b16c48"
}
}
}

View File

@ -0,0 +1,20 @@
{
"contract_name": "ZRX",
"networks": {
"1": {
"address": "0xe41d2489571d322189246dafa5ebde1f4699f498"
},
"3": {
"address": "0xa8e9fa8f91e5ae138c74648c9c304f1c75003a8d"
},
"4": {
"address": "0x00f58d6d585f84b2d7267940cede30ce2fe6eae8"
},
"42": {
"address": "0x6ff6c0ff1d68b964901f986d4c9fa3ac68346570"
},
"50": {
"address": "0x1d7022f5b17d2f8b695918fb48fa1089c9f85401"
}
}
}

View File

@ -0,0 +1,136 @@
import { schemas, SchemaValidator } from '@0xproject/json-schemas';
import {
generatePseudoRandomSalt,
getOrderHashHex,
isValidOrderHash,
isValidSignature,
signOrderHashAsync,
} from '@0xproject/order-utils';
import { ECSignature, Order, Provider, SignedOrder, TransactionReceiptWithDecodedLogs } from '@0xproject/types';
import { AbiDecoder, BigNumber, intervalUtils } from '@0xproject/utils';
import { Web3Wrapper } from '@0xproject/web3-wrapper';
import * as ethUtil from 'ethereumjs-util';
import * as _ from 'lodash';
import { artifacts } from './artifacts';
import { EtherTokenWrapper } from './contract_wrappers/ether_token_wrapper';
import { ExchangeWrapper } from './contract_wrappers/exchange_wrapper';
import { TokenRegistryWrapper } from './contract_wrappers/token_registry_wrapper';
import { TokenTransferProxyWrapper } from './contract_wrappers/token_transfer_proxy_wrapper';
import { TokenWrapper } from './contract_wrappers/token_wrapper';
import { zeroExContractConfigSchema } from './schemas/zero_ex_contract_config_schema';
import { zeroExContractPrivateNetworkConfigSchema } from './schemas/zero_ex_contract_private_network_config_schema';
import { zeroExContractPublicNetworkConfigSchema } from './schemas/zero_ex_contract_public_network_config_schema';
import { ZeroExContractConfig } from './types';
import { assert } from './utils/assert';
import { constants } from './utils/constants';
import { decorators } from './utils/decorators';
import { utils } from './utils/utils';
/**
* The ContractWrappers class contains smart contract wrappers helpful when building on 0x protocol.
*/
export class ContractWrappers {
/**
* An instance of the ExchangeWrapper class containing methods for interacting with the 0x Exchange smart contract.
*/
public exchange: ExchangeWrapper;
/**
* An instance of the TokenRegistryWrapper class containing methods for interacting with the 0x
* TokenRegistry smart contract.
*/
public tokenRegistry: TokenRegistryWrapper;
/**
* An instance of the TokenWrapper class containing methods for interacting with any ERC20 token smart contract.
*/
public token: TokenWrapper;
/**
* An instance of the EtherTokenWrapper class containing methods for interacting with the
* wrapped ETH ERC20 token smart contract.
*/
public etherToken: EtherTokenWrapper;
/**
* An instance of the TokenTransferProxyWrapper class containing methods for interacting with the
* tokenTransferProxy smart contract.
*/
public proxy: TokenTransferProxyWrapper;
private _web3Wrapper: Web3Wrapper;
/**
* Instantiates a new ContractWrappers instance.
* @param provider The Provider instance you would like the 0x.js library to use for interacting with
* the Ethereum network.
* @param config The configuration object. Look up the type for the description.
* @return An instance of the ContractWrappers class.
*/
constructor(provider: Provider, config: ZeroExContractConfig) {
assert.isWeb3Provider('provider', provider);
assert.doesConformToSchema('config', config, zeroExContractConfigSchema, [
zeroExContractPrivateNetworkConfigSchema,
zeroExContractPublicNetworkConfigSchema,
]);
const artifactJSONs = _.values(artifacts);
const abiArrays = _.map(artifactJSONs, artifact => artifact.abi);
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.proxy);
this.exchange = new ExchangeWrapper(
this._web3Wrapper,
config.networkId,
this.token,
config.exchangeContractAddress,
config.zrxContractAddress,
);
this.tokenRegistry = new TokenRegistryWrapper(
this._web3Wrapper,
config.networkId,
config.tokenRegistryContractAddress,
);
this.etherToken = new EtherTokenWrapper(this._web3Wrapper, config.networkId, this.token);
}
/**
* Sets a new web3 provider for 0x.js. Updating the provider will stop all
* subscriptions so you will need to re-subscribe to all events relevant to your app after this call.
* @param provider The Web3Provider you would like the 0x.js library to use from now on.
* @param networkId The id of the network your provider is connected to
*/
public setProvider(provider: Provider, networkId: number): void {
this._web3Wrapper.setProvider(provider);
(this.exchange as any)._invalidateContractInstances();
(this.exchange as any)._setNetworkId(networkId);
(this.tokenRegistry as any)._invalidateContractInstance();
(this.tokenRegistry as any)._setNetworkId(networkId);
(this.token as any)._invalidateContractInstances();
(this.token as any)._setNetworkId(networkId);
(this.proxy as any)._invalidateContractInstance();
(this.proxy as any)._setNetworkId(networkId);
(this.etherToken as any)._invalidateContractInstance();
(this.etherToken as any)._setNetworkId(networkId);
}
/**
* Get the provider instance currently used by 0x.js
* @return Web3 provider instance
*/
public getProvider(): Provider {
return this._web3Wrapper.getProvider();
}
/*
* HACK: `TokenWrapper` needs a token transfer proxy address. `TokenTransferProxy` address is fetched from
* an `ExchangeWrapper`. `ExchangeWrapper` needs `TokenWrapper` to validate orders, creating a dependency cycle.
* In order to break this - we create this function here and pass it as a parameter to the `TokenWrapper`
* and `ProxyWrapper`.
*/
private async _getTokenTransferProxyAddressAsync(): Promise<string> {
const tokenTransferProxyAddress = await (this.exchange as any)._getTokenTransferProxyAddressAsync();
return tokenTransferProxyAddress;
}
}

View File

@ -1,32 +1,38 @@
import { BlockParamLiteral, ContractAbi, FilterObject, LogEntry, LogWithDecodedArgs, RawLog } from '@0xproject/types'; import {
Artifact,
BlockParamLiteral,
ContractAbi,
FilterObject,
LogEntry,
LogWithDecodedArgs,
RawLog,
} from '@0xproject/types';
import { AbiDecoder, intervalUtils } from '@0xproject/utils'; import { AbiDecoder, intervalUtils } from '@0xproject/utils';
import { Web3Wrapper } from '@0xproject/web3-wrapper'; import { Web3Wrapper } from '@0xproject/web3-wrapper';
import { Block, BlockAndLogStreamer } from 'ethereumjs-blockstream'; import { Block, BlockAndLogStreamer } from 'ethereumjs-blockstream';
import * as _ from 'lodash'; import * as _ from 'lodash';
import * as Web3 from 'web3';
import { import {
Artifact,
BlockRange, BlockRange,
ContractEventArgs, ContractEventArgs,
ContractEvents, ContractEvents,
ContractWrappersError,
EventCallback, EventCallback,
IndexedFilterValues, IndexedFilterValues,
InternalZeroExError, InternalContractWrappersError,
ZeroExError,
} from '../types'; } from '../types';
import { constants } from '../utils/constants'; import { constants } from '../utils/constants';
import { filterUtils } from '../utils/filter_utils'; import { filterUtils } from '../utils/filter_utils';
const CONTRACT_NAME_TO_NOT_FOUND_ERROR: { const CONTRACT_NAME_TO_NOT_FOUND_ERROR: {
[contractName: string]: ZeroExError; [contractName: string]: ContractWrappersError;
} = { } = {
ZRX: ZeroExError.ZRXContractDoesNotExist, ZRX: ContractWrappersError.ZRXContractDoesNotExist,
EtherToken: ZeroExError.EtherTokenContractDoesNotExist, EtherToken: ContractWrappersError.EtherTokenContractDoesNotExist,
Token: ZeroExError.TokenContractDoesNotExist, Token: ContractWrappersError.TokenContractDoesNotExist,
TokenRegistry: ZeroExError.TokenRegistryContractDoesNotExist, TokenRegistry: ContractWrappersError.TokenRegistryContractDoesNotExist,
TokenTransferProxy: ZeroExError.TokenTransferProxyContractDoesNotExist, TokenTransferProxy: ContractWrappersError.TokenTransferProxyContractDoesNotExist,
Exchange: ZeroExError.ExchangeContractDoesNotExist, Exchange: ContractWrappersError.ExchangeContractDoesNotExist,
}; };
export class ContractWrapper { export class ContractWrapper {
@ -57,7 +63,7 @@ export class ContractWrapper {
} }
protected _unsubscribe(filterToken: string, err?: Error): void { protected _unsubscribe(filterToken: string, err?: Error): void {
if (_.isUndefined(this._filters[filterToken])) { if (_.isUndefined(this._filters[filterToken])) {
throw new Error(ZeroExError.SubscriptionNotFound); throw new Error(ContractWrappersError.SubscriptionNotFound);
} }
if (!_.isUndefined(err)) { if (!_.isUndefined(err)) {
const callback = this._filterCallbacks[filterToken]; const callback = this._filterCallbacks[filterToken];
@ -101,7 +107,7 @@ export class ContractWrapper {
log: LogEntry, log: LogEntry,
): LogWithDecodedArgs<ArgsType> | RawLog { ): LogWithDecodedArgs<ArgsType> | RawLog {
if (_.isUndefined(this._web3Wrapper.abiDecoder)) { if (_.isUndefined(this._web3Wrapper.abiDecoder)) {
throw new Error(InternalZeroExError.NoAbiDecoder); throw new Error(InternalContractWrappersError.NoAbiDecoder);
} }
const logWithDecodedArgs = this._web3Wrapper.abiDecoder.tryToDecodeLogOrNoop(log); const logWithDecodedArgs = this._web3Wrapper.abiDecoder.tryToDecodeLogOrNoop(log);
return logWithDecodedArgs; return logWithDecodedArgs;
@ -113,7 +119,7 @@ export class ContractWrapper {
let contractAddress: string; let contractAddress: string;
if (_.isUndefined(addressIfExists)) { if (_.isUndefined(addressIfExists)) {
if (_.isUndefined(artifact.networks[this._networkId])) { if (_.isUndefined(artifact.networks[this._networkId])) {
throw new Error(ZeroExError.ContractNotDeployedOnNetwork); throw new Error(ContractWrappersError.ContractNotDeployedOnNetwork);
} }
contractAddress = artifact.networks[this._networkId].address.toLowerCase(); contractAddress = artifact.networks[this._networkId].address.toLowerCase();
} else { } else {
@ -130,7 +136,7 @@ export class ContractWrapper {
if (_.isUndefined(addressIfExists)) { if (_.isUndefined(addressIfExists)) {
const contractAddress = artifact.networks[this._networkId].address; const contractAddress = artifact.networks[this._networkId].address;
if (_.isUndefined(contractAddress)) { if (_.isUndefined(contractAddress)) {
throw new Error(ZeroExError.ExchangeContractDoesNotExist); throw new Error(ContractWrappersError.ExchangeContractDoesNotExist);
} }
return contractAddress; return contractAddress;
} else { } else {
@ -151,7 +157,7 @@ export class ContractWrapper {
} }
private _startBlockAndLogStream(): void { private _startBlockAndLogStream(): void {
if (!_.isUndefined(this._blockAndLogStreamerIfExists)) { if (!_.isUndefined(this._blockAndLogStreamerIfExists)) {
throw new Error(ZeroExError.SubscriptionAlreadyPresent); throw new Error(ContractWrappersError.SubscriptionAlreadyPresent);
} }
this._blockAndLogStreamerIfExists = new BlockAndLogStreamer( this._blockAndLogStreamerIfExists = new BlockAndLogStreamer(
this._web3Wrapper.getBlockAsync.bind(this._web3Wrapper), this._web3Wrapper.getBlockAsync.bind(this._web3Wrapper),
@ -184,7 +190,7 @@ export class ContractWrapper {
} }
private _stopBlockAndLogStream(): void { private _stopBlockAndLogStream(): void {
if (_.isUndefined(this._blockAndLogStreamerIfExists)) { if (_.isUndefined(this._blockAndLogStreamerIfExists)) {
throw new Error(ZeroExError.SubscriptionNotFound); throw new Error(ContractWrappersError.SubscriptionNotFound);
} }
this._blockAndLogStreamerIfExists.unsubscribeFromOnLogAdded(this._onLogAddedSubscriptionToken as string); this._blockAndLogStreamerIfExists.unsubscribeFromOnLogAdded(this._onLogAddedSubscriptionToken as string);
this._blockAndLogStreamerIfExists.unsubscribeFromOnLogRemoved(this._onLogRemovedSubscriptionToken as string); this._blockAndLogStreamerIfExists.unsubscribeFromOnLogRemoved(this._onLogRemovedSubscriptionToken as string);

View File

@ -5,7 +5,7 @@ import { Web3Wrapper } from '@0xproject/web3-wrapper';
import * as _ from 'lodash'; import * as _ from 'lodash';
import { artifacts } from '../artifacts'; import { artifacts } from '../artifacts';
import { BlockRange, EventCallback, IndexedFilterValues, TransactionOpts, ZeroExError } from '../types'; import { BlockRange, ContractWrappersError, EventCallback, IndexedFilterValues, TransactionOpts } from '../types';
import { assert } from '../utils/assert'; import { assert } from '../utils/assert';
import { ContractWrapper } from './contract_wrapper'; import { ContractWrapper } from './contract_wrapper';
@ -48,7 +48,7 @@ export class EtherTokenWrapper extends ContractWrapper {
const normalizedDepositorAddress = depositor.toLowerCase(); const normalizedDepositorAddress = depositor.toLowerCase();
const ethBalanceInWei = await this._web3Wrapper.getBalanceInWeiAsync(normalizedDepositorAddress); const ethBalanceInWei = await this._web3Wrapper.getBalanceInWeiAsync(normalizedDepositorAddress);
assert.assert(ethBalanceInWei.gte(amountInWei), ZeroExError.InsufficientEthBalanceForDeposit); assert.assert(ethBalanceInWei.gte(amountInWei), ContractWrappersError.InsufficientEthBalanceForDeposit);
const wethContract = await this._getEtherTokenContractAsync(normalizedEtherTokenAddress); const wethContract = await this._getEtherTokenContractAsync(normalizedEtherTokenAddress);
const txHash = await wethContract.deposit.sendTransactionAsync({ const txHash = await wethContract.deposit.sendTransactionAsync({
@ -84,7 +84,10 @@ export class EtherTokenWrapper extends ContractWrapper {
normalizedEtherTokenAddress, normalizedEtherTokenAddress,
normalizedWithdrawerAddress, normalizedWithdrawerAddress,
); );
assert.assert(WETHBalanceInBaseUnits.gte(amountInWei), ZeroExError.InsufficientWEthBalanceForWithdrawal); assert.assert(
WETHBalanceInBaseUnits.gte(amountInWei),
ContractWrappersError.InsufficientWEthBalanceForWithdrawal,
);
const wethContract = await this._getEtherTokenContractAsync(normalizedEtherTokenAddress); const wethContract = await this._getEtherTokenContractAsync(normalizedEtherTokenAddress);
const txHash = await wethContract.withdraw.sendTransactionAsync(amountInWei, { const txHash = await wethContract.withdraw.sendTransactionAsync(amountInWei, {
@ -119,7 +122,7 @@ export class EtherTokenWrapper extends ContractWrapper {
eventName, eventName,
blockRange, blockRange,
indexFilterValues, indexFilterValues,
artifacts.EtherTokenArtifact.abi, artifacts.EtherToken.abi,
); );
return logs; return logs;
} }
@ -147,7 +150,7 @@ export class EtherTokenWrapper extends ContractWrapper {
normalizedEtherTokenAddress, normalizedEtherTokenAddress,
eventName, eventName,
indexFilterValues, indexFilterValues,
artifacts.EtherTokenArtifact.abi, artifacts.EtherToken.abi,
callback, callback,
); );
return subscriptionToken; return subscriptionToken;
@ -172,7 +175,7 @@ export class EtherTokenWrapper extends ContractWrapper {
* @returns The Ethereum address of the EtherToken contract or undefined. * @returns The Ethereum address of the EtherToken contract or undefined.
*/ */
public getContractAddressIfExists(): string | undefined { public getContractAddressIfExists(): string | undefined {
const networkSpecificArtifact = artifacts.EtherTokenArtifact.networks[this._networkId]; const networkSpecificArtifact = artifacts.EtherToken.networks[this._networkId];
const contractAddressIfExists = _.isUndefined(networkSpecificArtifact) const contractAddressIfExists = _.isUndefined(networkSpecificArtifact)
? undefined ? undefined
: networkSpecificArtifact.address; : networkSpecificArtifact.address;
@ -188,7 +191,7 @@ export class EtherTokenWrapper extends ContractWrapper {
return etherTokenContract; return etherTokenContract;
} }
const [abi, address] = await this._getContractAbiAndAddressFromArtifactsAsync( const [abi, address] = await this._getContractAbiAndAddressFromArtifactsAsync(
artifacts.EtherTokenArtifact, artifacts.EtherToken,
etherTokenAddress, etherTokenAddress,
); );
const contractInstance = new EtherTokenContract( const contractInstance = new EtherTokenContract(

View File

@ -1,12 +1,16 @@
import { schemas } from '@0xproject/json-schemas'; import { schemas } from '@0xproject/json-schemas';
import { getOrderHashHex } from '@0xproject/order-utils'; import { formatters, getOrderHashHex, OrderStateUtils } from '@0xproject/order-utils';
import { import {
BlockParamLiteral, BlockParamLiteral,
DecodedLogArgs, DecodedLogArgs,
ECSignature, ECSignature,
ExchangeContractErrs,
LogEntry, LogEntry,
LogWithDecodedArgs, LogWithDecodedArgs,
Order, Order,
OrderAddresses,
OrderState,
OrderValues,
SignedOrder, SignedOrder,
} from '@0xproject/types'; } from '@0xproject/types';
import { AbiDecoder, BigNumber } from '@0xproject/utils'; import { AbiDecoder, BigNumber } from '@0xproject/utils';
@ -20,21 +24,16 @@ import {
BlockRange, BlockRange,
EventCallback, EventCallback,
ExchangeContractErrCodes, ExchangeContractErrCodes,
ExchangeContractErrs,
IndexedFilterValues, IndexedFilterValues,
MethodOpts, MethodOpts,
OrderAddresses,
OrderCancellationRequest, OrderCancellationRequest,
OrderFillRequest, OrderFillRequest,
OrderState,
OrderTransactionOpts, OrderTransactionOpts,
OrderValues,
ValidateOrderFillableOpts, ValidateOrderFillableOpts,
} from '../types'; } from '../types';
import { assert } from '../utils/assert'; import { assert } from '../utils/assert';
import { decorators } from '../utils/decorators'; import { decorators } from '../utils/decorators';
import { ExchangeTransferSimulator } from '../utils/exchange_transfer_simulator'; import { ExchangeTransferSimulator } from '../utils/exchange_transfer_simulator';
import { OrderStateUtils } from '../utils/order_state_utils';
import { OrderValidationUtils } from '../utils/order_validation_utils'; import { OrderValidationUtils } from '../utils/order_validation_utils';
import { utils } from '../utils/utils'; import { utils } from '../utils/utils';
@ -70,24 +69,6 @@ export class ExchangeWrapper extends ContractWrapper {
}; };
private _contractAddressIfExists?: string; private _contractAddressIfExists?: string;
private _zrxContractAddressIfExists?: string; private _zrxContractAddressIfExists?: string;
private static _getOrderAddressesAndValues(order: Order): [OrderAddresses, OrderValues] {
const orderAddresses: OrderAddresses = [
order.maker,
order.taker,
order.makerTokenAddress,
order.takerTokenAddress,
order.feeRecipient,
];
const orderValues: OrderValues = [
order.makerTokenAmount,
order.takerTokenAmount,
order.makerFee,
order.takerFee,
order.expirationUnixTimestampSec,
order.salt,
];
return [orderAddresses, orderValues];
}
constructor( constructor(
web3Wrapper: Web3Wrapper, web3Wrapper: Web3Wrapper,
networkId: number, networkId: number,
@ -209,7 +190,7 @@ export class ExchangeWrapper extends ContractWrapper {
); );
} }
const [orderAddresses, orderValues] = ExchangeWrapper._getOrderAddressesAndValues(signedOrder); const [orderAddresses, orderValues] = formatters.getOrderAddressesAndValues(signedOrder);
const txHash: string = await exchangeInstance.fillOrder.sendTransactionAsync( const txHash: string = await exchangeInstance.fillOrder.sendTransactionAsync(
orderAddresses, orderAddresses,
@ -296,7 +277,7 @@ export class ExchangeWrapper extends ContractWrapper {
const orderAddressesValuesAndSignatureArray = _.map(signedOrders, signedOrder => { const orderAddressesValuesAndSignatureArray = _.map(signedOrders, signedOrder => {
return [ return [
...ExchangeWrapper._getOrderAddressesAndValues(signedOrder), ...formatters.getOrderAddressesAndValues(signedOrder),
signedOrder.ecSignature.v, signedOrder.ecSignature.v,
signedOrder.ecSignature.r, signedOrder.ecSignature.r,
signedOrder.ecSignature.s, signedOrder.ecSignature.s,
@ -384,7 +365,7 @@ export class ExchangeWrapper extends ContractWrapper {
const orderAddressesValuesAmountsAndSignatureArray = _.map(orderFillRequests, orderFillRequest => { const orderAddressesValuesAmountsAndSignatureArray = _.map(orderFillRequests, orderFillRequest => {
return [ return [
...ExchangeWrapper._getOrderAddressesAndValues(orderFillRequest.signedOrder), ...formatters.getOrderAddressesAndValues(orderFillRequest.signedOrder),
orderFillRequest.takerTokenFillAmount, orderFillRequest.takerTokenFillAmount,
orderFillRequest.signedOrder.ecSignature.v, orderFillRequest.signedOrder.ecSignature.v,
orderFillRequest.signedOrder.ecSignature.r, orderFillRequest.signedOrder.ecSignature.r,
@ -453,7 +434,7 @@ export class ExchangeWrapper extends ContractWrapper {
); );
} }
const [orderAddresses, orderValues] = ExchangeWrapper._getOrderAddressesAndValues(signedOrder); const [orderAddresses, orderValues] = formatters.getOrderAddressesAndValues(signedOrder);
const txHash = await exchangeInstance.fillOrKillOrder.sendTransactionAsync( const txHash = await exchangeInstance.fillOrKillOrder.sendTransactionAsync(
orderAddresses, orderAddresses,
orderValues, orderValues,
@ -519,7 +500,7 @@ export class ExchangeWrapper extends ContractWrapper {
const orderAddressesValuesAndTakerTokenFillAmounts = _.map(orderFillRequests, request => { const orderAddressesValuesAndTakerTokenFillAmounts = _.map(orderFillRequests, request => {
return [ return [
...ExchangeWrapper._getOrderAddressesAndValues(request.signedOrder), ...formatters.getOrderAddressesAndValues(request.signedOrder),
request.takerTokenFillAmount, request.takerTokenFillAmount,
request.signedOrder.ecSignature.v, request.signedOrder.ecSignature.v,
request.signedOrder.ecSignature.r, request.signedOrder.ecSignature.r,
@ -580,7 +561,7 @@ export class ExchangeWrapper extends ContractWrapper {
); );
} }
const [orderAddresses, orderValues] = ExchangeWrapper._getOrderAddressesAndValues(order); const [orderAddresses, orderValues] = formatters.getOrderAddressesAndValues(order);
const txHash = await exchangeInstance.cancelOrder.sendTransactionAsync( const txHash = await exchangeInstance.cancelOrder.sendTransactionAsync(
orderAddresses, orderAddresses,
orderValues, orderValues,
@ -645,7 +626,7 @@ export class ExchangeWrapper extends ContractWrapper {
const exchangeInstance = await this._getExchangeContractAsync(); const exchangeInstance = await this._getExchangeContractAsync();
const orderAddressesValuesAndTakerTokenCancelAmounts = _.map(orderCancellationRequests, cancellationRequest => { const orderAddressesValuesAndTakerTokenCancelAmounts = _.map(orderCancellationRequests, cancellationRequest => {
return [ return [
...ExchangeWrapper._getOrderAddressesAndValues(cancellationRequest.order), ...formatters.getOrderAddressesAndValues(cancellationRequest.order),
cancellationRequest.takerTokenCancelAmount, cancellationRequest.takerTokenCancelAmount,
]; ];
}); });
@ -686,7 +667,7 @@ export class ExchangeWrapper extends ContractWrapper {
exchangeContractAddress, exchangeContractAddress,
eventName, eventName,
indexFilterValues, indexFilterValues,
artifacts.ExchangeArtifact.abi, artifacts.Exchange.abi,
callback, callback,
); );
return subscriptionToken; return subscriptionToken;
@ -726,7 +707,7 @@ export class ExchangeWrapper extends ContractWrapper {
eventName, eventName,
blockRange, blockRange,
indexFilterValues, indexFilterValues,
artifacts.ExchangeArtifact.abi, artifacts.Exchange.abi,
); );
return logs; return logs;
} }
@ -736,7 +717,7 @@ export class ExchangeWrapper extends ContractWrapper {
* @returns The Ethereum address of the Exchange contract being used. * @returns The Ethereum address of the Exchange contract being used.
*/ */
public getContractAddress(): string { public getContractAddress(): string {
const contractAddress = this._getContractAddress(artifacts.ExchangeArtifact, this._contractAddressIfExists); const contractAddress = this._getContractAddress(artifacts.Exchange, this._contractAddressIfExists);
return contractAddress; return contractAddress;
} }
/** /**
@ -904,7 +885,7 @@ export class ExchangeWrapper extends ContractWrapper {
* @return Address of ZRX token * @return Address of ZRX token
*/ */
public getZRXTokenAddress(): string { public getZRXTokenAddress(): string {
const contractAddress = this._getContractAddress(artifacts.ZRXArtifact, this._zrxContractAddressIfExists); const contractAddress = this._getContractAddress(artifacts.ZRX, this._zrxContractAddressIfExists);
return contractAddress; return contractAddress;
} }
private _invalidateContractInstances(): void { private _invalidateContractInstances(): void {
@ -934,7 +915,7 @@ export class ExchangeWrapper extends ContractWrapper {
} }
private async _getOrderHashHexUsingContractCallAsync(order: Order | SignedOrder): Promise<string> { private async _getOrderHashHexUsingContractCallAsync(order: Order | SignedOrder): Promise<string> {
const exchangeInstance = await this._getExchangeContractAsync(); const exchangeInstance = await this._getExchangeContractAsync();
const [orderAddresses, orderValues] = ExchangeWrapper._getOrderAddressesAndValues(order); const [orderAddresses, orderValues] = formatters.getOrderAddressesAndValues(order);
const orderHashHex = await exchangeInstance.getOrderHash.callAsync(orderAddresses, orderValues); const orderHashHex = await exchangeInstance.getOrderHash.callAsync(orderAddresses, orderValues);
return orderHashHex; return orderHashHex;
} }
@ -943,7 +924,7 @@ export class ExchangeWrapper extends ContractWrapper {
return this._exchangeContractIfExists; return this._exchangeContractIfExists;
} }
const [abi, address] = await this._getContractAbiAndAddressFromArtifactsAsync( const [abi, address] = await this._getContractAbiAndAddressFromArtifactsAsync(
artifacts.ExchangeArtifact, artifacts.Exchange,
this._contractAddressIfExists, this._contractAddressIfExists,
); );
const contractInstance = new ExchangeContract( const contractInstance = new ExchangeContract(

View File

@ -0,0 +1,84 @@
/**
* This file is auto-generated using abi-gen. Don't edit directly.
* Templates can be found at https://github.com/0xProject/0x-monorepo/tree/development/packages/contract_templates.
*/
// tslint:disable:no-consecutive-blank-lines
// tslint:disable-next-line:no-unused-variable
import { BaseContract } from '@0xproject/base-contract';
import {
BlockParam,
BlockParamLiteral,
CallData,
ContractAbi,
DataItem,
MethodAbi,
Provider,
TxData,
TxDataPayable,
} from '@0xproject/types';
import { BigNumber, classUtils, promisify } from '@0xproject/utils';
import { Web3Wrapper } from '@0xproject/web3-wrapper';
import * as ethers from 'ethers';
import * as _ from 'lodash';
// tslint:disable:no-parameter-reassignment
export class DummyTokenContract extends BaseContract {
public setBalance = {
async sendTransactionAsync(_target: string, _value: BigNumber, txData: Partial<TxData> = {}): Promise<string> {
const self = (this as any) as DummyTokenContract;
const inputAbi = self._lookupAbi('setBalance(address,uint256)').inputs;
[_target, _value] = BaseContract._formatABIDataItemList(
inputAbi,
[_target, _value],
BaseContract._bigNumberToString.bind(self),
);
const encodedData = self
._lookupEthersInterface('setBalance(address,uint256)')
.functions.setBalance(_target, _value).data;
const txDataWithDefaults = await self._applyDefaultsToTxDataAsync(
{
...txData,
data: encodedData,
},
self.setBalance.estimateGasAsync.bind(self, _target, _value),
);
const txHash = await self._web3Wrapper.sendTransactionAsync(txDataWithDefaults);
return txHash;
},
async estimateGasAsync(_target: string, _value: BigNumber, txData: Partial<TxData> = {}): Promise<number> {
const self = (this as any) as DummyTokenContract;
const inputAbi = self._lookupAbi('setBalance(address,uint256)').inputs;
[_target, _value] = BaseContract._formatABIDataItemList(
inputAbi,
[_target, _value],
BaseContract._bigNumberToString.bind(this),
);
const encodedData = self
._lookupEthersInterface('setBalance(address,uint256)')
.functions.setBalance(_target, _value).data;
const txDataWithDefaults = await self._applyDefaultsToTxDataAsync({
...txData,
data: encodedData,
});
const gas = await self._web3Wrapper.estimateGasAsync(txDataWithDefaults);
return gas;
},
getABIEncodedTransactionData(_target: string, _value: BigNumber): string {
const self = (this as any) as DummyTokenContract;
const inputAbi = self._lookupAbi('setBalance(address,uint256)').inputs;
[_target, _value] = BaseContract._formatABIDataItemList(
inputAbi,
[_target, _value],
BaseContract._bigNumberToString.bind(self),
);
const abiEncodedTransactionData = self
._lookupEthersInterface('setBalance(address,uint256)')
.functions.setBalance(_target, _value).data;
return abiEncodedTransactionData;
},
};
constructor(abi: ContractAbi, address: string, provider: Provider, defaults?: Partial<TxData>) {
super(abi, address, provider, defaults);
classUtils.bindAll(this, ['_ethersInterfacesByFunctionSignature', 'address', 'abi', '_web3Wrapper']);
}
} // tslint:disable:max-file-line-count

View File

@ -0,0 +1,621 @@
/**
* This file is auto-generated using abi-gen. Don't edit directly.
* Templates can be found at https://github.com/0xProject/0x-monorepo/tree/development/packages/contract_templates.
*/
// tslint:disable:no-consecutive-blank-lines
// tslint:disable-next-line:no-unused-variable
import { BaseContract } from '@0xproject/base-contract';
import {
BlockParam,
BlockParamLiteral,
CallData,
ContractAbi,
DataItem,
MethodAbi,
Provider,
TxData,
TxDataPayable,
} from '@0xproject/types';
import { BigNumber, classUtils, promisify } from '@0xproject/utils';
import { Web3Wrapper } from '@0xproject/web3-wrapper';
import * as ethers from 'ethers';
import * as _ from 'lodash';
export type EtherTokenContractEventArgs =
| TransferContractEventArgs
| ApprovalContractEventArgs
| DepositContractEventArgs
| WithdrawalContractEventArgs;
export enum EtherTokenEvents {
Transfer = 'Transfer',
Approval = 'Approval',
Deposit = 'Deposit',
Withdrawal = 'Withdrawal',
}
export interface TransferContractEventArgs {
_from: string;
_to: string;
_value: BigNumber;
}
export interface ApprovalContractEventArgs {
_owner: string;
_spender: string;
_value: BigNumber;
}
export interface DepositContractEventArgs {
_owner: string;
_value: BigNumber;
}
export interface WithdrawalContractEventArgs {
_owner: string;
_value: BigNumber;
}
// tslint:disable:no-parameter-reassignment
export class EtherTokenContract extends BaseContract {
public name = {
async callAsync(callData: Partial<CallData> = {}, defaultBlock?: BlockParam): Promise<string> {
const self = (this as any) as EtherTokenContract;
const functionSignature = 'name()';
const inputAbi = self._lookupAbi(functionSignature).inputs;
[] = BaseContract._formatABIDataItemList(inputAbi, [], BaseContract._bigNumberToString.bind(self));
const ethersFunction = self
._lookupEthersInterface(functionSignature)
.functions.name() as ethers.CallDescription;
const encodedData = ethersFunction.data;
const callDataWithDefaults = await self._applyDefaultsToTxDataAsync({
data: encodedData,
});
const rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock);
let resultArray = ethersFunction.parse(rawCallResult);
const outputAbi = (_.find(self.abi, { name: 'name' }) as MethodAbi).outputs;
resultArray = BaseContract._formatABIDataItemList(
outputAbi,
resultArray,
BaseContract._lowercaseAddress.bind(this),
);
resultArray = BaseContract._formatABIDataItemList(
outputAbi,
resultArray,
BaseContract._bnToBigNumber.bind(this),
);
return resultArray[0];
},
};
public approve = {
async sendTransactionAsync(_spender: string, _value: BigNumber, txData: Partial<TxData> = {}): Promise<string> {
const self = (this as any) as EtherTokenContract;
const inputAbi = self._lookupAbi('approve(address,uint256)').inputs;
[_spender, _value] = BaseContract._formatABIDataItemList(
inputAbi,
[_spender, _value],
BaseContract._bigNumberToString.bind(self),
);
const encodedData = self
._lookupEthersInterface('approve(address,uint256)')
.functions.approve(_spender, _value).data;
const txDataWithDefaults = await self._applyDefaultsToTxDataAsync(
{
...txData,
data: encodedData,
},
self.approve.estimateGasAsync.bind(self, _spender, _value),
);
const txHash = await self._web3Wrapper.sendTransactionAsync(txDataWithDefaults);
return txHash;
},
async estimateGasAsync(_spender: string, _value: BigNumber, txData: Partial<TxData> = {}): Promise<number> {
const self = (this as any) as EtherTokenContract;
const inputAbi = self._lookupAbi('approve(address,uint256)').inputs;
[_spender, _value] = BaseContract._formatABIDataItemList(
inputAbi,
[_spender, _value],
BaseContract._bigNumberToString.bind(this),
);
const encodedData = self
._lookupEthersInterface('approve(address,uint256)')
.functions.approve(_spender, _value).data;
const txDataWithDefaults = await self._applyDefaultsToTxDataAsync({
...txData,
data: encodedData,
});
const gas = await self._web3Wrapper.estimateGasAsync(txDataWithDefaults);
return gas;
},
getABIEncodedTransactionData(_spender: string, _value: BigNumber): string {
const self = (this as any) as EtherTokenContract;
const inputAbi = self._lookupAbi('approve(address,uint256)').inputs;
[_spender, _value] = BaseContract._formatABIDataItemList(
inputAbi,
[_spender, _value],
BaseContract._bigNumberToString.bind(self),
);
const abiEncodedTransactionData = self
._lookupEthersInterface('approve(address,uint256)')
.functions.approve(_spender, _value).data;
return abiEncodedTransactionData;
},
async callAsync(
_spender: string,
_value: BigNumber,
callData: Partial<CallData> = {},
defaultBlock?: BlockParam,
): Promise<boolean> {
const self = (this as any) as EtherTokenContract;
const functionSignature = 'approve(address,uint256)';
const inputAbi = self._lookupAbi(functionSignature).inputs;
[_spender, _value] = BaseContract._formatABIDataItemList(
inputAbi,
[_spender, _value],
BaseContract._bigNumberToString.bind(self),
);
const ethersFunction = self
._lookupEthersInterface(functionSignature)
.functions.approve(_spender, _value) as ethers.CallDescription;
const encodedData = ethersFunction.data;
const callDataWithDefaults = await self._applyDefaultsToTxDataAsync({
data: encodedData,
});
const rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock);
let resultArray = ethersFunction.parse(rawCallResult);
const outputAbi = (_.find(self.abi, { name: 'approve' }) as MethodAbi).outputs;
resultArray = BaseContract._formatABIDataItemList(
outputAbi,
resultArray,
BaseContract._lowercaseAddress.bind(this),
);
resultArray = BaseContract._formatABIDataItemList(
outputAbi,
resultArray,
BaseContract._bnToBigNumber.bind(this),
);
return resultArray[0];
},
};
public totalSupply = {
async callAsync(callData: Partial<CallData> = {}, defaultBlock?: BlockParam): Promise<BigNumber> {
const self = (this as any) as EtherTokenContract;
const functionSignature = 'totalSupply()';
const inputAbi = self._lookupAbi(functionSignature).inputs;
[] = BaseContract._formatABIDataItemList(inputAbi, [], BaseContract._bigNumberToString.bind(self));
const ethersFunction = self
._lookupEthersInterface(functionSignature)
.functions.totalSupply() as ethers.CallDescription;
const encodedData = ethersFunction.data;
const callDataWithDefaults = await self._applyDefaultsToTxDataAsync({
data: encodedData,
});
const rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock);
let resultArray = ethersFunction.parse(rawCallResult);
const outputAbi = (_.find(self.abi, { name: 'totalSupply' }) as MethodAbi).outputs;
resultArray = BaseContract._formatABIDataItemList(
outputAbi,
resultArray,
BaseContract._lowercaseAddress.bind(this),
);
resultArray = BaseContract._formatABIDataItemList(
outputAbi,
resultArray,
BaseContract._bnToBigNumber.bind(this),
);
return resultArray[0];
},
};
public transferFrom = {
async sendTransactionAsync(
_from: string,
_to: string,
_value: BigNumber,
txData: Partial<TxData> = {},
): Promise<string> {
const self = (this as any) as EtherTokenContract;
const inputAbi = self._lookupAbi('transferFrom(address,address,uint256)').inputs;
[_from, _to, _value] = BaseContract._formatABIDataItemList(
inputAbi,
[_from, _to, _value],
BaseContract._bigNumberToString.bind(self),
);
const encodedData = self
._lookupEthersInterface('transferFrom(address,address,uint256)')
.functions.transferFrom(_from, _to, _value).data;
const txDataWithDefaults = await self._applyDefaultsToTxDataAsync(
{
...txData,
data: encodedData,
},
self.transferFrom.estimateGasAsync.bind(self, _from, _to, _value),
);
const txHash = await self._web3Wrapper.sendTransactionAsync(txDataWithDefaults);
return txHash;
},
async estimateGasAsync(
_from: string,
_to: string,
_value: BigNumber,
txData: Partial<TxData> = {},
): Promise<number> {
const self = (this as any) as EtherTokenContract;
const inputAbi = self._lookupAbi('transferFrom(address,address,uint256)').inputs;
[_from, _to, _value] = BaseContract._formatABIDataItemList(
inputAbi,
[_from, _to, _value],
BaseContract._bigNumberToString.bind(this),
);
const encodedData = self
._lookupEthersInterface('transferFrom(address,address,uint256)')
.functions.transferFrom(_from, _to, _value).data;
const txDataWithDefaults = await self._applyDefaultsToTxDataAsync({
...txData,
data: encodedData,
});
const gas = await self._web3Wrapper.estimateGasAsync(txDataWithDefaults);
return gas;
},
getABIEncodedTransactionData(_from: string, _to: string, _value: BigNumber): string {
const self = (this as any) as EtherTokenContract;
const inputAbi = self._lookupAbi('transferFrom(address,address,uint256)').inputs;
[_from, _to, _value] = BaseContract._formatABIDataItemList(
inputAbi,
[_from, _to, _value],
BaseContract._bigNumberToString.bind(self),
);
const abiEncodedTransactionData = self
._lookupEthersInterface('transferFrom(address,address,uint256)')
.functions.transferFrom(_from, _to, _value).data;
return abiEncodedTransactionData;
},
async callAsync(
_from: string,
_to: string,
_value: BigNumber,
callData: Partial<CallData> = {},
defaultBlock?: BlockParam,
): Promise<boolean> {
const self = (this as any) as EtherTokenContract;
const functionSignature = 'transferFrom(address,address,uint256)';
const inputAbi = self._lookupAbi(functionSignature).inputs;
[_from, _to, _value] = BaseContract._formatABIDataItemList(
inputAbi,
[_from, _to, _value],
BaseContract._bigNumberToString.bind(self),
);
const ethersFunction = self
._lookupEthersInterface(functionSignature)
.functions.transferFrom(_from, _to, _value) as ethers.CallDescription;
const encodedData = ethersFunction.data;
const callDataWithDefaults = await self._applyDefaultsToTxDataAsync({
data: encodedData,
});
const rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock);
let resultArray = ethersFunction.parse(rawCallResult);
const outputAbi = (_.find(self.abi, { name: 'transferFrom' }) as MethodAbi).outputs;
resultArray = BaseContract._formatABIDataItemList(
outputAbi,
resultArray,
BaseContract._lowercaseAddress.bind(this),
);
resultArray = BaseContract._formatABIDataItemList(
outputAbi,
resultArray,
BaseContract._bnToBigNumber.bind(this),
);
return resultArray[0];
},
};
public withdraw = {
async sendTransactionAsync(amount: BigNumber, txData: Partial<TxData> = {}): Promise<string> {
const self = (this as any) as EtherTokenContract;
const inputAbi = self._lookupAbi('withdraw(uint256)').inputs;
[amount] = BaseContract._formatABIDataItemList(
inputAbi,
[amount],
BaseContract._bigNumberToString.bind(self),
);
const encodedData = self._lookupEthersInterface('withdraw(uint256)').functions.withdraw(amount).data;
const txDataWithDefaults = await self._applyDefaultsToTxDataAsync(
{
...txData,
data: encodedData,
},
self.withdraw.estimateGasAsync.bind(self, amount),
);
const txHash = await self._web3Wrapper.sendTransactionAsync(txDataWithDefaults);
return txHash;
},
async estimateGasAsync(amount: BigNumber, txData: Partial<TxData> = {}): Promise<number> {
const self = (this as any) as EtherTokenContract;
const inputAbi = self._lookupAbi('withdraw(uint256)').inputs;
[amount] = BaseContract._formatABIDataItemList(
inputAbi,
[amount],
BaseContract._bigNumberToString.bind(this),
);
const encodedData = self._lookupEthersInterface('withdraw(uint256)').functions.withdraw(amount).data;
const txDataWithDefaults = await self._applyDefaultsToTxDataAsync({
...txData,
data: encodedData,
});
const gas = await self._web3Wrapper.estimateGasAsync(txDataWithDefaults);
return gas;
},
getABIEncodedTransactionData(amount: BigNumber): string {
const self = (this as any) as EtherTokenContract;
const inputAbi = self._lookupAbi('withdraw(uint256)').inputs;
[amount] = BaseContract._formatABIDataItemList(
inputAbi,
[amount],
BaseContract._bigNumberToString.bind(self),
);
const abiEncodedTransactionData = self
._lookupEthersInterface('withdraw(uint256)')
.functions.withdraw(amount).data;
return abiEncodedTransactionData;
},
};
public decimals = {
async callAsync(callData: Partial<CallData> = {}, defaultBlock?: BlockParam): Promise<number> {
const self = (this as any) as EtherTokenContract;
const functionSignature = 'decimals()';
const inputAbi = self._lookupAbi(functionSignature).inputs;
[] = BaseContract._formatABIDataItemList(inputAbi, [], BaseContract._bigNumberToString.bind(self));
const ethersFunction = self
._lookupEthersInterface(functionSignature)
.functions.decimals() as ethers.CallDescription;
const encodedData = ethersFunction.data;
const callDataWithDefaults = await self._applyDefaultsToTxDataAsync({
data: encodedData,
});
const rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock);
let resultArray = ethersFunction.parse(rawCallResult);
const outputAbi = (_.find(self.abi, { name: 'decimals' }) as MethodAbi).outputs;
resultArray = BaseContract._formatABIDataItemList(
outputAbi,
resultArray,
BaseContract._lowercaseAddress.bind(this),
);
resultArray = BaseContract._formatABIDataItemList(
outputAbi,
resultArray,
BaseContract._bnToBigNumber.bind(this),
);
return resultArray[0];
},
};
public balanceOf = {
async callAsync(
_owner: string,
callData: Partial<CallData> = {},
defaultBlock?: BlockParam,
): Promise<BigNumber> {
const self = (this as any) as EtherTokenContract;
const functionSignature = 'balanceOf(address)';
const inputAbi = self._lookupAbi(functionSignature).inputs;
[_owner] = BaseContract._formatABIDataItemList(
inputAbi,
[_owner],
BaseContract._bigNumberToString.bind(self),
);
const ethersFunction = self
._lookupEthersInterface(functionSignature)
.functions.balanceOf(_owner) as ethers.CallDescription;
const encodedData = ethersFunction.data;
const callDataWithDefaults = await self._applyDefaultsToTxDataAsync({
data: encodedData,
});
const rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock);
let resultArray = ethersFunction.parse(rawCallResult);
const outputAbi = (_.find(self.abi, { name: 'balanceOf' }) as MethodAbi).outputs;
resultArray = BaseContract._formatABIDataItemList(
outputAbi,
resultArray,
BaseContract._lowercaseAddress.bind(this),
);
resultArray = BaseContract._formatABIDataItemList(
outputAbi,
resultArray,
BaseContract._bnToBigNumber.bind(this),
);
return resultArray[0];
},
};
public symbol = {
async callAsync(callData: Partial<CallData> = {}, defaultBlock?: BlockParam): Promise<string> {
const self = (this as any) as EtherTokenContract;
const functionSignature = 'symbol()';
const inputAbi = self._lookupAbi(functionSignature).inputs;
[] = BaseContract._formatABIDataItemList(inputAbi, [], BaseContract._bigNumberToString.bind(self));
const ethersFunction = self
._lookupEthersInterface(functionSignature)
.functions.symbol() as ethers.CallDescription;
const encodedData = ethersFunction.data;
const callDataWithDefaults = await self._applyDefaultsToTxDataAsync({
data: encodedData,
});
const rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock);
let resultArray = ethersFunction.parse(rawCallResult);
const outputAbi = (_.find(self.abi, { name: 'symbol' }) as MethodAbi).outputs;
resultArray = BaseContract._formatABIDataItemList(
outputAbi,
resultArray,
BaseContract._lowercaseAddress.bind(this),
);
resultArray = BaseContract._formatABIDataItemList(
outputAbi,
resultArray,
BaseContract._bnToBigNumber.bind(this),
);
return resultArray[0];
},
};
public transfer = {
async sendTransactionAsync(_to: string, _value: BigNumber, txData: Partial<TxData> = {}): Promise<string> {
const self = (this as any) as EtherTokenContract;
const inputAbi = self._lookupAbi('transfer(address,uint256)').inputs;
[_to, _value] = BaseContract._formatABIDataItemList(
inputAbi,
[_to, _value],
BaseContract._bigNumberToString.bind(self),
);
const encodedData = self._lookupEthersInterface('transfer(address,uint256)').functions.transfer(_to, _value)
.data;
const txDataWithDefaults = await self._applyDefaultsToTxDataAsync(
{
...txData,
data: encodedData,
},
self.transfer.estimateGasAsync.bind(self, _to, _value),
);
const txHash = await self._web3Wrapper.sendTransactionAsync(txDataWithDefaults);
return txHash;
},
async estimateGasAsync(_to: string, _value: BigNumber, txData: Partial<TxData> = {}): Promise<number> {
const self = (this as any) as EtherTokenContract;
const inputAbi = self._lookupAbi('transfer(address,uint256)').inputs;
[_to, _value] = BaseContract._formatABIDataItemList(
inputAbi,
[_to, _value],
BaseContract._bigNumberToString.bind(this),
);
const encodedData = self._lookupEthersInterface('transfer(address,uint256)').functions.transfer(_to, _value)
.data;
const txDataWithDefaults = await self._applyDefaultsToTxDataAsync({
...txData,
data: encodedData,
});
const gas = await self._web3Wrapper.estimateGasAsync(txDataWithDefaults);
return gas;
},
getABIEncodedTransactionData(_to: string, _value: BigNumber): string {
const self = (this as any) as EtherTokenContract;
const inputAbi = self._lookupAbi('transfer(address,uint256)').inputs;
[_to, _value] = BaseContract._formatABIDataItemList(
inputAbi,
[_to, _value],
BaseContract._bigNumberToString.bind(self),
);
const abiEncodedTransactionData = self
._lookupEthersInterface('transfer(address,uint256)')
.functions.transfer(_to, _value).data;
return abiEncodedTransactionData;
},
async callAsync(
_to: string,
_value: BigNumber,
callData: Partial<CallData> = {},
defaultBlock?: BlockParam,
): Promise<boolean> {
const self = (this as any) as EtherTokenContract;
const functionSignature = 'transfer(address,uint256)';
const inputAbi = self._lookupAbi(functionSignature).inputs;
[_to, _value] = BaseContract._formatABIDataItemList(
inputAbi,
[_to, _value],
BaseContract._bigNumberToString.bind(self),
);
const ethersFunction = self
._lookupEthersInterface(functionSignature)
.functions.transfer(_to, _value) as ethers.CallDescription;
const encodedData = ethersFunction.data;
const callDataWithDefaults = await self._applyDefaultsToTxDataAsync({
data: encodedData,
});
const rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock);
let resultArray = ethersFunction.parse(rawCallResult);
const outputAbi = (_.find(self.abi, { name: 'transfer' }) as MethodAbi).outputs;
resultArray = BaseContract._formatABIDataItemList(
outputAbi,
resultArray,
BaseContract._lowercaseAddress.bind(this),
);
resultArray = BaseContract._formatABIDataItemList(
outputAbi,
resultArray,
BaseContract._bnToBigNumber.bind(this),
);
return resultArray[0];
},
};
public deposit = {
async sendTransactionAsync(txData: Partial<TxDataPayable> = {}): Promise<string> {
const self = (this as any) as EtherTokenContract;
const inputAbi = self._lookupAbi('deposit()').inputs;
[] = BaseContract._formatABIDataItemList(inputAbi, [], BaseContract._bigNumberToString.bind(self));
const encodedData = self._lookupEthersInterface('deposit()').functions.deposit().data;
const txDataWithDefaults = await self._applyDefaultsToTxDataAsync(
{
...txData,
data: encodedData,
},
self.deposit.estimateGasAsync.bind(self),
);
const txHash = await self._web3Wrapper.sendTransactionAsync(txDataWithDefaults);
return txHash;
},
async estimateGasAsync(txData: Partial<TxData> = {}): Promise<number> {
const self = (this as any) as EtherTokenContract;
const inputAbi = self._lookupAbi('deposit()').inputs;
[] = BaseContract._formatABIDataItemList(inputAbi, [], BaseContract._bigNumberToString.bind(this));
const encodedData = self._lookupEthersInterface('deposit()').functions.deposit().data;
const txDataWithDefaults = await self._applyDefaultsToTxDataAsync({
...txData,
data: encodedData,
});
const gas = await self._web3Wrapper.estimateGasAsync(txDataWithDefaults);
return gas;
},
getABIEncodedTransactionData(): string {
const self = (this as any) as EtherTokenContract;
const inputAbi = self._lookupAbi('deposit()').inputs;
[] = BaseContract._formatABIDataItemList(inputAbi, [], BaseContract._bigNumberToString.bind(self));
const abiEncodedTransactionData = self._lookupEthersInterface('deposit()').functions.deposit().data;
return abiEncodedTransactionData;
},
};
public allowance = {
async callAsync(
_owner: string,
_spender: string,
callData: Partial<CallData> = {},
defaultBlock?: BlockParam,
): Promise<BigNumber> {
const self = (this as any) as EtherTokenContract;
const functionSignature = 'allowance(address,address)';
const inputAbi = self._lookupAbi(functionSignature).inputs;
[_owner, _spender] = BaseContract._formatABIDataItemList(
inputAbi,
[_owner, _spender],
BaseContract._bigNumberToString.bind(self),
);
const ethersFunction = self
._lookupEthersInterface(functionSignature)
.functions.allowance(_owner, _spender) as ethers.CallDescription;
const encodedData = ethersFunction.data;
const callDataWithDefaults = await self._applyDefaultsToTxDataAsync({
data: encodedData,
});
const rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock);
let resultArray = ethersFunction.parse(rawCallResult);
const outputAbi = (_.find(self.abi, { name: 'allowance' }) as MethodAbi).outputs;
resultArray = BaseContract._formatABIDataItemList(
outputAbi,
resultArray,
BaseContract._lowercaseAddress.bind(this),
);
resultArray = BaseContract._formatABIDataItemList(
outputAbi,
resultArray,
BaseContract._bnToBigNumber.bind(this),
);
return resultArray[0];
},
};
constructor(abi: ContractAbi, address: string, provider: Provider, defaults?: Partial<TxData>) {
super(abi, address, provider, defaults);
classUtils.bindAll(this, ['_ethersInterfacesByFunctionSignature', 'address', 'abi', '_web3Wrapper']);
}
} // tslint:disable:max-file-line-count

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,432 @@
/**
* This file is auto-generated using abi-gen. Don't edit directly.
* Templates can be found at https://github.com/0xProject/0x-monorepo/tree/development/packages/contract_templates.
*/
// tslint:disable:no-consecutive-blank-lines
// tslint:disable-next-line:no-unused-variable
import { BaseContract } from '@0xproject/base-contract';
import {
BlockParam,
BlockParamLiteral,
CallData,
ContractAbi,
DataItem,
MethodAbi,
Provider,
TxData,
TxDataPayable,
} from '@0xproject/types';
import { BigNumber, classUtils, promisify } from '@0xproject/utils';
import { Web3Wrapper } from '@0xproject/web3-wrapper';
import * as ethers from 'ethers';
import * as _ from 'lodash';
export type TokenContractEventArgs = TransferContractEventArgs | ApprovalContractEventArgs;
export enum TokenEvents {
Transfer = 'Transfer',
Approval = 'Approval',
}
export interface TransferContractEventArgs {
_from: string;
_to: string;
_value: BigNumber;
}
export interface ApprovalContractEventArgs {
_owner: string;
_spender: string;
_value: BigNumber;
}
// tslint:disable:no-parameter-reassignment
export class TokenContract extends BaseContract {
public approve = {
async sendTransactionAsync(_spender: string, _value: BigNumber, txData: Partial<TxData> = {}): Promise<string> {
const self = (this as any) as TokenContract;
const inputAbi = self._lookupAbi('approve(address,uint256)').inputs;
[_spender, _value] = BaseContract._formatABIDataItemList(
inputAbi,
[_spender, _value],
BaseContract._bigNumberToString.bind(self),
);
const encodedData = self
._lookupEthersInterface('approve(address,uint256)')
.functions.approve(_spender, _value).data;
const txDataWithDefaults = await self._applyDefaultsToTxDataAsync(
{
...txData,
data: encodedData,
},
self.approve.estimateGasAsync.bind(self, _spender, _value),
);
const txHash = await self._web3Wrapper.sendTransactionAsync(txDataWithDefaults);
return txHash;
},
async estimateGasAsync(_spender: string, _value: BigNumber, txData: Partial<TxData> = {}): Promise<number> {
const self = (this as any) as TokenContract;
const inputAbi = self._lookupAbi('approve(address,uint256)').inputs;
[_spender, _value] = BaseContract._formatABIDataItemList(
inputAbi,
[_spender, _value],
BaseContract._bigNumberToString.bind(this),
);
const encodedData = self
._lookupEthersInterface('approve(address,uint256)')
.functions.approve(_spender, _value).data;
const txDataWithDefaults = await self._applyDefaultsToTxDataAsync({
...txData,
data: encodedData,
});
const gas = await self._web3Wrapper.estimateGasAsync(txDataWithDefaults);
return gas;
},
getABIEncodedTransactionData(_spender: string, _value: BigNumber): string {
const self = (this as any) as TokenContract;
const inputAbi = self._lookupAbi('approve(address,uint256)').inputs;
[_spender, _value] = BaseContract._formatABIDataItemList(
inputAbi,
[_spender, _value],
BaseContract._bigNumberToString.bind(self),
);
const abiEncodedTransactionData = self
._lookupEthersInterface('approve(address,uint256)')
.functions.approve(_spender, _value).data;
return abiEncodedTransactionData;
},
async callAsync(
_spender: string,
_value: BigNumber,
callData: Partial<CallData> = {},
defaultBlock?: BlockParam,
): Promise<boolean> {
const self = (this as any) as TokenContract;
const functionSignature = 'approve(address,uint256)';
const inputAbi = self._lookupAbi(functionSignature).inputs;
[_spender, _value] = BaseContract._formatABIDataItemList(
inputAbi,
[_spender, _value],
BaseContract._bigNumberToString.bind(self),
);
const ethersFunction = self
._lookupEthersInterface(functionSignature)
.functions.approve(_spender, _value) as ethers.CallDescription;
const encodedData = ethersFunction.data;
const callDataWithDefaults = await self._applyDefaultsToTxDataAsync({
data: encodedData,
});
const rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock);
let resultArray = ethersFunction.parse(rawCallResult);
const outputAbi = (_.find(self.abi, { name: 'approve' }) as MethodAbi).outputs;
resultArray = BaseContract._formatABIDataItemList(
outputAbi,
resultArray,
BaseContract._lowercaseAddress.bind(this),
);
resultArray = BaseContract._formatABIDataItemList(
outputAbi,
resultArray,
BaseContract._bnToBigNumber.bind(this),
);
return resultArray[0];
},
};
public totalSupply = {
async callAsync(callData: Partial<CallData> = {}, defaultBlock?: BlockParam): Promise<BigNumber> {
const self = (this as any) as TokenContract;
const functionSignature = 'totalSupply()';
const inputAbi = self._lookupAbi(functionSignature).inputs;
[] = BaseContract._formatABIDataItemList(inputAbi, [], BaseContract._bigNumberToString.bind(self));
const ethersFunction = self
._lookupEthersInterface(functionSignature)
.functions.totalSupply() as ethers.CallDescription;
const encodedData = ethersFunction.data;
const callDataWithDefaults = await self._applyDefaultsToTxDataAsync({
data: encodedData,
});
const rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock);
let resultArray = ethersFunction.parse(rawCallResult);
const outputAbi = (_.find(self.abi, { name: 'totalSupply' }) as MethodAbi).outputs;
resultArray = BaseContract._formatABIDataItemList(
outputAbi,
resultArray,
BaseContract._lowercaseAddress.bind(this),
);
resultArray = BaseContract._formatABIDataItemList(
outputAbi,
resultArray,
BaseContract._bnToBigNumber.bind(this),
);
return resultArray[0];
},
};
public transferFrom = {
async sendTransactionAsync(
_from: string,
_to: string,
_value: BigNumber,
txData: Partial<TxData> = {},
): Promise<string> {
const self = (this as any) as TokenContract;
const inputAbi = self._lookupAbi('transferFrom(address,address,uint256)').inputs;
[_from, _to, _value] = BaseContract._formatABIDataItemList(
inputAbi,
[_from, _to, _value],
BaseContract._bigNumberToString.bind(self),
);
const encodedData = self
._lookupEthersInterface('transferFrom(address,address,uint256)')
.functions.transferFrom(_from, _to, _value).data;
const txDataWithDefaults = await self._applyDefaultsToTxDataAsync(
{
...txData,
data: encodedData,
},
self.transferFrom.estimateGasAsync.bind(self, _from, _to, _value),
);
const txHash = await self._web3Wrapper.sendTransactionAsync(txDataWithDefaults);
return txHash;
},
async estimateGasAsync(
_from: string,
_to: string,
_value: BigNumber,
txData: Partial<TxData> = {},
): Promise<number> {
const self = (this as any) as TokenContract;
const inputAbi = self._lookupAbi('transferFrom(address,address,uint256)').inputs;
[_from, _to, _value] = BaseContract._formatABIDataItemList(
inputAbi,
[_from, _to, _value],
BaseContract._bigNumberToString.bind(this),
);
const encodedData = self
._lookupEthersInterface('transferFrom(address,address,uint256)')
.functions.transferFrom(_from, _to, _value).data;
const txDataWithDefaults = await self._applyDefaultsToTxDataAsync({
...txData,
data: encodedData,
});
const gas = await self._web3Wrapper.estimateGasAsync(txDataWithDefaults);
return gas;
},
getABIEncodedTransactionData(_from: string, _to: string, _value: BigNumber): string {
const self = (this as any) as TokenContract;
const inputAbi = self._lookupAbi('transferFrom(address,address,uint256)').inputs;
[_from, _to, _value] = BaseContract._formatABIDataItemList(
inputAbi,
[_from, _to, _value],
BaseContract._bigNumberToString.bind(self),
);
const abiEncodedTransactionData = self
._lookupEthersInterface('transferFrom(address,address,uint256)')
.functions.transferFrom(_from, _to, _value).data;
return abiEncodedTransactionData;
},
async callAsync(
_from: string,
_to: string,
_value: BigNumber,
callData: Partial<CallData> = {},
defaultBlock?: BlockParam,
): Promise<boolean> {
const self = (this as any) as TokenContract;
const functionSignature = 'transferFrom(address,address,uint256)';
const inputAbi = self._lookupAbi(functionSignature).inputs;
[_from, _to, _value] = BaseContract._formatABIDataItemList(
inputAbi,
[_from, _to, _value],
BaseContract._bigNumberToString.bind(self),
);
const ethersFunction = self
._lookupEthersInterface(functionSignature)
.functions.transferFrom(_from, _to, _value) as ethers.CallDescription;
const encodedData = ethersFunction.data;
const callDataWithDefaults = await self._applyDefaultsToTxDataAsync({
data: encodedData,
});
const rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock);
let resultArray = ethersFunction.parse(rawCallResult);
const outputAbi = (_.find(self.abi, { name: 'transferFrom' }) as MethodAbi).outputs;
resultArray = BaseContract._formatABIDataItemList(
outputAbi,
resultArray,
BaseContract._lowercaseAddress.bind(this),
);
resultArray = BaseContract._formatABIDataItemList(
outputAbi,
resultArray,
BaseContract._bnToBigNumber.bind(this),
);
return resultArray[0];
},
};
public balanceOf = {
async callAsync(
_owner: string,
callData: Partial<CallData> = {},
defaultBlock?: BlockParam,
): Promise<BigNumber> {
const self = (this as any) as TokenContract;
const functionSignature = 'balanceOf(address)';
const inputAbi = self._lookupAbi(functionSignature).inputs;
[_owner] = BaseContract._formatABIDataItemList(
inputAbi,
[_owner],
BaseContract._bigNumberToString.bind(self),
);
const ethersFunction = self
._lookupEthersInterface(functionSignature)
.functions.balanceOf(_owner) as ethers.CallDescription;
const encodedData = ethersFunction.data;
const callDataWithDefaults = await self._applyDefaultsToTxDataAsync({
data: encodedData,
});
const rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock);
let resultArray = ethersFunction.parse(rawCallResult);
const outputAbi = (_.find(self.abi, { name: 'balanceOf' }) as MethodAbi).outputs;
resultArray = BaseContract._formatABIDataItemList(
outputAbi,
resultArray,
BaseContract._lowercaseAddress.bind(this),
);
resultArray = BaseContract._formatABIDataItemList(
outputAbi,
resultArray,
BaseContract._bnToBigNumber.bind(this),
);
return resultArray[0];
},
};
public transfer = {
async sendTransactionAsync(_to: string, _value: BigNumber, txData: Partial<TxData> = {}): Promise<string> {
const self = (this as any) as TokenContract;
const inputAbi = self._lookupAbi('transfer(address,uint256)').inputs;
[_to, _value] = BaseContract._formatABIDataItemList(
inputAbi,
[_to, _value],
BaseContract._bigNumberToString.bind(self),
);
const encodedData = self._lookupEthersInterface('transfer(address,uint256)').functions.transfer(_to, _value)
.data;
const txDataWithDefaults = await self._applyDefaultsToTxDataAsync(
{
...txData,
data: encodedData,
},
self.transfer.estimateGasAsync.bind(self, _to, _value),
);
const txHash = await self._web3Wrapper.sendTransactionAsync(txDataWithDefaults);
return txHash;
},
async estimateGasAsync(_to: string, _value: BigNumber, txData: Partial<TxData> = {}): Promise<number> {
const self = (this as any) as TokenContract;
const inputAbi = self._lookupAbi('transfer(address,uint256)').inputs;
[_to, _value] = BaseContract._formatABIDataItemList(
inputAbi,
[_to, _value],
BaseContract._bigNumberToString.bind(this),
);
const encodedData = self._lookupEthersInterface('transfer(address,uint256)').functions.transfer(_to, _value)
.data;
const txDataWithDefaults = await self._applyDefaultsToTxDataAsync({
...txData,
data: encodedData,
});
const gas = await self._web3Wrapper.estimateGasAsync(txDataWithDefaults);
return gas;
},
getABIEncodedTransactionData(_to: string, _value: BigNumber): string {
const self = (this as any) as TokenContract;
const inputAbi = self._lookupAbi('transfer(address,uint256)').inputs;
[_to, _value] = BaseContract._formatABIDataItemList(
inputAbi,
[_to, _value],
BaseContract._bigNumberToString.bind(self),
);
const abiEncodedTransactionData = self
._lookupEthersInterface('transfer(address,uint256)')
.functions.transfer(_to, _value).data;
return abiEncodedTransactionData;
},
async callAsync(
_to: string,
_value: BigNumber,
callData: Partial<CallData> = {},
defaultBlock?: BlockParam,
): Promise<boolean> {
const self = (this as any) as TokenContract;
const functionSignature = 'transfer(address,uint256)';
const inputAbi = self._lookupAbi(functionSignature).inputs;
[_to, _value] = BaseContract._formatABIDataItemList(
inputAbi,
[_to, _value],
BaseContract._bigNumberToString.bind(self),
);
const ethersFunction = self
._lookupEthersInterface(functionSignature)
.functions.transfer(_to, _value) as ethers.CallDescription;
const encodedData = ethersFunction.data;
const callDataWithDefaults = await self._applyDefaultsToTxDataAsync({
data: encodedData,
});
const rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock);
let resultArray = ethersFunction.parse(rawCallResult);
const outputAbi = (_.find(self.abi, { name: 'transfer' }) as MethodAbi).outputs;
resultArray = BaseContract._formatABIDataItemList(
outputAbi,
resultArray,
BaseContract._lowercaseAddress.bind(this),
);
resultArray = BaseContract._formatABIDataItemList(
outputAbi,
resultArray,
BaseContract._bnToBigNumber.bind(this),
);
return resultArray[0];
},
};
public allowance = {
async callAsync(
_owner: string,
_spender: string,
callData: Partial<CallData> = {},
defaultBlock?: BlockParam,
): Promise<BigNumber> {
const self = (this as any) as TokenContract;
const functionSignature = 'allowance(address,address)';
const inputAbi = self._lookupAbi(functionSignature).inputs;
[_owner, _spender] = BaseContract._formatABIDataItemList(
inputAbi,
[_owner, _spender],
BaseContract._bigNumberToString.bind(self),
);
const ethersFunction = self
._lookupEthersInterface(functionSignature)
.functions.allowance(_owner, _spender) as ethers.CallDescription;
const encodedData = ethersFunction.data;
const callDataWithDefaults = await self._applyDefaultsToTxDataAsync({
data: encodedData,
});
const rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock);
let resultArray = ethersFunction.parse(rawCallResult);
const outputAbi = (_.find(self.abi, { name: 'allowance' }) as MethodAbi).outputs;
resultArray = BaseContract._formatABIDataItemList(
outputAbi,
resultArray,
BaseContract._lowercaseAddress.bind(this),
);
resultArray = BaseContract._formatABIDataItemList(
outputAbi,
resultArray,
BaseContract._bnToBigNumber.bind(this),
);
return resultArray[0];
},
};
constructor(abi: ContractAbi, address: string, provider: Provider, defaults?: Partial<TxData>) {
super(abi, address, provider, defaults);
classUtils.bindAll(this, ['_ethersInterfacesByFunctionSignature', 'address', 'abi', '_web3Wrapper']);
}
} // tslint:disable:max-file-line-count

View File

@ -0,0 +1,799 @@
/**
* This file is auto-generated using abi-gen. Don't edit directly.
* Templates can be found at https://github.com/0xProject/0x-monorepo/tree/development/packages/contract_templates.
*/
// tslint:disable:no-consecutive-blank-lines
// tslint:disable-next-line:no-unused-variable
import { BaseContract } from '@0xproject/base-contract';
import {
BlockParam,
BlockParamLiteral,
CallData,
ContractAbi,
DataItem,
MethodAbi,
Provider,
TxData,
TxDataPayable,
} from '@0xproject/types';
import { BigNumber, classUtils, promisify } from '@0xproject/utils';
import { Web3Wrapper } from '@0xproject/web3-wrapper';
import * as ethers from 'ethers';
import * as _ from 'lodash';
export type TokenRegistryContractEventArgs =
| LogAddTokenContractEventArgs
| LogRemoveTokenContractEventArgs
| LogTokenNameChangeContractEventArgs
| LogTokenSymbolChangeContractEventArgs
| LogTokenIpfsHashChangeContractEventArgs
| LogTokenSwarmHashChangeContractEventArgs;
export enum TokenRegistryEvents {
LogAddToken = 'LogAddToken',
LogRemoveToken = 'LogRemoveToken',
LogTokenNameChange = 'LogTokenNameChange',
LogTokenSymbolChange = 'LogTokenSymbolChange',
LogTokenIpfsHashChange = 'LogTokenIpfsHashChange',
LogTokenSwarmHashChange = 'LogTokenSwarmHashChange',
}
export interface LogAddTokenContractEventArgs {
token: string;
name: string;
symbol: string;
decimals: number;
ipfsHash: string;
swarmHash: string;
}
export interface LogRemoveTokenContractEventArgs {
token: string;
name: string;
symbol: string;
decimals: number;
ipfsHash: string;
swarmHash: string;
}
export interface LogTokenNameChangeContractEventArgs {
token: string;
oldName: string;
newName: string;
}
export interface LogTokenSymbolChangeContractEventArgs {
token: string;
oldSymbol: string;
newSymbol: string;
}
export interface LogTokenIpfsHashChangeContractEventArgs {
token: string;
oldIpfsHash: string;
newIpfsHash: string;
}
export interface LogTokenSwarmHashChangeContractEventArgs {
token: string;
oldSwarmHash: string;
newSwarmHash: string;
}
// tslint:disable:no-parameter-reassignment
export class TokenRegistryContract extends BaseContract {
public removeToken = {
async sendTransactionAsync(_token: string, _index: BigNumber, txData: Partial<TxData> = {}): Promise<string> {
const self = (this as any) as TokenRegistryContract;
const inputAbi = self._lookupAbi('removeToken(address,uint256)').inputs;
[_token, _index] = BaseContract._formatABIDataItemList(
inputAbi,
[_token, _index],
BaseContract._bigNumberToString.bind(self),
);
const encodedData = self
._lookupEthersInterface('removeToken(address,uint256)')
.functions.removeToken(_token, _index).data;
const txDataWithDefaults = await self._applyDefaultsToTxDataAsync(
{
...txData,
data: encodedData,
},
self.removeToken.estimateGasAsync.bind(self, _token, _index),
);
const txHash = await self._web3Wrapper.sendTransactionAsync(txDataWithDefaults);
return txHash;
},
async estimateGasAsync(_token: string, _index: BigNumber, txData: Partial<TxData> = {}): Promise<number> {
const self = (this as any) as TokenRegistryContract;
const inputAbi = self._lookupAbi('removeToken(address,uint256)').inputs;
[_token, _index] = BaseContract._formatABIDataItemList(
inputAbi,
[_token, _index],
BaseContract._bigNumberToString.bind(this),
);
const encodedData = self
._lookupEthersInterface('removeToken(address,uint256)')
.functions.removeToken(_token, _index).data;
const txDataWithDefaults = await self._applyDefaultsToTxDataAsync({
...txData,
data: encodedData,
});
const gas = await self._web3Wrapper.estimateGasAsync(txDataWithDefaults);
return gas;
},
getABIEncodedTransactionData(_token: string, _index: BigNumber): string {
const self = (this as any) as TokenRegistryContract;
const inputAbi = self._lookupAbi('removeToken(address,uint256)').inputs;
[_token, _index] = BaseContract._formatABIDataItemList(
inputAbi,
[_token, _index],
BaseContract._bigNumberToString.bind(self),
);
const abiEncodedTransactionData = self
._lookupEthersInterface('removeToken(address,uint256)')
.functions.removeToken(_token, _index).data;
return abiEncodedTransactionData;
},
};
public getTokenAddressByName = {
async callAsync(_name: string, callData: Partial<CallData> = {}, defaultBlock?: BlockParam): Promise<string> {
const self = (this as any) as TokenRegistryContract;
const functionSignature = 'getTokenAddressByName(string)';
const inputAbi = self._lookupAbi(functionSignature).inputs;
[_name] = BaseContract._formatABIDataItemList(
inputAbi,
[_name],
BaseContract._bigNumberToString.bind(self),
);
const ethersFunction = self
._lookupEthersInterface(functionSignature)
.functions.getTokenAddressByName(_name) as ethers.CallDescription;
const encodedData = ethersFunction.data;
const callDataWithDefaults = await self._applyDefaultsToTxDataAsync({
data: encodedData,
});
const rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock);
let resultArray = ethersFunction.parse(rawCallResult);
const outputAbi = (_.find(self.abi, { name: 'getTokenAddressByName' }) as MethodAbi).outputs;
resultArray = BaseContract._formatABIDataItemList(
outputAbi,
resultArray,
BaseContract._lowercaseAddress.bind(this),
);
resultArray = BaseContract._formatABIDataItemList(
outputAbi,
resultArray,
BaseContract._bnToBigNumber.bind(this),
);
return resultArray[0];
},
};
public getTokenAddressBySymbol = {
async callAsync(_symbol: string, callData: Partial<CallData> = {}, defaultBlock?: BlockParam): Promise<string> {
const self = (this as any) as TokenRegistryContract;
const functionSignature = 'getTokenAddressBySymbol(string)';
const inputAbi = self._lookupAbi(functionSignature).inputs;
[_symbol] = BaseContract._formatABIDataItemList(
inputAbi,
[_symbol],
BaseContract._bigNumberToString.bind(self),
);
const ethersFunction = self
._lookupEthersInterface(functionSignature)
.functions.getTokenAddressBySymbol(_symbol) as ethers.CallDescription;
const encodedData = ethersFunction.data;
const callDataWithDefaults = await self._applyDefaultsToTxDataAsync({
data: encodedData,
});
const rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock);
let resultArray = ethersFunction.parse(rawCallResult);
const outputAbi = (_.find(self.abi, { name: 'getTokenAddressBySymbol' }) as MethodAbi).outputs;
resultArray = BaseContract._formatABIDataItemList(
outputAbi,
resultArray,
BaseContract._lowercaseAddress.bind(this),
);
resultArray = BaseContract._formatABIDataItemList(
outputAbi,
resultArray,
BaseContract._bnToBigNumber.bind(this),
);
return resultArray[0];
},
};
public setTokenSwarmHash = {
async sendTransactionAsync(_token: string, _swarmHash: string, txData: Partial<TxData> = {}): Promise<string> {
const self = (this as any) as TokenRegistryContract;
const inputAbi = self._lookupAbi('setTokenSwarmHash(address,bytes)').inputs;
[_token, _swarmHash] = BaseContract._formatABIDataItemList(
inputAbi,
[_token, _swarmHash],
BaseContract._bigNumberToString.bind(self),
);
const encodedData = self
._lookupEthersInterface('setTokenSwarmHash(address,bytes)')
.functions.setTokenSwarmHash(_token, _swarmHash).data;
const txDataWithDefaults = await self._applyDefaultsToTxDataAsync(
{
...txData,
data: encodedData,
},
self.setTokenSwarmHash.estimateGasAsync.bind(self, _token, _swarmHash),
);
const txHash = await self._web3Wrapper.sendTransactionAsync(txDataWithDefaults);
return txHash;
},
async estimateGasAsync(_token: string, _swarmHash: string, txData: Partial<TxData> = {}): Promise<number> {
const self = (this as any) as TokenRegistryContract;
const inputAbi = self._lookupAbi('setTokenSwarmHash(address,bytes)').inputs;
[_token, _swarmHash] = BaseContract._formatABIDataItemList(
inputAbi,
[_token, _swarmHash],
BaseContract._bigNumberToString.bind(this),
);
const encodedData = self
._lookupEthersInterface('setTokenSwarmHash(address,bytes)')
.functions.setTokenSwarmHash(_token, _swarmHash).data;
const txDataWithDefaults = await self._applyDefaultsToTxDataAsync({
...txData,
data: encodedData,
});
const gas = await self._web3Wrapper.estimateGasAsync(txDataWithDefaults);
return gas;
},
getABIEncodedTransactionData(_token: string, _swarmHash: string): string {
const self = (this as any) as TokenRegistryContract;
const inputAbi = self._lookupAbi('setTokenSwarmHash(address,bytes)').inputs;
[_token, _swarmHash] = BaseContract._formatABIDataItemList(
inputAbi,
[_token, _swarmHash],
BaseContract._bigNumberToString.bind(self),
);
const abiEncodedTransactionData = self
._lookupEthersInterface('setTokenSwarmHash(address,bytes)')
.functions.setTokenSwarmHash(_token, _swarmHash).data;
return abiEncodedTransactionData;
},
};
public getTokenMetaData = {
async callAsync(
_token: string,
callData: Partial<CallData> = {},
defaultBlock?: BlockParam,
): Promise<[string, string, string, number, string, string]> {
const self = (this as any) as TokenRegistryContract;
const functionSignature = 'getTokenMetaData(address)';
const inputAbi = self._lookupAbi(functionSignature).inputs;
[_token] = BaseContract._formatABIDataItemList(
inputAbi,
[_token],
BaseContract._bigNumberToString.bind(self),
);
const ethersFunction = self
._lookupEthersInterface(functionSignature)
.functions.getTokenMetaData(_token) as ethers.CallDescription;
const encodedData = ethersFunction.data;
const callDataWithDefaults = await self._applyDefaultsToTxDataAsync({
data: encodedData,
});
const rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock);
let resultArray = ethersFunction.parse(rawCallResult);
const outputAbi = (_.find(self.abi, { name: 'getTokenMetaData' }) as MethodAbi).outputs;
resultArray = BaseContract._formatABIDataItemList(
outputAbi,
resultArray,
BaseContract._lowercaseAddress.bind(this),
);
resultArray = BaseContract._formatABIDataItemList(
outputAbi,
resultArray,
BaseContract._bnToBigNumber.bind(this),
);
return resultArray;
},
};
public owner = {
async callAsync(callData: Partial<CallData> = {}, defaultBlock?: BlockParam): Promise<string> {
const self = (this as any) as TokenRegistryContract;
const functionSignature = 'owner()';
const inputAbi = self._lookupAbi(functionSignature).inputs;
[] = BaseContract._formatABIDataItemList(inputAbi, [], BaseContract._bigNumberToString.bind(self));
const ethersFunction = self
._lookupEthersInterface(functionSignature)
.functions.owner() as ethers.CallDescription;
const encodedData = ethersFunction.data;
const callDataWithDefaults = await self._applyDefaultsToTxDataAsync({
data: encodedData,
});
const rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock);
let resultArray = ethersFunction.parse(rawCallResult);
const outputAbi = (_.find(self.abi, { name: 'owner' }) as MethodAbi).outputs;
resultArray = BaseContract._formatABIDataItemList(
outputAbi,
resultArray,
BaseContract._lowercaseAddress.bind(this),
);
resultArray = BaseContract._formatABIDataItemList(
outputAbi,
resultArray,
BaseContract._bnToBigNumber.bind(this),
);
return resultArray[0];
},
};
public addToken = {
async sendTransactionAsync(
_token: string,
_name: string,
_symbol: string,
_decimals: number | BigNumber,
_ipfsHash: string,
_swarmHash: string,
txData: Partial<TxData> = {},
): Promise<string> {
const self = (this as any) as TokenRegistryContract;
const inputAbi = self._lookupAbi('addToken(address,string,string,uint8,bytes,bytes)').inputs;
[_token, _name, _symbol, _decimals, _ipfsHash, _swarmHash] = BaseContract._formatABIDataItemList(
inputAbi,
[_token, _name, _symbol, _decimals, _ipfsHash, _swarmHash],
BaseContract._bigNumberToString.bind(self),
);
const encodedData = self
._lookupEthersInterface('addToken(address,string,string,uint8,bytes,bytes)')
.functions.addToken(_token, _name, _symbol, _decimals, _ipfsHash, _swarmHash).data;
const txDataWithDefaults = await self._applyDefaultsToTxDataAsync(
{
...txData,
data: encodedData,
},
self.addToken.estimateGasAsync.bind(self, _token, _name, _symbol, _decimals, _ipfsHash, _swarmHash),
);
const txHash = await self._web3Wrapper.sendTransactionAsync(txDataWithDefaults);
return txHash;
},
async estimateGasAsync(
_token: string,
_name: string,
_symbol: string,
_decimals: number | BigNumber,
_ipfsHash: string,
_swarmHash: string,
txData: Partial<TxData> = {},
): Promise<number> {
const self = (this as any) as TokenRegistryContract;
const inputAbi = self._lookupAbi('addToken(address,string,string,uint8,bytes,bytes)').inputs;
[_token, _name, _symbol, _decimals, _ipfsHash, _swarmHash] = BaseContract._formatABIDataItemList(
inputAbi,
[_token, _name, _symbol, _decimals, _ipfsHash, _swarmHash],
BaseContract._bigNumberToString.bind(this),
);
const encodedData = self
._lookupEthersInterface('addToken(address,string,string,uint8,bytes,bytes)')
.functions.addToken(_token, _name, _symbol, _decimals, _ipfsHash, _swarmHash).data;
const txDataWithDefaults = await self._applyDefaultsToTxDataAsync({
...txData,
data: encodedData,
});
const gas = await self._web3Wrapper.estimateGasAsync(txDataWithDefaults);
return gas;
},
getABIEncodedTransactionData(
_token: string,
_name: string,
_symbol: string,
_decimals: number | BigNumber,
_ipfsHash: string,
_swarmHash: string,
): string {
const self = (this as any) as TokenRegistryContract;
const inputAbi = self._lookupAbi('addToken(address,string,string,uint8,bytes,bytes)').inputs;
[_token, _name, _symbol, _decimals, _ipfsHash, _swarmHash] = BaseContract._formatABIDataItemList(
inputAbi,
[_token, _name, _symbol, _decimals, _ipfsHash, _swarmHash],
BaseContract._bigNumberToString.bind(self),
);
const abiEncodedTransactionData = self
._lookupEthersInterface('addToken(address,string,string,uint8,bytes,bytes)')
.functions.addToken(_token, _name, _symbol, _decimals, _ipfsHash, _swarmHash).data;
return abiEncodedTransactionData;
},
};
public setTokenName = {
async sendTransactionAsync(_token: string, _name: string, txData: Partial<TxData> = {}): Promise<string> {
const self = (this as any) as TokenRegistryContract;
const inputAbi = self._lookupAbi('setTokenName(address,string)').inputs;
[_token, _name] = BaseContract._formatABIDataItemList(
inputAbi,
[_token, _name],
BaseContract._bigNumberToString.bind(self),
);
const encodedData = self
._lookupEthersInterface('setTokenName(address,string)')
.functions.setTokenName(_token, _name).data;
const txDataWithDefaults = await self._applyDefaultsToTxDataAsync(
{
...txData,
data: encodedData,
},
self.setTokenName.estimateGasAsync.bind(self, _token, _name),
);
const txHash = await self._web3Wrapper.sendTransactionAsync(txDataWithDefaults);
return txHash;
},
async estimateGasAsync(_token: string, _name: string, txData: Partial<TxData> = {}): Promise<number> {
const self = (this as any) as TokenRegistryContract;
const inputAbi = self._lookupAbi('setTokenName(address,string)').inputs;
[_token, _name] = BaseContract._formatABIDataItemList(
inputAbi,
[_token, _name],
BaseContract._bigNumberToString.bind(this),
);
const encodedData = self
._lookupEthersInterface('setTokenName(address,string)')
.functions.setTokenName(_token, _name).data;
const txDataWithDefaults = await self._applyDefaultsToTxDataAsync({
...txData,
data: encodedData,
});
const gas = await self._web3Wrapper.estimateGasAsync(txDataWithDefaults);
return gas;
},
getABIEncodedTransactionData(_token: string, _name: string): string {
const self = (this as any) as TokenRegistryContract;
const inputAbi = self._lookupAbi('setTokenName(address,string)').inputs;
[_token, _name] = BaseContract._formatABIDataItemList(
inputAbi,
[_token, _name],
BaseContract._bigNumberToString.bind(self),
);
const abiEncodedTransactionData = self
._lookupEthersInterface('setTokenName(address,string)')
.functions.setTokenName(_token, _name).data;
return abiEncodedTransactionData;
},
};
public tokens = {
async callAsync(
index_0: string,
callData: Partial<CallData> = {},
defaultBlock?: BlockParam,
): Promise<[string, string, string, number, string, string]> {
const self = (this as any) as TokenRegistryContract;
const functionSignature = 'tokens(address)';
const inputAbi = self._lookupAbi(functionSignature).inputs;
[index_0] = BaseContract._formatABIDataItemList(
inputAbi,
[index_0],
BaseContract._bigNumberToString.bind(self),
);
const ethersFunction = self
._lookupEthersInterface(functionSignature)
.functions.tokens(index_0) as ethers.CallDescription;
const encodedData = ethersFunction.data;
const callDataWithDefaults = await self._applyDefaultsToTxDataAsync({
data: encodedData,
});
const rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock);
let resultArray = ethersFunction.parse(rawCallResult);
const outputAbi = (_.find(self.abi, { name: 'tokens' }) as MethodAbi).outputs;
resultArray = BaseContract._formatABIDataItemList(
outputAbi,
resultArray,
BaseContract._lowercaseAddress.bind(this),
);
resultArray = BaseContract._formatABIDataItemList(
outputAbi,
resultArray,
BaseContract._bnToBigNumber.bind(this),
);
return resultArray;
},
};
public tokenAddresses = {
async callAsync(
index_0: BigNumber,
callData: Partial<CallData> = {},
defaultBlock?: BlockParam,
): Promise<string> {
const self = (this as any) as TokenRegistryContract;
const functionSignature = 'tokenAddresses(uint256)';
const inputAbi = self._lookupAbi(functionSignature).inputs;
[index_0] = BaseContract._formatABIDataItemList(
inputAbi,
[index_0],
BaseContract._bigNumberToString.bind(self),
);
const ethersFunction = self
._lookupEthersInterface(functionSignature)
.functions.tokenAddresses(index_0) as ethers.CallDescription;
const encodedData = ethersFunction.data;
const callDataWithDefaults = await self._applyDefaultsToTxDataAsync({
data: encodedData,
});
const rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock);
let resultArray = ethersFunction.parse(rawCallResult);
const outputAbi = (_.find(self.abi, { name: 'tokenAddresses' }) as MethodAbi).outputs;
resultArray = BaseContract._formatABIDataItemList(
outputAbi,
resultArray,
BaseContract._lowercaseAddress.bind(this),
);
resultArray = BaseContract._formatABIDataItemList(
outputAbi,
resultArray,
BaseContract._bnToBigNumber.bind(this),
);
return resultArray[0];
},
};
public getTokenByName = {
async callAsync(
_name: string,
callData: Partial<CallData> = {},
defaultBlock?: BlockParam,
): Promise<[string, string, string, number, string, string]> {
const self = (this as any) as TokenRegistryContract;
const functionSignature = 'getTokenByName(string)';
const inputAbi = self._lookupAbi(functionSignature).inputs;
[_name] = BaseContract._formatABIDataItemList(
inputAbi,
[_name],
BaseContract._bigNumberToString.bind(self),
);
const ethersFunction = self
._lookupEthersInterface(functionSignature)
.functions.getTokenByName(_name) as ethers.CallDescription;
const encodedData = ethersFunction.data;
const callDataWithDefaults = await self._applyDefaultsToTxDataAsync({
data: encodedData,
});
const rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock);
let resultArray = ethersFunction.parse(rawCallResult);
const outputAbi = (_.find(self.abi, { name: 'getTokenByName' }) as MethodAbi).outputs;
resultArray = BaseContract._formatABIDataItemList(
outputAbi,
resultArray,
BaseContract._lowercaseAddress.bind(this),
);
resultArray = BaseContract._formatABIDataItemList(
outputAbi,
resultArray,
BaseContract._bnToBigNumber.bind(this),
);
return resultArray;
},
};
public getTokenAddresses = {
async callAsync(callData: Partial<CallData> = {}, defaultBlock?: BlockParam): Promise<string[]> {
const self = (this as any) as TokenRegistryContract;
const functionSignature = 'getTokenAddresses()';
const inputAbi = self._lookupAbi(functionSignature).inputs;
[] = BaseContract._formatABIDataItemList(inputAbi, [], BaseContract._bigNumberToString.bind(self));
const ethersFunction = self
._lookupEthersInterface(functionSignature)
.functions.getTokenAddresses() as ethers.CallDescription;
const encodedData = ethersFunction.data;
const callDataWithDefaults = await self._applyDefaultsToTxDataAsync({
data: encodedData,
});
const rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock);
let resultArray = ethersFunction.parse(rawCallResult);
const outputAbi = (_.find(self.abi, { name: 'getTokenAddresses' }) as MethodAbi).outputs;
resultArray = BaseContract._formatABIDataItemList(
outputAbi,
resultArray,
BaseContract._lowercaseAddress.bind(this),
);
resultArray = BaseContract._formatABIDataItemList(
outputAbi,
resultArray,
BaseContract._bnToBigNumber.bind(this),
);
return resultArray[0];
},
};
public setTokenIpfsHash = {
async sendTransactionAsync(_token: string, _ipfsHash: string, txData: Partial<TxData> = {}): Promise<string> {
const self = (this as any) as TokenRegistryContract;
const inputAbi = self._lookupAbi('setTokenIpfsHash(address,bytes)').inputs;
[_token, _ipfsHash] = BaseContract._formatABIDataItemList(
inputAbi,
[_token, _ipfsHash],
BaseContract._bigNumberToString.bind(self),
);
const encodedData = self
._lookupEthersInterface('setTokenIpfsHash(address,bytes)')
.functions.setTokenIpfsHash(_token, _ipfsHash).data;
const txDataWithDefaults = await self._applyDefaultsToTxDataAsync(
{
...txData,
data: encodedData,
},
self.setTokenIpfsHash.estimateGasAsync.bind(self, _token, _ipfsHash),
);
const txHash = await self._web3Wrapper.sendTransactionAsync(txDataWithDefaults);
return txHash;
},
async estimateGasAsync(_token: string, _ipfsHash: string, txData: Partial<TxData> = {}): Promise<number> {
const self = (this as any) as TokenRegistryContract;
const inputAbi = self._lookupAbi('setTokenIpfsHash(address,bytes)').inputs;
[_token, _ipfsHash] = BaseContract._formatABIDataItemList(
inputAbi,
[_token, _ipfsHash],
BaseContract._bigNumberToString.bind(this),
);
const encodedData = self
._lookupEthersInterface('setTokenIpfsHash(address,bytes)')
.functions.setTokenIpfsHash(_token, _ipfsHash).data;
const txDataWithDefaults = await self._applyDefaultsToTxDataAsync({
...txData,
data: encodedData,
});
const gas = await self._web3Wrapper.estimateGasAsync(txDataWithDefaults);
return gas;
},
getABIEncodedTransactionData(_token: string, _ipfsHash: string): string {
const self = (this as any) as TokenRegistryContract;
const inputAbi = self._lookupAbi('setTokenIpfsHash(address,bytes)').inputs;
[_token, _ipfsHash] = BaseContract._formatABIDataItemList(
inputAbi,
[_token, _ipfsHash],
BaseContract._bigNumberToString.bind(self),
);
const abiEncodedTransactionData = self
._lookupEthersInterface('setTokenIpfsHash(address,bytes)')
.functions.setTokenIpfsHash(_token, _ipfsHash).data;
return abiEncodedTransactionData;
},
};
public getTokenBySymbol = {
async callAsync(
_symbol: string,
callData: Partial<CallData> = {},
defaultBlock?: BlockParam,
): Promise<[string, string, string, number, string, string]> {
const self = (this as any) as TokenRegistryContract;
const functionSignature = 'getTokenBySymbol(string)';
const inputAbi = self._lookupAbi(functionSignature).inputs;
[_symbol] = BaseContract._formatABIDataItemList(
inputAbi,
[_symbol],
BaseContract._bigNumberToString.bind(self),
);
const ethersFunction = self
._lookupEthersInterface(functionSignature)
.functions.getTokenBySymbol(_symbol) as ethers.CallDescription;
const encodedData = ethersFunction.data;
const callDataWithDefaults = await self._applyDefaultsToTxDataAsync({
data: encodedData,
});
const rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock);
let resultArray = ethersFunction.parse(rawCallResult);
const outputAbi = (_.find(self.abi, { name: 'getTokenBySymbol' }) as MethodAbi).outputs;
resultArray = BaseContract._formatABIDataItemList(
outputAbi,
resultArray,
BaseContract._lowercaseAddress.bind(this),
);
resultArray = BaseContract._formatABIDataItemList(
outputAbi,
resultArray,
BaseContract._bnToBigNumber.bind(this),
);
return resultArray;
},
};
public setTokenSymbol = {
async sendTransactionAsync(_token: string, _symbol: string, txData: Partial<TxData> = {}): Promise<string> {
const self = (this as any) as TokenRegistryContract;
const inputAbi = self._lookupAbi('setTokenSymbol(address,string)').inputs;
[_token, _symbol] = BaseContract._formatABIDataItemList(
inputAbi,
[_token, _symbol],
BaseContract._bigNumberToString.bind(self),
);
const encodedData = self
._lookupEthersInterface('setTokenSymbol(address,string)')
.functions.setTokenSymbol(_token, _symbol).data;
const txDataWithDefaults = await self._applyDefaultsToTxDataAsync(
{
...txData,
data: encodedData,
},
self.setTokenSymbol.estimateGasAsync.bind(self, _token, _symbol),
);
const txHash = await self._web3Wrapper.sendTransactionAsync(txDataWithDefaults);
return txHash;
},
async estimateGasAsync(_token: string, _symbol: string, txData: Partial<TxData> = {}): Promise<number> {
const self = (this as any) as TokenRegistryContract;
const inputAbi = self._lookupAbi('setTokenSymbol(address,string)').inputs;
[_token, _symbol] = BaseContract._formatABIDataItemList(
inputAbi,
[_token, _symbol],
BaseContract._bigNumberToString.bind(this),
);
const encodedData = self
._lookupEthersInterface('setTokenSymbol(address,string)')
.functions.setTokenSymbol(_token, _symbol).data;
const txDataWithDefaults = await self._applyDefaultsToTxDataAsync({
...txData,
data: encodedData,
});
const gas = await self._web3Wrapper.estimateGasAsync(txDataWithDefaults);
return gas;
},
getABIEncodedTransactionData(_token: string, _symbol: string): string {
const self = (this as any) as TokenRegistryContract;
const inputAbi = self._lookupAbi('setTokenSymbol(address,string)').inputs;
[_token, _symbol] = BaseContract._formatABIDataItemList(
inputAbi,
[_token, _symbol],
BaseContract._bigNumberToString.bind(self),
);
const abiEncodedTransactionData = self
._lookupEthersInterface('setTokenSymbol(address,string)')
.functions.setTokenSymbol(_token, _symbol).data;
return abiEncodedTransactionData;
},
};
public transferOwnership = {
async sendTransactionAsync(newOwner: string, txData: Partial<TxData> = {}): Promise<string> {
const self = (this as any) as TokenRegistryContract;
const inputAbi = self._lookupAbi('transferOwnership(address)').inputs;
[newOwner] = BaseContract._formatABIDataItemList(
inputAbi,
[newOwner],
BaseContract._bigNumberToString.bind(self),
);
const encodedData = self
._lookupEthersInterface('transferOwnership(address)')
.functions.transferOwnership(newOwner).data;
const txDataWithDefaults = await self._applyDefaultsToTxDataAsync(
{
...txData,
data: encodedData,
},
self.transferOwnership.estimateGasAsync.bind(self, newOwner),
);
const txHash = await self._web3Wrapper.sendTransactionAsync(txDataWithDefaults);
return txHash;
},
async estimateGasAsync(newOwner: string, txData: Partial<TxData> = {}): Promise<number> {
const self = (this as any) as TokenRegistryContract;
const inputAbi = self._lookupAbi('transferOwnership(address)').inputs;
[newOwner] = BaseContract._formatABIDataItemList(
inputAbi,
[newOwner],
BaseContract._bigNumberToString.bind(this),
);
const encodedData = self
._lookupEthersInterface('transferOwnership(address)')
.functions.transferOwnership(newOwner).data;
const txDataWithDefaults = await self._applyDefaultsToTxDataAsync({
...txData,
data: encodedData,
});
const gas = await self._web3Wrapper.estimateGasAsync(txDataWithDefaults);
return gas;
},
getABIEncodedTransactionData(newOwner: string): string {
const self = (this as any) as TokenRegistryContract;
const inputAbi = self._lookupAbi('transferOwnership(address)').inputs;
[newOwner] = BaseContract._formatABIDataItemList(
inputAbi,
[newOwner],
BaseContract._bigNumberToString.bind(self),
);
const abiEncodedTransactionData = self
._lookupEthersInterface('transferOwnership(address)')
.functions.transferOwnership(newOwner).data;
return abiEncodedTransactionData;
},
};
constructor(abi: ContractAbi, address: string, provider: Provider, defaults?: Partial<TxData>) {
super(abi, address, provider, defaults);
classUtils.bindAll(this, ['_ethersInterfacesByFunctionSignature', 'address', 'abi', '_web3Wrapper']);
}
} // tslint:disable:max-file-line-count

View File

@ -0,0 +1,447 @@
/**
* This file is auto-generated using abi-gen. Don't edit directly.
* Templates can be found at https://github.com/0xProject/0x-monorepo/tree/development/packages/contract_templates.
*/
// tslint:disable:no-consecutive-blank-lines
// tslint:disable-next-line:no-unused-variable
import { BaseContract } from '@0xproject/base-contract';
import {
BlockParam,
BlockParamLiteral,
CallData,
ContractAbi,
DataItem,
MethodAbi,
Provider,
TxData,
TxDataPayable,
} from '@0xproject/types';
import { BigNumber, classUtils, promisify } from '@0xproject/utils';
import { Web3Wrapper } from '@0xproject/web3-wrapper';
import * as ethers from 'ethers';
import * as _ from 'lodash';
export type TokenTransferProxyContractEventArgs =
| LogAuthorizedAddressAddedContractEventArgs
| LogAuthorizedAddressRemovedContractEventArgs;
export enum TokenTransferProxyEvents {
LogAuthorizedAddressAdded = 'LogAuthorizedAddressAdded',
LogAuthorizedAddressRemoved = 'LogAuthorizedAddressRemoved',
}
export interface LogAuthorizedAddressAddedContractEventArgs {
target: string;
caller: string;
}
export interface LogAuthorizedAddressRemovedContractEventArgs {
target: string;
caller: string;
}
// tslint:disable:no-parameter-reassignment
export class TokenTransferProxyContract extends BaseContract {
public transferFrom = {
async sendTransactionAsync(
token: string,
from: string,
to: string,
value: BigNumber,
txData: Partial<TxData> = {},
): Promise<string> {
const self = (this as any) as TokenTransferProxyContract;
const inputAbi = self._lookupAbi('transferFrom(address,address,address,uint256)').inputs;
[token, from, to, value] = BaseContract._formatABIDataItemList(
inputAbi,
[token, from, to, value],
BaseContract._bigNumberToString.bind(self),
);
const encodedData = self
._lookupEthersInterface('transferFrom(address,address,address,uint256)')
.functions.transferFrom(token, from, to, value).data;
const txDataWithDefaults = await self._applyDefaultsToTxDataAsync(
{
...txData,
data: encodedData,
},
self.transferFrom.estimateGasAsync.bind(self, token, from, to, value),
);
const txHash = await self._web3Wrapper.sendTransactionAsync(txDataWithDefaults);
return txHash;
},
async estimateGasAsync(
token: string,
from: string,
to: string,
value: BigNumber,
txData: Partial<TxData> = {},
): Promise<number> {
const self = (this as any) as TokenTransferProxyContract;
const inputAbi = self._lookupAbi('transferFrom(address,address,address,uint256)').inputs;
[token, from, to, value] = BaseContract._formatABIDataItemList(
inputAbi,
[token, from, to, value],
BaseContract._bigNumberToString.bind(this),
);
const encodedData = self
._lookupEthersInterface('transferFrom(address,address,address,uint256)')
.functions.transferFrom(token, from, to, value).data;
const txDataWithDefaults = await self._applyDefaultsToTxDataAsync({
...txData,
data: encodedData,
});
const gas = await self._web3Wrapper.estimateGasAsync(txDataWithDefaults);
return gas;
},
getABIEncodedTransactionData(token: string, from: string, to: string, value: BigNumber): string {
const self = (this as any) as TokenTransferProxyContract;
const inputAbi = self._lookupAbi('transferFrom(address,address,address,uint256)').inputs;
[token, from, to, value] = BaseContract._formatABIDataItemList(
inputAbi,
[token, from, to, value],
BaseContract._bigNumberToString.bind(self),
);
const abiEncodedTransactionData = self
._lookupEthersInterface('transferFrom(address,address,address,uint256)')
.functions.transferFrom(token, from, to, value).data;
return abiEncodedTransactionData;
},
async callAsync(
token: string,
from: string,
to: string,
value: BigNumber,
callData: Partial<CallData> = {},
defaultBlock?: BlockParam,
): Promise<boolean> {
const self = (this as any) as TokenTransferProxyContract;
const functionSignature = 'transferFrom(address,address,address,uint256)';
const inputAbi = self._lookupAbi(functionSignature).inputs;
[token, from, to, value] = BaseContract._formatABIDataItemList(
inputAbi,
[token, from, to, value],
BaseContract._bigNumberToString.bind(self),
);
const ethersFunction = self
._lookupEthersInterface(functionSignature)
.functions.transferFrom(token, from, to, value) as ethers.CallDescription;
const encodedData = ethersFunction.data;
const callDataWithDefaults = await self._applyDefaultsToTxDataAsync({
data: encodedData,
});
const rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock);
let resultArray = ethersFunction.parse(rawCallResult);
const outputAbi = (_.find(self.abi, { name: 'transferFrom' }) as MethodAbi).outputs;
resultArray = BaseContract._formatABIDataItemList(
outputAbi,
resultArray,
BaseContract._lowercaseAddress.bind(this),
);
resultArray = BaseContract._formatABIDataItemList(
outputAbi,
resultArray,
BaseContract._bnToBigNumber.bind(this),
);
return resultArray[0];
},
};
public addAuthorizedAddress = {
async sendTransactionAsync(target: string, txData: Partial<TxData> = {}): Promise<string> {
const self = (this as any) as TokenTransferProxyContract;
const inputAbi = self._lookupAbi('addAuthorizedAddress(address)').inputs;
[target] = BaseContract._formatABIDataItemList(
inputAbi,
[target],
BaseContract._bigNumberToString.bind(self),
);
const encodedData = self
._lookupEthersInterface('addAuthorizedAddress(address)')
.functions.addAuthorizedAddress(target).data;
const txDataWithDefaults = await self._applyDefaultsToTxDataAsync(
{
...txData,
data: encodedData,
},
self.addAuthorizedAddress.estimateGasAsync.bind(self, target),
);
const txHash = await self._web3Wrapper.sendTransactionAsync(txDataWithDefaults);
return txHash;
},
async estimateGasAsync(target: string, txData: Partial<TxData> = {}): Promise<number> {
const self = (this as any) as TokenTransferProxyContract;
const inputAbi = self._lookupAbi('addAuthorizedAddress(address)').inputs;
[target] = BaseContract._formatABIDataItemList(
inputAbi,
[target],
BaseContract._bigNumberToString.bind(this),
);
const encodedData = self
._lookupEthersInterface('addAuthorizedAddress(address)')
.functions.addAuthorizedAddress(target).data;
const txDataWithDefaults = await self._applyDefaultsToTxDataAsync({
...txData,
data: encodedData,
});
const gas = await self._web3Wrapper.estimateGasAsync(txDataWithDefaults);
return gas;
},
getABIEncodedTransactionData(target: string): string {
const self = (this as any) as TokenTransferProxyContract;
const inputAbi = self._lookupAbi('addAuthorizedAddress(address)').inputs;
[target] = BaseContract._formatABIDataItemList(
inputAbi,
[target],
BaseContract._bigNumberToString.bind(self),
);
const abiEncodedTransactionData = self
._lookupEthersInterface('addAuthorizedAddress(address)')
.functions.addAuthorizedAddress(target).data;
return abiEncodedTransactionData;
},
};
public authorities = {
async callAsync(
index_0: BigNumber,
callData: Partial<CallData> = {},
defaultBlock?: BlockParam,
): Promise<string> {
const self = (this as any) as TokenTransferProxyContract;
const functionSignature = 'authorities(uint256)';
const inputAbi = self._lookupAbi(functionSignature).inputs;
[index_0] = BaseContract._formatABIDataItemList(
inputAbi,
[index_0],
BaseContract._bigNumberToString.bind(self),
);
const ethersFunction = self
._lookupEthersInterface(functionSignature)
.functions.authorities(index_0) as ethers.CallDescription;
const encodedData = ethersFunction.data;
const callDataWithDefaults = await self._applyDefaultsToTxDataAsync({
data: encodedData,
});
const rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock);
let resultArray = ethersFunction.parse(rawCallResult);
const outputAbi = (_.find(self.abi, { name: 'authorities' }) as MethodAbi).outputs;
resultArray = BaseContract._formatABIDataItemList(
outputAbi,
resultArray,
BaseContract._lowercaseAddress.bind(this),
);
resultArray = BaseContract._formatABIDataItemList(
outputAbi,
resultArray,
BaseContract._bnToBigNumber.bind(this),
);
return resultArray[0];
},
};
public removeAuthorizedAddress = {
async sendTransactionAsync(target: string, txData: Partial<TxData> = {}): Promise<string> {
const self = (this as any) as TokenTransferProxyContract;
const inputAbi = self._lookupAbi('removeAuthorizedAddress(address)').inputs;
[target] = BaseContract._formatABIDataItemList(
inputAbi,
[target],
BaseContract._bigNumberToString.bind(self),
);
const encodedData = self
._lookupEthersInterface('removeAuthorizedAddress(address)')
.functions.removeAuthorizedAddress(target).data;
const txDataWithDefaults = await self._applyDefaultsToTxDataAsync(
{
...txData,
data: encodedData,
},
self.removeAuthorizedAddress.estimateGasAsync.bind(self, target),
);
const txHash = await self._web3Wrapper.sendTransactionAsync(txDataWithDefaults);
return txHash;
},
async estimateGasAsync(target: string, txData: Partial<TxData> = {}): Promise<number> {
const self = (this as any) as TokenTransferProxyContract;
const inputAbi = self._lookupAbi('removeAuthorizedAddress(address)').inputs;
[target] = BaseContract._formatABIDataItemList(
inputAbi,
[target],
BaseContract._bigNumberToString.bind(this),
);
const encodedData = self
._lookupEthersInterface('removeAuthorizedAddress(address)')
.functions.removeAuthorizedAddress(target).data;
const txDataWithDefaults = await self._applyDefaultsToTxDataAsync({
...txData,
data: encodedData,
});
const gas = await self._web3Wrapper.estimateGasAsync(txDataWithDefaults);
return gas;
},
getABIEncodedTransactionData(target: string): string {
const self = (this as any) as TokenTransferProxyContract;
const inputAbi = self._lookupAbi('removeAuthorizedAddress(address)').inputs;
[target] = BaseContract._formatABIDataItemList(
inputAbi,
[target],
BaseContract._bigNumberToString.bind(self),
);
const abiEncodedTransactionData = self
._lookupEthersInterface('removeAuthorizedAddress(address)')
.functions.removeAuthorizedAddress(target).data;
return abiEncodedTransactionData;
},
};
public owner = {
async callAsync(callData: Partial<CallData> = {}, defaultBlock?: BlockParam): Promise<string> {
const self = (this as any) as TokenTransferProxyContract;
const functionSignature = 'owner()';
const inputAbi = self._lookupAbi(functionSignature).inputs;
[] = BaseContract._formatABIDataItemList(inputAbi, [], BaseContract._bigNumberToString.bind(self));
const ethersFunction = self
._lookupEthersInterface(functionSignature)
.functions.owner() as ethers.CallDescription;
const encodedData = ethersFunction.data;
const callDataWithDefaults = await self._applyDefaultsToTxDataAsync({
data: encodedData,
});
const rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock);
let resultArray = ethersFunction.parse(rawCallResult);
const outputAbi = (_.find(self.abi, { name: 'owner' }) as MethodAbi).outputs;
resultArray = BaseContract._formatABIDataItemList(
outputAbi,
resultArray,
BaseContract._lowercaseAddress.bind(this),
);
resultArray = BaseContract._formatABIDataItemList(
outputAbi,
resultArray,
BaseContract._bnToBigNumber.bind(this),
);
return resultArray[0];
},
};
public authorized = {
async callAsync(
index_0: string,
callData: Partial<CallData> = {},
defaultBlock?: BlockParam,
): Promise<boolean> {
const self = (this as any) as TokenTransferProxyContract;
const functionSignature = 'authorized(address)';
const inputAbi = self._lookupAbi(functionSignature).inputs;
[index_0] = BaseContract._formatABIDataItemList(
inputAbi,
[index_0],
BaseContract._bigNumberToString.bind(self),
);
const ethersFunction = self
._lookupEthersInterface(functionSignature)
.functions.authorized(index_0) as ethers.CallDescription;
const encodedData = ethersFunction.data;
const callDataWithDefaults = await self._applyDefaultsToTxDataAsync({
data: encodedData,
});
const rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock);
let resultArray = ethersFunction.parse(rawCallResult);
const outputAbi = (_.find(self.abi, { name: 'authorized' }) as MethodAbi).outputs;
resultArray = BaseContract._formatABIDataItemList(
outputAbi,
resultArray,
BaseContract._lowercaseAddress.bind(this),
);
resultArray = BaseContract._formatABIDataItemList(
outputAbi,
resultArray,
BaseContract._bnToBigNumber.bind(this),
);
return resultArray[0];
},
};
public getAuthorizedAddresses = {
async callAsync(callData: Partial<CallData> = {}, defaultBlock?: BlockParam): Promise<string[]> {
const self = (this as any) as TokenTransferProxyContract;
const functionSignature = 'getAuthorizedAddresses()';
const inputAbi = self._lookupAbi(functionSignature).inputs;
[] = BaseContract._formatABIDataItemList(inputAbi, [], BaseContract._bigNumberToString.bind(self));
const ethersFunction = self
._lookupEthersInterface(functionSignature)
.functions.getAuthorizedAddresses() as ethers.CallDescription;
const encodedData = ethersFunction.data;
const callDataWithDefaults = await self._applyDefaultsToTxDataAsync({
data: encodedData,
});
const rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock);
let resultArray = ethersFunction.parse(rawCallResult);
const outputAbi = (_.find(self.abi, { name: 'getAuthorizedAddresses' }) as MethodAbi).outputs;
resultArray = BaseContract._formatABIDataItemList(
outputAbi,
resultArray,
BaseContract._lowercaseAddress.bind(this),
);
resultArray = BaseContract._formatABIDataItemList(
outputAbi,
resultArray,
BaseContract._bnToBigNumber.bind(this),
);
return resultArray[0];
},
};
public transferOwnership = {
async sendTransactionAsync(newOwner: string, txData: Partial<TxData> = {}): Promise<string> {
const self = (this as any) as TokenTransferProxyContract;
const inputAbi = self._lookupAbi('transferOwnership(address)').inputs;
[newOwner] = BaseContract._formatABIDataItemList(
inputAbi,
[newOwner],
BaseContract._bigNumberToString.bind(self),
);
const encodedData = self
._lookupEthersInterface('transferOwnership(address)')
.functions.transferOwnership(newOwner).data;
const txDataWithDefaults = await self._applyDefaultsToTxDataAsync(
{
...txData,
data: encodedData,
},
self.transferOwnership.estimateGasAsync.bind(self, newOwner),
);
const txHash = await self._web3Wrapper.sendTransactionAsync(txDataWithDefaults);
return txHash;
},
async estimateGasAsync(newOwner: string, txData: Partial<TxData> = {}): Promise<number> {
const self = (this as any) as TokenTransferProxyContract;
const inputAbi = self._lookupAbi('transferOwnership(address)').inputs;
[newOwner] = BaseContract._formatABIDataItemList(
inputAbi,
[newOwner],
BaseContract._bigNumberToString.bind(this),
);
const encodedData = self
._lookupEthersInterface('transferOwnership(address)')
.functions.transferOwnership(newOwner).data;
const txDataWithDefaults = await self._applyDefaultsToTxDataAsync({
...txData,
data: encodedData,
});
const gas = await self._web3Wrapper.estimateGasAsync(txDataWithDefaults);
return gas;
},
getABIEncodedTransactionData(newOwner: string): string {
const self = (this as any) as TokenTransferProxyContract;
const inputAbi = self._lookupAbi('transferOwnership(address)').inputs;
[newOwner] = BaseContract._formatABIDataItemList(
inputAbi,
[newOwner],
BaseContract._bigNumberToString.bind(self),
);
const abiEncodedTransactionData = self
._lookupEthersInterface('transferOwnership(address)')
.functions.transferOwnership(newOwner).data;
return abiEncodedTransactionData;
},
};
constructor(abi: ContractAbi, address: string, provider: Provider, defaults?: Partial<TxData>) {
super(abi, address, provider, defaults);
classUtils.bindAll(this, ['_ethersInterfacesByFunctionSignature', 'address', 'abi', '_web3Wrapper']);
}
} // tslint:disable:max-file-line-count

View File

@ -1,8 +1,9 @@
import { Token } from '@0xproject/types';
import { Web3Wrapper } from '@0xproject/web3-wrapper'; import { Web3Wrapper } from '@0xproject/web3-wrapper';
import * as _ from 'lodash'; import * as _ from 'lodash';
import { artifacts } from '../artifacts'; import { artifacts } from '../artifacts';
import { Token, TokenMetadata } from '../types'; import { TokenMetadata } from '../types';
import { assert } from '../utils/assert'; import { assert } from '../utils/assert';
import { constants } from '../utils/constants'; import { constants } from '../utils/constants';
@ -105,7 +106,7 @@ export class TokenRegistryWrapper extends ContractWrapper {
*/ */
public getContractAddress(): string { public getContractAddress(): string {
const contractAddress = this._getContractAddress( const contractAddress = this._getContractAddress(
artifacts.TokenRegistryArtifact, artifacts.TokenRegistry,
this._contractAddressIfExists, this._contractAddressIfExists,
); );
return contractAddress; return contractAddress;
@ -118,7 +119,7 @@ export class TokenRegistryWrapper extends ContractWrapper {
return this._tokenRegistryContractIfExists; return this._tokenRegistryContractIfExists;
} }
const [abi, address] = await this._getContractAbiAndAddressFromArtifactsAsync( const [abi, address] = await this._getContractAbiAndAddressFromArtifactsAsync(
artifacts.TokenRegistryArtifact, artifacts.TokenRegistry,
this._contractAddressIfExists, this._contractAddressIfExists,
); );
const contractInstance = new TokenRegistryContract( const contractInstance = new TokenRegistryContract(

View File

@ -47,7 +47,7 @@ export class TokenTransferProxyWrapper extends ContractWrapper {
*/ */
public getContractAddress(): string { public getContractAddress(): string {
const contractAddress = this._getContractAddress( const contractAddress = this._getContractAddress(
artifacts.TokenTransferProxyArtifact, artifacts.TokenTransferProxy,
this._contractAddressIfExists, this._contractAddressIfExists,
); );
return contractAddress; return contractAddress;
@ -60,7 +60,7 @@ export class TokenTransferProxyWrapper extends ContractWrapper {
return this._tokenTransferProxyContractIfExists; return this._tokenTransferProxyContractIfExists;
} }
const [abi, address] = await this._getContractAbiAndAddressFromArtifactsAsync( const [abi, address] = await this._getContractAbiAndAddressFromArtifactsAsync(
artifacts.TokenTransferProxyArtifact, artifacts.TokenTransferProxy,
this._contractAddressIfExists, this._contractAddressIfExists,
); );
const contractInstance = new TokenTransferProxyContract( const contractInstance = new TokenTransferProxyContract(

View File

@ -5,7 +5,14 @@ import { Web3Wrapper } from '@0xproject/web3-wrapper';
import * as _ from 'lodash'; import * as _ from 'lodash';
import { artifacts } from '../artifacts'; import { artifacts } from '../artifacts';
import { BlockRange, EventCallback, IndexedFilterValues, MethodOpts, TransactionOpts, ZeroExError } from '../types'; import {
BlockRange,
ContractWrappersError,
EventCallback,
IndexedFilterValues,
MethodOpts,
TransactionOpts,
} from '../types';
import { assert } from '../utils/assert'; import { assert } from '../utils/assert';
import { constants } from '../utils/constants'; import { constants } from '../utils/constants';
@ -266,7 +273,7 @@ export class TokenWrapper extends ContractWrapper {
const fromAddressBalance = await this.getBalanceAsync(normalizedTokenAddress, normalizedFromAddress); const fromAddressBalance = await this.getBalanceAsync(normalizedTokenAddress, normalizedFromAddress);
if (fromAddressBalance.lessThan(amountInBaseUnits)) { if (fromAddressBalance.lessThan(amountInBaseUnits)) {
throw new Error(ZeroExError.InsufficientBalanceForTransfer); throw new Error(ContractWrappersError.InsufficientBalanceForTransfer);
} }
const txHash = await tokenContract.transfer.sendTransactionAsync(normalizedToAddress, amountInBaseUnits, { const txHash = await tokenContract.transfer.sendTransactionAsync(normalizedToAddress, amountInBaseUnits, {
@ -316,12 +323,12 @@ export class TokenWrapper extends ContractWrapper {
normalizedSenderAddress, normalizedSenderAddress,
); );
if (fromAddressAllowance.lessThan(amountInBaseUnits)) { if (fromAddressAllowance.lessThan(amountInBaseUnits)) {
throw new Error(ZeroExError.InsufficientAllowanceForTransfer); throw new Error(ContractWrappersError.InsufficientAllowanceForTransfer);
} }
const fromAddressBalance = await this.getBalanceAsync(normalizedTokenAddress, normalizedFromAddress); const fromAddressBalance = await this.getBalanceAsync(normalizedTokenAddress, normalizedFromAddress);
if (fromAddressBalance.lessThan(amountInBaseUnits)) { if (fromAddressBalance.lessThan(amountInBaseUnits)) {
throw new Error(ZeroExError.InsufficientBalanceForTransfer); throw new Error(ContractWrappersError.InsufficientBalanceForTransfer);
} }
const txHash = await tokenContract.transferFrom.sendTransactionAsync( const txHash = await tokenContract.transferFrom.sendTransactionAsync(
@ -360,7 +367,7 @@ export class TokenWrapper extends ContractWrapper {
normalizedTokenAddress, normalizedTokenAddress,
eventName, eventName,
indexFilterValues, indexFilterValues,
artifacts.TokenArtifact.abi, artifacts.Token.abi,
callback, callback,
); );
return subscriptionToken; return subscriptionToken;
@ -403,7 +410,7 @@ export class TokenWrapper extends ContractWrapper {
eventName, eventName,
blockRange, blockRange,
indexFilterValues, indexFilterValues,
artifacts.TokenArtifact.abi, artifacts.Token.abi,
); );
return logs; return logs;
} }
@ -418,7 +425,7 @@ export class TokenWrapper extends ContractWrapper {
return tokenContract; return tokenContract;
} }
const [abi, address] = await this._getContractAbiAndAddressFromArtifactsAsync( const [abi, address] = await this._getContractAbiAndAddressFromArtifactsAsync(
artifacts.TokenArtifact, artifacts.Token,
normalizedTokenAddress, normalizedTokenAddress,
); );
const contractInstance = new TokenContract( const contractInstance = new TokenContract(

View File

@ -1,10 +1,10 @@
import { AbstractBalanceAndProxyAllowanceFetcher } from '@0xproject/order-utils';
import { BlockParamLiteral } from '@0xproject/types'; import { BlockParamLiteral } from '@0xproject/types';
import { BigNumber } from '@0xproject/utils'; import { BigNumber } from '@0xproject/utils';
import { BalanceAndProxyAllowanceFetcher } from '../abstract/balance_and_proxy_allowance_fetcher';
import { TokenWrapper } from '../contract_wrappers/token_wrapper'; import { TokenWrapper } from '../contract_wrappers/token_wrapper';
export class SimpleBalanceAndProxyAllowanceFetcher implements BalanceAndProxyAllowanceFetcher { export class SimpleBalanceAndProxyAllowanceFetcher implements AbstractBalanceAndProxyAllowanceFetcher {
private _tokenWrapper: TokenWrapper; private _tokenWrapper: TokenWrapper;
private _defaultBlock: BlockParamLiteral; private _defaultBlock: BlockParamLiteral;
constructor(token: TokenWrapper, defaultBlock: BlockParamLiteral) { constructor(token: TokenWrapper, defaultBlock: BlockParamLiteral) {

View File

@ -1,10 +1,10 @@
import { AbstractOrderFilledCancelledFetcher } from '@0xproject/order-utils';
import { BlockParamLiteral } from '@0xproject/types'; import { BlockParamLiteral } from '@0xproject/types';
import { BigNumber } from '@0xproject/utils'; import { BigNumber } from '@0xproject/utils';
import { OrderFilledCancelledFetcher } from '../abstract/order_filled_cancelled_fetcher';
import { ExchangeWrapper } from '../contract_wrappers/exchange_wrapper'; import { ExchangeWrapper } from '../contract_wrappers/exchange_wrapper';
export class SimpleOrderFilledCancelledFetcher implements OrderFilledCancelledFetcher { export class SimpleOrderFilledCancelledFetcher implements AbstractOrderFilledCancelledFetcher {
private _exchangeWrapper: ExchangeWrapper; private _exchangeWrapper: ExchangeWrapper;
private _defaultBlock: BlockParamLiteral; private _defaultBlock: BlockParamLiteral;
constructor(exchange: ExchangeWrapper, defaultBlock: BlockParamLiteral) { constructor(exchange: ExchangeWrapper, defaultBlock: BlockParamLiteral) {
@ -25,4 +25,10 @@ export class SimpleOrderFilledCancelledFetcher implements OrderFilledCancelledFe
const cancelledTakerAmount = this._exchangeWrapper.getCancelledTakerAmountAsync(orderHash, methodOpts); const cancelledTakerAmount = this._exchangeWrapper.getCancelledTakerAmountAsync(orderHash, methodOpts);
return cancelledTakerAmount; return cancelledTakerAmount;
} }
public async getUnavailableTakerAmountAsync(orderHash: string) {
return this._exchangeWrapper.getUnavailableTakerAmountAsync(orderHash);
}
public getZRXTokenAddress(): string {
return this._exchangeWrapper.getZRXTokenAddress();
}
} }

View File

@ -0,0 +1,6 @@
declare module '*.json' {
const json: any;
/* tslint:disable */
export default json;
/* tslint:enable */
}

View File

@ -0,0 +1,68 @@
export { ContractWrappers } from './contract_wrappers';
export { ExchangeWrapper } from './contract_wrappers/exchange_wrapper';
export { TokenWrapper } from './contract_wrappers/token_wrapper';
export { TokenRegistryWrapper } from './contract_wrappers/token_registry_wrapper';
export { EtherTokenWrapper } from './contract_wrappers/ether_token_wrapper';
export { TokenTransferProxyWrapper } from './contract_wrappers/token_transfer_proxy_wrapper';
export {
ContractWrappersError,
EventCallback,
ContractEvent,
Token,
IndexedFilterValues,
BlockRange,
OrderCancellationRequest,
OrderFillRequest,
ContractEventArgs,
ZeroExContractConfig,
MethodOpts,
OrderTransactionOpts,
TransactionOpts,
LogEvent,
DecodedLogEvent,
OnOrderStateChangeCallback,
} from './types';
export {
BlockParamLiteral,
FilterObject,
BlockParam,
ContractEventArg,
ExchangeContractErrs,
LogWithDecodedArgs,
Order,
Provider,
SignedOrder,
ECSignature,
OrderStateValid,
OrderStateInvalid,
OrderState,
TransactionReceipt,
TransactionReceiptWithDecodedLogs,
} from '@0xproject/types';
export {
EtherTokenContractEventArgs,
WithdrawalContractEventArgs,
DepositContractEventArgs,
EtherTokenEvents,
} from './contract_wrappers/generated/ether_token';
export {
TransferContractEventArgs,
ApprovalContractEventArgs,
TokenContractEventArgs,
TokenEvents,
} from './contract_wrappers/generated/token';
export {
LogErrorContractEventArgs,
LogCancelContractEventArgs,
LogFillContractEventArgs,
ExchangeContractEventArgs,
ExchangeEvents,
} from './contract_wrappers/generated/exchange';
export { BalanceAndProxyAllowanceLazyStore } from './stores/balance_proxy_allowance_lazy_store';
export { OrderFilledCancelledLazyStore } from './stores/order_filled_cancelled_lazy_store';

View File

@ -0,0 +1,8 @@
import { postpublishUtils } from '@0xproject/monorepo-scripts';
import * as packageJSON from '../package.json';
import * as tsConfigJSON from '../tsconfig.json';
const cwd = `${__dirname}/..`;
// tslint:disable-next-line:no-floating-promises
postpublishUtils.runAsync(packageJSON, tsConfigJSON, cwd);

View File

@ -0,0 +1,5 @@
export const zeroExContractConfigSchema = {
id: '/ZeroExContractConfig',
oneOf: [{ $ref: '/ZeroExContractPrivateNetworkConfig' }, { $ref: '/ZeroExContractPublicNetworkConfig' }],
type: 'object',
};

View File

@ -0,0 +1,35 @@
export const zeroExContractPrivateNetworkConfigSchema = {
id: '/ZeroExContractPrivateNetworkConfig',
properties: {
networkId: {
type: 'number',
minimum: 1,
},
gasPrice: { $ref: '/Number' },
zrxContractAddress: { $ref: '/Address' },
exchangeContractAddress: { $ref: '/Address' },
tokenRegistryContractAddress: { $ref: '/Address' },
tokenTransferProxyContractAddress: { $ref: '/Address' },
orderWatcherConfig: {
type: 'object',
properties: {
pollingIntervalMs: {
type: 'number',
minimum: 0,
},
numConfirmations: {
type: 'number',
minimum: 0,
},
},
},
},
type: 'object',
required: [
'networkId',
'zrxContractAddress',
'exchangeContractAddress',
'tokenRegistryContractAddress',
'tokenTransferProxyContractAddress',
],
};

View File

@ -0,0 +1,29 @@
export const zeroExContractPublicNetworkConfigSchema = {
id: '/ZeroExContractPublicNetworkConfig',
properties: {
networkId: {
type: 'number',
enum: [1, 3, 4, 42, 50],
},
gasPrice: { $ref: '/Number' },
zrxContractAddress: { $ref: '/Address' },
exchangeContractAddress: { $ref: '/Address' },
tokenRegistryContractAddress: { $ref: '/Address' },
tokenTransferProxyContractAddress: { $ref: '/Address' },
orderWatcherConfig: {
type: 'object',
properties: {
pollingIntervalMs: {
type: 'number',
minimum: 0,
},
numConfirmations: {
type: 'number',
minimum: 0,
},
},
},
},
type: 'object',
required: ['networkId'],
};

View File

@ -1,14 +1,14 @@
import { AbstractBalanceAndProxyAllowanceFetcher } from '@0xproject/order-utils';
import { BlockParamLiteral } from '@0xproject/types'; import { BlockParamLiteral } from '@0xproject/types';
import { BigNumber } from '@0xproject/utils'; import { BigNumber } from '@0xproject/utils';
import * as _ from 'lodash'; import * as _ from 'lodash';
import { BalanceAndProxyAllowanceFetcher } from '../abstract/balance_and_proxy_allowance_fetcher';
import { TokenWrapper } from '../contract_wrappers/token_wrapper'; import { TokenWrapper } from '../contract_wrappers/token_wrapper';
/** /**
* Copy on read store for balances/proxyAllowances of tokens/accounts * Copy on read store for balances/proxyAllowances of tokens/accounts
*/ */
export class BalanceAndProxyAllowanceLazyStore implements BalanceAndProxyAllowanceFetcher { export class BalanceAndProxyAllowanceLazyStore implements AbstractBalanceAndProxyAllowanceFetcher {
private _tokenWrapper: TokenWrapper; private _tokenWrapper: TokenWrapper;
private _defaultBlock: BlockParamLiteral; private _defaultBlock: BlockParamLiteral;
private _balance: { private _balance: {

View File

@ -1,14 +1,14 @@
import { AbstractOrderFilledCancelledFetcher } from '@0xproject/order-utils';
import { BlockParamLiteral } from '@0xproject/types'; import { BlockParamLiteral } from '@0xproject/types';
import { BigNumber } from '@0xproject/utils'; import { BigNumber } from '@0xproject/utils';
import * as _ from 'lodash'; import * as _ from 'lodash';
import { OrderFilledCancelledFetcher } from '../abstract/order_filled_cancelled_fetcher';
import { ExchangeWrapper } from '../contract_wrappers/exchange_wrapper'; import { ExchangeWrapper } from '../contract_wrappers/exchange_wrapper';
/** /**
* Copy on read store for filled/cancelled taker amounts * Copy on read store for filled/cancelled taker amounts
*/ */
export class OrderFilledCancelledLazyStore implements OrderFilledCancelledFetcher { export class OrderFilledCancelledLazyStore implements AbstractOrderFilledCancelledFetcher {
private _exchangeWrapper: ExchangeWrapper; private _exchangeWrapper: ExchangeWrapper;
private _defaultBlock: BlockParamLiteral; private _defaultBlock: BlockParamLiteral;
private _filledTakerAmount: { private _filledTakerAmount: {
@ -64,4 +64,10 @@ export class OrderFilledCancelledLazyStore implements OrderFilledCancelledFetche
this._filledTakerAmount = {}; this._filledTakerAmount = {};
this._cancelledTakerAmount = {}; this._cancelledTakerAmount = {};
} }
public async getUnavailableTakerAmountAsync(orderHash: string) {
return this._exchangeWrapper.getUnavailableTakerAmountAsync(orderHash);
}
public getZRXTokenAddress(): string {
return this._exchangeWrapper.getZRXTokenAddress();
}
} }

View File

@ -0,0 +1,187 @@
import { BigNumber } from '@0xproject/utils';
import {
BlockParam,
BlockParamLiteral,
ContractAbi,
ContractEventArg,
ExchangeContractErrs,
FilterObject,
LogEntryEvent,
LogWithDecodedArgs,
Order,
OrderState,
SignedOrder,
} from '@0xproject/types';
import { EtherTokenContractEventArgs, EtherTokenEvents } from './contract_wrappers/generated/ether_token';
import { ExchangeContractEventArgs, ExchangeEvents } from './contract_wrappers/generated/exchange';
import { TokenContractEventArgs, TokenEvents } from './contract_wrappers/generated/token';
export enum ContractWrappersError {
ExchangeContractDoesNotExist = 'EXCHANGE_CONTRACT_DOES_NOT_EXIST',
ZRXContractDoesNotExist = 'ZRX_CONTRACT_DOES_NOT_EXIST',
EtherTokenContractDoesNotExist = 'ETHER_TOKEN_CONTRACT_DOES_NOT_EXIST',
TokenTransferProxyContractDoesNotExist = 'TOKEN_TRANSFER_PROXY_CONTRACT_DOES_NOT_EXIST',
TokenRegistryContractDoesNotExist = 'TOKEN_REGISTRY_CONTRACT_DOES_NOT_EXIST',
TokenContractDoesNotExist = 'TOKEN_CONTRACT_DOES_NOT_EXIST',
ContractNotDeployedOnNetwork = 'CONTRACT_NOT_DEPLOYED_ON_NETWORK',
InsufficientAllowanceForTransfer = 'INSUFFICIENT_ALLOWANCE_FOR_TRANSFER',
InsufficientBalanceForTransfer = 'INSUFFICIENT_BALANCE_FOR_TRANSFER',
InsufficientEthBalanceForDeposit = 'INSUFFICIENT_ETH_BALANCE_FOR_DEPOSIT',
InsufficientWEthBalanceForWithdrawal = 'INSUFFICIENT_WETH_BALANCE_FOR_WITHDRAWAL',
InvalidJump = 'INVALID_JUMP',
OutOfGas = 'OUT_OF_GAS',
SubscriptionNotFound = 'SUBSCRIPTION_NOT_FOUND',
SubscriptionAlreadyPresent = 'SUBSCRIPTION_ALREADY_PRESENT',
}
export enum InternalContractWrappersError {
NoAbiDecoder = 'NO_ABI_DECODER',
ZrxNotInTokenRegistry = 'ZRX_NOT_IN_TOKEN_REGISTRY',
WethNotInTokenRegistry = 'WETH_NOT_IN_TOKEN_REGISTRY',
}
export type LogEvent = LogEntryEvent;
export interface DecodedLogEvent<ArgsType> {
isRemoved: boolean;
log: LogWithDecodedArgs<ArgsType>;
}
export type EventCallback<ArgsType> = (err: null | Error, log?: DecodedLogEvent<ArgsType>) => void;
export enum ExchangeContractErrCodes {
ERROR_FILL_EXPIRED, // Order has already expired
ERROR_FILL_NO_VALUE, // Order has already been fully filled or cancelled
ERROR_FILL_TRUNCATION, // Rounding error too large
ERROR_FILL_BALANCE_ALLOWANCE, // Insufficient balance or allowance for token transfer
ERROR_CANCEL_EXPIRED, // Order has already expired
ERROR_CANCEL_NO_VALUE, // Order has already been fully filled or cancelled
}
export interface ContractEvent {
logIndex: number;
transactionIndex: number;
transactionHash: string;
blockHash: string;
blockNumber: number;
address: string;
type: string;
event: string;
args: ContractEventArgs;
}
export type ContractEventArgs = ExchangeContractEventArgs | TokenContractEventArgs | EtherTokenContractEventArgs;
// [address, name, symbol, decimals, ipfsHash, swarmHash]
export type TokenMetadata = [string, string, string, number, string, string];
export interface Token {
name: string;
address: string;
symbol: string;
decimals: number;
}
export interface TxOpts {
from: string;
gas?: number;
value?: BigNumber;
gasPrice?: BigNumber;
}
export interface TokenAddressBySymbol {
[symbol: string]: string;
}
export type ContractEvents = TokenEvents | ExchangeEvents | EtherTokenEvents;
export interface IndexedFilterValues {
[index: string]: ContractEventArg;
}
export interface BlockRange {
fromBlock: BlockParam;
toBlock: BlockParam;
}
export interface OrderCancellationRequest {
order: Order | SignedOrder;
takerTokenCancelAmount: BigNumber;
}
export interface OrderFillRequest {
signedOrder: SignedOrder;
takerTokenFillAmount: BigNumber;
}
export type AsyncMethod = (...args: any[]) => Promise<any>;
export type SyncMethod = (...args: any[]) => any;
/**
* networkId: The id of the underlying ethereum network your provider is connected to. (1-mainnet, 3-ropsten, 4-rinkeby, 42-kovan, 50-testrpc)
* gasPrice: Gas price to use with every transaction
* exchangeContractAddress: The address of an exchange contract to use
* zrxContractAddress: The address of the ZRX contract to use
* tokenRegistryContractAddress: The address of a token registry contract to use
* tokenTransferProxyContractAddress: The address of the token transfer proxy contract to use
* orderWatcherConfig: All the configs related to the orderWatcher
*/
export interface ZeroExContractConfig {
networkId: number;
gasPrice?: BigNumber;
exchangeContractAddress?: string;
zrxContractAddress?: string;
tokenRegistryContractAddress?: string;
tokenTransferProxyContractAddress?: string;
}
/**
* expectedFillTakerTokenAmount: If specified, the validation method will ensure that the
* supplied order maker has a sufficient allowance/balance to fill this amount of the order's
* takerTokenAmount. If not specified, the validation method ensures that the maker has a sufficient
* allowance/balance to fill the entire remaining order amount.
*/
export interface ValidateOrderFillableOpts {
expectedFillTakerTokenAmount?: BigNumber;
}
/**
* defaultBlock: The block up to which to query the blockchain state. Setting this to a historical block number
* let's the user query the blockchain's state at an arbitrary point in time. In order for this to work, the
* backing Ethereum node must keep the entire historical state of the chain (e.g setting `--pruning=archive`
* flag when running Parity).
*/
export interface MethodOpts {
defaultBlock?: BlockParam;
}
/**
* gasPrice: Gas price in Wei to use for a transaction
* gasLimit: The amount of gas to send with a transaction
*/
export interface TransactionOpts {
gasPrice?: BigNumber;
gasLimit?: number;
}
/**
* shouldValidate: Flag indicating whether the library should make attempts to validate a transaction before
* broadcasting it. For example, order has a valid signature, maker has sufficient funds, etc. Default=true.
*/
export interface OrderTransactionOpts extends TransactionOpts {
shouldValidate?: boolean;
}
export enum TradeSide {
Maker = 'maker',
Taker = 'taker',
}
export enum TransferType {
Trade = 'trade',
Fee = 'fee',
}
export type OnOrderStateChangeCallback = (err: Error | null, orderState?: OrderState) => void;
// tslint:disable:max-file-line-count

View File

@ -0,0 +1,11 @@
import { BigNumber } from '@0xproject/utils';
export const constants = {
NULL_ADDRESS: '0x0000000000000000000000000000000000000000',
TESTRPC_NETWORK_ID: 50,
INVALID_JUMP_PATTERN: 'invalid JUMP at',
OUT_OF_GAS_PATTERN: 'out of gas',
INVALID_TAKER_FORMAT: 'instance.taker is not of a type(s) string',
UNLIMITED_ALLOWANCE_IN_BASE_UNITS: new BigNumber(2).pow(256).minus(1),
DEFAULT_BLOCK_POLLING_INTERVAL: 1000,
};

View File

@ -1,6 +1,6 @@
import * as _ from 'lodash'; import * as _ from 'lodash';
import { AsyncMethod, SyncMethod, ZeroExError } from '../types'; import { AsyncMethod, ContractWrappersError, SyncMethod } from '../types';
import { constants } from './constants'; import { constants } from './constants';
@ -8,10 +8,10 @@ type ErrorTransformer = (err: Error) => Error;
const contractCallErrorTransformer = (error: Error) => { const contractCallErrorTransformer = (error: Error) => {
if (_.includes(error.message, constants.INVALID_JUMP_PATTERN)) { if (_.includes(error.message, constants.INVALID_JUMP_PATTERN)) {
return new Error(ZeroExError.InvalidJump); return new Error(ContractWrappersError.InvalidJump);
} }
if (_.includes(error.message, constants.OUT_OF_GAS_PATTERN)) { if (_.includes(error.message, constants.OUT_OF_GAS_PATTERN)) {
return new Error(ZeroExError.OutOfGas); return new Error(ContractWrappersError.OutOfGas);
} }
return error; return error;
}; };

View File

@ -1,10 +1,10 @@
import { BlockParamLiteral } from '@0xproject/types'; import { BlockParamLiteral, ExchangeContractErrs } from '@0xproject/types';
import { BigNumber } from '@0xproject/utils'; import { BigNumber } from '@0xproject/utils';
import * as _ from 'lodash'; import * as _ from 'lodash';
import { TokenWrapper } from '../contract_wrappers/token_wrapper'; import { TokenWrapper } from '../contract_wrappers/token_wrapper';
import { BalanceAndProxyAllowanceLazyStore } from '../stores/balance_proxy_allowance_lazy_store'; import { BalanceAndProxyAllowanceLazyStore } from '../stores/balance_proxy_allowance_lazy_store';
import { ExchangeContractErrs, TradeSide, TransferType } from '../types'; import { TradeSide, TransferType } from '../types';
import { constants } from '../utils/constants'; import { constants } from '../utils/constants';
enum FailureReason { enum FailureReason {

View File

@ -1,11 +1,10 @@
import { getOrderHashHex, OrderError } from '@0xproject/order-utils'; import { getOrderHashHex, isValidSignature, OrderError } from '@0xproject/order-utils';
import { Order, SignedOrder } from '@0xproject/types'; import { ExchangeContractErrs, Order, SignedOrder } from '@0xproject/types';
import { BigNumber } from '@0xproject/utils'; import { BigNumber } from '@0xproject/utils';
import * as _ from 'lodash'; import * as _ from 'lodash';
import { ZeroEx } from '../0x';
import { ExchangeWrapper } from '../contract_wrappers/exchange_wrapper'; import { ExchangeWrapper } from '../contract_wrappers/exchange_wrapper';
import { ExchangeContractErrs, TradeSide, TransferType, ZeroExError } from '../types'; import { ContractWrappersError, TradeSide, TransferType } from '../types';
import { constants } from '../utils/constants'; import { constants } from '../utils/constants';
import { utils } from '../utils/utils'; import { utils } from '../utils/utils';
@ -144,7 +143,7 @@ export class OrderValidationUtils {
throw new Error(ExchangeContractErrs.OrderFillAmountZero); throw new Error(ExchangeContractErrs.OrderFillAmountZero);
} }
const orderHash = getOrderHashHex(signedOrder); const orderHash = getOrderHashHex(signedOrder);
if (!ZeroEx.isValidSignature(orderHash, signedOrder.ecSignature, signedOrder.maker)) { if (!isValidSignature(orderHash, signedOrder.ecSignature, signedOrder.maker)) {
throw new Error(OrderError.InvalidSignature); throw new Error(OrderError.InvalidSignature);
} }
const unavailableTakerTokenAmount = await this._exchangeWrapper.getUnavailableTakerAmountAsync(orderHash); const unavailableTakerTokenAmount = await this._exchangeWrapper.getUnavailableTakerAmountAsync(orderHash);

View File

@ -0,0 +1,39 @@
{
"contract_name": "AccountLevels",
"networks": {
"50": {
"solc_version": "0.4.23",
"source_tree_hash": "0x48558bbda893aa15786836980a5fffb694db15163d462619c4dcb0f8ad97977b",
"optimizer_enabled": false,
"abi": [
{
"constant": true,
"inputs": [
{
"name": "user",
"type": "address"
}
],
"name": "accountLevel",
"outputs": [
{
"name": "",
"type": "uint256"
}
],
"payable": false,
"stateMutability": "view",
"type": "function"
}
],
"bytecode": "0x608060405234801561001057600080fd5b5060ce8061001f6000396000f300608060405260043610603f576000357c0100000000000000000000000000000000000000000000000000000000900463ffffffff1680631cbd0519146044575b600080fd5b348015604f57600080fd5b506082600480360381019080803573ffffffffffffffffffffffffffffffffffffffff1690602001909291905050506098565b6040518082815260200191505060405180910390f35b60008090509190505600a165627a7a72305820ba8f0553b1bad01d6aebe1dfdcea170d83055523ddd0c848be8952e0494b9e230029",
"runtime_bytecode": "0x608060405260043610603f576000357c0100000000000000000000000000000000000000000000000000000000900463ffffffff1680631cbd0519146044575b600080fd5b348015604f57600080fd5b506082600480360381019080803573ffffffffffffffffffffffffffffffffffffffff1690602001909291905050506098565b6040518082815260200191505060405180910390f35b60008090509190505600a165627a7a72305820ba8f0553b1bad01d6aebe1dfdcea170d83055523ddd0c848be8952e0494b9e230029",
"updated_at": 1525776887441,
"source_map": "26:388:0:-;;;;8:9:-1;5:2;;;30:1;27;20:12;5:2;26:388:0;;;;;;;",
"source_map_runtime": "26:388:0:-;;;;;;;;;;;;;;;;;;;;;;;;328:84;;8:9:-1;5:2;;;30:1;27;20:12;5:2;328:84:0;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;381:4;404:1;397:8;;328:84;;;:::o",
"sources": [
"/Users/fabioberger/Documents/projects/0x_project/0x-monorepo/packages/contracts/src/contracts/current/tutorials/EtherDelta/AccountLevels.sol"
]
}
}
}

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

View File

@ -0,0 +1,179 @@
{
"contract_name": "Token",
"networks": {
"50": {
"solc_version": "0.4.23",
"source_tree_hash": "0xe43382be55ddb9c7a28567b4cc59e35072da198e6c49a90ff1396aa8399fd61e",
"optimizer_enabled": false,
"abi": [
{
"constant": false,
"inputs": [
{
"name": "_spender",
"type": "address"
},
{
"name": "_value",
"type": "uint256"
}
],
"name": "approve",
"outputs": [
{
"name": "",
"type": "bool"
}
],
"payable": false,
"stateMutability": "nonpayable",
"type": "function"
},
{
"constant": false,
"inputs": [
{
"name": "_from",
"type": "address"
},
{
"name": "_to",
"type": "address"
},
{
"name": "_value",
"type": "uint256"
}
],
"name": "transferFrom",
"outputs": [
{
"name": "",
"type": "bool"
}
],
"payable": false,
"stateMutability": "nonpayable",
"type": "function"
},
{
"constant": true,
"inputs": [
{
"name": "_owner",
"type": "address"
}
],
"name": "balanceOf",
"outputs": [
{
"name": "",
"type": "uint256"
}
],
"payable": false,
"stateMutability": "view",
"type": "function"
},
{
"constant": false,
"inputs": [
{
"name": "_to",
"type": "address"
},
{
"name": "_value",
"type": "uint256"
}
],
"name": "transfer",
"outputs": [
{
"name": "",
"type": "bool"
}
],
"payable": false,
"stateMutability": "nonpayable",
"type": "function"
},
{
"constant": true,
"inputs": [
{
"name": "_owner",
"type": "address"
},
{
"name": "_spender",
"type": "address"
}
],
"name": "allowance",
"outputs": [
{
"name": "",
"type": "uint256"
}
],
"payable": false,
"stateMutability": "view",
"type": "function"
},
{
"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"
},
{
"anonymous": false,
"inputs": [
{
"indexed": true,
"name": "_owner",
"type": "address"
},
{
"indexed": true,
"name": "_spender",
"type": "address"
},
{
"indexed": false,
"name": "_value",
"type": "uint256"
}
],
"name": "Approval",
"type": "event"
}
],
"bytecode": "0x608060405234801561001057600080fd5b506102e3806100206000396000f30060806040526004361061006d576000357c0100000000000000000000000000000000000000000000000000000000900463ffffffff168063095ea7b31461007257806323b872dd146100d757806370a082311461015c578063a9059cbb146101b3578063dd62ed3e14610218575b600080fd5b34801561007e57600080fd5b506100bd600480360381019080803573ffffffffffffffffffffffffffffffffffffffff1690602001909291908035906020019092919050505061028f565b604051808215151515815260200191505060405180910390f35b3480156100e357600080fd5b50610142600480360381019080803573ffffffffffffffffffffffffffffffffffffffff169060200190929190803573ffffffffffffffffffffffffffffffffffffffff16906020019092919080359060200190929190505050610297565b604051808215151515815260200191505060405180910390f35b34801561016857600080fd5b5061019d600480360381019080803573ffffffffffffffffffffffffffffffffffffffff1690602001909291905050506102a0565b6040518082815260200191505060405180910390f35b3480156101bf57600080fd5b506101fe600480360381019080803573ffffffffffffffffffffffffffffffffffffffff169060200190929190803590602001909291905050506102a7565b604051808215151515815260200191505060405180910390f35b34801561022457600080fd5b50610279600480360381019080803573ffffffffffffffffffffffffffffffffffffffff169060200190929190803573ffffffffffffffffffffffffffffffffffffffff1690602001909291905050506102af565b6040518082815260200191505060405180910390f35b600092915050565b60009392505050565b6000919050565b600092915050565b6000929150505600a165627a7a72305820c0eb8c14c0b2d0b9f45639d053a22e400cf642410f155a793e5b2ea1e78925bb0029",
"runtime_bytecode": "0x60806040526004361061006d576000357c0100000000000000000000000000000000000000000000000000000000900463ffffffff168063095ea7b31461007257806323b872dd146100d757806370a082311461015c578063a9059cbb146101b3578063dd62ed3e14610218575b600080fd5b34801561007e57600080fd5b506100bd600480360381019080803573ffffffffffffffffffffffffffffffffffffffff1690602001909291908035906020019092919050505061028f565b604051808215151515815260200191505060405180910390f35b3480156100e357600080fd5b50610142600480360381019080803573ffffffffffffffffffffffffffffffffffffffff169060200190929190803573ffffffffffffffffffffffffffffffffffffffff16906020019092919080359060200190929190505050610297565b604051808215151515815260200191505060405180910390f35b34801561016857600080fd5b5061019d600480360381019080803573ffffffffffffffffffffffffffffffffffffffff1690602001909291905050506102a0565b6040518082815260200191505060405180910390f35b3480156101bf57600080fd5b506101fe600480360381019080803573ffffffffffffffffffffffffffffffffffffffff169060200190929190803590602001909291905050506102a7565b604051808215151515815260200191505060405180910390f35b34801561022457600080fd5b50610279600480360381019080803573ffffffffffffffffffffffffffffffffffffffff169060200190929190803573ffffffffffffffffffffffffffffffffffffffff1690602001909291905050506102af565b6040518082815260200191505060405180910390f35b600092915050565b60009392505050565b6000919050565b600092915050565b6000929150505600a165627a7a72305820c0eb8c14c0b2d0b9f45639d053a22e400cf642410f155a793e5b2ea1e78925bb0029",
"updated_at": 1525776876709,
"source_map": "26:1709:0:-;;;;8:9:-1;5:2;;;30:1;27;20:12;5:2;26:1709:0;;;;;;;",
"source_map_runtime": "26:1709:0:-;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;1037:72;;8:9:-1;5:2;;;30:1;27;20:12;5:2;1037:72:0;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;667:87;;8:9:-1;5:2;;;30:1;27;20:12;5:2;667:87:0;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;1218:64;;8:9:-1;5:2;;;30:1;27;20:12;5:2;1218:64:0;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;278:68;;8:9:-1;5:2;;;30:1;27;20:12;5:2;278:68:0;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;1490:82;;8:9:-1;5:2;;;30:1;27;20:12;5:2;1490:82:0;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;1037:72;1101:4;1037:72;;;;:::o;667:87::-;746:4;667:87;;;;;:::o;1218:64::-;1274:4;1218:64;;;:::o;278:68::-;338:4;278:68;;;;:::o;1490:82::-;1564:4;1490:82;;;;:::o",
"sources": [
"/Users/fabioberger/Documents/projects/0x_project/0x-monorepo/packages/contracts/src/contracts/current/tokens/Token/Token.sol"
]
}
}
}

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

View File

@ -0,0 +1,49 @@
import { web3Factory } from '@0xproject/dev-utils';
import * as fs from 'fs';
import { ContractWrappers } from '../src';
import { chaiSetup } from './utils/chai_setup';
import { constants } from './utils/constants';
chaiSetup.configure();
// Those tests are slower cause they're talking to a remote node
const TIMEOUT = 10000;
describe('Artifacts', () => {
describe('contracts are deployed on kovan', () => {
const kovanRpcUrl = constants.KOVAN_RPC_URL;
const provider = web3Factory.create({ rpcUrl: kovanRpcUrl }).currentProvider;
const config = {
networkId: constants.KOVAN_NETWORK_ID,
};
const contractWrappers = new ContractWrappers(provider, config);
it('token registry contract is deployed', async () => {
await (contractWrappers.tokenRegistry as any)._getTokenRegistryContractAsync();
}).timeout(TIMEOUT);
it('proxy contract is deployed', async () => {
await (contractWrappers.proxy as any)._getTokenTransferProxyContractAsync();
}).timeout(TIMEOUT);
it('exchange contract is deployed', async () => {
await (contractWrappers.exchange as any)._getExchangeContractAsync();
}).timeout(TIMEOUT);
});
describe('contracts are deployed on ropsten', () => {
const ropstenRpcUrl = constants.ROPSTEN_RPC_URL;
const provider = web3Factory.create({ rpcUrl: ropstenRpcUrl }).currentProvider;
const config = {
networkId: constants.ROPSTEN_NETWORK_ID,
};
const contractWrappers = new ContractWrappers(provider, config);
it('token registry contract is deployed', async () => {
await (contractWrappers.tokenRegistry as any)._getTokenRegistryContractAsync();
}).timeout(TIMEOUT);
it('proxy contract is deployed', async () => {
await (contractWrappers.proxy as any)._getTokenTransferProxyContractAsync();
}).timeout(TIMEOUT);
it('exchange contract is deployed', async () => {
await (contractWrappers.exchange as any)._getExchangeContractAsync();
}).timeout(TIMEOUT);
});
});

View File

@ -1,4 +1,5 @@
import { BlockchainLifecycle, devConstants, web3Factory } from '@0xproject/dev-utils'; import { BlockchainLifecycle, callbackErrorReporter, devConstants, web3Factory } from '@0xproject/dev-utils';
import { DoneCallback } from '@0xproject/types';
import { BigNumber } from '@0xproject/utils'; import { BigNumber } from '@0xproject/utils';
import { Web3Wrapper } from '@0xproject/web3-wrapper'; import { Web3Wrapper } from '@0xproject/web3-wrapper';
import * as chai from 'chai'; import * as chai from 'chai';
@ -8,20 +9,18 @@ import {
ApprovalContractEventArgs, ApprovalContractEventArgs,
BlockParamLiteral, BlockParamLiteral,
BlockRange, BlockRange,
ContractWrappers,
ContractWrappersError,
DecodedLogEvent, DecodedLogEvent,
DepositContractEventArgs, DepositContractEventArgs,
EtherTokenEvents, EtherTokenEvents,
Token, Token,
TransferContractEventArgs, TransferContractEventArgs,
WithdrawalContractEventArgs, WithdrawalContractEventArgs,
ZeroEx,
ZeroExError,
} from '../src'; } from '../src';
import { DoneCallback } from '../src/types';
import { chaiSetup } from './utils/chai_setup'; import { chaiSetup } from './utils/chai_setup';
import { constants } from './utils/constants'; import { constants } from './utils/constants';
import { reportNodeCallbackErrors } from './utils/report_callback_errors';
import { TokenUtils } from './utils/token_utils'; import { TokenUtils } from './utils/token_utils';
import { provider, web3Wrapper } from './utils/web3_wrapper'; import { provider, web3Wrapper } from './utils/web3_wrapper';
@ -36,7 +35,7 @@ const blockchainLifecycle = new BlockchainLifecycle(web3Wrapper);
const MAX_REASONABLE_GAS_COST_IN_WEI = 62517; const MAX_REASONABLE_GAS_COST_IN_WEI = 62517;
describe('EtherTokenWrapper', () => { describe('EtherTokenWrapper', () => {
let zeroEx: ZeroEx; let contractWrappers: ContractWrappers;
let tokens: Token[]; let tokens: Token[];
let userAddresses: string[]; let userAddresses: string[];
let addressWithETH: string; let addressWithETH: string;
@ -54,11 +53,11 @@ describe('EtherTokenWrapper', () => {
const depositAmount = new BigNumber(42); const depositAmount = new BigNumber(42);
const withdrawalAmount = new BigNumber(42); const withdrawalAmount = new BigNumber(42);
before(async () => { before(async () => {
zeroEx = new ZeroEx(provider, zeroExConfig); contractWrappers = new ContractWrappers(provider, zeroExConfig);
tokens = await zeroEx.tokenRegistry.getTokensAsync(); tokens = await contractWrappers.tokenRegistry.getTokensAsync();
userAddresses = await zeroEx.getAvailableAddressesAsync(); userAddresses = await web3Wrapper.getAvailableAddressesAsync();
addressWithETH = userAddresses[0]; addressWithETH = userAddresses[0];
wethContractAddress = zeroEx.etherToken.getContractAddressIfExists() as string; wethContractAddress = contractWrappers.etherToken.getContractAddressIfExists() as string;
depositWeiAmount = Web3Wrapper.toWei(new BigNumber(5)); depositWeiAmount = Web3Wrapper.toWei(new BigNumber(5));
decimalPlaces = 7; decimalPlaces = 7;
addressWithoutFunds = userAddresses[1]; addressWithoutFunds = userAddresses[1];
@ -71,14 +70,14 @@ describe('EtherTokenWrapper', () => {
}); });
describe('#getContractAddressIfExists', async () => { describe('#getContractAddressIfExists', async () => {
it('should return contract address if connected to a known network', () => { it('should return contract address if connected to a known network', () => {
const contractAddressIfExists = zeroEx.etherToken.getContractAddressIfExists(); const contractAddressIfExists = contractWrappers.etherToken.getContractAddressIfExists();
expect(contractAddressIfExists).to.not.be.undefined(); expect(contractAddressIfExists).to.not.be.undefined();
}); });
it('should throw if connected to a private network and contract addresses are not specified', () => { it('should throw if connected to a private network and contract addresses are not specified', () => {
const UNKNOWN_NETWORK_NETWORK_ID = 10; const UNKNOWN_NETWORK_NETWORK_ID = 10;
expect( expect(
() => () =>
new ZeroEx(provider, { new ContractWrappers(provider, {
networkId: UNKNOWN_NETWORK_NETWORK_ID, networkId: UNKNOWN_NETWORK_NETWORK_ID,
} as any), } as any),
).to.throw(); ).to.throw();
@ -86,16 +85,23 @@ describe('EtherTokenWrapper', () => {
}); });
describe('#depositAsync', () => { describe('#depositAsync', () => {
it('should successfully deposit ETH and issue Wrapped ETH tokens', async () => { it('should successfully deposit ETH and issue Wrapped ETH tokens', async () => {
const preETHBalance = await (zeroEx as any)._web3Wrapper.getBalanceInWeiAsync(addressWithETH); const preETHBalance = await web3Wrapper.getBalanceInWeiAsync(addressWithETH);
const preWETHBalance = await zeroEx.token.getBalanceAsync(wethContractAddress, addressWithETH); const preWETHBalance = await contractWrappers.token.getBalanceAsync(wethContractAddress, addressWithETH);
expect(preETHBalance).to.be.bignumber.gt(0); expect(preETHBalance).to.be.bignumber.gt(0);
expect(preWETHBalance).to.be.bignumber.equal(0); expect(preWETHBalance).to.be.bignumber.equal(0);
const txHash = await zeroEx.etherToken.depositAsync(wethContractAddress, depositWeiAmount, addressWithETH); const txHash = await contractWrappers.etherToken.depositAsync(
await zeroEx.awaitTransactionMinedAsync(txHash); wethContractAddress,
depositWeiAmount,
addressWithETH,
);
await web3Wrapper.awaitTransactionMinedAsync(txHash);
const postETHBalanceInWei = await (zeroEx as any)._web3Wrapper.getBalanceInWeiAsync(addressWithETH); const postETHBalanceInWei = await web3Wrapper.getBalanceInWeiAsync(addressWithETH);
const postWETHBalanceInBaseUnits = await zeroEx.token.getBalanceAsync(wethContractAddress, addressWithETH); const postWETHBalanceInBaseUnits = await contractWrappers.token.getBalanceAsync(
wethContractAddress,
addressWithETH,
);
expect(postWETHBalanceInBaseUnits).to.be.bignumber.equal(depositWeiAmount); expect(postWETHBalanceInBaseUnits).to.be.bignumber.equal(depositWeiAmount);
const remainingETHInWei = preETHBalance.minus(depositWeiAmount); const remainingETHInWei = preETHBalance.minus(depositWeiAmount);
@ -103,34 +109,41 @@ describe('EtherTokenWrapper', () => {
expect(gasCost).to.be.bignumber.lte(MAX_REASONABLE_GAS_COST_IN_WEI); expect(gasCost).to.be.bignumber.lte(MAX_REASONABLE_GAS_COST_IN_WEI);
}); });
it('should throw if user has insufficient ETH balance for deposit', async () => { it('should throw if user has insufficient ETH balance for deposit', async () => {
const preETHBalance = await (zeroEx as any)._web3Wrapper.getBalanceInWeiAsync(addressWithETH); const preETHBalance = await web3Wrapper.getBalanceInWeiAsync(addressWithETH);
const extraETHBalance = Web3Wrapper.toWei(new BigNumber(5)); const extraETHBalance = Web3Wrapper.toWei(new BigNumber(5));
const overETHBalanceinWei = preETHBalance.add(extraETHBalance); const overETHBalanceinWei = preETHBalance.add(extraETHBalance);
return expect( return expect(
zeroEx.etherToken.depositAsync(wethContractAddress, overETHBalanceinWei, addressWithETH), contractWrappers.etherToken.depositAsync(wethContractAddress, overETHBalanceinWei, addressWithETH),
).to.be.rejectedWith(ZeroExError.InsufficientEthBalanceForDeposit); ).to.be.rejectedWith(ContractWrappersError.InsufficientEthBalanceForDeposit);
}); });
}); });
describe('#withdrawAsync', () => { describe('#withdrawAsync', () => {
it('should successfully withdraw ETH in return for Wrapped ETH tokens', async () => { it('should successfully withdraw ETH in return for Wrapped ETH tokens', async () => {
const ETHBalanceInWei = await (zeroEx as any)._web3Wrapper.getBalanceInWeiAsync(addressWithETH); const ETHBalanceInWei = await web3Wrapper.getBalanceInWeiAsync(addressWithETH);
await zeroEx.etherToken.depositAsync(wethContractAddress, depositWeiAmount, addressWithETH); await contractWrappers.etherToken.depositAsync(wethContractAddress, depositWeiAmount, addressWithETH);
const expectedPreETHBalance = ETHBalanceInWei.minus(depositWeiAmount); const expectedPreETHBalance = ETHBalanceInWei.minus(depositWeiAmount);
const preETHBalance = await (zeroEx as any)._web3Wrapper.getBalanceInWeiAsync(addressWithETH); const preETHBalance = await web3Wrapper.getBalanceInWeiAsync(addressWithETH);
const preWETHBalance = await zeroEx.token.getBalanceAsync(wethContractAddress, addressWithETH); const preWETHBalance = await contractWrappers.token.getBalanceAsync(wethContractAddress, addressWithETH);
let gasCost = expectedPreETHBalance.minus(preETHBalance); let gasCost = expectedPreETHBalance.minus(preETHBalance);
expect(gasCost).to.be.bignumber.lte(MAX_REASONABLE_GAS_COST_IN_WEI); expect(gasCost).to.be.bignumber.lte(MAX_REASONABLE_GAS_COST_IN_WEI);
expect(preWETHBalance).to.be.bignumber.equal(depositWeiAmount); expect(preWETHBalance).to.be.bignumber.equal(depositWeiAmount);
const txHash = await zeroEx.etherToken.withdrawAsync(wethContractAddress, depositWeiAmount, addressWithETH); const txHash = await contractWrappers.etherToken.withdrawAsync(
await zeroEx.awaitTransactionMinedAsync(txHash); wethContractAddress,
depositWeiAmount,
addressWithETH,
);
await web3Wrapper.awaitTransactionMinedAsync(txHash);
const postETHBalance = await (zeroEx as any)._web3Wrapper.getBalanceInWeiAsync(addressWithETH); const postETHBalance = await web3Wrapper.getBalanceInWeiAsync(addressWithETH);
const postWETHBalanceInBaseUnits = await zeroEx.token.getBalanceAsync(wethContractAddress, addressWithETH); const postWETHBalanceInBaseUnits = await contractWrappers.token.getBalanceAsync(
wethContractAddress,
addressWithETH,
);
expect(postWETHBalanceInBaseUnits).to.be.bignumber.equal(0); expect(postWETHBalanceInBaseUnits).to.be.bignumber.equal(0);
const expectedETHBalance = preETHBalance.add(depositWeiAmount).round(decimalPlaces); const expectedETHBalance = preETHBalance.add(depositWeiAmount).round(decimalPlaces);
@ -138,14 +151,14 @@ describe('EtherTokenWrapper', () => {
expect(gasCost).to.be.bignumber.lte(MAX_REASONABLE_GAS_COST_IN_WEI); expect(gasCost).to.be.bignumber.lte(MAX_REASONABLE_GAS_COST_IN_WEI);
}); });
it('should throw if user has insufficient WETH balance for withdrawal', async () => { it('should throw if user has insufficient WETH balance for withdrawal', async () => {
const preWETHBalance = await zeroEx.token.getBalanceAsync(wethContractAddress, addressWithETH); const preWETHBalance = await contractWrappers.token.getBalanceAsync(wethContractAddress, addressWithETH);
expect(preWETHBalance).to.be.bignumber.equal(0); expect(preWETHBalance).to.be.bignumber.equal(0);
const overWETHBalance = preWETHBalance.add(999999999); const overWETHBalance = preWETHBalance.add(999999999);
return expect( return expect(
zeroEx.etherToken.withdrawAsync(wethContractAddress, overWETHBalance, addressWithETH), contractWrappers.etherToken.withdrawAsync(wethContractAddress, overWETHBalance, addressWithETH),
).to.be.rejectedWith(ZeroExError.InsufficientWEthBalanceForWithdrawal); ).to.be.rejectedWith(ContractWrappersError.InsufficientWEthBalanceForWithdrawal);
}); });
}); });
describe('#subscribe', () => { describe('#subscribe', () => {
@ -157,7 +170,7 @@ describe('EtherTokenWrapper', () => {
etherTokenAddress = etherToken.address; etherTokenAddress = etherToken.address;
}); });
afterEach(() => { afterEach(() => {
zeroEx.etherToken.unsubscribeAll(); contractWrappers.etherToken.unsubscribeAll();
}); });
// Hack: Mocha does not allow a test to be both async and have a `done` callback // Hack: Mocha does not allow a test to be both async and have a `done` callback
// Since we need to await the receipt of the event in the `subscribe` callback, // Since we need to await the receipt of the event in the `subscribe` callback,
@ -166,7 +179,7 @@ describe('EtherTokenWrapper', () => {
// Source: https://github.com/mochajs/mocha/issues/2407 // Source: https://github.com/mochajs/mocha/issues/2407
it('Should receive the Transfer event when tokens are transfered', (done: DoneCallback) => { it('Should receive the Transfer event when tokens are transfered', (done: DoneCallback) => {
(async () => { (async () => {
const callback = reportNodeCallbackErrors(done)( const callback = callbackErrorReporter.reportNodeCallbackErrors(done)(
(logEvent: DecodedLogEvent<TransferContractEventArgs>) => { (logEvent: DecodedLogEvent<TransferContractEventArgs>) => {
expect(logEvent).to.not.be.undefined(); expect(logEvent).to.not.be.undefined();
expect(logEvent.isRemoved).to.be.false(); expect(logEvent.isRemoved).to.be.false();
@ -179,9 +192,14 @@ describe('EtherTokenWrapper', () => {
expect(args._value).to.be.bignumber.equal(transferAmount); expect(args._value).to.be.bignumber.equal(transferAmount);
}, },
); );
await zeroEx.etherToken.depositAsync(etherTokenAddress, transferAmount, addressWithETH); await contractWrappers.etherToken.depositAsync(etherTokenAddress, transferAmount, addressWithETH);
zeroEx.etherToken.subscribe(etherTokenAddress, EtherTokenEvents.Transfer, indexFilterValues, callback); contractWrappers.etherToken.subscribe(
await zeroEx.token.transferAsync( etherTokenAddress,
EtherTokenEvents.Transfer,
indexFilterValues,
callback,
);
await contractWrappers.token.transferAsync(
etherTokenAddress, etherTokenAddress,
addressWithETH, addressWithETH,
addressWithoutFunds, addressWithoutFunds,
@ -191,7 +209,7 @@ describe('EtherTokenWrapper', () => {
}); });
it('Should receive the Approval event when allowance is being set', (done: DoneCallback) => { it('Should receive the Approval event when allowance is being set', (done: DoneCallback) => {
(async () => { (async () => {
const callback = reportNodeCallbackErrors(done)( const callback = callbackErrorReporter.reportNodeCallbackErrors(done)(
(logEvent: DecodedLogEvent<ApprovalContractEventArgs>) => { (logEvent: DecodedLogEvent<ApprovalContractEventArgs>) => {
expect(logEvent).to.not.be.undefined(); expect(logEvent).to.not.be.undefined();
expect(logEvent.isRemoved).to.be.false(); expect(logEvent.isRemoved).to.be.false();
@ -201,8 +219,13 @@ describe('EtherTokenWrapper', () => {
expect(args._value).to.be.bignumber.equal(allowanceAmount); expect(args._value).to.be.bignumber.equal(allowanceAmount);
}, },
); );
zeroEx.etherToken.subscribe(etherTokenAddress, EtherTokenEvents.Approval, indexFilterValues, callback); contractWrappers.etherToken.subscribe(
await zeroEx.token.setAllowanceAsync( etherTokenAddress,
EtherTokenEvents.Approval,
indexFilterValues,
callback,
);
await contractWrappers.token.setAllowanceAsync(
etherTokenAddress, etherTokenAddress,
addressWithETH, addressWithETH,
addressWithoutFunds, addressWithoutFunds,
@ -212,7 +235,7 @@ describe('EtherTokenWrapper', () => {
}); });
it('Should receive the Deposit event when ether is being deposited', (done: DoneCallback) => { it('Should receive the Deposit event when ether is being deposited', (done: DoneCallback) => {
(async () => { (async () => {
const callback = reportNodeCallbackErrors(done)( const callback = callbackErrorReporter.reportNodeCallbackErrors(done)(
(logEvent: DecodedLogEvent<DepositContractEventArgs>) => { (logEvent: DecodedLogEvent<DepositContractEventArgs>) => {
expect(logEvent).to.not.be.undefined(); expect(logEvent).to.not.be.undefined();
expect(logEvent.isRemoved).to.be.false(); expect(logEvent.isRemoved).to.be.false();
@ -221,13 +244,18 @@ describe('EtherTokenWrapper', () => {
expect(args._value).to.be.bignumber.equal(depositAmount); expect(args._value).to.be.bignumber.equal(depositAmount);
}, },
); );
zeroEx.etherToken.subscribe(etherTokenAddress, EtherTokenEvents.Deposit, indexFilterValues, callback); contractWrappers.etherToken.subscribe(
await zeroEx.etherToken.depositAsync(etherTokenAddress, depositAmount, addressWithETH); etherTokenAddress,
EtherTokenEvents.Deposit,
indexFilterValues,
callback,
);
await contractWrappers.etherToken.depositAsync(etherTokenAddress, depositAmount, addressWithETH);
})().catch(done); })().catch(done);
}); });
it('Should receive the Withdrawal event when ether is being withdrawn', (done: DoneCallback) => { it('Should receive the Withdrawal event when ether is being withdrawn', (done: DoneCallback) => {
(async () => { (async () => {
const callback = reportNodeCallbackErrors(done)( const callback = callbackErrorReporter.reportNodeCallbackErrors(done)(
(logEvent: DecodedLogEvent<WithdrawalContractEventArgs>) => { (logEvent: DecodedLogEvent<WithdrawalContractEventArgs>) => {
expect(logEvent).to.not.be.undefined(); expect(logEvent).to.not.be.undefined();
expect(logEvent.isRemoved).to.be.false(); expect(logEvent.isRemoved).to.be.false();
@ -236,39 +264,39 @@ describe('EtherTokenWrapper', () => {
expect(args._value).to.be.bignumber.equal(depositAmount); expect(args._value).to.be.bignumber.equal(depositAmount);
}, },
); );
await zeroEx.etherToken.depositAsync(etherTokenAddress, depositAmount, addressWithETH); await contractWrappers.etherToken.depositAsync(etherTokenAddress, depositAmount, addressWithETH);
zeroEx.etherToken.subscribe( contractWrappers.etherToken.subscribe(
etherTokenAddress, etherTokenAddress,
EtherTokenEvents.Withdrawal, EtherTokenEvents.Withdrawal,
indexFilterValues, indexFilterValues,
callback, callback,
); );
await zeroEx.etherToken.withdrawAsync(etherTokenAddress, withdrawalAmount, addressWithETH); await contractWrappers.etherToken.withdrawAsync(etherTokenAddress, withdrawalAmount, addressWithETH);
})().catch(done); })().catch(done);
}); });
it('should cancel outstanding subscriptions when ZeroEx.setProvider is called', (done: DoneCallback) => { it('should cancel outstanding subscriptions when ZeroEx.setProvider is called', (done: DoneCallback) => {
(async () => { (async () => {
const callbackNeverToBeCalled = reportNodeCallbackErrors(done)( const callbackNeverToBeCalled = callbackErrorReporter.reportNodeCallbackErrors(done)(
(logEvent: DecodedLogEvent<ApprovalContractEventArgs>) => { (logEvent: DecodedLogEvent<ApprovalContractEventArgs>) => {
done(new Error('Expected this subscription to have been cancelled')); done(new Error('Expected this subscription to have been cancelled'));
}, },
); );
zeroEx.etherToken.subscribe( contractWrappers.etherToken.subscribe(
etherTokenAddress, etherTokenAddress,
EtherTokenEvents.Transfer, EtherTokenEvents.Transfer,
indexFilterValues, indexFilterValues,
callbackNeverToBeCalled, callbackNeverToBeCalled,
); );
const callbackToBeCalled = reportNodeCallbackErrors(done)(); const callbackToBeCalled = callbackErrorReporter.reportNodeCallbackErrors(done)();
zeroEx.setProvider(provider, constants.TESTRPC_NETWORK_ID); contractWrappers.setProvider(provider, constants.TESTRPC_NETWORK_ID);
await zeroEx.etherToken.depositAsync(etherTokenAddress, transferAmount, addressWithETH); await contractWrappers.etherToken.depositAsync(etherTokenAddress, transferAmount, addressWithETH);
zeroEx.etherToken.subscribe( contractWrappers.etherToken.subscribe(
etherTokenAddress, etherTokenAddress,
EtherTokenEvents.Transfer, EtherTokenEvents.Transfer,
indexFilterValues, indexFilterValues,
callbackToBeCalled, callbackToBeCalled,
); );
await zeroEx.token.transferAsync( await contractWrappers.token.transferAsync(
etherTokenAddress, etherTokenAddress,
addressWithETH, addressWithETH,
addressWithoutFunds, addressWithoutFunds,
@ -278,20 +306,20 @@ describe('EtherTokenWrapper', () => {
}); });
it('Should cancel subscription when unsubscribe called', (done: DoneCallback) => { it('Should cancel subscription when unsubscribe called', (done: DoneCallback) => {
(async () => { (async () => {
const callbackNeverToBeCalled = reportNodeCallbackErrors(done)( const callbackNeverToBeCalled = callbackErrorReporter.reportNodeCallbackErrors(done)(
(logEvent: DecodedLogEvent<ApprovalContractEventArgs>) => { (logEvent: DecodedLogEvent<ApprovalContractEventArgs>) => {
done(new Error('Expected this subscription to have been cancelled')); done(new Error('Expected this subscription to have been cancelled'));
}, },
); );
await zeroEx.etherToken.depositAsync(etherTokenAddress, transferAmount, addressWithETH); await contractWrappers.etherToken.depositAsync(etherTokenAddress, transferAmount, addressWithETH);
const subscriptionToken = zeroEx.etherToken.subscribe( const subscriptionToken = contractWrappers.etherToken.subscribe(
etherTokenAddress, etherTokenAddress,
EtherTokenEvents.Transfer, EtherTokenEvents.Transfer,
indexFilterValues, indexFilterValues,
callbackNeverToBeCalled, callbackNeverToBeCalled,
); );
zeroEx.etherToken.unsubscribe(subscriptionToken); contractWrappers.etherToken.unsubscribe(subscriptionToken);
await zeroEx.token.transferAsync( await contractWrappers.token.transferAsync(
etherTokenAddress, etherTokenAddress,
addressWithETH, addressWithETH,
addressWithoutFunds, addressWithoutFunds,
@ -314,14 +342,14 @@ describe('EtherTokenWrapper', () => {
const tokenUtils = new TokenUtils(tokens); const tokenUtils = new TokenUtils(tokens);
const etherToken = tokenUtils.getWethTokenOrThrow(); const etherToken = tokenUtils.getWethTokenOrThrow();
etherTokenAddress = etherToken.address; etherTokenAddress = etherToken.address;
tokenTransferProxyAddress = zeroEx.proxy.getContractAddress(); tokenTransferProxyAddress = contractWrappers.proxy.getContractAddress();
}); });
it('should get logs with decoded args emitted by Approval', async () => { it('should get logs with decoded args emitted by Approval', async () => {
txHash = await zeroEx.token.setUnlimitedProxyAllowanceAsync(etherTokenAddress, addressWithETH); txHash = await contractWrappers.token.setUnlimitedProxyAllowanceAsync(etherTokenAddress, addressWithETH);
await zeroEx.awaitTransactionMinedAsync(txHash); await web3Wrapper.awaitTransactionMinedAsync(txHash);
const eventName = EtherTokenEvents.Approval; const eventName = EtherTokenEvents.Approval;
const indexFilterValues = {}; const indexFilterValues = {};
const logs = await zeroEx.etherToken.getLogsAsync<ApprovalContractEventArgs>( const logs = await contractWrappers.etherToken.getLogsAsync<ApprovalContractEventArgs>(
etherTokenAddress, etherTokenAddress,
eventName, eventName,
blockRange, blockRange,
@ -332,13 +360,13 @@ describe('EtherTokenWrapper', () => {
expect(logs[0].event).to.be.equal(eventName); expect(logs[0].event).to.be.equal(eventName);
expect(args._owner).to.be.equal(addressWithETH); expect(args._owner).to.be.equal(addressWithETH);
expect(args._spender).to.be.equal(tokenTransferProxyAddress); expect(args._spender).to.be.equal(tokenTransferProxyAddress);
expect(args._value).to.be.bignumber.equal(zeroEx.token.UNLIMITED_ALLOWANCE_IN_BASE_UNITS); expect(args._value).to.be.bignumber.equal(contractWrappers.token.UNLIMITED_ALLOWANCE_IN_BASE_UNITS);
}); });
it('should get logs with decoded args emitted by Deposit', async () => { it('should get logs with decoded args emitted by Deposit', async () => {
await zeroEx.etherToken.depositAsync(etherTokenAddress, depositAmount, addressWithETH); await contractWrappers.etherToken.depositAsync(etherTokenAddress, depositAmount, addressWithETH);
const eventName = EtherTokenEvents.Deposit; const eventName = EtherTokenEvents.Deposit;
const indexFilterValues = {}; const indexFilterValues = {};
const logs = await zeroEx.etherToken.getLogsAsync<DepositContractEventArgs>( const logs = await contractWrappers.etherToken.getLogsAsync<DepositContractEventArgs>(
etherTokenAddress, etherTokenAddress,
eventName, eventName,
blockRange, blockRange,
@ -351,11 +379,11 @@ describe('EtherTokenWrapper', () => {
expect(args._value).to.be.bignumber.equal(depositAmount); expect(args._value).to.be.bignumber.equal(depositAmount);
}); });
it('should only get the logs with the correct event name', async () => { it('should only get the logs with the correct event name', async () => {
txHash = await zeroEx.token.setUnlimitedProxyAllowanceAsync(etherTokenAddress, addressWithETH); txHash = await contractWrappers.token.setUnlimitedProxyAllowanceAsync(etherTokenAddress, addressWithETH);
await zeroEx.awaitTransactionMinedAsync(txHash); await web3Wrapper.awaitTransactionMinedAsync(txHash);
const differentEventName = EtherTokenEvents.Transfer; const differentEventName = EtherTokenEvents.Transfer;
const indexFilterValues = {}; const indexFilterValues = {};
const logs = await zeroEx.etherToken.getLogsAsync( const logs = await contractWrappers.etherToken.getLogsAsync(
etherTokenAddress, etherTokenAddress,
differentEventName, differentEventName,
blockRange, blockRange,
@ -364,15 +392,18 @@ describe('EtherTokenWrapper', () => {
expect(logs).to.have.length(0); expect(logs).to.have.length(0);
}); });
it('should only get the logs with the correct indexed fields', async () => { it('should only get the logs with the correct indexed fields', async () => {
txHash = await zeroEx.token.setUnlimitedProxyAllowanceAsync(etherTokenAddress, addressWithETH); txHash = await contractWrappers.token.setUnlimitedProxyAllowanceAsync(etherTokenAddress, addressWithETH);
await zeroEx.awaitTransactionMinedAsync(txHash); await web3Wrapper.awaitTransactionMinedAsync(txHash);
txHash = await zeroEx.token.setUnlimitedProxyAllowanceAsync(etherTokenAddress, addressWithoutFunds); txHash = await contractWrappers.token.setUnlimitedProxyAllowanceAsync(
await zeroEx.awaitTransactionMinedAsync(txHash); etherTokenAddress,
addressWithoutFunds,
);
await web3Wrapper.awaitTransactionMinedAsync(txHash);
const eventName = EtherTokenEvents.Approval; const eventName = EtherTokenEvents.Approval;
const indexFilterValues = { const indexFilterValues = {
_owner: addressWithETH, _owner: addressWithETH,
}; };
const logs = await zeroEx.etherToken.getLogsAsync<ApprovalContractEventArgs>( const logs = await contractWrappers.etherToken.getLogsAsync<ApprovalContractEventArgs>(
etherTokenAddress, etherTokenAddress,
eventName, eventName,
blockRange, blockRange,

View File

@ -1,9 +1,9 @@
import { BlockchainLifecycle, devConstants } from '@0xproject/dev-utils'; import { BlockchainLifecycle, devConstants } from '@0xproject/dev-utils';
import { BlockParamLiteral } from '@0xproject/types'; import { BlockParamLiteral, Token } from '@0xproject/types';
import { BigNumber } from '@0xproject/utils'; import { BigNumber } from '@0xproject/utils';
import * as chai from 'chai'; import * as chai from 'chai';
import { ExchangeContractErrs, Token, ZeroEx } from '../src'; import { ContractWrappers, ExchangeContractErrs } from '../src';
import { TradeSide, TransferType } from '../src/types'; import { TradeSide, TransferType } from '../src/types';
import { ExchangeTransferSimulator } from '../src/utils/exchange_transfer_simulator'; import { ExchangeTransferSimulator } from '../src/utils/exchange_transfer_simulator';
@ -19,7 +19,7 @@ describe('ExchangeTransferSimulator', () => {
const config = { const config = {
networkId: constants.TESTRPC_NETWORK_ID, networkId: constants.TESTRPC_NETWORK_ID,
}; };
const zeroEx = new ZeroEx(provider, config); const contractWrappers = new ContractWrappers(provider, config);
const transferAmount = new BigNumber(5); const transferAmount = new BigNumber(5);
let userAddresses: string[]; let userAddresses: string[];
let tokens: Token[]; let tokens: Token[];
@ -30,9 +30,9 @@ describe('ExchangeTransferSimulator', () => {
let exchangeTransferSimulator: ExchangeTransferSimulator; let exchangeTransferSimulator: ExchangeTransferSimulator;
let txHash: string; let txHash: string;
before(async () => { before(async () => {
userAddresses = await zeroEx.getAvailableAddressesAsync(); userAddresses = await web3Wrapper.getAvailableAddressesAsync();
[coinbase, sender, recipient] = userAddresses; [coinbase, sender, recipient] = userAddresses;
tokens = await zeroEx.tokenRegistry.getTokensAsync(); tokens = await contractWrappers.tokenRegistry.getTokensAsync();
exampleTokenAddress = tokens[0].address; exampleTokenAddress = tokens[0].address;
}); });
beforeEach(async () => { beforeEach(async () => {
@ -43,7 +43,7 @@ describe('ExchangeTransferSimulator', () => {
}); });
describe('#transferFromAsync', () => { describe('#transferFromAsync', () => {
beforeEach(() => { beforeEach(() => {
exchangeTransferSimulator = new ExchangeTransferSimulator(zeroEx.token, BlockParamLiteral.Latest); exchangeTransferSimulator = new ExchangeTransferSimulator(contractWrappers.token, BlockParamLiteral.Latest);
}); });
it("throws if the user doesn't have enough allowance", async () => { it("throws if the user doesn't have enough allowance", async () => {
return expect( return expect(
@ -58,8 +58,8 @@ describe('ExchangeTransferSimulator', () => {
).to.be.rejectedWith(ExchangeContractErrs.InsufficientTakerAllowance); ).to.be.rejectedWith(ExchangeContractErrs.InsufficientTakerAllowance);
}); });
it("throws if the user doesn't have enough balance", async () => { it("throws if the user doesn't have enough balance", async () => {
txHash = await zeroEx.token.setProxyAllowanceAsync(exampleTokenAddress, sender, transferAmount); txHash = await contractWrappers.token.setProxyAllowanceAsync(exampleTokenAddress, sender, transferAmount);
await zeroEx.awaitTransactionMinedAsync(txHash); await web3Wrapper.awaitTransactionMinedAsync(txHash);
return expect( return expect(
exchangeTransferSimulator.transferFromAsync( exchangeTransferSimulator.transferFromAsync(
exampleTokenAddress, exampleTokenAddress,
@ -72,10 +72,10 @@ describe('ExchangeTransferSimulator', () => {
).to.be.rejectedWith(ExchangeContractErrs.InsufficientMakerBalance); ).to.be.rejectedWith(ExchangeContractErrs.InsufficientMakerBalance);
}); });
it('updates balances and proxyAllowance after transfer', async () => { it('updates balances and proxyAllowance after transfer', async () => {
txHash = await zeroEx.token.transferAsync(exampleTokenAddress, coinbase, sender, transferAmount); txHash = await contractWrappers.token.transferAsync(exampleTokenAddress, coinbase, sender, transferAmount);
await zeroEx.awaitTransactionMinedAsync(txHash); await web3Wrapper.awaitTransactionMinedAsync(txHash);
txHash = await zeroEx.token.setProxyAllowanceAsync(exampleTokenAddress, sender, transferAmount); txHash = await contractWrappers.token.setProxyAllowanceAsync(exampleTokenAddress, sender, transferAmount);
await zeroEx.awaitTransactionMinedAsync(txHash); await web3Wrapper.awaitTransactionMinedAsync(txHash);
await exchangeTransferSimulator.transferFromAsync( await exchangeTransferSimulator.transferFromAsync(
exampleTokenAddress, exampleTokenAddress,
sender, sender,
@ -93,10 +93,10 @@ describe('ExchangeTransferSimulator', () => {
expect(senderProxyAllowance).to.be.bignumber.equal(0); expect(senderProxyAllowance).to.be.bignumber.equal(0);
}); });
it("doesn't update proxyAllowance after transfer if unlimited", async () => { it("doesn't update proxyAllowance after transfer if unlimited", async () => {
txHash = await zeroEx.token.transferAsync(exampleTokenAddress, coinbase, sender, transferAmount); txHash = await contractWrappers.token.transferAsync(exampleTokenAddress, coinbase, sender, transferAmount);
await zeroEx.awaitTransactionMinedAsync(txHash); await web3Wrapper.awaitTransactionMinedAsync(txHash);
txHash = await zeroEx.token.setUnlimitedProxyAllowanceAsync(exampleTokenAddress, sender); txHash = await contractWrappers.token.setUnlimitedProxyAllowanceAsync(exampleTokenAddress, sender);
await zeroEx.awaitTransactionMinedAsync(txHash); await web3Wrapper.awaitTransactionMinedAsync(txHash);
await exchangeTransferSimulator.transferFromAsync( await exchangeTransferSimulator.transferFromAsync(
exampleTokenAddress, exampleTokenAddress,
sender, sender,
@ -111,7 +111,7 @@ describe('ExchangeTransferSimulator', () => {
const senderProxyAllowance = await store.getProxyAllowanceAsync(exampleTokenAddress, sender); const senderProxyAllowance = await store.getProxyAllowanceAsync(exampleTokenAddress, sender);
expect(senderBalance).to.be.bignumber.equal(0); expect(senderBalance).to.be.bignumber.equal(0);
expect(recipientBalance).to.be.bignumber.equal(transferAmount); expect(recipientBalance).to.be.bignumber.equal(transferAmount);
expect(senderProxyAllowance).to.be.bignumber.equal(zeroEx.token.UNLIMITED_ALLOWANCE_IN_BASE_UNITS); expect(senderProxyAllowance).to.be.bignumber.equal(contractWrappers.token.UNLIMITED_ALLOWANCE_IN_BASE_UNITS);
}); });
}); });
}); });

View File

@ -1,12 +1,16 @@
import { BlockchainLifecycle, devConstants, web3Factory } from '@0xproject/dev-utils'; import { BlockchainLifecycle, callbackErrorReporter, devConstants, web3Factory } from '@0xproject/dev-utils';
import { BlockParamLiteral } from '@0xproject/types'; import { FillScenarios } from '@0xproject/fill-scenarios';
import { getOrderHashHex } from '@0xproject/order-utils';
import { BlockParamLiteral, DoneCallback, OrderState } from '@0xproject/types';
import { BigNumber } from '@0xproject/utils'; import { BigNumber } from '@0xproject/utils';
import { Web3Wrapper } from '@0xproject/web3-wrapper';
import * as chai from 'chai'; import * as chai from 'chai';
import * as _ from 'lodash'; import * as _ from 'lodash';
import 'mocha'; import 'mocha';
import { import {
BlockRange, BlockRange,
ContractWrappers,
DecodedLogEvent, DecodedLogEvent,
ExchangeContractErrs, ExchangeContractErrs,
ExchangeEvents, ExchangeEvents,
@ -14,17 +18,12 @@ import {
LogFillContractEventArgs, LogFillContractEventArgs,
OrderCancellationRequest, OrderCancellationRequest,
OrderFillRequest, OrderFillRequest,
OrderState,
SignedOrder, SignedOrder,
Token, Token,
ZeroEx,
} from '../src'; } from '../src';
import { DoneCallback } from '../src/types';
import { chaiSetup } from './utils/chai_setup'; import { chaiSetup } from './utils/chai_setup';
import { constants } from './utils/constants'; import { constants } from './utils/constants';
import { FillScenarios } from './utils/fill_scenarios';
import { reportNodeCallbackErrors } from './utils/report_callback_errors';
import { TokenUtils } from './utils/token_utils'; import { TokenUtils } from './utils/token_utils';
import { provider, web3Wrapper } from './utils/web3_wrapper'; import { provider, web3Wrapper } from './utils/web3_wrapper';
@ -35,7 +34,7 @@ const blockchainLifecycle = new BlockchainLifecycle(web3Wrapper);
const NON_EXISTENT_ORDER_HASH = '0x79370342234e7acd6bbeac335bd3bb1d368383294b64b8160a00f4060e4d3777'; const NON_EXISTENT_ORDER_HASH = '0x79370342234e7acd6bbeac335bd3bb1d368383294b64b8160a00f4060e4d3777';
describe('ExchangeWrapper', () => { describe('ExchangeWrapper', () => {
let zeroEx: ZeroEx; let contractWrappers: ContractWrappers;
let tokenUtils: TokenUtils; let tokenUtils: TokenUtils;
let tokens: Token[]; let tokens: Token[];
let userAddresses: string[]; let userAddresses: string[];
@ -46,13 +45,13 @@ describe('ExchangeWrapper', () => {
networkId: constants.TESTRPC_NETWORK_ID, networkId: constants.TESTRPC_NETWORK_ID,
}; };
before(async () => { before(async () => {
zeroEx = new ZeroEx(provider, config); contractWrappers = new ContractWrappers(provider, config);
exchangeContractAddress = zeroEx.exchange.getContractAddress(); exchangeContractAddress = contractWrappers.exchange.getContractAddress();
userAddresses = await zeroEx.getAvailableAddressesAsync(); userAddresses = await web3Wrapper.getAvailableAddressesAsync();
tokens = await zeroEx.tokenRegistry.getTokensAsync(); tokens = await contractWrappers.tokenRegistry.getTokensAsync();
tokenUtils = new TokenUtils(tokens); tokenUtils = new TokenUtils(tokens);
zrxTokenAddress = tokenUtils.getProtocolTokenOrThrow().address; zrxTokenAddress = tokenUtils.getProtocolTokenOrThrow().address;
fillScenarios = new FillScenarios(zeroEx, userAddresses, tokens, zrxTokenAddress, exchangeContractAddress); fillScenarios = new FillScenarios(provider, userAddresses, tokens, zrxTokenAddress, exchangeContractAddress);
await fillScenarios.initTokenBalancesAsync(); await fillScenarios.initTokenBalancesAsync();
}); });
beforeEach(async () => { beforeEach(async () => {
@ -71,7 +70,7 @@ describe('ExchangeWrapper', () => {
const takerTokenFillAmount = new BigNumber(5); const takerTokenFillAmount = new BigNumber(5);
before(async () => { before(async () => {
[coinbase, makerAddress, takerAddress, feeRecipient] = userAddresses; [coinbase, makerAddress, takerAddress, feeRecipient] = userAddresses;
tokens = await zeroEx.tokenRegistry.getTokensAsync(); tokens = await contractWrappers.tokenRegistry.getTokensAsync();
const [makerToken, takerToken] = tokenUtils.getDummyTokens(); const [makerToken, takerToken] = tokenUtils.getDummyTokens();
makerTokenAddress = makerToken.address; makerTokenAddress = makerToken.address;
takerTokenAddress = takerToken.address; takerTokenAddress = takerToken.address;
@ -104,7 +103,7 @@ describe('ExchangeWrapper', () => {
takerTokenFillAmount: partialFillTakerAmount, takerTokenFillAmount: partialFillTakerAmount,
}, },
]; ];
await zeroEx.exchange.batchFillOrKillAsync(orderFillRequests, takerAddress); await contractWrappers.exchange.batchFillOrKillAsync(orderFillRequests, takerAddress);
}); });
describe('order transaction options', () => { describe('order transaction options', () => {
let signedOrder: SignedOrder; let signedOrder: SignedOrder;
@ -127,19 +126,19 @@ describe('ExchangeWrapper', () => {
}); });
it('should validate when orderTransactionOptions are not present', async () => { it('should validate when orderTransactionOptions are not present', async () => {
return expect( return expect(
zeroEx.exchange.batchFillOrKillAsync(orderFillRequests, takerAddress), contractWrappers.exchange.batchFillOrKillAsync(orderFillRequests, takerAddress),
).to.be.rejectedWith(ExchangeContractErrs.OrderFillAmountZero); ).to.be.rejectedWith(ExchangeContractErrs.OrderFillAmountZero);
}); });
it('should validate when orderTransactionOptions specify to validate', async () => { it('should validate when orderTransactionOptions specify to validate', async () => {
return expect( return expect(
zeroEx.exchange.batchFillOrKillAsync(orderFillRequests, takerAddress, { contractWrappers.exchange.batchFillOrKillAsync(orderFillRequests, takerAddress, {
shouldValidate: true, shouldValidate: true,
}), }),
).to.be.rejectedWith(ExchangeContractErrs.OrderFillAmountZero); ).to.be.rejectedWith(ExchangeContractErrs.OrderFillAmountZero);
}); });
it('should not validate when orderTransactionOptions specify not to validate', async () => { it('should not validate when orderTransactionOptions specify not to validate', async () => {
return expect( return expect(
zeroEx.exchange.batchFillOrKillAsync(orderFillRequests, takerAddress, { contractWrappers.exchange.batchFillOrKillAsync(orderFillRequests, takerAddress, {
shouldValidate: false, shouldValidate: false,
}), }),
).to.not.be.rejectedWith(ExchangeContractErrs.OrderFillAmountZero); ).to.not.be.rejectedWith(ExchangeContractErrs.OrderFillAmountZero);
@ -160,66 +159,70 @@ describe('ExchangeWrapper', () => {
}); });
describe('successful fills', () => { describe('successful fills', () => {
it('should fill a valid order', async () => { it('should fill a valid order', async () => {
expect(await zeroEx.token.getBalanceAsync(makerTokenAddress, makerAddress)).to.be.bignumber.equal( expect(
fillableAmount, await contractWrappers.token.getBalanceAsync(makerTokenAddress, makerAddress),
); ).to.be.bignumber.equal(fillableAmount);
expect(await zeroEx.token.getBalanceAsync(takerTokenAddress, makerAddress)).to.be.bignumber.equal( expect(
0, await contractWrappers.token.getBalanceAsync(takerTokenAddress, makerAddress),
); ).to.be.bignumber.equal(0);
expect(await zeroEx.token.getBalanceAsync(makerTokenAddress, takerAddress)).to.be.bignumber.equal( expect(
0, await contractWrappers.token.getBalanceAsync(makerTokenAddress, takerAddress),
); ).to.be.bignumber.equal(0);
expect(await zeroEx.token.getBalanceAsync(takerTokenAddress, takerAddress)).to.be.bignumber.equal( expect(
fillableAmount, await contractWrappers.token.getBalanceAsync(takerTokenAddress, takerAddress),
); ).to.be.bignumber.equal(fillableAmount);
await zeroEx.exchange.fillOrKillOrderAsync(signedOrder, takerTokenFillAmount, takerAddress); await contractWrappers.exchange.fillOrKillOrderAsync(
expect(await zeroEx.token.getBalanceAsync(makerTokenAddress, makerAddress)).to.be.bignumber.equal( signedOrder,
fillableAmount.minus(takerTokenFillAmount),
);
expect(await zeroEx.token.getBalanceAsync(takerTokenAddress, makerAddress)).to.be.bignumber.equal(
takerTokenFillAmount, takerTokenFillAmount,
takerAddress,
); );
expect(await zeroEx.token.getBalanceAsync(makerTokenAddress, takerAddress)).to.be.bignumber.equal( expect(
takerTokenFillAmount, await contractWrappers.token.getBalanceAsync(makerTokenAddress, makerAddress),
); ).to.be.bignumber.equal(fillableAmount.minus(takerTokenFillAmount));
expect(await zeroEx.token.getBalanceAsync(takerTokenAddress, takerAddress)).to.be.bignumber.equal( expect(
fillableAmount.minus(takerTokenFillAmount), await contractWrappers.token.getBalanceAsync(takerTokenAddress, makerAddress),
); ).to.be.bignumber.equal(takerTokenFillAmount);
expect(
await contractWrappers.token.getBalanceAsync(makerTokenAddress, takerAddress),
).to.be.bignumber.equal(takerTokenFillAmount);
expect(
await contractWrappers.token.getBalanceAsync(takerTokenAddress, takerAddress),
).to.be.bignumber.equal(fillableAmount.minus(takerTokenFillAmount));
}); });
it('should partially fill a valid order', async () => { it('should partially fill a valid order', async () => {
const partialFillAmount = new BigNumber(3); const partialFillAmount = new BigNumber(3);
await zeroEx.exchange.fillOrKillOrderAsync(signedOrder, partialFillAmount, takerAddress); await contractWrappers.exchange.fillOrKillOrderAsync(signedOrder, partialFillAmount, takerAddress);
expect(await zeroEx.token.getBalanceAsync(makerTokenAddress, makerAddress)).to.be.bignumber.equal( expect(
fillableAmount.minus(partialFillAmount), await contractWrappers.token.getBalanceAsync(makerTokenAddress, makerAddress),
); ).to.be.bignumber.equal(fillableAmount.minus(partialFillAmount));
expect(await zeroEx.token.getBalanceAsync(takerTokenAddress, makerAddress)).to.be.bignumber.equal( expect(
partialFillAmount, await contractWrappers.token.getBalanceAsync(takerTokenAddress, makerAddress),
); ).to.be.bignumber.equal(partialFillAmount);
expect(await zeroEx.token.getBalanceAsync(makerTokenAddress, takerAddress)).to.be.bignumber.equal( expect(
partialFillAmount, await contractWrappers.token.getBalanceAsync(makerTokenAddress, takerAddress),
); ).to.be.bignumber.equal(partialFillAmount);
expect(await zeroEx.token.getBalanceAsync(takerTokenAddress, takerAddress)).to.be.bignumber.equal( expect(
fillableAmount.minus(partialFillAmount), await contractWrappers.token.getBalanceAsync(takerTokenAddress, takerAddress),
); ).to.be.bignumber.equal(fillableAmount.minus(partialFillAmount));
}); });
}); });
describe('order transaction options', () => { describe('order transaction options', () => {
const emptyFillableAmount = new BigNumber(0); const emptyFillableAmount = new BigNumber(0);
it('should validate when orderTransactionOptions are not present', async () => { it('should validate when orderTransactionOptions are not present', async () => {
return expect( return expect(
zeroEx.exchange.fillOrKillOrderAsync(signedOrder, emptyFillableAmount, takerAddress), contractWrappers.exchange.fillOrKillOrderAsync(signedOrder, emptyFillableAmount, takerAddress),
).to.be.rejectedWith(ExchangeContractErrs.OrderFillAmountZero); ).to.be.rejectedWith(ExchangeContractErrs.OrderFillAmountZero);
}); });
it('should validate when orderTransactionOptions specify to validate', async () => { it('should validate when orderTransactionOptions specify to validate', async () => {
return expect( return expect(
zeroEx.exchange.fillOrKillOrderAsync(signedOrder, emptyFillableAmount, takerAddress, { contractWrappers.exchange.fillOrKillOrderAsync(signedOrder, emptyFillableAmount, takerAddress, {
shouldValidate: true, shouldValidate: true,
}), }),
).to.be.rejectedWith(ExchangeContractErrs.OrderFillAmountZero); ).to.be.rejectedWith(ExchangeContractErrs.OrderFillAmountZero);
}); });
it('should not validate when orderTransactionOptions specify not to validate', async () => { it('should not validate when orderTransactionOptions specify not to validate', async () => {
return expect( return expect(
zeroEx.exchange.fillOrKillOrderAsync(signedOrder, emptyFillableAmount, takerAddress, { contractWrappers.exchange.fillOrKillOrderAsync(signedOrder, emptyFillableAmount, takerAddress, {
shouldValidate: false, shouldValidate: false,
}), }),
).to.not.be.rejectedWith(ExchangeContractErrs.OrderFillAmountZero); ).to.not.be.rejectedWith(ExchangeContractErrs.OrderFillAmountZero);
@ -239,7 +242,7 @@ describe('ExchangeWrapper', () => {
const shouldThrowOnInsufficientBalanceOrAllowance = true; const shouldThrowOnInsufficientBalanceOrAllowance = true;
before(async () => { before(async () => {
[coinbase, makerAddress, takerAddress, feeRecipient] = userAddresses; [coinbase, makerAddress, takerAddress, feeRecipient] = userAddresses;
tokens = await zeroEx.tokenRegistry.getTokensAsync(); tokens = await contractWrappers.tokenRegistry.getTokensAsync();
const [makerToken, takerToken] = tokenUtils.getDummyTokens(); const [makerToken, takerToken] = tokenUtils.getDummyTokens();
makerTokenAddress = makerToken.address; makerTokenAddress = makerToken.address;
takerTokenAddress = takerToken.address; takerTokenAddress = takerToken.address;
@ -254,37 +257,37 @@ describe('ExchangeWrapper', () => {
takerAddress, takerAddress,
fillableAmount, fillableAmount,
); );
expect(await zeroEx.token.getBalanceAsync(makerTokenAddress, makerAddress)).to.be.bignumber.equal( expect(
fillableAmount, await contractWrappers.token.getBalanceAsync(makerTokenAddress, makerAddress),
); ).to.be.bignumber.equal(fillableAmount);
expect(await zeroEx.token.getBalanceAsync(takerTokenAddress, makerAddress)).to.be.bignumber.equal( expect(
0, await contractWrappers.token.getBalanceAsync(takerTokenAddress, makerAddress),
); ).to.be.bignumber.equal(0);
expect(await zeroEx.token.getBalanceAsync(makerTokenAddress, takerAddress)).to.be.bignumber.equal( expect(
0, await contractWrappers.token.getBalanceAsync(makerTokenAddress, takerAddress),
); ).to.be.bignumber.equal(0);
expect(await zeroEx.token.getBalanceAsync(takerTokenAddress, takerAddress)).to.be.bignumber.equal( expect(
fillableAmount, await contractWrappers.token.getBalanceAsync(takerTokenAddress, takerAddress),
); ).to.be.bignumber.equal(fillableAmount);
const txHash = await zeroEx.exchange.fillOrderAsync( const txHash = await contractWrappers.exchange.fillOrderAsync(
signedOrder, signedOrder,
takerTokenFillAmount, takerTokenFillAmount,
shouldThrowOnInsufficientBalanceOrAllowance, shouldThrowOnInsufficientBalanceOrAllowance,
takerAddress, takerAddress,
); );
await zeroEx.awaitTransactionMinedAsync(txHash); await web3Wrapper.awaitTransactionMinedAsync(txHash);
expect(await zeroEx.token.getBalanceAsync(makerTokenAddress, makerAddress)).to.be.bignumber.equal( expect(
fillableAmount.minus(takerTokenFillAmount), await contractWrappers.token.getBalanceAsync(makerTokenAddress, makerAddress),
); ).to.be.bignumber.equal(fillableAmount.minus(takerTokenFillAmount));
expect(await zeroEx.token.getBalanceAsync(takerTokenAddress, makerAddress)).to.be.bignumber.equal( expect(
takerTokenFillAmount, await contractWrappers.token.getBalanceAsync(takerTokenAddress, makerAddress),
); ).to.be.bignumber.equal(takerTokenFillAmount);
expect(await zeroEx.token.getBalanceAsync(makerTokenAddress, takerAddress)).to.be.bignumber.equal( expect(
takerTokenFillAmount, await contractWrappers.token.getBalanceAsync(makerTokenAddress, takerAddress),
); ).to.be.bignumber.equal(takerTokenFillAmount);
expect(await zeroEx.token.getBalanceAsync(takerTokenAddress, takerAddress)).to.be.bignumber.equal( expect(
fillableAmount.minus(takerTokenFillAmount), await contractWrappers.token.getBalanceAsync(takerTokenAddress, takerAddress),
); ).to.be.bignumber.equal(fillableAmount.minus(takerTokenFillAmount));
}); });
it('should partially fill the valid order', async () => { it('should partially fill the valid order', async () => {
const signedOrder = await fillScenarios.createFillableSignedOrderAsync( const signedOrder = await fillScenarios.createFillableSignedOrderAsync(
@ -295,25 +298,25 @@ describe('ExchangeWrapper', () => {
fillableAmount, fillableAmount,
); );
const partialFillAmount = new BigNumber(3); const partialFillAmount = new BigNumber(3);
const txHash = await zeroEx.exchange.fillOrderAsync( const txHash = await contractWrappers.exchange.fillOrderAsync(
signedOrder, signedOrder,
partialFillAmount, partialFillAmount,
shouldThrowOnInsufficientBalanceOrAllowance, shouldThrowOnInsufficientBalanceOrAllowance,
takerAddress, takerAddress,
); );
await zeroEx.awaitTransactionMinedAsync(txHash); await web3Wrapper.awaitTransactionMinedAsync(txHash);
expect(await zeroEx.token.getBalanceAsync(makerTokenAddress, makerAddress)).to.be.bignumber.equal( expect(
fillableAmount.minus(partialFillAmount), await contractWrappers.token.getBalanceAsync(makerTokenAddress, makerAddress),
); ).to.be.bignumber.equal(fillableAmount.minus(partialFillAmount));
expect(await zeroEx.token.getBalanceAsync(takerTokenAddress, makerAddress)).to.be.bignumber.equal( expect(
partialFillAmount, await contractWrappers.token.getBalanceAsync(takerTokenAddress, makerAddress),
); ).to.be.bignumber.equal(partialFillAmount);
expect(await zeroEx.token.getBalanceAsync(makerTokenAddress, takerAddress)).to.be.bignumber.equal( expect(
partialFillAmount, await contractWrappers.token.getBalanceAsync(makerTokenAddress, takerAddress),
); ).to.be.bignumber.equal(partialFillAmount);
expect(await zeroEx.token.getBalanceAsync(takerTokenAddress, takerAddress)).to.be.bignumber.equal( expect(
fillableAmount.minus(partialFillAmount), await contractWrappers.token.getBalanceAsync(takerTokenAddress, takerAddress),
); ).to.be.bignumber.equal(fillableAmount.minus(partialFillAmount));
}); });
it('should fill the valid orders with fees', async () => { it('should fill the valid orders with fees', async () => {
const makerFee = new BigNumber(1); const makerFee = new BigNumber(1);
@ -328,16 +331,16 @@ describe('ExchangeWrapper', () => {
fillableAmount, fillableAmount,
feeRecipient, feeRecipient,
); );
const txHash = await zeroEx.exchange.fillOrderAsync( const txHash = await contractWrappers.exchange.fillOrderAsync(
signedOrder, signedOrder,
takerTokenFillAmount, takerTokenFillAmount,
shouldThrowOnInsufficientBalanceOrAllowance, shouldThrowOnInsufficientBalanceOrAllowance,
takerAddress, takerAddress,
); );
await zeroEx.awaitTransactionMinedAsync(txHash); await web3Wrapper.awaitTransactionMinedAsync(txHash);
expect(await zeroEx.token.getBalanceAsync(zrxTokenAddress, feeRecipient)).to.be.bignumber.equal( expect(
makerFee.plus(takerFee), await contractWrappers.token.getBalanceAsync(zrxTokenAddress, feeRecipient),
); ).to.be.bignumber.equal(makerFee.plus(takerFee));
}); });
}); });
describe('order transaction options', () => { describe('order transaction options', () => {
@ -354,7 +357,7 @@ describe('ExchangeWrapper', () => {
}); });
it('should validate when orderTransactionOptions are not present', async () => { it('should validate when orderTransactionOptions are not present', async () => {
return expect( return expect(
zeroEx.exchange.fillOrderAsync( contractWrappers.exchange.fillOrderAsync(
signedOrder, signedOrder,
emptyFillTakerAmount, emptyFillTakerAmount,
shouldThrowOnInsufficientBalanceOrAllowance, shouldThrowOnInsufficientBalanceOrAllowance,
@ -364,7 +367,7 @@ describe('ExchangeWrapper', () => {
}); });
it('should validate when orderTransactionOptions specify to validate', async () => { it('should validate when orderTransactionOptions specify to validate', async () => {
return expect( return expect(
zeroEx.exchange.fillOrderAsync( contractWrappers.exchange.fillOrderAsync(
signedOrder, signedOrder,
emptyFillTakerAmount, emptyFillTakerAmount,
shouldThrowOnInsufficientBalanceOrAllowance, shouldThrowOnInsufficientBalanceOrAllowance,
@ -377,7 +380,7 @@ describe('ExchangeWrapper', () => {
}); });
it('should not validate when orderTransactionOptions specify not to validate', async () => { it('should not validate when orderTransactionOptions specify not to validate', async () => {
return expect( return expect(
zeroEx.exchange.fillOrderAsync( contractWrappers.exchange.fillOrderAsync(
signedOrder, signedOrder,
emptyFillTakerAmount, emptyFillTakerAmount,
shouldThrowOnInsufficientBalanceOrAllowance, shouldThrowOnInsufficientBalanceOrAllowance,
@ -403,7 +406,7 @@ describe('ExchangeWrapper', () => {
}); });
it('should not allow the exchange wrapper to fill if amount is negative', async () => { it('should not allow the exchange wrapper to fill if amount is negative', async () => {
return expect( return expect(
zeroEx.exchange.fillOrderAsync( contractWrappers.exchange.fillOrderAsync(
signedOrder, signedOrder,
negativeFillTakerAmount, negativeFillTakerAmount,
shouldThrowOnInsufficientBalanceOrAllowance, shouldThrowOnInsufficientBalanceOrAllowance,
@ -427,7 +430,7 @@ describe('ExchangeWrapper', () => {
takerAddress, takerAddress,
fillableAmount, fillableAmount,
); );
signedOrderHashHex = ZeroEx.getOrderHashHex(signedOrder); signedOrderHashHex = getOrderHashHex(signedOrder);
anotherSignedOrder = await fillScenarios.createFillableSignedOrderAsync( anotherSignedOrder = await fillScenarios.createFillableSignedOrderAsync(
makerTokenAddress, makerTokenAddress,
takerTokenAddress, takerTokenAddress,
@ -435,7 +438,7 @@ describe('ExchangeWrapper', () => {
takerAddress, takerAddress,
fillableAmount, fillableAmount,
); );
anotherOrderHashHex = ZeroEx.getOrderHashHex(anotherSignedOrder); anotherOrderHashHex = getOrderHashHex(anotherSignedOrder);
}); });
describe('successful batch fills', () => { describe('successful batch fills', () => {
beforeEach(() => { beforeEach(() => {
@ -452,7 +455,7 @@ describe('ExchangeWrapper', () => {
}); });
it('should throw if a batch is empty', async () => { it('should throw if a batch is empty', async () => {
return expect( return expect(
zeroEx.exchange.batchFillOrdersAsync( contractWrappers.exchange.batchFillOrdersAsync(
[], [],
shouldThrowOnInsufficientBalanceOrAllowance, shouldThrowOnInsufficientBalanceOrAllowance,
takerAddress, takerAddress,
@ -460,14 +463,16 @@ describe('ExchangeWrapper', () => {
).to.be.rejectedWith(ExchangeContractErrs.BatchOrdersMustHaveAtLeastOneItem); ).to.be.rejectedWith(ExchangeContractErrs.BatchOrdersMustHaveAtLeastOneItem);
}); });
it('should successfully fill multiple orders', async () => { it('should successfully fill multiple orders', async () => {
const txHash = await zeroEx.exchange.batchFillOrdersAsync( const txHash = await contractWrappers.exchange.batchFillOrdersAsync(
orderFillBatch, orderFillBatch,
shouldThrowOnInsufficientBalanceOrAllowance, shouldThrowOnInsufficientBalanceOrAllowance,
takerAddress, takerAddress,
); );
await zeroEx.awaitTransactionMinedAsync(txHash); await web3Wrapper.awaitTransactionMinedAsync(txHash);
const filledAmount = await zeroEx.exchange.getFilledTakerAmountAsync(signedOrderHashHex); const filledAmount = await contractWrappers.exchange.getFilledTakerAmountAsync(signedOrderHashHex);
const anotherFilledAmount = await zeroEx.exchange.getFilledTakerAmountAsync(anotherOrderHashHex); const anotherFilledAmount = await contractWrappers.exchange.getFilledTakerAmountAsync(
anotherOrderHashHex,
);
expect(filledAmount).to.be.bignumber.equal(takerTokenFillAmount); expect(filledAmount).to.be.bignumber.equal(takerTokenFillAmount);
expect(anotherFilledAmount).to.be.bignumber.equal(takerTokenFillAmount); expect(anotherFilledAmount).to.be.bignumber.equal(takerTokenFillAmount);
}); });
@ -488,7 +493,7 @@ describe('ExchangeWrapper', () => {
}); });
it('should validate when orderTransactionOptions are not present', async () => { it('should validate when orderTransactionOptions are not present', async () => {
return expect( return expect(
zeroEx.exchange.batchFillOrdersAsync( contractWrappers.exchange.batchFillOrdersAsync(
orderFillBatch, orderFillBatch,
shouldThrowOnInsufficientBalanceOrAllowance, shouldThrowOnInsufficientBalanceOrAllowance,
takerAddress, takerAddress,
@ -497,7 +502,7 @@ describe('ExchangeWrapper', () => {
}); });
it('should validate when orderTransactionOptions specify to validate', async () => { it('should validate when orderTransactionOptions specify to validate', async () => {
return expect( return expect(
zeroEx.exchange.batchFillOrdersAsync( contractWrappers.exchange.batchFillOrdersAsync(
orderFillBatch, orderFillBatch,
shouldThrowOnInsufficientBalanceOrAllowance, shouldThrowOnInsufficientBalanceOrAllowance,
takerAddress, takerAddress,
@ -509,7 +514,7 @@ describe('ExchangeWrapper', () => {
}); });
it('should not validate when orderTransactionOptions specify not to validate', async () => { it('should not validate when orderTransactionOptions specify not to validate', async () => {
return expect( return expect(
zeroEx.exchange.batchFillOrdersAsync( contractWrappers.exchange.batchFillOrdersAsync(
orderFillBatch, orderFillBatch,
shouldThrowOnInsufficientBalanceOrAllowance, shouldThrowOnInsufficientBalanceOrAllowance,
takerAddress, takerAddress,
@ -536,7 +541,7 @@ describe('ExchangeWrapper', () => {
}); });
it('should not allow the exchange wrapper to batch fill if any amount is negative', async () => { it('should not allow the exchange wrapper to batch fill if any amount is negative', async () => {
return expect( return expect(
zeroEx.exchange.batchFillOrdersAsync( contractWrappers.exchange.batchFillOrdersAsync(
orderFillBatch, orderFillBatch,
shouldThrowOnInsufficientBalanceOrAllowance, shouldThrowOnInsufficientBalanceOrAllowance,
takerAddress, takerAddress,
@ -560,7 +565,7 @@ describe('ExchangeWrapper', () => {
takerAddress, takerAddress,
fillableAmount, fillableAmount,
); );
signedOrderHashHex = ZeroEx.getOrderHashHex(signedOrder); signedOrderHashHex = getOrderHashHex(signedOrder);
anotherSignedOrder = await fillScenarios.createFillableSignedOrderAsync( anotherSignedOrder = await fillScenarios.createFillableSignedOrderAsync(
makerTokenAddress, makerTokenAddress,
takerTokenAddress, takerTokenAddress,
@ -568,13 +573,13 @@ describe('ExchangeWrapper', () => {
takerAddress, takerAddress,
fillableAmount, fillableAmount,
); );
anotherOrderHashHex = ZeroEx.getOrderHashHex(anotherSignedOrder); anotherOrderHashHex = getOrderHashHex(anotherSignedOrder);
signedOrders = [signedOrder, anotherSignedOrder]; signedOrders = [signedOrder, anotherSignedOrder];
}); });
describe('successful batch fills', () => { describe('successful batch fills', () => {
it('should throw if a batch is empty', async () => { it('should throw if a batch is empty', async () => {
return expect( return expect(
zeroEx.exchange.fillOrdersUpToAsync( contractWrappers.exchange.fillOrdersUpToAsync(
[], [],
fillUpToAmount, fillUpToAmount,
shouldThrowOnInsufficientBalanceOrAllowance, shouldThrowOnInsufficientBalanceOrAllowance,
@ -583,45 +588,54 @@ describe('ExchangeWrapper', () => {
).to.be.rejectedWith(ExchangeContractErrs.BatchOrdersMustHaveAtLeastOneItem); ).to.be.rejectedWith(ExchangeContractErrs.BatchOrdersMustHaveAtLeastOneItem);
}); });
it('should successfully fill up to specified amount when all orders are fully funded', async () => { it('should successfully fill up to specified amount when all orders are fully funded', async () => {
const txHash = await zeroEx.exchange.fillOrdersUpToAsync( const txHash = await contractWrappers.exchange.fillOrdersUpToAsync(
signedOrders, signedOrders,
fillUpToAmount, fillUpToAmount,
shouldThrowOnInsufficientBalanceOrAllowance, shouldThrowOnInsufficientBalanceOrAllowance,
takerAddress, takerAddress,
); );
await zeroEx.awaitTransactionMinedAsync(txHash); await web3Wrapper.awaitTransactionMinedAsync(txHash);
const filledAmount = await zeroEx.exchange.getFilledTakerAmountAsync(signedOrderHashHex); const filledAmount = await contractWrappers.exchange.getFilledTakerAmountAsync(signedOrderHashHex);
const anotherFilledAmount = await zeroEx.exchange.getFilledTakerAmountAsync(anotherOrderHashHex); const anotherFilledAmount = await contractWrappers.exchange.getFilledTakerAmountAsync(
anotherOrderHashHex,
);
expect(filledAmount).to.be.bignumber.equal(fillableAmount); expect(filledAmount).to.be.bignumber.equal(fillableAmount);
const remainingFillAmount = fillableAmount.minus(1); const remainingFillAmount = fillableAmount.minus(1);
expect(anotherFilledAmount).to.be.bignumber.equal(remainingFillAmount); expect(anotherFilledAmount).to.be.bignumber.equal(remainingFillAmount);
}); });
it('should successfully fill up to specified amount and leave the rest of the orders untouched', async () => { it('should successfully fill up to specified amount and leave the rest of the orders untouched', async () => {
const txHash = await zeroEx.exchange.fillOrdersUpToAsync( const txHash = await contractWrappers.exchange.fillOrdersUpToAsync(
signedOrders, signedOrders,
fillableAmount, fillableAmount,
shouldThrowOnInsufficientBalanceOrAllowance, shouldThrowOnInsufficientBalanceOrAllowance,
takerAddress, takerAddress,
); );
await zeroEx.awaitTransactionMinedAsync(txHash); await web3Wrapper.awaitTransactionMinedAsync(txHash);
const filledAmount = await zeroEx.exchange.getFilledTakerAmountAsync(signedOrderHashHex); const filledAmount = await contractWrappers.exchange.getFilledTakerAmountAsync(signedOrderHashHex);
const zeroAmount = await zeroEx.exchange.getFilledTakerAmountAsync(anotherOrderHashHex); const zeroAmount = await contractWrappers.exchange.getFilledTakerAmountAsync(anotherOrderHashHex);
expect(filledAmount).to.be.bignumber.equal(fillableAmount); expect(filledAmount).to.be.bignumber.equal(fillableAmount);
expect(zeroAmount).to.be.bignumber.equal(0); expect(zeroAmount).to.be.bignumber.equal(0);
}); });
it('should successfully fill up to specified amount even if filling all orders would fail', async () => { it('should successfully fill up to specified amount even if filling all orders would fail', async () => {
const missingBalance = new BigNumber(1); // User will still have enough balance to fill up to 9, const missingBalance = new BigNumber(1); // User will still have enough balance to fill up to 9,
// but won't have 10 to fully fill all orders in a batch. // but won't have 10 to fully fill all orders in a batch.
await zeroEx.token.transferAsync(makerTokenAddress, makerAddress, coinbase, missingBalance); await contractWrappers.token.transferAsync(
const txHash = await zeroEx.exchange.fillOrdersUpToAsync( makerTokenAddress,
makerAddress,
coinbase,
missingBalance,
);
const txHash = await contractWrappers.exchange.fillOrdersUpToAsync(
signedOrders, signedOrders,
fillUpToAmount, fillUpToAmount,
shouldThrowOnInsufficientBalanceOrAllowance, shouldThrowOnInsufficientBalanceOrAllowance,
takerAddress, takerAddress,
); );
await zeroEx.awaitTransactionMinedAsync(txHash); await web3Wrapper.awaitTransactionMinedAsync(txHash);
const filledAmount = await zeroEx.exchange.getFilledTakerAmountAsync(signedOrderHashHex); const filledAmount = await contractWrappers.exchange.getFilledTakerAmountAsync(signedOrderHashHex);
const anotherFilledAmount = await zeroEx.exchange.getFilledTakerAmountAsync(anotherOrderHashHex); const anotherFilledAmount = await contractWrappers.exchange.getFilledTakerAmountAsync(
anotherOrderHashHex,
);
expect(filledAmount).to.be.bignumber.equal(fillableAmount); expect(filledAmount).to.be.bignumber.equal(fillableAmount);
const remainingFillAmount = fillableAmount.minus(1); const remainingFillAmount = fillableAmount.minus(1);
expect(anotherFilledAmount).to.be.bignumber.equal(remainingFillAmount); expect(anotherFilledAmount).to.be.bignumber.equal(remainingFillAmount);
@ -630,9 +644,14 @@ describe('ExchangeWrapper', () => {
describe('failed batch fills', () => { describe('failed batch fills', () => {
it("should fail validation if user doesn't have enough balance without fill up to", async () => { it("should fail validation if user doesn't have enough balance without fill up to", async () => {
const missingBalance = new BigNumber(2); // User will only have enough balance to fill up to 8 const missingBalance = new BigNumber(2); // User will only have enough balance to fill up to 8
await zeroEx.token.transferAsync(makerTokenAddress, makerAddress, coinbase, missingBalance); await contractWrappers.token.transferAsync(
makerTokenAddress,
makerAddress,
coinbase,
missingBalance,
);
return expect( return expect(
zeroEx.exchange.fillOrdersUpToAsync( contractWrappers.exchange.fillOrdersUpToAsync(
signedOrders, signedOrders,
fillUpToAmount, fillUpToAmount,
shouldThrowOnInsufficientBalanceOrAllowance, shouldThrowOnInsufficientBalanceOrAllowance,
@ -645,7 +664,7 @@ describe('ExchangeWrapper', () => {
const emptyFillUpToAmount = new BigNumber(0); const emptyFillUpToAmount = new BigNumber(0);
it('should validate when orderTransactionOptions are not present', async () => { it('should validate when orderTransactionOptions are not present', async () => {
return expect( return expect(
zeroEx.exchange.fillOrdersUpToAsync( contractWrappers.exchange.fillOrdersUpToAsync(
signedOrders, signedOrders,
emptyFillUpToAmount, emptyFillUpToAmount,
shouldThrowOnInsufficientBalanceOrAllowance, shouldThrowOnInsufficientBalanceOrAllowance,
@ -655,7 +674,7 @@ describe('ExchangeWrapper', () => {
}); });
it('should validate when orderTransactionOptions specify to validate', async () => { it('should validate when orderTransactionOptions specify to validate', async () => {
return expect( return expect(
zeroEx.exchange.fillOrdersUpToAsync( contractWrappers.exchange.fillOrdersUpToAsync(
signedOrders, signedOrders,
emptyFillUpToAmount, emptyFillUpToAmount,
shouldThrowOnInsufficientBalanceOrAllowance, shouldThrowOnInsufficientBalanceOrAllowance,
@ -668,7 +687,7 @@ describe('ExchangeWrapper', () => {
}); });
it('should not validate when orderTransactionOptions specify not to validate', async () => { it('should not validate when orderTransactionOptions specify not to validate', async () => {
return expect( return expect(
zeroEx.exchange.fillOrdersUpToAsync( contractWrappers.exchange.fillOrdersUpToAsync(
signedOrders, signedOrders,
emptyFillUpToAmount, emptyFillUpToAmount,
shouldThrowOnInsufficientBalanceOrAllowance, shouldThrowOnInsufficientBalanceOrAllowance,
@ -704,14 +723,14 @@ describe('ExchangeWrapper', () => {
takerAddress, takerAddress,
fillableAmount, fillableAmount,
); );
orderHashHex = ZeroEx.getOrderHashHex(signedOrder); orderHashHex = getOrderHashHex(signedOrder);
}); });
describe('#cancelOrderAsync', () => { describe('#cancelOrderAsync', () => {
describe('successful cancels', () => { describe('successful cancels', () => {
it('should cancel an order', async () => { it('should cancel an order', async () => {
const txHash = await zeroEx.exchange.cancelOrderAsync(signedOrder, cancelAmount); const txHash = await contractWrappers.exchange.cancelOrderAsync(signedOrder, cancelAmount);
await zeroEx.awaitTransactionMinedAsync(txHash); await web3Wrapper.awaitTransactionMinedAsync(txHash);
const cancelledAmount = await zeroEx.exchange.getCancelledTakerAmountAsync(orderHashHex); const cancelledAmount = await contractWrappers.exchange.getCancelledTakerAmountAsync(orderHashHex);
expect(cancelledAmount).to.be.bignumber.equal(cancelAmount); expect(cancelledAmount).to.be.bignumber.equal(cancelAmount);
}); });
}); });
@ -719,19 +738,19 @@ describe('ExchangeWrapper', () => {
const emptyCancelTakerTokenAmount = new BigNumber(0); const emptyCancelTakerTokenAmount = new BigNumber(0);
it('should validate when orderTransactionOptions are not present', async () => { it('should validate when orderTransactionOptions are not present', async () => {
return expect( return expect(
zeroEx.exchange.cancelOrderAsync(signedOrder, emptyCancelTakerTokenAmount), contractWrappers.exchange.cancelOrderAsync(signedOrder, emptyCancelTakerTokenAmount),
).to.be.rejectedWith(ExchangeContractErrs.OrderCancelAmountZero); ).to.be.rejectedWith(ExchangeContractErrs.OrderCancelAmountZero);
}); });
it('should validate when orderTransactionOptions specify to validate', async () => { it('should validate when orderTransactionOptions specify to validate', async () => {
return expect( return expect(
zeroEx.exchange.cancelOrderAsync(signedOrder, emptyCancelTakerTokenAmount, { contractWrappers.exchange.cancelOrderAsync(signedOrder, emptyCancelTakerTokenAmount, {
shouldValidate: true, shouldValidate: true,
}), }),
).to.be.rejectedWith(ExchangeContractErrs.OrderCancelAmountZero); ).to.be.rejectedWith(ExchangeContractErrs.OrderCancelAmountZero);
}); });
it('should not validate when orderTransactionOptions specify not to validate', async () => { it('should not validate when orderTransactionOptions specify not to validate', async () => {
return expect( return expect(
zeroEx.exchange.cancelOrderAsync(signedOrder, emptyCancelTakerTokenAmount, { contractWrappers.exchange.cancelOrderAsync(signedOrder, emptyCancelTakerTokenAmount, {
shouldValidate: false, shouldValidate: false,
}), }),
).to.not.be.rejectedWith(ExchangeContractErrs.OrderCancelAmountZero); ).to.not.be.rejectedWith(ExchangeContractErrs.OrderCancelAmountZero);
@ -750,7 +769,7 @@ describe('ExchangeWrapper', () => {
takerAddress, takerAddress,
fillableAmount, fillableAmount,
); );
anotherOrderHashHex = ZeroEx.getOrderHashHex(anotherSignedOrder); anotherOrderHashHex = getOrderHashHex(anotherSignedOrder);
cancelBatch = [ cancelBatch = [
{ {
order: signedOrder, order: signedOrder,
@ -772,7 +791,7 @@ describe('ExchangeWrapper', () => {
fillableAmount, fillableAmount,
); );
return expect( return expect(
zeroEx.exchange.batchCancelOrdersAsync([ contractWrappers.exchange.batchCancelOrdersAsync([
cancelBatch[0], cancelBatch[0],
{ {
order: signedOrderWithDifferentMaker, order: signedOrderWithDifferentMaker,
@ -784,9 +803,9 @@ describe('ExchangeWrapper', () => {
}); });
describe('successful batch cancels', () => { describe('successful batch cancels', () => {
it('should cancel a batch of orders', async () => { it('should cancel a batch of orders', async () => {
await zeroEx.exchange.batchCancelOrdersAsync(cancelBatch); await contractWrappers.exchange.batchCancelOrdersAsync(cancelBatch);
const cancelledAmount = await zeroEx.exchange.getCancelledTakerAmountAsync(orderHashHex); const cancelledAmount = await contractWrappers.exchange.getCancelledTakerAmountAsync(orderHashHex);
const anotherCancelledAmount = await zeroEx.exchange.getCancelledTakerAmountAsync( const anotherCancelledAmount = await contractWrappers.exchange.getCancelledTakerAmountAsync(
anotherOrderHashHex, anotherOrderHashHex,
); );
expect(cancelledAmount).to.be.bignumber.equal(cancelAmount); expect(cancelledAmount).to.be.bignumber.equal(cancelAmount);
@ -808,20 +827,20 @@ describe('ExchangeWrapper', () => {
]; ];
}); });
it('should validate when orderTransactionOptions are not present', async () => { it('should validate when orderTransactionOptions are not present', async () => {
return expect(zeroEx.exchange.batchCancelOrdersAsync(cancelBatch)).to.be.rejectedWith( return expect(contractWrappers.exchange.batchCancelOrdersAsync(cancelBatch)).to.be.rejectedWith(
ExchangeContractErrs.OrderCancelAmountZero, ExchangeContractErrs.OrderCancelAmountZero,
); );
}); });
it('should validate when orderTransactionOptions specify to validate', async () => { it('should validate when orderTransactionOptions specify to validate', async () => {
return expect( return expect(
zeroEx.exchange.batchCancelOrdersAsync(cancelBatch, { contractWrappers.exchange.batchCancelOrdersAsync(cancelBatch, {
shouldValidate: true, shouldValidate: true,
}), }),
).to.be.rejectedWith(ExchangeContractErrs.OrderCancelAmountZero); ).to.be.rejectedWith(ExchangeContractErrs.OrderCancelAmountZero);
}); });
it('should not validate when orderTransactionOptions specify not to validate', async () => { it('should not validate when orderTransactionOptions specify not to validate', async () => {
return expect( return expect(
zeroEx.exchange.batchCancelOrdersAsync(cancelBatch, { contractWrappers.exchange.batchCancelOrdersAsync(cancelBatch, {
shouldValidate: false, shouldValidate: false,
}), }),
).to.not.be.rejectedWith(ExchangeContractErrs.OrderCancelAmountZero); ).to.not.be.rejectedWith(ExchangeContractErrs.OrderCancelAmountZero);
@ -854,53 +873,63 @@ describe('ExchangeWrapper', () => {
fillableAmount, fillableAmount,
partialFillAmount, partialFillAmount,
); );
orderHash = ZeroEx.getOrderHashHex(signedOrder); orderHash = getOrderHashHex(signedOrder);
}); });
describe('#getUnavailableTakerAmountAsync', () => { describe('#getUnavailableTakerAmountAsync', () => {
it('should throw if passed an invalid orderHash', async () => { it('should throw if passed an invalid orderHash', async () => {
const invalidOrderHashHex = '0x123'; const invalidOrderHashHex = '0x123';
return expect(zeroEx.exchange.getUnavailableTakerAmountAsync(invalidOrderHashHex)).to.be.rejected(); return expect(
contractWrappers.exchange.getUnavailableTakerAmountAsync(invalidOrderHashHex),
).to.be.rejected();
}); });
it('should return zero if passed a valid but non-existent orderHash', async () => { it('should return zero if passed a valid but non-existent orderHash', async () => {
const unavailableValueT = await zeroEx.exchange.getUnavailableTakerAmountAsync(NON_EXISTENT_ORDER_HASH); const unavailableValueT = await contractWrappers.exchange.getUnavailableTakerAmountAsync(
NON_EXISTENT_ORDER_HASH,
);
expect(unavailableValueT).to.be.bignumber.equal(0); expect(unavailableValueT).to.be.bignumber.equal(0);
}); });
it('should return the unavailableValueT for a valid and partially filled orderHash', async () => { it('should return the unavailableValueT for a valid and partially filled orderHash', async () => {
const unavailableValueT = await zeroEx.exchange.getUnavailableTakerAmountAsync(orderHash); const unavailableValueT = await contractWrappers.exchange.getUnavailableTakerAmountAsync(orderHash);
expect(unavailableValueT).to.be.bignumber.equal(partialFillAmount); expect(unavailableValueT).to.be.bignumber.equal(partialFillAmount);
}); });
}); });
describe('#getFilledTakerAmountAsync', () => { describe('#getFilledTakerAmountAsync', () => {
it('should throw if passed an invalid orderHash', async () => { it('should throw if passed an invalid orderHash', async () => {
const invalidOrderHashHex = '0x123'; const invalidOrderHashHex = '0x123';
return expect(zeroEx.exchange.getFilledTakerAmountAsync(invalidOrderHashHex)).to.be.rejected(); return expect(
contractWrappers.exchange.getFilledTakerAmountAsync(invalidOrderHashHex),
).to.be.rejected();
}); });
it('should return zero if passed a valid but non-existent orderHash', async () => { it('should return zero if passed a valid but non-existent orderHash', async () => {
const filledValueT = await zeroEx.exchange.getFilledTakerAmountAsync(NON_EXISTENT_ORDER_HASH); const filledValueT = await contractWrappers.exchange.getFilledTakerAmountAsync(NON_EXISTENT_ORDER_HASH);
expect(filledValueT).to.be.bignumber.equal(0); expect(filledValueT).to.be.bignumber.equal(0);
}); });
it('should return the filledValueT for a valid and partially filled orderHash', async () => { it('should return the filledValueT for a valid and partially filled orderHash', async () => {
const filledValueT = await zeroEx.exchange.getFilledTakerAmountAsync(orderHash); const filledValueT = await contractWrappers.exchange.getFilledTakerAmountAsync(orderHash);
expect(filledValueT).to.be.bignumber.equal(partialFillAmount); expect(filledValueT).to.be.bignumber.equal(partialFillAmount);
}); });
}); });
describe('#getCancelledTakerAmountAsync', () => { describe('#getCancelledTakerAmountAsync', () => {
it('should throw if passed an invalid orderHash', async () => { it('should throw if passed an invalid orderHash', async () => {
const invalidOrderHashHex = '0x123'; const invalidOrderHashHex = '0x123';
return expect(zeroEx.exchange.getCancelledTakerAmountAsync(invalidOrderHashHex)).to.be.rejected(); return expect(
contractWrappers.exchange.getCancelledTakerAmountAsync(invalidOrderHashHex),
).to.be.rejected();
}); });
it('should return zero if passed a valid but non-existent orderHash', async () => { it('should return zero if passed a valid but non-existent orderHash', async () => {
const cancelledValueT = await zeroEx.exchange.getCancelledTakerAmountAsync(NON_EXISTENT_ORDER_HASH); const cancelledValueT = await contractWrappers.exchange.getCancelledTakerAmountAsync(
NON_EXISTENT_ORDER_HASH,
);
expect(cancelledValueT).to.be.bignumber.equal(0); expect(cancelledValueT).to.be.bignumber.equal(0);
}); });
it('should return the cancelledValueT for a valid and partially filled orderHash', async () => { it('should return the cancelledValueT for a valid and partially filled orderHash', async () => {
const cancelledValueT = await zeroEx.exchange.getCancelledTakerAmountAsync(orderHash); const cancelledValueT = await contractWrappers.exchange.getCancelledTakerAmountAsync(orderHash);
expect(cancelledValueT).to.be.bignumber.equal(0); expect(cancelledValueT).to.be.bignumber.equal(0);
}); });
it('should return the cancelledValueT for a valid and cancelled orderHash', async () => { it('should return the cancelledValueT for a valid and cancelled orderHash', async () => {
const cancelAmount = fillableAmount.minus(partialFillAmount); const cancelAmount = fillableAmount.minus(partialFillAmount);
await zeroEx.exchange.cancelOrderAsync(signedOrder, cancelAmount); await contractWrappers.exchange.cancelOrderAsync(signedOrder, cancelAmount);
const cancelledValueT = await zeroEx.exchange.getCancelledTakerAmountAsync(orderHash); const cancelledValueT = await contractWrappers.exchange.getCancelledTakerAmountAsync(orderHash);
expect(cancelledValueT).to.be.bignumber.equal(cancelAmount); expect(cancelledValueT).to.be.bignumber.equal(cancelAmount);
}); });
}); });
@ -934,7 +963,7 @@ describe('ExchangeWrapper', () => {
); );
}); });
afterEach(async () => { afterEach(async () => {
zeroEx.exchange.unsubscribeAll(); contractWrappers.exchange.unsubscribeAll();
}); });
// Hack: Mocha does not allow a test to be both async and have a `done` callback // Hack: Mocha does not allow a test to be both async and have a `done` callback
// Since we need to await the receipt of the event in the `subscribe` callback, // Since we need to await the receipt of the event in the `subscribe` callback,
@ -943,13 +972,13 @@ describe('ExchangeWrapper', () => {
// Source: https://github.com/mochajs/mocha/issues/2407 // Source: https://github.com/mochajs/mocha/issues/2407
it('Should receive the LogFill event when an order is filled', (done: DoneCallback) => { it('Should receive the LogFill event when an order is filled', (done: DoneCallback) => {
(async () => { (async () => {
const callback = reportNodeCallbackErrors(done)( const callback = callbackErrorReporter.reportNodeCallbackErrors(done)(
(logEvent: DecodedLogEvent<LogFillContractEventArgs>) => { (logEvent: DecodedLogEvent<LogFillContractEventArgs>) => {
expect(logEvent.log.event).to.be.equal(ExchangeEvents.LogFill); expect(logEvent.log.event).to.be.equal(ExchangeEvents.LogFill);
}, },
); );
zeroEx.exchange.subscribe(ExchangeEvents.LogFill, indexFilterValues, callback); contractWrappers.exchange.subscribe(ExchangeEvents.LogFill, indexFilterValues, callback);
await zeroEx.exchange.fillOrderAsync( await contractWrappers.exchange.fillOrderAsync(
signedOrder, signedOrder,
takerTokenFillAmountInBaseUnits, takerTokenFillAmountInBaseUnits,
shouldThrowOnInsufficientBalanceOrAllowance, shouldThrowOnInsufficientBalanceOrAllowance,
@ -959,33 +988,33 @@ describe('ExchangeWrapper', () => {
}); });
it('Should receive the LogCancel event when an order is cancelled', (done: DoneCallback) => { it('Should receive the LogCancel event when an order is cancelled', (done: DoneCallback) => {
(async () => { (async () => {
const callback = reportNodeCallbackErrors(done)( const callback = callbackErrorReporter.reportNodeCallbackErrors(done)(
(logEvent: DecodedLogEvent<LogCancelContractEventArgs>) => { (logEvent: DecodedLogEvent<LogCancelContractEventArgs>) => {
expect(logEvent.log.event).to.be.equal(ExchangeEvents.LogCancel); expect(logEvent.log.event).to.be.equal(ExchangeEvents.LogCancel);
}, },
); );
zeroEx.exchange.subscribe(ExchangeEvents.LogCancel, indexFilterValues, callback); contractWrappers.exchange.subscribe(ExchangeEvents.LogCancel, indexFilterValues, callback);
await zeroEx.exchange.cancelOrderAsync(signedOrder, cancelTakerAmountInBaseUnits); await contractWrappers.exchange.cancelOrderAsync(signedOrder, cancelTakerAmountInBaseUnits);
})().catch(done); })().catch(done);
}); });
it('Outstanding subscriptions are cancelled when zeroEx.setProvider called', (done: DoneCallback) => { it('Outstanding subscriptions are cancelled when contractWrappers.setProvider called', (done: DoneCallback) => {
(async () => { (async () => {
const callbackNeverToBeCalled = reportNodeCallbackErrors(done)( const callbackNeverToBeCalled = callbackErrorReporter.reportNodeCallbackErrors(done)(
(logEvent: DecodedLogEvent<LogFillContractEventArgs>) => { (logEvent: DecodedLogEvent<LogFillContractEventArgs>) => {
done(new Error('Expected this subscription to have been cancelled')); done(new Error('Expected this subscription to have been cancelled'));
}, },
); );
zeroEx.exchange.subscribe(ExchangeEvents.LogFill, indexFilterValues, callbackNeverToBeCalled); contractWrappers.exchange.subscribe(ExchangeEvents.LogFill, indexFilterValues, callbackNeverToBeCalled);
zeroEx.setProvider(provider, constants.TESTRPC_NETWORK_ID); contractWrappers.setProvider(provider, constants.TESTRPC_NETWORK_ID);
const callback = reportNodeCallbackErrors(done)( const callback = callbackErrorReporter.reportNodeCallbackErrors(done)(
(logEvent: DecodedLogEvent<LogFillContractEventArgs>) => { (logEvent: DecodedLogEvent<LogFillContractEventArgs>) => {
expect(logEvent.log.event).to.be.equal(ExchangeEvents.LogFill); expect(logEvent.log.event).to.be.equal(ExchangeEvents.LogFill);
}, },
); );
zeroEx.exchange.subscribe(ExchangeEvents.LogFill, indexFilterValues, callback); contractWrappers.exchange.subscribe(ExchangeEvents.LogFill, indexFilterValues, callback);
await zeroEx.exchange.fillOrderAsync( await contractWrappers.exchange.fillOrderAsync(
signedOrder, signedOrder,
takerTokenFillAmountInBaseUnits, takerTokenFillAmountInBaseUnits,
shouldThrowOnInsufficientBalanceOrAllowance, shouldThrowOnInsufficientBalanceOrAllowance,
@ -995,18 +1024,18 @@ describe('ExchangeWrapper', () => {
}); });
it('Should cancel subscription when unsubscribe called', (done: DoneCallback) => { it('Should cancel subscription when unsubscribe called', (done: DoneCallback) => {
(async () => { (async () => {
const callbackNeverToBeCalled = reportNodeCallbackErrors(done)( const callbackNeverToBeCalled = callbackErrorReporter.reportNodeCallbackErrors(done)(
(logEvent: DecodedLogEvent<LogFillContractEventArgs>) => { (logEvent: DecodedLogEvent<LogFillContractEventArgs>) => {
done(new Error('Expected this subscription to have been cancelled')); done(new Error('Expected this subscription to have been cancelled'));
}, },
); );
const subscriptionToken = zeroEx.exchange.subscribe( const subscriptionToken = contractWrappers.exchange.subscribe(
ExchangeEvents.LogFill, ExchangeEvents.LogFill,
indexFilterValues, indexFilterValues,
callbackNeverToBeCalled, callbackNeverToBeCalled,
); );
zeroEx.exchange.unsubscribe(subscriptionToken); contractWrappers.exchange.unsubscribe(subscriptionToken);
await zeroEx.exchange.fillOrderAsync( await contractWrappers.exchange.fillOrderAsync(
signedOrder, signedOrder,
takerTokenFillAmountInBaseUnits, takerTokenFillAmountInBaseUnits,
shouldThrowOnInsufficientBalanceOrAllowance, shouldThrowOnInsufficientBalanceOrAllowance,
@ -1036,8 +1065,8 @@ describe('ExchangeWrapper', () => {
takerAddress, takerAddress,
fillableAmount, fillableAmount,
); );
const orderHash = ZeroEx.getOrderHashHex(signedOrder); const orderHash = getOrderHashHex(signedOrder);
const orderHashFromContract = await (zeroEx.exchange as any)._getOrderHashHexUsingContractCallAsync( const orderHashFromContract = await (contractWrappers.exchange as any)._getOrderHashHexUsingContractCallAsync(
signedOrder, signedOrder,
); );
expect(orderHash).to.equal(orderHashFromContract); expect(orderHash).to.equal(orderHashFromContract);
@ -1045,7 +1074,7 @@ describe('ExchangeWrapper', () => {
}); });
describe('#getZRXTokenAddressAsync', () => { describe('#getZRXTokenAddressAsync', () => {
it('gets the same token as is in token registry', () => { it('gets the same token as is in token registry', () => {
const zrxAddress = zeroEx.exchange.getZRXTokenAddress(); const zrxAddress = contractWrappers.exchange.getZRXTokenAddress();
const zrxToken = tokenUtils.getProtocolTokenOrThrow(); const zrxToken = tokenUtils.getProtocolTokenOrThrow();
expect(zrxAddress).to.equal(zrxToken.address); expect(zrxAddress).to.equal(zrxToken.address);
}); });
@ -1076,16 +1105,16 @@ describe('ExchangeWrapper', () => {
takerAddress, takerAddress,
fillableAmount, fillableAmount,
); );
txHash = await zeroEx.exchange.fillOrderAsync( txHash = await contractWrappers.exchange.fillOrderAsync(
signedOrder, signedOrder,
fillableAmount, fillableAmount,
shouldThrowOnInsufficientBalanceOrAllowance, shouldThrowOnInsufficientBalanceOrAllowance,
takerAddress, takerAddress,
); );
await zeroEx.awaitTransactionMinedAsync(txHash); await web3Wrapper.awaitTransactionMinedAsync(txHash);
const eventName = ExchangeEvents.LogFill; const eventName = ExchangeEvents.LogFill;
const indexFilterValues = {}; const indexFilterValues = {};
const logs = await zeroEx.exchange.getLogsAsync(eventName, blockRange, indexFilterValues); const logs = await contractWrappers.exchange.getLogsAsync(eventName, blockRange, indexFilterValues);
expect(logs).to.have.length(1); expect(logs).to.have.length(1);
expect(logs[0].event).to.be.equal(eventName); expect(logs[0].event).to.be.equal(eventName);
}); });
@ -1097,16 +1126,20 @@ describe('ExchangeWrapper', () => {
takerAddress, takerAddress,
fillableAmount, fillableAmount,
); );
txHash = await zeroEx.exchange.fillOrderAsync( txHash = await contractWrappers.exchange.fillOrderAsync(
signedOrder, signedOrder,
fillableAmount, fillableAmount,
shouldThrowOnInsufficientBalanceOrAllowance, shouldThrowOnInsufficientBalanceOrAllowance,
takerAddress, takerAddress,
); );
await zeroEx.awaitTransactionMinedAsync(txHash); await web3Wrapper.awaitTransactionMinedAsync(txHash);
const differentEventName = ExchangeEvents.LogCancel; const differentEventName = ExchangeEvents.LogCancel;
const indexFilterValues = {}; const indexFilterValues = {};
const logs = await zeroEx.exchange.getLogsAsync(differentEventName, blockRange, indexFilterValues); const logs = await contractWrappers.exchange.getLogsAsync(
differentEventName,
blockRange,
indexFilterValues,
);
expect(logs).to.have.length(0); expect(logs).to.have.length(0);
}); });
it('should only get the logs with the correct indexed fields', async () => { it('should only get the logs with the correct indexed fields', async () => {
@ -1117,13 +1150,13 @@ describe('ExchangeWrapper', () => {
takerAddress, takerAddress,
fillableAmount, fillableAmount,
); );
txHash = await zeroEx.exchange.fillOrderAsync( txHash = await contractWrappers.exchange.fillOrderAsync(
signedOrder, signedOrder,
fillableAmount, fillableAmount,
shouldThrowOnInsufficientBalanceOrAllowance, shouldThrowOnInsufficientBalanceOrAllowance,
takerAddress, takerAddress,
); );
await zeroEx.awaitTransactionMinedAsync(txHash); await web3Wrapper.awaitTransactionMinedAsync(txHash);
const differentMakerAddress = userAddresses[2]; const differentMakerAddress = userAddresses[2];
const anotherSignedOrder = await fillScenarios.createFillableSignedOrderAsync( const anotherSignedOrder = await fillScenarios.createFillableSignedOrderAsync(
@ -1133,19 +1166,19 @@ describe('ExchangeWrapper', () => {
takerAddress, takerAddress,
fillableAmount, fillableAmount,
); );
txHash = await zeroEx.exchange.fillOrderAsync( txHash = await contractWrappers.exchange.fillOrderAsync(
anotherSignedOrder, anotherSignedOrder,
fillableAmount, fillableAmount,
shouldThrowOnInsufficientBalanceOrAllowance, shouldThrowOnInsufficientBalanceOrAllowance,
takerAddress, takerAddress,
); );
await zeroEx.awaitTransactionMinedAsync(txHash); await web3Wrapper.awaitTransactionMinedAsync(txHash);
const eventName = ExchangeEvents.LogFill; const eventName = ExchangeEvents.LogFill;
const indexFilterValues = { const indexFilterValues = {
maker: differentMakerAddress, maker: differentMakerAddress,
}; };
const logs = await zeroEx.exchange.getLogsAsync<LogFillContractEventArgs>( const logs = await contractWrappers.exchange.getLogsAsync<LogFillContractEventArgs>(
eventName, eventName,
blockRange, blockRange,
indexFilterValues, indexFilterValues,
@ -1162,10 +1195,10 @@ describe('ExchangeWrapper', () => {
let takerToken: Token; let takerToken: Token;
let signedOrder: SignedOrder; let signedOrder: SignedOrder;
let orderState: OrderState; let orderState: OrderState;
const fillableAmount = ZeroEx.toBaseUnitAmount(new BigNumber(5), constants.ZRX_DECIMALS); const fillableAmount = Web3Wrapper.toBaseUnitAmount(new BigNumber(5), constants.ZRX_DECIMALS);
before(async () => { before(async () => {
[, maker, taker] = userAddresses; [, maker, taker] = userAddresses;
tokens = await zeroEx.tokenRegistry.getTokensAsync(); tokens = await contractWrappers.tokenRegistry.getTokensAsync();
[makerToken, takerToken] = tokenUtils.getDummyTokens(); [makerToken, takerToken] = tokenUtils.getDummyTokens();
}); });
it('should report orderStateValid when order is fillable', async () => { it('should report orderStateValid when order is fillable', async () => {
@ -1176,7 +1209,7 @@ describe('ExchangeWrapper', () => {
taker, taker,
fillableAmount, fillableAmount,
); );
orderState = await zeroEx.exchange.getOrderStateAsync(signedOrder); orderState = await contractWrappers.exchange.getOrderStateAsync(signedOrder);
expect(orderState.isValid).to.be.true(); expect(orderState.isValid).to.be.true();
}); });
it('should report orderStateInvalid when maker allowance set to 0', async () => { it('should report orderStateInvalid when maker allowance set to 0', async () => {
@ -1187,8 +1220,8 @@ describe('ExchangeWrapper', () => {
taker, taker,
fillableAmount, fillableAmount,
); );
await zeroEx.token.setProxyAllowanceAsync(makerToken.address, maker, new BigNumber(0)); await contractWrappers.token.setProxyAllowanceAsync(makerToken.address, maker, new BigNumber(0));
orderState = await zeroEx.exchange.getOrderStateAsync(signedOrder); orderState = await contractWrappers.exchange.getOrderStateAsync(signedOrder);
expect(orderState.isValid).to.be.false(); expect(orderState.isValid).to.be.false();
}); });
}); });

View File

@ -0,0 +1,7 @@
import { runMigrationsAsync } from '@0xproject/migrations';
import { deployer } from './utils/deployer';
before('migrate contracts', async () => {
await runMigrationsAsync(deployer);
});

View File

@ -1,18 +1,18 @@
import { BlockchainLifecycle, devConstants } from '@0xproject/dev-utils'; import { BlockchainLifecycle, devConstants } from '@0xproject/dev-utils';
import { FillScenarios } from '@0xproject/fill-scenarios';
import { OrderError } from '@0xproject/order-utils'; import { OrderError } from '@0xproject/order-utils';
import { BlockParamLiteral } from '@0xproject/types'; import { BlockParamLiteral } from '@0xproject/types';
import { BigNumber } from '@0xproject/utils'; import { BigNumber } from '@0xproject/utils';
import * as chai from 'chai'; import * as chai from 'chai';
import * as Sinon from 'sinon'; import * as Sinon from 'sinon';
import { ExchangeContractErrs, SignedOrder, Token, ZeroEx, ZeroExError } from '../src'; import { ContractWrappers, ContractWrappersError, ExchangeContractErrs, SignedOrder, Token } from '../src';
import { TradeSide, TransferType } from '../src/types'; import { TradeSide, TransferType } from '../src/types';
import { ExchangeTransferSimulator } from '../src/utils/exchange_transfer_simulator'; import { ExchangeTransferSimulator } from '../src/utils/exchange_transfer_simulator';
import { OrderValidationUtils } from '../src/utils/order_validation_utils'; import { OrderValidationUtils } from '../src/utils/order_validation_utils';
import { chaiSetup } from './utils/chai_setup'; import { chaiSetup } from './utils/chai_setup';
import { constants } from './utils/constants'; import { constants } from './utils/constants';
import { FillScenarios } from './utils/fill_scenarios';
import { TokenUtils } from './utils/token_utils'; import { TokenUtils } from './utils/token_utils';
import { provider, web3Wrapper } from './utils/web3_wrapper'; import { provider, web3Wrapper } from './utils/web3_wrapper';
@ -21,7 +21,7 @@ const expect = chai.expect;
const blockchainLifecycle = new BlockchainLifecycle(web3Wrapper); const blockchainLifecycle = new BlockchainLifecycle(web3Wrapper);
describe('OrderValidation', () => { describe('OrderValidation', () => {
let zeroEx: ZeroEx; let contractWrappers: ContractWrappers;
let userAddresses: string[]; let userAddresses: string[];
let tokens: Token[]; let tokens: Token[];
let tokenUtils: TokenUtils; let tokenUtils: TokenUtils;
@ -40,14 +40,14 @@ describe('OrderValidation', () => {
networkId: constants.TESTRPC_NETWORK_ID, networkId: constants.TESTRPC_NETWORK_ID,
}; };
before(async () => { before(async () => {
zeroEx = new ZeroEx(provider, config); contractWrappers = new ContractWrappers(provider, config);
exchangeContractAddress = zeroEx.exchange.getContractAddress(); exchangeContractAddress = contractWrappers.exchange.getContractAddress();
userAddresses = await zeroEx.getAvailableAddressesAsync(); userAddresses = await web3Wrapper.getAvailableAddressesAsync();
[coinbase, makerAddress, takerAddress, feeRecipient] = userAddresses; [coinbase, makerAddress, takerAddress, feeRecipient] = userAddresses;
tokens = await zeroEx.tokenRegistry.getTokensAsync(); tokens = await contractWrappers.tokenRegistry.getTokensAsync();
tokenUtils = new TokenUtils(tokens); tokenUtils = new TokenUtils(tokens);
zrxTokenAddress = tokenUtils.getProtocolTokenOrThrow().address; zrxTokenAddress = tokenUtils.getProtocolTokenOrThrow().address;
fillScenarios = new FillScenarios(zeroEx, userAddresses, tokens, zrxTokenAddress, exchangeContractAddress); fillScenarios = new FillScenarios(provider, userAddresses, tokens, zrxTokenAddress, exchangeContractAddress);
const [makerToken, takerToken] = tokenUtils.getDummyTokens(); const [makerToken, takerToken] = tokenUtils.getDummyTokens();
makerTokenAddress = makerToken.address; makerTokenAddress = makerToken.address;
takerTokenAddress = takerToken.address; takerTokenAddress = takerToken.address;
@ -67,7 +67,7 @@ describe('OrderValidation', () => {
takerAddress, takerAddress,
fillableAmount, fillableAmount,
); );
await zeroEx.exchange.validateOrderFillableOrThrowAsync(signedOrder); await contractWrappers.exchange.validateOrderFillableOrThrowAsync(signedOrder);
}); });
it('should succeed if the maker is buying ZRX and has no ZRX balance', async () => { it('should succeed if the maker is buying ZRX and has no ZRX balance', async () => {
const makerFee = new BigNumber(2); const makerFee = new BigNumber(2);
@ -82,9 +82,9 @@ describe('OrderValidation', () => {
fillableAmount, fillableAmount,
feeRecipient, feeRecipient,
); );
const zrxMakerBalance = await zeroEx.token.getBalanceAsync(zrxTokenAddress, makerAddress); const zrxMakerBalance = await contractWrappers.token.getBalanceAsync(zrxTokenAddress, makerAddress);
await zeroEx.token.transferAsync(zrxTokenAddress, makerAddress, takerAddress, zrxMakerBalance); await contractWrappers.token.transferAsync(zrxTokenAddress, makerAddress, takerAddress, zrxMakerBalance);
await zeroEx.exchange.validateOrderFillableOrThrowAsync(signedOrder); await contractWrappers.exchange.validateOrderFillableOrThrowAsync(signedOrder);
}); });
it('should succeed if the maker is buying ZRX and has no ZRX balance and there is no specified taker', async () => { it('should succeed if the maker is buying ZRX and has no ZRX balance and there is no specified taker', async () => {
const makerFee = new BigNumber(2); const makerFee = new BigNumber(2);
@ -99,9 +99,9 @@ describe('OrderValidation', () => {
fillableAmount, fillableAmount,
feeRecipient, feeRecipient,
); );
const zrxMakerBalance = await zeroEx.token.getBalanceAsync(zrxTokenAddress, makerAddress); const zrxMakerBalance = await contractWrappers.token.getBalanceAsync(zrxTokenAddress, makerAddress);
await zeroEx.token.transferAsync(zrxTokenAddress, makerAddress, takerAddress, zrxMakerBalance); await contractWrappers.token.transferAsync(zrxTokenAddress, makerAddress, takerAddress, zrxMakerBalance);
await zeroEx.exchange.validateOrderFillableOrThrowAsync(signedOrder); await contractWrappers.exchange.validateOrderFillableOrThrowAsync(signedOrder);
}); });
it('should succeed if the order is asymmetric and fillable', async () => { it('should succeed if the order is asymmetric and fillable', async () => {
const makerFillableAmount = fillableAmount; const makerFillableAmount = fillableAmount;
@ -114,7 +114,7 @@ describe('OrderValidation', () => {
makerFillableAmount, makerFillableAmount,
takerFillableAmount, takerFillableAmount,
); );
await zeroEx.exchange.validateOrderFillableOrThrowAsync(signedOrder); await contractWrappers.exchange.validateOrderFillableOrThrowAsync(signedOrder);
}); });
it('should throw when the order is fully filled or cancelled', async () => { it('should throw when the order is fully filled or cancelled', async () => {
const signedOrder = await fillScenarios.createFillableSignedOrderAsync( const signedOrder = await fillScenarios.createFillableSignedOrderAsync(
@ -124,8 +124,8 @@ describe('OrderValidation', () => {
takerAddress, takerAddress,
fillableAmount, fillableAmount,
); );
await zeroEx.exchange.cancelOrderAsync(signedOrder, fillableAmount); await contractWrappers.exchange.cancelOrderAsync(signedOrder, fillableAmount);
return expect(zeroEx.exchange.validateOrderFillableOrThrowAsync(signedOrder)).to.be.rejectedWith( return expect(contractWrappers.exchange.validateOrderFillableOrThrowAsync(signedOrder)).to.be.rejectedWith(
ExchangeContractErrs.OrderRemainingFillAmountZero, ExchangeContractErrs.OrderRemainingFillAmountZero,
); );
}); });
@ -139,7 +139,7 @@ describe('OrderValidation', () => {
fillableAmount, fillableAmount,
expirationInPast, expirationInPast,
); );
return expect(zeroEx.exchange.validateOrderFillableOrThrowAsync(signedOrder)).to.be.rejectedWith( return expect(contractWrappers.exchange.validateOrderFillableOrThrowAsync(signedOrder)).to.be.rejectedWith(
ExchangeContractErrs.OrderFillExpired, ExchangeContractErrs.OrderFillExpired,
); );
}); });
@ -155,7 +155,11 @@ describe('OrderValidation', () => {
); );
const zeroFillAmount = new BigNumber(0); const zeroFillAmount = new BigNumber(0);
return expect( return expect(
zeroEx.exchange.validateFillOrderThrowIfInvalidAsync(signedOrder, zeroFillAmount, takerAddress), contractWrappers.exchange.validateFillOrderThrowIfInvalidAsync(
signedOrder,
zeroFillAmount,
takerAddress,
),
).to.be.rejectedWith(ExchangeContractErrs.OrderFillAmountZero); ).to.be.rejectedWith(ExchangeContractErrs.OrderFillAmountZero);
}); });
it('should throw when the signature is invalid', async () => { it('should throw when the signature is invalid', async () => {
@ -169,7 +173,11 @@ describe('OrderValidation', () => {
// 27 <--> 28 // 27 <--> 28
signedOrder.ecSignature.v = 28 - signedOrder.ecSignature.v + 27; signedOrder.ecSignature.v = 28 - signedOrder.ecSignature.v + 27;
return expect( return expect(
zeroEx.exchange.validateFillOrderThrowIfInvalidAsync(signedOrder, fillableAmount, takerAddress), contractWrappers.exchange.validateFillOrderThrowIfInvalidAsync(
signedOrder,
fillableAmount,
takerAddress,
),
).to.be.rejectedWith(OrderError.InvalidSignature); ).to.be.rejectedWith(OrderError.InvalidSignature);
}); });
it('should throw when the order is fully filled or cancelled', async () => { it('should throw when the order is fully filled or cancelled', async () => {
@ -180,9 +188,13 @@ describe('OrderValidation', () => {
takerAddress, takerAddress,
fillableAmount, fillableAmount,
); );
await zeroEx.exchange.cancelOrderAsync(signedOrder, fillableAmount); await contractWrappers.exchange.cancelOrderAsync(signedOrder, fillableAmount);
return expect( return expect(
zeroEx.exchange.validateFillOrderThrowIfInvalidAsync(signedOrder, fillableAmount, takerAddress), contractWrappers.exchange.validateFillOrderThrowIfInvalidAsync(
signedOrder,
fillableAmount,
takerAddress,
),
).to.be.rejectedWith(ExchangeContractErrs.OrderRemainingFillAmountZero); ).to.be.rejectedWith(ExchangeContractErrs.OrderRemainingFillAmountZero);
}); });
it('should throw when sender is not a taker', async () => { it('should throw when sender is not a taker', async () => {
@ -195,7 +207,11 @@ describe('OrderValidation', () => {
); );
const nonTakerAddress = userAddresses[6]; const nonTakerAddress = userAddresses[6];
return expect( return expect(
zeroEx.exchange.validateFillOrderThrowIfInvalidAsync(signedOrder, fillTakerAmount, nonTakerAddress), contractWrappers.exchange.validateFillOrderThrowIfInvalidAsync(
signedOrder,
fillTakerAmount,
nonTakerAddress,
),
).to.be.rejectedWith(ExchangeContractErrs.TransactionSenderIsNotFillOrderTaker); ).to.be.rejectedWith(ExchangeContractErrs.TransactionSenderIsNotFillOrderTaker);
}); });
it('should throw when order is expired', async () => { it('should throw when order is expired', async () => {
@ -209,7 +225,11 @@ describe('OrderValidation', () => {
expirationInPast, expirationInPast,
); );
return expect( return expect(
zeroEx.exchange.validateFillOrderThrowIfInvalidAsync(signedOrder, fillTakerAmount, takerAddress), contractWrappers.exchange.validateFillOrderThrowIfInvalidAsync(
signedOrder,
fillTakerAmount,
takerAddress,
),
).to.be.rejectedWith(ExchangeContractErrs.OrderFillExpired); ).to.be.rejectedWith(ExchangeContractErrs.OrderFillExpired);
}); });
it('should throw when there a rounding error would have occurred', async () => { it('should throw when there a rounding error would have occurred', async () => {
@ -225,7 +245,7 @@ describe('OrderValidation', () => {
); );
const fillTakerAmountThatCausesRoundingError = new BigNumber(3); const fillTakerAmountThatCausesRoundingError = new BigNumber(3);
return expect( return expect(
zeroEx.exchange.validateFillOrderThrowIfInvalidAsync( contractWrappers.exchange.validateFillOrderThrowIfInvalidAsync(
signedOrder, signedOrder,
fillTakerAmountThatCausesRoundingError, fillTakerAmountThatCausesRoundingError,
takerAddress, takerAddress,
@ -244,13 +264,13 @@ describe('OrderValidation', () => {
); );
const tooLargeFillAmount = new BigNumber(7); const tooLargeFillAmount = new BigNumber(7);
const fillAmountDifference = tooLargeFillAmount.minus(fillableAmount); const fillAmountDifference = tooLargeFillAmount.minus(fillableAmount);
await zeroEx.token.transferAsync(takerTokenAddress, coinbase, takerAddress, fillAmountDifference); await contractWrappers.token.transferAsync(takerTokenAddress, coinbase, takerAddress, fillAmountDifference);
await zeroEx.token.setProxyAllowanceAsync(takerTokenAddress, takerAddress, tooLargeFillAmount); await contractWrappers.token.setProxyAllowanceAsync(takerTokenAddress, takerAddress, tooLargeFillAmount);
await zeroEx.token.transferAsync(makerTokenAddress, coinbase, makerAddress, fillAmountDifference); await contractWrappers.token.transferAsync(makerTokenAddress, coinbase, makerAddress, fillAmountDifference);
await zeroEx.token.setProxyAllowanceAsync(makerTokenAddress, makerAddress, tooLargeFillAmount); await contractWrappers.token.setProxyAllowanceAsync(makerTokenAddress, makerAddress, tooLargeFillAmount);
return expect( return expect(
zeroEx.exchange.validateFillOrKillOrderThrowIfInvalidAsync( contractWrappers.exchange.validateFillOrKillOrderThrowIfInvalidAsync(
signedOrder, signedOrder,
tooLargeFillAmount, tooLargeFillAmount,
takerAddress, takerAddress,
@ -277,7 +297,7 @@ describe('OrderValidation', () => {
it('should throw when cancel amount is zero', async () => { it('should throw when cancel amount is zero', async () => {
const zeroCancelAmount = new BigNumber(0); const zeroCancelAmount = new BigNumber(0);
return expect( return expect(
zeroEx.exchange.validateCancelOrderThrowIfInvalidAsync(signedOrder, zeroCancelAmount), contractWrappers.exchange.validateCancelOrderThrowIfInvalidAsync(signedOrder, zeroCancelAmount),
).to.be.rejectedWith(ExchangeContractErrs.OrderCancelAmountZero); ).to.be.rejectedWith(ExchangeContractErrs.OrderCancelAmountZero);
}); });
it('should throw when order is expired', async () => { it('should throw when order is expired', async () => {
@ -291,13 +311,13 @@ describe('OrderValidation', () => {
expirationInPast, expirationInPast,
); );
return expect( return expect(
zeroEx.exchange.validateCancelOrderThrowIfInvalidAsync(expiredSignedOrder, cancelAmount), contractWrappers.exchange.validateCancelOrderThrowIfInvalidAsync(expiredSignedOrder, cancelAmount),
).to.be.rejectedWith(ExchangeContractErrs.OrderCancelExpired); ).to.be.rejectedWith(ExchangeContractErrs.OrderCancelExpired);
}); });
it('should throw when order is already cancelled or filled', async () => { it('should throw when order is already cancelled or filled', async () => {
await zeroEx.exchange.cancelOrderAsync(signedOrder, fillableAmount); await contractWrappers.exchange.cancelOrderAsync(signedOrder, fillableAmount);
return expect( return expect(
zeroEx.exchange.validateCancelOrderThrowIfInvalidAsync(signedOrder, fillableAmount), contractWrappers.exchange.validateCancelOrderThrowIfInvalidAsync(signedOrder, fillableAmount),
).to.be.rejectedWith(ExchangeContractErrs.OrderAlreadyCancelledOrFilled); ).to.be.rejectedWith(ExchangeContractErrs.OrderAlreadyCancelledOrFilled);
}); });
}); });
@ -308,7 +328,7 @@ describe('OrderValidation', () => {
return Sinon.match((value: BigNumber) => value.eq(expected)); return Sinon.match((value: BigNumber) => value.eq(expected));
}; };
beforeEach('create exchangeTransferSimulator', async () => { beforeEach('create exchangeTransferSimulator', async () => {
exchangeTransferSimulator = new ExchangeTransferSimulator(zeroEx.token, BlockParamLiteral.Latest); exchangeTransferSimulator = new ExchangeTransferSimulator(contractWrappers.token, BlockParamLiteral.Latest);
transferFromAsync = Sinon.spy(); transferFromAsync = Sinon.spy();
exchangeTransferSimulator.transferFromAsync = transferFromAsync as any; exchangeTransferSimulator.transferFromAsync = transferFromAsync as any;
}); });
@ -391,7 +411,7 @@ describe('OrderValidation', () => {
makerFee, makerFee,
takerFee, takerFee,
makerAddress, makerAddress,
ZeroEx.NULL_ADDRESS, constants.NULL_ADDRESS,
fillableAmount, fillableAmount,
feeRecipient, feeRecipient,
); );
@ -485,7 +505,7 @@ describe('OrderValidation', () => {
makerAddress, makerAddress,
takerAddress, takerAddress,
fillableAmount, fillableAmount,
ZeroEx.NULL_ADDRESS, constants.NULL_ADDRESS,
); );
const fillTakerTokenAmount = fillableAmount.div(2).round(0); const fillTakerTokenAmount = fillableAmount.div(2).round(0);
await OrderValidationUtils.validateFillOrderBalancesAllowancesThrowIfInvalidAsync( await OrderValidationUtils.validateFillOrderBalancesAllowancesThrowIfInvalidAsync(

View File

@ -1,22 +1,21 @@
import { BlockchainLifecycle, devConstants } from '@0xproject/dev-utils'; import { BlockchainLifecycle, callbackErrorReporter, devConstants } from '@0xproject/dev-utils';
import { DoneCallback } from '@0xproject/types';
import { BigNumber } from '@0xproject/utils'; import { BigNumber } from '@0xproject/utils';
import * as _ from 'lodash'; import * as _ from 'lodash';
import 'mocha'; import 'mocha';
import * as Sinon from 'sinon'; import * as Sinon from 'sinon';
import { ApprovalContractEventArgs, DecodedLogEvent, Token, TokenEvents, ZeroEx } from '../src'; import { ApprovalContractEventArgs, ContractWrappers, DecodedLogEvent, Token, TokenEvents } from '../src';
import { DoneCallback } from '../src/types';
import { chaiSetup } from './utils/chai_setup'; import { chaiSetup } from './utils/chai_setup';
import { constants } from './utils/constants'; import { constants } from './utils/constants';
import { assertNodeCallbackError } from './utils/report_callback_errors';
import { provider, web3Wrapper } from './utils/web3_wrapper'; import { provider, web3Wrapper } from './utils/web3_wrapper';
chaiSetup.configure(); chaiSetup.configure();
const blockchainLifecycle = new BlockchainLifecycle(web3Wrapper); const blockchainLifecycle = new BlockchainLifecycle(web3Wrapper);
describe('SubscriptionTest', () => { describe('SubscriptionTest', () => {
let zeroEx: ZeroEx; let contractWrappers: ContractWrappers;
let userAddresses: string[]; let userAddresses: string[];
let tokens: Token[]; let tokens: Token[];
let coinbase: string; let coinbase: string;
@ -25,9 +24,9 @@ describe('SubscriptionTest', () => {
networkId: constants.TESTRPC_NETWORK_ID, networkId: constants.TESTRPC_NETWORK_ID,
}; };
before(async () => { before(async () => {
zeroEx = new ZeroEx(provider, config); contractWrappers = new ContractWrappers(provider, config);
userAddresses = await zeroEx.getAvailableAddressesAsync(); userAddresses = await web3Wrapper.getAvailableAddressesAsync();
tokens = await zeroEx.tokenRegistry.getTokensAsync(); tokens = await contractWrappers.tokenRegistry.getTokensAsync();
coinbase = userAddresses[0]; coinbase = userAddresses[0];
addressWithoutFunds = userAddresses[1]; addressWithoutFunds = userAddresses[1];
}); });
@ -47,34 +46,48 @@ describe('SubscriptionTest', () => {
tokenAddress = token.address; tokenAddress = token.address;
}); });
afterEach(() => { afterEach(() => {
zeroEx.token.unsubscribeAll(); contractWrappers.token.unsubscribeAll();
_.each(stubs, s => s.restore()); _.each(stubs, s => s.restore());
stubs = []; stubs = [];
}); });
it('Should receive the Error when an error occurs while fetching the block', (done: DoneCallback) => { it('Should receive the Error when an error occurs while fetching the block', (done: DoneCallback) => {
(async () => { (async () => {
const errMsg = 'Error fetching block'; const errMsg = 'Error fetching block';
const callback = assertNodeCallbackError(done, errMsg); const callback = callbackErrorReporter.assertNodeCallbackError(done, errMsg);
stubs = [Sinon.stub((zeroEx as any)._web3Wrapper, 'getBlockAsync').throws(new Error(errMsg))]; stubs = [Sinon.stub((contractWrappers as any)._web3Wrapper, 'getBlockAsync').throws(new Error(errMsg))];
zeroEx.token.subscribe(tokenAddress, TokenEvents.Approval, indexFilterValues, callback); contractWrappers.token.subscribe(tokenAddress, TokenEvents.Approval, indexFilterValues, callback);
await zeroEx.token.setAllowanceAsync(tokenAddress, coinbase, addressWithoutFunds, allowanceAmount); await contractWrappers.token.setAllowanceAsync(
tokenAddress,
coinbase,
addressWithoutFunds,
allowanceAmount,
);
})().catch(done); })().catch(done);
}); });
it('Should receive the Error when an error occurs while reconciling the new block', (done: DoneCallback) => { it('Should receive the Error when an error occurs while reconciling the new block', (done: DoneCallback) => {
(async () => { (async () => {
const errMsg = 'Error fetching logs'; const errMsg = 'Error fetching logs';
const callback = assertNodeCallbackError(done, errMsg); const callback = callbackErrorReporter.assertNodeCallbackError(done, errMsg);
stubs = [Sinon.stub((zeroEx as any)._web3Wrapper, 'getLogsAsync').throws(new Error(errMsg))]; stubs = [Sinon.stub((contractWrappers as any)._web3Wrapper, 'getLogsAsync').throws(new Error(errMsg))];
zeroEx.token.subscribe(tokenAddress, TokenEvents.Approval, indexFilterValues, callback); contractWrappers.token.subscribe(tokenAddress, TokenEvents.Approval, indexFilterValues, callback);
await zeroEx.token.setAllowanceAsync(tokenAddress, coinbase, addressWithoutFunds, allowanceAmount); await contractWrappers.token.setAllowanceAsync(
tokenAddress,
coinbase,
addressWithoutFunds,
allowanceAmount,
);
})().catch(done); })().catch(done);
}); });
it('Should allow unsubscribeAll to be called successfully after an error', (done: DoneCallback) => { it('Should allow unsubscribeAll to be called successfully after an error', (done: DoneCallback) => {
(async () => { (async () => {
const callback = (err: Error | null, logEvent?: DecodedLogEvent<ApprovalContractEventArgs>) => _.noop; const callback = (err: Error | null, logEvent?: DecodedLogEvent<ApprovalContractEventArgs>) => _.noop;
zeroEx.token.subscribe(tokenAddress, TokenEvents.Approval, indexFilterValues, callback); contractWrappers.token.subscribe(tokenAddress, TokenEvents.Approval, indexFilterValues, callback);
stubs = [Sinon.stub((zeroEx as any)._web3Wrapper, 'getBlockAsync').throws(new Error('JSON RPC error'))]; stubs = [
zeroEx.token.unsubscribeAll(); Sinon.stub((contractWrappers as any)._web3Wrapper, 'getBlockAsync').throws(
new Error('JSON RPC error'),
),
];
contractWrappers.token.unsubscribeAll();
done(); done();
})().catch(done); })().catch(done);
}); });

View File

@ -4,7 +4,7 @@ import * as chai from 'chai';
import * as _ from 'lodash'; import * as _ from 'lodash';
import 'mocha'; import 'mocha';
import { Token, ZeroEx } from '../src'; import { ContractWrappers, Token } from '../src';
import { chaiSetup } from './utils/chai_setup'; import { chaiSetup } from './utils/chai_setup';
import { constants } from './utils/constants'; import { constants } from './utils/constants';
@ -17,7 +17,7 @@ const blockchainLifecycle = new BlockchainLifecycle(web3Wrapper);
const TOKEN_REGISTRY_SIZE_AFTER_MIGRATION = 7; const TOKEN_REGISTRY_SIZE_AFTER_MIGRATION = 7;
describe('TokenRegistryWrapper', () => { describe('TokenRegistryWrapper', () => {
let zeroEx: ZeroEx; let contractWrappers: ContractWrappers;
let tokens: Token[]; let tokens: Token[];
const tokenAddressBySymbol: { [symbol: string]: string } = {}; const tokenAddressBySymbol: { [symbol: string]: string } = {};
const tokenAddressByName: { [symbol: string]: string } = {}; const tokenAddressByName: { [symbol: string]: string } = {};
@ -31,8 +31,8 @@ describe('TokenRegistryWrapper', () => {
networkId: constants.TESTRPC_NETWORK_ID, networkId: constants.TESTRPC_NETWORK_ID,
}; };
before(async () => { before(async () => {
zeroEx = new ZeroEx(provider, config); contractWrappers = new ContractWrappers(provider, config);
tokens = await zeroEx.tokenRegistry.getTokensAsync(); tokens = await contractWrappers.tokenRegistry.getTokensAsync();
_.map(tokens, token => { _.map(tokens, token => {
tokenAddressBySymbol[token.symbol] = token.address; tokenAddressBySymbol[token.symbol] = token.address;
tokenAddressByName[token.name] = token.address; tokenAddressByName[token.name] = token.address;
@ -59,54 +59,60 @@ describe('TokenRegistryWrapper', () => {
}); });
describe('#getTokenAddressesAsync', () => { describe('#getTokenAddressesAsync', () => {
it('should return all the token addresses added to the tokenRegistry during the migration', async () => { it('should return all the token addresses added to the tokenRegistry during the migration', async () => {
const tokenAddresses = await zeroEx.tokenRegistry.getTokenAddressesAsync(); const tokenAddresses = await contractWrappers.tokenRegistry.getTokenAddressesAsync();
expect(tokenAddresses).to.have.lengthOf(TOKEN_REGISTRY_SIZE_AFTER_MIGRATION); expect(tokenAddresses).to.have.lengthOf(TOKEN_REGISTRY_SIZE_AFTER_MIGRATION);
const schemaValidator = new SchemaValidator(); const schemaValidator = new SchemaValidator();
_.each(tokenAddresses, tokenAddress => { _.each(tokenAddresses, tokenAddress => {
const validationResult = schemaValidator.validate(tokenAddress, schemas.addressSchema); const validationResult = schemaValidator.validate(tokenAddress, schemas.addressSchema);
expect(validationResult.errors).to.have.lengthOf(0); expect(validationResult.errors).to.have.lengthOf(0);
expect(tokenAddress).to.not.be.equal(ZeroEx.NULL_ADDRESS); expect(tokenAddress).to.not.be.equal(constants.NULL_ADDRESS);
}); });
}); });
}); });
describe('#getTokenAddressBySymbol', () => { describe('#getTokenAddressBySymbol', () => {
it('should return correct address for a token in the registry', async () => { it('should return correct address for a token in the registry', async () => {
const tokenAddress = await zeroEx.tokenRegistry.getTokenAddressBySymbolIfExistsAsync(registeredSymbol); const tokenAddress = await contractWrappers.tokenRegistry.getTokenAddressBySymbolIfExistsAsync(
registeredSymbol,
);
expect(tokenAddress).to.be.equal(tokenAddressBySymbol[registeredSymbol]); expect(tokenAddress).to.be.equal(tokenAddressBySymbol[registeredSymbol]);
}); });
it('should return undefined for a token out of registry', async () => { it('should return undefined for a token out of registry', async () => {
const tokenAddress = await zeroEx.tokenRegistry.getTokenAddressBySymbolIfExistsAsync(unregisteredSymbol); const tokenAddress = await contractWrappers.tokenRegistry.getTokenAddressBySymbolIfExistsAsync(
unregisteredSymbol,
);
expect(tokenAddress).to.be.undefined(); expect(tokenAddress).to.be.undefined();
}); });
}); });
describe('#getTokenAddressByName', () => { describe('#getTokenAddressByName', () => {
it('should return correct address for a token in the registry', async () => { it('should return correct address for a token in the registry', async () => {
const tokenAddress = await zeroEx.tokenRegistry.getTokenAddressByNameIfExistsAsync(registeredName); const tokenAddress = await contractWrappers.tokenRegistry.getTokenAddressByNameIfExistsAsync(registeredName);
expect(tokenAddress).to.be.equal(tokenAddressByName[registeredName]); expect(tokenAddress).to.be.equal(tokenAddressByName[registeredName]);
}); });
it('should return undefined for a token out of registry', async () => { it('should return undefined for a token out of registry', async () => {
const tokenAddress = await zeroEx.tokenRegistry.getTokenAddressByNameIfExistsAsync(unregisteredName); const tokenAddress = await contractWrappers.tokenRegistry.getTokenAddressByNameIfExistsAsync(
unregisteredName,
);
expect(tokenAddress).to.be.undefined(); expect(tokenAddress).to.be.undefined();
}); });
}); });
describe('#getTokenBySymbol', () => { describe('#getTokenBySymbol', () => {
it('should return correct token for a token in the registry', async () => { it('should return correct token for a token in the registry', async () => {
const token = await zeroEx.tokenRegistry.getTokenBySymbolIfExistsAsync(registeredSymbol); const token = await contractWrappers.tokenRegistry.getTokenBySymbolIfExistsAsync(registeredSymbol);
expect(token).to.be.deep.equal(tokenBySymbol[registeredSymbol]); expect(token).to.be.deep.equal(tokenBySymbol[registeredSymbol]);
}); });
it('should return undefined for a token out of registry', async () => { it('should return undefined for a token out of registry', async () => {
const token = await zeroEx.tokenRegistry.getTokenBySymbolIfExistsAsync(unregisteredSymbol); const token = await contractWrappers.tokenRegistry.getTokenBySymbolIfExistsAsync(unregisteredSymbol);
expect(token).to.be.undefined(); expect(token).to.be.undefined();
}); });
}); });
describe('#getTokenByName', () => { describe('#getTokenByName', () => {
it('should return correct token for a token in the registry', async () => { it('should return correct token for a token in the registry', async () => {
const token = await zeroEx.tokenRegistry.getTokenByNameIfExistsAsync(registeredName); const token = await contractWrappers.tokenRegistry.getTokenByNameIfExistsAsync(registeredName);
expect(token).to.be.deep.equal(tokenByName[registeredName]); expect(token).to.be.deep.equal(tokenByName[registeredName]);
}); });
it('should return undefined for a token out of registry', async () => { it('should return undefined for a token out of registry', async () => {
const token = await zeroEx.tokenRegistry.getTokenByNameIfExistsAsync(unregisteredName); const token = await contractWrappers.tokenRegistry.getTokenByNameIfExistsAsync(unregisteredName);
expect(token).to.be.undefined(); expect(token).to.be.undefined();
}); });
}); });
@ -114,14 +120,14 @@ describe('TokenRegistryWrapper', () => {
it('should return the token added to the tokenRegistry during the migration', async () => { it('should return the token added to the tokenRegistry during the migration', async () => {
const aToken = tokens[0]; const aToken = tokens[0];
const token = await zeroEx.tokenRegistry.getTokenIfExistsAsync(aToken.address); const token = await contractWrappers.tokenRegistry.getTokenIfExistsAsync(aToken.address);
const schemaValidator = new SchemaValidator(); const schemaValidator = new SchemaValidator();
const validationResult = schemaValidator.validate(token, schemas.tokenSchema); const validationResult = schemaValidator.validate(token, schemas.tokenSchema);
expect(validationResult.errors).to.have.lengthOf(0); expect(validationResult.errors).to.have.lengthOf(0);
}); });
it('should return return undefined when passed a token address not in the tokenRegistry', async () => { it('should return return undefined when passed a token address not in the tokenRegistry', async () => {
const unregisteredTokenAddress = '0x5409ed021d9299bf6814279a6a1411a7e866a631'; const unregisteredTokenAddress = '0x5409ed021d9299bf6814279a6a1411a7e866a631';
const tokenIfExists = await zeroEx.tokenRegistry.getTokenIfExistsAsync(unregisteredTokenAddress); const tokenIfExists = await contractWrappers.tokenRegistry.getTokenIfExistsAsync(unregisteredTokenAddress);
expect(tokenIfExists).to.be.undefined(); expect(tokenIfExists).to.be.undefined();
}); });
}); });

View File

@ -1,6 +1,6 @@
import * as chai from 'chai'; import * as chai from 'chai';
import { ZeroEx } from '../src'; import { ContractWrappers } from '../src';
import { chaiSetup } from './utils/chai_setup'; import { chaiSetup } from './utils/chai_setup';
import { constants } from './utils/constants'; import { constants } from './utils/constants';
@ -10,24 +10,24 @@ chaiSetup.configure();
const expect = chai.expect; const expect = chai.expect;
describe('TokenTransferProxyWrapper', () => { describe('TokenTransferProxyWrapper', () => {
let zeroEx: ZeroEx; let contractWrappers: ContractWrappers;
const config = { const config = {
networkId: constants.TESTRPC_NETWORK_ID, networkId: constants.TESTRPC_NETWORK_ID,
}; };
before(async () => { before(async () => {
zeroEx = new ZeroEx(provider, config); contractWrappers = new ContractWrappers(provider, config);
}); });
describe('#isAuthorizedAsync', () => { describe('#isAuthorizedAsync', () => {
it('should return false if the address is not authorized', async () => { it('should return false if the address is not authorized', async () => {
const isAuthorized = await zeroEx.proxy.isAuthorizedAsync(ZeroEx.NULL_ADDRESS); const isAuthorized = await contractWrappers.proxy.isAuthorizedAsync(constants.NULL_ADDRESS);
expect(isAuthorized).to.be.false(); expect(isAuthorized).to.be.false();
}); });
}); });
describe('#getAuthorizedAddressesAsync', () => { describe('#getAuthorizedAddressesAsync', () => {
it('should return the list of authorized addresses', async () => { it('should return the list of authorized addresses', async () => {
const authorizedAddresses = await zeroEx.proxy.getAuthorizedAddressesAsync(); const authorizedAddresses = await contractWrappers.proxy.getAuthorizedAddressesAsync();
for (const authorizedAddress of authorizedAddresses) { for (const authorizedAddress of authorizedAddresses) {
const isAuthorized = await zeroEx.proxy.isAuthorizedAsync(authorizedAddress); const isAuthorized = await contractWrappers.proxy.isAuthorizedAsync(authorizedAddress);
expect(isAuthorized).to.be.true(); expect(isAuthorized).to.be.true();
} }
}); });

View File

@ -1,6 +1,6 @@
import { BlockchainLifecycle, devConstants } from '@0xproject/dev-utils'; import { BlockchainLifecycle, callbackErrorReporter, devConstants } from '@0xproject/dev-utils';
import { EmptyWalletSubprovider } from '@0xproject/subproviders'; import { EmptyWalletSubprovider } from '@0xproject/subproviders';
import { Provider } from '@0xproject/types'; import { DoneCallback, Provider } from '@0xproject/types';
import { BigNumber } from '@0xproject/utils'; import { BigNumber } from '@0xproject/utils';
import * as chai from 'chai'; import * as chai from 'chai';
import 'mocha'; import 'mocha';
@ -10,18 +10,16 @@ import {
ApprovalContractEventArgs, ApprovalContractEventArgs,
BlockParamLiteral, BlockParamLiteral,
BlockRange, BlockRange,
ContractWrappers,
ContractWrappersError,
DecodedLogEvent, DecodedLogEvent,
Token, Token,
TokenEvents, TokenEvents,
TransferContractEventArgs, TransferContractEventArgs,
ZeroEx,
ZeroExError,
} from '../src'; } from '../src';
import { DoneCallback } from '../src/types';
import { chaiSetup } from './utils/chai_setup'; import { chaiSetup } from './utils/chai_setup';
import { constants } from './utils/constants'; import { constants } from './utils/constants';
import { reportNodeCallbackErrors } from './utils/report_callback_errors';
import { TokenUtils } from './utils/token_utils'; import { TokenUtils } from './utils/token_utils';
import { provider, web3Wrapper } from './utils/web3_wrapper'; import { provider, web3Wrapper } from './utils/web3_wrapper';
@ -30,7 +28,7 @@ const expect = chai.expect;
const blockchainLifecycle = new BlockchainLifecycle(web3Wrapper); const blockchainLifecycle = new BlockchainLifecycle(web3Wrapper);
describe('TokenWrapper', () => { describe('TokenWrapper', () => {
let zeroEx: ZeroEx; let contractWrappers: ContractWrappers;
let userAddresses: string[]; let userAddresses: string[];
let tokens: Token[]; let tokens: Token[];
let tokenUtils: TokenUtils; let tokenUtils: TokenUtils;
@ -40,9 +38,9 @@ describe('TokenWrapper', () => {
networkId: constants.TESTRPC_NETWORK_ID, networkId: constants.TESTRPC_NETWORK_ID,
}; };
before(async () => { before(async () => {
zeroEx = new ZeroEx(provider, config); contractWrappers = new ContractWrappers(provider, config);
userAddresses = await zeroEx.getAvailableAddressesAsync(); userAddresses = await web3Wrapper.getAvailableAddressesAsync();
tokens = await zeroEx.tokenRegistry.getTokensAsync(); tokens = await contractWrappers.tokenRegistry.getTokensAsync();
tokenUtils = new TokenUtils(tokens); tokenUtils = new TokenUtils(tokens);
coinbase = userAddresses[0]; coinbase = userAddresses[0];
addressWithoutFunds = userAddresses[1]; addressWithoutFunds = userAddresses[1];
@ -63,26 +61,26 @@ describe('TokenWrapper', () => {
it('should successfully transfer tokens', async () => { it('should successfully transfer tokens', async () => {
const fromAddress = coinbase; const fromAddress = coinbase;
const toAddress = addressWithoutFunds; const toAddress = addressWithoutFunds;
const preBalance = await zeroEx.token.getBalanceAsync(token.address, toAddress); const preBalance = await contractWrappers.token.getBalanceAsync(token.address, toAddress);
expect(preBalance).to.be.bignumber.equal(0); expect(preBalance).to.be.bignumber.equal(0);
await zeroEx.token.transferAsync(token.address, fromAddress, toAddress, transferAmount); await contractWrappers.token.transferAsync(token.address, fromAddress, toAddress, transferAmount);
const postBalance = await zeroEx.token.getBalanceAsync(token.address, toAddress); const postBalance = await contractWrappers.token.getBalanceAsync(token.address, toAddress);
return expect(postBalance).to.be.bignumber.equal(transferAmount); return expect(postBalance).to.be.bignumber.equal(transferAmount);
}); });
it('should fail to transfer tokens if fromAddress has an insufficient balance', async () => { it('should fail to transfer tokens if fromAddress has an insufficient balance', async () => {
const fromAddress = addressWithoutFunds; const fromAddress = addressWithoutFunds;
const toAddress = coinbase; const toAddress = coinbase;
return expect( return expect(
zeroEx.token.transferAsync(token.address, fromAddress, toAddress, transferAmount), contractWrappers.token.transferAsync(token.address, fromAddress, toAddress, transferAmount),
).to.be.rejectedWith(ZeroExError.InsufficientBalanceForTransfer); ).to.be.rejectedWith(ContractWrappersError.InsufficientBalanceForTransfer);
}); });
it('should throw a CONTRACT_DOES_NOT_EXIST error for a non-existent token contract', async () => { it('should throw a CONTRACT_DOES_NOT_EXIST error for a non-existent token contract', async () => {
const nonExistentTokenAddress = '0x9dd402f14d67e001d8efbe6583e51bf9706aa065'; const nonExistentTokenAddress = '0x9dd402f14d67e001d8efbe6583e51bf9706aa065';
const fromAddress = coinbase; const fromAddress = coinbase;
const toAddress = coinbase; const toAddress = coinbase;
return expect( return expect(
zeroEx.token.transferAsync(nonExistentTokenAddress, fromAddress, toAddress, transferAmount), contractWrappers.token.transferAsync(nonExistentTokenAddress, fromAddress, toAddress, transferAmount),
).to.be.rejectedWith(ZeroExError.TokenContractDoesNotExist); ).to.be.rejectedWith(ContractWrappersError.TokenContractDoesNotExist);
}); });
}); });
describe('#transferFromAsync', () => { describe('#transferFromAsync', () => {
@ -98,35 +96,51 @@ describe('TokenWrapper', () => {
const fromAddress = coinbase; const fromAddress = coinbase;
const transferAmount = new BigNumber(42); const transferAmount = new BigNumber(42);
const fromAddressBalance = await zeroEx.token.getBalanceAsync(token.address, fromAddress); const fromAddressBalance = await contractWrappers.token.getBalanceAsync(token.address, fromAddress);
expect(fromAddressBalance).to.be.bignumber.greaterThan(transferAmount); expect(fromAddressBalance).to.be.bignumber.greaterThan(transferAmount);
const fromAddressAllowance = await zeroEx.token.getAllowanceAsync(token.address, fromAddress, toAddress); const fromAddressAllowance = await contractWrappers.token.getAllowanceAsync(
token.address,
fromAddress,
toAddress,
);
expect(fromAddressAllowance).to.be.bignumber.equal(0); expect(fromAddressAllowance).to.be.bignumber.equal(0);
return expect( return expect(
zeroEx.token.transferFromAsync(token.address, fromAddress, toAddress, senderAddress, transferAmount), contractWrappers.token.transferFromAsync(
).to.be.rejectedWith(ZeroExError.InsufficientAllowanceForTransfer); token.address,
fromAddress,
toAddress,
senderAddress,
transferAmount,
),
).to.be.rejectedWith(ContractWrappersError.InsufficientAllowanceForTransfer);
}); });
it('[regression] should fail to transfer tokens if set allowance for toAddress instead of senderAddress', async () => { it('[regression] should fail to transfer tokens if set allowance for toAddress instead of senderAddress', async () => {
const fromAddress = coinbase; const fromAddress = coinbase;
const transferAmount = new BigNumber(42); const transferAmount = new BigNumber(42);
await zeroEx.token.setAllowanceAsync(token.address, fromAddress, toAddress, transferAmount); await contractWrappers.token.setAllowanceAsync(token.address, fromAddress, toAddress, transferAmount);
return expect( return expect(
zeroEx.token.transferFromAsync(token.address, fromAddress, toAddress, senderAddress, transferAmount), contractWrappers.token.transferFromAsync(
).to.be.rejectedWith(ZeroExError.InsufficientAllowanceForTransfer); token.address,
fromAddress,
toAddress,
senderAddress,
transferAmount,
),
).to.be.rejectedWith(ContractWrappersError.InsufficientAllowanceForTransfer);
}); });
it('should fail to transfer tokens if fromAddress has insufficient balance', async () => { it('should fail to transfer tokens if fromAddress has insufficient balance', async () => {
const fromAddress = addressWithoutFunds; const fromAddress = addressWithoutFunds;
const transferAmount = new BigNumber(42); const transferAmount = new BigNumber(42);
const fromAddressBalance = await zeroEx.token.getBalanceAsync(token.address, fromAddress); const fromAddressBalance = await contractWrappers.token.getBalanceAsync(token.address, fromAddress);
expect(fromAddressBalance).to.be.bignumber.equal(0); expect(fromAddressBalance).to.be.bignumber.equal(0);
await zeroEx.token.setAllowanceAsync(token.address, fromAddress, senderAddress, transferAmount); await contractWrappers.token.setAllowanceAsync(token.address, fromAddress, senderAddress, transferAmount);
const fromAddressAllowance = await zeroEx.token.getAllowanceAsync( const fromAddressAllowance = await contractWrappers.token.getAllowanceAsync(
token.address, token.address,
fromAddress, fromAddress,
senderAddress, senderAddress,
@ -134,34 +148,46 @@ describe('TokenWrapper', () => {
expect(fromAddressAllowance).to.be.bignumber.equal(transferAmount); expect(fromAddressAllowance).to.be.bignumber.equal(transferAmount);
return expect( return expect(
zeroEx.token.transferFromAsync(token.address, fromAddress, toAddress, senderAddress, transferAmount), contractWrappers.token.transferFromAsync(
).to.be.rejectedWith(ZeroExError.InsufficientBalanceForTransfer); token.address,
fromAddress,
toAddress,
senderAddress,
transferAmount,
),
).to.be.rejectedWith(ContractWrappersError.InsufficientBalanceForTransfer);
}); });
it('should successfully transfer tokens', async () => { it('should successfully transfer tokens', async () => {
const fromAddress = coinbase; const fromAddress = coinbase;
const preBalance = await zeroEx.token.getBalanceAsync(token.address, toAddress); const preBalance = await contractWrappers.token.getBalanceAsync(token.address, toAddress);
expect(preBalance).to.be.bignumber.equal(0); expect(preBalance).to.be.bignumber.equal(0);
const transferAmount = new BigNumber(42); const transferAmount = new BigNumber(42);
await zeroEx.token.setAllowanceAsync(token.address, fromAddress, senderAddress, transferAmount); await contractWrappers.token.setAllowanceAsync(token.address, fromAddress, senderAddress, transferAmount);
await zeroEx.token.transferFromAsync(token.address, fromAddress, toAddress, senderAddress, transferAmount); await contractWrappers.token.transferFromAsync(
const postBalance = await zeroEx.token.getBalanceAsync(token.address, toAddress); token.address,
fromAddress,
toAddress,
senderAddress,
transferAmount,
);
const postBalance = await contractWrappers.token.getBalanceAsync(token.address, toAddress);
return expect(postBalance).to.be.bignumber.equal(transferAmount); return expect(postBalance).to.be.bignumber.equal(transferAmount);
}); });
it('should throw a CONTRACT_DOES_NOT_EXIST error for a non-existent token contract', async () => { it('should throw a CONTRACT_DOES_NOT_EXIST error for a non-existent token contract', async () => {
const fromAddress = coinbase; const fromAddress = coinbase;
const nonExistentTokenAddress = '0x9dd402f14d67e001d8efbe6583e51bf9706aa065'; const nonExistentTokenAddress = '0x9dd402f14d67e001d8efbe6583e51bf9706aa065';
return expect( return expect(
zeroEx.token.transferFromAsync( contractWrappers.token.transferFromAsync(
nonExistentTokenAddress, nonExistentTokenAddress,
fromAddress, fromAddress,
toAddress, toAddress,
senderAddress, senderAddress,
new BigNumber(42), new BigNumber(42),
), ),
).to.be.rejectedWith(ZeroExError.TokenContractDoesNotExist); ).to.be.rejectedWith(ContractWrappersError.TokenContractDoesNotExist);
}); });
}); });
describe('#getBalanceAsync', () => { describe('#getBalanceAsync', () => {
@ -169,36 +195,36 @@ describe('TokenWrapper', () => {
it('should return the balance for an existing ERC20 token', async () => { it('should return the balance for an existing ERC20 token', async () => {
const token = tokens[0]; const token = tokens[0];
const ownerAddress = coinbase; const ownerAddress = coinbase;
const balance = await zeroEx.token.getBalanceAsync(token.address, ownerAddress); const balance = await contractWrappers.token.getBalanceAsync(token.address, ownerAddress);
const expectedBalance = new BigNumber('1000000000000000000000000000'); const expectedBalance = new BigNumber('1000000000000000000000000000');
return expect(balance).to.be.bignumber.equal(expectedBalance); return expect(balance).to.be.bignumber.equal(expectedBalance);
}); });
it('should throw a CONTRACT_DOES_NOT_EXIST error for a non-existent token contract', async () => { it('should throw a CONTRACT_DOES_NOT_EXIST error for a non-existent token contract', async () => {
const nonExistentTokenAddress = '0x9dd402f14d67e001d8efbe6583e51bf9706aa065'; const nonExistentTokenAddress = '0x9dd402f14d67e001d8efbe6583e51bf9706aa065';
const ownerAddress = coinbase; const ownerAddress = coinbase;
return expect(zeroEx.token.getBalanceAsync(nonExistentTokenAddress, ownerAddress)).to.be.rejectedWith( return expect(
ZeroExError.TokenContractDoesNotExist, contractWrappers.token.getBalanceAsync(nonExistentTokenAddress, ownerAddress),
); ).to.be.rejectedWith(ContractWrappersError.TokenContractDoesNotExist);
}); });
it('should return a balance of 0 for a non-existent owner address', async () => { it('should return a balance of 0 for a non-existent owner address', async () => {
const token = tokens[0]; const token = tokens[0];
const nonExistentOwner = '0x198c6ad858f213fb31b6fe809e25040e6b964593'; const nonExistentOwner = '0x198c6ad858f213fb31b6fe809e25040e6b964593';
const balance = await zeroEx.token.getBalanceAsync(token.address, nonExistentOwner); const balance = await contractWrappers.token.getBalanceAsync(token.address, nonExistentOwner);
const expectedBalance = new BigNumber(0); const expectedBalance = new BigNumber(0);
return expect(balance).to.be.bignumber.equal(expectedBalance); return expect(balance).to.be.bignumber.equal(expectedBalance);
}); });
}); });
describe('With provider without accounts', () => { describe('With provider without accounts', () => {
let zeroExWithoutAccounts: ZeroEx; let zeroExContractWithoutAccounts: ContractWrappers;
before(async () => { before(async () => {
const hasAddresses = false; const hasAddresses = false;
const emptyWalletProvider = addEmptyWalletSubprovider(provider); const emptyWalletProvider = addEmptyWalletSubprovider(provider);
zeroExWithoutAccounts = new ZeroEx(emptyWalletProvider, config); zeroExContractWithoutAccounts = new ContractWrappers(emptyWalletProvider, config);
}); });
it('should return balance even when called with provider instance without addresses', async () => { it('should return balance even when called with provider instance without addresses', async () => {
const token = tokens[0]; const token = tokens[0];
const ownerAddress = coinbase; const ownerAddress = coinbase;
const balance = await zeroExWithoutAccounts.token.getBalanceAsync(token.address, ownerAddress); const balance = await zeroExContractWithoutAccounts.token.getBalanceAsync(token.address, ownerAddress);
const expectedBalance = new BigNumber('1000000000000000000000000000'); const expectedBalance = new BigNumber('1000000000000000000000000000');
return expect(balance).to.be.bignumber.equal(expectedBalance); return expect(balance).to.be.bignumber.equal(expectedBalance);
}); });
@ -210,7 +236,7 @@ describe('TokenWrapper', () => {
const ownerAddress = coinbase; const ownerAddress = coinbase;
const spenderAddress = addressWithoutFunds; const spenderAddress = addressWithoutFunds;
const allowanceBeforeSet = await zeroEx.token.getAllowanceAsync( const allowanceBeforeSet = await contractWrappers.token.getAllowanceAsync(
token.address, token.address,
ownerAddress, ownerAddress,
spenderAddress, spenderAddress,
@ -219,9 +245,18 @@ describe('TokenWrapper', () => {
expect(allowanceBeforeSet).to.be.bignumber.equal(expectedAllowanceBeforeAllowanceSet); expect(allowanceBeforeSet).to.be.bignumber.equal(expectedAllowanceBeforeAllowanceSet);
const amountInBaseUnits = new BigNumber(50); const amountInBaseUnits = new BigNumber(50);
await zeroEx.token.setAllowanceAsync(token.address, ownerAddress, spenderAddress, amountInBaseUnits); await contractWrappers.token.setAllowanceAsync(
token.address,
ownerAddress,
spenderAddress,
amountInBaseUnits,
);
const allowanceAfterSet = await zeroEx.token.getAllowanceAsync(token.address, ownerAddress, spenderAddress); const allowanceAfterSet = await contractWrappers.token.getAllowanceAsync(
token.address,
ownerAddress,
spenderAddress,
);
const expectedAllowanceAfterAllowanceSet = amountInBaseUnits; const expectedAllowanceAfterAllowanceSet = amountInBaseUnits;
return expect(allowanceAfterSet).to.be.bignumber.equal(expectedAllowanceAfterAllowanceSet); return expect(allowanceAfterSet).to.be.bignumber.equal(expectedAllowanceAfterAllowanceSet);
}); });
@ -232,30 +267,39 @@ describe('TokenWrapper', () => {
const ownerAddress = coinbase; const ownerAddress = coinbase;
const spenderAddress = addressWithoutFunds; const spenderAddress = addressWithoutFunds;
await zeroEx.token.setUnlimitedAllowanceAsync(token.address, ownerAddress, spenderAddress); await contractWrappers.token.setUnlimitedAllowanceAsync(token.address, ownerAddress, spenderAddress);
const allowance = await zeroEx.token.getAllowanceAsync(token.address, ownerAddress, spenderAddress); const allowance = await contractWrappers.token.getAllowanceAsync(
return expect(allowance).to.be.bignumber.equal(zeroEx.token.UNLIMITED_ALLOWANCE_IN_BASE_UNITS); token.address,
ownerAddress,
spenderAddress,
);
return expect(allowance).to.be.bignumber.equal(contractWrappers.token.UNLIMITED_ALLOWANCE_IN_BASE_UNITS);
}); });
it('should reduce the gas cost for transfers including tokens with unlimited allowance support', async () => { it('should reduce the gas cost for transfers including tokens with unlimited allowance support', async () => {
const transferAmount = new BigNumber(5); const transferAmount = new BigNumber(5);
const zrx = tokenUtils.getProtocolTokenOrThrow(); const zrx = tokenUtils.getProtocolTokenOrThrow();
const [, userWithNormalAllowance, userWithUnlimitedAllowance] = userAddresses; const [, userWithNormalAllowance, userWithUnlimitedAllowance] = userAddresses;
await zeroEx.token.setAllowanceAsync(zrx.address, coinbase, userWithNormalAllowance, transferAmount); await contractWrappers.token.setAllowanceAsync(
await zeroEx.token.setUnlimitedAllowanceAsync(zrx.address, coinbase, userWithUnlimitedAllowance); zrx.address,
coinbase,
userWithNormalAllowance,
transferAmount,
);
await contractWrappers.token.setUnlimitedAllowanceAsync(zrx.address, coinbase, userWithUnlimitedAllowance);
const initBalanceWithNormalAllowance = await web3Wrapper.getBalanceInWeiAsync(userWithNormalAllowance); const initBalanceWithNormalAllowance = await web3Wrapper.getBalanceInWeiAsync(userWithNormalAllowance);
const initBalanceWithUnlimitedAllowance = await web3Wrapper.getBalanceInWeiAsync( const initBalanceWithUnlimitedAllowance = await web3Wrapper.getBalanceInWeiAsync(
userWithUnlimitedAllowance, userWithUnlimitedAllowance,
); );
await zeroEx.token.transferFromAsync( await contractWrappers.token.transferFromAsync(
zrx.address, zrx.address,
coinbase, coinbase,
userWithNormalAllowance, userWithNormalAllowance,
userWithNormalAllowance, userWithNormalAllowance,
transferAmount, transferAmount,
); );
await zeroEx.token.transferFromAsync( await contractWrappers.token.transferFromAsync(
zrx.address, zrx.address,
coinbase, coinbase,
userWithUnlimitedAllowance, userWithUnlimitedAllowance,
@ -285,9 +329,18 @@ describe('TokenWrapper', () => {
const spenderAddress = addressWithoutFunds; const spenderAddress = addressWithoutFunds;
const amountInBaseUnits = new BigNumber(50); const amountInBaseUnits = new BigNumber(50);
await zeroEx.token.setAllowanceAsync(token.address, ownerAddress, spenderAddress, amountInBaseUnits); await contractWrappers.token.setAllowanceAsync(
token.address,
ownerAddress,
spenderAddress,
amountInBaseUnits,
);
const allowance = await zeroEx.token.getAllowanceAsync(token.address, ownerAddress, spenderAddress); const allowance = await contractWrappers.token.getAllowanceAsync(
token.address,
ownerAddress,
spenderAddress,
);
const expectedAllowance = amountInBaseUnits; const expectedAllowance = amountInBaseUnits;
return expect(allowance).to.be.bignumber.equal(expectedAllowance); return expect(allowance).to.be.bignumber.equal(expectedAllowance);
}); });
@ -295,17 +348,21 @@ describe('TokenWrapper', () => {
const token = tokens[0]; const token = tokens[0];
const ownerAddress = coinbase; const ownerAddress = coinbase;
const spenderAddress = addressWithoutFunds; const spenderAddress = addressWithoutFunds;
const allowance = await zeroEx.token.getAllowanceAsync(token.address, ownerAddress, spenderAddress); const allowance = await contractWrappers.token.getAllowanceAsync(
token.address,
ownerAddress,
spenderAddress,
);
const expectedAllowance = new BigNumber(0); const expectedAllowance = new BigNumber(0);
return expect(allowance).to.be.bignumber.equal(expectedAllowance); return expect(allowance).to.be.bignumber.equal(expectedAllowance);
}); });
}); });
describe('With provider without accounts', () => { describe('With provider without accounts', () => {
let zeroExWithoutAccounts: ZeroEx; let zeroExContractWithoutAccounts: ContractWrappers;
before(async () => { before(async () => {
const hasAddresses = false; const hasAddresses = false;
const emptyWalletProvider = addEmptyWalletSubprovider(provider); const emptyWalletProvider = addEmptyWalletSubprovider(provider);
zeroExWithoutAccounts = new ZeroEx(emptyWalletProvider, config); zeroExContractWithoutAccounts = new ContractWrappers(emptyWalletProvider, config);
}); });
it('should get the proxy allowance', async () => { it('should get the proxy allowance', async () => {
const token = tokens[0]; const token = tokens[0];
@ -313,9 +370,14 @@ describe('TokenWrapper', () => {
const spenderAddress = addressWithoutFunds; const spenderAddress = addressWithoutFunds;
const amountInBaseUnits = new BigNumber(50); const amountInBaseUnits = new BigNumber(50);
await zeroEx.token.setAllowanceAsync(token.address, ownerAddress, spenderAddress, amountInBaseUnits); await contractWrappers.token.setAllowanceAsync(
token.address,
ownerAddress,
spenderAddress,
amountInBaseUnits,
);
const allowance = await zeroExWithoutAccounts.token.getAllowanceAsync( const allowance = await zeroExContractWithoutAccounts.token.getAllowanceAsync(
token.address, token.address,
ownerAddress, ownerAddress,
spenderAddress, spenderAddress,
@ -331,9 +393,9 @@ describe('TokenWrapper', () => {
const ownerAddress = coinbase; const ownerAddress = coinbase;
const amountInBaseUnits = new BigNumber(50); const amountInBaseUnits = new BigNumber(50);
await zeroEx.token.setProxyAllowanceAsync(token.address, ownerAddress, amountInBaseUnits); await contractWrappers.token.setProxyAllowanceAsync(token.address, ownerAddress, amountInBaseUnits);
const allowance = await zeroEx.token.getProxyAllowanceAsync(token.address, ownerAddress); const allowance = await contractWrappers.token.getProxyAllowanceAsync(token.address, ownerAddress);
const expectedAllowance = amountInBaseUnits; const expectedAllowance = amountInBaseUnits;
return expect(allowance).to.be.bignumber.equal(expectedAllowance); return expect(allowance).to.be.bignumber.equal(expectedAllowance);
}); });
@ -343,14 +405,14 @@ describe('TokenWrapper', () => {
const token = tokens[0]; const token = tokens[0];
const ownerAddress = coinbase; const ownerAddress = coinbase;
const allowanceBeforeSet = await zeroEx.token.getProxyAllowanceAsync(token.address, ownerAddress); const allowanceBeforeSet = await contractWrappers.token.getProxyAllowanceAsync(token.address, ownerAddress);
const expectedAllowanceBeforeAllowanceSet = new BigNumber(0); const expectedAllowanceBeforeAllowanceSet = new BigNumber(0);
expect(allowanceBeforeSet).to.be.bignumber.equal(expectedAllowanceBeforeAllowanceSet); expect(allowanceBeforeSet).to.be.bignumber.equal(expectedAllowanceBeforeAllowanceSet);
const amountInBaseUnits = new BigNumber(50); const amountInBaseUnits = new BigNumber(50);
await zeroEx.token.setProxyAllowanceAsync(token.address, ownerAddress, amountInBaseUnits); await contractWrappers.token.setProxyAllowanceAsync(token.address, ownerAddress, amountInBaseUnits);
const allowanceAfterSet = await zeroEx.token.getProxyAllowanceAsync(token.address, ownerAddress); const allowanceAfterSet = await contractWrappers.token.getProxyAllowanceAsync(token.address, ownerAddress);
const expectedAllowanceAfterAllowanceSet = amountInBaseUnits; const expectedAllowanceAfterAllowanceSet = amountInBaseUnits;
return expect(allowanceAfterSet).to.be.bignumber.equal(expectedAllowanceAfterAllowanceSet); return expect(allowanceAfterSet).to.be.bignumber.equal(expectedAllowanceAfterAllowanceSet);
}); });
@ -360,9 +422,9 @@ describe('TokenWrapper', () => {
const token = tokens[0]; const token = tokens[0];
const ownerAddress = coinbase; const ownerAddress = coinbase;
await zeroEx.token.setUnlimitedProxyAllowanceAsync(token.address, ownerAddress); await contractWrappers.token.setUnlimitedProxyAllowanceAsync(token.address, ownerAddress);
const allowance = await zeroEx.token.getProxyAllowanceAsync(token.address, ownerAddress); const allowance = await contractWrappers.token.getProxyAllowanceAsync(token.address, ownerAddress);
return expect(allowance).to.be.bignumber.equal(zeroEx.token.UNLIMITED_ALLOWANCE_IN_BASE_UNITS); return expect(allowance).to.be.bignumber.equal(contractWrappers.token.UNLIMITED_ALLOWANCE_IN_BASE_UNITS);
}); });
}); });
describe('#subscribe', () => { describe('#subscribe', () => {
@ -375,7 +437,7 @@ describe('TokenWrapper', () => {
tokenAddress = token.address; tokenAddress = token.address;
}); });
afterEach(() => { afterEach(() => {
zeroEx.token.unsubscribeAll(); contractWrappers.token.unsubscribeAll();
}); });
// Hack: Mocha does not allow a test to be both async and have a `done` callback // Hack: Mocha does not allow a test to be both async and have a `done` callback
// Since we need to await the receipt of the event in the `subscribe` callback, // Since we need to await the receipt of the event in the `subscribe` callback,
@ -384,7 +446,7 @@ describe('TokenWrapper', () => {
// Source: https://github.com/mochajs/mocha/issues/2407 // Source: https://github.com/mochajs/mocha/issues/2407
it('Should receive the Transfer event when tokens are transfered', (done: DoneCallback) => { it('Should receive the Transfer event when tokens are transfered', (done: DoneCallback) => {
(async () => { (async () => {
const callback = reportNodeCallbackErrors(done)( const callback = callbackErrorReporter.reportNodeCallbackErrors(done)(
(logEvent: DecodedLogEvent<TransferContractEventArgs>) => { (logEvent: DecodedLogEvent<TransferContractEventArgs>) => {
expect(logEvent.isRemoved).to.be.false(); expect(logEvent.isRemoved).to.be.false();
expect(logEvent.log.logIndex).to.be.equal(0); expect(logEvent.log.logIndex).to.be.equal(0);
@ -396,13 +458,13 @@ describe('TokenWrapper', () => {
expect(args._value).to.be.bignumber.equal(transferAmount); expect(args._value).to.be.bignumber.equal(transferAmount);
}, },
); );
zeroEx.token.subscribe(tokenAddress, TokenEvents.Transfer, indexFilterValues, callback); contractWrappers.token.subscribe(tokenAddress, TokenEvents.Transfer, indexFilterValues, callback);
await zeroEx.token.transferAsync(tokenAddress, coinbase, addressWithoutFunds, transferAmount); await contractWrappers.token.transferAsync(tokenAddress, coinbase, addressWithoutFunds, transferAmount);
})().catch(done); })().catch(done);
}); });
it('Should receive the Approval event when allowance is being set', (done: DoneCallback) => { it('Should receive the Approval event when allowance is being set', (done: DoneCallback) => {
(async () => { (async () => {
const callback = reportNodeCallbackErrors(done)( const callback = callbackErrorReporter.reportNodeCallbackErrors(done)(
(logEvent: DecodedLogEvent<ApprovalContractEventArgs>) => { (logEvent: DecodedLogEvent<ApprovalContractEventArgs>) => {
expect(logEvent).to.not.be.undefined(); expect(logEvent).to.not.be.undefined();
expect(logEvent.isRemoved).to.be.false(); expect(logEvent.isRemoved).to.be.false();
@ -412,39 +474,54 @@ describe('TokenWrapper', () => {
expect(args._value).to.be.bignumber.equal(allowanceAmount); expect(args._value).to.be.bignumber.equal(allowanceAmount);
}, },
); );
zeroEx.token.subscribe(tokenAddress, TokenEvents.Approval, indexFilterValues, callback); contractWrappers.token.subscribe(tokenAddress, TokenEvents.Approval, indexFilterValues, callback);
await zeroEx.token.setAllowanceAsync(tokenAddress, coinbase, addressWithoutFunds, allowanceAmount); await contractWrappers.token.setAllowanceAsync(
tokenAddress,
coinbase,
addressWithoutFunds,
allowanceAmount,
);
})().catch(done); })().catch(done);
}); });
it('Outstanding subscriptions are cancelled when zeroEx.setProvider called', (done: DoneCallback) => { it('Outstanding subscriptions are cancelled when contractWrappers.setProvider called', (done: DoneCallback) => {
(async () => { (async () => {
const callbackNeverToBeCalled = reportNodeCallbackErrors(done)( const callbackNeverToBeCalled = callbackErrorReporter.reportNodeCallbackErrors(done)(
(logEvent: DecodedLogEvent<ApprovalContractEventArgs>) => { (logEvent: DecodedLogEvent<ApprovalContractEventArgs>) => {
done(new Error('Expected this subscription to have been cancelled')); done(new Error('Expected this subscription to have been cancelled'));
}, },
); );
zeroEx.token.subscribe(tokenAddress, TokenEvents.Transfer, indexFilterValues, callbackNeverToBeCalled); contractWrappers.token.subscribe(
const callbackToBeCalled = reportNodeCallbackErrors(done)();
zeroEx.setProvider(provider, constants.TESTRPC_NETWORK_ID);
zeroEx.token.subscribe(tokenAddress, TokenEvents.Transfer, indexFilterValues, callbackToBeCalled);
await zeroEx.token.transferAsync(tokenAddress, coinbase, addressWithoutFunds, transferAmount);
})().catch(done);
});
it('Should cancel subscription when unsubscribe called', (done: DoneCallback) => {
(async () => {
const callbackNeverToBeCalled = reportNodeCallbackErrors(done)(
(logEvent: DecodedLogEvent<ApprovalContractEventArgs>) => {
done(new Error('Expected this subscription to have been cancelled'));
},
);
const subscriptionToken = zeroEx.token.subscribe(
tokenAddress, tokenAddress,
TokenEvents.Transfer, TokenEvents.Transfer,
indexFilterValues, indexFilterValues,
callbackNeverToBeCalled, callbackNeverToBeCalled,
); );
zeroEx.token.unsubscribe(subscriptionToken); const callbackToBeCalled = callbackErrorReporter.reportNodeCallbackErrors(done)();
await zeroEx.token.transferAsync(tokenAddress, coinbase, addressWithoutFunds, transferAmount); contractWrappers.setProvider(provider, constants.TESTRPC_NETWORK_ID);
contractWrappers.token.subscribe(
tokenAddress,
TokenEvents.Transfer,
indexFilterValues,
callbackToBeCalled,
);
await contractWrappers.token.transferAsync(tokenAddress, coinbase, addressWithoutFunds, transferAmount);
})().catch(done);
});
it('Should cancel subscription when unsubscribe called', (done: DoneCallback) => {
(async () => {
const callbackNeverToBeCalled = callbackErrorReporter.reportNodeCallbackErrors(done)(
(logEvent: DecodedLogEvent<ApprovalContractEventArgs>) => {
done(new Error('Expected this subscription to have been cancelled'));
},
);
const subscriptionToken = contractWrappers.token.subscribe(
tokenAddress,
TokenEvents.Transfer,
indexFilterValues,
callbackNeverToBeCalled,
);
contractWrappers.token.unsubscribe(subscriptionToken);
await contractWrappers.token.transferAsync(tokenAddress, coinbase, addressWithoutFunds, transferAmount);
done(); done();
})().catch(done); })().catch(done);
}); });
@ -460,14 +537,14 @@ describe('TokenWrapper', () => {
before(() => { before(() => {
const token = tokens[0]; const token = tokens[0];
tokenAddress = token.address; tokenAddress = token.address;
tokenTransferProxyAddress = zeroEx.proxy.getContractAddress(); tokenTransferProxyAddress = contractWrappers.proxy.getContractAddress();
}); });
it('should get logs with decoded args emitted by Approval', async () => { it('should get logs with decoded args emitted by Approval', async () => {
txHash = await zeroEx.token.setUnlimitedProxyAllowanceAsync(tokenAddress, coinbase); txHash = await contractWrappers.token.setUnlimitedProxyAllowanceAsync(tokenAddress, coinbase);
await zeroEx.awaitTransactionMinedAsync(txHash); await web3Wrapper.awaitTransactionMinedAsync(txHash);
const eventName = TokenEvents.Approval; const eventName = TokenEvents.Approval;
const indexFilterValues = {}; const indexFilterValues = {};
const logs = await zeroEx.token.getLogsAsync<ApprovalContractEventArgs>( const logs = await contractWrappers.token.getLogsAsync<ApprovalContractEventArgs>(
tokenAddress, tokenAddress,
eventName, eventName,
blockRange, blockRange,
@ -478,14 +555,14 @@ describe('TokenWrapper', () => {
expect(logs[0].event).to.be.equal(eventName); expect(logs[0].event).to.be.equal(eventName);
expect(args._owner).to.be.equal(coinbase); expect(args._owner).to.be.equal(coinbase);
expect(args._spender).to.be.equal(tokenTransferProxyAddress); expect(args._spender).to.be.equal(tokenTransferProxyAddress);
expect(args._value).to.be.bignumber.equal(zeroEx.token.UNLIMITED_ALLOWANCE_IN_BASE_UNITS); expect(args._value).to.be.bignumber.equal(contractWrappers.token.UNLIMITED_ALLOWANCE_IN_BASE_UNITS);
}); });
it('should only get the logs with the correct event name', async () => { it('should only get the logs with the correct event name', async () => {
txHash = await zeroEx.token.setUnlimitedProxyAllowanceAsync(tokenAddress, coinbase); txHash = await contractWrappers.token.setUnlimitedProxyAllowanceAsync(tokenAddress, coinbase);
await zeroEx.awaitTransactionMinedAsync(txHash); await web3Wrapper.awaitTransactionMinedAsync(txHash);
const differentEventName = TokenEvents.Transfer; const differentEventName = TokenEvents.Transfer;
const indexFilterValues = {}; const indexFilterValues = {};
const logs = await zeroEx.token.getLogsAsync( const logs = await contractWrappers.token.getLogsAsync(
tokenAddress, tokenAddress,
differentEventName, differentEventName,
blockRange, blockRange,
@ -494,15 +571,15 @@ describe('TokenWrapper', () => {
expect(logs).to.have.length(0); expect(logs).to.have.length(0);
}); });
it('should only get the logs with the correct indexed fields', async () => { it('should only get the logs with the correct indexed fields', async () => {
txHash = await zeroEx.token.setUnlimitedProxyAllowanceAsync(tokenAddress, coinbase); txHash = await contractWrappers.token.setUnlimitedProxyAllowanceAsync(tokenAddress, coinbase);
await zeroEx.awaitTransactionMinedAsync(txHash); await web3Wrapper.awaitTransactionMinedAsync(txHash);
txHash = await zeroEx.token.setUnlimitedProxyAllowanceAsync(tokenAddress, addressWithoutFunds); txHash = await contractWrappers.token.setUnlimitedProxyAllowanceAsync(tokenAddress, addressWithoutFunds);
await zeroEx.awaitTransactionMinedAsync(txHash); await web3Wrapper.awaitTransactionMinedAsync(txHash);
const eventName = TokenEvents.Approval; const eventName = TokenEvents.Approval;
const indexFilterValues = { const indexFilterValues = {
_owner: coinbase, _owner: coinbase,
}; };
const logs = await zeroEx.token.getLogsAsync<ApprovalContractEventArgs>( const logs = await contractWrappers.token.getLogsAsync<ApprovalContractEventArgs>(
tokenAddress, tokenAddress,
eventName, eventName,
blockRange, blockRange,

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,9 @@
export const constants = {
NULL_ADDRESS: '0x0000000000000000000000000000000000000000',
ROPSTEN_NETWORK_ID: 3,
KOVAN_NETWORK_ID: 42,
TESTRPC_NETWORK_ID: 50,
KOVAN_RPC_URL: 'https://kovan.infura.io/',
ROPSTEN_RPC_URL: 'https://ropsten.infura.io/',
ZRX_DECIMALS: 18,
};

View File

@ -0,0 +1,18 @@
import { Deployer } from '@0xproject/deployer';
import { devConstants } from '@0xproject/dev-utils';
import * as path from 'path';
import { constants } from './constants';
import { provider } from './web3_wrapper';
const artifactsDir = path.resolve('test', 'artifacts');
const deployerOpts = {
artifactsDir,
provider,
networkId: constants.TESTRPC_NETWORK_ID,
defaults: {
gas: devConstants.GAS_ESTIMATE,
},
};
export const deployer = new Deployer(deployerOpts);

View File

@ -0,0 +1,33 @@
import * as _ from 'lodash';
import { InternalContractWrappersError, Token } from '../../src/types';
const PROTOCOL_TOKEN_SYMBOL = 'ZRX';
const WETH_TOKEN_SYMBOL = 'WETH';
export class TokenUtils {
private _tokens: Token[];
constructor(tokens: Token[]) {
this._tokens = tokens;
}
public getProtocolTokenOrThrow(): Token {
const zrxToken = _.find(this._tokens, { symbol: PROTOCOL_TOKEN_SYMBOL });
if (_.isUndefined(zrxToken)) {
throw new Error(InternalContractWrappersError.ZrxNotInTokenRegistry);
}
return zrxToken;
}
public getWethTokenOrThrow(): Token {
const wethToken = _.find(this._tokens, { symbol: WETH_TOKEN_SYMBOL });
if (_.isUndefined(wethToken)) {
throw new Error(InternalContractWrappersError.WethNotInTokenRegistry);
}
return wethToken;
}
public getDummyTokens(): Token[] {
const dummyTokens = _.filter(this._tokens, token => {
return !_.includes([PROTOCOL_TOKEN_SYMBOL, WETH_TOKEN_SYMBOL], token.symbol);
});
return dummyTokens;
}
}

View File

@ -0,0 +1,9 @@
import { devConstants, web3Factory } from '@0xproject/dev-utils';
import { Provider } from '@0xproject/types';
import { Web3Wrapper } from '@0xproject/web3-wrapper';
const web3 = web3Factory.create({ shouldUseInProcessGanache: true });
const provider: Provider = web3.currentProvider;
const web3Wrapper = new Web3Wrapper(web3.currentProvider);
export { provider, web3Wrapper };

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

@ -1,4 +1,4 @@
import { ZeroEx, ZeroExError } from '0x.js'; import { ZeroEx, ContractWrappersError } from '0x.js';
import { BlockchainLifecycle, devConstants, web3Factory } from '@0xproject/dev-utils'; import { BlockchainLifecycle, devConstants, web3Factory } from '@0xproject/dev-utils';
import { BigNumber, promisify } from '@0xproject/utils'; import { BigNumber, promisify } from '@0xproject/utils';
import { Web3Wrapper } from '@0xproject/web3-wrapper'; import { Web3Wrapper } from '@0xproject/web3-wrapper';
@ -43,7 +43,7 @@ describe('EtherToken', () => {
const ethToDeposit = initEthBalance.plus(1); const ethToDeposit = initEthBalance.plus(1);
return expect(zeroEx.etherToken.depositAsync(etherTokenAddress, ethToDeposit, account)).to.be.rejectedWith( return expect(zeroEx.etherToken.depositAsync(etherTokenAddress, ethToDeposit, account)).to.be.rejectedWith(
ZeroExError.InsufficientEthBalanceForDeposit, ContractWrappersError.InsufficientEthBalanceForDeposit,
); );
}); });
@ -72,7 +72,7 @@ describe('EtherToken', () => {
return expect( return expect(
zeroEx.etherToken.withdrawAsync(etherTokenAddress, ethTokensToWithdraw, account), zeroEx.etherToken.withdrawAsync(etherTokenAddress, ethTokensToWithdraw, account),
).to.be.rejectedWith(ZeroExError.InsufficientWEthBalanceForWithdrawal); ).to.be.rejectedWith(ContractWrappersError.InsufficientWEthBalanceForWithdrawal);
}); });
it('should convert ether tokens to ether with sufficient balance', async () => { it('should convert ether tokens to ether with sufficient balance', async () => {

View File

@ -17,7 +17,7 @@ import { chaiSetup } from './utils/chai_setup';
import { deployer } from './utils/deployer'; import { deployer } from './utils/deployer';
import { provider, web3Wrapper } from './utils/web3_wrapper'; import { provider, web3Wrapper } from './utils/web3_wrapper';
const MULTI_SIG_ABI = artifacts.MultiSigWalletWithTimeLockArtifact.networks[constants.TESTRPC_NETWORK_ID].abi; const MULTI_SIG_ABI = artifacts.MultiSigWalletWithTimeLock.networks[constants.TESTRPC_NETWORK_ID].abi;
chaiSetup.configure(); chaiSetup.configure();
const expect = chai.expect; const expect = chai.expect;
const blockchainLifecycle = new BlockchainLifecycle(web3Wrapper); const blockchainLifecycle = new BlockchainLifecycle(web3Wrapper);

View File

@ -17,9 +17,9 @@ import { ContractName, SubmissionContractEventArgs, TransactionDataParams } from
import { chaiSetup } from './utils/chai_setup'; import { chaiSetup } from './utils/chai_setup';
import { deployer } from './utils/deployer'; import { deployer } from './utils/deployer';
import { provider, web3Wrapper } from './utils/web3_wrapper'; import { provider, web3Wrapper } from './utils/web3_wrapper';
const PROXY_ABI = artifacts.TokenTransferProxyArtifact.networks[constants.TESTRPC_NETWORK_ID].abi; const PROXY_ABI = artifacts.TokenTransferProxy.networks[constants.TESTRPC_NETWORK_ID].abi;
const MUTISIG_WALLET_WITH_TIME_LOCK_EXCEPT_REMOVE_AUTHORIZED_ADDRESS_ABI = const MUTISIG_WALLET_WITH_TIME_LOCK_EXCEPT_REMOVE_AUTHORIZED_ADDRESS_ABI =
artifacts.MultiSigWalletWithTimeLockExceptRemoveAuthorizedAddressArtifact.networks[constants.TESTRPC_NETWORK_ID] artifacts.MultiSigWalletWithTimeLockExceptRemoveAuthorizedAddress.networks[constants.TESTRPC_NETWORK_ID]
.abi; .abi;
chaiSetup.configure(); chaiSetup.configure();

View File

@ -1,5 +1,6 @@
import { ECSignature, SignedOrder, ZeroEx } from '0x.js'; import { ECSignature, SignedOrder, ZeroEx } from '0x.js';
import { BlockchainLifecycle, devConstants, web3Factory } from '@0xproject/dev-utils'; import { BlockchainLifecycle, devConstants, web3Factory } from '@0xproject/dev-utils';
import { ExchangeContractErrs } from '@0xproject/types';
import { BigNumber } from '@0xproject/utils'; import { BigNumber } from '@0xproject/utils';
import { Web3Wrapper } from '@0xproject/web3-wrapper'; import { Web3Wrapper } from '@0xproject/web3-wrapper';
import * as chai from 'chai'; import * as chai from 'chai';
@ -14,7 +15,7 @@ import { constants } from '../../util/constants';
import { crypto } from '../../util/crypto'; import { crypto } from '../../util/crypto';
import { ExchangeWrapper } from '../../util/exchange_wrapper'; import { ExchangeWrapper } from '../../util/exchange_wrapper';
import { OrderFactory } from '../../util/order_factory'; import { OrderFactory } from '../../util/order_factory';
import { BalancesByOwner, ContractName, ExchangeContractErrs } from '../../util/types'; import { BalancesByOwner, ContractName } from '../../util/types';
import { chaiSetup } from '../utils/chai_setup'; import { chaiSetup } from '../utils/chai_setup';
import { deployer } from '../utils/deployer'; import { deployer } from '../utils/deployer';
import { provider, web3Wrapper } from '../utils/web3_wrapper'; import { provider, web3Wrapper } from '../utils/web3_wrapper';

View File

@ -1,25 +1,25 @@
import * as DummyTokenArtifact from '../src/artifacts/DummyToken.json'; import * as DummyToken from '../src/artifacts/DummyToken.json';
import * as ExchangeArtifact from '../src/artifacts/Exchange.json'; import * as Exchange from '../src/artifacts/Exchange.json';
import * as MaliciousTokenArtifact from '../src/artifacts/MaliciousToken.json'; import * as MaliciousToken from '../src/artifacts/MaliciousToken.json';
import * as MultiSigWalletWithTimeLockArtifact from '../src/artifacts/MultiSigWalletWithTimeLock.json'; import * as MultiSigWalletWithTimeLock from '../src/artifacts/MultiSigWalletWithTimeLock.json';
import * as MultiSigWalletWithTimeLockExceptRemoveAuthorizedAddressArtifact from '../src/artifacts/MultiSigWalletWithTimeLockExceptRemoveAuthorizedAddress.json'; import * as MultiSigWalletWithTimeLockExceptRemoveAuthorizedAddress from '../src/artifacts/MultiSigWalletWithTimeLockExceptRemoveAuthorizedAddress.json';
import * as TokenArtifact from '../src/artifacts/Token.json'; import * as Token from '../src/artifacts/Token.json';
import * as TokenRegistryArtifact from '../src/artifacts/TokenRegistry.json'; import * as TokenRegistry from '../src/artifacts/TokenRegistry.json';
import * as TokenTransferProxyArtifact from '../src/artifacts/TokenTransferProxy.json'; import * as TokenTransferProxy from '../src/artifacts/TokenTransferProxy.json';
import * as EtherTokenArtifact from '../src/artifacts/WETH9.json'; import * as EtherToken from '../src/artifacts/WETH9.json';
import * as ZRXArtifact from '../src/artifacts/ZRXToken.json'; import * as ZRX from '../src/artifacts/ZRXToken.json';
import { Artifact } from './types'; import { Artifact } from './types';
export const artifacts = { export const artifacts = {
ZRXArtifact: (ZRXArtifact as any) as Artifact, ZRX: (ZRX as any) as Artifact,
DummyTokenArtifact: (DummyTokenArtifact as any) as Artifact, DummyToken: (DummyToken as any) as Artifact,
TokenArtifact: (TokenArtifact as any) as Artifact, Token: (Token as any) as Artifact,
ExchangeArtifact: (ExchangeArtifact as any) as Artifact, Exchange: (Exchange as any) as Artifact,
EtherTokenArtifact: (EtherTokenArtifact as any) as Artifact, EtherToken: (EtherToken as any) as Artifact,
TokenRegistryArtifact: (TokenRegistryArtifact as any) as Artifact, TokenRegistry: (TokenRegistry as any) as Artifact,
MaliciousTokenArtifact: (MaliciousTokenArtifact as any) as Artifact, MaliciousToken: (MaliciousToken as any) as Artifact,
TokenTransferProxyArtifact: (TokenTransferProxyArtifact as any) as Artifact, TokenTransferProxy: (TokenTransferProxy as any) as Artifact,
MultiSigWalletWithTimeLockArtifact: (MultiSigWalletWithTimeLockArtifact as any) as Artifact, MultiSigWalletWithTimeLock: (MultiSigWalletWithTimeLock as any) as Artifact,
MultiSigWalletWithTimeLockExceptRemoveAuthorizedAddressArtifact: (MultiSigWalletWithTimeLockExceptRemoveAuthorizedAddressArtifact as any) as Artifact, MultiSigWalletWithTimeLockExceptRemoveAuthorizedAddress: (MultiSigWalletWithTimeLockExceptRemoveAuthorizedAddress as any) as Artifact,
}; };

View File

@ -1,9 +1,10 @@
import { DoneCallback } from '@0xproject/types';
import * as chai from 'chai'; import * as chai from 'chai';
import 'mocha'; import 'mocha';
import { Compiler } from '../src/compiler'; import { Compiler } from '../src/compiler';
import { fsWrapper } from '../src/utils/fs_wrapper'; import { fsWrapper } from '../src/utils/fs_wrapper';
import { CompilerOptions, ContractArtifact, ContractNetworkData, DoneCallback } from '../src/utils/types'; import { CompilerOptions, ContractArtifact, ContractNetworkData } from '../src/utils/types';
import { exchange_binary } from './fixtures/exchange_bin'; import { exchange_binary } from './fixtures/exchange_bin';
import { constants } from './util/constants'; import { constants } from './util/constants';

View File

@ -1,10 +1,11 @@
import { DoneCallback } from '@0xproject/types';
import * as chai from 'chai'; import * as chai from 'chai';
import 'mocha'; import 'mocha';
import { Compiler } from '../src/compiler'; import { Compiler } from '../src/compiler';
import { Deployer } from '../src/deployer'; import { Deployer } from '../src/deployer';
import { fsWrapper } from '../src/utils/fs_wrapper'; import { fsWrapper } from '../src/utils/fs_wrapper';
import { CompilerOptions, ContractArtifact, ContractNetworkData, DoneCallback } from '../src/utils/types'; import { CompilerOptions, ContractArtifact, ContractNetworkData } from '../src/utils/types';
import { constructor_args, exchange_binary } from './fixtures/exchange_bin'; import { constructor_args, exchange_binary } from './fixtures/exchange_bin';
import { constants } from './util/constants'; import { constants } from './util/constants';

View File

@ -1,4 +1,12 @@
[ [
{
"version": "0.4.2",
"changes": [
{
"note": "Move callbackErrorReporter over from 0x.js"
}
]
},
{ {
"timestamp": 1525477860, "timestamp": 1525477860,
"version": "0.4.1", "version": "0.4.1",

View File

@ -0,0 +1,66 @@
import * as chai from 'chai';
import * as _ from 'lodash';
import { DoneCallback } from '@0xproject/types';
const expect = chai.expect;
export const callbackErrorReporter = {
reportNoErrorCallbackErrors(done: DoneCallback, expectToBeCalledOnce = true) {
return <T>(f?: (value: T) => void) => {
const wrapped = (value: T) => {
if (_.isUndefined(f)) {
done();
return;
}
try {
f(value);
if (expectToBeCalledOnce) {
done();
}
} catch (err) {
done(err);
}
};
return wrapped;
};
},
reportNodeCallbackErrors(done: DoneCallback, expectToBeCalledOnce = true) {
return <T>(f?: (value: T) => void) => {
const wrapped = (error: Error | null, value: T | undefined) => {
if (!_.isNull(error)) {
done(error);
} else {
if (_.isUndefined(f)) {
done();
return;
}
try {
f(value as T);
if (expectToBeCalledOnce) {
done();
}
} catch (err) {
done(err);
}
}
};
return wrapped;
};
},
assertNodeCallbackError(done: DoneCallback, errMsg: string) {
const wrapped = <T>(error: Error | null, value: T | undefined) => {
if (_.isNull(error)) {
done(new Error('Expected callback to receive an error'));
} else {
try {
expect(error.message).to.be.equal(errMsg);
done();
} catch (err) {
done(err);
}
}
};
return wrapped;
},
};

View File

@ -3,3 +3,4 @@ export { web3Factory } from './web3_factory';
export { constants as devConstants } from './constants'; export { constants as devConstants } from './constants';
export { coverage } from './coverage'; export { coverage } from './coverage';
export { env, EnvVars } from './env'; export { env, EnvVars } from './env';
export { callbackErrorReporter } from './callback_error_reporter';

View File

@ -0,0 +1,6 @@
.*
yarn-error.log
/scripts/
/src/
tsconfig.json
/lib/monorepo_scripts/

View File

@ -0,0 +1,10 @@
[
{
"version": "0.0.1",
"changes": [
{
"note": "Move FillScenarios out of 0x.js"
}
]
}
]

View File

@ -0,0 +1,75 @@
## @0xproject/fill-scenarios
0x order fill scenario generator
## Installation
```bash
yarn add @0xproject/fill-scenarios
```
If your project is in [TypeScript](https://www.typescriptlang.org/), add the following to your `tsconfig.json`:
```json
"compilerOptions": {
"typeRoots": ["node_modules/@0xproject/typescript-typings/types", "node_modules/@types"],
}
```
## Contributing
We welcome improvements and fixes from the wider community! To report bugs within this package, please create an issue in this repository.
Please read our [contribution guidelines](../../CONTRIBUTING.md) before getting started.
### Install dependencies
If you don't have yarn workspaces enabled (Yarn < v1.0) - enable them:
```bash
yarn config set workspaces-experimental true
```
Then install dependencies
```bash
yarn install
```
### Build
If this is your **first** time building this package, you must first build **all** packages within the monorepo. This is because packages that depend on other packages located inside this monorepo are symlinked when run from **within** the monorepo. This allows you to make changes across multiple packages without first publishing dependent packages to NPM. To build all packages, run the following from the monorepo root directory:
```bash
yarn lerna:rebuild
```
Or continuously rebuild on change:
```bash
yarn dev
```
You can also build this specific package by running the following from within its directory:
```bash
yarn build
```
or continuously rebuild on change:
```bash
yarn build:watch
```
### Clean
```bash
yarn clean
```
### Lint
```bash
yarn lint
```

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