Merge branch 'development' into feature/forwarder-helper/init

* development: (187 commits)
  Remove trailing slash
  Fix linter
  Stop nesting interfaces and add necessary type exports
  Remove duplicate type and remove nested interface
  Add support for rending the Tuple type
  Add missing keyu
  Remove excessive timestamp
  Improve doc commebnt
  Remove docs catch-all endpoint
  Fix comments
  Look for all TS mapped types
  Add catch and exit with non-zero
  Remove superfluous dep
  Fix CHANGELOG entry
  Fix double assignment
  Upgrade Typedoc to 0.12.0, which works with TS 3.x
  Fix prettier issues
  Enable dry run of release publishing and handle git tags existing
  update yarn.lock
  Missing/superfluous type exports from connect
  ...
This commit is contained in:
Brandon Millman
2018-08-23 10:58:33 -07:00
282 changed files with 3553 additions and 12502 deletions

View File

@@ -1,4 +1,14 @@
[
{
"version": "1.0.1-rc.4",
"changes": [
{
"note":
"Re-organize the exported interface of 0x.js. Remove the `ZeroEx` class, and instead export the same exports as `0x.js`'s sub-packages: `@0xproject/contract-wrappers`, `@0xproject/order-utils` and `@0xproject/order-watcher`",
"pr": 963
}
]
},
{
"version": "1.0.1-rc.3",
"changes": [

View File

@@ -15,51 +15,26 @@
"main": "lib/src/index.js",
"types": "lib/src/index.d.ts",
"scripts": {
"watch_without_deps": "yarn pre_build && tsc -w",
"build": "yarn pre_build && yarn build:all && copyfiles -u 3 './lib/src/monorepo_scripts/**/*' ./scripts",
"watch_without_deps": "tsc -w",
"build": "yarn build:all",
"build:all": "run-p build:umd:prod build:commonjs; exit 0;",
"pre_build": "run-s update_artifacts generate_contract_wrappers",
"copy_artifacts": "copyfiles -u 2 './src/artifacts/**/*.json' ./lib/src/artifacts",
"update_artifacts": "for i in ${npm_package_config_contracts}; do copyfiles -u 4 ../migrations/artifacts/2.0.0-beta-testnet/$i.json src/artifacts; done;",
"generate_contract_wrappers": "abi-gen --abis 'src/artifacts/@(ZRXToken).json' --template ../contract_templates/contract.handlebars --partials '../contract_templates/partials/**/*.handlebars' --output src/generated_contract_wrappers --backend ethers",
"lint": "tslint --project . --exclude **/src/generated_contract_wrappers/**/*",
"test:circleci": "run-s test:coverage",
"test": "yarn run_mocha",
"rebuild_and_test": "run-s build test",
"test:coverage": "nyc npm run test --all && yarn coverage:report:lcov",
"coverage:report:lcov": "nyc report --reporter=text-lcov > coverage/lcov.info",
"clean": "shx rm -rf _bundles lib test_temp scripts src/generated_contract_wrappers",
"clean": "shx rm -rf _bundles lib test_temp src/generated_contract_wrappers generated_docs",
"build:umd:prod": "NODE_ENV=production webpack",
"build:commonjs": "tsc && yarn copy_artifacts && copyfiles -u 3 './lib/src/monorepo_scripts/**/*' ./scripts",
"run_mocha": "mocha --require source-map-support/register --require make-promises-safe lib/test/**/*_test.js lib/test/global_hooks.js --timeout 10000 --bail --exit",
"manual:postpublish": "yarn build; node ./scripts/postpublish.js",
"docs:stage": "node scripts/stage_docs.js",
"docs:json": "typedoc --excludePrivate --excludeExternals --target ES5 --json $JSON_FILE_PATH $PROJECT_FILES",
"upload_docs_json": "aws s3 cp generated_docs/index.json $S3_URL --profile 0xproject --grants read=uri=http://acs.amazonaws.com/groups/global/AllUsers --content-type application/json"
"build:commonjs": "tsc",
"docs:json": "typedoc --excludePrivate --excludeExternals --target ES5 --json $JSON_FILE_PATH $PROJECT_FILES"
},
"config": {
"contracts": "ZRXToken AssetProxyOwner DummyERC20Token DummyERC721Token ERC20Proxy ERC721Proxy Exchange Forwarder OrderValidator WETH9",
"postpublish": {
"assets": [
"packages/0x.js/_bundles/index.js",
"packages/0x.js/_bundles/index.min.js"
],
"docPublishConfigs": {
"extraFileIncludes": [
"../types/src/index.ts",
"../ethereum-types/src/index.ts",
"../contract-wrappers/src/types.ts",
"../contract-wrappers/src/contract_wrappers/ether_token_wrapper.ts",
"../contract-wrappers/src/contract_wrappers/exchange_wrapper.ts",
"../contract-wrappers/src/contract_wrappers/erc20_proxy_wrapper.ts",
"../contract-wrappers/src/contract_wrappers/erc721_proxy_wrapper.ts",
"../contract-wrappers/src/contract_wrappers/erc20_token_wrapper.ts",
"../contract-wrappers/src/contract_wrappers/erc721_token_wrapper.ts",
"../order-watcher/src/order_watcher/order_watcher.ts"
],
"s3BucketPath": "s3://doc-jsons/0x.js/",
"s3StagingBucketPath": "s3://staging-doc-jsons/0x.js/"
}
]
}
},
"repository": {
@@ -93,7 +68,7 @@
"sinon": "^4.0.0",
"source-map-support": "^0.5.0",
"tslint": "5.11.0",
"typedoc": "0xProject/typedoc",
"typedoc": "0.12.0",
"typescript": "3.0.1",
"webpack": "^3.1.0"
},
@@ -102,7 +77,7 @@
"@0xproject/base-contract": "^2.0.0-rc.1",
"@0xproject/contract-wrappers": "^1.0.1-rc.3",
"@0xproject/order-utils": "^1.0.1-rc.3",
"@0xproject/sol-compiler": "^1.0.5",
"@0xproject/order-watcher": "1.0.1-rc.3",
"@0xproject/subproviders": "^1.0.5",
"@0xproject/types": "^1.0.1-rc.4",
"@0xproject/typescript-typings": "^1.0.4",
@@ -110,7 +85,8 @@
"@0xproject/web3-wrapper": "^1.2.0",
"ethereum-types": "^1.0.4",
"ethers": "3.0.22",
"lodash": "^4.17.5"
"lodash": "^4.17.5",
"web3-provider-engine": "14.0.6"
},
"publishConfig": {
"access": "public"

View File

@@ -1,279 +0,0 @@
import { assert } from '@0xproject/assert';
import {
ContractWrappers,
ContractWrappersConfig,
ERC20ProxyWrapper,
ERC20TokenWrapper,
ERC721ProxyWrapper,
ERC721TokenWrapper,
EtherTokenWrapper,
ExchangeWrapper,
} from '@0xproject/contract-wrappers';
import {
assetDataUtils,
ecSignOrderHashAsync,
generatePseudoRandomSalt,
isValidSignatureAsync,
orderHashUtils,
} from '@0xproject/order-utils';
// HACK: Since we export assetDataUtils from ZeroEx and it has AssetProxyId, ERC20AssetData and ERC721AssetData
// in it's public interface, we need to import these types here.
// tslint:disable-next-line:no-unused-variable
import { AssetProxyId, ERC20AssetData, ERC721AssetData, Order, SignedOrder, SignerType } from '@0xproject/types';
import { BigNumber } from '@0xproject/utils';
import { Web3Wrapper } from '@0xproject/web3-wrapper';
import { Provider, TransactionReceiptWithDecodedLogs } from 'ethereum-types';
import { constants } from './utils/constants';
/**
* The ZeroEx class is the single entry-point into the 0x.js library. It contains all of the library's functionality
* and all calls to the library should be made through a ZeroEx instance.
*/
export class ZeroEx {
/**
* When creating an order without a specified taker or feeRecipient you must supply the Solidity
* address null type (as opposed to Javascripts `null`, `undefined` or empty string). We expose
* this constant for your convenience.
*/
public static NULL_ADDRESS = constants.NULL_ADDRESS;
/**
* An instance of the ExchangeWrapper class containing methods for interacting with the 0x Exchange smart contract.
*/
public exchange: ExchangeWrapper;
/**
* An instance of the ERC20TokenWrapper class containing methods for interacting with any ERC20 token smart contract.
*/
public erc20Token: ERC20TokenWrapper;
/**
* An instance of the ERC721TokenWrapper class containing methods for interacting with any ERC721 token smart contract.
*/
public erc721Token: ERC721TokenWrapper;
/**
* 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 ERC20ProxyWrapper class containing methods for interacting with the
* ERC20 proxy smart contract.
*/
public erc20Proxy: ERC20ProxyWrapper;
/**
* An instance of the ERC721ProxyWrapper class containing methods for interacting with the
* ERC721 proxy smart contract.
*/
public erc721Proxy: ERC721ProxyWrapper;
private readonly _contractWrappers: ContractWrappers;
/**
* Generates a pseudo-random 256-bit salt.
* The salt can be included in a 0x order, ensuring that the order generates a unique orderHash
* and will not collide with other outstanding orders that are identical in all other parameters.
* @return A pseudo-random 256-bit number that can be used as a salt.
*/
public static generatePseudoRandomSalt(): BigNumber {
return generatePseudoRandomSalt();
}
/**
* Computes the orderHash for a supplied order.
* @param order An object that conforms to the Order or SignedOrder interface definitions.
* @return The resulting orderHash from hashing the supplied order.
*/
public static getOrderHashHex(order: Order | SignedOrder): string {
return orderHashUtils.getOrderHashHex(order);
}
/**
* Checks if the supplied hex encoded order hash is valid.
* Note: Valid means it has the expected format, not that an order with the orderHash exists.
* Use this method when processing orderHashes submitted as user input.
* @param orderHash Hex encoded orderHash.
* @return Whether the supplied orderHash has the expected format.
*/
public static isValidOrderHash(orderHash: string): boolean {
return orderHashUtils.isValidOrderHash(orderHash);
}
/**
* A unit amount is defined as the amount of a token above the specified decimal places (integer part).
* E.g: If a currency has 18 decimal places, 1e18 or one quintillion of the currency is equivalent
* to 1 unit.
* @param amount The amount in baseUnits that you would like converted to units.
* @param decimals The number of decimal places the unit amount has.
* @return The amount in units.
*/
public static toUnitAmount(amount: BigNumber, decimals: number): BigNumber {
assert.isValidBaseUnitAmount('amount', amount);
assert.isNumber('decimals', decimals);
const unitAmount = Web3Wrapper.toUnitAmount(amount, decimals);
return unitAmount;
}
/**
* A baseUnit is defined as the smallest denomination of a token. An amount expressed in baseUnits
* is the amount expressed in the smallest denomination.
* E.g: 1 unit of a token with 18 decimal places is expressed in baseUnits as 1000000000000000000
* @param amount The amount of units that you would like converted to baseUnits.
* @param decimals The number of decimal places the unit amount has.
* @return The amount in baseUnits.
*/
public static toBaseUnitAmount(amount: BigNumber, decimals: number): BigNumber {
assert.isBigNumber('amount', amount);
assert.isNumber('decimals', decimals);
const baseUnitAmount = Web3Wrapper.toBaseUnitAmount(amount, decimals);
return baseUnitAmount;
}
/**
* Encodes an ERC20 token address into a hex encoded assetData string, usable in the makerAssetData or
* takerAssetData fields in a 0x order.
* @param tokenAddress The ERC20 token address to encode
* @return The hex encoded assetData string
*/
public static encodeERC20AssetData(tokenAddress: string): string {
return assetDataUtils.encodeERC20AssetData(tokenAddress);
}
/**
* Decodes an ERC20 assetData hex string into it's corresponding ERC20 tokenAddress & assetProxyId
* @param assetData Hex encoded assetData string to decode
* @return An object containing the decoded tokenAddress & assetProxyId
*/
public static decodeERC20AssetData(assetData: string): ERC20AssetData {
return assetDataUtils.decodeERC20AssetData(assetData);
}
/**
* Encodes an ERC721 token address into a hex encoded assetData string, usable in the makerAssetData or
* takerAssetData fields in a 0x order.
* @param tokenAddress The ERC721 token address to encode
* @param tokenId The ERC721 tokenId to encode
* @return The hex encoded assetData string
*/
public static encodeERC721AssetData(tokenAddress: string, tokenId: BigNumber): string {
return assetDataUtils.encodeERC721AssetData(tokenAddress, tokenId);
}
/**
* Decodes an ERC721 assetData hex string into it's corresponding ERC721 tokenAddress, tokenId & assetProxyId
* @param assetData Hex encoded assetData string to decode
* @return An object containing the decoded tokenAddress, tokenId & assetProxyId
*/
public static decodeERC721AssetData(assetData: string): ERC721AssetData {
return assetDataUtils.decodeERC721AssetData(assetData);
}
/**
* Decode and return the assetProxyId from the assetData
* @param assetData Hex encoded assetData string to decode
* @return The assetProxyId
*/
public static decodeAssetProxyId(assetData: string): AssetProxyId {
return assetDataUtils.decodeAssetProxyId(assetData);
}
/**
* Decode any assetData into it's corresponding assetData object
* @param assetData Hex encoded assetData string to decode
* @return Either a ERC20 or ERC721 assetData object
*/
public static decodeAssetDataOrThrow(assetData: string): ERC20AssetData | ERC721AssetData {
return assetDataUtils.decodeAssetDataOrThrow(assetData);
}
/**
* Instantiates a new ZeroEx instance that provides the public interface to the 0x.js library.
* @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 0x.js ZeroEx class.
*/
constructor(provider: Provider, config: ContractWrappersConfig) {
assert.isWeb3Provider('provider', provider);
this._contractWrappers = new ContractWrappers(provider, config);
this.erc20Proxy = this._contractWrappers.erc20Proxy;
this.erc721Proxy = this._contractWrappers.erc721Proxy;
this.erc20Token = this._contractWrappers.erc20Token;
this.erc721Token = this._contractWrappers.erc721Token;
this.exchange = this._contractWrappers.exchange;
this.etherToken = this._contractWrappers.etherToken;
}
/**
* Verifies that the provided signature is valid according to the 0x Protocol smart contracts
* @param data The hex encoded data signed by the supplied signature.
* @param signature The hex encoded signature.
* @param signerAddress The hex encoded address that signed the data, producing the supplied signature.
* @return Whether the signature is valid for the supplied signerAddress and data.
*/
public async isValidSignatureAsync(data: string, signature: string, signerAddress: string): Promise<boolean> {
const isValid = await isValidSignatureAsync(
this._contractWrappers.getProvider(),
data,
signature,
signerAddress,
);
return isValid;
}
/**
* 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._contractWrappers.setProvider(provider, networkId);
}
/**
* Get the provider instance currently used by 0x.js
* @return Web3 provider instance
*/
public getProvider(): Provider {
return this._contractWrappers.getProvider();
}
/**
* Get user Ethereum addresses available through the supplied web3 provider available for sending transactions.
* @return An array of available user Ethereum addresses.
*/
public async getAvailableAddressesAsync(): Promise<string[]> {
// Hack: Get Web3Wrapper from ContractWrappers
const web3Wrapper: Web3Wrapper = (this._contractWrappers as any)._web3Wrapper;
const availableAddresses = await web3Wrapper.getAvailableAddressesAsync();
return availableAddresses;
}
/**
* Signs an orderHash and returns it's elliptic curve signature.
* This method currently supports TestRPC, Geth and Parity above and below V1.6.6
* @param orderHash Hex encoded orderHash to sign.
* @param signerAddress The hex encoded Ethereum address you wish to sign it with. This address
* must be available via the Provider supplied to 0x.js.
* @param signerType the signer type that will perform the `eth_sign` operation. E.g Default, Metamask, Ledger or Trezor.
* Some implementations exhibit different behaviour. Default will assume a spec compliant eth_sign implementation.
* This parameter is defaulted to `SignerType.Default`.
* @return A hex encoded string of the Elliptic curve signature parameters generated by signing the orderHash and signature type.
*/
public async ecSignOrderHashAsync(
orderHash: string,
signerAddress: string,
signerType: SignerType = SignerType.Default,
): Promise<string> {
const signature = await ecSignOrderHashAsync(
this._contractWrappers.getProvider(),
orderHash,
signerAddress,
signerType,
);
return signature;
}
/**
* Waits for a transaction to be mined and returns the transaction receipt.
* @param txHash Transaction hash
* @param pollingIntervalMs How often (in ms) should we check if the transaction is mined.
* @param timeoutMs How long (in ms) to poll for transaction mined until aborting.
* @return Transaction receipt with decoded log args.
*/
public async awaitTransactionMinedAsync(
txHash: string,
pollingIntervalMs: number = 1000,
timeoutMs?: number,
): Promise<TransactionReceiptWithDecodedLogs> {
// Hack: Get Web3Wrapper from ContractWrappers
const web3Wrapper: Web3Wrapper = (this._contractWrappers as any)._web3Wrapper;
const transactionReceiptWithDecodedLogs = await web3Wrapper.awaitTransactionMinedAsync(
txHash,
pollingIntervalMs,
timeoutMs,
);
return transactionReceiptWithDecodedLogs;
}
}

View File

@@ -1,7 +0,0 @@
import { ContractArtifact } from '@0xproject/sol-compiler';
import * as ZRXToken from './artifacts/ZRXToken.json';
export const artifacts = {
ZRXToken: (ZRXToken as any) as ContractArtifact,
};

View File

@@ -1,47 +1,22 @@
export { ZeroEx } from './0x';
export { Web3ProviderEngine, RPCSubprovider } from '@0xproject/subproviders';
export { assetDataUtils, signatureUtils, generatePseudoRandomSalt, orderHashUtils } from '@0xproject/order-utils';
export {
ExchangeContractErrs,
Order,
SignedOrder,
SignerType,
ECSignature,
OrderStateValid,
OrderStateInvalid,
OrderState,
Token,
ERC20AssetData,
ERC721AssetData,
AssetProxyId,
} from '@0xproject/types';
export {
BlockParamLiteral,
FilterObject,
BlockParam,
LogWithDecodedArgs,
ContractEventArg,
Provider,
TransactionReceipt,
TransactionReceiptWithDecodedLogs,
} from 'ethereum-types';
export {
EventCallback,
ContractEvent,
ContractWrappers,
ERC20TokenWrapper,
ERC721TokenWrapper,
EtherTokenWrapper,
ExchangeWrapper,
ERC20ProxyWrapper,
ERC721ProxyWrapper,
ForwarderWrapper,
IndexedFilterValues,
BlockRange,
OrderFillRequest,
ContractEventArgs,
ContractWrappersConfig,
MethodOpts,
OrderTransactionOpts,
TransactionOpts,
LogEvent,
DecodedLogEvent,
OnOrderStateChangeCallback,
ContractWrappersError,
OrderStatus,
OrderInfo,
WETH9Events,
WETH9WithdrawalEventArgs,
WETH9ApprovalEventArgs,
@@ -56,11 +31,69 @@ export {
ERC721TokenApprovalForAllEventArgs,
ERC721TokenTransferEventArgs,
ERC721TokenEvents,
ERC721TokenEventArgs,
ExchangeCancelUpToEventArgs,
ExchangeAssetProxyRegisteredEventArgs,
ExchangeSignatureValidatorApprovalEventArgs,
ExchangeFillEventArgs,
ExchangeCancelEventArgs,
ExchangeEvents,
EventCallback,
DecodedLogEvent,
ExchangeEventArgs,
ContractWrappersConfig,
OrderInfo,
TransactionEncoder,
} from '@0xproject/contract-wrappers';
export { OrderWatcher, OnOrderStateChangeCallback, OrderWatcherConfig } from '@0xproject/order-watcher';
export import Web3ProviderEngine = require('web3-provider-engine');
export { RPCSubprovider, Callback, JSONRPCRequestPayloadWithMethod, ErrorCallback } from '@0xproject/subproviders';
export { AbiDecoder } from '@0xproject/utils';
export { BigNumber } from '@0xproject/utils';
export {
ExchangeContractErrs,
Order,
SignedOrder,
ECSignature,
OrderStateValid,
OrderStateInvalid,
OrderState,
AssetProxyId,
SignerType,
ERC20AssetData,
ERC721AssetData,
SignatureType,
OrderRelevantState,
} from '@0xproject/types';
export {
BlockParamLiteral,
ContractAbi,
BlockParam,
LogWithDecodedArgs,
ContractEventArg,
Provider,
JSONRPCRequestPayload,
JSONRPCResponsePayload,
JSONRPCErrorCallback,
LogEntry,
DecodedLogArgs,
LogEntryEvent,
DecodedLogEntry,
DecodedLogEntryEvent,
RawLog,
AbiDefinition,
FunctionAbi,
EventAbi,
EventParameter,
MethodAbi,
ConstructorAbi,
FallbackAbi,
DataItem,
ConstructorStateMutability,
StateMutability,
} from 'ethereum-types';

View File

@@ -1,8 +0,0 @@
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

@@ -1,8 +0,0 @@
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.publishDocsToStagingAsync(packageJSON, tsConfigJSON, cwd);

View File

@@ -1,5 +0,0 @@
export const zeroExConfigSchema = {
id: '/ZeroExConfig',
oneOf: [{ $ref: '/ZeroExPrivateNetworkConfig' }, { $ref: '/ZeroExPublicNetworkConfig' }],
type: 'object',
};

View File

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

View File

@@ -1,43 +0,0 @@
const networkNameToId: { [networkName: string]: number } = {
mainnet: 1,
ropsten: 3,
rinkeby: 4,
kovan: 42,
ganache: 50,
};
export const zeroExPublicNetworkConfigSchema = {
id: '/ZeroExPublicNetworkConfig',
properties: {
networkId: {
type: 'number',
enum: [
networkNameToId.mainnet,
networkNameToId.ropsten,
networkNameToId.rinkeby,
networkNameToId.kovan,
networkNameToId.ganache,
],
},
gasPrice: { $ref: '/Number' },
zrxContractAddress: { $ref: '/Address' },
exchangeContractAddress: { $ref: '/Address' },
erc20ProxyContractAddress: { $ref: '/Address' },
erc721ProxyContractAddress: { $ref: '/Address' },
orderWatcherConfig: {
type: 'object',
properties: {
pollingIntervalMs: {
type: 'number',
minimum: 0,
},
numConfirmations: {
type: 'number',
minimum: 0,
},
},
},
},
type: 'object',
required: ['networkId'],
};

View File

@@ -1,7 +0,0 @@
export enum InternalZeroExError {
NoAbiDecoder = 'NO_ABI_DECODER',
ZrxNotInTokenRegistry = 'ZRX_NOT_IN_TOKEN_REGISTRY',
WethNotInTokenRegistry = 'WETH_NOT_IN_TOKEN_REGISTRY',
}
// tslint:disable:max-file-line-count

View File

@@ -1,4 +0,0 @@
export const constants = {
NULL_ADDRESS: '0x0000000000000000000000000000000000000000',
TESTRPC_NETWORK_ID: 50,
};

View File

@@ -1,150 +0,0 @@
import { ContractWrappers } from '@0xproject/contract-wrappers';
import { BlockchainLifecycle } from '@0xproject/dev-utils';
import { BigNumber } from '@0xproject/utils';
import * as chai from 'chai';
import 'mocha';
import { ERC20TokenApprovalEventArgs, ERC20TokenEvents, LogWithDecodedArgs, ZeroEx } from '../src';
import { chaiSetup } from './utils/chai_setup';
import { constants } from './utils/constants';
import { tokenUtils } from './utils/token_utils';
import { provider, web3Wrapper } from './utils/web3_wrapper';
const blockchainLifecycle = new BlockchainLifecycle(web3Wrapper);
chaiSetup.configure();
const expect = chai.expect;
describe('ZeroEx library', () => {
let zeroEx: ZeroEx;
before(async () => {
const config = {
networkId: constants.TESTRPC_NETWORK_ID,
};
zeroEx = new ZeroEx(provider, config);
});
describe('#setProvider', () => {
it('overrides provider in nested web3s and invalidates contractInstances', async () => {
// Instantiate the contract instances with the current provider
await (zeroEx.exchange as any)._getExchangeContractAsync();
expect((zeroEx.exchange as any)._exchangeContractIfExists).to.not.be.undefined();
// Add property to newProvider so that we can differentiate it from old provider
(provider as any).zeroExTestId = 1;
zeroEx.setProvider(provider, constants.TESTRPC_NETWORK_ID);
// Check that contractInstances with old provider are removed after provider update
expect((zeroEx.exchange as any)._exchangeContractIfExists).to.be.undefined();
// Check that all nested zeroExContract/web3Wrapper instances return the updated provider
const nestedWeb3WrapperProvider = ((zeroEx as any)._contractWrappers as ContractWrappers).getProvider();
expect((nestedWeb3WrapperProvider as any).zeroExTestId).to.be.a('number');
const exchangeWeb3WrapperProvider = (zeroEx.exchange as any)._web3Wrapper.getProvider();
expect(exchangeWeb3WrapperProvider.zeroExTestId).to.be.a('number');
});
});
describe('#isValidSignature', () => {
const dataHex = '0x6927e990021d23b1eb7b8789f6a6feaf98fe104bb0cf8259421b79f9a34222b0';
const ethSignSignature =
'0x1B61a3ed31b43c8780e905a260a35faefcc527be7516aa11c0256729b5b351bc3340349190569279751135161d22529dc25add4f6069af05be04cacbda2ace225403';
const address = '0x5409ed021d9299bf6814279a6a1411a7e866a631';
const bytes32Zeros = '0x0000000000000000000000000000000000000000000000000000000000000000';
it("should return false if the data doesn't pertain to the signature & address", async () => {
return expect(
(zeroEx.exchange as any).isValidSignatureAsync(bytes32Zeros, address, ethSignSignature),
).to.become(false);
});
it("should return false if the address doesn't pertain to the signature & data", async () => {
const validUnrelatedAddress = '0x8b0292b11a196601ed2ce54b665cafeca0347d42';
return expect(
(zeroEx.exchange as any).isValidSignatureAsync(dataHex, validUnrelatedAddress, ethSignSignature),
).to.become(false);
});
it("should return false if the signature doesn't pertain to the dataHex & address", async () => {
const signatureArray = ethSignSignature.split('');
// tslint:disable-next-line:custom-no-magic-numbers
signatureArray[5] = 'C'; // V = 28, instead of 27
const wrongSignature = signatureArray.join('');
return expect((zeroEx.exchange as any).isValidSignatureAsync(dataHex, address, wrongSignature)).to.become(
false,
);
});
it('should return true if the signature does pertain to the dataHex & address', async () => {
return expect((zeroEx.exchange as any).isValidSignatureAsync(dataHex, address, ethSignSignature)).to.become(
true,
);
});
});
describe('#toUnitAmount', () => {
it('should throw if invalid baseUnit amount supplied as argument', () => {
const invalidBaseUnitAmount = new BigNumber(1000000000.4);
const decimals = 6;
expect(() => ZeroEx.toUnitAmount(invalidBaseUnitAmount, decimals)).to.throw(
'amount should be in baseUnits (no decimals), found value: 1000000000.4',
);
});
it('Should return the expected unit amount for the decimals passed in', () => {
const baseUnitAmount = new BigNumber(1000000000);
const decimals = 6;
const unitAmount = ZeroEx.toUnitAmount(baseUnitAmount, decimals);
const expectedUnitAmount = new BigNumber(1000);
expect(unitAmount).to.be.bignumber.equal(expectedUnitAmount);
});
});
describe('#toBaseUnitAmount', () => {
it('Should return the expected base unit amount for the decimals passed in', () => {
const unitAmount = new BigNumber(1000);
const decimals = 6;
const baseUnitAmount = ZeroEx.toBaseUnitAmount(unitAmount, decimals);
const expectedUnitAmount = new BigNumber(1000000000);
expect(baseUnitAmount).to.be.bignumber.equal(expectedUnitAmount);
});
it('should throw if unitAmount has more decimals then specified as the max decimal precision', () => {
const unitAmount = new BigNumber(0.823091);
const decimals = 5;
expect(() => ZeroEx.toBaseUnitAmount(unitAmount, decimals)).to.throw(
'Invalid unit amount: 0.823091 - Too many decimal places',
);
});
});
describe('#awaitTransactionMinedAsync', () => {
beforeEach(async () => {
await blockchainLifecycle.startAsync();
});
afterEach(async () => {
await blockchainLifecycle.revertAsync();
});
it('returns transaction receipt with decoded logs', async () => {
const availableAddresses = await zeroEx.getAvailableAddressesAsync();
const coinbase = availableAddresses[0];
const zrxTokenAddress = tokenUtils.getProtocolTokenAddress();
const erc20ProxyAddress = zeroEx.erc20Proxy.getContractAddress();
const txHash = await zeroEx.erc20Token.setUnlimitedProxyAllowanceAsync(zrxTokenAddress, coinbase);
const txReceiptWithDecodedLogs = await zeroEx.awaitTransactionMinedAsync(txHash);
// tslint:disable-next-line:no-unnecessary-type-assertion
const log = txReceiptWithDecodedLogs.logs[0] as LogWithDecodedArgs<ERC20TokenApprovalEventArgs>;
expect(log.event).to.be.equal(ERC20TokenEvents.Approval);
expect(log.args._owner).to.be.equal(coinbase);
expect(log.args._spender).to.be.equal(erc20ProxyAddress);
expect(log.args._value).to.be.bignumber.equal(zeroEx.erc20Token.UNLIMITED_ALLOWANCE_IN_BASE_UNITS);
});
});
describe('#config', () => {
it('allows to specify exchange contract address', async () => {
const zeroExConfig = {
exchangeContractAddress: ZeroEx.NULL_ADDRESS,
networkId: constants.TESTRPC_NETWORK_ID,
};
const zeroExWithWrongExchangeAddress = new ZeroEx(provider, zeroExConfig);
expect(zeroExWithWrongExchangeAddress.exchange.getContractAddress()).to.be.equal(ZeroEx.NULL_ADDRESS);
});
it('allows to specify erc20Proxy contract address', async () => {
const zeroExConfig = {
erc20ProxyContractAddress: ZeroEx.NULL_ADDRESS,
networkId: constants.TESTRPC_NETWORK_ID,
};
const zeroExWithWrongERC20ProxyAddress = new ZeroEx(provider, zeroExConfig);
expect(zeroExWithWrongERC20ProxyAddress.erc20Proxy.getContractAddress()).to.be.equal(ZeroEx.NULL_ADDRESS);
});
});
});

View File

@@ -1,17 +0,0 @@
import { devConstants } from '@0xproject/dev-utils';
import { runV2MigrationsAsync } from '@0xproject/migrations';
import { provider } from './utils/web3_wrapper';
before('migrate contracts', async function(): Promise<void> {
// HACK: Since the migrations take longer then our global mocha timeout limit
// we manually increase it for this before hook.
const mochaTestTimeoutMs = 20000;
this.timeout(mochaTestTimeoutMs); // tslint:disable-line:no-invalid-this
const txDefaults = {
gas: devConstants.GAS_LIMIT,
from: devConstants.TESTRPC_FIRST_ADDRESS,
};
const artifactsDir = `src/artifacts`;
await runV2MigrationsAsync(provider, artifactsDir, txDefaults);
});

View File

@@ -1,13 +0,0 @@
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(): void {
chai.config.includeStack = true;
chai.use(ChaiBigNumber());
chai.use(dirtyChai);
chai.use(chaiAsPromised);
},
};

View File

@@ -1,9 +0,0 @@
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

@@ -1,9 +0,0 @@
import { artifacts } from '../../src/artifacts';
import { constants } from './constants';
export const tokenUtils = {
getProtocolTokenAddress(): string {
return artifacts.ZRXToken.networks[constants.TESTRPC_NETWORK_ID].address;
},
};

View File

@@ -1,12 +0,0 @@
import { devConstants, web3Factory } from '@0xproject/dev-utils';
import { Web3Wrapper } from '@0xproject/web3-wrapper';
import { Provider } from 'ethereum-types';
const txDefaults = {
from: devConstants.TESTRPC_FIRST_ADDRESS,
gas: devConstants.GAS_LIMIT,
};
const provider: Provider = web3Factory.getRpcProvider({ shouldUseInProcessGanache: true });
const web3Wrapper = new Web3Wrapper(provider);
export { provider, web3Wrapper, txDefaults };

View File

@@ -10,14 +10,13 @@
"scripts": {
"watch_without_deps": "tsc -w",
"lint": "tslint --project .",
"clean": "shx rm -rf lib scripts",
"build": "tsc && copyfiles -u 2 './lib/monorepo_scripts/**/*' ./scripts",
"clean": "shx rm -rf lib",
"build": "tsc",
"test": "yarn run_mocha",
"run_mocha": "mocha --require source-map-support/register --require make-promises-safe lib/test/**/*_test.js --bail --exit",
"test:circleci": "yarn test:coverage",
"test:coverage": "nyc npm run test --all && yarn coverage:report:lcov",
"coverage:report:lcov": "nyc report --reporter=text-lcov > coverage/lcov.info",
"manual:postpublish": "yarn build; node ./scripts/postpublish.js"
"coverage:report:lcov": "nyc report --reporter=text-lcov > coverage/lcov.info"
},
"bin": {
"abi-gen": "bin/abi-gen.js"
@@ -46,7 +45,6 @@
"yargs": "^10.0.3"
},
"devDependencies": {
"@0xproject/monorepo-scripts": "^1.0.5",
"@0xproject/tslint-config": "^1.0.5",
"@types/glob": "5.0.35",
"@types/handlebars": "^4.0.36",

View File

@@ -1,8 +0,0 @@
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

@@ -9,16 +9,15 @@
"types": "lib/src/index.d.ts",
"scripts": {
"watch_without_deps": "tsc -w",
"build": "tsc && copyfiles -u 3 './lib/src/monorepo_scripts/**/*' ./scripts",
"clean": "shx rm -rf lib test_temp scripts",
"build": "tsc",
"clean": "shx rm -rf lib test_temp",
"lint": "tslint --project .",
"run_mocha": "mocha --require source-map-support/register --require make-promises-safe lib/test/**/*_test.js --exit",
"test": "yarn run_mocha",
"rebuild_and_test": "run-s clean build test",
"test:coverage": "nyc npm run test --all && yarn coverage:report:lcov",
"coverage:report:lcov": "nyc report --reporter=text-lcov > coverage/lcov.info",
"test:circleci": "yarn test:coverage",
"manual:postpublish": "yarn build; node ./scripts/postpublish.js"
"test:circleci": "yarn test:coverage"
},
"license": "Apache-2.0",
"repository": {
@@ -30,7 +29,6 @@
},
"homepage": "https://github.com/0xProject/0x-monorepo/packages/assert/README.md",
"devDependencies": {
"@0xproject/monorepo-scripts": "^1.0.5",
"@0xproject/tslint-config": "^1.0.5",
"@types/lodash": "4.14.104",
"@types/mocha": "^2.2.42",

View File

@@ -1,8 +0,0 @@
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

@@ -9,16 +9,15 @@
"types": "lib/src/index.d.ts",
"scripts": {
"watch_without_deps": "tsc -w",
"build": "tsc && copyfiles -u 3 './lib/src/monorepo_scripts/**/*' ./scripts",
"clean": "shx rm -rf lib scripts",
"build": "tsc",
"clean": "shx rm -rf lib",
"test": "yarn run_mocha",
"rebuild_and_test": "run-s clean build test",
"test:circleci": "yarn test:coverage",
"run_mocha": "mocha --require source-map-support/register --require make-promises-safe lib/test/**/*_test.js --bail --exit",
"test:coverage": "nyc npm run test --all && yarn coverage:report:lcov",
"coverage:report:lcov": "nyc report --reporter=text-lcov > coverage/lcov.info",
"lint": "tslint --project . --exclude **/src/contract_wrappers/**/*",
"manual:postpublish": "yarn build; node ./scripts/postpublish.js"
"lint": "tslint --project . --exclude **/src/contract_wrappers/**/*"
},
"license": "Apache-2.0",
"repository": {
@@ -30,7 +29,6 @@
},
"homepage": "https://github.com/0xProject/0x-monorepo/packages/base-contract/README.md",
"devDependencies": {
"@0xproject/monorepo-scripts": "^1.0.5",
"@0xproject/tslint-config": "^1.0.5",
"@types/lodash": "4.14.104",
"chai": "^4.0.1",

View File

@@ -1,8 +0,0 @@
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

@@ -5,6 +5,10 @@
{
"note": "Updated for SRA v2",
"pr": 974
},
{
"note": "Stopped exporting `Order` type",
"pr": 924
}
]
},

View File

@@ -16,8 +16,8 @@
"types": "lib/src/index.d.ts",
"scripts": {
"watch_without_deps": "tsc -w",
"build": "tsc && copyfiles -u 3 './lib/src/monorepo_scripts/**/*' ./scripts",
"clean": "shx rm -rf lib test_temp scripts",
"build": "tsc",
"clean": "shx rm -rf lib test_temp generated_docs",
"copy_test_fixtures": "copyfiles -u 2 './test/fixtures/**/*.json' ./lib/test/fixtures",
"lint": "tslint --project .",
"run_mocha": "mocha --require source-map-support/register --require make-promises-safe lib/test/**/*_test.js --exit",
@@ -26,18 +26,11 @@
"test:coverage": "nyc npm run test --all && yarn coverage:report:lcov",
"coverage:report:lcov": "nyc report --reporter=text-lcov > coverage/lcov.info",
"test:circleci": "yarn test:coverage",
"manual:postpublish": "yarn build; node ./scripts/postpublish.js",
"docs:stage": "node scripts/stage_docs.js",
"docs:json": "typedoc --excludePrivate --excludeExternals --target ES5 --json $JSON_FILE_PATH $PROJECT_FILES",
"upload_docs_json": "aws s3 cp generated_docs/index.json $S3_URL --profile 0xproject --grants read=uri=http://acs.amazonaws.com/groups/global/AllUsers --content-type application/json"
"docs:json": "typedoc --excludePrivate --excludeExternals --target ES5 --json $JSON_FILE_PATH $PROJECT_FILES"
},
"config": {
"postpublish": {
"assets": [],
"docPublishConfigs": {
"s3BucketPath": "s3://doc-jsons/connect/",
"s3StagingBucketPath": "s3://staging-doc-jsons/connect/"
}
"assets": []
}
},
"repository": {
@@ -63,7 +56,6 @@
"websocket": "^1.0.25"
},
"devDependencies": {
"@0xproject/monorepo-scripts": "^1.0.5",
"@0xproject/tslint-config": "^1.0.5",
"@types/fetch-mock": "^6.0.3",
"@types/lodash": "4.14.104",
@@ -84,7 +76,7 @@
"nyc": "^11.0.1",
"shx": "^0.2.2",
"tslint": "5.11.0",
"typedoc": "~0.8.0",
"typedoc": "0.12.0",
"typescript": "3.0.1"
},
"publishConfig": {

View File

@@ -11,9 +11,13 @@ export {
OrderbookResponse,
OrdersRequestOpts,
PagedRequestOpts,
AssetPairsItem,
AssetPairsRequestOpts,
Asset,
RequestOpts,
AssetPairsResponse,
FeeRecipientsResponse,
APIOrder,
OrdersResponse,
PaginatedCollection,
} from './types';
export { Order, SignedOrder } from '@0xproject/types';
export { SignedOrder } from '@0xproject/types';

View File

@@ -1,8 +0,0 @@
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

@@ -1,8 +0,0 @@
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.publishDocsToStagingAsync(packageJSON, tsConfigJSON, cwd);

View File

@@ -3,8 +3,18 @@
"version": "1.0.1-rc.4",
"changes": [
{
"pr": 975,
"note": "Added Transaction Encoder for use with 0x Exchange executeTransaction"
"note":
"Export missing types: `TransactionEncoder`, `ContractAbi`, `JSONRPCRequestPayload`, `JSONRPCResponsePayload`, `JSONRPCErrorCallback`, `AbiDefinition`, `FunctionAbi`, `EventAbi`, `EventParameter`, `DecodedLogArgs`, `MethodAbi`, `ConstructorAbi`, `FallbackAbi`, `DataItem`, `ConstructorStateMutability`, `StateMutability` & `ExchangeSignatureValidatorApprovalEventArgs`",
"pr": 924
},
{
"note":
"Remove superfluous exported types: `ContractEvent`, `Token`, `OrderFillRequest`, `ContractEventArgs`, `LogEvent`, `OnOrderStateChangeCallback`, `ECSignature`, `OrderStateValid`, `OrderStateInvalid`, `OrderState`, `FilterObject`, `TransactionReceipt` & `TransactionReceiptWithDecodedLogs`",
"pr": 924
},
{
"note": "Added Transaction Encoder for use with 0x Exchange executeTransaction",
"pr": 975
}
]
},

View File

@@ -12,7 +12,7 @@
"types": "lib/src/index.d.ts",
"scripts": {
"watch_without_deps": "yarn pre_build && tsc -w",
"build": "yarn pre_build && tsc && copyfiles -u 3 './lib/src/monorepo_scripts/**/*' ./scripts",
"build": "yarn pre_build && tsc",
"pre_build": "run-s update_artifacts_v2_beta update_artifacts_v2 generate_contract_wrappers copy_artifacts",
"generate_contract_wrappers": "abi-gen --abis 'src/artifacts/@(Exchange|DummyERC20Token|DummyERC721Token|ZRXToken|ERC20Token|ERC721Token|WETH9|ERC20Proxy|ERC721Proxy|Forwarder).json' --template ../contract_templates/contract.handlebars --partials '../contract_templates/partials/**/*.handlebars' --output src/contract_wrappers/generated --backend ethers",
"lint": "tslint --project . --exclude **/src/contract_wrappers/**/* --exclude **/lib/**/*",
@@ -24,13 +24,16 @@
"update_artifacts_v2_beta": "for i in ${npm_package_config_contracts_v2_beta}; do copyfiles -u 4 ../migrations/artifacts/2.0.0-beta-testnet/$i.json src/artifacts; done;",
"update_artifacts_v2": "for i in ${npm_package_config_contracts_v2}; do copyfiles -u 4 ../migrations/artifacts/2.0.0/$i.json src/artifacts; done;",
"copy_artifacts": "copyfiles -u 2 './src/artifacts/**/*.json' ./lib/src/artifacts",
"clean": "shx rm -rf _bundles lib test_temp scripts test/artifacts src/contract_wrappers/generated src/artifacts",
"clean": "shx rm -rf _bundles lib test_temp test/artifacts src/contract_wrappers/generated src/artifacts generated_docs",
"run_mocha": "mocha --require source-map-support/register --require make-promises-safe lib/test/**/*_test.js lib/test/global_hooks.js --timeout 10000 --bail --exit",
"manual:postpublish": "yarn build; node ./scripts/postpublish.js"
"docs:json": "typedoc --excludePrivate --excludeExternals --target ES5 --json $JSON_FILE_PATH $PROJECT_FILES"
},
"config": {
"contracts_v2_beta": "AssetProxyOwner Exchange ERC20Proxy ERC20Token ERC721Proxy ERC721Token WETH9 ZRXToken Forwarder OrderValidator",
"contracts_v2": "DummyERC20Token DummyERC721Token"
"contracts_v2": "DummyERC20Token DummyERC721Token",
"postpublish": {
"assets": []
}
},
"repository": {
"type": "git",
@@ -44,8 +47,6 @@
"@0xproject/abi-gen": "^1.0.5",
"@0xproject/dev-utils": "^1.0.4",
"@0xproject/migrations": "^1.0.4",
"@0xproject/monorepo-scripts": "^1.0.5",
"@0xproject/sol-compiler": "^1.0.5",
"@0xproject/subproviders": "^1.0.5",
"@0xproject/tslint-config": "^1.0.5",
"@types/lodash": "4.14.104",
@@ -68,6 +69,7 @@
"sinon": "^4.0.0",
"source-map-support": "^0.5.0",
"tslint": "5.11.0",
"typedoc": "0.12.0",
"typescript": "3.0.1",
"web3-provider-engine": "14.0.6"
},

View File

@@ -1,4 +1,4 @@
import { ContractArtifact } from '@0xproject/sol-compiler';
import { ContractArtifact } from 'ethereum-types';
import * as DummyERC20Token from './artifacts/DummyERC20Token.json';
import * as DummyERC721Token from './artifacts/DummyERC721Token.json';

View File

@@ -1,6 +1,6 @@
import { ContractArtifact } from '@0xproject/sol-compiler';
import { AbiDecoder, intervalUtils, logUtils } from '@0xproject/utils';
import { Web3Wrapper } from '@0xproject/web3-wrapper';
import { ContractArtifact } from 'ethereum-types';
import { BlockParamLiteral, ContractAbi, FilterObject, LogEntry, LogWithDecodedArgs, RawLog } from 'ethereum-types';
import { Block, BlockAndLogStreamer, Log } from 'ethereumjs-blockstream';
import * as _ from 'lodash';

View File

@@ -16,6 +16,13 @@ export class ERC20ProxyWrapper extends ContractWrapper {
public abi: ContractAbi = artifacts.ERC20Proxy.compilerOutput.abi;
private _erc20ProxyContractIfExists?: ERC20ProxyContract;
private _contractAddressIfExists?: string;
/**
* Instantiate ERC20ProxyWrapper
* @param web3Wrapper Web3Wrapper instance to use
* @param networkId Desired networkId
* @param contractAddressIfExists The contract address to use. This is usually pulled from
* the artifacts but needs to be specified when using with your own custom testnet.
*/
constructor(web3Wrapper: Web3Wrapper, networkId: number, contractAddressIfExists?: string) {
super(web3Wrapper, networkId);
this._contractAddressIfExists = contractAddressIfExists;

View File

@@ -34,6 +34,13 @@ export class ERC20TokenWrapper extends ContractWrapper {
public UNLIMITED_ALLOWANCE_IN_BASE_UNITS = constants.UNLIMITED_ALLOWANCE_IN_BASE_UNITS;
private _tokenContractsByAddress: { [address: string]: ERC20TokenContract };
private _erc20ProxyWrapper: ERC20ProxyWrapper;
/**
* Instantiate ERC20TokenWrapper
* @param web3Wrapper Web3Wrapper instance to use
* @param networkId Desired networkId
* @param erc20ProxyWrapper The ERC20ProxyWrapper instance to use
* @param blockPollingIntervalMs The block polling interval to use for active subscriptions
*/
constructor(
web3Wrapper: Web3Wrapper,
networkId: number,

View File

@@ -16,6 +16,13 @@ export class ERC721ProxyWrapper extends ContractWrapper {
public abi: ContractAbi = artifacts.ERC20Proxy.compilerOutput.abi;
private _erc721ProxyContractIfExists?: ERC721ProxyContract;
private _contractAddressIfExists?: string;
/**
* Instantiate ERC721ProxyWrapper
* @param web3Wrapper Web3Wrapper instance to use
* @param networkId Desired networkId
* @param contractAddressIfExists The contract address to use. This is usually pulled from
* the artifacts but needs to be specified when using with your own custom testnet.
*/
constructor(web3Wrapper: Web3Wrapper, networkId: number, contractAddressIfExists?: string) {
super(web3Wrapper, networkId);
this._contractAddressIfExists = contractAddressIfExists;

View File

@@ -33,6 +33,13 @@ export class ERC721TokenWrapper extends ContractWrapper {
public abi: ContractAbi = artifacts.ERC721Token.compilerOutput.abi;
private _tokenContractsByAddress: { [address: string]: ERC721TokenContract };
private _erc721ProxyWrapper: ERC721ProxyWrapper;
/**
* Instantiate ERC721TokenWrapper
* @param web3Wrapper Web3Wrapper instance to use
* @param networkId Desired networkId
* @param erc721ProxyWrapper The ERC721ProxyWrapper instance to use
* @param blockPollingIntervalMs The block polling interval to use for active subscriptions
*/
constructor(
web3Wrapper: Web3Wrapper,
networkId: number,

View File

@@ -24,6 +24,13 @@ export class EtherTokenWrapper extends ContractWrapper {
[address: string]: WETH9Contract;
} = {};
private _erc20TokenWrapper: ERC20TokenWrapper;
/**
* Instantiate EtherTokenWrapper.
* @param web3Wrapper Web3Wrapper instance to use
* @param networkId Desired networkId
* @param erc20TokenWrapper The ERC20TokenWrapper instance to use
* @param blockPollingIntervalMs The block polling interval to use for active subscriptions
*/
constructor(
web3Wrapper: Web3Wrapper,
networkId: number,

View File

@@ -35,6 +35,16 @@ export class ExchangeWrapper extends ContractWrapper {
private _exchangeContractIfExists?: ExchangeContract;
private _contractAddressIfExists?: string;
private _zrxContractAddressIfExists?: string;
/**
* Instantiate ExchangeWrapper
* @param web3Wrapper Web3Wrapper instance to use
* @param networkId Desired networkId
* @param contractAddressIfExists The exchange contract address to use. This is usually pulled from
* the artifacts but needs to be specified when using with your own custom testnet.
* @param zrxContractAddressIfExists The ZRXToken contract address to use. This is usually pulled from
* the artifacts but needs to be specified when using with your own custom testnet.
* @param blockPollingIntervalMs The block polling interval to use for active subscriptions
*/
constructor(
web3Wrapper: Web3Wrapper,
networkId: number,
@@ -666,6 +676,7 @@ export class ExchangeWrapper extends ContractWrapper {
* @param leftSignedOrder First order to match.
* @param rightSignedOrder Second order to match.
* @param takerAddress The address that sends the transaction and gets the spread.
* @param orderTransactionOpts Optional arguments this method accepts.
* @return Transaction hash.
*/
@decorators.asyncZeroExErrorHandler
@@ -724,6 +735,7 @@ export class ExchangeWrapper extends ContractWrapper {
* @param signerAddress Address that should have signed the given hash.
* @param signature Proof that the hash has been signed by signer.
* @param senderAddress Address that should send the transaction.
* @param orderTransactionOpts Optional arguments this method accepts.
* @returns Transaction hash.
*/
@decorators.asyncZeroExErrorHandler
@@ -902,7 +914,7 @@ export class ExchangeWrapper extends ContractWrapper {
/**
* Cancel a given order.
* @param order An object that conforms to the Order or SignedOrder interface. The order you would like to cancel.
* @param transactionOpts Optional arguments this method accepts.
* @param orderTransactionOpts Optional arguments this method accepts.
* @return Transaction hash.
*/
@decorators.asyncZeroExErrorHandler

View File

@@ -7,45 +7,45 @@ export { ERC20ProxyWrapper } from './contract_wrappers/erc20_proxy_wrapper';
export { ERC721ProxyWrapper } from './contract_wrappers/erc721_proxy_wrapper';
export { ForwarderWrapper } from './contract_wrappers/forwarder_wrapper';
export { TransactionEncoder } from './utils/transaction_encoder';
export {
ContractWrappersError,
EventCallback,
ContractEvent,
Token,
IndexedFilterValues,
BlockRange,
OrderFillRequest,
ContractEventArgs,
ContractWrappersConfig,
MethodOpts,
OrderTransactionOpts,
TransactionOpts,
LogEvent,
DecodedLogEvent,
OnOrderStateChangeCallback,
OrderStatus,
OrderInfo,
EventCallback,
DecodedLogEvent,
} from './types';
export {
Order,
SignedOrder,
ECSignature,
OrderStateValid,
OrderStateInvalid,
OrderState,
AssetProxyId,
} from '@0xproject/types';
export { Order, SignedOrder, AssetProxyId } from '@0xproject/types';
export {
BlockParamLiteral,
FilterObject,
BlockParam,
ContractEventArg,
LogWithDecodedArgs,
Provider,
TransactionReceipt,
TransactionReceiptWithDecodedLogs,
ContractAbi,
JSONRPCRequestPayload,
JSONRPCResponsePayload,
JSONRPCErrorCallback,
AbiDefinition,
LogWithDecodedArgs,
FunctionAbi,
EventAbi,
EventParameter,
DecodedLogArgs,
MethodAbi,
ConstructorAbi,
FallbackAbi,
DataItem,
ConstructorStateMutability,
StateMutability,
} from 'ethereum-types';
export {
@@ -75,6 +75,7 @@ export {
export {
ExchangeCancelUpToEventArgs,
ExchangeAssetProxyRegisteredEventArgs,
ExchangeSignatureValidatorApprovalEventArgs,
ExchangeFillEventArgs,
ExchangeCancelEventArgs,
ExchangeEventArgs,

View File

@@ -1,8 +0,0 @@
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

@@ -1,8 +1,8 @@
import { assert as sharedAssert } from '@0xproject/assert';
// HACK: We need those two unused imports because they're actually used by sharedAssert which gets injected here
import { Schema } from '@0xproject/json-schemas'; // tslint:disable-line:no-unused-variable
import { assetDataUtils, isValidSignatureAsync } from '@0xproject/order-utils';
import { ECSignature, Order } from '@0xproject/types'; // tslint:disable-line:no-unused-variable
import { signatureUtils, assetDataUtils } from '@0xproject/order-utils';
import { Order } from '@0xproject/types'; // tslint:disable-line:no-unused-variable
import { BigNumber } from '@0xproject/utils'; // tslint:disable-line:no-unused-variable
import { Web3Wrapper } from '@0xproject/web3-wrapper';
import { Provider } from 'ethereum-types';
@@ -18,7 +18,7 @@ export const assert = {
signature: string,
signerAddress: string,
): Promise<void> {
const isValid = await isValidSignatureAsync(provider, orderHash, signature, signerAddress);
const isValid = await signatureUtils.isValidSignatureAsync(provider, orderHash, signature, signerAddress);
sharedAssert.assert(isValid, `Expected order with hash '${orderHash}' to have a valid signature`);
},
isValidSubscriptionToken(variableName: string, subscriptionToken: string): void {

View File

@@ -1,5 +1,5 @@
import { schemas } from '@0xproject/json-schemas';
import { EIP712Schema, EIP712Types, EIP712Utils } from '@0xproject/order-utils';
import { EIP712Schema, EIP712Types, eip712Utils } from '@0xproject/order-utils';
import { Order, SignedOrder } from '@0xproject/types';
import { BigNumber } from '@0xproject/utils';
import _ = require('lodash');
@@ -41,11 +41,11 @@ export class TransactionEncoder {
signerAddress,
data,
};
const executeTransactionHashBuff = EIP712Utils.structHash(
const executeTransactionHashBuff = eip712Utils.structHash(
EIP712_ZEROEX_TRANSACTION_SCHEMA,
executeTransactionData,
);
const eip721MessageBuffer = EIP712Utils.createEIP712Message(executeTransactionHashBuff, exchangeAddress);
const eip721MessageBuffer = eip712Utils.createEIP712Message(executeTransactionHashBuff, exchangeAddress);
const messageHex = `0x${eip721MessageBuffer.toString('hex')}`;
return messageHex;
}

View File

@@ -1,4 +1,4 @@
import { orderFactory } from '@0xproject/order-utils';
import { orderFactory } from '@0xproject/order-utils/lib/src/order_factory';
import * as chai from 'chai';
import * as _ from 'lodash';
import 'mocha';

View File

@@ -11,12 +11,13 @@ import {
BlockRange,
ContractWrappers,
ContractWrappersError,
DecodedLogEvent,
ERC20TokenApprovalEventArgs,
ERC20TokenEvents,
ERC20TokenTransferEventArgs,
} from '../src';
import { DecodedLogEvent } from '../src/types';
import { chaiSetup } from './utils/chai_setup';
import { constants } from './utils/constants';
import { tokenUtils } from './utils/token_utils';

View File

@@ -11,12 +11,12 @@ import {
BlockRange,
ContractWrappers,
ContractWrappersError,
DecodedLogEvent,
ERC721TokenApprovalEventArgs,
ERC721TokenApprovalForAllEventArgs,
ERC721TokenEvents,
ERC721TokenTransferEventArgs,
} from '../src';
import { DecodedLogEvent } from '../src/types';
import { chaiSetup } from './utils/chai_setup';
import { constants } from './utils/constants';

View File

@@ -10,7 +10,6 @@ import {
BlockRange,
ContractWrappers,
ContractWrappersError,
DecodedLogEvent,
WETH9ApprovalEventArgs,
WETH9DepositEventArgs,
WETH9Events,
@@ -18,6 +17,8 @@ import {
WETH9WithdrawalEventArgs,
} from '../src';
import { DecodedLogEvent } from '../src/types';
import { chaiSetup } from './utils/chai_setup';
import { constants } from './utils/constants';
import { tokenUtils } from './utils/token_utils';

View File

@@ -7,14 +7,8 @@ import * as chai from 'chai';
import { BlockParamLiteral } from 'ethereum-types';
import 'mocha';
import {
ContractWrappers,
DecodedLogEvent,
ExchangeCancelEventArgs,
ExchangeEvents,
ExchangeFillEventArgs,
OrderStatus,
} from '../src';
import { ContractWrappers, ExchangeCancelEventArgs, ExchangeEvents, ExchangeFillEventArgs, OrderStatus } from '../src';
import { DecodedLogEvent } from '../src/types';
import { chaiSetup } from './utils/chai_setup';
import { constants } from './utils/constants';

View File

@@ -7,14 +7,8 @@ import * as chai from 'chai';
import { BlockParamLiteral } from 'ethereum-types';
import 'mocha';
import {
ContractWrappers,
DecodedLogEvent,
ExchangeCancelEventArgs,
ExchangeEvents,
ExchangeFillEventArgs,
OrderStatus,
} from '../src';
import { ContractWrappers, ExchangeCancelEventArgs, ExchangeEvents, ExchangeFillEventArgs, OrderStatus } from '../src';
import { DecodedLogEvent } from '../src/types';
import { chaiSetup } from './utils/chai_setup';
import { constants } from './utils/constants';

View File

@@ -5,7 +5,8 @@ import * as _ from 'lodash';
import 'mocha';
import * as Sinon from 'sinon';
import { ContractWrappers, DecodedLogEvent, ERC20TokenApprovalEventArgs, ERC20TokenEvents, Token } from '../src';
import { ContractWrappers, ERC20TokenApprovalEventArgs, ERC20TokenEvents } from '../src';
import { DecodedLogEvent } from '../src/types';
import { chaiSetup } from './utils/chai_setup';
import { constants } from './utils/constants';

View File

@@ -1,6 +1,6 @@
import { BlockchainLifecycle } from '@0xproject/dev-utils';
import { FillScenarios } from '@0xproject/fill-scenarios';
import { assetDataUtils, ecSignOrderHashAsync, generatePseudoRandomSalt, orderHashUtils } from '@0xproject/order-utils';
import { assetDataUtils, signatureUtils, generatePseudoRandomSalt, orderHashUtils } from '@0xproject/order-utils';
import { SignedOrder, SignerType } from '@0xproject/types';
import { BigNumber } from '@0xproject/utils';
import 'mocha';
@@ -80,7 +80,7 @@ describe('TransactionEncoder', () => {
): Promise<void> => {
const salt = generatePseudoRandomSalt();
const encodedTransaction = encoder.getTransactionHex(data, salt, signerAddress);
const signature = await ecSignOrderHashAsync(
const signature = await signatureUtils.ecSignOrderHashAsync(
provider,
encodedTransaction,
signerAddress,

View File

@@ -1,9 +1,9 @@
// tslint:disable:no-consecutive-blank-lines ordered-imports align trailing-comma whitespace class-name
// tslint:disable:no-unused-variable
// tslint:disable:no-unbound-method
import { BaseContract } from '@0xproject/base-contract';
import { ContractArtifact } from '@0xproject/sol-compiler';
import { BlockParam, BlockParamLiteral, CallData, ContractAbi, DataItem, DecodedLogArgs, MethodAbi, Provider, TxData, TxDataPayable } from 'ethereum-types';
import { BigNumber, classUtils, logUtils, promisify } from '@0xproject/utils';
import { BlockParam, CallData, ContractAbi, ContractArtifact, DecodedLogArgs, MethodAbi, Provider, TxData, TxDataPayable } from 'ethereum-types';
import { BigNumber, classUtils, logUtils } from '@0xproject/utils';
import { Web3Wrapper } from '@0xproject/web3-wrapper';
import * as ethers from 'ethers';
import * as _ from 'lodash';
@@ -85,3 +85,4 @@ export class {{contractName}}Contract extends BaseContract {
classUtils.bindAll(this, ['_ethersInterfacesByFunctionSignature', 'address', 'abi', '_web3Wrapper']);
}
} // tslint:disable:max-file-line-count
// tslint:enable:no-unbound-method

View File

@@ -55,6 +55,7 @@
"@0xproject/sol-cov": "^2.0.0",
"@0xproject/subproviders": "^1.0.5",
"@0xproject/tslint-config": "^1.0.5",
"@0xproject/sol-compiler": "^1.0.5",
"@types/bn.js": "^4.11.0",
"@types/ethereumjs-abi": "^0.6.0",
"@types/lodash": "4.14.104",
@@ -78,7 +79,6 @@
"dependencies": {
"@0xproject/base-contract": "^2.0.0-rc.1",
"@0xproject/order-utils": "^1.0.1-rc.3",
"@0xproject/sol-compiler": "^1.0.5",
"@0xproject/types": "^1.0.1-rc.4",
"@0xproject/typescript-typings": "^1.0.4",
"@0xproject/utils": "^1.0.5",

View File

@@ -1,5 +1,5 @@
import { BlockchainLifecycle } from '@0xproject/dev-utils';
import { assetDataUtils, EIP712Utils, orderHashUtils } from '@0xproject/order-utils';
import { assetDataUtils, eip712Utils, orderHashUtils } from '@0xproject/order-utils';
import { SignedOrder } from '@0xproject/types';
import { BigNumber } from '@0xproject/utils';
import * as chai from 'chai';
@@ -109,7 +109,7 @@ describe('Exchange libs', () => {
describe('getDomainSeparatorSchema', () => {
it('should output the correct domain separator schema hash', async () => {
const domainSeparatorSchema = await libs.getDomainSeparatorSchemaHash.callAsync();
const domainSchemaBuffer = EIP712Utils._getDomainSeparatorSchemaBuffer();
const domainSchemaBuffer = eip712Utils._getDomainSeparatorSchemaBuffer();
const schemaHashHex = `0x${domainSchemaBuffer.toString('hex')}`;
expect(schemaHashHex).to.be.equal(domainSeparatorSchema);
});

View File

@@ -1,5 +1,5 @@
import { BlockchainLifecycle } from '@0xproject/dev-utils';
import { addSignedMessagePrefix, assetDataUtils, orderHashUtils } from '@0xproject/order-utils';
import { assetDataUtils, orderHashUtils, signatureUtils } from '@0xproject/order-utils';
import { RevertReason, SignatureType, SignedOrder, SignerType } from '@0xproject/types';
import * as chai from 'chai';
import { LogWithDecodedArgs } from 'ethereum-types';
@@ -213,7 +213,10 @@ describe('MixinSignatureValidator', () => {
it('should return true when SignatureType=EthSign and signature is valid', async () => {
// Create EthSign signature
const orderHashHex = orderHashUtils.getOrderHashHex(signedOrder);
const orderHashWithEthSignPrefixHex = addSignedMessagePrefix(orderHashHex, SignerType.Default);
const orderHashWithEthSignPrefixHex = signatureUtils.addSignedMessagePrefix(
orderHashHex,
SignerType.Default,
);
const orderHashWithEthSignPrefixBuffer = ethUtil.toBuffer(orderHashWithEthSignPrefixHex);
const ecSignature = ethUtil.ecsign(orderHashWithEthSignPrefixBuffer, signerPrivateKey);
// Create 0x signature from EthSign signature
@@ -236,7 +239,10 @@ describe('MixinSignatureValidator', () => {
it('should return false when SignatureType=EthSign and signature is invalid', async () => {
// Create EthSign signature
const orderHashHex = orderHashUtils.getOrderHashHex(signedOrder);
const orderHashWithEthSignPrefixHex = addSignedMessagePrefix(orderHashHex, SignerType.Default);
const orderHashWithEthSignPrefixHex = signatureUtils.addSignedMessagePrefix(
orderHashHex,
SignerType.Default,
);
const orderHashWithEthSignPrefixBuffer = ethUtil.toBuffer(orderHashWithEthSignPrefixHex);
const ecSignature = ethUtil.ecsign(orderHashWithEthSignPrefixBuffer, signerPrivateKey);
// Create 0x signature from EthSign signature
@@ -385,7 +391,7 @@ describe('MixinSignatureValidator', () => {
it('should return true when SignatureType=Trezor and signature is valid', async () => {
// Create Trezor signature
const orderHashHex = orderHashUtils.getOrderHashHex(signedOrder);
const orderHashWithTrezorPrefixHex = addSignedMessagePrefix(orderHashHex, SignerType.Trezor);
const orderHashWithTrezorPrefixHex = signatureUtils.addSignedMessagePrefix(orderHashHex, SignerType.Trezor);
const orderHashWithTrezorPrefixBuffer = ethUtil.toBuffer(orderHashWithTrezorPrefixHex);
const ecSignature = ethUtil.ecsign(orderHashWithTrezorPrefixBuffer, signerPrivateKey);
// Create 0x signature from Trezor signature
@@ -408,7 +414,7 @@ describe('MixinSignatureValidator', () => {
it('should return false when SignatureType=Trezor and signature is invalid', async () => {
// Create Trezor signature
const orderHashHex = orderHashUtils.getOrderHashHex(signedOrder);
const orderHashWithTrezorPrefixHex = addSignedMessagePrefix(orderHashHex, SignerType.Trezor);
const orderHashWithTrezorPrefixHex = signatureUtils.addSignedMessagePrefix(orderHashHex, SignerType.Trezor);
const orderHashWithTrezorPrefixBuffer = ethUtil.toBuffer(orderHashWithTrezorPrefixHex);
const ecSignature = ethUtil.ecsign(orderHashWithTrezorPrefixBuffer, signerPrivateKey);
// Create 0x signature from Trezor signature

View File

@@ -1,4 +1,5 @@
import { crypto, generatePseudoRandomSalt } from '@0xproject/order-utils';
import { generatePseudoRandomSalt } from '@0xproject/order-utils';
import { crypto } from '@0xproject/order-utils/lib/src/crypto';
export const addressUtils = {
generatePseudoRandomAddress(): string {

View File

@@ -1,4 +1,4 @@
import { ContractArtifact } from '@0xproject/sol-compiler';
import { ContractArtifact } from 'ethereum-types';
import * as AssetProxyOwner from '../../artifacts/AssetProxyOwner.json';
import * as DummyERC20Token from '../../artifacts/DummyERC20Token.json';

View File

@@ -20,6 +20,13 @@ export class ERC20Wrapper {
private readonly _dummyTokenContracts: DummyERC20TokenContract[];
private _proxyContract?: ERC20ProxyContract;
private _proxyIdIfExists?: string;
/**
* Instanitates an ERC20Wrapper
* @param provider Web3 provider to use for all JSON RPC requests
* @param tokenOwnerAddresses Addresses that we want to endow as owners for dummy ERC20 tokens
* @param contractOwnerAddress Desired owner of the contract
* Instance of ERC20Wrapper
*/
constructor(provider: Provider, tokenOwnerAddresses: string[], contractOwnerAddress: string) {
this._dummyTokenContracts = [];
this._web3Wrapper = new Web3Wrapper(provider);

View File

@@ -1,8 +1,8 @@
import { ContractArtifact } from '@0xproject/sol-compiler';
import { AbiDecoder, BigNumber } from '@0xproject/utils';
import { Web3Wrapper } from '@0xproject/web3-wrapper';
import {
AbiDefinition,
ContractArtifact,
DecodedLogArgs,
LogEntry,
LogWithDecodedArgs,

View File

@@ -1,4 +1,4 @@
import { EIP712Schema, EIP712Types, EIP712Utils, generatePseudoRandomSalt } from '@0xproject/order-utils';
import { EIP712Schema, EIP712Types, eip712Utils, generatePseudoRandomSalt } from '@0xproject/order-utils';
import { SignatureType } from '@0xproject/types';
import * as ethUtil from 'ethereumjs-util';
@@ -31,11 +31,11 @@ export class TransactionFactory {
signerAddress,
data,
};
const executeTransactionHashBuff = EIP712Utils.structHash(
const executeTransactionHashBuff = eip712Utils.structHash(
EIP712_ZEROEX_TRANSACTION_SCHEMA,
executeTransactionData,
);
const txHash = EIP712Utils.createEIP712Message(executeTransactionHashBuff, this._exchangeAddress);
const txHash = eip712Utils.createEIP712Message(executeTransactionHashBuff, this._exchangeAddress);
const signature = signingUtils.signMessage(txHash, this._privateKey, signatureType);
const signedTx = {
exchangeAddress: this._exchangeAddress,

View File

@@ -9,16 +9,15 @@
"types": "lib/src/index.d.ts",
"scripts": {
"watch_without_deps": "tsc -w",
"build": "tsc && copyfiles -u 3 './lib/src/monorepo_scripts/**/*' ./scripts",
"build": "tsc",
"test": "yarn run_mocha",
"rebuild_and_test": "run-s clean build test",
"test:circleci": "yarn test:coverage",
"run_mocha": "mocha --require source-map-support/register --require make-promises-safe lib/test/**/*_test.js --bail --exit",
"test:coverage": "nyc npm run test --all && yarn coverage:report:lcov",
"coverage:report:lcov": "nyc report --reporter=text-lcov > coverage/lcov.info",
"clean": "shx rm -rf lib scripts",
"lint": "tslint --project .",
"manual:postpublish": "yarn build; node ./scripts/postpublish.js"
"clean": "shx rm -rf lib",
"lint": "tslint --project ."
},
"license": "Apache-2.0",
"repository": {
@@ -30,7 +29,6 @@
},
"homepage": "https://github.com/0xProject/0x-monorepo/packages/dev-utils/README.md",
"devDependencies": {
"@0xproject/monorepo-scripts": "^1.0.5",
"@0xproject/tslint-config": "^1.0.5",
"@types/lodash": "4.14.104",
"@types/mocha": "^2.2.42",

View File

@@ -1,8 +0,0 @@
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

@@ -46,6 +46,10 @@
{
"note": "Add `TransactionReceiptStatus` type",
"pr": 812
},
{
"note": "Add Artifact types: `CompilerSettings`, `CompilerOptions`, `OutputField`",
"pr": 924
}
]
},

View File

@@ -9,20 +9,14 @@
"types": "lib/index.d.ts",
"scripts": {
"watch_without_deps": "tsc -w",
"build": "tsc && copyfiles -u 2 './lib/monorepo_scripts/**/*' ./scripts",
"clean": "shx rm -rf lib scripts",
"build": "tsc",
"clean": "shx rm -rf lib generated_docs",
"lint": "tslint --project .",
"manual:postpublish": "yarn build; node ./scripts/postpublish.js",
"docs:stage": "node scripts/stage_docs.js",
"docs:json": "typedoc --excludePrivate --excludeExternals --target ES5 --json $JSON_FILE_PATH $PROJECT_FILES",
"upload_docs_json": "aws s3 cp generated_docs/index.json $S3_URL --profile 0xproject --grants read=uri=http://acs.amazonaws.com/groups/global/AllUsers --content-type application/json"
"docs:json": "typedoc --excludePrivate --excludeExternals --target ES5 --json $JSON_FILE_PATH $PROJECT_FILES"
},
"config": {
"postpublish": {
"docPublishConfigs": {
"s3BucketPath": "s3://doc-jsons/ethereum-types/",
"s3StagingBucketPath": "s3://staging-doc-jsons/ethereum-types/"
}
"assets": []
}
},
"license": "Apache-2.0",
@@ -35,7 +29,6 @@
},
"homepage": "https://github.com/0xProject/0x-monorepo/packages/ethereum-types/README.md",
"devDependencies": {
"@0xproject/monorepo-scripts": "^1.0.5",
"@0xproject/tslint-config": "^1.0.5",
"copyfiles": "^2.0.0",
"make-promises-safe": "^1.1.0",

View File

@@ -20,7 +20,7 @@ export type ConstructorStateMutability = 'nonpayable' | 'payable';
export type StateMutability = 'pure' | 'view' | ConstructorStateMutability;
export interface MethodAbi {
type: AbiType.Function;
type: 'function'; // We hardcode this here b/c doc pages cannot render an enum value
name: string;
inputs: DataItem[];
outputs: DataItem[];
@@ -30,14 +30,14 @@ export interface MethodAbi {
}
export interface ConstructorAbi {
type: AbiType.Constructor;
type: 'constructor'; // We hardcode this here b/c doc pages cannot render an enum value
inputs: DataItem[];
payable: boolean;
stateMutability: ConstructorStateMutability;
}
export interface FallbackAbi {
type: AbiType.Fallback;
type: 'fallback'; // We hardcode this here b/c doc pages cannot render an enum value
payable: boolean;
}
@@ -46,7 +46,7 @@ export interface EventParameter extends DataItem {
}
export interface EventAbi {
type: AbiType.Event;
type: 'event'; // We hardcode this here b/c doc pages cannot render an enum value
name: string;
inputs: EventParameter[];
anonymous: boolean;
@@ -287,3 +287,149 @@ export interface TraceParams {
disableStack?: boolean;
disableStorage?: boolean;
}
export type OutputField =
| '*'
| 'ast'
| 'legacyAST'
| 'abi'
| 'devdoc'
| 'userdoc'
| 'metadata'
| 'ir'
| 'evm.assembly'
| 'evm.legacyAssembly'
| 'evm.bytecode.object'
| 'evm.bytecode.opcodes'
| 'evm.bytecode.sourceMap'
| 'evm.bytecode.linkReferences'
| 'evm.deployedBytecode.object'
| 'evm.deployedBytecode.opcodes'
| 'evm.deployedBytecode.sourceMap'
| 'evm.deployedBytecode.linkReferences'
| 'evm.methodIdentifiers'
| 'evm.gasEstimates'
| 'ewasm.wast'
| 'ewasm.wasm';
export interface ContractNetworks {
[networkId: number]: ContractNetworkData;
}
export interface ContractNetworkData {
address: string;
links: {
[linkName: string]: string;
};
constructorArgs: string;
}
export interface StandardContractOutput {
abi: ContractAbi;
evm: EvmOutput;
}
export interface EvmOutput {
bytecode: EvmBytecodeOutput;
deployedBytecode: EvmBytecodeOutput;
}
export interface EvmBytecodeOutput {
object: string;
sourceMap: string;
}
export interface ContractVersionData {
compiler: CompilerOpts;
sources: {
[sourceName: string]: {
id: number;
};
};
sourceCodes: {
[sourceName: string]: string;
};
sourceTreeHashHex: string;
compilerOutput: StandardContractOutput;
}
export interface CompilerOpts {
name: 'solc';
version: string;
settings: CompilerSettings;
}
/**
* This type defines the schema of the artifact.json file generated by Sol-compiler
* schemaVersion: The version of the artifact schema
* contractName: The contract name it represents
* networks: Network specific information by network (address, id, constructor args, etc...)
* compilerOutput: The Solidity compiler output generated from the specified compiler input
* description (http://solidity.readthedocs.io/en/v0.4.24/using-the-compiler.html#compiler-input-and-output-json-description)
* compiler: The compiler settings used
* sourceCodes: The source code of the contract and all it's dependencies
* sources: A mapping from source filePath to sourceMap id
* sourceTreeHashHex: A unique hash generated from the contract source and that of it's dependencies.
* If any of the sources change, the hash would change notifying us that a re-compilation is necessary
*/
export interface ContractArtifact extends ContractVersionData {
schemaVersion: string;
contractName: string;
networks: ContractNetworks;
}
export interface GeneratedCompilerOptions {
name: 'solc';
version: string;
settings: CompilerSettings;
}
// Copied from the solc.js library types
export interface CompilerSettings {
remappings?: string[];
optimizer?: OptimizerSettings;
evmVersion?: 'homestead' | 'tangerineWhistle' | 'spuriousDragon' | 'byzantium' | 'constantinople';
metadata?: CompilerSettingsMetadata;
libraries?: {
[fileName: string]: {
[libName: string]: string;
};
};
outputSelection: {
[fileName: string]: {
[contractName: string]: OutputField[];
};
};
}
export interface CompilerSettingsMetadata {
useLiteralContent: true;
}
export interface OptimizerSettings {
enabled: boolean;
runs?: number;
}
export interface Source {
id: number;
}
/**
* Options you can specify (as flags or in a compiler.json file) when invoking sol-compiler
* contractsDir: Directory containing your project's Solidity contracts. Can contain nested directories.
* artifactsDir: Directory where you want the generated artifacts.json written to
* compilerSettings: Desired settings to pass to the Solidity compiler during compilation.
* (http://solidity.readthedocs.io/en/v0.4.24/using-the-compiler.html#compiler-input-and-output-json-description)
* contracts: List of contract names you wish to compile, or alternatively ['*'] to compile all contracts in the
* specified directory.
* solcVersion: If you don't want to compile each contract with the Solidity version specified in-file, you can force all
* contracts to compile with the the version specified here.
*/
export interface CompilerOptions {
contractsDir?: string;
artifactsDir?: string;
compilerSettings?: CompilerSettings;
contracts?: string[] | '*';
solcVersion?: string;
}

View File

@@ -1,8 +0,0 @@
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

@@ -1,8 +0,0 @@
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.publishDocsToStagingAsync(packageJSON, tsConfigJSON, cwd);

View File

@@ -6,14 +6,13 @@
"types": "lib/index.d.ts",
"scripts": {
"watch_without_deps": "yarn pre_build && tsc -w",
"build": "yarn pre_build && tsc && copyfiles -u 2 './lib/monorepo_scripts/**/*' ./scripts",
"build": "yarn pre_build && tsc",
"pre_build": "run-s update_artifacts generate_contract_wrappers",
"update_artifacts": "for i in ${npm_package_config_contracts}; do copyfiles -u 4 ../migrations/artifacts/2.0.0-beta-testnet/$i.json lib/artifacts; done;",
"generate_contract_wrappers": "abi-gen --abis 'lib/artifacts/@(Exchange|DummyERC20Token|DummyERC721Token).json' --template ../contract_templates/contract.handlebars --partials '../contract_templates/partials/**/*.handlebars' --output src/generated_contract_wrappers --backend ethers",
"copy_monorepo_scripts": "copyfiles -u 3 './lib/src/monorepo_scripts/**/*' ./scripts",
"clean": "shx rm -rf lib scripts src/generated_contract_wrappers",
"lint": "tslint --project . --exclude **/src/generated_contract_wrappers/**/*",
"manual:postpublish": "yarn build; node ./scripts/postpublish.js"
"clean": "shx rm -rf lib src/generated_contract_wrappers",
"lint": "tslint --project . --exclude **/src/generated_contract_wrappers/**/*"
},
"config": {
"contracts": "Exchange DummyERC20Token DummyERC721Token"
@@ -29,8 +28,6 @@
"homepage": "https://github.com/0xProject/0x-monorepo/packages/fill-scenarios/README.md",
"devDependencies": {
"@0xproject/abi-gen": "^1.0.5",
"@0xproject/monorepo-scripts": "^1.0.5",
"@0xproject/sol-compiler": "^1.0.5",
"@0xproject/tslint-config": "^1.0.5",
"@types/lodash": "4.14.104",
"copyfiles": "^2.0.0",

View File

@@ -1,4 +1,4 @@
import { ContractArtifact } from '@0xproject/sol-compiler';
import { ContractArtifact } from 'ethereum-types';
import * as DummyERC20Token from './artifacts/DummyERC20Token.json';
import * as DummyERC721Token from './artifacts/DummyERC721Token.json';

View File

@@ -1,4 +1,5 @@
import { assetDataUtils, orderFactory } from '@0xproject/order-utils';
import { assetDataUtils } from '@0xproject/order-utils';
import { orderFactory } from '@0xproject/order-utils/lib/src/order_factory';
import { AssetProxyId, ERC721AssetData, OrderWithoutExchangeAddress, SignedOrder } from '@0xproject/types';
import { BigNumber } from '@0xproject/utils';
import { Web3Wrapper } from '@0xproject/web3-wrapper';

View File

@@ -1,8 +0,0 @@
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

@@ -16,24 +16,14 @@
"coverage:report:lcov": "nyc report --reporter=text-lcov > coverage/lcov.info",
"test:circleci": "yarn test:coverage",
"run_mocha": "mocha --require source-map-support/register --require make-promises-safe lib/test/**/*_test.js --exit",
"clean": "shx rm -rf lib test_temp scripts",
"build": "tsc && copyfiles -u 3 './lib/src/monorepo_scripts/**/*' ./scripts",
"manual:postpublish": "yarn build; node ./scripts/postpublish.js",
"docs:stage": "node scripts/stage_docs.js",
"docs:json": "typedoc --excludePrivate --excludeExternals --target ES5 --json $JSON_FILE_PATH $PROJECT_FILES",
"upload_docs_json": "aws s3 cp generated_docs/index.json $S3_URL --profile 0xproject --grants read=uri=http://acs.amazonaws.com/groups/global/AllUsers --content-type application/json"
"clean": "shx rm -rf lib test_temp generated_docs",
"build": "tsc",
"docs:json": "typedoc --excludePrivate --excludeExternals --target ES5 --json $JSON_FILE_PATH $PROJECT_FILES"
},
"config": {
"postpublish": {
"assets": [],
"docPublishConfigs": {
"extraFileIncludes": [
"../types/src/index.ts",
"../ethereum-types/src/index.ts"
],
"s3BucketPath": "s3://doc-jsons/json-schemas/",
"s3StagingBucketPath": "s3://staging-doc-jsons/json-schemas/"
}
"docOmitExports": ["schemas"]
}
},
"repository": {
@@ -53,7 +43,6 @@
"lodash.values": "^4.3.0"
},
"devDependencies": {
"@0xproject/monorepo-scripts": "^1.0.5",
"@0xproject/tslint-config": "^1.0.5",
"@0xproject/utils": "^1.0.5",
"@types/lodash.foreach": "^4.5.3",
@@ -69,7 +58,7 @@
"nyc": "^11.0.1",
"shx": "^0.2.2",
"tslint": "5.11.0",
"typedoc": "0xProject/typedoc",
"typedoc": "0.12.0",
"typescript": "3.0.1"
},
"publishConfig": {

View File

@@ -1,8 +0,0 @@
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

@@ -1,8 +0,0 @@
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.publishDocsToStagingAsync(packageJSON, tsConfigJSON, cwd);

View File

@@ -31,7 +31,6 @@
"dependencies": {
"@0xproject/abi-gen": "^1.0.5",
"@0xproject/base-contract": "^2.0.0-rc.1",
"@0xproject/sol-compiler": "^1.0.5",
"@0xproject/sol-cov": "^2.0.0",
"@0xproject/subproviders": "^1.0.5",
"@0xproject/tslint-config": "^1.0.5",
@@ -48,6 +47,7 @@
},
"devDependencies": {
"@0xproject/dev-utils": "^1.0.4",
"@0xproject/sol-compiler": "^1.0.5",
"chai": "^4.0.1",
"chai-as-promised": "^7.1.0",
"chai-bignumber": "^2.0.1",

View File

@@ -1,8 +1,7 @@
import { BlockchainLifecycle, devConstants } from '@0xproject/dev-utils';
import { ContractArtifact } from '@0xproject/sol-compiler';
import { BigNumber } from '@0xproject/utils';
import * as chai from 'chai';
import { LogWithDecodedArgs } from 'ethereum-types';
import { ContractArtifact, LogWithDecodedArgs } from 'ethereum-types';
import * as MetacoinArtifact from '../artifacts/Metacoin.json';
import { MetacoinContract, MetacoinTransferEventArgs } from '../src/contract_wrappers/metacoin';

View File

@@ -9,8 +9,7 @@
"types": "lib/index.d.ts",
"scripts": {
"watch_without_deps": "yarn pre_build && tsc -w",
"build": "yarn pre_build && tsc && copyfiles -u 2 './lib/monorepo_scripts/**/*' ./scripts",
"manual:postpublish": "yarn build; node ./scripts/postpublish.js",
"build": "yarn pre_build && tsc",
"pre_build": "run-s compile:v2 copy_artifacts generate_contract_wrappers",
"copy_artifacts": "copyfiles 'artifacts/**/*' ./lib",
"clean": "shx rm -rf lib src/1.0.0/contract_wrappers src/2.0.0/contract_wrappers src/2.0.0-beta-testnet/contract_wrappers artifacts/2.0.0",
@@ -38,7 +37,6 @@
"devDependencies": {
"@0xproject/abi-gen": "^1.0.5",
"@0xproject/dev-utils": "^1.0.4",
"@0xproject/monorepo-scripts": "^1.0.5",
"@0xproject/tslint-config": "^1.0.5",
"@0xproject/types": "^1.0.1-rc.4",
"@types/yargs": "^10.0.0",

View File

@@ -1,4 +1,4 @@
import { ContractArtifact } from '@0xproject/sol-compiler';
import { ContractArtifact } from 'ethereum-types';
import * as DummyERC20Token from '../../artifacts/1.0.0/DummyERC20Token.json';
import * as Exchange from '../../artifacts/1.0.0/Exchange_v1.json';

View File

@@ -1,4 +1,4 @@
import { ContractArtifact } from '@0xproject/sol-compiler';
import { ContractArtifact } from 'ethereum-types';
import * as AssetProxyOwner from '../../artifacts/2.0.0-beta-testnet/AssetProxyOwner.json';
import * as ERC20Proxy from '../../artifacts/2.0.0-beta-testnet/ERC20Proxy.json';

View File

@@ -1,4 +1,4 @@
import { ContractArtifact } from '@0xproject/sol-compiler';
import { ContractArtifact } from 'ethereum-types';
import * as AssetProxyOwner from '../../artifacts/2.0.0/AssetProxyOwner.json';
import * as DummyERC20Token from '../../artifacts/2.0.0/DummyERC20Token.json';

View File

@@ -1,8 +0,0 @@
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

@@ -1,5 +1,5 @@
import { BaseContract } from '@0xproject/base-contract';
import { ContractArtifact } from '@0xproject/sol-compiler';
import { ContractArtifact } from 'ethereum-types';
import * as fs from 'fs';
import * as path from 'path';

View File

@@ -1,4 +1,5 @@
{
"private": true,
"name": "@0xproject/monorepo-scripts",
"version": "1.0.5",
"engines": {
@@ -17,7 +18,9 @@
"script:deps_versions": "node ./lib/deps_versions.js",
"script:prepublish_checks": "node ./lib/prepublish_checks.js",
"script:publish": "IS_DRY_RUN=true node ./lib/publish.js",
"script:find_unused_deps": "node ./lib/find_unused_dependencies.js"
"script:find_unused_deps": "node ./lib/find_unused_dependencies.js",
"script:doc_generate_and_upload": "node ./lib/doc_generate_and_upload.js",
"script:publish_release_notes": "node ./lib/publish_release_notes.js"
},
"repository": {
"type": "git",
@@ -35,6 +38,7 @@
"@types/opn": "^5.1.0",
"@types/rimraf": "^2.0.2",
"@types/semver": "5.5.0",
"@types/yargs": "^10.0.0",
"depcheck": "^0.6.9",
"make-promises-safe": "^1.1.0",
"npm-run-all": "^4.1.2",
@@ -60,7 +64,9 @@
"rimraf": "^2.6.2",
"semver": "5.5.0",
"semver-diff": "^2.1.0",
"semver-sort": "0.0.4"
"semver-sort": "0.0.4",
"typedoc": "0.12.0",
"yargs": "^10.0.3"
},
"publishConfig": {
"access": "public"

View File

@@ -5,4 +5,5 @@ export const constants = {
stagingWebsite: 'http://staging-0xproject.s3-website-us-east-1.amazonaws.com',
lernaExecutable: path.join('node_modules', '@0x-lerna-fork', 'lerna', 'cli.js'),
githubPersonalAccessToken: process.env.GITHUB_PERSONAL_ACCESS_TOKEN_0X_JS,
dependenciesUpdatedMessage: 'Dependencies updated',
};

View File

@@ -0,0 +1,51 @@
import { DocGenConfigs } from './types';
export const docGenConfigs: DocGenConfigs = {
// Versions our doc JSON format so we can handle breaking changes intelligently
DOC_JSON_VERSION: '0.0.1',
// Some types that are exposed by our package's public interface are external types. As such, we won't
// be able to render their definitions. Instead we link to them using this lookup.
EXTERNAL_TYPE_TO_LINK: {
Array: 'https://developer.mozilla.org/pt-PT/docs/Web/JavaScript/Reference/Global_Objects/Array',
BigNumber: 'http://mikemcl.github.io/bignumber.js',
Error: 'https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error',
Buffer: 'https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/node/v9/index.d.ts#L262',
'solc.StandardContractOutput':
'https://solidity.readthedocs.io/en/v0.4.24/using-the-compiler.html#output-description',
'solc.CompilerSettings': 'https://solidity.readthedocs.io/en/v0.4.24/using-the-compiler.html#input-description',
Schema:
'https://github.com/tdegrunt/jsonschema/blob/5c2edd4baba149964aec0f23c87ad12c25a50dfb/lib/index.d.ts#L49',
Uint8Array: 'https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array',
'Ganache.GanacheOpts':
'https://github.com/0xProject/0x-monorepo/blob/ddf85112d7e4eb1581e0d82ce6eedad429641106/packages/typescript-typings/types/ganache-core/index.d.ts#L3',
'lightwallet.keystore':
'https://github.com/0xProject/0x-monorepo/blob/ddf85112d7e4eb1581e0d82ce6eedad429641106/packages/typescript-typings/types/eth-lightwallet/index.d.ts#L32',
},
// If a 0x package re-exports an external package, we should add a link to it's exported items here
EXTERNAL_EXPORT_TO_LINK: {
Web3ProviderEngine: 'https://www.npmjs.com/package/web3-provider-engine',
BigNumber: 'https://www.npmjs.com/package/bignumber.js',
Schema: 'https://github.com/tdegrunt/jsonschema/blob/v1.2.4/lib/index.d.ts#L49',
ValidatorResult: 'https://github.com/tdegrunt/jsonschema/blob/v1.2.4/lib/helpers.js#L31',
},
// Sometimes we want to hide a constructor from rendering in our docs. An example is when our library has a
// factory method which instantiates an instance of a class, but we don't want users instantiating it themselves
// and getting confused. Any class name in this list will not have it's constructor rendered in our docs.
CLASSES_WITH_HIDDEN_CONSTRUCTORS: [
'ERC20ProxyWrapper',
'ERC20TokenWrapper',
'ERC721ProxyWrapper',
'ERC721TokenWrapper',
'EtherTokenWrapper',
'ExchangeWrapper',
'ForwarderWrapper',
'TransactionEncoder',
],
// Some types are not explicitly part of the public interface like params, return values, etc... But we still
// want them exported. E.g error enum types that can be thrown by methods. These must be manually added to this
// config
IGNORED_EXCESSIVE_TYPES: ['NonceSubproviderErrors', 'Web3WrapperErrors', 'ContractWrappersError', 'OrderError'],
// Some libraries only export types. In those cases, we cannot check if the exported types are part of the
// "exported public interface". Thus we add them here and skip those checks.
TYPES_ONLY_LIBRARIES: ['ethereum-types', 'types'],
};

View File

@@ -0,0 +1,37 @@
import * as yargs from 'yargs';
import { DocGenerateAndUploadUtils } from './utils/doc_generate_and_upload_utils';
import { utils } from './utils/utils';
const args = yargs
.option('package', {
describe: 'Monorepo sub-package for which to generate DocJSON',
type: 'string',
demandOption: true,
})
.option('isStaging', {
describe: 'Whether we wish to publish docs to staging or production',
type: 'boolean',
demandOption: true,
})
.option('shouldUpload', {
describe: 'Whether we wish to upload the docs to S3 or not',
type: 'boolean',
demandOption: false,
default: true,
})
.example("$0 --package '0x.js' --isStaging true", 'Full usage example').argv;
(async () => {
const packageName = args.package;
const isStaging = args.isStaging;
const shouldUploadDocs = args.shouldUpload;
const docGenerateAndUploadUtils = new DocGenerateAndUploadUtils(packageName, isStaging, shouldUploadDocs);
await docGenerateAndUploadUtils.generateAndUploadDocsAsync();
process.exit(0);
})().catch(err => {
utils.log(err);
process.exit(1);
});

View File

@@ -1 +0,0 @@
export { postpublishUtils } from './postpublish_utils';

View File

@@ -1,202 +0,0 @@
import { execAsync } from 'async-child-process';
import * as promisify from 'es6-promisify';
import * as fs from 'fs';
import * as _ from 'lodash';
import * as path from 'path';
import * as publishRelease from 'publish-release';
import { constants } from './constants';
import { configs } from './utils/configs';
import { utils } from './utils/utils';
const publishReleaseAsync = promisify(publishRelease);
const generatedDocsDirectoryName = 'generated_docs';
export interface PostpublishConfigs {
cwd: string;
packageName: string;
version: string;
assets: string[];
docPublishConfigs: DocPublishConfigs;
}
export interface DocPublishConfigs {
fileIncludes: string[];
s3BucketPath: string;
s3StagingBucketPath: string;
}
export const postpublishUtils = {
generateConfig(packageJSON: any, tsConfigJSON: any, cwd: string): PostpublishConfigs {
if (_.isUndefined(packageJSON.name)) {
throw new Error('name field required in package.json. Cannot publish release notes to Github.');
}
if (_.isUndefined(packageJSON.version)) {
throw new Error('version field required in package.json. Cannot publish release notes to Github.');
}
const postpublishConfig = _.get(packageJSON, 'config.postpublish', {});
const postpublishConfigs: PostpublishConfigs = {
cwd,
packageName: packageJSON.name,
version: packageJSON.version,
assets: _.get(postpublishConfig, 'assets', []),
docPublishConfigs: {
fileIncludes: [
...tsConfigJSON.include,
..._.get(postpublishConfig, 'docPublishConfigs.extraFileIncludes', []),
],
s3BucketPath: _.get(postpublishConfig, 'docPublishConfigs.s3BucketPath'),
s3StagingBucketPath: _.get(postpublishConfig, 'docPublishConfigs.s3StagingBucketPath'),
},
};
return postpublishConfigs;
},
async runAsync(packageJSON: any, tsConfigJSON: any, cwd: string): Promise<void> {
if (configs.IS_LOCAL_PUBLISH) {
return;
}
const postpublishConfigs = postpublishUtils.generateConfig(packageJSON, tsConfigJSON, cwd);
await postpublishUtils.publishReleaseNotesAsync(
postpublishConfigs.packageName,
postpublishConfigs.version,
postpublishConfigs.assets,
);
if (
!_.isUndefined(postpublishConfigs.docPublishConfigs.s3BucketPath) ||
!_.isUndefined(postpublishConfigs.docPublishConfigs.s3StagingBucketPath)
) {
utils.log('POSTPUBLISH: Release successful, generating docs...');
await postpublishUtils.generateAndUploadDocsAsync(
postpublishConfigs.cwd,
postpublishConfigs.docPublishConfigs.fileIncludes,
postpublishConfigs.version,
postpublishConfigs.docPublishConfigs.s3BucketPath,
);
} else {
utils.log(`POSTPUBLISH: No S3Bucket config found for ${packageJSON.name}. Skipping doc JSON generation.`);
}
},
async publishDocsToStagingAsync(packageJSON: any, tsConfigJSON: any, cwd: string): Promise<void> {
const postpublishConfigs = postpublishUtils.generateConfig(packageJSON, tsConfigJSON, cwd);
if (_.isUndefined(postpublishConfigs.docPublishConfigs.s3StagingBucketPath)) {
utils.log('config.postpublish.docPublishConfigs.s3StagingBucketPath entry in package.json not found!');
return;
}
utils.log('POSTPUBLISH: Generating docs...');
await postpublishUtils.generateAndUploadDocsAsync(
postpublishConfigs.cwd,
postpublishConfigs.docPublishConfigs.fileIncludes,
postpublishConfigs.version,
postpublishConfigs.docPublishConfigs.s3StagingBucketPath,
);
},
async publishReleaseNotesAsync(packageName: string, version: string, assets: string[]): Promise<void> {
const notes = postpublishUtils.getReleaseNotes(packageName, version);
const releaseName = postpublishUtils.getReleaseName(packageName, version);
const tag = postpublishUtils.getTag(packageName, version);
postpublishUtils.adjustAssetPaths(assets);
utils.log('POSTPUBLISH: Releasing ', releaseName, '...');
await publishReleaseAsync({
token: constants.githubPersonalAccessToken,
owner: '0xProject',
repo: '0x-monorepo',
tag,
name: releaseName,
notes,
draft: false,
prerelease: false,
reuseRelease: true,
reuseDraftOnly: false,
assets,
});
},
getReleaseNotes(packageName: string, version: string): string {
const packageNameWithNamespace = packageName.replace('@0xproject/', '');
const changelogJSONPath = path.join(
constants.monorepoRootPath,
'packages',
packageNameWithNamespace,
'CHANGELOG.json',
);
const changelogJSON = fs.readFileSync(changelogJSONPath, 'utf-8');
const changelogs = JSON.parse(changelogJSON);
const latestLog = changelogs[0];
// We sanity check that the version for the changelog notes we are about to publish to Github
// correspond to the new version of the package.
if (version !== latestLog.version) {
throw new Error('Expected CHANGELOG.json latest entry version to coincide with published version.');
}
let notes = '';
_.each(latestLog.changes, change => {
notes += `* ${change.note}`;
if (change.pr) {
notes += ` (#${change.pr})`;
}
notes += `\n`;
});
return notes;
},
getTag(packageName: string, version: string): string {
return `${packageName}@${version}`;
},
getReleaseName(subPackageName: string, version: string): string {
const releaseName = `${subPackageName} v${version}`;
return releaseName;
},
// Asset paths should described from the monorepo root. This method prefixes
// the supplied path with the absolute path to the monorepo root.
adjustAssetPaths(assets: string[]): string[] {
const finalAssets: string[] = [];
_.each(assets, (asset: string) => {
finalAssets.push(`${constants.monorepoRootPath}/${asset}`);
});
return finalAssets;
},
adjustFileIncludePaths(fileIncludes: string[], cwd: string): string[] {
const fileIncludesAdjusted = _.map(fileIncludes, fileInclude => {
let includePath = _.startsWith(fileInclude, './')
? `${cwd}/${fileInclude.substr(2)}`
: `${cwd}/${fileInclude}`;
// HACK: tsconfig.json needs wildcard directory endings as `/**/*`
// but TypeDoc needs it as `/**` in order to pick up files at the root
if (_.endsWith(includePath, '/**/*')) {
// tslint:disable-next-line:custom-no-magic-numbers
includePath = includePath.slice(0, -2);
}
return includePath;
});
return fileIncludesAdjusted;
},
async generateAndUploadDocsAsync(
cwd: string,
fileIncludes: string[],
version: string,
S3BucketPath: string,
): Promise<void> {
const fileIncludesAdjusted = postpublishUtils.adjustFileIncludePaths(fileIncludes, cwd);
const projectFiles = fileIncludesAdjusted.join(' ');
const jsonFilePath = `${cwd}/${generatedDocsDirectoryName}/index.json`;
const result = await execAsync(
`JSON_FILE_PATH=${jsonFilePath} PROJECT_FILES="${projectFiles}" yarn docs:json`,
{
cwd,
},
);
if (!_.isEmpty(result.stderr)) {
throw new Error(result.stderr);
}
const fileName = `v${version}.json`;
utils.log(`POSTPUBLISH: Doc generation successful, uploading docs... as ${fileName}`);
const s3Url = S3BucketPath + fileName;
await execAsync(`S3_URL=${s3Url} yarn upload_docs_json`, {
cwd,
});
// Remove the generated docs directory
await execAsync(`rm -rf ${generatedDocsDirectoryName}`, {
cwd,
});
utils.log(`POSTPUBLISH: Docs uploaded to S3 bucket: ${S3BucketPath}`);
},
};

View File

@@ -1,6 +1,7 @@
#!/usr/bin/env node
import * as promisify from 'es6-promisify';
import * as fs from 'fs';
import * as _ from 'lodash';
import * as moment from 'moment';
import opn = require('opn');
@@ -13,23 +14,13 @@ import { constants } from './constants';
import { Package, PackageToNextVersion, VersionChangelog } from './types';
import { changelogUtils } from './utils/changelog_utils';
import { configs } from './utils/configs';
import { DocGenerateAndUploadUtils } from './utils/doc_generate_and_upload_utils';
import { publishReleaseNotesAsync } from './utils/github_release_utils';
import { utils } from './utils/utils';
const DOC_GEN_COMMAND = 'docs:json';
const NPM_NAMESPACE = '@0xproject/';
const TODAYS_TIMESTAMP = moment().unix();
const packageNameToWebsitePath: { [name: string]: string } = {
'0x.js': '0xjs',
'web3-wrapper': 'web3_wrapper',
contracts: 'contracts',
connect: 'connect',
'json-schemas': 'json-schemas',
'sol-compiler': 'sol-compiler',
'sol-cov': 'sol-cov',
subproviders: 'subproviders',
'order-utils': 'order-utils',
'ethereum-types': 'ethereum-types',
};
async function confirmAsync(message: string): Promise<void> {
prompt.start();
@@ -45,12 +36,13 @@ async function confirmAsync(message: string): Promise<void> {
// Fetch public, updated Lerna packages
const shouldIncludePrivate = true;
const allUpdatedPackages = await utils.getUpdatedPackagesAsync(shouldIncludePrivate);
const packagesWithDocs = getPackagesWithDocs(allUpdatedPackages);
if (!configs.IS_LOCAL_PUBLISH) {
await confirmAsync(
'THIS IS NOT A TEST PUBLISH! You are about to publish one or more packages to npm. Are you sure you want to continue? (y/n)',
);
await confirmDocPagesRenderAsync(allUpdatedPackages);
await confirmDocPagesRenderAsync(packagesWithDocs);
}
// Update CHANGELOGs
@@ -83,44 +75,67 @@ async function confirmAsync(message: string): Promise<void> {
});
utils.log(`Calling 'lerna publish'...`);
await lernaPublishAsync(packageToNextVersion);
const isStaging = false;
const shouldUploadDocs = !configs.IS_LOCAL_PUBLISH;
await generateAndUploadDocJsonsAsync(packagesWithDocs, isStaging, shouldUploadDocs);
const isDryRun = configs.IS_LOCAL_PUBLISH;
await publishReleaseNotesAsync(updatedPublicPackages, isDryRun);
})().catch(err => {
utils.log(err);
process.exit(1);
});
async function confirmDocPagesRenderAsync(packages: Package[]): Promise<void> {
function getPackagesWithDocs(allUpdatedPackages: Package[]): Package[] {
const rootPackageJsonPath = `${constants.monorepoRootPath}/package.json`;
const rootPackageJson = JSON.parse(fs.readFileSync(rootPackageJsonPath).toString());
const packagesWithDocPagesStringIfExist = _.get(rootPackageJson, 'configs.packagesWithDocPages', undefined);
if (_.isUndefined(packagesWithDocPagesStringIfExist)) {
return []; // None to generate & publish
}
const packagesWithDocPages = packagesWithDocPagesStringIfExist.split(' ');
const updatedPackagesWithDocPages: Package[] = [];
_.each(allUpdatedPackages, pkg => {
const nameWithoutPrefix = pkg.packageJson.name.replace('@0xproject/', '');
if (_.includes(packagesWithDocPages, nameWithoutPrefix)) {
updatedPackagesWithDocPages.push(pkg);
}
});
return updatedPackagesWithDocPages;
}
async function generateAndUploadDocJsonsAsync(
packagesWithDocs: Package[],
isStaging: boolean,
shouldUploadDocs: boolean,
): Promise<void> {
for (const pkg of packagesWithDocs) {
const nameWithoutPrefix = pkg.packageJson.name.replace('@0xproject/', '');
const docGenerateAndUploadUtils = new DocGenerateAndUploadUtils(nameWithoutPrefix, isStaging, shouldUploadDocs);
await docGenerateAndUploadUtils.generateAndUploadDocsAsync();
}
}
async function confirmDocPagesRenderAsync(packagesWithDocs: Package[]): Promise<void> {
// push docs to staging
utils.log("Upload all docJson's to S3 staging...");
await execAsync(`yarn stage_docs`, { cwd: constants.monorepoRootPath });
const isStaging = true;
const shouldUploadDocs = true;
await generateAndUploadDocJsonsAsync(packagesWithDocs, isStaging, shouldUploadDocs);
// deploy website to staging
utils.log('Deploy website to staging...');
const pathToWebsite = `${constants.monorepoRootPath}/packages/website`;
await execAsync(`yarn deploy_staging`, { cwd: pathToWebsite });
const packagesWithDocs = _.filter(packages, pkg => {
const scriptsIfExists = pkg.packageJson.scripts;
if (_.isUndefined(scriptsIfExists)) {
throw new Error('Found a public package without any scripts in package.json');
}
return !_.isUndefined(scriptsIfExists[DOC_GEN_COMMAND]);
});
_.each(packagesWithDocs, pkg => {
const name = pkg.packageJson.name;
const nameWithoutPrefix = _.startsWith(name, NPM_NAMESPACE) ? name.split('@0xproject/')[1] : name;
const docSegmentIfExists = packageNameToWebsitePath[nameWithoutPrefix];
if (_.isUndefined(docSegmentIfExists)) {
throw new Error(
`Found package '${name}' with doc commands but no corresponding docSegment in monorepo_scripts
package.ts. Please add an entry for it and try again.`,
);
}
const link = `${constants.stagingWebsite}/docs/${docSegmentIfExists}`;
const link = `${constants.stagingWebsite}/docs/${nameWithoutPrefix}`;
// tslint:disable-next-line:no-floating-promises
opn(link);
});
await confirmAsync('Do all the doc pages render properly? (y/n)');
await confirmAsync('Do all the doc pages render? (y/n)');
}
async function pushChangelogsToGithubAsync(): Promise<void> {
@@ -153,7 +168,7 @@ async function updateChangeLogsAsync(updatedPublicPackages: Package[]): Promise<
version: nextPatchVersionIfValid,
changes: [
{
note: 'Dependencies updated',
note: constants.dependenciesUpdatedMessage,
},
],
};

View File

@@ -0,0 +1,23 @@
import * as yargs from 'yargs';
import { publishReleaseNotesAsync } from './utils/github_release_utils';
import { utils } from './utils/utils';
const args = yargs
.option('isDryRun', {
describe: 'Whether we wish to do a dry run, not committing anything to Github',
type: 'boolean',
demandOption: true,
})
.example('$0 --isDryRun true', 'Full usage example').argv;
(async () => {
const isDryRun = args.isDryRun;
const shouldIncludePrivate = false;
const allUpdatedPackages = await utils.getUpdatedPackagesAsync(shouldIncludePrivate);
await publishReleaseNotesAsync(allUpdatedPackages, isDryRun);
})().catch(err => {
utils.log(err);
process.exit(1);
});

View File

@@ -49,3 +49,25 @@ export interface Package {
location: string;
packageJson: PackageJSON;
}
export interface DocGenConfigs {
DOC_JSON_VERSION: string;
EXTERNAL_TYPE_TO_LINK: { [externalType: string]: string };
EXTERNAL_EXPORT_TO_LINK: { [externalExport: string]: string };
CLASSES_WITH_HIDDEN_CONSTRUCTORS: string[];
IGNORED_EXCESSIVE_TYPES: string[];
TYPES_ONLY_LIBRARIES: string[];
}
export interface ExportPathToExportedItems {
[pkgName: string]: string[];
}
export interface ExportInfo {
exportPathToExportedItems: ExportPathToExportedItems;
exportPathOrder: string[];
}
export interface ExportNameToTypedocNames {
[exportName: string]: string[];
}

View File

@@ -0,0 +1,485 @@
import { readFileSync, writeFileSync } from 'fs';
import * as _ from 'lodash';
import * as path from 'path';
import { exec as execAsync } from 'promisify-child-process';
import * as ts from 'typescript';
import { constants } from '../constants';
import { docGenConfigs } from '../doc_gen_configs';
import { ExportInfo, ExportNameToTypedocNames, ExportPathToExportedItems, PackageJSON } from '../types';
import { utils } from './utils';
export class DocGenerateAndUploadUtils {
private readonly _isStaging: boolean;
private readonly _shouldUploadDocs: boolean;
private readonly _packageName: string;
private readonly _omitExports: string[];
private readonly _packagePath: string;
private readonly _exportPathToExportedItems: ExportPathToExportedItems;
private readonly _exportPathOrder: string[];
private readonly _monoRepoPkgNameToPath: { [name: string]: string };
private readonly _packageJson: PackageJSON;
/**
* Recursively iterate over the TypeDoc JSON object and find all type names
*/
private static _getAllTypeNames(node: any, typeNames: string[]): string[] {
if (!_.isObject(node)) {
return typeNames;
}
const typeKindStrings = ['Interface', 'Enumeration', 'Type alias'];
if (_.includes(typeKindStrings, node.kindString)) {
return [...typeNames, node.name];
}
let updatedTypeNames = typeNames;
_.each(node, nodeValue => {
if (_.isArray(nodeValue)) {
_.each(nodeValue, aNode => {
updatedTypeNames = DocGenerateAndUploadUtils._getAllTypeNames(aNode, updatedTypeNames);
});
} else if (_.isObject(nodeValue)) {
updatedTypeNames = DocGenerateAndUploadUtils._getAllTypeNames(nodeValue, updatedTypeNames);
}
});
return updatedTypeNames;
}
/**
* Recursively iterate over the TypeDoc JSON object and find all reference names (i.e types, classNames,
* objectLiteral names, etc...)
*/
private static _getAllReferenceNames(propertyName: string, node: any, referenceNames: string[]): string[] {
if (!_.isObject(node)) {
return referenceNames;
}
let updatedReferenceNames = referenceNames;
// Some nodes of type reference are for subtypes, which we don't want to return.
// We therefore filter them out.
const SUB_TYPE_PROPERTY_NAMES = ['inheritedFrom', 'overwrites', 'extendedTypes', 'implementationOf'];
const TS_MAPPED_TYPES = ['Partial', 'Promise', 'Readonly', 'Pick', 'Record'];
if (
!_.isUndefined(node.type) &&
_.isString(node.type) &&
node.type === 'reference' &&
!_.includes(TS_MAPPED_TYPES, node.name) &&
!_.includes(SUB_TYPE_PROPERTY_NAMES, propertyName)
) {
updatedReferenceNames = _.uniq([...referenceNames, node.name]);
return updatedReferenceNames;
}
_.each(node, (nodeValue, innerPropertyName) => {
if (_.isArray(nodeValue)) {
_.each(nodeValue, aNode => {
updatedReferenceNames = DocGenerateAndUploadUtils._getAllReferenceNames(
innerPropertyName,
aNode,
updatedReferenceNames,
);
});
} else if (_.isObject(nodeValue)) {
updatedReferenceNames = DocGenerateAndUploadUtils._getAllReferenceNames(
innerPropertyName,
nodeValue,
updatedReferenceNames,
);
}
});
return _.uniq(updatedReferenceNames);
}
private static _getExportPathToExportedItems(filePath: string, omitExports?: string[]): ExportInfo {
const sourceFile = ts.createSourceFile(
'indexFile',
readFileSync(filePath).toString(),
ts.ScriptTarget.ES2017,
/*setParentNodes */ true,
);
const exportPathToExportedItems: ExportPathToExportedItems = {};
const exportPathOrder: string[] = [];
const exportsToOmit = _.isUndefined(omitExports) ? [] : omitExports;
processNode(sourceFile);
function processNode(node: ts.Node): void {
switch (node.kind) {
case ts.SyntaxKind.ExportDeclaration: {
const exportClause = (node as any).exportClause;
const exportPath = exportClause.parent.moduleSpecifier.text;
_.each(exportClause.elements, element => {
const exportItem = element.name.escapedText;
if (!_.includes(exportsToOmit, exportItem)) {
exportPathToExportedItems[exportPath] = _.isUndefined(exportPathToExportedItems[exportPath])
? [exportItem]
: [...exportPathToExportedItems[exportPath], exportItem];
}
});
if (!_.isUndefined(exportPathToExportedItems[exportPath])) {
exportPathOrder.push(exportPath);
}
break;
}
case ts.SyntaxKind.ExportKeyword: {
const foundNode: any = node;
let exportPath = './index';
if (foundNode.parent && foundNode.parent.name) {
const exportItem = foundNode.parent.name.escapedText;
const isExportImportRequireStatement = !_.isUndefined(
_.get(foundNode, 'parent.moduleReference.expression.text'),
);
if (isExportImportRequireStatement) {
exportPath = foundNode.parent.moduleReference.expression.text;
}
if (!_.includes(exportsToOmit, exportItem)) {
exportPathToExportedItems[exportPath] = _.isUndefined(exportPathToExportedItems[exportPath])
? [exportItem]
: [...exportPathToExportedItems[exportPath], exportItem];
}
}
if (
!_.includes(exportPathOrder, exportPath) &&
!_.isUndefined(exportPathToExportedItems[exportPath])
) {
exportPathOrder.push(exportPath);
}
break;
}
default:
// noop
break;
}
ts.forEachChild(node, processNode);
}
const exportInfo = {
exportPathToExportedItems,
exportPathOrder,
};
return exportInfo;
}
constructor(packageName: string, isStaging: boolean, shouldUploadDocs: boolean) {
this._isStaging = isStaging;
this._packageName = packageName;
this._shouldUploadDocs = shouldUploadDocs;
this._packagePath = `${constants.monorepoRootPath}/packages/${packageName}`;
this._monoRepoPkgNameToPath = {};
const monorepoPackages = utils.getPackages(constants.monorepoRootPath);
_.each(monorepoPackages, p => (this._monoRepoPkgNameToPath[p.packageJson.name] = p.location));
const pkg = _.find(monorepoPackages, monorepoPackage => {
return _.includes(monorepoPackage.packageJson.name, packageName);
});
if (_.isUndefined(pkg)) {
throw new Error(`Couldn't find a package.json for ${packageName}`);
}
this._packageJson = pkg.packageJson;
this._omitExports = _.get(this._packageJson, 'config.postpublish.docOmitExports', []);
const indexPath = `${this._packagePath}/src/index.ts`;
const exportInfo = DocGenerateAndUploadUtils._getExportPathToExportedItems(indexPath, this._omitExports);
this._exportPathToExportedItems = exportInfo.exportPathToExportedItems;
this._exportPathOrder = exportInfo.exportPathOrder;
}
public async generateAndUploadDocsAsync(): Promise<void> {
// For each dep that is another one of our monorepo packages, we fetch it's index.ts
// and see which specific files we must pass to TypeDoc, in order to generate a Doc JSON
// the includes everything exported by the public interface.
const typeDocExtraFileIncludes: string[] = this._getTypeDocFileIncludesForPackage();
// In order to avoid TS errors, we need to pass TypeDoc the package's global.d.ts file
typeDocExtraFileIncludes.push(path.join(this._packagePath, 'src', 'globals.d.ts'));
utils.log(`GENERATE_UPLOAD_DOCS: Generating Typedoc JSON for ${this._packageName}...`);
const jsonFilePath = path.join(this._packagePath, 'generated_docs', 'index.json');
const projectFiles = typeDocExtraFileIncludes.join(' ');
const cwd = path.join(constants.monorepoRootPath, 'packages', this._packageName);
// HACK: For some reason calling `typedoc` command directly from here, even with `cwd` set to the
// packages root dir, does not work. It only works when called via a `package.json` script located
// in the package's root.
await execAsync(`JSON_FILE_PATH=${jsonFilePath} PROJECT_FILES="${projectFiles}" yarn docs:json`, {
cwd,
});
utils.log('GENERATE_UPLOAD_DOCS: Modifying Typedoc JSON to our custom format...');
const typedocOutputString = readFileSync(jsonFilePath).toString();
const typedocOutput = JSON.parse(typedocOutputString);
const standardizedTypedocOutput = this._standardizeTypedocOutputTopLevelChildNames(typedocOutput);
const modifiedTypedocOutput = this._pruneTypedocOutput(standardizedTypedocOutput);
if (!_.includes(docGenConfigs.TYPES_ONLY_LIBRARIES, this._packageName)) {
const propertyName = ''; // Root has no property name
const referenceNames = DocGenerateAndUploadUtils._getAllReferenceNames(
propertyName,
modifiedTypedocOutput,
[],
);
this._lookForUnusedExportedTypesThrowIfExists(referenceNames, modifiedTypedocOutput);
this._lookForMissingReferenceExportsThrowIfExists(referenceNames);
}
// Some of our packages re-export external package exports in their index.ts
// Typedoc is incapable of rendering these packages, so we need to special-case them
const externalExportToLink: { [externalExport: string]: string } = {};
const externalExportsWithoutLinks: string[] = [];
const externalExports: string[] = this._getAllExternalExports();
_.each(externalExports, externalExport => {
const linkIfExists = docGenConfigs.EXTERNAL_EXPORT_TO_LINK[externalExport];
if (_.isUndefined(linkIfExists)) {
externalExportsWithoutLinks.push(externalExport);
return;
}
externalExportToLink[externalExport] = linkIfExists;
});
if (!_.isEmpty(externalExportsWithoutLinks)) {
throw new Error(
`Found the following external exports in ${
this._packageName
}'s index.ts:\n ${externalExportsWithoutLinks.join(
'\n',
)}\nThey are missing from the EXTERNAL_EXPORT_TO_LINK mapping. Add them and try again.`,
);
}
const exportPathToTypedocNames: ExportNameToTypedocNames = {};
_.each(modifiedTypedocOutput.children, file => {
const exportPath = this._findExportPathGivenTypedocName(file.name);
exportPathToTypedocNames[exportPath] = _.isUndefined(exportPathToTypedocNames[exportPath])
? [file.name]
: [...exportPathToTypedocNames[exportPath], file.name];
});
// Since we need additional metadata included in the doc JSON, we nest the TypeDoc JSON
// within our own custom, versioned docsJson format.
const docJson = {
version: docGenConfigs.DOC_JSON_VERSION,
metadata: {
exportPathToTypedocNames,
exportPathOrder: this._exportPathOrder,
externalTypeToLink: docGenConfigs.EXTERNAL_TYPE_TO_LINK,
externalExportToLink,
},
typedocJson: modifiedTypedocOutput,
};
utils.log(`GENERATE_UPLOAD_DOCS: Saving Doc JSON to: ${jsonFilePath}`);
writeFileSync(jsonFilePath, JSON.stringify(docJson, null, 2));
if (this._shouldUploadDocs) {
await this._uploadDocsAsync(jsonFilePath, cwd);
}
utils.log(`GENERATE_UPLOAD_DOCS: Doc generation done for ${this._packageName}`);
}
private async _uploadDocsAsync(jsonFilePath: string, cwd: string): Promise<void> {
const fileName = `v${this._packageJson.version}.json`;
utils.log(`GENERATE_UPLOAD_DOCS: Doc generation successful, uploading docs... as ${fileName}`);
const S3BucketPath = this._isStaging
? `s3://staging-doc-jsons/${this._packageName}/`
: `s3://doc-jsons/${this._packageName}/`;
const s3Url = `${S3BucketPath}${fileName}`;
await execAsync(
`aws s3 cp ${jsonFilePath} ${s3Url} --profile 0xproject --grants read=uri=http://acs.amazonaws.com/groups/global/AllUsers --content-type application/json`,
{
cwd,
},
);
utils.log(`GENERATE_UPLOAD_DOCS: Docs uploaded to S3 bucket: ${S3BucketPath}`);
// Remove the generated docs directory
await execAsync(`rm -rf ${jsonFilePath}`, {
cwd,
});
}
/**
* Look for types that are used by the public interface but are missing from a package's index.ts
*/
private _lookForMissingReferenceExportsThrowIfExists(referenceNames: string[]): void {
const allExportedItems = _.flatten(_.values(this._exportPathToExportedItems));
const missingReferences: string[] = [];
_.each(referenceNames, referenceName => {
if (
!_.includes(allExportedItems, referenceName) &&
_.isUndefined(docGenConfigs.EXTERNAL_TYPE_TO_LINK[referenceName])
) {
missingReferences.push(referenceName);
}
});
if (!_.isEmpty(missingReferences)) {
throw new Error(
`${this._packageName} package needs to export: \n${missingReferences.join(
'\n',
)} \nFrom it\'s index.ts. If any are from external dependencies, then add them to the EXTERNAL_TYPE_TO_LINK mapping.`,
);
}
}
/**
* Look for exported types that are not used by the package's public interface
*/
private _lookForUnusedExportedTypesThrowIfExists(referenceNames: string[], typedocOutput: any): void {
const exportedTypes = DocGenerateAndUploadUtils._getAllTypeNames(typedocOutput, []);
const excessiveReferences = _.difference(exportedTypes, referenceNames);
const excessiveReferencesExceptIgnored = _.difference(
excessiveReferences,
docGenConfigs.IGNORED_EXCESSIVE_TYPES,
);
if (!_.isEmpty(excessiveReferencesExceptIgnored)) {
throw new Error(
`${this._packageName} package exports BUT does not need: \n${excessiveReferencesExceptIgnored.join(
'\n',
)} \nin it\'s index.ts. Remove them then try again.`,
);
}
}
/**
* For each entry in the TypeDoc JSON, remove it if:
* - it was not exported in index.ts
* - the constructor is to be ignored
* - it begins with an underscore (i.e is private)
*/
private _pruneTypedocOutput(typedocOutput: any): any {
const modifiedTypedocOutput = _.cloneDeep(typedocOutput);
_.each(typedocOutput.children, (file, i) => {
const exportPath = this._findExportPathGivenTypedocName(file.name);
const exportItems = this._exportPathToExportedItems[exportPath];
_.each(file.children, (child, j) => {
const isNotExported = !_.includes(exportItems, child.name);
if (isNotExported) {
delete modifiedTypedocOutput.children[i].children[j];
return;
}
const innerChildren = typedocOutput.children[i].children[j].children;
_.each(innerChildren, (innerChild, k) => {
const isHiddenConstructor =
child.kindString === 'Class' &&
_.includes(docGenConfigs.CLASSES_WITH_HIDDEN_CONSTRUCTORS, child.name) &&
innerChild.kindString === 'Constructor';
const isPrivate = _.startsWith(innerChild.name, '_');
if (isHiddenConstructor || isPrivate) {
delete modifiedTypedocOutput.children[i].children[j].children[k];
}
});
modifiedTypedocOutput.children[i].children[j].children = _.compact(
modifiedTypedocOutput.children[i].children[j].children,
);
});
modifiedTypedocOutput.children[i].children = _.compact(modifiedTypedocOutput.children[i].children);
});
return modifiedTypedocOutput;
}
/**
* Unfortunately TypeDoc children names will only be prefixed with the name of the package _if_ we passed
* TypeDoc files outside of the packages root path (i.e this package exports another package from our
* monorepo). In order to enforce that the names are always prefixed with the package's name, we check and add
* them here when necessary.
*/
private _standardizeTypedocOutputTopLevelChildNames(typedocOutput: any): any {
const modifiedTypedocOutput = _.cloneDeep(typedocOutput);
_.each(typedocOutput.children, (child, i) => {
if (!_.includes(child.name, '/src/')) {
const nameWithoutQuotes = child.name.replace(/"/g, '');
const standardizedName = `"${this._packageName}/src/${nameWithoutQuotes}"`;
modifiedTypedocOutput.children[i].name = standardizedName;
}
});
return modifiedTypedocOutput;
}
/**
* Maps back each top-level TypeDoc JSON object name to the exportPath from which it was generated.
*/
private _findExportPathGivenTypedocName(typedocName: string): string {
const typeDocNameWithoutQuotes = _.replace(typedocName, /"/g, '');
const sanitizedExportPathToExportPath: { [sanitizedName: string]: string } = {};
const exportPaths = _.keys(this._exportPathToExportedItems);
const sanitizedExportPaths = _.map(exportPaths, exportPath => {
if (_.startsWith(exportPath, './')) {
const sanitizedExportPath = path.join(this._packageName, 'src', exportPath);
sanitizedExportPathToExportPath[sanitizedExportPath] = exportPath;
return sanitizedExportPath;
}
const monorepoPrefix = '@0xproject/';
if (_.startsWith(exportPath, monorepoPrefix)) {
const sanitizedExportPath = exportPath.split(monorepoPrefix)[1];
sanitizedExportPathToExportPath[sanitizedExportPath] = exportPath;
return sanitizedExportPath;
}
sanitizedExportPathToExportPath[exportPath] = exportPath;
return exportPath;
});
// We need to sort the exportPaths by length (longest first), so that the match finding will pick
// longer matches before shorter matches, since it might match both, but the longer match is more
// precisely what we are looking for.
const sanitizedExportPathsSortedByLength = sanitizedExportPaths.sort((a: string, b: string) => {
return b.length - a.length;
});
const matchingSanitizedExportPathIfExists = _.find(sanitizedExportPathsSortedByLength, p => {
return _.startsWith(typeDocNameWithoutQuotes, p);
});
if (_.isUndefined(matchingSanitizedExportPathIfExists)) {
throw new Error(`Didn't find an exportPath for ${typeDocNameWithoutQuotes}`);
}
const matchingExportPath = sanitizedExportPathToExportPath[matchingSanitizedExportPathIfExists];
return matchingExportPath;
}
private _getAllExternalExports(): string[] {
const externalExports: string[] = [];
_.each(this._exportPathToExportedItems, (exportedItems, exportPath) => {
const pathIfExists = this._monoRepoPkgNameToPath[exportPath];
if (_.isUndefined(pathIfExists) && !_.startsWith(exportPath, './')) {
_.each(exportedItems, exportedItem => {
externalExports.push(exportedItem);
});
return; // It's an external package
}
});
return externalExports;
}
private _getTypeDocFileIncludesForPackage(): string[] {
let typeDocExtraFileIncludes: string[] = [];
_.each(this._exportPathToExportedItems, (exportedItems, exportPath) => {
const isInternalToPkg = _.startsWith(exportPath, '.');
if (isInternalToPkg) {
const pathToInternalPkg = path.join(this._packagePath, 'src', `${exportPath}.ts`);
typeDocExtraFileIncludes.push(pathToInternalPkg);
return;
}
const pathIfExists = this._monoRepoPkgNameToPath[exportPath];
if (_.isUndefined(pathIfExists)) {
return; // It's an external package
}
const typeDocSourceIncludes = new Set();
const pathToIndex = `${pathIfExists}/src/index.ts`;
const exportInfo = DocGenerateAndUploadUtils._getExportPathToExportedItems(pathToIndex);
const innerExportPathToExportedItems = exportInfo.exportPathToExportedItems;
_.each(exportedItems, exportName => {
_.each(innerExportPathToExportedItems, (innerExportItems, innerExportPath) => {
if (!_.includes(innerExportItems, exportName)) {
return;
}
if (!_.startsWith(innerExportPath, './')) {
throw new Error(
`GENERATE_UPLOAD_DOCS: WARNING - ${
this._packageName
} is exporting one of ${innerExportItems} which is
itself exported from an external package. To fix this, export the external dependency directly,
not indirectly through ${innerExportPath}.`,
);
} else {
const absoluteSrcPath = path.join(pathIfExists, 'src', `${innerExportPath}.ts`);
typeDocSourceIncludes.add(absoluteSrcPath);
}
});
});
// @0xproject/types & ethereum-types are examples of packages where their index.ts exports types
// directly, meaning no internal paths will exist to follow. Other packages also have direct exports
// in their index.ts, so we always add it to the source files passed to TypeDoc
if (typeDocSourceIncludes.size === 0) {
typeDocSourceIncludes.add(pathToIndex);
}
typeDocExtraFileIncludes = [...typeDocExtraFileIncludes, ...Array.from(typeDocSourceIncludes)];
});
return typeDocExtraFileIncludes;
}
}

View File

@@ -0,0 +1,119 @@
import * as promisify from 'es6-promisify';
import { readFileSync } from 'fs';
import * as _ from 'lodash';
import * as path from 'path';
import { exec as execAsync } from 'promisify-child-process';
import * as publishRelease from 'publish-release';
import { constants } from '../constants';
import { Package } from '../types';
import { utils } from './utils';
const publishReleaseAsync = promisify(publishRelease);
// tslint:disable-next-line:completed-docs
export async function publishReleaseNotesAsync(updatedPublishPackages: Package[], isDryRun: boolean): Promise<void> {
// Git push a tag representing this publish (publish-{commit-hash}) (truncate hash)
const result = await execAsync('git log -n 1 --pretty=format:"%H"', { cwd: constants.monorepoRootPath });
const latestGitCommit = result.stdout;
const prefixLength = 7;
const shortenedGitCommit = latestGitCommit.slice(0, prefixLength);
const tagName = `monorepo@${shortenedGitCommit}`;
if (!isDryRun) {
try {
await execAsync(`git tag ${tagName}`);
} catch (err) {
if (_.includes(err.message, 'already exists')) {
// Noop tag creation since already exists
} else {
throw err;
}
}
const { stdout } = await execAsync(`git ls-remote --tags origin refs/tags/${tagName}`);
if (_.isEmpty(stdout)) {
await execAsync(`git push origin ${tagName}`);
}
}
const releaseName = `0x monorepo - ${shortenedGitCommit}`;
let assets: string[] = [];
let aggregateNotes = '';
_.each(updatedPublishPackages, pkg => {
const notes = getReleaseNotesForPackage(pkg.packageJson.name, pkg.packageJson.version);
if (_.isEmpty(notes)) {
return; // don't include it
}
aggregateNotes += `### ${pkg.packageJson.name}@${pkg.packageJson.version}\n${notes}\n\n`;
const packageAssets = _.get(pkg.packageJson, 'config.postpublish.assets');
if (!_.isUndefined(packageAssets)) {
assets = [...assets, ...packageAssets];
}
});
const finalAssets = adjustAssetPaths(assets);
const publishReleaseConfigs = {
token: constants.githubPersonalAccessToken,
owner: '0xProject',
tag: tagName,
repo: '0x-monorepo',
name: releaseName,
notes: aggregateNotes,
draft: false,
prerelease: false,
reuseRelease: true,
reuseDraftOnly: false,
// TODO: Currently publish-release doesn't let you specify the labels for each asset uploaded
// Ideally we would like to name the assets after the package they are from
// Source: https://github.com/remixz/publish-release/issues/39
assets: finalAssets,
};
if (isDryRun) {
utils.log(`Dry run: stopping short of publishing release notes to github`);
utils.log(`Would publish with configs:\n${JSON.stringify(publishReleaseConfigs, null, '\t')}`);
return;
}
utils.log('Publishing release notes ', releaseName, '...');
await publishReleaseAsync(publishReleaseConfigs);
}
// Asset paths should described from the monorepo root. This method prefixes
// the supplied path with the absolute path to the monorepo root.
function adjustAssetPaths(assets: string[]): string[] {
const finalAssets: string[] = [];
_.each(assets, (asset: string) => {
const finalAsset = `${constants.monorepoRootPath}/${asset}`;
finalAssets.push(finalAsset);
});
return finalAssets;
}
function getReleaseNotesForPackage(packageName: string, version: string): string {
const packageNameWithoutNamespace = packageName.replace('@0xproject/', '');
const changelogJSONPath = path.join(
constants.monorepoRootPath,
'packages',
packageNameWithoutNamespace,
'CHANGELOG.json',
);
const changelogJSON = readFileSync(changelogJSONPath, 'utf-8');
const changelogs = JSON.parse(changelogJSON);
const latestLog = changelogs[0];
// If only has a `Dependencies updated` changelog, we don't include it in release notes
if (latestLog.changes.length === 1 && latestLog.changes[0].note === constants.dependenciesUpdatedMessage) {
return '';
}
let notes = '';
_.each(latestLog.changes, change => {
notes += `* ${change.note}`;
if (change.pr) {
notes += ` (#${change.pr})`;
}
notes += `\n`;
});
return notes;
}

View File

@@ -48,7 +48,7 @@ export const utils = {
};
packages.push(pkg);
} catch (err) {
utils.log(`Couldn't find a 'package.json' for ${subpackageName}. Skipping.`);
// Couldn't find a 'package.json' for package. Skipping.
}
}
}

View File

@@ -15,6 +15,16 @@
"Update marketUtils api such that all optional parameters are bundled into one optional param and more defaults are provided",
"pr": 954
},
{
"note":
"Instead of exporting signature util methods individually, they are now exported as `signatureUtils`",
"pr": 924
},
{
"note":
"Export types: `SignedOrder`, `Order`, `OrderRelevantState`, `OrderState`, `ECSignature`, `ERC20AssetData`, `ERC721AssetData`, `AssetProxyId`, `SignerType`, `SignatureType`, `OrderStateValid`, `OrderStateInvalid`, `ExchangeContractErrs`, `TradeSide`, `TransferType`, `FindFeeOrdersThatCoverFeesForTargetOrdersOpts`, `FindOrdersThatCoverMakerAssetFillAmountOpts`, `FeeOrdersAndRemainingFeeAmount`, `OrdersAndRemainingFillAmount`, `Provider`, `JSONRPCRequestPayload`, `JSONRPCErrorCallback` and `JSONRPCResponsePayload`",
"pr": 924
},
{
"note":
"Rename `resultOrders` to `resultFeeOrders` for object returned by `findFeeOrdersThatCoverFeesForTargetOrders` in `marketUtils` api",

View File

@@ -9,10 +9,9 @@
"types": "lib/src/index.d.ts",
"scripts": {
"watch_without_deps": "yarn pre_build && tsc -w",
"build": "run-s pre_build transpile copy_monorepo_scripts",
"build": "run-s pre_build transpile",
"pre_build": "run-s update_artifacts_v2_beta generate_contract_wrappers",
"transpile": "tsc",
"copy_monorepo_scripts": "copyfiles -u 3 './lib/src/monorepo_scripts/**/*' ./scripts",
"generate_contract_wrappers": "abi-gen --abis 'lib/src/artifacts/@(Exchange|IWallet|IValidator|DummyERC20Token|ERC20Proxy|ERC20Token).json' --template ../contract_templates/contract.handlebars --partials '../contract_templates/partials/**/*.handlebars' --output src/generated_contract_wrappers --backend ethers",
"update_artifacts_v2_beta": "for i in ${npm_package_config_contracts_v2_beta}; do copyfiles -u 4 ../migrations/artifacts/2.0.0-beta-testnet/$i.json lib/src/artifacts; done;",
"test": "yarn run_mocha",
@@ -21,24 +20,14 @@
"run_mocha": "mocha --require source-map-support/register --require make-promises-safe lib/test/**/*_test.js --bail --exit",
"test:coverage": "nyc npm run test --all && yarn coverage:report:lcov",
"coverage:report:lcov": "nyc report --reporter=text-lcov > coverage/lcov.info",
"clean": "shx rm -rf lib scripts lib/src/artifacts src/generated_contract_wrappers",
"clean": "shx rm -rf lib lib/src/artifacts src/generated_contract_wrappers generated_docs",
"lint": "tslint --project . --exclude **/src/generated_contract_wrappers/**/*",
"manual:postpublish": "yarn build; node ./scripts/postpublish.js",
"docs:stage": "node scripts/stage_docs.js",
"docs:json": "typedoc --excludePrivate --excludeExternals --target ES5 --json $JSON_FILE_PATH $PROJECT_FILES",
"upload_docs_json": "aws s3 cp generated_docs/index.json $S3_URL --profile 0xproject --grants read=uri=http://acs.amazonaws.com/groups/global/AllUsers --content-type application/json"
"docs:json": "typedoc --excludePrivate --excludeExternals --target ES5 --json $JSON_FILE_PATH $PROJECT_FILES"
},
"config": {
"contracts_v2_beta": "IWallet IValidator Exchange ERC20Proxy ERC20Token DummyERC20Token",
"postpublish": {
"docPublishConfigs": {
"extraFileIncludes": [
"../types/src/index.ts",
"../ethereum-types/src/index.ts"
],
"s3BucketPath": "s3://doc-jsons/order-utils/",
"s3StagingBucketPath": "s3://staging-doc-jsons/order-utils/"
}
"assets": []
}
},
"license": "Apache-2.0",
@@ -52,7 +41,6 @@
"homepage": "https://github.com/0xProject/0x-monorepo/packages/order-utils/README.md",
"devDependencies": {
"@0xproject/dev-utils": "^1.0.4",
"@0xproject/monorepo-scripts": "^1.0.5",
"@0xproject/tslint-config": "^1.0.5",
"@types/bn.js": "^4.11.0",
"@types/lodash": "4.14.104",
@@ -67,14 +55,13 @@
"shx": "^0.2.2",
"sinon": "^4.0.0",
"tslint": "5.11.0",
"typedoc": "0xProject/typedoc",
"typedoc": "0.12.0",
"typescript": "3.0.1"
},
"dependencies": {
"@0xproject/assert": "^1.0.5",
"@0xproject/base-contract": "^2.0.0-rc.1",
"@0xproject/json-schemas": "^1.0.1-rc.4",
"@0xproject/sol-compiler": "^1.0.5",
"@0xproject/types": "^1.0.1-rc.4",
"@0xproject/typescript-typings": "^1.0.4",
"@0xproject/utils": "^1.0.5",

View File

@@ -1,6 +1,23 @@
import { BigNumber } from '@0xproject/utils';
/**
* An abstract class to be implemented in order to use OrderStateUtils. The class that
* implements this interface must be capable of fetching the balance and proxyAllowance
* for an Ethereum address and assetData
*/
export abstract class AbstractBalanceAndProxyAllowanceFetcher {
/**
* Get balance of assetData for userAddress
* @param assetData AssetData for which to fetch the balance
* @param userAddress Ethereum address for which to fetch the balance
* @return Balance amount in base units
*/
public abstract async getBalanceAsync(assetData: string, userAddress: string): Promise<BigNumber>;
/**
* Get the 0x asset proxy allowance of assetData for userAddress
* @param assetData AssetData for which to fetch the allowance
* @param userAddress Ethereum address for which to fetch the allowance
* @return Allowance amount in base units
*/
public abstract async getProxyAllowanceAsync(assetData: string, userAddress: string): Promise<BigNumber>;
}

View File

@@ -1,7 +1,22 @@
import { BigNumber } from '@0xproject/utils';
/**
* An abstract class to be implemented in order to use OrderStateUtils. The class that
* implements this interface must be capable of fetching the amount filled of an order
* and whether it's been cancelled.
*/
export abstract class AbstractOrderFilledCancelledFetcher {
/**
* Get the amount of the order's takerToken amount already filled
* @param orderHash OrderHash of order we are interested in
* @return FilledTakerAmount
*/
public abstract async getFilledTakerAmountAsync(orderHash: string): Promise<BigNumber>;
/**
* Whether an order is cancelled
* @param orderHash OrderHash of order we are interested in
* @return Whether or not the order is cancelled
*/
public abstract async isOrderCancelledAsync(orderHash: string): Promise<boolean>;
public abstract getZRXAssetData(): string;
}

View File

@@ -1,4 +1,4 @@
import { ContractArtifact } from '@0xproject/sol-compiler';
import { ContractArtifact } from 'ethereum-types';
import * as DummyERC20Token from './artifacts/DummyERC20Token.json';
import * as ERC20Proxy from './artifacts/ERC20Proxy.json';

View File

@@ -18,14 +18,14 @@ const EIP712_DOMAIN_SCHEMA: EIP712Schema = {
],
};
export const EIP712Utils = {
export const eip712Utils = {
/**
* Compiles the EIP712Schema and returns the hash of the schema.
* @param schema The EIP712 schema.
* @return The hash of the compiled schema
*/
compileSchema(schema: EIP712Schema): Buffer {
const eip712Schema = EIP712Utils._encodeType(schema);
const eip712Schema = eip712Utils._encodeType(schema);
const eip712SchemaHashBuffer = crypto.solSHA3([eip712Schema]);
return eip712SchemaHashBuffer;
},
@@ -36,25 +36,47 @@ export const EIP712Utils = {
* @return The hash of an EIP712 message with domain separator prefixed
*/
createEIP712Message(hashStruct: Buffer, contractAddress: string): Buffer {
const domainSeparatorHashBuffer = EIP712Utils._getDomainSeparatorHashBuffer(contractAddress);
const domainSeparatorHashBuffer = eip712Utils._getDomainSeparatorHashBuffer(contractAddress);
const messageBuff = crypto.solSHA3([EIP191_PREFIX, domainSeparatorHashBuffer, hashStruct]);
return messageBuff;
},
/**
* Pad an address to 32 bytes
* @param address Address to pad
* @return padded address
*/
pad32Address(address: string): Buffer {
const addressBuffer = ethUtil.toBuffer(address);
const addressPadded = EIP712Utils.pad32Buffer(addressBuffer);
const addressPadded = eip712Utils.pad32Buffer(addressBuffer);
return addressPadded;
},
/**
* Pad an buffer to 32 bytes
* @param buffer Address to pad
* @return padded buffer
*/
pad32Buffer(buffer: Buffer): Buffer {
const bufferPadded = ethUtil.setLengthLeft(buffer, EIP712_VALUE_LENGTH);
return bufferPadded;
},
/**
* Hash together a EIP712 schema with the corresponding data
* @param schema EIP712-compliant schema
* @param data Data the complies to the schema
* @return A buffer containing the SHA256 hash of the schema and encoded data
*/
structHash(schema: EIP712Schema, data: { [key: string]: any }): Buffer {
const encodedData = eip712Utils._encodeData(schema, data);
const schemaHash = eip712Utils.compileSchema(schema);
const hashBuffer = crypto.solSHA3([schemaHash, ...encodedData]);
return hashBuffer;
},
_getDomainSeparatorSchemaBuffer(): Buffer {
return EIP712Utils.compileSchema(EIP712_DOMAIN_SCHEMA);
return eip712Utils.compileSchema(EIP712_DOMAIN_SCHEMA);
},
_getDomainSeparatorHashBuffer(exchangeAddress: string): Buffer {
const domainSeparatorSchemaBuffer = EIP712Utils._getDomainSeparatorSchemaBuffer();
const encodedData = EIP712Utils._encodeData(EIP712_DOMAIN_SCHEMA, {
const domainSeparatorSchemaBuffer = eip712Utils._getDomainSeparatorSchemaBuffer();
const encodedData = eip712Utils._encodeData(EIP712_DOMAIN_SCHEMA, {
name: EIP712_DOMAIN_NAME,
version: EIP712_DOMAIN_VERSION,
verifyingContract: exchangeAddress,
@@ -77,17 +99,11 @@ export const EIP712Utils = {
} else if (parameter.type === EIP712Types.Uint256) {
encodedValues.push(value);
} else if (parameter.type === EIP712Types.Address) {
encodedValues.push(EIP712Utils.pad32Address(value));
encodedValues.push(eip712Utils.pad32Address(value));
} else {
throw new Error(`Unable to encode ${parameter.type}`);
}
}
return encodedValues;
},
structHash(schema: EIP712Schema, data: { [key: string]: any }): Buffer {
const encodedData = EIP712Utils._encodeData(schema, data);
const schemaHash = EIP712Utils.compileSchema(schema);
const hashBuffer = crypto.solSHA3([schemaHash, ...encodedData]);
return hashBuffer;
},
};

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